tax report: deduct credits from taxable amount, #27698
[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);
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   # purify taxname properly here, as we're going to include it in lots of 
45   # SQL statements using single quotes only
46   if ( $opt{taxname} =~ /^([\w\s]+)$/ ) {
47     $taxname = $1;
48   } else {
49     die "taxname required"; # UI prevents this
50   }
51
52   if ( $opt{country} =~ /^(\w\w)$/ ) {
53     $country = $1;
54   } else {
55     die "country required";
56   }
57
58   # %breakdown: short name => field identifier
59   %breakdown = (
60     'taxclass'  => 'cust_main_county.taxclass',
61     'pkgclass'  => '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
78   my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg "; 
79
80   # all queries MUST be linked to both cust_bill and cust_main_county
81
82   # Either or both of these can be used to link cust_bill_pkg to 
83   # cust_main_county. This one links a taxed line item (billpkgnum) to a tax rate
84   # (taxnum), and gives the amount of tax charged on that line item under that
85   # rate (as tax_amount).
86   my $pkg_tax = "SELECT SUM(amount) as tax_amount, taxnum, ".
87     "taxable_billpkgnum AS billpkgnum ".
88     "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
89     "GROUP BY taxable_billpkgnum, taxnum";
90
91   # This one links a tax-exempted line item (billpkgnum) to a tax rate (taxnum),
92   # and gives the amount of the tax exemption.  EXEMPT_WHERE should be replaced 
93   # with a real WHERE clause to further limit the tax exemptions that will be
94   # included.
95   my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
96     "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
97
98   # This just calculates the sum of credit applications to a line item.
99   my $pkg_credited = "SELECT SUM(amount) AS credited, billpkgnum ".
100     "FROM cust_credit_bill_pkg GROUP BY billpkgnum";
101
102   my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ".
103               "AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname' ".
104               "AND cust_main_county.country = '$country'";
105   # SELECT/GROUP clauses for first-level queries
106   my $select = "SELECT ";
107   my $group = "GROUP BY ";
108   foreach (qw(pkgclass taxclass state county city district)) {
109     if ( $breakdown{$_} ) {
110       $select .= "$breakdown{$_} AS $_, ";
111       $group  .= "$breakdown{$_}, ";
112     } else {
113       $select .= "NULL AS $_, ";
114     }
115   }
116   $select .= "array_to_string(array_agg(DISTINCT(cust_main_county.taxnum)), ',') AS taxnums, ";
117   $group =~ s/, $//;
118
119   # SELECT/GROUP clauses for second-level (totals) queries
120   # breakdown by package class only, if anything
121   my $select_all = "SELECT NULL AS pkgclass, ";
122   my $group_all = "";
123   if ( $breakdown{pkgclass} ) {
124     $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
125     $group_all = "GROUP BY $breakdown{pkgclass}";
126   }
127   $select_all .= "array_to_string(array_agg(DISTINCT(cust_main_county.taxnum)), ',') AS taxnums, ";
128
129   my $agentnum;
130   if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
131     $agentnum = $1;
132     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
133     die "agent not found" unless $agent;
134     $where .= " AND cust_main.agentnum = $agentnum";
135   }
136
137   my $nottax = 
138     '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
139
140   # one query for each column of the report
141   # plus separate queries for the totals row
142   my (%sql, %all_sql);
143
144   # SALES QUERIES (taxable sales, all types of exempt sales)
145   # -------------
146
147   # general form
148   my $exempt = "$select SUM(exempt_charged)
149     FROM cust_main_county
150     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
151     USING (taxnum)
152     JOIN cust_bill_pkg USING (billpkgnum)
153     $join_cust_pkg $where AND $nottax
154     $group";
155
156   my $all_exempt = "$select_all SUM(exempt_charged)
157     FROM cust_main_county
158     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
159     USING (taxnum)
160     JOIN cust_bill_pkg USING (billpkgnum)
161     $join_cust_pkg $where AND $nottax
162     $group_all";
163
164   # sales to tax-exempt customers
165   $sql{exempt_cust} = $exempt;
166   $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
167   $all_sql{exempt_cust} = $all_exempt;
168   $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
169
170   # sales of tax-exempt packages
171   $sql{exempt_pkg} = $exempt;
172   $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
173   $all_sql{exempt_pkg} = $all_exempt;
174   $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
175
176   # monthly per-customer exemptions
177   $sql{exempt_monthly} = $exempt;
178   $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
179   $all_sql{exempt_monthly} = $all_exempt;
180   $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
181
182   # taxable sales
183   # (sale - exemptions - credits, except not negative)
184   $sql{taxable} = "$select
185     SUM(
186       cust_bill_pkg.setup + cust_bill_pkg.recur
187         - COALESCE(exempt_charged, 0)
188         - COALESCE(credited, 0)
189       )
190     FROM cust_bill_pkg
191     LEFT JOIN ($pkg_tax) AS pkg_tax
192       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
193     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
194       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
195     LEFT JOIN ($pkg_credited) AS pkg_credited
196       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
197     LEFT JOIN cust_main_county
198       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
199     $join_cust_pkg $where AND $nottax 
200     $group";
201
202   $all_sql{taxable} = "$select_all
203     SUM(
204       cust_bill_pkg.setup + cust_bill_pkg.recur
205         - COALESCE(exempt_charged, 0)
206         - COALESCE(credited, 0)
207       )
208     FROM cust_bill_pkg
209     LEFT JOIN ($pkg_tax) AS pkg_tax
210       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
211     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
212       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
213     LEFT JOIN ($pkg_credited) AS pkg_credited
214       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
215     LEFT JOIN cust_main_county
216       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
217     $join_cust_pkg $where AND $nottax 
218     $group_all";
219
220   $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
221   $all_sql{taxable} =~ s/EXEMPT_WHERE//;
222
223   # estimated tax (taxable * rate)
224   $sql{estimated} = "$select
225     SUM(cust_main_county.tax / 100 * 
226       ( cust_bill_pkg.setup + cust_bill_pkg.recur
227         - COALESCE(exempt_charged, 0)
228         - COALESCE(credited, 0)
229       )
230     )
231     FROM cust_bill_pkg
232     LEFT JOIN ($pkg_tax) AS pkg_tax
233       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
234     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
235       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
236     LEFT JOIN ($pkg_credited) AS pkg_credited
237       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
238     LEFT JOIN cust_main_county
239       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
240     $join_cust_pkg $where AND $nottax 
241     $group";
242
243   $all_sql{estimated} = "$select_all
244     SUM(cust_main_county.tax / 100 * 
245       ( cust_bill_pkg.setup + cust_bill_pkg.recur
246         - COALESCE(exempt_charged, 0)
247         - COALESCE(credited, 0)
248       )
249     )
250     FROM cust_bill_pkg
251     LEFT JOIN ($pkg_tax) AS pkg_tax
252       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
253     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
254       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
255     LEFT JOIN ($pkg_credited) AS pkg_credited
256       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
257     LEFT JOIN cust_main_county
258       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
259     $join_cust_pkg $where AND $nottax 
260     $group_all";
261
262   # there isn't one for 'sales', because we calculate sales by adding up 
263   # the taxable and exempt columns.
264   
265   # TAX QUERIES (billed tax, credited tax)
266   # -----------
267
268   # sum of billed tax:
269   # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
270   my $taxfrom = " FROM cust_bill_pkg 
271                   $join_cust 
272                   LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
273                   LEFT JOIN cust_main_county USING ( taxnum )";
274
275   if ( $breakdown{pkgclass} ) {
276     # If we're not grouping by package class, this is unnecessary, and
277     # probably really expensive.
278     $taxfrom .= "
279                   LEFT JOIN cust_bill_pkg AS taxable
280                     ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
281                   LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
282                   LEFT JOIN part_pkg USING (pkgpart)";
283   }
284
285   my $istax = "cust_bill_pkg.pkgnum = 0";
286
287   $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
288                $taxfrom
289                $where AND $istax
290                $group";
291
292   $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
293                $taxfrom
294                $where AND $istax
295                $group_all";
296
297   # sum of credits applied against billed tax
298   # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
299   # is on)
300   my $creditfrom = $taxfrom .
301     ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
302     ' JOIN cust_credit_bill     USING (creditbillnum)';
303   my $creditwhere = $where . 
304     ' AND billpkgtaxratelocationnum IS NULL';
305
306   # if the credit_date option is set to application date, change
307   # $creditwhere accordingly
308   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
309     $creditwhere     =~ s/cust_bill._date/cust_credit_bill._date/g;
310   }
311
312   $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
313                   $creditfrom
314                   $creditwhere AND $istax
315                   $group";
316
317   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
318                   $creditfrom
319                   $creditwhere AND $istax
320                   $group_all";
321
322   my %data;
323   my %total;
324   # note that we use keys(%sql) here and keys(%all_sql) later. nothing
325   # obligates us to use the same set of variables for the total query 
326   # as for the individual category queries
327   foreach my $k (keys(%sql)) {
328     my $stmt = $sql{$k};
329     warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
330     my $sth = dbh->prepare($stmt);
331     # eight columns: pkgclass, taxclass, state, county, city, district
332     # taxnums (comma separated), value
333     $sth->execute 
334       or die "failed to execute $k query: ".$sth->errstr;
335     while ( my $row = $sth->fetchrow_arrayref ) {
336       my $bin = $data
337                 {$row->[0]} # pkgclass
338                 {$row->[1]  # taxclass
339                   || ($breakdown{taxclass} ? 'Unclassified' : '')}
340                 {$row->[2]} # state
341                 {$row->[3] ? $row->[3] . ' County' : ''} # county
342                 {$row->[4]} # city
343                 {$row->[5]} # district
344               ||= [];
345       push @$bin, [ $k, $row->[6], $row->[7] ];
346     }
347   }
348   warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
349
350   foreach my $k (keys %all_sql) {
351     warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
352     my $sth = dbh->prepare($all_sql{$k});
353     # three columns: pkgclass, taxnums (comma separated), value
354     $sth->execute 
355       or die "failed to execute $k totals query: ".$sth->errstr;
356     while ( my $row = $sth->fetchrow_arrayref ) {
357       my $bin = $total{$row->[0]} ||= [];
358       push @$bin, [ $k, $row->[1], $row->[2] ];
359     }
360   }
361   warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
362
363   # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
364   #   [ 'taxable',     taxnums, amount ],
365   #   [ 'exempt_cust', taxnums, amount ],
366   #   ...
367   # ]
368   # non-requested grouping levels simply collapse into key = ''
369
370   # the much-maligned "out of taxable region"...
371   # find sales that are not linked to any tax with this name
372   # but are still inside the date range/agent criteria.
373   #
374   # This doesn't use $select_all/$group_all because we want a single number,
375   # not a breakdown by pkgclass. Unless someone needs that eventually, 
376   # in which case we'll turn it into an %all_sql query.
377   
378   my $outside_where =
379     "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending";
380   if ( $agentnum ) {
381     $outside_where .= " AND cust_main.agentnum = $agentnum";
382   }
383   my $sql_outside = "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
384     FROM cust_bill_pkg
385     $join_cust_pkg
386     $outside_where
387     AND $nottax
388     AND NOT EXISTS(
389       SELECT 1 FROM cust_tax_exempt_pkg
390         JOIN cust_main_county USING (taxnum)
391         WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
392           AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname'
393     )
394     AND NOT EXISTS(
395       SELECT 1 FROM cust_bill_pkg_tax_location
396         JOIN cust_main_county USING (taxnum)
397         WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
398           AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname'
399     )
400   ";
401   warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
402   my $total_outside = FS::Record->scalar_sql($sql_outside);
403
404   my %taxrates;
405   foreach my $tax (
406     qsearch('cust_main_county', {
407               country => $country,
408               tax => { op => '>', value => 0 }
409             }) )
410     {
411     $taxrates{$tax->taxnum} = $tax->tax;
412   }
413
414   # return the data
415   bless {
416     'opt'       => \%opt,
417     'data'      => \%data,
418     'total'     => \%total,
419     'taxrates'  => \%taxrates,
420     'outside'   => $total_outside,
421   }, $class;
422 }
423
424 sub opt {
425   my $self = shift;
426   $self->{opt};
427 }
428
429 sub data {
430   my $self = shift;
431   $self->{data};
432 }
433
434 # sub fetchall_array...
435
436 sub table {
437   my $self = shift;
438   my @columns = (qw(pkgclass taxclass state county city district));
439   # taxnums, field headings, and amounts
440   my @rows;
441   my %row_template;
442
443   # de-treeify this thing
444   my $descend;
445   $descend = sub {
446     my ($tree, $level) = @_;
447     if ( ref($tree) eq 'HASH' ) {
448       foreach my $k ( sort {
449            -1*($b eq '')    # sort '' to the end
450           or  ($a eq '')    # sort '' to the end
451           or  ($a <=> $b)   # sort numbers as numbers
452           or  ($a cmp $b)   # sort alphabetics as alphabetics
453         } keys %$tree )
454       {
455         $row_template{ $columns[$level] } = $k;
456         &{ $descend }($tree->{$k}, $level + 1);
457         if ( $level == 0 ) {
458           # then insert the total row for the pkgclass
459           $row_template{'total'} = 1; # flag it as a total
460           &{ $descend }($self->{total}->{$k}, 1);
461           $row_template{'total'} = 0;
462         }
463       }
464     } elsif ( ref($tree) eq 'ARRAY' ) {
465       # then we've reached the bottom; elements of this array are arrayrefs
466       # of [ field, taxnums, amount ].
467       # start with the inherited location-element fields
468       my %this_row = %row_template;
469       my %taxnums;
470       foreach my $x (@$tree) {
471         # accumulate taxnums
472         foreach (split(',', $x->[1])) {
473           $taxnums{$_} = 1;
474         }
475         # and money values
476         $this_row{ $x->[0] } = $x->[2];
477       }
478       # store combined taxnums
479       $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
480       # and calculate row totals
481       $this_row{sales} = sprintf('%.2f',
482                           $this_row{taxable} +
483                           $this_row{exempt_cust} +
484                           $this_row{exempt_pkg} + 
485                           $this_row{exempt_monthly}
486                         );
487       # and give it a label
488       if ( $this_row{total} ) {
489         $this_row{label} = 'Total';
490       } else {
491         $this_row{label} = join(', ', grep $_,
492                             $this_row{taxclass},
493                             $this_row{state},
494                             $this_row{county}, # already has ' County' suffix
495                             $this_row{city},
496                             $this_row{district}
497                            );
498       }
499       # and indicate the tax rate, if any
500       my $rate;
501       foreach (keys %taxnums) {
502         $rate ||= $self->{taxrates}->{$_};
503         if ( $rate != $self->{taxrates}->{$_} ) {
504           $rate = 'variable';
505           last;
506         }
507       }
508       if ( $rate eq 'variable' ) {
509         $this_row{rate} = 'variable';
510       } elsif ( $rate > 0 ) {
511         $this_row{rate} = sprintf('%.2f', $rate);
512       }
513       push @rows, \%this_row;
514     }
515   };
516
517   &{ $descend }($self->{data}, 0);
518
519   warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
520   return @rows;
521 }
522
523 sub taxrates {
524   my $self = shift;
525   $self->{taxrates}
526 }
527
528 sub title {
529   my $self = shift;
530   my $string = '';
531   if ( $self->{opt}->{agentnum} ) {
532     my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
533     $string .= $agent->agent . ' ';
534   }
535   $string .= 'Tax Report: '; # XXX localization
536   if ( $self->{opt}->{beginning} ) {
537     $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
538   }
539   $string .= 'through ';
540   if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
541     $string .= time2str('%h %o %Y', $self->{opt}->{ending});
542   } else {
543     $string .= 'now';
544   }
545   $string .= ' - ' . $self->{opt}->{taxname};
546   return $string;
547 }
548
549 1;