use the mysql equivalent of array_to_string, #32548
[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   # 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 .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
117              ' AS taxnums, ';
118   $group =~ s/, $//;
119
120   # SELECT/GROUP clauses for second-level (totals) queries
121   # breakdown by package class only, if anything
122   my $select_all = "SELECT NULL AS pkgclass, ";
123   my $group_all = "";
124   if ( $breakdown{pkgclass} ) {
125     $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
126     $group_all = "GROUP BY $breakdown{pkgclass}";
127   }
128   $select_all .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
129                  ' AS taxnums, ';
130
131   my $agentnum;
132   if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
133     $agentnum = $1;
134     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
135     die "agent not found" unless $agent;
136     $where .= " AND cust_main.agentnum = $agentnum";
137   }
138
139   my $nottax = 
140     '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
141
142   # one query for each column of the report
143   # plus separate queries for the totals row
144   my (%sql, %all_sql);
145
146   # SALES QUERIES (taxable sales, all types of exempt sales)
147   # -------------
148
149   # general form
150   my $exempt = "$select SUM(exempt_charged)
151     FROM cust_main_county
152     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
153     USING (taxnum)
154     JOIN cust_bill_pkg USING (billpkgnum)
155     $join_cust_pkg $where AND $nottax
156     $group";
157
158   my $all_exempt = "$select_all SUM(exempt_charged)
159     FROM cust_main_county
160     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
161     USING (taxnum)
162     JOIN cust_bill_pkg USING (billpkgnum)
163     $join_cust_pkg $where AND $nottax
164     $group_all";
165
166   # sales to tax-exempt customers
167   $sql{exempt_cust} = $exempt;
168   $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
169   $all_sql{exempt_cust} = $all_exempt;
170   $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
171
172   # sales of tax-exempt packages
173   $sql{exempt_pkg} = $exempt;
174   $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
175   $all_sql{exempt_pkg} = $all_exempt;
176   $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
177
178   # monthly per-customer exemptions
179   $sql{exempt_monthly} = $exempt;
180   $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
181   $all_sql{exempt_monthly} = $all_exempt;
182   $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
183
184   # taxable sales
185   # (sale - exemptions - credits, except not negative)
186   $sql{taxable} = "$select
187     SUM(
188       cust_bill_pkg.setup + cust_bill_pkg.recur
189         - COALESCE(exempt_charged, 0)
190         - COALESCE(credited, 0)
191       )
192     FROM cust_bill_pkg
193     LEFT JOIN ($pkg_tax) AS pkg_tax
194       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
195     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
196       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
197     LEFT JOIN ($pkg_credited) AS pkg_credited
198       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
199     LEFT JOIN cust_main_county
200       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
201     $join_cust_pkg $where AND $nottax 
202     $group";
203
204   $all_sql{taxable} = "$select_all
205     SUM(
206       cust_bill_pkg.setup + cust_bill_pkg.recur
207         - COALESCE(exempt_charged, 0)
208         - COALESCE(credited, 0)
209       )
210     FROM cust_bill_pkg
211     LEFT JOIN ($pkg_tax) AS pkg_tax
212       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
213     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
214       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
215     LEFT JOIN ($pkg_credited) AS pkg_credited
216       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
217     LEFT JOIN cust_main_county
218       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
219     $join_cust_pkg $where AND $nottax 
220     $group_all";
221
222   $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
223   $all_sql{taxable} =~ s/EXEMPT_WHERE//;
224
225   # estimated tax (taxable * rate)
226   $sql{estimated} = "$select
227     SUM(cust_main_county.tax / 100 * 
228       ( cust_bill_pkg.setup + cust_bill_pkg.recur
229         - COALESCE(exempt_charged, 0)
230         - COALESCE(credited, 0)
231       )
232     )
233     FROM cust_bill_pkg
234     LEFT JOIN ($pkg_tax) AS pkg_tax
235       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
236     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
237       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
238     LEFT JOIN ($pkg_credited) AS pkg_credited
239       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
240     LEFT JOIN cust_main_county
241       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
242     $join_cust_pkg $where AND $nottax 
243     $group";
244
245   $all_sql{estimated} = "$select_all
246     SUM(cust_main_county.tax / 100 * 
247       ( cust_bill_pkg.setup + cust_bill_pkg.recur
248         - COALESCE(exempt_charged, 0)
249         - COALESCE(credited, 0)
250       )
251     )
252     FROM cust_bill_pkg
253     LEFT JOIN ($pkg_tax) AS pkg_tax
254       ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
255     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
256       ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
257     LEFT JOIN ($pkg_credited) AS pkg_credited
258       ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
259     LEFT JOIN cust_main_county
260       ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
261     $join_cust_pkg $where AND $nottax 
262     $group_all";
263
264   # there isn't one for 'sales', because we calculate sales by adding up 
265   # the taxable and exempt columns.
266   
267   # TAX QUERIES (billed tax, credited tax)
268   # -----------
269
270   # sum of billed tax:
271   # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
272   my $taxfrom = " FROM cust_bill_pkg 
273                   $join_cust 
274                   LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
275                   LEFT JOIN cust_main_county USING ( taxnum )";
276
277   if ( $breakdown{pkgclass} ) {
278     # If we're not grouping by package class, this is unnecessary, and
279     # probably really expensive.
280     $taxfrom .= "
281                   LEFT JOIN cust_bill_pkg AS taxable
282                     ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
283                   LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
284                   LEFT JOIN part_pkg USING (pkgpart)";
285   }
286
287   my $istax = "cust_bill_pkg.pkgnum = 0";
288
289   $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
290                $taxfrom
291                $where AND $istax
292                $group";
293
294   $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
295                $taxfrom
296                $where AND $istax
297                $group_all";
298
299   # sum of credits applied against billed tax
300   # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
301   # is on)
302   my $creditfrom = $taxfrom .
303     ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
304     ' JOIN cust_credit_bill     USING (creditbillnum)';
305   my $creditwhere = $where . 
306     ' AND billpkgtaxratelocationnum IS NULL';
307
308   # if the credit_date option is set to application date, change
309   # $creditwhere accordingly
310   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
311     $creditwhere     =~ s/cust_bill._date/cust_credit_bill._date/g;
312   }
313
314   $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
315                   $creditfrom
316                   $creditwhere AND $istax
317                   $group";
318
319   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
320                   $creditfrom
321                   $creditwhere 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;
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 > 1;
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     )
396     AND NOT EXISTS(
397       SELECT 1 FROM cust_bill_pkg_tax_location
398         JOIN cust_main_county USING (taxnum)
399         WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
400           AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname'
401     )
402   ";
403   warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
404   my $total_outside = FS::Record->scalar_sql($sql_outside);
405
406   my %taxrates;
407   foreach my $tax (
408     qsearch('cust_main_county', {
409               country => $country,
410               tax => { op => '>', value => 0 }
411             }) )
412     {
413     $taxrates{$tax->taxnum} = $tax->tax;
414   }
415
416   # return the data
417   bless {
418     'opt'       => \%opt,
419     'data'      => \%data,
420     'total'     => \%total,
421     'taxrates'  => \%taxrates,
422     'outside'   => $total_outside,
423   }, $class;
424 }
425
426 sub opt {
427   my $self = shift;
428   $self->{opt};
429 }
430
431 sub data {
432   my $self = shift;
433   $self->{data};
434 }
435
436 # sub fetchall_array...
437
438 sub table {
439   my $self = shift;
440   my @columns = (qw(pkgclass taxclass state county city district));
441   # taxnums, field headings, and amounts
442   my @rows;
443   my %row_template;
444
445   # de-treeify this thing
446   my $descend;
447   $descend = sub {
448     my ($tree, $level) = @_;
449     if ( ref($tree) eq 'HASH' ) {
450       foreach my $k ( sort {
451            -1*($b eq '')    # sort '' to the end
452           or  ($a eq '')    # sort '' to the end
453           or  ($a <=> $b)   # sort numbers as numbers
454           or  ($a cmp $b)   # sort alphabetics as alphabetics
455         } keys %$tree )
456       {
457         $row_template{ $columns[$level] } = $k;
458         &{ $descend }($tree->{$k}, $level + 1);
459         if ( $level == 0 ) {
460           # then insert the total row for the pkgclass
461           $row_template{'total'} = 1; # flag it as a total
462           &{ $descend }($self->{total}->{$k}, 1);
463           $row_template{'total'} = 0;
464         }
465       }
466     } elsif ( ref($tree) eq 'ARRAY' ) {
467       # then we've reached the bottom; elements of this array are arrayrefs
468       # of [ field, taxnums, amount ].
469       # start with the inherited location-element fields
470       my %this_row = %row_template;
471       my %taxnums;
472       foreach my $x (@$tree) {
473         # accumulate taxnums
474         foreach (split(',', $x->[1])) {
475           $taxnums{$_} = 1;
476         }
477         # and money values
478         $this_row{ $x->[0] } = $x->[2];
479       }
480       # store combined taxnums
481       $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
482       # and calculate row totals
483       $this_row{sales} = sprintf('%.2f',
484                           $this_row{taxable} +
485                           $this_row{exempt_cust} +
486                           $this_row{exempt_pkg} + 
487                           $this_row{exempt_monthly}
488                         );
489       # and give it a label
490       if ( $this_row{total} ) {
491         $this_row{label} = 'Total';
492       } else {
493         $this_row{label} = join(', ', grep $_,
494                             $this_row{taxclass},
495                             $this_row{state},
496                             $this_row{county}, # already has ' County' suffix
497                             $this_row{city},
498                             $this_row{district}
499                            );
500       }
501       # and indicate the tax rate, if any
502       my $rate;
503       foreach (keys %taxnums) {
504         $rate ||= $self->{taxrates}->{$_};
505         if ( $rate != $self->{taxrates}->{$_} ) {
506           $rate = 'variable';
507           last;
508         }
509       }
510       if ( $rate eq 'variable' ) {
511         $this_row{rate} = 'variable';
512       } elsif ( $rate > 0 ) {
513         $this_row{rate} = sprintf('%.2f', $rate);
514       }
515       push @rows, \%this_row;
516     }
517   };
518
519   &{ $descend }($self->{data}, 0);
520
521   warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
522   return @rows;
523 }
524
525 sub taxrates {
526   my $self = shift;
527   $self->{taxrates}
528 }
529
530 sub title {
531   my $self = shift;
532   my $string = '';
533   if ( $self->{opt}->{agentnum} ) {
534     my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
535     $string .= $agent->agent . ' ';
536   }
537   $string .= 'Tax Report: '; # XXX localization
538   if ( $self->{opt}->{beginning} ) {
539     $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
540   }
541   $string .= 'through ';
542   if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
543     $string .= time2str('%h %o %Y', $self->{opt}->{ending});
544   } else {
545     $string .= 'now';
546   }
547   $string .= ' - ' . $self->{opt}->{taxname};
548   return $string;
549 }
550
551 1;