9926133be847dcb9c154b0e7da70b56bd595e006
[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 
312 # cust_main_county. This one links a taxed line item (billpkgnum) to a tax rate
313 # (taxnum), and gives the amount of tax charged on that line item under that
314 # rate (as tax_amount).
315 my $pkg_tax = "SELECT SUM(amount) as tax_amount, taxnum, ".
316   "taxable_billpkgnum AS billpkgnum ".
317   "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
318   "GROUP BY taxable_billpkgnum, taxnum";
319
320 # This one links a tax-exempted line item (billpkgnum) to a tax rate (taxnum),
321 # and gives the amount of the tax exemption.  EXEMPT_WHERE should be replaced 
322 # with a real WHERE clause to further limit the tax exemptions that will be
323 # included.
324 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
325   "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
326
327 my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ";
328 # SELECT/GROUP clauses for first-level queries
329 # classnum is a placeholder; they all go in one class in this case.
330 my $select = "SELECT NULL AS classnum, cust_main_county.taxnum, ";
331 my $group =  "GROUP BY cust_main_county.taxnum";
332 # SELECT/GROUP clauses for second-level (totals) queries
333 my $select_all = "SELECT NULL AS classnum, ";
334 my $group_all =  "";
335
336 if ( $with_pkgclass ) {
337   $select = "SELECT COALESCE(part_pkg.classnum,0), cust_main_county.taxnum, ";
338   $group =  "GROUP BY part_pkg.classnum, cust_main_county.taxnum";
339   $select_all = "SELECT COALESCE(part_pkg.classnum,0), ";
340   $group_all  = "GROUP BY COALESCE(part_pkg.classnum,0)";
341 }
342
343 my $agentname = '';
344 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
345   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
346   die "agent not found" unless $agent;
347   $agentname = $agent->agent;
348   $where .= ' AND cust_main.agentnum = '. $agent->agentnum;
349 }
350
351 my $nottax = 
352   '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
353
354 # one query for each column of the report
355 # plus separate queries for the totals row
356 my (%sql, %all_sql);
357
358 # SALES QUERIES (taxable sales, all types of exempt sales)
359 # -------------
360
361 # general form
362 my $exempt = "$select SUM(exempt_charged)
363   FROM cust_main_county
364   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
365   USING (taxnum)
366   JOIN cust_bill_pkg USING (billpkgnum)
367   $join_cust_pkg $where AND $nottax $group";
368
369 my $all_exempt = "$select_all SUM(exempt_charged)
370   FROM cust_main_county
371   JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
372   USING (taxnum)
373   JOIN cust_bill_pkg USING (billpkgnum)
374   $join_cust_pkg $where AND $nottax
375   $group_all";
376
377 # sales to tax-exempt customers
378 $sql{exempt_cust} = $exempt;
379 $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
380 $all_sql{exempt_cust} = $all_exempt;
381 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
382
383 # sales of tax-exempt packages
384 $sql{exempt_pkg} = $exempt;
385 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
386 $all_sql{exempt_pkg} = $all_exempt;
387 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
388
389 # monthly per-customer exemptions
390 $sql{exempt_monthly} = $exempt;
391 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
392 $all_sql{exempt_monthly} = $all_exempt;
393 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
394
395 # taxable sales
396 $sql{taxable} = "$select
397   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
398   FROM cust_main_county
399   JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
400   JOIN cust_bill_pkg USING (billpkgnum)
401   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
402     ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
403         AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
404   $join_cust_pkg $where AND $nottax $group";
405
406 # Here we're going to sum all line items that are taxable _at all_,
407 # under any tax.  exempt_charged is the sum of all exemptions for a 
408 # particular billpkgnum + taxnum; we take the taxnum that has the 
409 # smallest sum of exemptions and subtract that from the charged amount.
410
411 # (This isn't an exact result, since line items can be taxable under 
412 # one tax and not another.  Under 4.x the tax report is designed to 
413 # consider only one variety of tax at a time, which should solve this.)
414
415 $all_sql{taxable} = "$select_all
416   SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(min_exempt, 0))
417   FROM cust_bill_pkg
418   JOIN (
419     SELECT billpkgnum, MIN(exempt_charged) AS min_exempt
420     FROM ($pkg_tax) AS pkg_tax
421     JOIN cust_bill_pkg USING (billpkgnum)
422     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
423     GROUP BY billpkgnum
424   ) AS pkg_is_taxable 
425   USING (billpkgnum)
426   $join_cust_pkg $where AND $nottax $group_all";
427
428 $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
429 $all_sql{taxable} =~ s/EXEMPT_WHERE//;
430
431 # there isn't one for 'sales', because we calculate sales by adding up 
432 # the taxable and exempt columns.
433
434 # TAX QUERIES (billed tax, credited tax)
435 # -----------
436
437 # sum of billed tax:
438 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
439 my $taxfrom = " FROM cust_bill_pkg 
440                 $join_cust 
441                 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
442                 LEFT JOIN cust_main_county USING ( taxnum )";
443
444 if ( $with_pkgclass ) {
445   # If we're not grouping by package class, this is unnecessary, and
446   # probably really expensive.
447   $taxfrom .= "
448                 LEFT JOIN cust_bill_pkg AS taxable
449                   ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
450                 LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
451                 LEFT JOIN part_pkg USING (pkgpart)";
452 }
453
454 my $istax = "cust_bill_pkg.pkgnum = 0";
455 my $named_tax =
456   "COALESCE(taxname,'Tax') = COALESCE(cust_bill_pkg.itemdesc,'Tax')";
457
458 $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
459              $taxfrom
460              $where AND $istax AND $named_tax
461              $group";
462
463 $all_sql{tax} = "$select_all SUM(cust_bill_pkg.setup)
464              FROM cust_bill_pkg
465              $join_cust
466              $where AND $istax
467              $group_all";
468
469 # sum of credits applied against billed tax
470 # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
471 # is on)
472 my $creditfrom = $taxfrom .
473   ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
474   ' JOIN cust_credit_bill     USING (creditbillnum)';
475 my $creditwhere = $where . 
476   ' AND billpkgtaxratelocationnum IS NULL';
477 my $creditwhere_all = $where;
478
479 # if the credit_date option is set to application date, change
480 # $creditwhere accordingly
481 if ( $cgi->param('credit_date') eq 'cust_credit_bill' ) {
482   $creditwhere     =~ s/cust_bill._date/cust_credit_bill._date/g;
483   $creditwhere_all =~ s/cust_bill._date/cust_credit_bill._date/g;
484 }
485
486 $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
487                 $creditfrom
488                 $creditwhere AND $istax AND $named_tax
489                 $group";
490
491 $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
492                 FROM cust_credit_bill_pkg
493                 JOIN cust_bill_pkg USING (billpkgnum)
494                 $join_cust
495                 JOIN cust_credit_bill USING (creditbillnum)
496                 $creditwhere_all AND $istax
497                 $group_all";
498 warn "\n\n$all_sql{credit}\n\n";
499 if ( $with_pkgclass ) {
500   # the slightly more complicated version, with lots of joins that are 
501   # unnecessary if you're not breaking down by package class
502   $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
503              $taxfrom
504              $where AND $istax
505              $group_all";
506
507   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
508                       $creditfrom
509                       $creditwhere_all AND $istax
510                       $group_all";
511 }
512
513 # "out of taxable region" sales
514 $all_sql{out_sales} = 
515   "$select_all SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
516   FROM (cust_bill_pkg $join_cust_pkg)
517   LEFT JOIN ($pkg_tax) AS pkg_tax USING (billpkgnum)
518   LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum)
519   $where AND $nottax
520   AND pkg_tax.taxnum IS NULL AND pkg_tax_exempt.taxnum IS NULL
521   $group_all"
522 ;
523
524 $all_sql{out_sales} =~ s/EXEMPT_WHERE//;
525
526 my %data;
527 my %total;
528 foreach my $k (keys(%sql)) {
529   my $stmt = $sql{$k};
530   warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
531   my $sth = dbh->prepare($stmt);
532   # three columns: classnum, taxnum, value
533   $sth->execute 
534     or die "failed to execute $k query: ".$sth->errstr;
535   while ( my $row = $sth->fetchrow_arrayref ) {
536     $data{$k}{$row->[0]}{$row->[1]} = $row->[2];
537   }
538 }
539 warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
540
541 foreach my $k (keys %all_sql) {
542   warn "\n".$all_sql{$k}."\n" if $DEBUG;
543   my $sth = dbh->prepare($all_sql{$k});
544   # two columns: classnum, value
545   $sth->execute 
546     or die "failed to execute $k totals query: ".$sth->errstr;
547   while ( my $row = $sth->fetchrow_arrayref ) {
548     $total{$k}{$row->[0]} = $row->[1];
549   }
550 }
551 warn "TOTALS:\n".Dumper(\%total);# if $DEBUG > 1;
552 # so $data{tax}, for example, is now a hash with one entry
553 # for each classnum, containing a hash with one entry for each
554 # taxnum, containing the tax billed on that taxnum.
555 # if with_pkgclass is off, then the classnum is always null.
556
557 # integrity checks
558 # unlinked tax collected
559 my $out_tax_sql =
560   "SELECT SUM(cust_bill_pkg.setup)
561   FROM (cust_bill_pkg $join_cust)
562   LEFT JOIN cust_bill_pkg_tax_location USING (billpkgnum)
563   $where AND $istax AND cust_bill_pkg_tax_location.billpkgnum IS NULL"
564 ;
565 my $unlinked_tax = FS::Record->scalar_sql($out_tax_sql);
566 # unlinked tax credited
567 my $out_credit_sql =
568   "SELECT SUM(cust_credit_bill_pkg.amount)
569   FROM cust_credit_bill_pkg
570   JOIN cust_bill_pkg USING (billpkgnum)
571   $join_cust
572   $where AND $istax AND cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL"
573 ;
574 my $unlinked_credit = FS::Record->scalar_sql($out_credit_sql);
575
576 # all sales
577 my $all_sales = FS::Record->scalar_sql(
578   "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
579   FROM cust_bill_pkg $join_cust $where AND $nottax"
580 );
581
582 #tax-report_groups filtering
583 my($group_op, $group_value) = ( '', '' );
584 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ ) {
585   ( $group_op, $group_value ) = ( $1, $2 );
586 }
587 my $group_test = sub { # to be applied to a tax label
588   my $label = shift;
589   return 1 unless $group_op; #in case we get called inadvertantly
590   if ( $label eq $out ) { #don't display "out of taxable region" in this case
591     0;
592   } elsif ( $group_op eq '=' ) {
593     $label =~ /^$group_value/;
594   } elsif ( $group_op eq '!=' ) {
595     $label !~ /^$group_value/;
596   } else {
597     die "guru meditation #00de: group_op $group_op\n";
598   }
599 };
600
601 my @pkgclasses;
602 if ($with_pkgclass) {
603   @pkgclasses = qsearch('pkg_class', {});
604   push @pkgclasses, FS::pkg_class->new({
605     classnum  => '0',
606     classname => 'Unclassified',
607   });
608 } else {
609   @pkgclasses = ( FS::pkg_class->new({
610     classnum  => '',
611     classname => '',
612   }) );
613 }
614 my %pkgclass_data;
615
616 foreach my $class (@pkgclasses) {
617   my $classnum = $class->classnum;
618   my $classname = $class->classname;
619
620   # if show_taxclasses is on, %base_regions will contain the same data
621   # as %regions, but with taxclasses merged together (and ignoring report_group
622   # filtering).
623   my (%regions, %base_regions);
624
625   my @loc_params = qw(country state county);
626   push @loc_params, 'city' if $cgi->param('show_cities');
627   push @loc_params, 'district' if $cgi->param('show_districts');
628
629   foreach my $r ( qsearch({ 'table'     => 'cust_main_county', })) {
630     my $taxnum = $r->taxnum;
631     # set up a %regions entry for this region's tax label
632     my $label = $r->label(%label_opt);
633     next if $label eq $out;
634     $regions{$label} ||= { label => $label };
635
636     $regions{$label}->{$_} = $r->get($_) foreach @loc_params;
637     $regions{$label}->{taxnums} ||= [];
638     push @{ $regions{$label}->{taxnums} }, $r->taxnum;
639
640     my %x; # keys are data items (like 'tax', 'exempt_cust', etc.)
641     foreach my $k (keys %data) {
642       next unless exists($data{$k}{$classnum}{$taxnum});
643       $x{$k} = $data{$k}{$classnum}{$taxnum};
644       $regions{$label}{$k} += $x{$k};
645       if ( $k eq 'taxable' or $k =~ /^exempt/ ) {
646         $regions{$label}->{'sales'} += $x{$k};
647       }
648     }
649
650     my $owed = $data{'taxable'}{$classnum}{$taxnum} * ($r->tax/100);
651     $regions{$label}->{'owed'} += $owed;
652     $total{'owed'}{$classnum} += $owed;
653
654     if ( defined($regions{$label}->{'rate'})
655          && $regions{$label}->{'rate'} != $r->tax.'%' ) {
656       $regions{$label}->{'rate'} = 'variable';
657     } else {
658       $regions{$label}->{'rate'} = $r->tax.'%';
659     }
660
661     if ( $cgi->param('show_taxclasses') ) {
662       my $base_label = $r->label(%label_opt, 'with_taxclass' => 0);
663       $base_regions{$base_label} ||=
664       {
665         label   => $base_label,
666         tax     => 0,
667         credit  => 0,
668       };
669       $base_regions{$base_label}->{tax}    += $x{tax};
670       $base_regions{$base_label}->{credit} += $x{credit};
671     }
672
673   }
674
675   my @regions = map { $_->{label} }
676     sort {
677       ($b eq $out) <=> ($a eq $out)
678       or $a->{country} cmp $b->{country}
679       or $a->{state}   cmp $b->{state}
680       or $a->{county}  cmp $b->{county}
681       or $a->{city}    cmp $b->{city}
682     } 
683     grep { $_->{sales} > 0 or $_->{tax} > 0 or $_->{credit} > 0 }
684     values %regions;
685
686   #tax-report_groups filtering
687   @regions = grep &{$group_test}($_), @regions
688     if $group_op;
689
690   #calculate totals
691   my %taxclasses = ();
692   my %county = ();
693   my %state = ();
694   my %country = ();
695   foreach my $label (@regions) {
696     $taxclasses{$regions{$_}->{'taxclass'}} = 1
697       if $regions{$_}->{'taxclass'};
698     $county{$regions{$_}->{'county'}} = 1;
699     $state{$regions{$_}->{'state'}} = 1;
700     $country{$regions{$_}->{'country'}} = 1;
701   }
702
703   my $total_url_param = '';
704   my $total_url_param_invoiced = '';
705   if ( $group_op ) {
706
707     my @country = keys %country;
708     warn "WARNING: multiple countries on this grouped report; total links broken"
709       if scalar(@country) > 1;
710     my $country = $country[0];
711
712     my @state = keys %state;
713     warn "WARNING: multiple countries on this grouped report; total links broken"
714       if scalar(@state) > 1;
715     my $state = $state[0];
716
717     $total_url_param_invoiced =
718     $total_url_param =
719       'report_group='.uri_escape("$group_op $group_value").';'.
720       join(';', map 'taxclass='.uri_escape($_), keys %taxclasses );
721     $total_url_param .= ';'.
722       "country=$country;state=".uri_escape($state).';'.
723       join(';', map 'county='.uri_escape($_), keys %county ) ;
724
725   }
726
727   #ordering
728   @regions =
729     map $regions{$_},
730     sort { $a cmp $b }
731     @regions;
732
733   my @base_regions =
734     map $base_regions{$_},
735     sort { $a cmp $b }
736     keys %base_regions;
737
738   #add "Out of taxable" and total lines
739   if ( $total{out_sales}{$classnum} ) {
740     my %out = (
741       'sales' => $total{out_sales}{$classnum},
742       'label' => $out,
743       'rate' => ''
744     );
745     push @regions, \%out;
746     push @base_regions, \%out;
747   }
748
749   if ( @regions ) {
750     my %class_total = map { $_ => $total{$_}{$classnum} } keys(%total);
751     $class_total{is_total} = 1;
752     $class_total{sales} = sum(
753       @class_total{ 'taxable',
754                     'out_sales',
755                     grep(/^exempt/, keys %class_total) }
756     );
757
758     push @regions,      \%class_total;
759     push @base_regions, \%class_total;
760   }
761
762   $pkgclass_data{$classname} = {
763     classnum      => $classnum,
764     classname     => $classname,
765     regions       => \@regions,
766     base_regions  => \@base_regions,
767   };
768 }
769
770 if ( $with_pkgclass ) {
771   my $class_zero = delete( $pkgclass_data{'Unclassified'} );
772   @pkgclasses = map { $pkgclass_data{$_} }
773                 sort { $a cmp $b }
774                 keys %pkgclass_data;
775   push @pkgclasses, $class_zero;
776
777   my %grand_total = map {
778     $_ => sum( values(%{ $total{$_} }) )
779   } keys(%total);
780
781   $grand_total{sales} = $all_sales;
782
783   push @pkgclasses, {
784     classnum      => '',
785     classname     => 'Total',
786     regions       => [ \%grand_total ],
787     base_regions  => [ \%grand_total ],
788   }
789 } else {
790   @pkgclasses = $pkgclass_data{''};
791 }
792
793 #-- 
794
795 my $money_char = $conf->config('money_char') || '$';
796 my $money_sprintf = sub {
797   $money_char. sprintf('%.2f', shift );
798 };
799 my $money_sprintf_nonzero = sub {
800   $_[0] == 0 ? '' : &$money_sprintf($_[0])
801 };
802
803 my $dateagentlink = "begin=$beginning;end=$ending";
804 $dateagentlink .= ';agentnum='. $cgi->param('agentnum')
805   if length($agentname);
806 my $baselink   = $p. "search/cust_bill_pkg.cgi?$dateagentlink";
807 my $exemptlink = $p. "search/cust_tax_exempt_pkg.cgi?$dateagentlink";
808
809 my $creditlink = $baselink . ";credit=1";
810 if ( $cgi->param('credit_date') eq 'cust_credit_bill' ) {
811   $creditlink =~ s/begin/credit_begin/;
812   $creditlink =~ s/end/credit_end/;
813 }
814 warn $creditlink;
815
816
817 </%init>