1 package FS::Report::Tax;
5 use FS::Record qw(dbh qsearch qsearchs);
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 if ( $opt{taxname} =~ /^([\w\s]+)$/ ) {
47 die "taxname required"; # UI prevents this
50 if ( $opt{country} =~ /^(\w\w)$/ ) {
53 die "country required";
56 # %breakdown: short name => field identifier
58 'taxclass' => 'cust_main_county.taxclass',
59 'pkgclass' => 'part_pkg.classnum',
60 'city' => 'cust_main_county.city',
61 'district' => 'cust_main_county.district',
62 'state' => 'cust_main_county.state',
63 'county' => 'cust_main_county.county',
65 foreach (qw(taxclass pkgclass city district)) {
66 delete $breakdown{$_} unless $opt{breakdown}->{$_};
69 my $join_cust = ' JOIN cust_bill USING ( invnum )
70 LEFT JOIN cust_main USING ( custnum ) ';
72 my $join_cust_pkg = $join_cust.
73 ' LEFT JOIN cust_pkg USING ( pkgnum )
74 LEFT JOIN part_pkg USING ( pkgpart ) ';
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 (taxnum),
90 # and gives the amount of the tax exemption. EXEMPT_WHERE should be replaced
91 # with a real WHERE clause to further limit the tax exemptions that will be
93 my $pkg_tax_exempt = "SELECT SUM(amount) AS exempt_charged, billpkgnum, taxnum ".
94 "FROM cust_tax_exempt_pkg EXEMPT_WHERE GROUP BY billpkgnum, taxnum";
96 my $where = "WHERE cust_bill._date >= $beginning AND cust_bill._date <= $ending ".
97 "AND COALESCE(cust_main_county.taxname,'Tax') = '$taxname' ".
98 "AND cust_main_county.country = '$country'";
99 # SELECT/GROUP clauses for first-level queries
100 my $select = "SELECT ";
101 my $group = "GROUP BY ";
102 foreach (qw(pkgclass taxclass state county city district)) {
103 if ( $breakdown{$_} ) {
104 $select .= "$breakdown{$_} AS $_, ";
105 $group .= "$breakdown{$_}, ";
107 $select .= "NULL AS $_, ";
110 $select .= "array_to_string(array_agg(DISTINCT(cust_main_county.taxnum)), ',') AS taxnums, ";
113 # SELECT/GROUP clauses for second-level (totals) queries
114 # breakdown by package class only, if anything
115 my $select_all = "SELECT NULL AS pkgclass, ";
117 if ( $breakdown{pkgclass} ) {
118 $select_all = "SELECT $breakdown{pkgclass} AS pkgclass, ";
119 $group_all = "GROUP BY $breakdown{pkgclass}";
121 $select_all .= "array_to_string(array_agg(DISTINCT(cust_main_county.taxnum)), ',') AS taxnums, ";
124 if ( $opt{agentnum} and $opt{agentnum} =~ /^(\d+)$/ ) {
126 my $agent = qsearchs('agent', { 'agentnum' => $agentnum } );
127 die "agent not found" unless $agent;
128 $where .= " AND cust_main.agentnum = $agentnum";
132 '(cust_bill_pkg.pkgnum != 0 OR cust_bill_pkg.feepart IS NOT NULL)';
134 # one query for each column of the report
135 # plus separate queries for the totals row
138 # SALES QUERIES (taxable sales, all types of exempt sales)
142 my $exempt = "$select SUM(exempt_charged)
143 FROM cust_main_county
144 JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
146 JOIN cust_bill_pkg USING (billpkgnum)
147 $join_cust_pkg $where AND $nottax
150 my $all_exempt = "$select_all 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 # sales to tax-exempt customers
159 $sql{exempt_cust} = $exempt;
160 $sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
161 $all_sql{exempt_cust} = $all_exempt;
162 $all_sql{exempt_cust} =~ s/EXEMPT_WHERE/WHERE exempt_cust = 'Y' OR exempt_cust_taxname = 'Y'/;
164 # sales of tax-exempt packages
165 $sql{exempt_pkg} = $exempt;
166 $sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
167 $all_sql{exempt_pkg} = $all_exempt;
168 $all_sql{exempt_pkg} =~ s/EXEMPT_WHERE/WHERE exempt_setup = 'Y' OR exempt_recur = 'Y'/;
170 # monthly per-customer exemptions
171 $sql{exempt_monthly} = $exempt;
172 $sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
173 $all_sql{exempt_monthly} = $all_exempt;
174 $all_sql{exempt_monthly} =~ s/EXEMPT_WHERE/WHERE exempt_monthly = 'Y'/;
177 $sql{taxable} = "$select
178 SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - COALESCE(exempt_charged, 0))
179 FROM cust_main_county
180 JOIN ($pkg_tax) AS pkg_tax USING (taxnum)
181 JOIN cust_bill_pkg USING (billpkgnum)
182 LEFT JOIN ($pkg_tax_exempt) AS pkg_tax_exempt
183 ON (pkg_tax_exempt.billpkgnum = cust_bill_pkg.billpkgnum
184 AND pkg_tax_exempt.taxnum = cust_main_county.taxnum)
185 $join_cust_pkg $where AND $nottax
188 $all_sql{taxable} = "$select_all
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 $sql{taxable} =~ s/EXEMPT_WHERE//; # unrestricted
200 $all_sql{taxable} =~ s/EXEMPT_WHERE//;
202 # there isn't one for 'sales', because we calculate sales by adding up
203 # the taxable and exempt columns.
205 # TAX QUERIES (billed tax, credited tax)
209 # join cust_bill_pkg to cust_main_county via cust_bill_pkg_tax_location
210 my $taxfrom = " FROM cust_bill_pkg
212 LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
213 LEFT JOIN cust_main_county USING ( taxnum )";
215 if ( $breakdown{pkgclass} ) {
216 # If we're not grouping by package class, this is unnecessary, and
217 # probably really expensive.
219 LEFT JOIN cust_bill_pkg AS taxable
220 ON (cust_bill_pkg_tax_location.taxable_billpkgnum = taxable.billpkgnum)
221 LEFT JOIN cust_pkg ON (taxable.pkgnum = cust_pkg.pkgnum)
222 LEFT JOIN part_pkg USING (pkgpart)";
225 my $istax = "cust_bill_pkg.pkgnum = 0";
227 $sql{tax} = "$select SUM(cust_bill_pkg_tax_location.amount)
232 $all_sql{tax} = "$select_all SUM(cust_bill_pkg_tax_location.amount)
237 # sum of credits applied against billed tax
238 # ($creditfrom includes join of taxable item to part_pkg if with_pkgclass
240 my $creditfrom = $taxfrom .
241 ' JOIN cust_credit_bill_pkg USING (billpkgtaxlocationnum)' .
242 ' JOIN cust_credit_bill USING (creditbillnum)';
243 my $creditwhere = $where .
244 ' AND billpkgtaxratelocationnum IS NULL';
246 # if the credit_date option is set to application date, change
247 # $creditwhere accordingly
248 if ( $opt{credit_date} eq 'cust_credit_bill' ) {
249 $creditwhere =~ s/cust_bill._date/cust_credit_bill._date/g;
252 $sql{credit} = "$select SUM(cust_credit_bill_pkg.amount)
254 $creditwhere AND $istax
257 $all_sql{credit} = "$select_all SUM(cust_credit_bill_pkg.amount)
259 $creditwhere AND $istax
264 foreach my $k (keys(%sql)) {
266 warn "\n".uc($k).":\n".$stmt."\n" if $DEBUG;
267 my $sth = dbh->prepare($stmt);
268 # eight columns: pkgclass, taxclass, state, county, city, district
269 # taxnums (comma separated), value
271 or die "failed to execute $k query: ".$sth->errstr;
272 while ( my $row = $sth->fetchrow_arrayref ) {
274 {$row->[0]} # pkgclass
275 {$row->[1] # taxclass
276 || ($breakdown{taxclass} ? 'Unclassified' : '')}
278 {$row->[3] ? $row->[3] . ' County' : ''} # county
280 {$row->[5]} # district
282 push @$bin, [ $k, $row->[6], $row->[7] ];
285 warn "DATA:\n".Dumper(\%data) if $DEBUG > 1;
287 foreach my $k (keys %all_sql) {
288 warn "\nTOTAL ".uc($k).":\n".$all_sql{$k}."\n" if $DEBUG;
289 my $sth = dbh->prepare($all_sql{$k});
290 # three columns: pkgclass, taxnums (comma separated), value
292 or die "failed to execute $k totals query: ".$sth->errstr;
293 while ( my $row = $sth->fetchrow_arrayref ) {
294 my $bin = $total{$row->[0]} ||= [];
295 push @$bin, [ $k, $row->[1], $row->[2] ];
298 warn "TOTALS:\n".Dumper(\%total) if $DEBUG > 1;
300 # $data{$pkgclass}{$taxclass}{$state}{$county}{$city}{$district} = [
301 # [ 'taxable', taxnums, amount ],
302 # [ 'exempt_cust', taxnums, amount ],
305 # non-requested grouping levels simply collapse into key = ''
309 qsearch('cust_main_county', {
311 tax => { op => '>', value => 0 }
314 $taxrates{$tax->taxnum} = $tax->tax;
322 'taxrates' => \%taxrates,
336 # sub fetchall_array...
340 my @columns = (qw(pkgclass taxclass state county city district));
341 # taxnums, field headings, and amounts
345 # de-treeify this thing
348 my ($tree, $level) = @_;
349 if ( ref($tree) eq 'HASH' ) {
350 foreach my $k ( sort {
351 -1*($b eq '') # sort '' to the end
352 or ($a eq '') # sort '' to the end
353 or ($a <=> $b) # sort numbers as numbers
354 or ($a cmp $b) # sort alphabetics as alphabetics
357 $row_template{ $columns[$level] } = $k;
358 &{ $descend }($tree->{$k}, $level + 1);
360 # then insert the total row for the pkgclass
361 $row_template{'total'} = 1; # flag it as a total
362 &{ $descend }($self->{total}->{$k}, 1);
363 $row_template{'total'} = 0;
366 } elsif ( ref($tree) eq 'ARRAY' ) {
367 # then we've reached the bottom; elements of this array are arrayrefs
368 # of [ field, taxnums, amount ].
369 # start with the inherited location-element fields
370 my %this_row = %row_template;
372 foreach my $x (@$tree) {
374 foreach (split(',', $x->[1])) {
378 $this_row{ $x->[0] } = $x->[2];
380 # store combined taxnums
381 $this_row{taxnums} = join(',', sort { $a cmp $b } keys %taxnums);
382 # and calculate row totals
383 $this_row{sales} = sprintf('%.2f',
385 $this_row{exempt_cust} +
386 $this_row{exempt_pkg} +
387 $this_row{exempt_monthly}
389 # and give it a label
390 if ( $this_row{total} ) {
391 $this_row{label} = 'Total';
393 $this_row{label} = join(', ', grep $_,
396 $this_row{county}, # already has ' County' suffix
401 # and indicate the tax rate, if any
403 foreach (keys %taxnums) {
404 $rate ||= $self->{taxrates}->{$_};
405 if ( $rate != $self->{taxrates}->{$_} ) {
410 if ( $rate eq 'variable' ) {
411 $this_row{rate} = 'variable';
412 } elsif ( $rate > 0 ) {
413 $this_row{rate} = sprintf('%.2f', $rate);
414 $this_row{estimated} =
415 sprintf('%.2f', $this_row{taxable} * $rate / 100);
417 push @rows, \%this_row;
421 &{ $descend }($self->{data}, 0);
423 warn "TABLE:\n".Dumper(\@rows) if $self->{opt}->{debug};
435 if ( $self->{opt}->{agentnum} ) {
436 my $agent = qsearchs('agent', { agentnum => $self->{opt}->{agentnum} });
437 $string .= $agent->agent . ' ';
440 $string .= 'Tax Report: '; # XXX localization
441 if ( $self->{opt}->{beginning} ) {
442 $string .= time2str('%h %o %Y ', $self->{opt}->{beginning});
444 $string .= 'through ';
445 if ( $self->{opt}->{ending} and $self->{opt}->{ending} < 4294967295 ) {
446 $string .= time2str('%h %o %Y', $self->{opt}->{ending});
450 $string .= ' - ' . $self->{opt}->{taxname};