d71fcf90be0e4c1cb37bac026adbe48cba2bf77b
[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 <STYLE type="text/css">
19 td.sectionhead {
20   background-color: #777777;
21   color: #ffffff;
22   font-weight: bold;
23   text-align: left;
24 }
25 </STYLE>
26 <% include('/elements/table-grid.html') %>
27   <TR>
28     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
29     <TH CLASS="grid" BGCOLOR="#cccccc" COLSPAN=9>Sales</TH>
30     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
31     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Rate</TH>
32     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
33     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax owed</TH>
34 % unless ( $cgi->param('show_taxclasses') ) { 
35       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax invoiced</TH>
36       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
37       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax credited</TH>
38       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3></TH>
39       <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=3>Tax collected</TH>
40 % } 
41   </TR>
42
43   <TR>
44     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Total</TH>
45     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
46     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=1>Non-taxable</TH>
47     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
48     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=1>Non-taxable</TH>
49     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
50     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=1>Non-taxable</TH>
51     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2></TH>
52     <TH CLASS="grid" BGCOLOR="#cccccc" ROWSPAN=2>Taxable</TH>
53   </TR>
54
55   <TR>
56     <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1>(tax-exempt customer)</FONT></TH>
57     <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1>(tax-exempt package)</FONT></TH>
58     <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1>(monthly exemption)</FONT></TH>
59   </TR>
60
61 % foreach my $class (@pkgclasses ) {
62 %   next if @{ $class->{regions} } == 0;
63 %   if ( $class->{classname} ) {
64   <TR>
65     <TD COLSPAN=19 CLASS="sectionhead"><% $class->{classname} %></TD>
66   </TR>
67 %   }
68
69 % my $bgcolor1 = '#eeeeee';
70 % my $bgcolor2 = '#ffffff';
71 % my $bgcolor;
72
73 % my @regions = @{ $class->{regions} };
74 % foreach my $region ( @regions ) {
75 %
76 %   my $link = '';
77 %   if ( $with_pkgclass and length($class->{classnum}) ) {
78 %     $link = ';classnum='.$class->{classnum};
79 %   } # else we're not breaking down pkg class, or this is the grand total
80 %
81 %   if ( $region->{'label'} eq $out ) {
82 %     $link .= ';out=1';
83 %   } elsif ( $region->{'taxnums'} ) {
84 %     # might be nicer to specify this as country:state:city
85 %     $link .= ';'.join(';', map { "taxnum=$_" } @{ $region->{'taxnums'} });
86 %   }
87 %
88 %   if ( $bgcolor eq $bgcolor1 ) {
89 %     $bgcolor = $bgcolor2;
90 %   } else {
91 %     $bgcolor = $bgcolor1;
92 %   }
93 %
94 %   my $hicolor = $bgcolor;
95 %   unless ( $cgi->param('show_taxclasses') ) {
96 %     my $diff = abs(   sprintf( '%.2f', $region->{'owed'} )
97 %                     - sprintf( '%.2f', $region->{'tax'}  )
98 %                   );
99 %     if ( $diff > 0.02 ) {
100 %       $hicolor = $hicolor eq '#eeeeee' ? '#eeee99' : '#ffffcc';
101 %     }
102 %   }
103 %
104 %
105 %   my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
106 %   my $tdh = qq(TD CLASS="grid" BGCOLOR="$hicolor");
107 %   my $bigmath = '<FONT FACE="sans-serif" SIZE="+1"><B>';
108 %   my $bme = '</B></FONT>';
109
110 %   if ( $region->{'is_total'} ) {
111     <TR STYLE="font-style: italic">
112       <TD STYLE="text-align: right; padding-right: 1ex; background-color:<%$bgcolor%>">Total</TD>
113 %   } else {
114     <TR>
115       <<%$td%>><% $region->{'label'} %></TD>
116 %   }
117       <<%$td%> ALIGN="right">
118         <A HREF="<% $baselink. $link %>;nottax=1"
119         ><% &$money_sprintf( $region->{'sales'} ) %></A>
120       </TD>
121 %   if ( $region->{'label'} eq $out ) {
122       <<%$td%> COLSPAN=12></TD>
123 %   } else { #not $out
124       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
125       <<%$td%> ALIGN="right">
126         <A HREF="<% $baselink. $link %>;nottax=1;exempt_cust=Y"
127         ><% &$money_sprintf( $region->{'exempt_cust'} ) %></A>
128       </TD>
129       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
130       <<%$td%> ALIGN="right">
131         <A HREF="<% $baselink. $link %>;nottax=1;exempt_pkg=Y"
132         ><% &$money_sprintf( $region->{'exempt_pkg'} ) %></A>
133       </TD>
134       <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
135       <<%$td%> ALIGN="right">
136         <A HREF="<% $exemptlink. $link %>"
137         ><% &$money_sprintf( $region->{'exempt_monthly'} ) %></A>
138         </TD>
139       <<%$td%>><FONT SIZE="+1"><B> = </B></FONT></TD>
140       <<%$td%> ALIGN="right">
141         <A HREF="<% $baselink. $link %>;nottax=1;taxable=1"
142         ><% &$money_sprintf( $region->{'taxable'} ) %></A>
143       </TD>
144       <<%$td%>><% $region->{'label'} eq 'Total' ? '' : "$bigmath X $bme" %></TD>
145       <<%$td%> ALIGN="right"><% $region->{'rate'} %></TD>
146       <<%$td%>><% $region->{'label'} eq 'Total' ? '' : "$bigmath = $bme" %></TD>
147       <<%$tdh%> ALIGN="right">
148         <% &$money_sprintf( $region->{'owed'} ) %>
149       </TD>
150 %   } # if !$out
151 %   unless ( $cgi->param('show_taxclasses') ) {
152 %     my $invlink = $region->{'url_param_inv'}
153 %                       ? ';'. $region->{'url_param_inv'}
154 %                       : $link;
155
156 %     if ( $region->{'label'} eq $out ) {
157         <<%$td%> ALIGN="right">
158           <A HREF="<% $baselink. $invlink %>;istax=1"
159           ><% &$money_sprintf_nonzero( $region->{'tax'} ) %></A>
160         </TD>
161         <<%$td%>></TD>
162         <<%$td%> ALIGN="right">
163           <A HREF="<% $creditlink. $invlink %>;istax=1"
164           ><% &$money_sprintf_nonzero( $region->{'credit'} ) %></A>
165         </TD>
166         <<%$td%> COLSPAN=2></TD>
167 %     } else { #not $out
168         <<%$tdh%> ALIGN="right">
169           <A HREF="<% $baselink. $invlink %>;istax=1"
170           ><% &$money_sprintf( $region->{'tax'} ) %></A>
171         </TD>
172         <<%$tdh%>><FONT SIZE="+1"><B> - </B></FONT></TD>
173         <<%$tdh%> ALIGN="right">
174           <A HREF="<% $creditlink. $invlink %>;istax=1"
175           ><% &$money_sprintf( $region->{'credit'} ) %></A>
176         </TD>
177         <<%$tdh%>><FONT SIZE="+1"><B> = </B></FONT></TD>
178         <<%$tdh%> ALIGN="right">
179           <% &$money_sprintf( $region->{'tax'} - $region->{'credit'} ) %>
180         </TD>
181 %     }
182 %   } # show_taxclasses
183
184     </TR>
185 % } # foreach $region
186
187 %} # foreach $class
188
189 </TABLE>
190
191 % if ( $cgi->param('show_taxclasses') ) {
192
193     <BR>
194     <% include('/elements/table-grid.html') %>
195     <TR>
196       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
197       <TH CLASS="grid" BGCOLOR="#cccccc">Tax invoiced</TH>
198       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
199       <TH CLASS="grid" BGCOLOR="#cccccc">Tax credited</TH>
200       <TH CLASS="grid" BGCOLOR="#cccccc"></TH>
201       <TH CLASS="grid" BGCOLOR="#cccccc">Tax collected</TH>
202     </TR>
203
204 %   #some false laziness w/above
205 %   foreach my $class (@pkgclasses) {
206 %   if ( $class->{classname} ) {
207     <TR>
208       <TD COLSPAN=6 CLASS="sectionhead"><% $class->{classname} %></TD>
209     </TR>
210 %   }
211
212 %   my $bgcolor1 = '#eeeeee';
213 %   my $bgcolor2 = '#ffffff';
214 %   my $bgcolor;
215 %
216 %   foreach my $region ( @{ $class->{base_regions} } ) {
217 %
218 %     my $link = '';
219 %     if ( $with_pkgclass and length($class->{classnum}) ) {
220 %       $link = ';classnum='.$class->{classnum};
221 %     }
222 %
223 %     if ( $region->{'label'} eq $out ) {
224 %       $link .= ';out=1';
225 %     } else {
226 %       $link .= ';'. $region->{'url_param'}
227 %         if $region->{'url_param'};
228 %     }
229 %
230 %     if ( $bgcolor eq $bgcolor1 ) {
231 %       $bgcolor = $bgcolor2;
232 %     } else {
233 %       $bgcolor = $bgcolor1;
234 %     }
235 %     my $td = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
236 %     my $tdh = qq(TD CLASS="grid" BGCOLOR="$bgcolor");
237 %
238 %     #?
239 %     my $invlink = $region->{'url_param_inv'}
240 %                     ? ';'. $region->{'url_param_inv'}
241 %                     : $link;
242
243       <TR>
244         <<%$td%>><% $region->{'label'} %></TD>
245 %     if ( $region->{'label'} eq $out ) {
246         <<%$td%> ALIGN="right">
247           <A HREF="<% $baselink. $invlink %>;istax=1"
248           ><% &$money_sprintf_nonzero( $region->{'tax'} ) %></A>
249         </TD>
250         <<%$td%>></TD>
251         <<%$td%> ALIGN="right">
252           <A HREF="<% $creditlink. $invlink %>;istax=1"
253           ><% &$money_sprintf_nonzero( $region->{'credit'} ) %></A>
254         </TD>
255         <<%$td%> COLSPAN=2></TD>
256 %     } else { #not $out
257         <<%$td%> ALIGN="right">
258           <A HREF="<% $baselink. $link %>;istax=1"
259           ><% &$money_sprintf( $region->{'tax'} ) %></A>
260         </TD>
261         <<%$td%>><FONT SIZE="+1"><B> - </B></FONT></TD>
262         <<%$tdh%> ALIGN="right">
263           <A HREF="<% $creditlink. $invlink %>;istax=1"
264           ><% &$money_sprintf( $region->{'credit'} ) %></A>
265         </TD>
266         <<%$td%>><FONT SIZE="+1"><B> = </B></FONT></TD>
267         <<%$tdh%> ALIGN="right">
268           <% &$money_sprintf( $region->{'tax'} - $region->{'credit'} ) %>
269         </TD>
270       </TR>
271 %     } # if $out
272 %   } #foreach $region
273 % } #foreach $class
274
275   </TABLE>
276
277 % } # if show_taxclasses
278
279 <% include('/elements/footer.html') %>
280
281 <%init>
282
283 die "access denied"
284   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
285
286 my $DEBUG = $cgi->param('debug') || 0;
287
288 my $conf = new FS::Conf;
289
290 my $out = 'Out of taxable region(s)';
291
292 my %label_opt = ( out => 1 ); #enable 'Out of Taxable Region' label
293 $label_opt{with_city} = 1     if $cgi->param('show_cities');
294 $label_opt{with_district} = 1 if $cgi->param('show_districts');
295
296 $label_opt{with_taxclass} = 1 if $cgi->param('show_taxclasses');
297
298 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
299
300 my $join_cust =     '     JOIN cust_bill      USING ( invnum  ) 
301                       LEFT JOIN cust_main     USING ( custnum ) ';
302
303 my $join_cust_pkg = $join_cust.
304                     ' LEFT JOIN cust_pkg      USING ( pkgnum  )
305                       LEFT JOIN part_pkg      USING ( pkgpart ) ';
306
307 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg "; 
308
309 my $with_pkgclass = $cgi->param('show_pkgclasses');
310
311 # either or both of these can be used to link cust_bill_pkg to cust_main_county
312 my $pkg_tax = "SELECT SUM(amount) as tax_amount, invnum, taxnum, ".
313   "cust_bill_pkg_tax_location.pkgnum ".
314   "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
315   "GROUP BY billpkgnum, invnum, taxnum, cust_bill_pkg_tax_location.pkgnum";
316
317 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
318   "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
319
320 my $where = "WHERE _date >= $beginning AND _date <= $ending ";
321 # SELECT/GROUP clauses for first-level queries
322 # classnum is a placeholder; they all go in one class in this case.
323 my $select = "SELECT NULL AS classnum, cust_main_county.taxnum, ";
324 my $group =  "GROUP BY cust_main_county.taxnum";
325 # SELECT/GROUP clauses for second-level (totals) queries
326 my $select_all = "SELECT NULL AS classnum, ";
327 my $group_all =  "";
328
329 if ( $with_pkgclass ) {
330   $select = "SELECT COALESCE(part_pkg.classnum,0), cust_main_county.taxnum, ";
331   $group =  "GROUP BY part_pkg.classnum, cust_main_county.taxnum";
332   $select_all = "SELECT COALESCE(part_pkg.classnum,0), ";
333   $group_all  = "GROUP BY COALESCE(part_pkg.classnum,0)";
334 }
335
336 my $agentname = '';
337 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
338   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
339   die "agent not found" unless $agent;
340   $agentname = $agent->agent;
341   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
342 }
343
344 my $nottax = 'cust_bill_pkg.pkgnum != 0';
345
346 # one query for each column of the report
347 # plus separate queries for the totals row
348 my (%sql, %all_sql);
349
350 # SALES QUERIES (taxable sales, all types of exempt sales)
351 # -------------
352
353 # general form
354 my $exempt = "$select SUM(exempt_charged)
355   FROM cust_main_county
356   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
357   USING (taxnum)
358   JOIN cust_bill_pkg USING (billpkgnum)
359   $join_cust_pkg $where AND $nottax $group";
360
361 my $all_exempt = "$select_all SUM(exempt_charged)
362   FROM cust_main_county
363   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
364   USING (taxnum)
365   JOIN cust_bill_pkg USING (billpkgnum)
366   $join_cust_pkg $where AND $nottax
367   $group_all";
368
369 # sales to tax-exempt customers
370 $sql{exempt_cust} = $exempt;
371 $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
372 $all_sql{exempt_cust} = $all_exempt;
373 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
374
375 # sales of tax-exempt packages
376 $sql{exempt_pkg} = $exempt;
377 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
378 $all_sql{exempt_pkg} = $all_exempt;
379 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
380
381 # monthly per-customer exemptions
382 $sql{exempt_monthly} = $exempt;
383 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
384 $all_sql{exempt_monthly} = $all_exempt;
385 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
386
387 # taxable sales
388 $sql{taxable} = "$select
389   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
390   FROM cust_main_county
391   JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
392   JOIN cust_bill_pkg USING (invnum, pkgnum)
393   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
394     ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
395         AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
396   $join_cust_pkg $where AND $nottax $group";
397
398 # Here we're going to sum all line items that are taxable _at all_,
399 # under any tax.  exempt_charged is the sum of all exemptions for a 
400 # particular billpkgnum + taxnum; we take the taxnum that has the 
401 # smallest sum of exemptions and subtract that from the charged amount.
402 $all_sql{taxable} = "$select_all
403   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(min_exempt, 0))
404   FROM cust_bill_pkg
405   JOIN (
406     SELECT invnum, pkgnum, MIN(exempt_charged) AS min_exempt
407     FROM ($pkg_tax) AS pkg_tax
408     JOIN cust_bill_pkg USING (invnum, pkgnum)
409     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
410     GROUP BY invnum, pkgnum
411   ) AS pkg_is_taxable 
412   USING (invnum, pkgnum)
413   $join_cust_pkg $where AND $nottax $group_all";
414
415 $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
416 $all_sql{taxable} =~ s/EXEMPT_WHERE//;
417
418 # there isn't one for 'sales', because we calculate sales by adding up 
419 # the taxable and exempt columns.
420
421 # TAX QUERIES (billed tax, credited tax)
422 # -----------
423
424 # sum of billed tax:
425 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
426 my $taxfrom = " FROM cust_bill_pkg 
427                 $join_cust 
428                 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
429                 LEFT JOIN cust_main_county USING ( taxnum )";
430
431 if ( $with_pkgclass ) {
432   # If we're not grouping by package class, this is unnecessary, and
433   # probably really expensive.
434   $taxfrom .= "
435                 LEFT JOIN cust_bill_pkg AS taxable
436                   ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
437                 LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
438                 LEFT JOIN part_pkg USING (pkgpart)";
439 }
440
441 my $istax = "cust_bill_pkg.pkgnum = 0";
442 my $named_tax =
443   "COALESCE(taxname,'Tax') = COALESCE(cust_bill_pkg.itemdesc,'Tax')";
444
445 $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
446              $taxfrom
447              $where AND $istax AND $named_tax
448              $group";
449
450 $all_sql{tax} = "$select_all SUM(cust_bill_pkg.setup)
451              FROM cust_bill_pkg
452              $join_cust
453              $where AND $istax
454              $group_all";
455
456 # sum of credits applied against billed tax
457 # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
458 # is on)
459 my $creditfrom = $taxfrom .
460    ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)';
461 my $creditwhere = $where . 
462    ' AND billpkgtaxratelocationnum IS NULL';
463
464 $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
465                 $creditfrom
466                 $creditwhere AND $istax AND $named_tax
467                 $group";
468
469 $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
470                 FROM cust_credit_bill_pkg
471                 JOIN cust_bill_pkg USING (billpkgnum)
472                 $join_cust
473                 $where AND $istax
474                 $group_all";
475
476 if ( $with_pkgclass ) {
477   # the slightly more complicated version, with lots of joins that are 
478   # unnecessary if you're not breaking down by package class
479   $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
480              $taxfrom
481              $where AND $istax
482              $group_all";
483
484   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
485                       $creditfrom
486                       $creditwhere AND $istax
487                       $group_all";
488 }
489
490 # "out of taxable region" sales
491 $all_sql{out_sales} = 
492   "$select_all SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
493   FROM (cust_bill_pkg $join_cust_pkg)
494   LEFT JOIN ($pkg_tax) AS pkg_tax USING (invnum, pkgnum)
495   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum)
496   $where AND $nottax
497   AND pkg_tax.taxnum IS NULL AND pkg_tax_exempt.taxnum IS NULL
498   $group_all"
499 ;
500
501 $all_sql{out_sales} =~ s/EXEMPT_WHERE//;
502
503 my %data;
504 my %total;
505 foreach my $k (keys(%sql)) {
506   my $stmt = $sql{$k};
507   warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
508   my $sth = dbh->prepare($stmt);
509   # three columns: classnum, taxnum, value
510   $sth->execute 
511     or die "failed to execute $k query: ".$sth->errstr;
512   while ( my $row = $sth->fetchrow_arrayref ) {
513     $data{$k}{$row->[0]}{$row->[1]} = $row->[2];
514   }
515 }
516 warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
517
518 foreach my $k (keys %all_sql) {
519   warn "\n".$all_sql{$k}."\n" if $DEBUG;
520   my $sth = dbh->prepare($all_sql{$k});
521   # two columns: classnum, value
522   $sth->execute 
523     or die "failed to execute $k totals query: ".$sth->errstr;
524   while ( my $row = $sth->fetchrow_arrayref ) {
525     $total{$k}{$row->[0]} = $row->[1];
526   }
527 }
528 warn "TOTALS:\n".Dumper(\%total);# if $DEBUG > 1;
529 # so $data{tax}, for example, is now a hash with one entry
530 # for each classnum, containing a hash with one entry for each
531 # taxnum, containing the tax billed on that taxnum.
532 # if with_pkgclass is off, then the classnum is always null.
533
534 # integrity checks
535 # unlinked tax collected
536 my $out_tax_sql =
537   "SELECT SUM(cust_bill_pkg.setup)
538   FROM (cust_bill_pkg $join_cust)
539   LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
540   $where AND $istax AND cust_bill_pkg_tax_location.billpkgnum IS NULL"
541 ;
542 my $unlinked_tax = FS::Record->scalar_sql($out_tax_sql);
543 # unlinked tax credited
544 my $out_credit_sql =
545   "SELECT SUM(cust_credit_bill_pkg.amount)
546   FROM cust_credit_bill_pkg
547   JOIN cust_bill_pkg USING (billpkgnum)
548   $join_cust
549   $where AND $istax AND cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL"
550 ;
551 my $unlinked_credit = FS::Record->scalar_sql($out_credit_sql);
552
553 # all sales
554 my $all_sales = FS::Record->scalar_sql(
555   "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
556   FROM cust_bill_pkg $join_cust $where AND $nottax"
557 );
558
559 #tax-report_groups filtering
560 my($group_op, $group_value) = ( '', '' );
561 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ ) {
562   ( $group_op, $group_value ) = ( $1, $2 );
563 }
564 my $group_test = sub { # to be applied to a tax label
565   my $label = shift;
566   return 1 unless $group_op; #in case we get called inadvertantly
567   if ( $label eq $out ) { #don't display "out of taxable region" in this case
568     0;
569   } elsif ( $group_op eq '=' ) {
570     $label =~ /^$group_value/;
571   } elsif ( $group_op eq '!=' ) {
572     $label !~ /^$group_value/;
573   } else {
574     die "guru meditation #00de: group_op $group_op\n";
575   }
576 };
577
578 my @pkgclasses;
579 if ($with_pkgclass) {
580   @pkgclasses = qsearch('pkg_class', {});
581   push @pkgclasses, FS::pkg_class->new({
582     classnum  => '0',
583     classname => 'Unclassified',
584   });
585 } else {
586   @pkgclasses = ( FS::pkg_class->new({
587     classnum  => '',
588     classname => '',
589   }) );
590 }
591 my %pkgclass_data;
592
593 foreach my $class (@pkgclasses) {
594   my $classnum = $class->classnum;
595   my $classname = $class->classname;
596
597   # if show_taxclasses is on, %base_regions will contain the same data
598   # as %regions, but with taxclasses merged together (and ignoring report_group
599   # filtering).
600   my (%regions, %base_regions);
601
602   my @loc_params = qw(country state county);
603   push @loc_params, 'city' if $cgi->param('show_cities');
604   push @loc_params, 'district' if $cgi->param('show_districts');
605
606   foreach my $r ( qsearch({ 'table'     => 'cust_main_county', })) {
607     my $taxnum = $r->taxnum;
608     # set up a %regions entry for this region's tax label
609     my $label = $r->label(%label_opt);
610     next if $label eq $out;
611     $regions{$label} ||= { label => $label };
612
613     $regions{$label}->{$_} = $r->get($_) foreach @loc_params;
614     $regions{$label}->{taxnums} ||= [];
615     push @{ $regions{$label}->{taxnums} }, $r->taxnum;
616
617     my %x; # keys are data items (like 'tax', 'exempt_cust', etc.)
618     foreach my $k (keys %data) {
619       next unless exists($data{$k}{$classnum}{$taxnum});
620       $x{$k} = $data{$k}{$classnum}{$taxnum};
621       $regions{$label}{$k} += $x{$k};
622       if ( $k eq 'taxable' or $k =~ /^exempt/ ) {
623         $regions{$label}->{'sales'} += $x{$k};
624       }
625     }
626
627     my $owed = $data{'taxable'}{$classnum}{$taxnum} * ($r->tax/100);
628     $regions{$label}->{'owed'} += $owed;
629     $total{'owed'}{$classnum} += $owed;
630
631     if ( defined($regions{$label}->{'rate'})
632          && $regions{$label}->{'rate'} != $r->tax.'%' ) {
633       $regions{$label}->{'rate'} = 'variable';
634     } else {
635       $regions{$label}->{'rate'} = $r->tax.'%';
636     }
637
638     if ( $cgi->param('show_taxclasses') ) {
639       my $base_label = $r->label(%label_opt, 'with_taxclass' => 0);
640       $base_regions{$base_label} ||=
641       {
642         label   => $base_label,
643         tax     => 0,
644         credit  => 0,
645       };
646       $base_regions{$base_label}->{tax}    += $x{tax};
647       $base_regions{$base_label}->{credit} += $x{credit};
648     }
649
650   }
651
652   my @regions = map { $_->{label} }
653     sort {
654       ($b eq $out) <=> ($a eq $out)
655       or $a->{country} cmp $b->{country}
656       or $a->{state}   cmp $b->{state}
657       or $a->{county}  cmp $b->{county}
658       or $a->{city}    cmp $b->{city}
659     } 
660     grep { $_->{sales} > 0 or $_->{tax} > 0 or $_->{credit} > 0 }
661     values %regions;
662
663   #tax-report_groups filtering
664   @regions = grep &{$group_test}($_), @regions
665     if $group_op;
666
667   #calculate totals
668   my %taxclasses = ();
669   my %county = ();
670   my %state = ();
671   my %country = ();
672   foreach my $label (@regions) {
673     $taxclasses{$regions{$_}->{'taxclass'}} = 1
674       if $regions{$_}->{'taxclass'};
675     $county{$regions{$_}->{'county'}} = 1;
676     $state{$regions{$_}->{'state'}} = 1;
677     $country{$regions{$_}->{'country'}} = 1;
678   }
679
680   my $total_url_param = '';
681   my $total_url_param_invoiced = '';
682   if ( $group_op ) {
683
684     my @country = keys %country;
685     warn "WARNING: multiple countries on this grouped report; total links broken"
686       if scalar(@country) > 1;
687     my $country = $country[0];
688
689     my @state = keys %state;
690     warn "WARNING: multiple countries on this grouped report; total links broken"
691       if scalar(@state) > 1;
692     my $state = $state[0];
693
694     $total_url_param_invoiced =
695     $total_url_param =
696       'report_group='.uri_escape("$group_op $group_value").';'.
697       join(';', map 'taxclass='.uri_escape($_), keys %taxclasses );
698     $total_url_param .= ';'.
699       "country=$country;state=".uri_escape($state).';'.
700       join(';', map 'county='.uri_escape($_), keys %county ) ;
701
702   }
703
704   #ordering
705   @regions =
706     map $regions{$_},
707     sort { $a cmp $b }
708     @regions;
709
710   my @base_regions =
711     map $base_regions{$_},
712     sort { $a cmp $b }
713     keys %base_regions;
714
715   #add "Out of taxable" and total lines
716   if ( $total{out_sales}{$classnum} ) {
717     my %out = (
718       'sales' => $total{out_sales}{$classnum},
719       'label' => $out,
720       'rate' => ''
721     );
722     push @regions, \%out;
723     push @base_regions, \%out;
724   }
725
726   if ( @regions ) {
727     my %class_total = map { $_ => $total{$_}{$classnum} } keys(%total);
728     $class_total{is_total} = 1;
729     $class_total{sales} = sum(
730       @class_total{ 'taxable',
731                     'out_sales',
732                     grep(/^exempt/, keys %class_total) }
733     );
734
735     push @regions,      \%class_total;
736     push @base_regions, \%class_total;
737   }
738
739   $pkgclass_data{$classname} = {
740     classnum      => $classnum,
741     classname     => $classname,
742     regions       => \@regions,
743     base_regions  => \@base_regions,
744   };
745 }
746
747 if ( $with_pkgclass ) {
748   my $class_zero = delete( $pkgclass_data{'Unclassified'} );
749   @pkgclasses = map { $pkgclass_data{$_} }
750                 sort { $a cmp $b }
751                 keys %pkgclass_data;
752   push @pkgclasses, $class_zero;
753
754   my %grand_total = map {
755     $_ => sum( values(%{ $total{$_} }) )
756   } keys(%total);
757
758   $grand_total{sales} = $all_sales;
759
760   push @pkgclasses, {
761     classnum      => '',
762     classname     => 'Total',
763     regions       => [ \%grand_total ],
764     base_regions  => [ \%grand_total ],
765   }
766 } else {
767   @pkgclasses = $pkgclass_data{''};
768 }
769
770 #-- 
771
772 my $money_char = $conf->config('money_char') || '$';
773 my $money_sprintf = sub {
774   $money_char. sprintf('%.2f', shift );
775 };
776 my $money_sprintf_nonzero = sub {
777   $_[0] == 0 ? '' : &$money_sprintf($_[0])
778 };
779
780 my $dateagentlink = "begin=$beginning;end=$ending";
781 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
782   if length($agentname);
783 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
784 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
785 my $creditlink = $p. "search/cust_bill_pkg.cgi?$dateagentlink;credit=1";
786
787 </%init>