customer bill/ship location refactoring, #940
[freeside.git] / httemplate / search / report_tax.cgi
1 <% include("/elements/header.html", "$agentname Tax Report - ".
2               ( $beginning
3                   ? time2str('%h %o %Y ', $beginning )
4                   : ''
5               ).
6               'through '.
7               ( $ending == 4294967295
8                   ? 'now'
9                   : time2str('%h %o %Y', $ending )
10               )
11           )
12 %>
13 <TD ALIGN="right">
14 Download full results<BR>
15 as <A HREF="<% $p.'search/report_tax-xls.cgi?'.$cgi->query_string%>">Excel spreadsheet</A>
16 </TD>
17
18 <% include('/elements/table-grid.html') %>
19
20   <TR>
21     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
22     <TH CLASS="grid" BGCOLOR="#cccccc" COLSPAN=9>Sales</TH>
23     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
24     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Rate</TH>
25     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
26     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax owed</TH>
27 % unless ( $cgi->param('show_taxclasses') ) { 
28       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax invoiced</TH>
29       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
30       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax credited</TH>
31       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
32       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax collected</TH>
33 % } 
34   </TR>
35
36   <TR>
37     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Total</TH>
38     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
39     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=1>Non-taxable</TH>
40     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
41     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=1>Non-taxable</TH>
42     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
43     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=1>Non-taxable</TH>
44     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
45     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Taxable</TH>
46   </TR>
47
48   <TR>
49     <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1>(tax-exempt customer)</FONT></TH>
50     <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1>(tax-exempt package)</FONT></TH>
51     <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1>(monthly exemption)</FONT></TH>
52   </TR>
53
54 % my $bgcolor1 = '#eeeeee';
55 % my $bgcolor2 = '#ffffff';
56 % my $bgcolor;
57 %
58 % foreach my $region ( @regions ) {
59 %
60 %   my $link = '';
61 %   if ( $region->{'label'} eq $out ) {
62 %     $link = ';out=1';
63 %   } else {
64 %     $link = ';'. $region->{'url_param'}
65 %       if $region->{'url_param'};
66 %   }
67 %
68 %   if ( $bgcolor eq $bgcolor1 ) {
69 %     $bgcolor = $bgcolor2;
70 %   } else {
71 %     $bgcolor = $bgcolor1;
72 %   }
73 %
74 %   #my $diff = 0;
75 %   my $hicolor = $bgcolor;
76 %   unless ( $cgi->param('show_taxclasses') ) {
77 %     my $diff = abs(   sprintf( '%.2f', $region->{'owed'} )
78 %                     - sprintf( '%.2f', $region->{'tax'}  )
79 %                   );
80 %     if ( $diff > 0.02 ) {
81 %     #  $hicolor = $hicolor eq '#eeeeee' ? '#eeee66' : '#ffff99';
82 %     #} elsif ( $diff ) {
83 %       $hicolor = $hicolor eq '#eeeeee' ? '#eeee99' : '#ffffcc';
84 %     }
85 %   }
86 %
87 %
88 %   my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
89 %   my $tdh = qq(TD CLASS="grid" BGCOLOR="$hicolor");
90 %   my $bigmath = '<FONT FACE="sans-serif" SIZE="+1"><B>';
91 %   my $bme = '</B></FONT>';
92
93     <TR>
94       <<%$td%>><% $region->{'label'} %></TD>
95       <<%$td%> ALIGN="right">
96         <A HREF="<% $baselink. $link %>;nottax=1"
97         ><% &$money_sprintf( $region->{'total'} ) %></A>
98       </TD>
99       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
100       <<%$td%> ALIGN="right">
101         <A HREF="<% $baselink. $link %>;nottax=1;cust_tax=Y"
102         ><% &$money_sprintf( $region->{'exempt_cust'} ) %></A>
103       </TD>
104       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
105       <<%$td%> ALIGN="right">
106         <A HREF="<% $baselink. $link %>;nottax=1;pkg_tax=Y"
107         ><% &$money_sprintf( $region->{'exempt_pkg'} ) %></A>
108       </TD>
109       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
110       <<%$td%> ALIGN="right">
111         <A HREF="<% $exemptlink. $link %>"
112         ><% &$money_sprintf( $region->{'exempt_monthly'} ) %></A>
113         </TD>
114       <<%$td%>><FONT SIZE="+1"><B> = </B></FONT></TD>
115       <<%$td%> ALIGN="right">
116         <A HREF="<% $baselink. $link %>;nottax=1;taxable=1"
117         ><% &$money_sprintf( $region->{'taxable'} ) %></A>
118       </TD>
119       <<%$td%>><% $region->{'label'} eq 'Total' ? '' : "$bigmath X $bme" %></TD>
120       <<%$td%> ALIGN="right"><% $region->{'rate'} %></TD>
121       <<%$td%>><% $region->{'label'} eq 'Total' ? '' : "$bigmath = $bme" %></TD>
122       <<%$tdh%> ALIGN="right">
123         <% &$money_sprintf( $region->{'owed'} ) %>
124       </TD>
125
126 % unless ( $cgi->param('show_taxclasses') ) { 
127 %       my $invlink = $region->{'url_param_inv'}
128 %                       ? ';'. $region->{'url_param_inv'}
129 %                       : $link;
130
131         <<%$tdh%> ALIGN="right">
132           <A HREF="<% $baselink. $invlink %>;istax=1"
133           ><% &$money_sprintf( $region->{'tax'} ) %></A>
134         </TD>
135         <<%$tdh%>><FONT SIZE="+1"><B> - </B></FONT></TD>
136         <<%$tdh%> ALIGN="right">
137           <A HREF="<% $creditlink. $invlink %>;istax=1"
138           ><% &$money_sprintf( $region->{'credit'} ) %></A>
139         </TD>
140         <<%$tdh%>><FONT SIZE="+1"><B> = </B></FONT></TD>
141         <<%$tdh%> ALIGN="right">
142           <% &$money_sprintf( $region->{'tax'} - $region->{'credit'} ) %>
143         </TD>
144 % } 
145
146     </TR>
147 % } 
148
149 </TABLE>
150
151 % if ( $cgi->param('show_taxclasses') ) {
152
153     <BR>
154     <% include('/elements/table-grid.html') %>
155     <TR>
156       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
157       <TH CLASS="grid" BGCOLOR="#cccccc">Tax invoiced</TH>
158       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
159       <TH CLASS="grid" BGCOLOR="#cccccc">Tax credited</TH>
160       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
161       <TH CLASS="grid" BGCOLOR="#cccccc">Tax collected</TH>
162     </TR>
163
164 %   #some false laziness w/above
165 %   $bgcolor1 = '#eeeeee';
166 %   $bgcolor2 = '#ffffff';
167 %
168 %   foreach my $region ( @base_regions ) {
169 %
170 %     my $link = '';
171 %     if ( $region->{'label'} eq $out ) {
172 %       $link = ';out=1';
173 %     } else {
174 %       $link = ';'. $region->{'url_param'}
175 %         if $region->{'url_param'};
176 %     }
177 %
178 %     if ( $bgcolor eq $bgcolor1 ) {
179 %       $bgcolor = $bgcolor2;
180 %     } else {
181 %       $bgcolor = $bgcolor1;
182 %     }
183 %     my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
184 %     my $tdh = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
185 %
186 %     #?
187 %     my $invlink = $region->{'url_param_inv'}
188 %                     ? ';'. $region->{'url_param_inv'}
189 %                     : $link;
190
191       <TR>
192         <<%$td%>><% $region->{'label'} %></TD>
193         <<%$td%> ALIGN="right">
194           <A HREF="<% $baselink. $link %>;istax=1"
195           ><% &$money_sprintf( $region->{'tax'} ) %></A>
196         </TD>
197         <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
198         <<%$tdh%> ALIGN="right">
199           <A HREF="<% $creditlink. $invlink %>;istax=1"
200           ><% &$money_sprintf( $region->{'credit'} ) %></A>
201         </TD>
202         <<%$td%>><FONT SIZE="+1"><B> = </B></FONT></TD>
203         <<%$tdh%> ALIGN="right">
204           <% &$money_sprintf( $region->{'tax'} - $region->{'credit'} ) %>
205         </TD>
206       </TR>
207
208 % } 
209
210 % if ( $bgcolor eq $bgcolor1 ) {
211 %   $bgcolor = $bgcolor2;
212 % } else {
213 %   $bgcolor = $bgcolor1;
214 % }
215 % my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
216
217   <TR>
218    <<%$td%>>Total</TD>
219    <<%$td%> ALIGN="right">
220      <A HREF="<% $baselink %>;istax=1"
221      ><% &$money_sprintf( $tot_tax ) %></A>
222    </TD>
223         <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
224    <<%$td%> ALIGN="right">
225      <A HREF="<% $creditlink %>;istax=1"
226      ><% &$money_sprintf( $tot_credit ) %></A>
227    </TD>
228         <<%$td%>><FONT SIZE="+1"><B> = </B></FONT></TD>
229    <<%$td%> ALIGN="right">
230      <% &$money_sprintf( $tot_tax - $tot_credit ) %>
231    </TD>
232   </TR>
233
234   </TABLE>
235
236 % } 
237
238 <% include('/elements/footer.html') %>
239
240 <%init>
241
242 my $DEBUG = $cgi->param('debug') || 0;
243
244 die "access denied"
245   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
246
247 my $conf = new FS::Conf;
248
249 my $user = getotaker;
250
251 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
252
253 my $join_cust =     '     JOIN cust_bill      USING ( invnum  ) 
254                       LEFT JOIN cust_main     USING ( custnum ) ';
255 my $join_cust_pkg = $join_cust.
256                     ' LEFT JOIN cust_pkg      USING ( pkgnum  )
257                       LEFT JOIN part_pkg      USING ( pkgpart ) 
258                       LEFT JOIN cust_location 
259                         ON ( cust_location.locationnum = ' .
260                         FS::cust_pkg->tax_locationnum_sql . ' )';
261
262 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg "; 
263
264 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
265
266 # this query will be run once per cust_main_county,
267 # or maybe once per country/state/city tuple,
268 # or maybe once per country/state...it's hard to say.
269 my ($location_sql, @base_param) = FS::cust_location->in_county_sql(param => 1);
270 $where .= " AND $location_sql ";
271
272 my $agentname = '';
273 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
274   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
275   die "agent not found" unless $agent;
276   $agentname = $agent->agent;
277   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
278 }
279
280 sub gotcust {
281   my $table = shift;
282   my $prefix = @_ ? shift : '';
283   "
284         ( $table.district = cust_main_county.district
285           OR cust_main_county.district = ''
286           OR cust_main_county.district IS NULL )
287     AND ( $table.${prefix}city  = cust_main_county.city
288           OR cust_main_county.city = ''
289           OR cust_main_county.city IS NULL )
290     AND ( $table.${prefix}county  = cust_main_county.county
291           OR cust_main_county.county = ''
292           OR cust_main_county.county IS NULL )
293     AND ( $table.${prefix}state   = cust_main_county.state
294           OR cust_main_county.state = ''
295           OR cust_main_county.state IS NULL )
296     AND ( $table.${prefix}country = cust_main_county.country )
297   ";
298 }
299
300 #non-parameterized form
301 my $location_in_county = FS::cust_location->in_county_sql;
302 my $gotcust = "WHERE EXISTS(
303   SELECT 1 FROM cust_location WHERE $location_in_county AND disabled IS NULL
304 )";
305
306 my $out = 'Out of taxable region(s)';
307 # these are actually tax labels, not regions
308 my %regions = ();
309
310 # Phase 1: Taxable and exempt sales
311 # Collect for each cust_main_county, and assign to a bin based on label.
312 # Note that "label" includes city if show_cities is on, and taxclass if
313 # show_taxclasses is on.
314 foreach my $r ( qsearch({ 'table'     => 'cust_main_county',
315                           'extra_sql' => $gotcust,
316                           'debug' => $DEBUG,
317                        })
318               )
319 {
320   warn $r->county. ' '. $r->state. ' '. $r->country. "\n" if $DEBUG > 1;
321
322   # set up a %regions entry for this region's tax label
323   my $label = getlabel($r);
324   $regions{$label}->{'label'} = $label;
325
326   $regions{$label}->{$_} = $r->$_() for (qw( county state country )); #taxname?
327
328   my @url_param = qw( county state country taxname );
329   push @url_param, 'city' if $cgi->param('show_cities') && $r->city();
330
331   $regions{$label}->{'url_param'} =
332     join(';', map "$_=".uri_escape($r->$_()), @url_param );
333
334   my @param = @base_param;
335   my $mywhere = $where;
336
337   if ( $r->taxclass ) {
338
339     $mywhere .= " AND taxclass = ? ";
340     push @param, 'taxclass';
341     $regions{$label}->{'url_param'} .= ';taxclass='. uri_escape($r->taxclass);
342     #no, always#  if $cgi->param('show_taxclasses');
343
344     $regions{$label}->{'taxclass'} = $r->taxclass;
345
346   } else {
347
348     # SQL for "taxclass doesn't match any other tax in the region"
349     my $same_sql = $r->sql_taxclass_sameregion;
350     $mywhere .= " AND $same_sql" if $same_sql;
351
352     $regions{$label}->{'url_param'} .= ';taxclassNULL=1'
353       if $cgi->param('show_taxclasses')
354       || $same_sql;
355
356   }
357
358   # FROM cust_bill_pkg JOIN (whatever is needed to determine tax location)
359   # WHERE (matches tax location and agentnum and taxclass)
360   # takes parameters in @base_param, plus taxclass if there is one
361   my $fromwhere = "$from_join_cust_pkg $mywhere"; # AND payby != 'COMP' ";
362
363   my $nottax = 'pkgnum != 0';
364
365   ## calculate total of sales (non-tax line items) for this region
366
367   my $t_sql =
368    "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) $fromwhere AND $nottax";
369   my $t = scalar_sql($r, \@param, $t_sql);
370   $regions{$label}->{'total'} += $t;
371
372   #$regions{$label}->{subtotals}->{$r->taxnum} = $t; #useful debug
373
374   ## calculate customer-exemption for this region
375
376   #false laziness -ish w/report_tax.cgi
377   my $cust_exempt;
378   if ( $r->taxname ) {
379     my $q_taxname = dbh->quote($r->taxname);
380     $cust_exempt =
381       "( tax = 'Y'
382          OR EXISTS ( SELECT 1 FROM cust_main_exemption
383                        WHERE cust_main_exemption.custnum = cust_main.custnum
384                          AND cust_main_exemption.taxname = $q_taxname
385                    )
386        )
387       ";
388   } else {
389     $cust_exempt = " tax = 'Y' ";
390   }
391
392   my $x_cust = scalar_sql($r, \@param,
393     "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur)
394      $fromwhere AND $nottax AND $cust_exempt "
395   );
396
397   $regions{$label}->{'exempt_cust'} += $x_cust;
398   
399   ## calculate package-exemption for this region
400
401   my $x_pkg = scalar_sql($r, \@param,
402     "SELECT SUM(
403                  ( CASE WHEN part_pkg.setuptax = 'Y'
404                         THEN cust_bill_pkg.setup
405                         ELSE 0
406                    END
407                  )
408                  +
409                  ( CASE WHEN part_pkg.recurtax = 'Y'
410                         THEN cust_bill_pkg.recur
411                         ELSE 0
412                    END
413                  )
414                )
415        $fromwhere
416        AND $nottax
417        AND (
418                 ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
419              OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 )
420            )
421        AND ( tax != 'Y' OR tax IS NULL )
422     "
423   );
424   $regions{$label}->{'exempt_pkg'} += $x_pkg;
425
426   ## calculate monthly exemption (texas tax) for this region
427
428   # count up all the cust_tax_exempt_pkg records associated with
429   # the actual line items.
430
431   my $x_monthly = scalar_sql($r, \@param,
432     "SELECT SUM(amount)
433        FROM cust_tax_exempt_pkg
434        JOIN cust_bill_pkg USING ( billpkgnum )
435        $join_cust_pkg
436      $mywhere"
437   );
438   $regions{$label}->{'exempt_monthly'} += $x_monthly;
439
440   my $taxable = $t - $x_cust - $x_pkg - $x_monthly;
441   $regions{$label}->{'taxable'} += $taxable;
442
443   $regions{$label}->{'owed'} += $taxable * ($r->tax/100);
444
445   if ( defined($regions{$label}->{'rate'})
446        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
447     $regions{$label}->{'rate'} = 'variable';
448   } else {
449     $regions{$label}->{'rate'} = $r->tax.'%';
450   }
451 }
452 warn Dumper(\%regions) if $DEBUG > 1;
453 # $regions{$label} now contains 'total', 'exempt_cust', 'exempt_pkg', 
454 # 'exempt_monthly', summed over each set of regions with the same label.
455
456 my $distinct = "country, state, county, city, district,
457                 CASE WHEN taxname IS NULL THEN '' ELSE taxname END AS taxname";
458 my $taxclass_distinct = 
459   #a little bit unsure of this part... test?
460   #ah, it looks like it winds up being irrelevant as ->{'tax'} 
461   # from $regions is not displayed when show_taxclasses is on
462   ( $cgi->param('show_taxclasses')
463       ? " CASE WHEN taxclass IS NULL THEN '' ELSE taxclass END "
464       : " '' "
465   )." AS taxclass";
466
467
468 # Phase 2: invoiced/credited tax items
469 # Collect this data for each country/state/city/district/taxname(/taxclass).
470 my %qsearch = (
471   'select'    => "DISTINCT $distinct, $taxclass_distinct",
472   'table'     => 'cust_main_county',
473   'hashref'   => {},
474   'extra_sql' => $gotcust,
475   'debug' => $DEBUG,
476 );
477
478 # Join to cust_main the same as before (we need agentnum)
479 # but not to cust_pkg (because tax line items don't have a package)
480 # and then to cust_location via cust_bill_pkg_tax_location
481 my $taxfromwhere = "FROM cust_bill_pkg $join_cust 
482                     LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
483                     LEFT JOIN cust_location USING ( locationnum )
484                     ";
485 my $taxwhere = $where;
486
487 my $creditfromwhere = $taxfromwhere. 
488    " JOIN cust_credit_bill_pkg USING (billpkgnum, billpkgtaxlocationnum)";
489
490 $taxfromwhere .= " $taxwhere "; #AND payby != 'COMP' ";
491 $creditfromwhere .= " $taxwhere AND billpkgtaxratelocationnum IS NULL"; #AND payby != 'COMP' ";
492
493 #should i be a cust_main_county method or something
494 # yes. yes, you should.
495
496 # $taxfromwhere: Most of a query to find cust_bill_pkg records linked to a 
497 # customer matching a given state/county/city/district (and within the date 
498 # range for the report).
499 # @base_param: A list of the fields from cust_main_county to use as parameters.
500
501 # $_taxamount_sub: Takes a cust_main_county and returns the sum of taxes billed
502 # within the report period for all customers located in that county.  If 
503 # the cust_main_county has a taxname, limits to taxes with that name; otherwise
504 # includes all line items with pkgnum = 0 and description either 'Tax' or empty.
505
506 my $_taxamount_sub = sub {
507   my $r = shift;
508
509   #match itemdesc if necessary!
510   my $named_tax =
511     $r->taxname
512       ? 'AND itemdesc = '. dbh->quote($r->taxname)
513       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
514
515   my $sql = "SELECT SUM(cust_bill_pkg.setup+cust_bill_pkg.recur) ".
516             " $taxfromwhere AND cust_bill_pkg.pkgnum = 0 $named_tax";
517
518   scalar_sql($r, [ @base_param ], $sql );
519 };
520
521 # $_creditamount_sub: As above, but returns the sum of credits applied 
522
523 my $_creditamount_sub = sub {
524   my $r = shift;
525
526   #match itemdesc if necessary!
527   my $named_tax =
528     $r->taxname
529       ? 'AND itemdesc = '. dbh->quote($r->taxname)
530       : "AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
531
532   my $sql = "SELECT SUM(cust_credit_bill_pkg.amount) ".
533             " $creditfromwhere AND cust_bill_pkg.pkgnum = 0 $named_tax";
534
535   scalar_sql($r, [ @base_param ], $sql );
536 };
537
538 #tax-report_groups filtering
539 my($group_op, $group_value) = ( '', '' );
540 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ ) {
541   ( $group_op, $group_value ) = ( $1, $2 );
542 }
543 my $group_test = sub {
544   my $label = shift;
545   return 1 unless $group_op; #in case we get called inadvertantly
546   if ( $label eq $out ) { #don't display "out of taxable region" in this case
547     0;
548   } elsif ( $group_op eq '=' ) {
549     $label =~ /^$group_value/;
550   } elsif ( $group_op eq '!=' ) {
551     $label !~ /^$group_value/;
552   } else {
553     die "guru meditation #00de: group_op $group_op\n";
554   }
555 };
556
557 my $tot_tax = 0;
558 my $tot_credit = 0;
559 #foreach my $label ( keys %regions ) {
560 foreach my $r ( qsearch(\%qsearch) ) {
561
562   #warn join('-', map { $r->$_() } qw( country state county taxname ) )."\n";
563
564   my $label = getlabel($r);
565   if ( $group_op ) {
566     next unless &{$group_test}($label);
567   }
568
569   #my $fromwhere = $join_pkg. $where. " AND payby != 'COMP' ";
570   #my @param = @base_param; 
571
572   my $x = &{$_taxamount_sub}($r);
573
574   $regions{$label}->{'tax'} += $x;
575   $tot_tax += $x unless $cgi->param('show_taxclasses');
576
577   ## calculate credit for this region
578
579   $x = &{$_creditamount_sub}($r);
580
581   $regions{$label}->{'credit'} += $x;
582   $tot_credit += $x unless $cgi->param('show_taxclasses');
583
584 }
585
586 # Phase 3: Non-taxclassed totals for invoiced/credited tax
587 # (If show_taxclasses is not in use, this was phase 2, but it 
588 # displays somewhere different.)
589 # Don't filter by report_groups.
590 my %base_regions = ();
591 if ( $cgi->param('show_taxclasses') ) {
592
593   $qsearch{'select'} = "DISTINCT $distinct";
594   foreach my $r ( qsearch(\%qsearch) ) {
595
596     my $x = &{$_taxamount_sub}($r);
597
598     my $base_label = getlabel($r, 'no_taxclass'=>1 );
599     $base_regions{$base_label}->{'label'} = $base_label;
600
601     $base_regions{$base_label}->{'url_param'} =
602       join(';', map "$_=". uri_escape($r->$_()),
603                      qw( county state country taxname )
604           );
605
606     $base_regions{$base_label}->{'tax'} += $x;
607     $tot_tax += $x;
608
609     ## calculate credit for this region
610
611     $x = &{$_creditamount_sub}($r);
612
613     $base_regions{$base_label}->{'credit'} += $x;
614     $tot_credit += $x;
615
616   }
617
618 }
619
620 my @regions = keys %regions;
621
622 #tax-report_groups filtering
623 @regions = grep &{$group_test}($_), @regions
624   if $group_op;
625
626 #calculate totals
627 my( $total, $tot_taxable, $tot_owed ) = ( 0, 0, 0 );
628 my( $exempt_cust, $exempt_pkg, $exempt_monthly, $tot_credit ) = ( 0, 0, 0, 0 );
629 my %taxclasses = ();
630 my %county = ();
631 my %state = ();
632 my %country = ();
633 foreach (@regions) {
634   $total          += $regions{$_}->{'total'};
635   $tot_taxable    += $regions{$_}->{'taxable'};
636   $tot_owed       += $regions{$_}->{'owed'};
637   $exempt_cust    += $regions{$_}->{'exempt_cust'};
638   $exempt_pkg     += $regions{$_}->{'exempt_pkg'};
639   $exempt_monthly += $regions{$_}->{'exempt_monthly'};
640   $tot_credit     += $regions{$_}->{'credit'};
641   $taxclasses{$regions{$_}->{'taxclass'}} = 1
642     if $regions{$_}->{'taxclass'};
643   $county{$regions{$_}->{'county'}} = 1;
644   $state{$regions{$_}->{'state'}} = 1;
645   $country{$regions{$_}->{'country'}} = 1;
646 }
647
648 my $total_url_param = '';
649 my $total_url_param_invoiced = '';
650 if ( $group_op ) {
651
652   my @country = keys %country;
653   warn "WARNING: multiple countries on this grouped report; total links broken"
654     if scalar(@country) > 1;
655   my $country = $country[0];
656
657   my @state = keys %state;
658   warn "WARNING: multiple countries on this grouped report; total links broken"
659     if scalar(@state) > 1;
660   my $state = $state[0];
661
662   $total_url_param_invoiced =
663   $total_url_param =
664     'report_group='.uri_escape("$group_op $group_value").';'.
665     join(';', map 'taxclass='.uri_escape($_), keys %taxclasses );
666   $total_url_param .= ';'.
667     "country=$country;state=".uri_escape($state).';'.
668     join(';', map 'county='.uri_escape($_), keys %county ) ;
669
670 }
671
672 #ordering
673 @regions =
674   map $regions{$_},
675   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
676   @regions;
677
678 my @base_regions =
679   map $base_regions{$_},
680   sort { ( ($a eq $out) cmp ($b eq $out) ) || ($b cmp $a) }
681   keys %base_regions;
682
683 #add total line
684 push @regions, {
685   'label'          => 'Total',
686   'url_param'      => $total_url_param,
687   'url_param_inv'  => $total_url_param_invoiced,
688   'total'          => $total,
689   'exempt_cust'    => $exempt_cust,
690   'exempt_pkg'     => $exempt_pkg,
691   'exempt_monthly' => $exempt_monthly,
692   'taxable'        => $tot_taxable,
693   'rate'           => '',
694   'owed'           => $tot_owed,
695   'tax'            => $tot_tax,
696   'credit'         => $tot_credit,
697 };
698
699 #-- 
700
701 my $money_char = $conf->config('money_char') || '$';
702 my $money_sprintf = sub {
703   $money_char. sprintf('%.2f', shift );
704 };
705
706 sub getlabel {
707   my $r = shift;
708   my %opt = @_;
709
710   my $label;
711   if (
712     $r->tax == 0 
713     && ! scalar( qsearch('cust_main_county', { 'district'=> $r->district,
714                                                'city'    => $r->city,
715                                                'county'  => $r->county,
716                                                'state'   => $r->state,
717                                                'country' => $r->country,
718                                                'tax' => { op=>'>', value=>0 },
719                                              }
720                         )
721                )
722
723   ) {
724     #kludge to avoid "will not stay shared" warning
725     my $out = 'Out of taxable region(s)';
726     $label = $out;
727   } else {
728     $label = $r->country;
729     $label = $r->state.", $label" if $r->state;
730     $label = $r->county." county, $label" if $r->county;
731     $label = $r->city. ", $label" if $r->city && $cgi->param('show_cities');
732     $label = "$label (". $r->taxclass. ")"
733       if $r->taxclass
734       && $cgi->param('show_taxclasses')
735       && ! $opt{'no_taxclass'};
736     $label = $r->taxname. " ($label)" if $r->taxname;
737   }
738   return $label;
739 }
740
741 #my %count_taxname = (); #cache
742 #sub count_taxname {
743 #  my $taxname = shift;
744 #  return $count_taxname{$taxname} if exists $count_taxname{$taxname};
745 #  my $sql = 'SELECT COUNT(*) FROM cust_main_county WHERE taxname = ?';
746 #  my $sth = dbh->prepare($sql) or die dbh->errstr;
747 #  $sth->execute( $taxname )
748 #    or die "Unexpected error executing statement $sql: ". $sth->errstr;
749 #  $count_taxname{$taxname} = $sth->fetchrow_arrayref->[0];
750 #}
751
752 #false laziness w/FS::Report::Table::Monthly (sub should probably be moved up
753 #to FS::Report or FS::Record or who the fuck knows where)
754 sub scalar_sql {
755   my( $r, $param, $sql ) = @_;
756   #warn "$sql\n";
757   my $sth = dbh->prepare($sql) or die dbh->errstr;
758   $sth->execute( map $r->$_(), @$param )
759     or die "Unexpected error executing statement $sql: ". $sth->errstr;
760   $sth->fetchrow_arrayref->[0] || 0;
761 }
762
763 my $dateagentlink = "begin=$beginning;end=$ending";
764 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
765   if length($agentname);
766 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
767 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
768 my $creditlink = $p. "search/cust_credit_bill_pkg.html?$dateagentlink";
769
770 </%init>