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