fix internal handling of monthly tax exemptions, from #34223
[freeside.git] / FS / FS / TaxEngine / internal.pm
1 package FS::TaxEngine::internal;
2
3 use strict;
4 use base 'FS::TaxEngine';
5 use FS::Record qw(dbh qsearch qsearchs);
6 use FS::Conf;
7 use vars qw( $conf );
8
9 FS::UID->install_callback(sub {
10     $conf = FS::Conf->new;
11 });
12
13 =head1 SUMMARY
14
15 FS::TaxEngine::internal: the classic Freeside "internal tax engine".
16 Uses tax rates and localities defined in L<FS::cust_main_county>.
17
18 =cut
19
20 my %part_pkg_cache;
21
22 sub add_sale {
23   my ($self, $cust_bill_pkg) = @_;
24
25   my $part_item = $cust_bill_pkg->part_X;
26   my $location = $cust_bill_pkg->tax_location;
27   my $custnum = $self->{cust_main}->custnum;
28
29   push @{ $self->{items} }, $cust_bill_pkg;
30
31   my @loc_keys = qw( district city county state country );
32   my %taxhash = map { $_ => $location->get($_) } @loc_keys;
33
34   $taxhash{'taxclass'} = $part_item->taxclass;
35
36   my @taxes = (); # entries are cust_main_county objects
37   my %taxhash_elim = %taxhash;
38   my @elim = qw( district city county state );
39   do {
40
41     #first try a match with taxclass
42     @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
43
44     if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
45       #then try a match without taxclass
46       my %no_taxclass = %taxhash_elim;
47       $no_taxclass{ 'taxclass' } = '';
48       @taxes = qsearch( 'cust_main_county', \%no_taxclass );
49     }
50
51     $taxhash_elim{ shift(@elim) } = '';
52   } while ( !scalar(@taxes) && scalar(@elim) );
53
54   foreach my $tax (@taxes) {
55     my $taxnum = $tax->taxnum;
56     $self->{taxes}->{$taxnum} ||= [ $tax ];
57     $cust_bill_pkg->set_exemptions( $tax, 'custnum' => $custnum );
58     push @{ $self->{taxes}->{$taxnum} }, $cust_bill_pkg;
59   }
60 }
61
62 sub taxline {
63   my ($self, %opt) = @_;
64   my $tax_object = $opt{tax};
65   my $taxables = $opt{sales};
66   my $taxnum = $tax_object->taxnum;
67   my $exemptions = $self->{exemptions}->{$taxnum} ||= [];
68   
69   my $taxable_cents = 0;
70   my $tax_cents = 0;
71
72   my $round_per_line_item = $conf->exists('tax-round_per_line_item');
73
74   my $cust_main = $self->{cust_main};
75   my $custnum   = $cust_main->custnum;
76   my $invoice_time = $self->{invoice_time};
77
78   # set a flag if the customer is tax-exempt
79   my $exempt_cust;
80   my $conf = FS::Conf->new;
81   if ( $conf->exists('cust_class-tax_exempt') ) {
82     my $cust_class = $cust_main->cust_class;
83     $exempt_cust = $cust_class->tax if $cust_class;
84   } else {
85     $exempt_cust = $cust_main->tax;
86   }
87   # set a flag if the customer is exempt from this tax here
88   my $exempt_cust_taxname = $cust_main->tax_exemption($tax_object->taxname)
89     if $tax_object->taxname;
90
91   # Gather any exemptions that are already attached to these cust_bill_pkgs
92   # so that we can deduct them from the customer's monthly limit.
93   my @existing_exemptions = @{ $exemptions };
94   push @existing_exemptions, @{ $_->cust_tax_exempt_pkg }
95     foreach @$taxables;
96
97   my @tax_links;
98
99   foreach my $cust_bill_pkg (@$taxables) {
100
101     my $cust_pkg  = $cust_bill_pkg->cust_pkg;
102     my $part_pkg  = $cust_bill_pkg->part_pkg;
103     my @new_exemptions;
104     my $taxable_charged = $cust_bill_pkg->setup + $cust_bill_pkg->recur
105       or next; # don't create zero-amount exemptions
106
107     # XXX the following procedure should probably be in cust_bill_pkg
108
109     if ( $exempt_cust ) {
110
111       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
112           amount => $taxable_charged,
113           exempt_cust => 'Y',
114         });
115       $taxable_charged = 0;
116
117     } elsif ( $exempt_cust_taxname ) {
118
119       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
120           amount => $taxable_charged,
121           exempt_cust_taxname => 'Y',
122         });
123       $taxable_charged = 0;
124
125     }
126
127     if ( ($part_pkg->setuptax eq 'Y' or $tax_object->setuptax eq 'Y')
128         and $cust_bill_pkg->setup > 0 and $taxable_charged > 0 ) {
129
130       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
131           amount => $cust_bill_pkg->setup,
132           exempt_setup => 'Y'
133       });
134       $taxable_charged -= $cust_bill_pkg->setup;
135
136     }
137     if ( ($part_pkg->recurtax eq 'Y' or $tax_object->recurtax eq 'Y')
138         and $cust_bill_pkg->recur > 0 and $taxable_charged > 0 ) {
139
140       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
141           amount => $cust_bill_pkg->recur,
142           exempt_recur => 'Y'
143       });
144        $taxable_charged -= $cust_bill_pkg->recur;
145
146     }
147
148     if ( $tax_object->exempt_amount && $tax_object->exempt_amount > 0
149       and $taxable_charged > 0 ) {
150       # If the billing period extends across multiple calendar months, 
151       # there may be several months of exemption available.
152       my $sdate = $cust_bill_pkg->sdate || $invoice_time;
153       my $start_month = (localtime($sdate))[4] + 1;
154       my $start_year  = (localtime($sdate))[5] + 1900;
155       my $edate = $cust_bill_pkg->edate || $invoice_time;
156       my $end_month   = (localtime($edate))[4] + 1;
157       my $end_year    = (localtime($edate))[5] + 1900;
158
159       # If the partial last month + partial first month <= one month,
160       # don't use the exemption in the last month
161       # (unless the last month is also the first month, e.g. one-time
162       # charges)
163       if ( (localtime($sdate))[3] >= (localtime($edate))[3]
164            and ($start_month != $end_month or $start_year != $end_year)
165      ) {
166         $end_month--;
167         if ( $end_month == 0 ) {
168           $end_year--;
169           $end_month = 12;
170         }
171       }
172
173       # number of months of exemption available
174       my $freq = ($end_month - $start_month) +
175                  ($end_year  - $start_year) * 12 +
176                  1;
177
178       # divide equally among all of them
179       my $permonth = sprintf('%.2f', $taxable_charged / $freq);
180
181       #call the whole thing off if this customer has any old
182       #exemption records...
183       my @cust_tax_exempt =
184         qsearch( 'cust_tax_exempt' => { custnum=> $custnum } );
185       if ( @cust_tax_exempt ) {
186         return
187           'this customer still has old-style tax exemption records; '.
188           'run bin/fs-migrate-cust_tax_exempt?';
189       }
190
191       my ($mon, $year) = ($start_month, $start_year);
192       while ($taxable_charged > 0.005 and
193              ($year < $end_year or
194                ($year == $end_year and $mon <= $end_month)
195              )
196       ) {
197
198         # find the sum of the exemption used by this customer, for this tax,
199         # in this month
200         my $sql = "
201           SELECT SUM(amount)
202             FROM cust_tax_exempt_pkg
203               LEFT JOIN cust_bill_pkg USING ( billpkgnum )
204               LEFT JOIN cust_bill     USING ( invnum     )
205             WHERE custnum = ?
206              AND taxnum  = ?
207               AND year    = ?
208               AND month   = ?
209               AND exempt_monthly = 'Y'
210         ";
211         my $sth = dbh->prepare($sql) or
212           return "fatal: can't lookup existing exemption: ". dbh->errstr;
213         $sth->execute(
214           $custnum,
215           $tax_object->taxnum,
216           $year,
217           $mon,
218         ) or
219           return "fatal: can't lookup existing exemption: ". dbh->errstr;
220         my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
221
222         # add any exemption we're already using for another line item
223        foreach ( grep { $_->taxnum == $tax_object->taxnum &&
224                          $_->exempt_monthly eq 'Y'   &&
225                          $_->month  == $mon          &&
226                          $_->year   == $year
227                        } @existing_exemptions
228                 )
229         {
230           $existing_exemption += $_->amount;
231         }
232
233         my $remaining_exemption =
234           $tax_object->exempt_amount - $existing_exemption;
235         if ( $remaining_exemption > 0 ) {
236           my $addl = $remaining_exemption > $permonth
237             ? $permonth
238             : $remaining_exemption;
239           $addl = $taxable_charged if $addl > $taxable_charged;
240
241           push @new_exemptions, FS::cust_tax_exempt_pkg->new({
242               amount          => sprintf('%.2f', $addl),
243               exempt_monthly  => 'Y',
244               year            => $year,
245               month           => $mon,
246               taxnum          => $tax_object->taxnum,
247             });
248
249           $taxable_charged -= $addl;
250         }
251         # if they're using multiple months of exemption for a multi-month
252         # package, then record the exemptions in separate months
253         $mon++;
254         if ( $mon > 12 ) {
255           $mon -= 12;
256           $year++;
257         }
258
259       }
260     } # if exempt_amount
261
262     # attach them to the line item
263     foreach my $ex (@new_exemptions) {
264
265       if ( $cust_bill_pkg->billpkgnum ) {
266         # the exempted item is already inserted (it should be, these days) so
267         # insert the exemption record now:
268         $ex->set('billpkgnum', $cust_bill_pkg->billpkgnum);
269         my $error = $ex->insert;
270         return "inserting tax exemption record: $error" if $error;
271
272       } else {
273         # defer it until the item is inserted
274         push @{ $cust_bill_pkg->cust_tax_exempt_pkg }, $ex;
275       }
276     }
277
278     # and remember we've used the exemption
279     push @existing_exemptions, @new_exemptions;
280
281     $taxable_charged = sprintf( "%.2f", $taxable_charged);
282     next if $taxable_charged == 0;
283
284     my $this_tax_cents = $taxable_charged * $tax_object->tax;
285     if ( $round_per_line_item ) {
286       # Round the tax to the nearest cent for each line item, instead of
287       # across the whole invoice.
288       $this_tax_cents = sprintf('%.0f', $this_tax_cents);
289     } else {
290       # Otherwise truncate it so that rounding error is always positive.
291       $this_tax_cents = int($this_tax_cents);
292     }
293
294     my $location = FS::cust_bill_pkg_tax_location->new({
295         'taxnum'      => $tax_object->taxnum,
296         'taxtype'     => ref($tax_object),
297         'cents'       => $this_tax_cents,
298         'pkgnum'      => $cust_bill_pkg->pkgnum,
299         'locationnum' => $cust_bill_pkg->cust_pkg->tax_locationnum,
300         'taxable_cust_bill_pkg' => $cust_bill_pkg,
301     });
302     push @tax_links, $location;
303
304     $taxable_cents += $taxable_charged;
305     $tax_cents += $this_tax_cents;
306   } #foreach $cust_bill_pkg
307
308   # calculate tax and rounding error for the whole group
309   my $extra_cents = sprintf('%.2f', $taxable_cents * $tax_object->tax / 100)
310                             * 100 - $tax_cents;
311   # make sure we have an integer
312   $extra_cents = sprintf('%.0f', $extra_cents);
313
314   # if we're rounding per item, then ignore that and don't distribute any
315   # extra cents.
316   if ( $round_per_line_item ) {
317     $extra_cents = 0;
318   }
319
320   if ( $extra_cents < 0 ) {
321     die "nonsense extra_cents value $extra_cents";
322   }
323   $tax_cents += $extra_cents;
324   my $i = 0;
325   foreach (@tax_links) { # can never require more than a single pass, yes?
326     my $cents = $_->get('cents');
327     if ( $extra_cents > 0 ) {
328       $cents++;
329       $extra_cents--;
330     }
331     $_->set('amount', sprintf('%.2f', $cents/100));
332   }
333
334   return @tax_links;
335 }
336
337 sub info {
338  +{
339     batch       => 0,
340     override    => 0,
341     rate_table  => 'cust_main_county',
342     link_table  => 'cust_bill_pkg_tax_location',
343   }
344 }
345
346 1;