NG auth: autocreate records for external users, RT#21563
[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{no_city} = 1     unless $cgi->param('show_cities');
254 $label_opt{no_taxclass} = 1 unless $cgi->param('show_taxclasses');
255
256 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
257
258 my $join_cust =     '     JOIN cust_bill      USING ( invnum  ) 
259                       LEFT JOIN cust_main     USING ( custnum ) ';
260
261 my $join_cust_pkg = $join_cust.
262                     ' LEFT JOIN cust_pkg      USING ( pkgnum  )
263                       LEFT JOIN part_pkg      USING ( pkgpart ) ';
264
265 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg "; 
266
267 # either or both of these can be used to link cust_bill_pkg to cust_main_county
268 my $pkg_tax = "SELECT SUM(amount) as tax_amount, invnum, taxnum, ".
269   "cust_bill_pkg_tax_location.pkgnum ".
270   "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
271   "GROUP BY billpkgnum, invnum, taxnum, cust_bill_pkg_tax_location.pkgnum";
272
273 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
274   "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
275
276 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
277 my $group = "GROUP BY cust_main_county.taxnum";
278
279 my $agentname = '';
280 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
281   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
282   die "agent not found" unless $agent;
283   $agentname = $agent->agent;
284   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
285 }
286
287 my $nottax = 'cust_bill_pkg.pkgnum != 0';
288
289 # one query for each column of the report
290 # plus separate queries for the totals row
291 my (%sql, %all_sql);
292
293 # general form
294 my $exempt = "SELECT cust_main_county.taxnum, SUM(exempt_charged)
295   FROM cust_main_county
296   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
297   USING (taxnum)
298   JOIN cust_bill_pkg USING (billpkgnum)
299   $join_cust $where AND $nottax $group";
300
301 my $all_exempt = "SELECT SUM(exempt_charged)
302   FROM cust_main_county
303   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
304   USING (taxnum)
305   JOIN cust_bill_pkg USING (billpkgnum)
306   $join_cust $where AND $nottax";
307
308 # sales to tax-exempt customers
309 $sql{exempt_cust} = $exempt;
310 $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
311 $all_sql{exempt_cust} = $all_exempt;
312 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
313
314 # sales of tax-exempt packages
315 $sql{exempt_pkg} = $exempt;
316 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
317 $all_sql{exempt_pkg} = $all_exempt;
318 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
319
320 # monthly per-customer exemptions
321 $sql{exempt_monthly} = $exempt;
322 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
323 $all_sql{exempt_monthly} = $all_exempt;
324 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
325
326 # taxable sales
327 $sql{taxable} = "SELECT cust_main_county.taxnum, 
328   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
329   FROM cust_main_county
330   JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
331   JOIN cust_bill_pkg USING (invnum, pkgnum)
332   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
333     ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
334         AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
335   $join_cust $where AND $nottax $group";
336
337 # Here we're going to sum all line items that are taxable _at all_,
338 # under any tax.  exempt_charged is the sum of all exemptions for a 
339 # particular billpkgnum + taxnum; we take the taxnum that has the 
340 # smallest sum of exemptions and subtract that from the charged amount.
341 $all_sql{taxable} = "SELECT
342   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(min_exempt, 0))
343   FROM cust_bill_pkg
344   JOIN (
345     SELECT invnum, pkgnum, MIN(exempt_charged) AS min_exempt
346     FROM ($pkg_tax) AS pkg_tax
347     JOIN cust_bill_pkg USING (invnum, pkgnum)
348     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
349     GROUP BY invnum, pkgnum
350   ) AS pkg_is_taxable 
351   USING (invnum, pkgnum)
352   $join_cust $where AND $nottax";
353   # we don't join pkg_tax_exempt.taxnum here, because
354
355 $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
356 $all_sql{taxable} =~ s/EXEMPT_WHERE//;
357
358 # there isn't one for 'sales', because we calculate sales by adding up 
359 # the taxable and exempt columns.
360
361 # sum of billed tax:
362 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
363 my $taxfrom = " FROM cust_bill_pkg 
364                 $join_cust 
365                 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
366                 LEFT JOIN cust_main_county USING ( taxnum )";
367
368 my $istax = "cust_bill_pkg.pkgnum = 0";
369 my $named_tax = "(
370   taxname = itemdesc
371   OR ( taxname IS NULL 
372     AND ( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )
373   )
374 )";
375
376 $sql{tax} = "SELECT cust_main_county.taxnum, 
377              SUM(cust_bill_pkg_tax_location.amount)
378              $taxfrom
379              $where AND $istax AND $named_tax
380              $group";
381
382 $all_sql{tax} = "SELECT SUM(cust_bill_pkg.setup)
383              FROM cust_bill_pkg
384              $join_cust
385              $where AND $istax";
386
387 # sum of credits applied against billed tax
388 my $creditfrom = $taxfrom .
389    ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)';
390 my $creditfromwhere = $where . 
391    ' AND billpkgtaxratelocationnum IS NULL';
392
393 $sql{credit} = "SELECT cust_main_county.taxnum,
394                 SUM(cust_credit_bill_pkg.amount)
395                 $creditfrom
396                 $creditfromwhere AND $istax AND $named_tax
397                 $group";
398
399 $all_sql{credit} = "SELECT SUM(cust_credit_bill_pkg.amount)
400                 FROM cust_credit_bill_pkg
401                 JOIN cust_bill_pkg USING (billpkgnum)
402                 $join_cust
403                 $where AND $istax";
404
405 my %data;
406 my %total = (owed => 0);
407 foreach my $k (keys(%sql)) {
408   my $stmt = $sql{$k};
409   warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
410   my $sth = dbh->prepare($stmt);
411   # two columns => key/value
412   $sth->execute 
413     or die "failed to execute $k query: ".$sth->errstr;
414   $data{$k} = +{ map { @$_ } @{ $sth->fetchall_arrayref([]) } };
415
416   warn "\n".$all_sql{$k}."\n" if $DEBUG;
417   $total{$k} = FS::Record->scalar_sql( $all_sql{$k} );
418   warn Dumper($data{$k}) if $DEBUG > 1;
419 }
420 # so $data{tax}, for example, is now a hash with one entry
421 # for each taxnum, containing the tax billed on that taxnum.
422
423 # oddball cases:
424 # "out of taxable region" sales
425 my %out;
426 my $out_sales_sql = 
427   "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
428   FROM (cust_bill_pkg $join_cust)
429   LEFT JOIN ($pkg_tax) AS pkg_tax USING (invnum, pkgnum)
430   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum)
431   $where AND $nottax
432   AND pkg_tax.taxnum IS NULL AND pkg_tax_exempt.taxnum IS NULL"
433 ;
434
435 $out_sales_sql =~ s/EXEMPT_WHERE//;
436
437 $out{sales} = FS::Record->scalar_sql($out_sales_sql);
438
439 # unlinked tax collected (for diagnostics)
440 my $out_tax_sql =
441   "SELECT SUM(cust_bill_pkg.setup)
442   FROM (cust_bill_pkg $join_cust)
443   LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
444   $where AND $istax AND cust_bill_pkg_tax_location.billpkgnum IS NULL"
445 ;
446 $out{tax} = FS::Record->scalar_sql($out_tax_sql);
447 # unlinked tax credited (for diagnostics)
448 my $out_credit_sql =
449   "SELECT SUM(cust_credit_bill_pkg.amount)
450   FROM cust_credit_bill_pkg
451   JOIN cust_bill_pkg USING (billpkgnum)
452   $join_cust
453   $where AND $istax AND cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL"
454 ;
455 $out{credit} = FS::Record->scalar_sql($out_credit_sql);
456
457 # all sales
458 $total{sales} = FS::Record->scalar_sql(
459   "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
460   FROM cust_bill_pkg $join_cust $where AND $nottax"
461 );
462
463 #tax-report_groups filtering
464 my($group_op, $group_value) = ( '', '' );
465 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ ) {
466   ( $group_op, $group_value ) = ( $1, $2 );
467 }
468 my $group_test = sub { # to be applied to a tax label
469   my $label = shift;
470   return 1 unless $group_op; #in case we get called inadvertantly
471   if ( $label eq $out ) { #don't display "out of taxable region" in this case
472     0;
473   } elsif ( $group_op eq '=' ) {
474     $label =~ /^$group_value/;
475   } elsif ( $group_op eq '!=' ) {
476     $label !~ /^$group_value/;
477   } else {
478     die "guru meditation #00de: group_op $group_op\n";
479   }
480 };
481
482 # if show_taxclasses is on, %base_regions will contain the same data
483 # as %regions, but with taxclasses merged together (and ignoring report_group
484 # filtering).
485 my (%regions, %base_regions);
486 my $tot_tax = 0;
487 my $tot_credit = 0;
488
489 my @loc_params = qw(country state county);
490 push @loc_params, qw(city district) if $cgi->param('show_cities');
491
492 foreach my $r ( qsearch({ 'table'     => 'cust_main_county', })) {
493   my $taxnum = $r->taxnum;
494   # set up a %regions entry for this region's tax label
495   my $label = $r->label(%label_opt);
496   next if $label eq $out;
497   $regions{$label} ||= { label => $label };
498
499   $regions{$label}->{$_} = $r->get($_) foreach @loc_params;
500   $regions{$label}->{taxnums} ||= [];
501   push @{ $regions{$label}->{taxnums} }, $r->taxnum;
502
503   my %x; # keys are data items (like 'tax', 'exempt_cust', etc.)
504   foreach my $k (keys %data) {
505     next unless exists($data{$k}->{$taxnum});
506     $x{$k} = $data{$k}->{$taxnum};
507     $regions{$label}->{$k} += $x{$k};
508     if ( $k eq 'taxable' or $k =~ /^exempt/ ) {
509       $regions{$label}->{'sales'} += $x{$k};
510     }
511   }
512
513   my $owed = $data{'taxable'}->{$taxnum} * ($r->tax/100);
514   $regions{$label}->{'owed'} += $owed;
515   $total{'owed'} += $owed;
516
517   if ( defined($regions{$label}->{'rate'})
518        && $regions{$label}->{'rate'} != $r->tax.'%' ) {
519     $regions{$label}->{'rate'} = 'variable';
520   } else {
521     $regions{$label}->{'rate'} = $r->tax.'%';
522   }
523
524   if ( $cgi->param('show_taxclasses') ) {
525     my $base_label = $r->label(%label_opt, 'no_taxclass' => 1);
526     $base_regions{$base_label} ||=
527     {
528       label   => $base_label,
529       tax     => 0,
530       credit  => 0,
531     };
532     $base_regions{$base_label}->{tax}    += $x{tax};
533     $base_regions{$base_label}->{credit} += $x{credit};
534   }
535
536 }
537
538 my @regions = map { $_->{label} }
539   sort {
540     ($b eq $out) <=> ($a eq $out)
541     or $a->{country} cmp $b->{country}
542     or $a->{state}   cmp $b->{state}
543     or $a->{county}  cmp $b->{county}
544     or $a->{city}    cmp $b->{city}
545   } 
546   grep { $_->{sales} > 0 or $_->{tax} > 0 or $_->{credit} > 0 }
547   values %regions;
548
549 #tax-report_groups filtering
550 @regions = grep &{$group_test}($_), @regions
551   if $group_op;
552
553 #calculate totals
554 my %taxclasses = ();
555 my %county = ();
556 my %state = ();
557 my %country = ();
558 foreach my $label (@regions) {
559   $taxclasses{$regions{$_}->{'taxclass'}} = 1
560     if $regions{$_}->{'taxclass'};
561   $county{$regions{$_}->{'county'}} = 1;
562   $state{$regions{$_}->{'state'}} = 1;
563   $country{$regions{$_}->{'country'}} = 1;
564 }
565
566 my $total_url_param = '';
567 my $total_url_param_invoiced = '';
568 if ( $group_op ) {
569
570   my @country = keys %country;
571   warn "WARNING: multiple countries on this grouped report; total links broken"
572     if scalar(@country) > 1;
573   my $country = $country[0];
574
575   my @state = keys %state;
576   warn "WARNING: multiple countries on this grouped report; total links broken"
577     if scalar(@state) > 1;
578   my $state = $state[0];
579
580   $total_url_param_invoiced =
581   $total_url_param =
582     'report_group='.uri_escape("$group_op $group_value").';'.
583     join(';', map 'taxclass='.uri_escape($_), keys %taxclasses );
584   $total_url_param .= ';'.
585     "country=$country;state=".uri_escape($state).';'.
586     join(';', map 'county='.uri_escape($_), keys %county ) ;
587
588 }
589
590 #ordering
591 @regions =
592   map $regions{$_},
593   sort { $a cmp $b }
594   @regions;
595
596 my @base_regions =
597   map $base_regions{$_},
598   sort { $a cmp $b }
599   keys %base_regions;
600
601 #add "Out of taxable" and total lines
602 %out = ( %out,
603   'label' => $out,
604   'rate' => ''
605 );
606 %total = ( %total, 
607   'label'         => 'Total',
608   'url_param'     => $total_url_param,
609   'url_param_inv' => $total_url_param_invoiced,
610   'rate'          => '',
611 );
612 push @regions, \%out, \%total;
613 push @base_regions, \%out, \%total;
614
615 #-- 
616
617 my $money_char = $conf->config('money_char') || '$';
618 my $money_sprintf = sub {
619   $money_char. sprintf('%.2f', shift );
620 };
621 my $money_sprintf_nonzero = sub {
622   $_[0] == 0 ? '' : &$money_sprintf($_[0])
623 };
624
625 my $dateagentlink = "begin=$beginning;end=$ending";
626 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
627   if length($agentname);
628 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
629 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
630 my $creditlink = $p. "search/cust_bill_pkg.cgi?$dateagentlink;credit=1";
631
632 </%init>