0923d55cfb32091641118da7f0dc9f927dc5d9f7
[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   # taxable sales
186   $sql{taxable} = "$select
187     SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
188     FROM cust_main_county
189     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
190     JOIN cust_bill_pkg USING (billpkgnum)
191     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
192       ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
193           AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
194     $join_cust_pkg $where AND $nottax 
195     $group";
196
197   $all_sql{taxable} = "$select_all
198     SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
199     FROM cust_main_county
200     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
201     JOIN cust_bill_pkg USING (billpkgnum)
202     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
203       ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
204           AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
205     $join_cust_pkg $where AND $nottax 
206     $group_all";
207
208   $sql{taxable} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
209   $all_sql{taxable} =~ s/EXEMPT_WHERE/TRUE/;
210
211   # estimated tax (taxable * rate)
212   $sql{estimated} = "$select
213     SUM(cust_main_county.tax / 100 * 
214       (cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
215     )
216     FROM cust_main_county
217     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
218     JOIN cust_bill_pkg USING (billpkgnum)
219     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
220       ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
221           AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
222     $join_cust_pkg $where AND $nottax 
223     $group";
224
225   $all_sql{estimated} = "$select_all
226     SUM(cust_main_county.tax / 100 * 
227       (cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
228     )
229     FROM cust_main_county
230     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
231     JOIN cust_bill_pkg USING (billpkgnum)
232     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
233       ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
234           AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
235     $join_cust_pkg $where AND $nottax 
236     $group_all";
237
238   $sql{estimated} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
239   $all_sql{estimated} =~ s/EXEMPT_WHERE/TRUE/;
240
241   # there isn't one for 'sales', because we calculate sales by adding up 
242   # the taxable and exempt columns.
243   
244   # TAX QUERIES (billed tax, credited tax, collected tax)
245   # -----------
246
247   # sum of billed tax:
248   # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
249   my $taxfrom = " FROM cust_bill_pkg 
250                   $join_cust 
251                   LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
252                   LEFT JOIN cust_main_county USING ( taxnum )";
253
254   if ( $breakdown{pkgclass} ) {
255     # If we're not grouping by package class, this is unnecessary, and
256     # probably really expensive.
257     # Remember that fees also have package classes.
258     $taxfrom .= "
259                   LEFT JOIN cust_bill_pkg AS taxable
260                     ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
261                   LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
262                   LEFT JOIN part_pkg USING (pkgpart)
263                   LEFT JOIN part_fee ON (taxable.feepart = part_fee.feepart) ";
264   }
265
266   my $istax = "cust_bill_pkg.pkgnum = 0 and cust_bill_pkg.feepart is null";
267
268   $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
269                $taxfrom
270                $where AND $istax
271                $group";
272
273   $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
274                $taxfrom
275                $where AND $istax
276                $group_all";
277
278   # sum of credits applied against billed tax
279   # ($creditfrom includes join of taxable item to part_pkg/part_fee if 
280   # with_pkgclass is on)
281   my $creditfrom = $taxfrom .
282     ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
283     ' JOIN cust_credit_bill     USING (creditbillnum)';
284   my $creditwhere = $where . 
285     ' AND billpkgtaxratelocationnum IS NULL';
286
287   # if the credit_date option is set to application date, change
288   # $creditwhere accordingly
289   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
290     $creditwhere     =~ s/cust_bill._date/cust_credit_bill._date/g;
291   }
292
293   $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
294                   $creditfrom
295                   $creditwhere AND $istax
296                   $group";
297
298   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
299                   $creditfrom
300                   $creditwhere AND $istax
301                   $group_all";
302
303   # sum of tax paid
304   # this suffers from the same ambiguity as anything else that applies 
305   # received payments to specific packages, but in reality the discrepancy
306   # should be minimal since people either pay their bill or don't.
307   # the join is on billpkgtaxlocationnum to avoid cross-producting.
308  
309   my $paidfrom = $taxfrom .
310     ' JOIN cust_bill_pay_pkg'.
311     ' ON (cust_bill_pay_pkg.billpkgtaxlocationnum ='.
312     ' cust_bill_pkg_tax_location.billpkgtaxlocationnum)';
313
314   $sql{tax_paid} = "$select SUM(cust_bill_pay_pkg.amount)
315                     $paidfrom
316                     $where AND $istax
317                     $group";
318
319   $all_sql{tax_paid} = "$select_all SUM(cust_bill_pay_pkg.amount)
320                     $paidfrom
321                     $where AND $istax
322                     $group_all";
323
324   my %data;
325   my %total;
326   # note that we use keys(%sql) here and keys(%all_sql) later. nothing
327   # obligates us to use the same set of variables for the total query 
328   # as for the individual category queries
329   foreach my $k (keys(%sql)) {
330     my $stmt = $sql{$k};
331     warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG > 1;
332     my $sth = dbh->prepare($stmt);
333     # eight columns: pkgclass, taxclass, state, county, city, district
334     # taxnums (comma separated), value
335     $sth->execute 
336       or die "failed to execute $k query: ".$sth->errstr;
337     while ( my $row = $sth->fetchrow_arrayref ) {
338       my $bin = $data
339                 {$row->[0]} # pkgclass
340                 {$row->[1]  # taxclass
341                   || ($breakdown{taxclass} ? 'Unclassified' : '')}
342                 {$row->[2]} # state
343                 {$row->[3] ? $row->[3] . ' County' : ''} # county
344                 {$row->[4]} # city
345                 {$row->[5]} # district
346               ||= [];
347       push @$bin, [ $k, $row->[6], $row->[7] ];
348     }
349   }
350   warn "DATA:\n".Dumper(\%data) if $DEBUG;
351
352   foreach my $k (keys %all_sql) {
353     warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
354     my $sth = dbh->prepare($all_sql{$k});
355     # three columns: pkgclass, taxnums (comma separated), value
356     $sth->execute 
357       or die "failed to execute $k totals query: ".$sth->errstr;
358     while ( my $row = $sth->fetchrow_arrayref ) {
359       my $bin = $total{$row->[0]} ||= [];
360       push @$bin, [ $k, $row->[1], $row->[2] ];
361     }
362   }
363   warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
364
365   # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
366   #   [ 'taxable',     taxnums, amount ],
367   #   [ 'exempt_cust', taxnums, amount ],
368   #   ...
369   # ]
370   # non-requested grouping levels simply collapse into key = ''
371
372   # the much-maligned "out of taxable region"...
373   # find sales that are not linked to any tax with this name
374   # but are still inside the date range/agent criteria.
375   #
376   # This doesn't use $select_all/$group_all because we want a single number,
377   # not a breakdown by pkgclass. Unless someone needs that eventually, 
378   # in which case we'll turn it into an %all_sql query.
379   
380   my $outside_where =
381     "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending";
382   if ( $agentnum ) {
383     $outside_where .= " AND cust_main.agentnum = $agentnum";
384   }
385   my $sql_outside = "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
386     FROM cust_bill_pkg
387     $join_cust_pkg
388     $outside_where
389     AND $nottax
390     AND NOT EXISTS(
391       SELECT 1 FROM cust_tax_exempt_pkg
392         JOIN cust_main_county USING (taxnum)
393         WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
394           AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
395           AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
396     )
397     AND NOT EXISTS(
398       SELECT 1 FROM cust_bill_pkg_tax_location
399         JOIN cust_main_county USING (taxnum)
400         WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
401           AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
402     )
403   ";
404   warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
405   my $total_outside = FS::Record->scalar_sql($sql_outside);
406
407   my %taxrates;
408   foreach my $tax (
409     qsearch('cust_main_county', {
410               country => $country,
411               tax => { op => '>', value => 0 }
412             }) )
413     {
414     $taxrates{$tax->taxnum} = $tax->tax;
415   }
416
417   # return the data
418   bless {
419     'opt'       => \%opt,
420     'data'      => \%data,
421     'total'     => \%total,
422     'taxrates'  => \%taxrates,
423     'outside'   => $total_outside,
424   }, $class;
425 }
426
427 sub opt {
428   my $self = shift;
429   $self->{opt};
430 }
431
432 sub data {
433   my $self = shift;
434   $self->{data};
435 }
436
437 # sub fetchall_array...
438
439 sub table {
440   my $self = shift;
441   my @columns = (qw(pkgclass taxclass state county city district));
442   # taxnums, field headings, and amounts
443   my @rows;
444   my %row_template;
445
446   # de-treeify this thing
447   my $descend;
448   $descend = sub {
449     my ($tree, $level) = @_;
450     if ( ref($tree) eq 'HASH' ) {
451       foreach my $k ( sort {
452            -1*($b eq '')    # sort '' to the end
453           or  ($a eq '')    # sort '' to the end
454           or  ($a <=> $b)   # sort numbers as numbers
455           or  ($a cmp $b)   # sort alphabetics as alphabetics
456         } keys %$tree )
457       {
458         $row_template{ $columns[$level] } = $k;
459         &{ $descend }($tree->{$k}, $level + 1);
460         if ( $level == 0 ) {
461           # then insert the total row for the pkgclass
462           $row_template{'total'} = 1; # flag it as a total
463           &{ $descend }($self->{total}->{$k}, 1);
464           $row_template{'total'} = 0;
465         }
466       }
467     } elsif ( ref($tree) eq 'ARRAY' ) {
468       # then we've reached the bottom; elements of this array are arrayrefs
469       # of [ field, taxnums, amount ].
470       # start with the inherited location-element fields
471       my %this_row = %row_template;
472       my %taxnums;
473       foreach my $x (@$tree) {
474         # accumulate taxnums
475         foreach (split(',', $x->[1])) {
476           $taxnums{$_} = 1;
477         }
478         # and money values
479         $this_row{ $x->[0] } = $x->[2];
480       }
481       # store combined taxnums
482       $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
483       # and calculate row totals
484       $this_row{sales} = sprintf('%.2f',
485                           $this_row{taxable} +
486                           $this_row{exempt_cust} +
487                           $this_row{exempt_pkg} + 
488                           $this_row{exempt_monthly}
489                         );
490       # and give it a label
491       if ( $this_row{total} ) {
492         $this_row{label} = 'Total';
493       } else {
494         $this_row{label} = join(', ', grep $_,
495                             $this_row{taxclass},
496                             $this_row{state},
497                             $this_row{county}, # already has ' County' suffix
498                             $this_row{city},
499                             $this_row{district}
500                            );
501       }
502       # and indicate the tax rate, if any
503       my $rate;
504       foreach (keys %taxnums) {
505         $rate ||= $self->{taxrates}->{$_};
506         if ( $rate != $self->{taxrates}->{$_} ) {
507           $rate = 'variable';
508           last;
509         }
510       }
511       if ( $rate eq 'variable' ) {
512         $this_row{rate} = 'variable';
513       } elsif ( $rate > 0 ) {
514         $this_row{rate} = sprintf('%.2f', $rate);
515       }
516       push @rows, \%this_row;
517     }
518   };
519
520   &{ $descend }($self->{data}, 0);
521
522   warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
523   return @rows;
524 }
525
526 sub taxrates {
527   my $self = shift;
528   $self->{taxrates}
529 }
530
531 sub title {
532   my $self = shift;
533   my $string = '';
534   if ( $self->{opt}->{agentnum} ) {
535     my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
536     $string .= $agent->agent . ' ';
537   }
538   $string .= 'Tax Report: '; # XXX localization
539   if ( $self->{opt}->{beginning} ) {
540     $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
541   }
542   $string .= 'through ';
543   if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
544     $string .= time2str('%h %o %Y', $self->{opt}->{ending});
545   } else {
546     $string .= 'now';
547   }
548   $string .= ' - ' . $self->{opt}->{taxname};
549   return $string;
550 }
551
552 1;