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