RT#29296: API stuff: Add new locations
[freeside.git] / FS / FS / Report / Tax.pm
1 package FS::Report::Tax;
2
3 use strict;
4 use vars qw($DEBUG);
5 use FS::Record qw(dbh qsearch qsearchs group_concat_sql);
6 use Date::Format qw( time2str );
7
8 use Data::Dumper;
9
10 $DEBUG = 0;
11
12 =item report_internal OPTIONS
13
14 Constructor.  Generates a tax report using the internal tax rate system 
15 (L<FS::cust_main_county>).
16
17 Required parameters:
18
19 - beginning, ending: the date range as Unix timestamps.
20 - taxname: the name of the tax (corresponds to C<cust_bill_pkg.itemdesc>).
21 - country: the country code.
22
23 Optional parameters:
24 - agentnum: limit to this agentnum.num.
25 - breakdown: hashref of the fields to group by.  Keys can be 'city', 'district',
26   'pkgclass', or 'taxclass'; values should be true.
27 - debug: sets the debug level.  1 will warn the data collected for the report;
28   2 will also warn all of the SQL statements.
29
30 =cut
31
32 sub report_internal {
33   my $class = shift;
34   my %opt = @_;
35
36   $DEBUG ||= $opt{debug};
37
38   my $conf = new FS::Conf;
39
40   my($beginning, $ending) = @opt{'beginning', 'ending'};
41
42   my ($taxname, $country, %breakdown);
43
44   # taxname can contain arbitrary punctuation; escape it properly and 
45   # include $taxname unquoted elsewhere
46   $taxname = dbh->quote($opt{'taxname'});
47
48   if ( $opt{country} =~ /^(\w\w)$/ ) {
49     $country = $1;
50   } else {
51     die "country required";
52   }
53
54   # %breakdown: short name => field identifier
55   # null classnum should remain null, not be converted to zero
56   %breakdown = (
57     'taxclass'  => 'cust_main_county.taxclass',
58     'pkgclass'  => 'COALESCE(part_fee.classnum,part_pkg.classnum)',
59     'city'      => 'cust_main_county.city',
60     'district'  => 'cust_main_county.district',
61     'state'     => 'cust_main_county.state',
62     'county'    => 'cust_main_county.county',
63   );
64   foreach (qw(taxclass pkgclass city district)) {
65     delete $breakdown{$_} unless $opt{breakdown}->{$_};
66   }
67
68   my $join_cust =     '      JOIN cust_bill     USING ( invnum  )
69                         LEFT JOIN cust_main     USING ( custnum ) ';
70
71   my $join_cust_pkg = $join_cust.
72                       ' LEFT JOIN cust_pkg      USING ( pkgnum  )
73                         LEFT JOIN part_pkg      USING ( pkgpart )
74                         LEFT JOIN part_fee      USING ( feepart ) ';
75
76   my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg "; 
77
78   # all queries MUST be linked to both cust_bill and cust_main_county
79
80   # Either or both of these can be used to link cust_bill_pkg to 
81   # cust_main_county. This one links a taxed line item (billpkgnum) to a tax rate
82   # (taxnum), and gives the amount of tax charged on that line item under that
83   # rate (as tax_amount).
84   my $pkg_tax = "SELECT SUM(amount) as tax_amount, taxnum, ".
85     "taxable_billpkgnum AS billpkgnum ".
86     "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
87     "GROUP BY taxable_billpkgnum, taxnum";
88
89   # This one links a tax-exempted line item (billpkgnum) to a tax rate
90   # (taxnum), and gives the amount of the tax exemption.  EXEMPT_WHERE must 
91   # be replaced with an expression to further limit the tax exemptions
92   # that will be included, or "TRUE" to not limit them.
93   #
94   # Note that tax exemptions with non-null creditbillpkgnum are always
95   # excluded. Those are "negative exemptions" created by crediting a sale 
96   # that had received an exemption.
97   my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
98     "FROM cust_tax_exempt_pkg WHERE
99       ( EXEMPT_WHERE )
100       AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
101      GROUP BY billpkgnum, taxnum";
102
103   my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ".
104               "AND COALESCE(cust_main_county.taxname,'Tax') = $taxname ".
105               "AND cust_main_county.country = '$country'";
106   # SELECT/GROUP clauses for first-level queries
107   my $select = "SELECT ";
108   my $group = "GROUP BY ";
109   foreach (qw(pkgclass taxclass state county city district)) {
110     if ( $breakdown{$_} ) {
111       $select .= "$breakdown{$_} AS $_, ";
112       $group  .= "$breakdown{$_}, ";
113     } else {
114       $select .= "NULL AS $_, ";
115     }
116   }
117   $select .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
118              ' AS taxnums, ';
119   $group =~ s/, $//;
120
121   # SELECT/GROUP clauses for second-level (totals) queries
122   # breakdown by package class only, if anything
123   my $select_all = "SELECT NULL AS pkgclass, ";
124   my $group_all = "";
125   if ( $breakdown{pkgclass} ) {
126     $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
127     $group_all = "GROUP BY $breakdown{pkgclass}";
128   }
129   $select_all .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
130                  ' AS taxnums, ';
131
132   my $agentnum;
133   if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
134     $agentnum = $1;
135     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
136     die "agent not found" unless $agent;
137     $where .= " AND cust_main.agentnum = $agentnum";
138   }
139
140   my $nottax = 
141     '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
142
143   # one query for each column of the report
144   # plus separate queries for the totals row
145   my (%sql, %all_sql);
146
147   # SALES QUERIES (taxable sales, all types of exempt sales)
148   # -------------
149
150   # general form
151   my $exempt = "$select SUM(exempt_charged)
152     FROM cust_main_county
153     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
154     USING (taxnum)
155     JOIN cust_bill_pkg USING (billpkgnum)
156     $join_cust_pkg $where AND $nottax
157     $group";
158
159   my $all_exempt = "$select_all SUM(exempt_charged)
160     FROM cust_main_county
161     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
162     USING (taxnum)
163     JOIN cust_bill_pkg USING (billpkgnum)
164     $join_cust_pkg $where AND $nottax
165     $group_all";
166
167   # sales to tax-exempt customers
168   $sql{exempt_cust} = $exempt;
169   $sql{exempt_cust} =~ s/EXEMPT_WHERE/exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
170   $all_sql{exempt_cust} = $all_exempt;
171   $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
172
173   # sales of tax-exempt packages
174   $sql{exempt_pkg} = $exempt;
175   $sql{exempt_pkg} =~ s/EXEMPT_WHERE/exempt_setup = 'Y' OR exempt_recur = 'Y'/;
176   $all_sql{exempt_pkg} = $all_exempt;
177   $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/exempt_setup = 'Y' OR exempt_recur = 'Y'/;
178
179   # monthly per-customer exemptions
180   $sql{exempt_monthly} = $exempt;
181   $sql{exempt_monthly} =~ s/EXEMPT_WHERE/exempt_monthly = 'Y'/;
182   $all_sql{exempt_monthly} = $all_exempt;
183   $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/exempt_monthly = 'Y'/;
184
185   # credits applied to taxable sales
186   # Note that negative exemptions (from exempt sales being credited) are NOT
187   # counted when calculating the exempt amount. (See above.) Therefore we need
188   # to NOT include any credits against exempt sales in this amount, either.
189   # These two subqueries implement that. They have joins to cust_credit_bill
190   # and cust_bill so that credits can be filtered by application date if
191   # requested.
192
193   # Each row here is the sum of credits applied to a line item.
194   my $sales_credit =
195     "SELECT billpkgnum, SUM(cust_credit_bill_pkg.amount) AS credited
196     FROM cust_credit_bill_pkg
197     JOIN cust_credit_bill USING (creditbillnum)
198     JOIN cust_bill USING (invnum)
199     WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending
200     GROUP BY billpkgnum
201     ";
202
203   # Each row here is the sum of negative exemptions applied to a combination
204   # of line item and tax definition.
205   my $exempt_credit =
206     "SELECT cust_credit_bill_pkg.billpkgnum, taxnum,
207       0 - SUM(cust_tax_exempt_pkg.amount) AS exempt_credited
208     FROM cust_credit_bill_pkg
209     LEFT JOIN cust_tax_exempt_pkg USING (creditbillpkgnum)
210     JOIN cust_credit_bill USING (creditbillnum)
211     JOIN cust_bill USING (invnum)
212     WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending
213     GROUP BY cust_credit_bill_pkg.billpkgnum, taxnum
214     ";
215   
216   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
217     $sales_credit =~ s/cust_bill._date/cust_credit_bill._date/g;
218     $exempt_credit =~ s/cust_bill._date/cust_credit_bill._date/g;
219   }
220
221   $sql{sales_credited} = "$select
222     SUM(COALESCE(credited, 0) - COALESCE(exempt_credited, 0))
223     FROM cust_main_county
224     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
225     JOIN cust_bill_pkg USING (billpkgnum)
226     LEFT JOIN ($sales_credit) AS sales_credit USING (billpkgnum)
227     LEFT JOIN ($exempt_credit) AS exempt_credit USING (billpkgnum, taxnum)
228     $join_cust_pkg $where AND $nottax
229     $group
230     ";
231
232   $all_sql{sales_credited} = "$select_all
233     SUM(COALESCE(credited, 0) - COALESCE(exempt_credited, 0))
234     FROM cust_main_county
235     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
236     JOIN cust_bill_pkg USING (billpkgnum)
237     LEFT JOIN ($sales_credit) AS sales_credit USING (billpkgnum)
238     LEFT JOIN ($exempt_credit) AS exempt_credit USING (billpkgnum, taxnum)
239     $join_cust_pkg $where AND $nottax
240     $group_all
241     ";
242
243   # also include the exempt-sales credit amount, for the credit report
244   $sql{exempt_credited} = "$select
245     SUM(COALESCE(exempt_credited, 0))
246     FROM cust_main_county
247     LEFT JOIN ($exempt_credit) AS exempt_credit USING (taxnum)
248     JOIN cust_bill_pkg USING (billpkgnum)
249     $join_cust_pkg $where AND $nottax
250     $group
251     ";
252
253   $all_sql{exempt_credited} = "$select_all
254     SUM(COALESCE(exempt_credited, 0))
255     FROM cust_main_county
256     LEFT JOIN ($exempt_credit) AS exempt_credit USING (taxnum)
257     JOIN cust_bill_pkg USING (billpkgnum)
258     $join_cust_pkg $where AND $nottax
259     $group_all
260     ";
261
262   # taxable sales
263   $sql{taxable} = "$select
264     SUM(cust_bill_pkg.setup + cust_bill_pkg.recur
265       - COALESCE(exempt_charged, 0)
266       - COALESCE(credited, 0)
267       + COALESCE(exempt_credited, 0)
268     )
269     FROM cust_main_county
270     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
271     JOIN cust_bill_pkg USING (billpkgnum)
272     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
273     LEFT JOIN ($sales_credit) AS sales_credit USING (billpkgnum)
274     LEFT JOIN ($exempt_credit) AS exempt_credit USING (billpkgnum, taxnum)
275     $join_cust_pkg $where AND $nottax 
276     $group";
277
278   $all_sql{taxable} = "$select_all
279     SUM(cust_bill_pkg.setup + cust_bill_pkg.recur
280       - COALESCE(exempt_charged, 0)
281       - COALESCE(credited, 0)
282       + COALESCE(exempt_credited, 0)
283     )
284     FROM cust_main_county
285     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
286     JOIN cust_bill_pkg USING (billpkgnum)
287     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
288     LEFT JOIN ($sales_credit) AS sales_credit USING (billpkgnum)
289     LEFT JOIN ($exempt_credit) AS exempt_credit USING (billpkgnum, taxnum)
290     $join_cust_pkg $where AND $nottax 
291     $group_all";
292
293   $sql{taxable} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
294   $all_sql{taxable} =~ s/EXEMPT_WHERE/TRUE/;
295
296   # estimated tax (taxable * rate)
297   $sql{estimated} = "$select
298     SUM(cust_main_county.tax / 100 * 
299       (cust_bill_pkg.setup + cust_bill_pkg.recur
300       - COALESCE(exempt_charged, 0)
301       - COALESCE(credited, 0)
302       + COALESCE(exempt_credited, 0)
303       )
304     )
305     FROM cust_main_county
306     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
307     JOIN cust_bill_pkg USING (billpkgnum)
308     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
309     LEFT JOIN ($sales_credit) AS sales_credit USING (billpkgnum)
310     LEFT JOIN ($exempt_credit) AS exempt_credit USING (billpkgnum, taxnum)
311     $join_cust_pkg $where AND $nottax 
312     $group";
313
314   $all_sql{estimated} = "$select_all
315     SUM(cust_main_county.tax / 100 * 
316       (cust_bill_pkg.setup + cust_bill_pkg.recur
317       - COALESCE(exempt_charged, 0)
318       - COALESCE(credited, 0)
319       + COALESCE(exempt_credited, 0)
320       )
321     )
322     FROM cust_main_county
323     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
324     JOIN cust_bill_pkg USING (billpkgnum)
325     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt USING (billpkgnum, taxnum)
326     LEFT JOIN ($sales_credit) AS sales_credit USING (billpkgnum)
327     LEFT JOIN ($exempt_credit) AS exempt_credit USING (billpkgnum, taxnum)
328     $join_cust_pkg $where AND $nottax 
329     $group_all";
330
331   $sql{estimated} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
332   $all_sql{estimated} =~ s/EXEMPT_WHERE/TRUE/;
333
334   # there isn't one for 'sales', because we calculate sales by adding up 
335   # the taxable and exempt columns.
336   
337   # TAX QUERIES (billed tax, credited tax, collected tax)
338   # -----------
339
340   # sum of billed tax:
341   # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
342   my $taxfrom = " FROM cust_bill_pkg 
343                   $join_cust 
344                   LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
345                   LEFT JOIN cust_main_county USING ( taxnum )";
346
347   if ( $breakdown{pkgclass} ) {
348     # If we're not grouping by package class, this is unnecessary, and
349     # probably really expensive.
350     # Remember that fees also have package classes.
351     $taxfrom .= "
352                   LEFT JOIN cust_bill_pkg AS taxable
353                     ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
354                   LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
355                   LEFT JOIN part_pkg USING (pkgpart)
356                   LEFT JOIN part_fee ON (taxable.feepart = part_fee.feepart) ";
357   }
358
359   my $istax = "cust_bill_pkg.pkgnum = 0 and cust_bill_pkg.feepart is null";
360
361   $sql{tax} = "$select COALESCE(SUM(cust_bill_pkg_tax_location.amount),0)
362                $taxfrom
363                $where AND $istax
364                $group";
365
366   $all_sql{tax} = "$select_all COALESCE(SUM(cust_bill_pkg_tax_location.amount),0)
367                $taxfrom
368                $where AND $istax
369                $group_all";
370
371   # sum of credits applied against billed tax
372   # ($creditfrom includes join of taxable item to part_pkg/part_fee if 
373   # with_pkgclass is on)
374   my $creditfrom = $taxfrom .
375     ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
376     ' JOIN cust_credit_bill     USING (creditbillnum)';
377   my $creditwhere = $where . 
378     ' AND billpkgtaxratelocationnum IS NULL';
379
380   # if the credit_date option is set to application date, change
381   # $creditwhere accordingly
382   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
383     $creditwhere     =~ s/cust_bill._date/cust_credit_bill._date/g;
384   }
385
386   $sql{tax_credited} = "$select COALESCE(SUM(cust_credit_bill_pkg.amount),0)
387                   $creditfrom
388                   $creditwhere AND $istax
389                   $group";
390
391   $all_sql{tax_credited} = "$select_all COALESCE(SUM(cust_credit_bill_pkg.amount),0)
392                   $creditfrom
393                   $creditwhere AND $istax
394                   $group_all";
395
396   # sum of tax paid
397   # this suffers from the same ambiguity as anything else that applies 
398   # received payments to specific packages, but in reality the discrepancy
399   # should be minimal since people either pay their bill or don't.
400   # the join is on billpkgtaxlocationnum to avoid cross-producting.
401  
402   my $paidfrom = $taxfrom .
403     ' JOIN cust_bill_pay_pkg'.
404     ' ON (cust_bill_pay_pkg.billpkgtaxlocationnum ='.
405     ' cust_bill_pkg_tax_location.billpkgtaxlocationnum)';
406
407   $sql{tax_paid} = "$select COALESCE(SUM(cust_bill_pay_pkg.amount),0)
408                     $paidfrom
409                     $where AND $istax
410                     $group";
411
412   $all_sql{tax_paid} = "$select_all COALESCE(SUM(cust_bill_pay_pkg.amount),0)
413                     $paidfrom
414                     $where AND $istax
415                     $group_all";
416
417   my %data;
418   my %total;
419   # note that we use keys(%sql) here and keys(%all_sql) later. nothing
420   # obligates us to use the same set of variables for the total query 
421   # as for the individual category queries
422   foreach my $k (keys(%sql)) {
423     my $stmt = $sql{$k};
424     warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG > 1;
425     my $sth = dbh->prepare($stmt);
426     # eight columns: pkgclass, taxclass, state, county, city, district
427     # taxnums (comma separated), value
428     $sth->execute 
429       or die "failed to execute $k query: ".$sth->errstr;
430     while ( my $row = $sth->fetchrow_arrayref ) {
431       my $bin = $data
432                 {$row->[0]} # pkgclass
433                 {$row->[1]  # taxclass
434                   || ($breakdown{taxclass} ? 'Unclassified' : '')}
435                 {$row->[2]} # state
436                 {$row->[3] ? $row->[3] . ' County' : ''} # county
437                 {$row->[4]} # city
438                 {$row->[5]} # district
439               ||= [];
440       push @$bin, [ $k, $row->[6], $row->[7] ];
441     }
442   }
443   warn "DATA:\n".Dumper(\%data) if $DEBUG;
444
445   foreach my $k (keys %all_sql) {
446     warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
447     my $sth = dbh->prepare($all_sql{$k});
448     # three columns: pkgclass, taxnums (comma separated), value
449     $sth->execute 
450       or die "failed to execute $k totals query: ".$sth->errstr;
451     while ( my $row = $sth->fetchrow_arrayref ) {
452       my $bin = $total{$row->[0]} ||= [];
453       push @$bin, [ $k, $row->[1], $row->[2] ];
454     }
455   }
456   warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
457
458   # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
459   #   [ 'taxable',     taxnums, amount ],
460   #   [ 'exempt_cust', taxnums, amount ],
461   #   ...
462   # ]
463   # non-requested grouping levels simply collapse into key = ''
464
465   # the much-maligned "out of taxable region"...
466   # find sales that are not linked to any tax with this name
467   # but are still inside the date range/agent criteria.
468   #
469   # This doesn't use $select_all/$group_all because we want a single number,
470   # not a breakdown by pkgclass. Unless someone needs that eventually, 
471   # in which case we'll turn it into an %all_sql query.
472   
473   my $outside_where =
474     "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending";
475   if ( $agentnum ) {
476     $outside_where .= " AND cust_main.agentnum = $agentnum";
477   }
478   $outside_where .= "
479     AND NOT EXISTS(
480       SELECT 1 FROM cust_tax_exempt_pkg
481         JOIN cust_main_county USING (taxnum)
482         WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
483           AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
484           AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
485     )
486     AND NOT EXISTS(
487       SELECT 1 FROM cust_bill_pkg_tax_location
488         JOIN cust_main_county USING (taxnum)
489         WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
490           AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
491     )";
492   my $sql_outside = "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
493     FROM cust_bill_pkg
494     $join_cust_pkg
495     $outside_where
496     AND $nottax
497   ";
498   warn "\nOUT_SALES:\n$sql_outside\n" if $DEBUG;
499   my $out_sales = FS::Record->scalar_sql($sql_outside);
500
501   # and out-of-region credit applications, also (excluding those applied
502   # to out-of-region sales _or taxes_)
503   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
504     $outside_where     =~ s/cust_bill._date/cust_credit_bill._date/g;
505   }
506
507   $sql_outside = "SELECT SUM(cust_credit_bill_pkg.amount)
508     FROM cust_credit_bill_pkg
509     JOIN cust_bill_pkg USING (billpkgnum)
510     $join_cust_pkg
511     JOIN cust_credit_bill USING (creditbillnum)
512     $outside_where
513     AND NOT EXISTS(
514       SELECT 1 FROM cust_bill_pkg_tax_location
515         JOIN cust_main_county USING (taxnum)
516         WHERE cust_bill_pkg_tax_location.billpkgnum = cust_bill_pkg.billpkgnum
517           AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
518     )
519   ";
520   warn "\nOUT_CREDIT:\n$sql_outside\n" if $DEBUG;
521   my $out_credit = FS::Record->scalar_sql($sql_outside);
522
523   my %taxrates;
524   foreach my $tax (
525     qsearch('cust_main_county', {
526               country => $country,
527               tax => { op => '>', value => 0 }
528             }) )
529     {
530     $taxrates{$tax->taxnum} = $tax->tax;
531   }
532
533   # return the data
534   bless {
535     'opt'         => \%opt,
536     'data'        => \%data,
537     'total'       => \%total,
538     'taxrates'    => \%taxrates,
539     'out_sales'   => $out_sales,
540     'out_credit'  => $out_credit,
541   }, $class;
542 }
543
544 sub opt {
545   my $self = shift;
546   $self->{opt};
547 }
548
549 sub data {
550   my $self = shift;
551   $self->{data};
552 }
553
554 # sub fetchall_array...
555
556 sub table {
557   my $self = shift;
558   my @columns = (qw(pkgclass taxclass state county city district));
559   # taxnums, field headings, and amounts
560   my @rows;
561   my %row_template;
562
563   # de-treeify this thing
564   my $descend;
565   $descend = sub {
566     my ($tree, $level) = @_;
567     if ( ref($tree) eq 'HASH' ) {
568       foreach my $k ( sort {
569            -1*($b eq '')    # sort '' to the end
570           or  ($a eq '')    # sort '' to the end
571           or  ($a <=> $b)   # sort numbers as numbers
572           or  ($a cmp $b)   # sort alphabetics as alphabetics
573         } keys %$tree )
574       {
575         $row_template{ $columns[$level] } = $k;
576         &{ $descend }($tree->{$k}, $level + 1);
577         if ( $level == 0 ) {
578           # then insert the total row for the pkgclass
579           $row_template{'total'} = 1; # flag it as a total
580           &{ $descend }($self->{total}->{$k}, 1);
581           $row_template{'total'} = 0;
582         }
583       }
584     } elsif ( ref($tree) eq 'ARRAY' ) {
585       # then we've reached the bottom; elements of this array are arrayrefs
586       # of [ field, taxnums, amount ].
587       # start with the inherited location-element fields
588       my %this_row = %row_template;
589       my %taxnums;
590       foreach my $x (@$tree) {
591         # accumulate taxnums
592         foreach (split(',', $x->[1])) {
593           $taxnums{$_} = 1;
594         }
595         # and money values
596         $this_row{ $x->[0] } = $x->[2];
597       }
598       # store combined taxnums
599       $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
600       # and calculate row totals
601       $this_row{sales} = sprintf('%.2f',
602                           $this_row{taxable} +
603                           $this_row{sales_credited} +
604                           $this_row{exempt_cust} +
605                           $this_row{exempt_pkg} + 
606                           $this_row{exempt_monthly}
607                         );
608       $this_row{credits} = sprintf('%.2f',
609                           $this_row{sales_credited} +
610                           $this_row{exempt_credited} +
611                           $this_row{tax_credited}
612                         );
613       # and give it a label
614       if ( $this_row{total} ) {
615         $this_row{label} = 'Total';
616       } else {
617         $this_row{label} = join(', ', grep $_,
618                             $this_row{taxclass},
619                             $this_row{state},
620                             $this_row{county}, # already has ' County' suffix
621                             $this_row{city},
622                             $this_row{district}
623                            );
624       }
625       # and indicate the tax rate, if any
626       my $rate;
627       foreach (keys %taxnums) {
628         $rate ||= $self->{taxrates}->{$_};
629         if ( $rate != $self->{taxrates}->{$_} ) {
630           $rate = 'variable';
631           last;
632         }
633       }
634       if ( $rate eq 'variable' ) {
635         $this_row{rate} = 'variable';
636       } elsif ( $rate > 0 ) {
637         $this_row{rate} = sprintf('%.2f', $rate);
638       }
639       push @rows, \%this_row;
640     }
641   };
642
643   &{ $descend }($self->{data}, 0);
644
645   warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
646   return @rows;
647 }
648
649 sub taxrates {
650   my $self = shift;
651   $self->{taxrates}
652 }
653
654 sub title {
655   my $self = shift;
656   my $string = '';
657   if ( $self->{opt}->{agentnum} ) {
658     my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
659     $string .= $agent->agent . ' ';
660   }
661   $string .= 'Tax Report: '; # XXX localization
662   if ( $self->{opt}->{beginning} ) {
663     $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
664   }
665   $string .= 'through ';
666   if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
667     $string .= time2str('%h %o %Y', $self->{opt}->{ending});
668   } else {
669     $string .= 'now';
670   }
671   $string .= ' - ' . $self->{opt}->{taxname};
672   return $string;
673 }
674
675 1;