1 package FS::Report::Tax;
5 use FS::Record qw(dbh qsearch qsearchs group_concat_sql);
6 use Date::Format qw( time2str );
12 =item report_internal OPTIONS
14 Constructor. Generates a tax report using the internal tax rate system
15 (L<FS::cust_main_county>).
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.
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.
36 $DEBUG ||= $opt{debug};
38 my $conf = new FS::Conf;
40 my($beginning, $ending) = @opt{'beginning', 'ending'};
42 my ($taxname, $country, %breakdown);
44 # taxname can contain arbitrary punctuation; escape it properly and
45 # include $taxname unquoted elsewhere
46 $taxname = dbh->quote($opt{'taxname'});
48 if ( $opt{country} =~ /^(\w\w)$/ ) {
51 die "country required";
54 # %breakdown: short name => field identifier
55 # null classnum should remain null, not be converted to zero
57 'taxclass' => 'cust_main_county.taxclass',
58 'pkgclass' => 'COALESCE(part_fee.classnum,part_pkg.classnum)',
59 'city' => 'cust_main_county.city',
60 'district' => 'cust_main_county.district',
61 'state' => 'cust_main_county.state',
62 'county' => 'cust_main_county.county',
64 foreach (qw(taxclass pkgclass city district)) {
65 delete $breakdown{$_} unless $opt{breakdown}->{$_};
68 my $join_cust = ' JOIN cust_bill USING ( invnum )
69 LEFT JOIN cust_main USING ( custnum ) ';
71 my $join_cust_pkg = $join_cust.
72 ' LEFT JOIN cust_pkg USING ( pkgnum )
73 LEFT JOIN part_pkg USING ( pkgpart )
74 LEFT JOIN part_fee USING ( feepart ) ';
76 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg ";
78 # all queries MUST be linked to both cust_bill and cust_main_county
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";
89 # This one links a tax-exempted line item (billpkgnum) to a tax rate
90 # (taxnum), and gives the amount of the tax exemption. EXEMPT_WHERE must
91 # be replaced with an expression to further limit the tax exemptions
92 # that will be included, or "TRUE" to not limit them.
94 # Note that tax exemptions with non-null creditbillpkgnum are always
95 # excluded. Those are "negative exemptions" created by crediting a sale
96 # that had received an exemption.
97 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
98 "FROM cust_tax_exempt_pkg WHERE
100 AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
101 GROUP BY billpkgnum, taxnum";
103 my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ".
104 "AND COALESCE(cust_main_county.taxname,'Tax') = $taxname ".
105 "AND cust_main_county.country = '$country'";
106 # SELECT/GROUP clauses for first-level queries
107 my $select = "SELECT ";
108 my $group = "GROUP BY ";
109 foreach (qw(pkgclass taxclass state county city district)) {
110 if ( $breakdown{$_} ) {
111 $select .= "$breakdown{$_} AS $_, ";
112 $group .= "$breakdown{$_}, ";
114 $select .= "NULL AS $_, ";
117 $select .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
121 # SELECT/GROUP clauses for second-level (totals) queries
122 # breakdown by package class only, if anything
123 my $select_all = "SELECT NULL AS pkgclass, ";
125 if ( $breakdown{pkgclass} ) {
126 $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
127 $group_all = "GROUP BY $breakdown{pkgclass}";
129 $select_all .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
133 if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
135 my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
136 die "agent not found" unless $agent;
137 $where .= " AND cust_main.agentnum = $agentnum";
141 '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
143 # one query for each column of the report
144 # plus separate queries for the totals row
147 # SALES QUERIES (taxable sales, all types of exempt sales)
151 my $exempt = "$select SUM(exempt_charged)
152 FROM cust_main_county
153 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
155 JOIN cust_bill_pkg USING (billpkgnum)
156 $join_cust_pkg $where AND $nottax
159 my $all_exempt = "$select_all SUM(exempt_charged)
160 FROM cust_main_county
161 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
163 JOIN cust_bill_pkg USING (billpkgnum)
164 $join_cust_pkg $where AND $nottax
167 # sales to tax-exempt customers
168 $sql{exempt_cust} = $exempt;
169 $sql{exempt_cust} =~ s/EXEMPT_WHERE/exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
170 $all_sql{exempt_cust} = $all_exempt;
171 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
173 # sales of tax-exempt packages
174 $sql{exempt_pkg} = $exempt;
175 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/exempt_setup = 'Y' OR exempt_recur = 'Y'/;
176 $all_sql{exempt_pkg} = $all_exempt;
177 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/exempt_setup = 'Y' OR exempt_recur = 'Y'/;
179 # monthly per-customer exemptions
180 $sql{exempt_monthly} = $exempt;
181 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/exempt_monthly = 'Y'/;
182 $all_sql{exempt_monthly} = $all_exempt;
183 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/exempt_monthly = 'Y'/;
186 $sql{taxable} = "$select
187 SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
188 FROM cust_main_county
189 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
190 JOIN cust_bill_pkg USING (billpkgnum)
191 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
192 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
193 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
194 $join_cust_pkg $where AND $nottax
197 $all_sql{taxable} = "$select_all
198 SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
199 FROM cust_main_county
200 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
201 JOIN cust_bill_pkg USING (billpkgnum)
202 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
203 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
204 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
205 $join_cust_pkg $where AND $nottax
208 $sql{taxable} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
209 $all_sql{taxable} =~ s/EXEMPT_WHERE/TRUE/;
211 # estimated tax (taxable * rate)
212 $sql{estimated} = "$select
213 SUM(cust_main_county.tax / 100 *
214 (cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
216 FROM cust_main_county
217 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
218 JOIN cust_bill_pkg USING (billpkgnum)
219 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
220 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
221 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
222 $join_cust_pkg $where AND $nottax
225 $all_sql{estimated} = "$select_all
226 SUM(cust_main_county.tax / 100 *
227 (cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
229 FROM cust_main_county
230 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
231 JOIN cust_bill_pkg USING (billpkgnum)
232 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
233 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
234 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
235 $join_cust_pkg $where AND $nottax
238 $sql{estimated} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
239 $all_sql{estimated} =~ s/EXEMPT_WHERE/TRUE/;
241 # there isn't one for 'sales', because we calculate sales by adding up
242 # the taxable and exempt columns.
244 # TAX QUERIES (billed tax, credited tax, collected tax)
248 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
249 my $taxfrom = " FROM cust_bill_pkg
251 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
252 LEFT JOIN cust_main_county USING ( taxnum )";
254 if ( $breakdown{pkgclass} ) {
255 # If we're not grouping by package class, this is unnecessary, and
256 # probably really expensive.
257 # Remember that fees also have package classes.
259 LEFT JOIN cust_bill_pkg AS taxable
260 ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
261 LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
262 LEFT JOIN part_pkg USING (pkgpart)
263 LEFT JOIN part_fee ON (taxable.feepart = part_fee.feepart) ";
266 my $istax = "cust_bill_pkg.pkgnum = 0 and cust_bill_pkg.feepart is null";
268 $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
273 $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
278 # sum of credits applied against billed tax
279 # ($creditfrom includes join of taxable item to part_pkg/part_fee if
280 # with_pkgclass 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';
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;
293 $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
295 $creditwhere AND $istax
298 $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
300 $creditwhere AND $istax
304 # this suffers from the same ambiguity as anything else that applies
305 # received payments to specific packages, but in reality the discrepancy
306 # should be minimal since people either pay their bill or don't.
307 # the join is on billpkgtaxlocationnum to avoid cross-producting.
309 my $paidfrom = $taxfrom .
310 ' JOIN cust_bill_pay_pkg'.
311 ' ON (cust_bill_pay_pkg.billpkgtaxlocationnum ='.
312 ' cust_bill_pkg_tax_location.billpkgtaxlocationnum)';
314 $sql{tax_paid} = "$select SUM(cust_bill_pay_pkg.amount)
319 $all_sql{tax_paid} = "$select_all SUM(cust_bill_pay_pkg.amount)
326 # note that we use keys(%sql) here and keys(%all_sql) later. nothing
327 # obligates us to use the same set of variables for the total query
328 # as for the individual category queries
329 foreach my $k (keys(%sql)) {
331 warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG > 1;
332 my $sth = dbh->prepare($stmt);
333 # eight columns: pkgclass, taxclass, state, county, city, district
334 # taxnums (comma separated), value
336 or die "failed to execute $k query: ".$sth->errstr;
337 while ( my $row = $sth->fetchrow_arrayref ) {
339 {$row->[0]} # pkgclass
340 {$row->[1] # taxclass
341 || ($breakdown{taxclass} ? 'Unclassified' : '')}
343 {$row->[3] ? $row->[3] . ' County' : ''} # county
345 {$row->[5]} # district
347 push @$bin, [ $k, $row->[6], $row->[7] ];
350 warn "DATA:\n".Dumper(\%data) if $DEBUG;
352 foreach my $k (keys %all_sql) {
353 warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
354 my $sth = dbh->prepare($all_sql{$k});
355 # three columns: pkgclass, taxnums (comma separated), value
357 or die "failed to execute $k totals query: ".$sth->errstr;
358 while ( my $row = $sth->fetchrow_arrayref ) {
359 my $bin = $total{$row->[0]} ||= [];
360 push @$bin, [ $k, $row->[1], $row->[2] ];
363 warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
365 # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
366 # [ 'taxable', taxnums, amount ],
367 # [ 'exempt_cust', taxnums, amount ],
370 # non-requested grouping levels simply collapse into key = ''
372 # the much-maligned "out of taxable region"...
373 # find sales that are not linked to any tax with this name
374 # but are still inside the date range/agent criteria.
376 # This doesn't use $select_all/$group_all because we want a single number,
377 # not a breakdown by pkgclass. Unless someone needs that eventually,
378 # in which case we'll turn it into an %all_sql query.
381 "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending";
383 $outside_where .= " AND cust_main.agentnum = $agentnum";
385 my $sql_outside = "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
391 SELECT 1 FROM cust_tax_exempt_pkg
392 JOIN cust_main_county USING (taxnum)
393 WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
394 AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
395 AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
398 SELECT 1 FROM cust_bill_pkg_tax_location
399 JOIN cust_main_county USING (taxnum)
400 WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
401 AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
404 warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
405 my $total_outside = FS::Record->scalar_sql($sql_outside);
409 qsearch('cust_main_county', {
411 tax => { op => '>', value => 0 }
414 $taxrates{$tax->taxnum} = $tax->tax;
422 'taxrates' => \%taxrates,
423 'outside' => $total_outside,
437 # sub fetchall_array...
441 my @columns = (qw(pkgclass taxclass state county city district));
442 # taxnums, field headings, and amounts
446 # de-treeify this thing
449 my ($tree, $level) = @_;
450 if ( ref($tree) eq 'HASH' ) {
451 foreach my $k ( sort {
452 -1*($b eq '') # sort '' to the end
453 or ($a eq '') # sort '' to the end
454 or ($a <=> $b) # sort numbers as numbers
455 or ($a cmp $b) # sort alphabetics as alphabetics
458 $row_template{ $columns[$level] } = $k;
459 &{ $descend }($tree->{$k}, $level + 1);
461 # then insert the total row for the pkgclass
462 $row_template{'total'} = 1; # flag it as a total
463 &{ $descend }($self->{total}->{$k}, 1);
464 $row_template{'total'} = 0;
467 } elsif ( ref($tree) eq 'ARRAY' ) {
468 # then we've reached the bottom; elements of this array are arrayrefs
469 # of [ field, taxnums, amount ].
470 # start with the inherited location-element fields
471 my %this_row = %row_template;
473 foreach my $x (@$tree) {
475 foreach (split(',', $x->[1])) {
479 $this_row{ $x->[0] } = $x->[2];
481 # store combined taxnums
482 $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
483 # and calculate row totals
484 $this_row{sales} = sprintf('%.2f',
486 $this_row{exempt_cust} +
487 $this_row{exempt_pkg} +
488 $this_row{exempt_monthly}
490 # and give it a label
491 if ( $this_row{total} ) {
492 $this_row{label} = 'Total';
494 $this_row{label} = join(', ', grep $_,
497 $this_row{county}, # already has ' County' suffix
502 # and indicate the tax rate, if any
504 foreach (keys %taxnums) {
505 $rate ||= $self->{taxrates}->{$_};
506 if ( $rate != $self->{taxrates}->{$_} ) {
511 if ( $rate eq 'variable' ) {
512 $this_row{rate} = 'variable';
513 } elsif ( $rate > 0 ) {
514 $this_row{rate} = sprintf('%.2f', $rate);
516 push @rows, \%this_row;
520 &{ $descend }($self->{data}, 0);
522 warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
534 if ( $self->{opt}->{agentnum} ) {
535 my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
536 $string .= $agent->agent . ' ';
538 $string .= 'Tax Report: '; # XXX localization
539 if ( $self->{opt}->{beginning} ) {
540 $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
542 $string .= 'through ';
543 if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
544 $string .= time2str('%h %o %Y', $self->{opt}->{ending});
548 $string .= ' - ' . $self->{opt}->{taxname};