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