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