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
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.
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
102 AND cust_tax_exempt_pkg.creditbillpkgnum IS NULL
103 GROUP BY billpkgnum, taxnum";
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{$_}, ";
116 $select .= "NULL AS $_, ";
119 $select .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
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, ";
127 if ( $breakdown{pkgclass} ) {
128 $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
129 $group_all = "GROUP BY $breakdown{pkgclass}";
131 $select_all .= group_concat_sql('DISTINCT(cust_main_county.taxnum)', ',') .
135 if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
137 my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
138 die "agent not found" unless $agent;
139 $where .= " AND cust_main.agentnum = $agentnum";
143 '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
145 # one query for each column of the report
146 # plus separate queries for the totals row
149 # SALES QUERIES (taxable sales, all types of exempt sales)
153 my $exempt = "$select SUM(exempt_charged)
154 FROM cust_main_county
155 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
157 JOIN cust_bill_pkg USING (billpkgnum)
158 $join_cust_pkg $where AND $nottax
161 my $all_exempt = "$select_all SUM(exempt_charged)
162 FROM cust_main_county
163 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
165 JOIN cust_bill_pkg USING (billpkgnum)
166 $join_cust_pkg $where AND $nottax
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'/;
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'/;
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'/;
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
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
210 $sql{taxable} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
211 $all_sql{taxable} =~ s/EXEMPT_WHERE/TRUE/;
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))
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
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))
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
240 $sql{estimated} =~ s/EXEMPT_WHERE/TRUE/; # unrestricted
241 $all_sql{estimated} =~ s/EXEMPT_WHERE/TRUE/;
243 # there isn't one for 'sales', because we calculate sales by adding up
244 # the taxable and exempt columns.
246 # TAX QUERIES (billed tax, credited tax)
250 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
251 my $taxfrom = " FROM cust_bill_pkg
253 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
254 LEFT JOIN cust_main_county USING ( taxnum )";
256 if ( $breakdown{pkgclass} ) {
257 # If we're not grouping by package class, this is unnecessary, and
258 # probably really expensive.
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)";
266 my $istax = "cust_bill_pkg.pkgnum = 0";
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 if with_pkgclass
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
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)) {
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
315 or die "failed to execute $k query: ".$sth->errstr;
316 while ( my $row = $sth->fetchrow_arrayref ) {
318 {$row->[0]} # pkgclass
319 {$row->[1] # taxclass
320 || ($breakdown{taxclass} ? 'Unclassified' : '')}
322 {$row->[3] ? $row->[3] . ' County' : ''} # county
324 {$row->[5]} # district
326 push @$bin, [ $k, $row->[6], $row->[7] ];
329 warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
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
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] ];
342 warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
344 # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
345 # [ 'taxable', taxnums, amount ],
346 # [ 'exempt_cust', taxnums, amount ],
349 # non-requested grouping levels simply collapse into key = ''
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.
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.
360 "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending";
362 $outside_where .= " AND cust_main.agentnum = $agentnum";
364 my $sql_outside = "SELECT SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)
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
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'
383 warn "\nOUTSIDE:\n$sql_outside\n" if $DEBUG;
384 my $total_outside = FS::Record->scalar_sql($sql_outside);
388 qsearch('cust_main_county', {
390 tax => { op => '>', value => 0 }
393 $taxrates{$tax->taxnum} = $tax->tax;
401 'taxrates' => \%taxrates,
402 'outside' => $total_outside,
416 # sub fetchall_array...
420 my @columns = (qw(pkgclass taxclass state county city district));
421 # taxnums, field headings, and amounts
425 # de-treeify this thing
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
437 $row_template{ $columns[$level] } = $k;
438 &{ $descend }($tree->{$k}, $level + 1);
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;
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;
452 foreach my $x (@$tree) {
454 foreach (split(',', $x->[1])) {
458 $this_row{ $x->[0] } = $x->[2];
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',
465 $this_row{exempt_cust} +
466 $this_row{exempt_pkg} +
467 $this_row{exempt_monthly}
469 # and give it a label
470 if ( $this_row{total} ) {
471 $this_row{label} = 'Total';
473 $this_row{label} = join(', ', grep $_,
476 $this_row{county}, # already has ' County' suffix
481 # and indicate the tax rate, if any
483 foreach (keys %taxnums) {
484 $rate ||= $self->{taxrates}->{$_};
485 if ( $rate != $self->{taxrates}->{$_} ) {
490 if ( $rate eq 'variable' ) {
491 $this_row{rate} = 'variable';
492 } elsif ( $rate > 0 ) {
493 $this_row{rate} = sprintf('%.2f', $rate);
495 push @rows, \%this_row;
499 &{ $descend }($self->{data}, 0);
501 warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
513 if ( $self->{opt}->{agentnum} ) {
514 my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
515 $string .= $agent->agent . ' ';
517 $string .= 'Tax Report: '; # XXX localization
518 if ( $self->{opt}->{beginning} ) {
519 $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
521 $string .= 'through ';
522 if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
523 $string .= time2str('%h %o %Y', $self->{opt}->{ending});
527 $string .= ' - ' . $self->{opt}->{taxname};