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 # 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]+)$/ ) {
49 die "taxname required"; # UI prevents this
52 if ( $opt{country} =~ /^(\w\w)$/ ) {
55 die "country required";
58 # %breakdown: short name => field identifier
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',
67 foreach (qw(taxclass pkgclass city district)) {
68 delete $breakdown{$_} unless $opt{breakdown}->{$_};
71 my $join_cust = ' JOIN cust_bill USING ( invnum )
72 LEFT JOIN cust_main USING ( custnum ) ';
74 my $join_cust_pkg = $join_cust.
75 ' LEFT JOIN cust_pkg USING ( pkgnum )
76 LEFT JOIN part_pkg USING ( pkgpart ) ';
78 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg ";
80 # all queries MUST be linked to both cust_bill and cust_main_county
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";
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
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";
98 # This just calculates the sum of credit applications to a line item.
99 my $pkg_credited = "SELECT SUM(amount) AS credited, billpkgnum ".
100 "FROM cust_credit_bill_pkg GROUP BY billpkgnum";
102 my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ".
103 "AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname' ".
104 "AND cust_main_county.country = '$country'";
105 # SELECT/GROUP clauses for first-level queries
106 my $select = "SELECT ";
107 my $group = "GROUP BY ";
108 foreach (qw(pkgclass taxclass state county city district)) {
109 if ( $breakdown{$_} ) {
110 $select .= "$breakdown{$_} AS $_, ";
111 $group .= "$breakdown{$_}, ";
113 $select .= "NULL AS $_, ";
116 $select .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
120 # SELECT/GROUP clauses for second-level (totals) queries
121 # breakdown by package class only, if anything
122 my $select_all = "SELECT NULL AS pkgclass, ";
124 if ( $breakdown{pkgclass} ) {
125 $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
126 $group_all = "GROUP BY $breakdown{pkgclass}";
128 $select_all .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
132 if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
134 my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
135 die "agent not found" unless $agent;
136 $where .= " AND cust_main.agentnum = $agentnum";
140 '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
142 # one query for each column of the report
143 # plus separate queries for the totals row
146 # SALES QUERIES (taxable sales, all types of exempt sales)
150 my $exempt = "$select SUM(exempt_charged)
151 FROM cust_main_county
152 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
154 JOIN cust_bill_pkg USING (billpkgnum)
155 $join_cust_pkg $where AND $nottax
158 my $all_exempt = "$select_all SUM(exempt_charged)
159 FROM cust_main_county
160 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
162 JOIN cust_bill_pkg USING (billpkgnum)
163 $join_cust_pkg $where AND $nottax
166 # sales to tax-exempt customers
167 $sql{exempt_cust} = $exempt;
168 $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
169 $all_sql{exempt_cust} = $all_exempt;
170 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
172 # sales of tax-exempt packages
173 $sql{exempt_pkg} = $exempt;
174 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
175 $all_sql{exempt_pkg} = $all_exempt;
176 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
178 # monthly per-customer exemptions
179 $sql{exempt_monthly} = $exempt;
180 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
181 $all_sql{exempt_monthly} = $all_exempt;
182 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
185 # (sale - exemptions - credits, except not negative)
186 $sql{taxable} = "$select
188 cust_bill_pkg.setup + cust_bill_pkg.recur
189 - COALESCE(exempt_charged, 0)
190 - COALESCE(credited, 0)
193 LEFT JOIN ($pkg_tax) AS pkg_tax
194 ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
195 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
196 ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
197 LEFT JOIN ($pkg_credited) AS pkg_credited
198 ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
199 LEFT JOIN cust_main_county
200 ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
201 $join_cust_pkg $where AND $nottax
204 $all_sql{taxable} = "$select_all
206 cust_bill_pkg.setup + cust_bill_pkg.recur
207 - COALESCE(exempt_charged, 0)
208 - COALESCE(credited, 0)
211 LEFT JOIN ($pkg_tax) AS pkg_tax
212 ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
213 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
214 ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
215 LEFT JOIN ($pkg_credited) AS pkg_credited
216 ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
217 LEFT JOIN cust_main_county
218 ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
219 $join_cust_pkg $where AND $nottax
222 $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
223 $all_sql{taxable} =~ s/EXEMPT_WHERE//;
225 # estimated tax (taxable * rate)
226 $sql{estimated} = "$select
227 SUM(cust_main_county.tax / 100 *
228 ( cust_bill_pkg.setup + cust_bill_pkg.recur
229 - COALESCE(exempt_charged, 0)
230 - COALESCE(credited, 0)
234 LEFT JOIN ($pkg_tax) AS pkg_tax
235 ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
236 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
237 ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
238 LEFT JOIN ($pkg_credited) AS pkg_credited
239 ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
240 LEFT JOIN cust_main_county
241 ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
242 $join_cust_pkg $where AND $nottax
245 $all_sql{estimated} = "$select_all
246 SUM(cust_main_county.tax / 100 *
247 ( cust_bill_pkg.setup + cust_bill_pkg.recur
248 - COALESCE(exempt_charged, 0)
249 - COALESCE(credited, 0)
253 LEFT JOIN ($pkg_tax) AS pkg_tax
254 ON (cust_bill_pkg.billpkgnum = pkg_tax.billpkgnum)
255 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
256 ON (cust_bill_pkg.billpkgnum = pkg_tax_exempt.billpkgnum)
257 LEFT JOIN ($pkg_credited) AS pkg_credited
258 ON (cust_bill_pkg.billpkgnum = pkg_credited.billpkgnum)
259 LEFT JOIN cust_main_county
260 ON (COALESCE(pkg_tax.taxnum, pkg_tax_exempt.taxnum) = cust_main_county.taxnum)
261 $join_cust_pkg $where AND $nottax
264 # there isn't one for 'sales', because we calculate sales by adding up
265 # the taxable and exempt columns.
267 # TAX QUERIES (billed tax, credited tax)
271 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
272 my $taxfrom = " FROM cust_bill_pkg
274 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
275 LEFT JOIN cust_main_county USING ( taxnum )";
277 if ( $breakdown{pkgclass} ) {
278 # If we're not grouping by package class, this is unnecessary, and
279 # probably really expensive.
281 LEFT JOIN cust_bill_pkg AS taxable
282 ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
283 LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
284 LEFT JOIN part_pkg USING (pkgpart)";
287 my $istax = "cust_bill_pkg.pkgnum = 0";
289 $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
294 $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
299 # sum of credits applied against billed tax
300 # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
302 my $creditfrom = $taxfrom .
303 ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
304 ' JOIN cust_credit_bill USING (creditbillnum)';
305 my $creditwhere = $where .
306 ' AND billpkgtaxratelocationnum IS NULL';
308 # if the credit_date option is set to application date, change
309 # $creditwhere accordingly
310 if ( $opt{credit_date} eq 'cust_credit_bill' ) {
311 $creditwhere =~ s/cust_bill._date/cust_credit_bill._date/g;
314 $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
316 $creditwhere AND $istax
319 $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
321 $creditwhere AND $istax
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;
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 > 1;
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'
397 SELECT 1 FROM cust_bill_pkg_tax_location
398 JOIN cust_main_county USING (taxnum)
399 WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
400 AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname'
403 warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
404 my $total_outside = FS::Record->scalar_sql($sql_outside);
408 qsearch('cust_main_county', {
410 tax => { op => '>', value => 0 }
413 $taxrates{$tax->taxnum} = $tax->tax;
421 'taxrates' => \%taxrates,
422 'outside' => $total_outside,
436 # sub fetchall_array...
440 my @columns = (qw(pkgclass taxclass state county city district));
441 # taxnums, field headings, and amounts
445 # de-treeify this thing
448 my ($tree, $level) = @_;
449 if ( ref($tree) eq 'HASH' ) {
450 foreach my $k ( sort {
451 -1*($b eq '') # sort '' to the end
452 or ($a eq '') # sort '' to the end
453 or ($a <=> $b) # sort numbers as numbers
454 or ($a cmp $b) # sort alphabetics as alphabetics
457 $row_template{ $columns[$level] } = $k;
458 &{ $descend }($tree->{$k}, $level + 1);
460 # then insert the total row for the pkgclass
461 $row_template{'total'} = 1; # flag it as a total
462 &{ $descend }($self->{total}->{$k}, 1);
463 $row_template{'total'} = 0;
466 } elsif ( ref($tree) eq 'ARRAY' ) {
467 # then we've reached the bottom; elements of this array are arrayrefs
468 # of [ field, taxnums, amount ].
469 # start with the inherited location-element fields
470 my %this_row = %row_template;
472 foreach my $x (@$tree) {
474 foreach (split(',', $x->[1])) {
478 $this_row{ $x->[0] } = $x->[2];
480 # store combined taxnums
481 $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
482 # and calculate row totals
483 $this_row{sales} = sprintf('%.2f',
485 $this_row{exempt_cust} +
486 $this_row{exempt_pkg} +
487 $this_row{exempt_monthly}
489 # and give it a label
490 if ( $this_row{total} ) {
491 $this_row{label} = 'Total';
493 $this_row{label} = join(', ', grep $_,
496 $this_row{county}, # already has ' County' suffix
501 # and indicate the tax rate, if any
503 foreach (keys %taxnums) {
504 $rate ||= $self->{taxrates}->{$_};
505 if ( $rate != $self->{taxrates}->{$_} ) {
510 if ( $rate eq 'variable' ) {
511 $this_row{rate} = 'variable';
512 } elsif ( $rate > 0 ) {
513 $this_row{rate} = sprintf('%.2f', $rate);
515 push @rows, \%this_row;
519 &{ $descend }($self->{data}, 0);
521 warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
533 if ( $self->{opt}->{agentnum} ) {
534 my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
535 $string .= $agent->agent . ' ';
537 $string .= 'Tax Report: '; # XXX localization
538 if ( $self->{opt}->{beginning} ) {
539 $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
541 $string .= 'through ';
542 if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
543 $string .= time2str('%h %o %Y', $self->{opt}->{ending});
547 $string .= ' - ' . $self->{opt}->{taxname};