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