tax report improvements, #23449, #25935
[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   if ( $opt{taxname} =~ /^([\w\s]+)$/ ) {
45     $taxname = $1;
46   } else {
47     die "taxname required"; # UI prevents this
48   }
49
50   if ( $opt{country} =~ /^(\w\w)$/ ) {
51     $country = $1;
52   } else {
53     die "country required";
54   }
55
56   # %breakdown: short name => field identifier
57   %breakdown = (
58     'taxclass'  => 'cust_main_county.taxclass',
59     'pkgclass'  => 'part_pkg.classnum',
60     'city'      => 'cust_main_county.city',
61     'district'  => 'cust_main_county.district',
62     'state'     => 'cust_main_county.state',
63     'county'    => 'cust_main_county.county',
64   );
65   foreach (qw(taxclass pkgclass city district)) {
66     delete $breakdown{$_} unless $opt{breakdown}->{$_};
67   }
68
69   my $join_cust =     '      JOIN cust_bill     USING ( invnum  )
70                         LEFT JOIN cust_main     USING ( custnum ) ';
71
72   my $join_cust_pkg = $join_cust.
73                       ' LEFT JOIN cust_pkg      USING ( pkgnum  )
74                         LEFT JOIN part_pkg      USING ( pkgpart ) ';
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 (taxnum),
90   # and gives the amount of the tax exemption.  EXEMPT_WHERE should be replaced 
91   # with a real WHERE clause to further limit the tax exemptions that will be
92   # included.
93   my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
94     "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
95
96   my $where = "WHERE _date >= $beginning AND _date <= $ending ".
97               "AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname' ".
98               "AND cust_main_county.country = '$country'";
99   # SELECT/GROUP clauses for first-level queries
100   my $select = "SELECT ";
101   my $group = "GROUP BY ";
102   foreach (qw(pkgclass taxclass state county city district)) {
103     if ( $breakdown{$_} ) {
104       $select .= "$breakdown{$_} AS $_, ";
105       $group  .= "$breakdown{$_}, ";
106     } else {
107       $select .= "NULL AS $_, ";
108     }
109   }
110   $select .= "array_to_string(array_agg(DISTINCT(cust_main_county.taxnum)), ',') AS taxnums, ";
111   $group =~ s/, $//;
112
113   # SELECT/GROUP clauses for second-level (totals) queries
114   # breakdown by package class only, if anything
115   my $select_all = "SELECT NULL AS pkgclass, ";
116   my $group_all = "";
117   if ( $breakdown{pkgclass} ) {
118     $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
119     $group_all = "GROUP BY $breakdown{pkgclass}";
120   }
121   $select_all .= "array_to_string(array_agg(DISTINCT(cust_main_county.taxnum)), ',') AS taxnums, ";
122
123   my $agentnum;
124   if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
125     $agentnum = $1;
126     my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
127     die "agent not found" unless $agent;
128     $where .= " AND cust_main.agentnum = $agentnum";
129   }
130
131   my $nottax = 
132     '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
133
134   # one query for each column of the report
135   # plus separate queries for the totals row
136   my (%sql, %all_sql);
137
138   # SALES QUERIES (taxable sales, all types of exempt sales)
139   # -------------
140
141   # general form
142   my $exempt = "$select SUM(exempt_charged)
143     FROM cust_main_county
144     JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
145     USING (taxnum)
146     JOIN cust_bill_pkg USING (billpkgnum)
147     $join_cust_pkg $where AND $nottax
148     $group";
149
150   my $all_exempt = "$select_all 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_all";
157
158   # sales to tax-exempt customers
159   $sql{exempt_cust} = $exempt;
160   $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
161   $all_sql{exempt_cust} = $all_exempt;
162   $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
163
164   # sales of tax-exempt packages
165   $sql{exempt_pkg} = $exempt;
166   $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
167   $all_sql{exempt_pkg} = $all_exempt;
168   $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
169
170   # monthly per-customer exemptions
171   $sql{exempt_monthly} = $exempt;
172   $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
173   $all_sql{exempt_monthly} = $all_exempt;
174   $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
175
176   # taxable sales
177   $sql{taxable} = "$select
178     SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
179     FROM cust_main_county
180     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
181     JOIN cust_bill_pkg USING (billpkgnum)
182     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
183       ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
184           AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
185     $join_cust_pkg $where AND $nottax 
186     $group";
187
188   $all_sql{taxable} = "$select_all
189     SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
190     FROM cust_main_county
191     JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
192     JOIN cust_bill_pkg USING (billpkgnum)
193     LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
194       ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum 
195           AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
196     $join_cust_pkg $where AND $nottax 
197     $group_all";
198
199   $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
200   $all_sql{taxable} =~ s/EXEMPT_WHERE//;
201
202   # there isn't one for 'sales', because we calculate sales by adding up 
203   # the taxable and exempt columns.
204
205   # TAX QUERIES (billed tax, credited tax)
206   # -----------
207
208   # sum of billed tax:
209   # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
210   my $taxfrom = " FROM cust_bill_pkg 
211                   $join_cust 
212                   LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
213                   LEFT JOIN cust_main_county USING ( taxnum )";
214
215   if ( $breakdown{pkgclass} ) {
216     # If we're not grouping by package class, this is unnecessary, and
217     # probably really expensive.
218     $taxfrom .= "
219                   LEFT JOIN cust_bill_pkg AS taxable
220                     ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
221                   LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
222                   LEFT JOIN part_pkg USING (pkgpart)";
223   }
224
225   my $istax = "cust_bill_pkg.pkgnum = 0";
226
227   $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
228                $taxfrom
229                $where AND $istax
230                $group";
231
232   $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
233                $taxfrom
234                $where AND $istax
235                $group_all";
236
237   # sum of credits applied against billed tax
238   # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
239   # is on)
240   my $creditfrom = $taxfrom .
241      ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)';
242   my $creditwhere = $where . 
243      ' AND billpkgtaxratelocationnum IS NULL';
244
245   $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
246                   $creditfrom
247                   $creditwhere AND $istax
248                   $group";
249
250   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
251                   $creditfrom
252                   $creditwhere AND $istax
253                   $group_all";
254
255   my %data;
256   my %total;
257   foreach my $k (keys(%sql)) {
258     my $stmt = $sql{$k};
259     warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
260     my $sth = dbh->prepare($stmt);
261     # eight columns: pkgclass, taxclass, state, county, city, district
262     # taxnums (comma separated), value
263     $sth->execute 
264       or die "failed to execute $k query: ".$sth->errstr;
265     while ( my $row = $sth->fetchrow_arrayref ) {
266       my $bin = $data
267                 {$row->[0]} # pkgclass
268                 {$row->[1]  # taxclass
269                   || ($breakdown{taxclass} ? 'Unclassified' : '')}
270                 {$row->[2]} # state
271                 {$row->[3] ? $row->[3] . ' County' : ''} # county
272                 {$row->[4]} # city
273                 {$row->[5]} # district
274               ||= [];
275       push @$bin, [ $k, $row->[6], $row->[7] ];
276     }
277   }
278   warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
279
280   foreach my $k (keys %all_sql) {
281     warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
282     my $sth = dbh->prepare($all_sql{$k});
283     # three columns: pkgclass, taxnums (comma separated), value
284     $sth->execute 
285       or die "failed to execute $k totals query: ".$sth->errstr;
286     while ( my $row = $sth->fetchrow_arrayref ) {
287       my $bin = $total{$row->[0]} ||= [];
288       push @$bin, [ $k, $row->[1], $row->[2] ];
289     }
290   }
291   warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
292
293   # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
294   #   [ 'taxable',     taxnums, amount ],
295   #   [ 'exempt_cust', taxnums, amount ],
296   #   ...
297   # ]
298   # non-requested grouping levels simply collapse into key = ''
299
300   my %taxrates;
301   foreach my $tax (
302     qsearch('cust_main_county', {
303               country => $country,
304               tax => { op => '>', value => 0 }
305             }) )
306     {
307     $taxrates{$tax->taxnum} = $tax->tax;
308   }
309
310   # return the data
311   bless {
312     'opt'       => \%opt,
313     'data'      => \%data,
314     'total'     => \%total,
315     'taxrates'  => \%taxrates,
316   }, $class;
317 }
318
319 sub opt {
320   my $self = shift;
321   $self->{opt};
322 }
323
324 sub data {
325   my $self = shift;
326   $self->{data};
327 }
328
329 # sub fetchall_array...
330
331 sub table {
332   my $self = shift;
333   my @columns = (qw(pkgclass taxclass state county city district));
334   # taxnums, field headings, and amounts
335   my @rows;
336   my %row_template;
337
338   # de-treeify this thing
339   my $descend;
340   $descend = sub {
341     my ($tree, $level) = @_;
342     if ( ref($tree) eq 'HASH' ) {
343       foreach my $k ( sort {
344            -1*($b eq '')    # sort '' to the end
345           or  ($a eq '')    # sort '' to the end
346           or  ($a <=> $b)   # sort numbers as numbers
347           or  ($a cmp $b)   # sort alphabetics as alphabetics
348         } keys %$tree )
349       {
350         $row_template{ $columns[$level] } = $k;
351         &{ $descend }($tree->{$k}, $level + 1);
352         if ( $level == 0 ) {
353           # then insert the total row for the pkgclass
354           $row_template{'total'} = 1; # flag it as a total
355           &{ $descend }($self->{total}->{$k}, 1);
356           $row_template{'total'} = 0;
357         }
358       }
359     } elsif ( ref($tree) eq 'ARRAY' ) {
360       # then we've reached the bottom; elements of this array are arrayrefs
361       # of [ field, taxnums, amount ].
362       # start with the inherited location-element fields
363       my %this_row = %row_template;
364       my %taxnums;
365       foreach my $x (@$tree) {
366         # accumulate taxnums
367         foreach (split(',', $x->[1])) {
368           $taxnums{$_} = 1;
369         }
370         # and money values
371         $this_row{ $x->[0] } = $x->[2];
372       }
373       # store combined taxnums
374       $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
375       # and calculate row totals
376       $this_row{sales} = sprintf('%.2f',
377                           $this_row{taxable} +
378                           $this_row{exempt_cust} +
379                           $this_row{exempt_pkg} + 
380                           $this_row{exempt_monthly}
381                         );
382       # and give it a label
383       if ( $this_row{total} ) {
384         $this_row{label} = 'Total';
385       } else {
386         $this_row{label} = join(', ', grep $_,
387                             $this_row{taxclass},
388                             $this_row{state},
389                             $this_row{county}, # already has ' County' suffix
390                             $this_row{city},
391                             $this_row{district}
392                            );
393       }
394       # and indicate the tax rate, if any
395       my $rate;
396       foreach (keys %taxnums) {
397         $rate ||= $self->{taxrates}->{$_};
398         if ( $rate != $self->{taxrates}->{$_} ) {
399           $rate = 'variable';
400           last;
401         }
402       }
403       if ( $rate eq 'variable' ) {
404         $this_row{rate} = 'variable';
405       } elsif ( $rate > 0 ) {
406         $this_row{rate} = sprintf('%.2f', $rate);
407         $this_row{estimated} =
408           sprintf('%.2f', $this_row{taxable} * $rate / 100);
409       }
410       push @rows, \%this_row;
411     }
412   };
413
414   &{ $descend }($self->{data}, 0);
415
416   warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
417   return @rows;
418 }
419
420 sub taxrates {
421   my $self = shift;
422   $self->{taxrates}
423 }
424
425 sub title {
426   my $self = shift;
427   my $string = '';
428   if ( $self->{opt}->{agentnum} ) {
429     my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
430     $string .= $agent->agent . ' ';
431     warn $string;
432   }
433   $string .= 'Tax Report: '; # XXX localization
434   if ( $self->{opt}->{beginning} ) {
435     $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
436   }
437   $string .= 'through ';
438   if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
439     $string .= time2str('%h %o %Y', $self->{opt}->{ending});
440   } else {
441     $string .= 'now';
442   }
443   $string .= ' - ' . $self->{opt}->{taxname};
444   return $string;
445 }
446
447 1;