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