d3322af87afa864e03bc9bc3e3be49e14a7637ad
[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 cust_bill._date >= $beginning AND cust_bill._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     ' JOIN cust_credit_bill     USING (creditbillnum)';
243   my $creditwhere = $where . 
244     ' AND billpkgtaxratelocationnum IS NULL';
245
246   # if the credit_date option is set to application date, change
247   # $creditwhere accordingly
248   if ( $opt{credit_date} eq 'cust_credit_bill' ) {
249     $creditwhere     =~ s/cust_bill._date/cust_credit_bill._date/g;
250   }
251
252   $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
253                   $creditfrom
254                   $creditwhere AND $istax
255                   $group";
256
257   $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
258                   $creditfrom
259                   $creditwhere AND $istax
260                   $group_all";
261
262   my %data;
263   my %total;
264   foreach my $k (keys(%sql)) {
265     my $stmt = $sql{$k};
266     warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
267     my $sth = dbh->prepare($stmt);
268     # eight columns: pkgclass, taxclass, state, county, city, district
269     # taxnums (comma separated), value
270     $sth->execute 
271       or die "failed to execute $k query: ".$sth->errstr;
272     while ( my $row = $sth->fetchrow_arrayref ) {
273       my $bin = $data
274                 {$row->[0]} # pkgclass
275                 {$row->[1]  # taxclass
276                   || ($breakdown{taxclass} ? 'Unclassified' : '')}
277                 {$row->[2]} # state
278                 {$row->[3] ? $row->[3] . ' County' : ''} # county
279                 {$row->[4]} # city
280                 {$row->[5]} # district
281               ||= [];
282       push @$bin, [ $k, $row->[6], $row->[7] ];
283     }
284   }
285   warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
286
287   foreach my $k (keys %all_sql) {
288     warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
289     my $sth = dbh->prepare($all_sql{$k});
290     # three columns: pkgclass, taxnums (comma separated), value
291     $sth->execute 
292       or die "failed to execute $k totals query: ".$sth->errstr;
293     while ( my $row = $sth->fetchrow_arrayref ) {
294       my $bin = $total{$row->[0]} ||= [];
295       push @$bin, [ $k, $row->[1], $row->[2] ];
296     }
297   }
298   warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
299
300   # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
301   #   [ 'taxable',     taxnums, amount ],
302   #   [ 'exempt_cust', taxnums, amount ],
303   #   ...
304   # ]
305   # non-requested grouping levels simply collapse into key = ''
306
307   my %taxrates;
308   foreach my $tax (
309     qsearch('cust_main_county', {
310               country => $country,
311               tax => { op => '>', value => 0 }
312             }) )
313     {
314     $taxrates{$tax->taxnum} = $tax->tax;
315   }
316
317   # return the data
318   bless {
319     'opt'       => \%opt,
320     'data'      => \%data,
321     'total'     => \%total,
322     'taxrates'  => \%taxrates,
323   }, $class;
324 }
325
326 sub opt {
327   my $self = shift;
328   $self->{opt};
329 }
330
331 sub data {
332   my $self = shift;
333   $self->{data};
334 }
335
336 # sub fetchall_array...
337
338 sub table {
339   my $self = shift;
340   my @columns = (qw(pkgclass taxclass state county city district));
341   # taxnums, field headings, and amounts
342   my @rows;
343   my %row_template;
344
345   # de-treeify this thing
346   my $descend;
347   $descend = sub {
348     my ($tree, $level) = @_;
349     if ( ref($tree) eq 'HASH' ) {
350       foreach my $k ( sort {
351            -1*($b eq '')    # sort '' to the end
352           or  ($a eq '')    # sort '' to the end
353           or  ($a <=> $b)   # sort numbers as numbers
354           or  ($a cmp $b)   # sort alphabetics as alphabetics
355         } keys %$tree )
356       {
357         $row_template{ $columns[$level] } = $k;
358         &{ $descend }($tree->{$k}, $level + 1);
359         if ( $level == 0 ) {
360           # then insert the total row for the pkgclass
361           $row_template{'total'} = 1; # flag it as a total
362           &{ $descend }($self->{total}->{$k}, 1);
363           $row_template{'total'} = 0;
364         }
365       }
366     } elsif ( ref($tree) eq 'ARRAY' ) {
367       # then we've reached the bottom; elements of this array are arrayrefs
368       # of [ field, taxnums, amount ].
369       # start with the inherited location-element fields
370       my %this_row = %row_template;
371       my %taxnums;
372       foreach my $x (@$tree) {
373         # accumulate taxnums
374         foreach (split(',', $x->[1])) {
375           $taxnums{$_} = 1;
376         }
377         # and money values
378         $this_row{ $x->[0] } = $x->[2];
379       }
380       # store combined taxnums
381       $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
382       # and calculate row totals
383       $this_row{sales} = sprintf('%.2f',
384                           $this_row{taxable} +
385                           $this_row{exempt_cust} +
386                           $this_row{exempt_pkg} + 
387                           $this_row{exempt_monthly}
388                         );
389       # and give it a label
390       if ( $this_row{total} ) {
391         $this_row{label} = 'Total';
392       } else {
393         $this_row{label} = join(', ', grep $_,
394                             $this_row{taxclass},
395                             $this_row{state},
396                             $this_row{county}, # already has ' County' suffix
397                             $this_row{city},
398                             $this_row{district}
399                            );
400       }
401       # and indicate the tax rate, if any
402       my $rate;
403       foreach (keys %taxnums) {
404         $rate ||= $self->{taxrates}->{$_};
405         if ( $rate != $self->{taxrates}->{$_} ) {
406           $rate = 'variable';
407           last;
408         }
409       }
410       if ( $rate eq 'variable' ) {
411         $this_row{rate} = 'variable';
412       } elsif ( $rate > 0 ) {
413         $this_row{rate} = sprintf('%.2f', $rate);
414         $this_row{estimated} =
415           sprintf('%.2f', $this_row{taxable} * $rate / 100);
416       }
417       push @rows, \%this_row;
418     }
419   };
420
421   &{ $descend }($self->{data}, 0);
422
423   warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
424   return @rows;
425 }
426
427 sub taxrates {
428   my $self = shift;
429   $self->{taxrates}
430 }
431
432 sub title {
433   my $self = shift;
434   my $string = '';
435   if ( $self->{opt}->{agentnum} ) {
436     my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
437     $string .= $agent->agent . ' ';
438     warn $string;
439   }
440   $string .= 'Tax Report: '; # XXX localization
441   if ( $self->{opt}->{beginning} ) {
442     $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
443   }
444   $string .= 'through ';
445   if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
446     $string .= time2str('%h %o %Y', $self->{opt}->{ending});
447   } else {
448     $string .= 'now';
449   }
450   $string .= ' - ' . $self->{opt}->{taxname};
451   return $string;
452 }
453
454 1;