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