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