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