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