Merge branch 'xss_fixes' of https://github.com/mcreenan/Freeside
[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 %   } elsif ( $region->{'taxnums'} ) {
64 %     # might be nicer to specify this as country:state:city
65 %     $link = ';'.join(';', map { "taxnum=$_" } @{ $region->{'taxnums'} });
66 %   }
67 %
68 %   if ( $bgcolor eq $bgcolor1 ) {
69 %     $bgcolor = $bgcolor2;
70 %   } else {
71 %     $bgcolor = $bgcolor1;
72 %   }
73 %
74 %   my $hicolor = $bgcolor;
75 %   unless ( $cgi->param('show_taxclasses') ) {
76 %     my $diff = abs(   sprintf( '%.2f', $region->{'owed'} )
77 %                     - sprintf( '%.2f', $region->{'tax'}  )
78 %                   );
79 %     if ( $diff > 0.02 ) {
80 %       $hicolor = $hicolor eq '#eeeeee' ? '#eeee99' : '#ffffcc';
81 %     }
82 %   }
83 %
84 %
85 %   my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
86 %   my $tdh = qq(TD CLASS="grid" BGCOLOR="$hicolor");
87 %   my $bigmath = '<FONT FACE="sans-serif" SIZE="+1"><B>';
88 %   my $bme = '</B></FONT>';
89
90     <TR>
91       <<%$td%>><% $region->{'label'} %></TD>
92       <<%$td%> ALIGN="right">
93         <A HREF="<% $baselink. $link %>;nottax=1"
94         ><% &$money_sprintf( $region->{'sales'} ) %></A>
95       </TD>
96 %     if ( $region->{'label'} eq $out ) {
97       <<%$td%> COLSPAN=12></TD>
98 %     } else { #not $out
99       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
100       <<%$td%> ALIGN="right">
101         <A HREF="<% $baselink. $link %>;nottax=1;exempt_cust=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;exempt_pkg=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 %   } # if !$out
126 %   unless ( $cgi->param('show_taxclasses') ) { 
127 %       my $invlink = $region->{'url_param_inv'}
128 %                       ? ';'. $region->{'url_param_inv'}
129 %                       : $link;
130
131 %     if ( $region->{'label'} eq $out ) {
132         <<%$td%> ALIGN="right">
133           <A HREF="<% $baselink. $invlink %>;istax=1"
134           ><% &$money_sprintf_nonzero( $region->{'tax'} ) %></A>
135         </TD>
136         <<%$td%>></TD>
137         <<%$td%> ALIGN="right">
138           <A HREF="<% $creditlink. $invlink %>;istax=1"
139           ><% &$money_sprintf_nonzero( $region->{'credit'} ) %></A>
140         </TD>
141         <<%$td%> COLSPAN=2></TD>
142 %     } else { #not $out
143         <<%$tdh%> ALIGN="right">
144           <A HREF="<% $baselink. $invlink %>;istax=1"
145           ><% &$money_sprintf( $region->{'tax'} ) %></A>
146         </TD>
147         <<%$tdh%>><FONT SIZE="+1"><B> - </B></FONT></TD>
148         <<%$tdh%> ALIGN="right">
149           <A HREF="<% $creditlink. $invlink %>;istax=1"
150           ><% &$money_sprintf( $region->{'credit'} ) %></A>
151         </TD>
152         <<%$tdh%>><FONT SIZE="+1"><B> = </B></FONT></TD>
153         <<%$tdh%> ALIGN="right">
154           <% &$money_sprintf( $region->{'tax'} - $region->{'credit'} ) %>
155         </TD>
156 %   }
157 % } # not $out
158
159     </TR>
160 % } 
161
162 </TABLE>
163
164 % if ( $cgi->param('show_taxclasses') ) {
165
166     <BR>
167     <% include('/elements/table-grid.html') %>
168     <TR>
169       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
170       <TH CLASS="grid" BGCOLOR="#cccccc">Tax invoiced</TH>
171       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
172       <TH CLASS="grid" BGCOLOR="#cccccc">Tax credited</TH>
173       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
174       <TH CLASS="grid" BGCOLOR="#cccccc">Tax collected</TH>
175     </TR>
176
177 %   #some false laziness w/above
178 %   $bgcolor1 = '#eeeeee';
179 %   $bgcolor2 = '#ffffff';
180 %
181 %   foreach my $region ( @base_regions ) {
182 %
183 %     my $link = '';
184 %     if ( $region->{'label'} eq $out ) {
185 %       $link = ';out=1';
186 %     } else {
187 %       $link = ';'. $region->{'url_param'}
188 %         if $region->{'url_param'};
189 %     }
190 %
191 %     if ( $bgcolor eq $bgcolor1 ) {
192 %       $bgcolor = $bgcolor2;
193 %     } else {
194 %       $bgcolor = $bgcolor1;
195 %     }
196 %     my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
197 %     my $tdh = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
198 %
199 %     #?
200 %     my $invlink = $region->{'url_param_inv'}
201 %                     ? ';'. $region->{'url_param_inv'}
202 %                     : $link;
203
204       <TR>
205         <<%$td%>><% $region->{'label'} %></TD>
206 %     if ( $region->{'label'} eq $out ) {
207         <<%$td%> ALIGN="right">
208           <A HREF="<% $baselink. $invlink %>;istax=1"
209           ><% &$money_sprintf_nonzero( $region->{'tax'} ) %></A>
210         </TD>
211         <<%$td%>></TD>
212         <<%$td%> ALIGN="right">
213           <A HREF="<% $creditlink. $invlink %>;istax=1"
214           ><% &$money_sprintf_nonzero( $region->{'credit'} ) %></A>
215         </TD>
216         <<%$td%> COLSPAN=2></TD>
217 %     } else { #not $out
218         <<%$td%> ALIGN="right">
219           <A HREF="<% $baselink. $link %>;istax=1"
220           ><% &$money_sprintf( $region->{'tax'} ) %></A>
221         </TD>
222         <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
223         <<%$tdh%> ALIGN="right">
224           <A HREF="<% $creditlink. $invlink %>;istax=1"
225           ><% &$money_sprintf( $region->{'credit'} ) %></A>
226         </TD>
227         <<%$td%>><FONT SIZE="+1"><B> = </B></FONT></TD>
228         <<%$tdh%> ALIGN="right">
229           <% &$money_sprintf( $region->{'tax'} - $region->{'credit'} ) %>
230         </TD>
231       </TR>
232 %     } # if $out
233 %   } #foreach $region
234
235   </TABLE>
236
237 % } # if show_taxclasses
238
239 <% include('/elements/footer.html') %>
240
241 <%init>
242
243 die "access denied"
244   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
245
246 my $DEBUG = $cgi->param('debug') || 0;
247
248 my $conf = new FS::Conf;
249
250 my $out = 'Out of taxable region(s)';
251
252 my %label_opt = ( out => 1 ); #enable 'Out of Taxable Region' label
253 $label_opt{with_city} = 1     if $cgi->param('show_cities');
254 $label_opt{with_district} = 1 if $cgi->param('show_districts');
255
256 $label_opt{with_taxclass} = 1 if $cgi->param('show_taxclasses');
257
258 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
259
260 my $join_cust =     '     JOIN cust_bill      USING ( invnum  ) 
261                       LEFT JOIN cust_main     USING ( custnum ) ';
262
263 my $join_cust_pkg = $join_cust.
264                     ' LEFT JOIN cust_pkg      USING ( pkgnum  )
265                       LEFT JOIN part_pkg      USING ( pkgpart ) ';
266
267 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg "; 
268
269 # either or both of these can be used to link cust_bill_pkg to cust_main_county
270 my $pkg_tax = "SELECT SUM(amount) as tax_amount, invnum, taxnum, ".
271   "cust_bill_pkg_tax_location.pkgnum ".
272   "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
273   "GROUP BY billpkgnum, invnum, taxnum, cust_bill_pkg_tax_location.pkgnum";
274
275 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
276   "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
277
278 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
279 my $group = "GROUP BY cust_main_county.taxnum";
280
281 my $agentname = '';
282 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
283   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
284   die "agent not found" unless $agent;
285   $agentname = $agent->agent;
286   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
287 }
288
289 my $nottax = 'cust_bill_pkg.pkgnum != 0';
290
291 # one query for each column of the report
292 # plus separate queries for the totals row
293 my (%sql, %all_sql);
294
295 # general form
296 my $exempt = "SELECT cust_main_county.taxnum, SUM(exempt_charged)
297   FROM cust_main_county
298   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
299   USING (taxnum)
300   JOIN cust_bill_pkg USING (billpkgnum)
301   $join_cust $where AND $nottax $group";
302
303 my $all_exempt = "SELECT SUM(exempt_charged)
304   FROM cust_main_county
305   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
306   USING (taxnum)
307   JOIN cust_bill_pkg USING (billpkgnum)
308   $join_cust $where AND $nottax";
309
310 # sales to tax-exempt customers
311 $sql{exempt_cust} = $exempt;
312 $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
313 $all_sql{exempt_cust} = $all_exempt;
314 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
315
316 # sales of tax-exempt packages
317 $sql{exempt_pkg} = $exempt;
318 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
319 $all_sql{exempt_pkg} = $all_exempt;
320 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
321
322 # monthly per-customer exemptions
323 $sql{exempt_monthly} = $exempt;
324 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
325 $all_sql{exempt_monthly} = $all_exempt;
326 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
327
328 # taxable sales
329 $sql{taxable} = "SELECT cust_main_county.taxnum, 
330   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
331   FROM cust_main_county
332   JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
333   JOIN cust_bill_pkg USING (invnum, pkgnum)
334   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
335     ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
336         AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
337   $join_cust $where AND $nottax $group";
338
339 # Here we're going to sum all line items that are taxable _at all_,
340 # under any tax.  exempt_charged is the sum of all exemptions for a 
341 # particular billpkgnum + taxnum; we take the taxnum that has the 
342 # smallest sum of exemptions and subtract that from the charged amount.
343 $all_sql{taxable} = "SELECT
344   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(min_exempt, 0))
345   FROM cust_bill_pkg
346   JOIN (
347     SELECT invnum, pkgnum, MIN(exempt_charged) AS min_exempt
348     FROM ($pkg_tax) AS pkg_tax
349     JOIN cust_bill_pkg USING (invnum, pkgnum)
350     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
351     GROUP BY invnum, pkgnum
352   ) AS pkg_is_taxable 
353   USING (invnum, pkgnum)
354   $join_cust $where AND $nottax";
355   # we don't join pkg_tax_exempt.taxnum here, because
356
357 $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
358 $all_sql{taxable} =~ s/EXEMPT_WHERE//;
359
360 # there isn't one for 'sales', because we calculate sales by adding up 
361 # the taxable and exempt columns.
362
363 # sum of billed tax:
364 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
365 my $taxfrom = " FROM cust_bill_pkg 
366                 $join_cust 
367                 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
368                 LEFT JOIN cust_main_county USING ( taxnum )";
369
370 my $istax = "cust_bill_pkg.pkgnum = 0";
371 my $named_tax = "(
372   taxname = itemdesc
373   OR ( taxname IS NULL 
374     AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )
375   )
376 )";
377
378 $sql{tax} = "SELECT cust_main_county.taxnum, 
379              SUM(cust_bill_pkg_tax_location.amount)
380              $taxfrom
381              $where AND $istax AND $named_tax
382              $group";
383
384 $all_sql{tax} = "SELECT SUM(cust_bill_pkg.setup)
385              FROM cust_bill_pkg
386              $join_cust
387              $where AND $istax";
388
389 # sum of credits applied against billed tax
390 my $creditfrom = $taxfrom .
391    ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)';
392 my $creditfromwhere = $where . 
393    ' AND billpkgtaxratelocationnum IS NULL';
394
395 $sql{credit} = "SELECT cust_main_county.taxnum,
396                 SUM(cust_credit_bill_pkg.amount)
397                 $creditfrom
398                 $creditfromwhere AND $istax AND $named_tax
399                 $group";
400
401 $all_sql{credit} = "SELECT SUM(cust_credit_bill_pkg.amount)
402                 FROM cust_credit_bill_pkg
403                 JOIN cust_bill_pkg USING (billpkgnum)
404                 $join_cust
405                 $where AND $istax";
406
407 my %data;
408 my %total = (owed => 0);
409 foreach my $k (keys(%sql)) {
410   my $stmt = $sql{$k};
411   warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
412   my $sth = dbh->prepare($stmt);
413   # two columns => key/value
414   $sth->execute 
415     or die "failed to execute $k query: ".$sth->errstr;
416   $data{$k} = +{ map { @$_ } @{ $sth->fetchall_arrayref([]) } };
417
418   warn "\n".$all_sql{$k}."\n" if $DEBUG;
419   $total{$k} = FS::Record->scalar_sql( $all_sql{$k} );
420   warn Dumper($data{$k}) if $DEBUG > 1;
421 }
422 # so $data{tax}, for example, is now a hash with one entry
423 # for each taxnum, containing the tax billed on that taxnum.
424
425 # oddball cases:
426 # "out of taxable region" sales
427 my %out;
428 my $out_sales_sql = 
429   "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
430   FROM (cust_bill_pkg $join_cust)
431   LEFT JOIN ($pkg_tax) AS pkg_tax USING (invnum, pkgnum)
432   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum)
433   $where AND $nottax
434   AND pkg_tax.taxnum IS NULL AND pkg_tax_exempt.taxnum IS NULL"
435 ;
436
437 $out_sales_sql =~ s/EXEMPT_WHERE//;
438
439 $out{sales} = FS::Record->scalar_sql($out_sales_sql);
440
441 # unlinked tax collected (for diagnostics)
442 my $out_tax_sql =
443   "SELECT SUM(cust_bill_pkg.setup)
444   FROM (cust_bill_pkg $join_cust)
445   LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
446   $where AND $istax AND cust_bill_pkg_tax_location.billpkgnum IS NULL"
447 ;
448 $out{tax} = FS::Record->scalar_sql($out_tax_sql);
449 # unlinked tax credited (for diagnostics)
450 my $out_credit_sql =
451   "SELECT SUM(cust_credit_bill_pkg.amount)
452   FROM cust_credit_bill_pkg
453   JOIN cust_bill_pkg USING (billpkgnum)
454   $join_cust
455   $where AND $istax AND cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL"
456 ;
457 $out{credit} = FS::Record->scalar_sql($out_credit_sql);
458
459 # all sales
460 $total{sales} = FS::Record->scalar_sql(
461   "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
462   FROM cust_bill_pkg $join_cust $where AND $nottax"
463 );
464
465 #tax-report_groups filtering
466 my($group_op, $group_value) = ( '', '' );
467 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ ) {
468   ( $group_op, $group_value ) = ( $1, $2 );
469 }
470 my $group_test = sub { # to be applied to a tax label
471   my $label = shift;
472   return 1 unless $group_op; #in case we get called inadvertantly
473   if ( $label eq $out ) { #don't display "out of taxable region" in this case
474     0;
475   } elsif ( $group_op eq '=' ) {
476     $label =~ /^$group_value/;
477   } elsif ( $group_op eq '!=' ) {
478     $label !~ /^$group_value/;
479   } else {
480     die "guru meditation #00de: group_op $group_op\n";
481   }
482 };
483
484 # if show_taxclasses is on, %base_regions will contain the same data
485 # as %regions, but with taxclasses merged together (and ignoring report_group
486 # filtering).
487 my (%regions, %base_regions);
488 my $tot_tax = 0;
489 my $tot_credit = 0;
490
491 my @loc_params = qw(country state county);
492 push @loc_params, 'city' if $cgi->param('show_cities');
493 push @loc_params, 'district' if $cgi->param('show_districts');
494
495 foreach my $r ( qsearch({ 'table'     => 'cust_main_county', })) {
496   my $taxnum = $r->taxnum;
497   # set up a %regions entry for this region's tax label
498   my $label = $r->label(%label_opt);
499   next if $label eq $out;
500   $regions{$label} ||= { label => $label };
501
502   $regions{$label}->{$_} = $r->get($_) foreach @loc_params;
503   $regions{$label}->{taxnums} ||= [];
504   push @{ $regions{$label}->{taxnums} }, $r->taxnum;
505
506   my %x; # keys are data items (like 'tax', 'exempt_cust', etc.)
507   foreach my $k (keys %data) {
508     next unless exists($data{$k}->{$taxnum});
509     $x{$k} = $data{$k}->{$taxnum};
510     $regions{$label}->{$k} += $x{$k};
511     if ( $k eq 'taxable' or $k =~ /^exempt/ ) {
512       $regions{$label}->{'sales'} += $x{$k};
513     }
514   }
515
516   my $owed = $data{'taxable'}->{$taxnum} * ($r->tax/100);
517   $regions{$label}->{'owed'} += $owed;
518   $total{'owed'} += $owed;
519
520   if ( defined($regions{$label}->{'rate'})
521        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
522     $regions{$label}->{'rate'} = 'variable';
523   } else {
524     $regions{$label}->{'rate'} = $r->tax.'%';
525   }
526
527   if ( $cgi->param('show_taxclasses') ) {
528     my $base_label = $r->label(%label_opt, 'with_taxclass' => 0);
529     $base_regions{$base_label} ||=
530     {
531       label   => $base_label,
532       tax     => 0,
533       credit  => 0,
534     };
535     $base_regions{$base_label}->{tax}    += $x{tax};
536     $base_regions{$base_label}->{credit} += $x{credit};
537   }
538
539 }
540
541 my @regions = map { $_->{label} }
542   sort {
543     ($b eq $out) <=> ($a eq $out)
544     or $a->{country} cmp $b->{country}
545     or $a->{state}   cmp $b->{state}
546     or $a->{county}  cmp $b->{county}
547     or $a->{city}    cmp $b->{city}
548   } 
549   grep { $_->{sales} > 0 or $_->{tax} > 0 or $_->{credit} > 0 }
550   values %regions;
551
552 #tax-report_groups filtering
553 @regions = grep &{$group_test}($_), @regions
554   if $group_op;
555
556 #calculate totals
557 my %taxclasses = ();
558 my %county = ();
559 my %state = ();
560 my %country = ();
561 foreach my $label (@regions) {
562   $taxclasses{$regions{$_}->{'taxclass'}} = 1
563     if $regions{$_}->{'taxclass'};
564   $county{$regions{$_}->{'county'}} = 1;
565   $state{$regions{$_}->{'state'}} = 1;
566   $country{$regions{$_}->{'country'}} = 1;
567 }
568
569 my $total_url_param = '';
570 my $total_url_param_invoiced = '';
571 if ( $group_op ) {
572
573   my @country = keys %country;
574   warn "WARNING: multiple countries on this grouped report; total links broken"
575     if scalar(@country) > 1;
576   my $country = $country[0];
577
578   my @state = keys %state;
579   warn "WARNING: multiple countries on this grouped report; total links broken"
580     if scalar(@state) > 1;
581   my $state = $state[0];
582
583   $total_url_param_invoiced =
584   $total_url_param =
585     'report_group='.uri_escape("$group_op $group_value").';'.
586     join(';', map 'taxclass='.uri_escape($_), keys %taxclasses );
587   $total_url_param .= ';'.
588     "country=$country;state=".uri_escape($state).';'.
589     join(';', map 'county='.uri_escape($_), keys %county ) ;
590
591 }
592
593 #ordering
594 @regions =
595   map $regions{$_},
596   sort { $a cmp $b }
597   @regions;
598
599 my @base_regions =
600   map $base_regions{$_},
601   sort { $a cmp $b }
602   keys %base_regions;
603
604 #add "Out of taxable" and total lines
605 %out = ( %out,
606   'label' => $out,
607   'rate' => ''
608 );
609 %total = ( %total, 
610   'label'         => 'Total',
611   'url_param'     => $total_url_param,
612   'url_param_inv' => $total_url_param_invoiced,
613   'rate'          => '',
614 );
615 push @regions, \%out, \%total;
616 push @base_regions, \%out, \%total;
617
618 #-- 
619
620 my $money_char = $conf->config('money_char') || '$';
621 my $money_sprintf = sub {
622   $money_char. sprintf('%.2f', shift );
623 };
624 my $money_sprintf_nonzero = sub {
625   $_[0] == 0 ? '' : &$money_sprintf($_[0])
626 };
627
628 my $dateagentlink = "begin=$beginning;end=$ending";
629 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
630   if length($agentname);
631 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
632 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
633 my $creditlink = $p. "search/cust_bill_pkg.cgi?$dateagentlink;credit=1";
634
635 </%init>