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