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
56 'taxclass' => 'cust_main_county.taxclass',
57 'pkgclass' => 'part_pkg.classnum',
58 'city' => 'cust_main_county.city',
59 'district' => 'cust_main_county.district',
60 'state' => 'cust_main_county.state',
61 'county' => 'cust_main_county.county',
63 foreach (qw(taxclass pkgclass city district)) {
64 delete $breakdown{$_} unless $opt{breakdown}->{$_};
67 my $join_cust = ' JOIN cust_bill USING ( invnum )
68 LEFT JOIN cust_main USING ( custnum ) ';
70 my $join_cust_pkg = $join_cust.
71 ' LEFT JOIN cust_pkg USING ( pkgnum )
72 LEFT JOIN part_pkg USING ( pkgpart ) ';
74 my $from_join_cust_pkg = " FROM cust_bill_pkg $join_cust_pkg ";
76 # all queries MUST be linked to both cust_bill and cust_main_county
78 # Either or both of these can be used to link cust_bill_pkg to
79 # cust_main_county. This one links a taxed line item (billpkgnum) to a tax rate
80 # (taxnum), and gives the amount of tax charged on that line item under that
81 # rate (as tax_amount).
82 my $pkg_tax = "SELECT SUM(amount) as tax_amount, taxnum, ".
83 "taxable_billpkgnum AS billpkgnum ".
84 "FROM cust_bill_pkg_tax_location JOIN cust_bill_pkg USING (billpkgnum) ".
85 "GROUP BY taxable_billpkgnum, taxnum";
87 # This one links a tax-exempted line item (billpkgnum) to a tax rate
88 # (taxnum), and gives the amount of the tax exemption. EXEMPT_WHERE must
89 # be replaced with an expression to further limit the tax exemptions
90 # that will be included, or "TRUE" to not limit them.
92 # Note that tax exemptions with non-null creditbillpkgnum are always
93 # excluded. Those are "negative exemptions" created by crediting a sale
94 # that had received an exemption.
95 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
96 "FROM cust_tax_exempt_pkg WHERE
98 AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
99 GROUP BY billpkgnum, taxnum";
101 my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ".
102 "AND COALESCE(cust_main_county.taxname,'Tax') = $taxname ".
103 "AND cust_main_county.country = '$country'";
104 # SELECT/GROUP clauses for first-level queries
105 my $select = "SELECT ";
106 my $group = "GROUP BY ";
107 foreach (qw(pkgclass taxclass state county city district)) {
108 if ( $breakdown{$_} ) {
109 $select .= "$breakdown{$_} AS $_, ";
110 $group .= "$breakdown{$_}, ";
112 $select .= "NULL AS $_, ";
115 $select .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
119 # SELECT/GROUP clauses for second-level (totals) queries
120 # breakdown by package class only, if anything
121 my $select_all = "SELECT NULL AS pkgclass, ";
123 if ( $breakdown{pkgclass} ) {
124 $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
125 $group_all = "GROUP BY $breakdown{pkgclass}";
127 $select_all .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
131 if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
133 my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
134 die "agent not found" unless $agent;
135 $where .= " AND cust_main.agentnum = $agentnum";
139 '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
141 # one query for each column of the report
142 # plus separate queries for the totals row
145 # SALES QUERIES (taxable sales, all types of exempt sales)
149 my $exempt = "$select SUM(exempt_charged)
150 FROM cust_main_county
151 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
153 JOIN cust_bill_pkg USING (billpkgnum)
154 $join_cust_pkg $where AND $nottax
157 my $all_exempt = "$select_all SUM(exempt_charged)
158 FROM cust_main_county
159 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
161 JOIN cust_bill_pkg USING (billpkgnum)
162 $join_cust_pkg $where AND $nottax
165 # sales to tax-exempt customers
166 $sql{exempt_cust} = $exempt;
167 $sql{exempt_cust} =~ s/EXEMPT_WHERE/exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
168 $all_sql{exempt_cust} = $all_exempt;
169 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
171 # sales of tax-exempt packages
172 $sql{exempt_pkg} = $exempt;
173 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/exempt_setup = 'Y' OR exempt_recur = 'Y'/;
174 $all_sql{exempt_pkg} = $all_exempt;
175 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/exempt_setup = 'Y' OR exempt_recur = 'Y'/;
177 # monthly per-customer exemptions
178 $sql{exempt_monthly} = $exempt;
179 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/exempt_monthly = 'Y'/;
180 $all_sql{exempt_monthly} = $all_exempt;
181 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/exempt_monthly = 'Y'/;
184 $sql{taxable} = "$select
185 SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
186 FROM cust_main_county
187 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
188 JOIN cust_bill_pkg USING (billpkgnum)
189 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
190 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
191 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
192 $join_cust_pkg $where AND $nottax
195 $all_sql{taxable} = "$select_all
196 SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
197 FROM cust_main_county
198 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
199 JOIN cust_bill_pkg USING (billpkgnum)
200 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
201 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
202 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
203 $join_cust_pkg $where AND $nottax
206 $sql{taxable} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
207 $all_sql{taxable} =~ s/EXEMPT_WHERE/TRUE/;
209 # estimated tax (taxable * rate)
210 $sql{estimated} = "$select
211 SUM(cust_main_county.tax / 100 *
212 (cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
214 FROM cust_main_county
215 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
216 JOIN cust_bill_pkg USING (billpkgnum)
217 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
218 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
219 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
220 $join_cust_pkg $where AND $nottax
223 $all_sql{estimated} = "$select_all
224 SUM(cust_main_county.tax / 100 *
225 (cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
227 FROM cust_main_county
228 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
229 JOIN cust_bill_pkg USING (billpkgnum)
230 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
231 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
232 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
233 $join_cust_pkg $where AND $nottax
236 $sql{estimated} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
237 $all_sql{estimated} =~ s/EXEMPT_WHERE/TRUE/;
239 # there isn't one for 'sales', because we calculate sales by adding up
240 # the taxable and exempt columns.
242 # TAX QUERIES (billed tax, credited tax)
246 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
247 my $taxfrom = " FROM cust_bill_pkg
249 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
250 LEFT JOIN cust_main_county USING ( taxnum )";
252 if ( $breakdown{pkgclass} ) {
253 # If we're not grouping by package class, this is unnecessary, and
254 # probably really expensive.
256 LEFT JOIN cust_bill_pkg AS taxable
257 ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
258 LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
259 LEFT JOIN part_pkg USING (pkgpart)";
262 my $istax = "cust_bill_pkg.pkgnum = 0";
264 $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
269 $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
274 # sum of credits applied against billed tax
275 # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
277 my $creditfrom = $taxfrom .
278 ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
279 ' JOIN cust_credit_bill USING (creditbillnum)';
280 my $creditwhere = $where .
281 ' AND billpkgtaxratelocationnum IS NULL';
283 # if the credit_date option is set to application date, change
284 # $creditwhere accordingly
285 if ( $opt{credit_date} eq 'cust_credit_bill' ) {
286 $creditwhere =~ s/cust_bill._date/cust_credit_bill._date/g;
289 $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
291 $creditwhere AND $istax
294 $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
296 $creditwhere AND $istax
301 # note that we use keys(%sql) here and keys(%all_sql) later. nothing
302 # obligates us to use the same set of variables for the total query
303 # as for the individual category queries
304 foreach my $k (keys(%sql)) {
306 warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
307 my $sth = dbh->prepare($stmt);
308 # eight columns: pkgclass, taxclass, state, county, city, district
309 # taxnums (comma separated), value
311 or die "failed to execute $k query: ".$sth->errstr;
312 while ( my $row = $sth->fetchrow_arrayref ) {
314 {$row->[0]} # pkgclass
315 {$row->[1] # taxclass
316 || ($breakdown{taxclass} ? 'Unclassified' : '')}
318 {$row->[3] ? $row->[3] . ' County' : ''} # county
320 {$row->[5]} # district
322 push @$bin, [ $k, $row->[6], $row->[7] ];
325 warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
327 foreach my $k (keys %all_sql) {
328 warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
329 my $sth = dbh->prepare($all_sql{$k});
330 # three columns: pkgclass, taxnums (comma separated), value
332 or die "failed to execute $k totals query: ".$sth->errstr;
333 while ( my $row = $sth->fetchrow_arrayref ) {
334 my $bin = $total{$row->[0]} ||= [];
335 push @$bin, [ $k, $row->[1], $row->[2] ];
338 warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
340 # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
341 # [ 'taxable', taxnums, amount ],
342 # [ 'exempt_cust', taxnums, amount ],
345 # non-requested grouping levels simply collapse into key = ''
347 # the much-maligned "out of taxable region"...
348 # find sales that are not linked to any tax with this name
349 # but are still inside the date range/agent criteria.
351 # This doesn't use $select_all/$group_all because we want a single number,
352 # not a breakdown by pkgclass. Unless someone needs that eventually,
353 # in which case we'll turn it into an %all_sql query.
356 "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending";
358 $outside_where .= " AND cust_main.agentnum = $agentnum";
360 my $sql_outside = "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
366 SELECT 1 FROM cust_tax_exempt_pkg
367 JOIN cust_main_county USING (taxnum)
368 WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
369 AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
370 AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
373 SELECT 1 FROM cust_bill_pkg_tax_location
374 JOIN cust_main_county USING (taxnum)
375 WHERE cust_bill_pkg_tax_location.taxable_billpkgnum = cust_bill_pkg.billpkgnum
376 AND COALESCE(cust_main_county.taxname,'Tax') = $taxname
379 warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
380 my $total_outside = FS::Record->scalar_sql($sql_outside);
384 qsearch('cust_main_county', {
386 tax => { op => '>', value => 0 }
389 $taxrates{$tax->taxnum} = $tax->tax;
397 'taxrates' => \%taxrates,
398 'outside' => $total_outside,
412 # sub fetchall_array...
416 my @columns = (qw(pkgclass taxclass state county city district));
417 # taxnums, field headings, and amounts
421 # de-treeify this thing
424 my ($tree, $level) = @_;
425 if ( ref($tree) eq 'HASH' ) {
426 foreach my $k ( sort {
427 -1*($b eq '') # sort '' to the end
428 or ($a eq '') # sort '' to the end
429 or ($a <=> $b) # sort numbers as numbers
430 or ($a cmp $b) # sort alphabetics as alphabetics
433 $row_template{ $columns[$level] } = $k;
434 &{ $descend }($tree->{$k}, $level + 1);
436 # then insert the total row for the pkgclass
437 $row_template{'total'} = 1; # flag it as a total
438 &{ $descend }($self->{total}->{$k}, 1);
439 $row_template{'total'} = 0;
442 } elsif ( ref($tree) eq 'ARRAY' ) {
443 # then we've reached the bottom; elements of this array are arrayrefs
444 # of [ field, taxnums, amount ].
445 # start with the inherited location-element fields
446 my %this_row = %row_template;
448 foreach my $x (@$tree) {
450 foreach (split(',', $x->[1])) {
454 $this_row{ $x->[0] } = $x->[2];
456 # store combined taxnums
457 $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
458 # and calculate row totals
459 $this_row{sales} = sprintf('%.2f',
461 $this_row{exempt_cust} +
462 $this_row{exempt_pkg} +
463 $this_row{exempt_monthly}
465 # and give it a label
466 if ( $this_row{total} ) {
467 $this_row{label} = 'Total';
469 $this_row{label} = join(', ', grep $_,
472 $this_row{county}, # already has ' County' suffix
477 # and indicate the tax rate, if any
479 foreach (keys %taxnums) {
480 $rate ||= $self->{taxrates}->{$_};
481 if ( $rate != $self->{taxrates}->{$_} ) {
486 if ( $rate eq 'variable' ) {
487 $this_row{rate} = 'variable';
488 } elsif ( $rate > 0 ) {
489 $this_row{rate} = sprintf('%.2f', $rate);
491 push @rows, \%this_row;
495 &{ $descend }($self->{data}, 0);
497 warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
509 if ( $self->{opt}->{agentnum} ) {
510 my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
511 $string .= $agent->agent . ' ';
513 $string .= 'Tax Report: '; # XXX localization
514 if ( $self->{opt}->{beginning} ) {
515 $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
517 $string .= 'through ';
518 if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
519 $string .= time2str('%h %o %Y', $self->{opt}->{ending});
523 $string .= ' - ' . $self->{opt}->{taxname};