dbe9a99e0dea0975096c638ecfe0e59471af1848
[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 %taxhash = map { $_ => $location->get($_) }
32                 qw( district county state country );
33   # city names in cust_main_county are uppercase
34   $taxhash{'city'} = uc($location->get('city'));
35
36   $taxhash{'taxclass'} = $part_item->taxclass;
37
38   my @taxes = (); # entries are cust_main_county objects
39   my %taxhash_elim = %taxhash;
40   my @elim = qw( district city county state );
41   do {
42
43     #first try a match with taxclass
44     @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
45
46     if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
47       #then try a match without taxclass
48       my %no_taxclass = %taxhash_elim;
49       $no_taxclass{ 'taxclass' } = '';
50       @taxes = qsearch( 'cust_main_county', \%no_taxclass );
51     }
52
53     $taxhash_elim{ shift(@elim) } = '';
54   } while ( !scalar(@taxes) && scalar(@elim) );
55
56   foreach my $tax (@taxes) {
57     my $taxnum = $tax->taxnum;
58     $self->{taxes}->{$taxnum} ||= [ $tax ];
59     $cust_bill_pkg->set_exemptions( $tax, 'custnum' => $custnum );
60     push @{ $self->{taxes}->{$taxnum} }, $cust_bill_pkg;
61   }
62 }
63
64 sub taxline {
65   my ($self, %opt) = @_;
66   my $tax_object = $opt{tax};
67   my $taxables = $opt{sales};
68   my $taxnum = $tax_object->taxnum;
69   my $exemptions = $self->{exemptions}->{$taxnum} ||= [];
70   
71   my $taxable_total = 0;
72   my $tax_cents = 0;
73
74   my $round_per_line_item = $conf->exists('tax-round_per_line_item');
75
76   my $cust_main = $self->{cust_main};
77   my $custnum   = $cust_main->custnum;
78   my $invoice_time = $self->{invoice_time};
79
80   # set a flag if the customer is tax-exempt
81   my $exempt_cust;
82   my $conf = FS::Conf->new;
83   if ( $conf->exists('cust_class-tax_exempt') ) {
84     my $cust_class = $cust_main->cust_class;
85     $exempt_cust = $cust_class->tax if $cust_class;
86   } else {
87     $exempt_cust = $cust_main->tax;
88   }
89   # set a flag if the customer is exempt from this tax here
90   my $exempt_cust_taxname = $cust_main->tax_exemption($tax_object->taxname)
91     if $tax_object->taxname;
92
93   # Gather any exemptions that are already attached to these cust_bill_pkgs
94   # so that we can deduct them from the customer's monthly limit.
95   my @existing_exemptions = @{ $exemptions };
96   push @existing_exemptions, @{ $_->cust_tax_exempt_pkg }
97     foreach @$taxables;
98
99   my @tax_links;
100
101   foreach my $cust_bill_pkg (@$taxables) {
102
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 ( my $part_pkg = $cust_bill_pkg->part_pkg ) {
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
151     if ( $tax_object->exempt_amount && $tax_object->exempt_amount > 0
152       and $taxable_charged > 0 ) {
153       # If the billing period extends across multiple calendar months, 
154       # there may be several months of exemption available.
155       my $sdate = $cust_bill_pkg->sdate || $invoice_time;
156       my $start_month = (localtime($sdate))[4] + 1;
157       my $start_year  = (localtime($sdate))[5] + 1900;
158       my $edate = $cust_bill_pkg->edate || $invoice_time;
159       my $end_month   = (localtime($edate))[4] + 1;
160       my $end_year    = (localtime($edate))[5] + 1900;
161
162       # If the partial last month + partial first month <= one month,
163       # don't use the exemption in the last month
164       # (unless the last month is also the first month, e.g. one-time
165       # charges)
166       if ( (localtime($sdate))[3] >= (localtime($edate))[3]
167            and ($start_month != $end_month or $start_year != $end_year)
168      ) {
169         $end_month--;
170         if ( $end_month == 0 ) {
171           $end_year--;
172           $end_month = 12;
173         }
174       }
175
176       # number of months of exemption available
177       my $freq = ($end_month - $start_month) +
178                  ($end_year  - $start_year) * 12 +
179                  1;
180
181       # divide equally among all of them
182       my $permonth = sprintf('%.2f', $taxable_charged / $freq);
183
184       #call the whole thing off if this customer has any old
185       #exemption records...
186       my @cust_tax_exempt =
187         qsearch( 'cust_tax_exempt' => { custnum=> $custnum } );
188       if ( @cust_tax_exempt ) {
189         return
190           'this customer still has old-style tax exemption records; '.
191           'run bin/fs-migrate-cust_tax_exempt?';
192       }
193
194       my ($mon, $year) = ($start_month, $start_year);
195       while ($taxable_charged > 0.005 and
196              ($year < $end_year or
197                ($year == $end_year and $mon <= $end_month)
198              )
199       ) {
200
201         # find the sum of the exemption used by this customer, for this tax,
202         # in this month
203         my $sql = "
204           SELECT SUM(amount)
205             FROM cust_tax_exempt_pkg
206               LEFT JOIN cust_bill_pkg USING ( billpkgnum )
207               LEFT JOIN cust_bill     USING ( invnum     )
208             WHERE custnum = ?
209              AND taxnum  = ?
210               AND year    = ?
211               AND month   = ?
212               AND exempt_monthly = 'Y'
213         ";
214         my $sth = dbh->prepare($sql) or
215           return "fatal: can't lookup existing exemption: ". dbh->errstr;
216         $sth->execute(
217           $custnum,
218           $tax_object->taxnum,
219           $year,
220           $mon,
221         ) or
222           return "fatal: can't lookup existing exemption: ". dbh->errstr;
223         my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
224
225         # add any exemption we're already using for another line item
226        foreach ( grep { $_->taxnum == $tax_object->taxnum &&
227                          $_->exempt_monthly eq 'Y'   &&
228                          $_->month  == $mon          &&
229                          $_->year   == $year
230                        } @existing_exemptions
231                 )
232         {
233           $existing_exemption += $_->amount;
234         }
235
236         my $remaining_exemption =
237           $tax_object->exempt_amount - $existing_exemption;
238         if ( $remaining_exemption > 0 ) {
239           my $addl = $remaining_exemption > $permonth
240             ? $permonth
241             : $remaining_exemption;
242           $addl = $taxable_charged if $addl > $taxable_charged;
243
244           push @new_exemptions, FS::cust_tax_exempt_pkg->new({
245               amount          => sprintf('%.2f', $addl),
246               exempt_monthly  => 'Y',
247               year            => $year,
248               month           => $mon,
249             });
250
251           $taxable_charged -= $addl;
252         }
253         # if they're using multiple months of exemption for a multi-month
254         # package, then record the exemptions in separate months
255         $mon++;
256         if ( $mon > 12 ) {
257           $mon -= 12;
258           $year++;
259         }
260
261       }
262     } # if exempt_amount
263
264     # attach them to the line item
265     foreach my $ex (@new_exemptions) {
266
267       $ex->set('taxnum', $taxnum);
268
269       if ( $cust_bill_pkg->billpkgnum ) {
270         # the exempted item is already inserted (it should be, these days) so
271         # insert the exemption record now:
272         $ex->set('billpkgnum', $cust_bill_pkg->billpkgnum);
273         my $error = $ex->insert;
274         return "inserting tax exemption record: $error" if $error;
275
276       } else {
277         # defer it until the item is inserted
278         push @{ $cust_bill_pkg->cust_tax_exempt_pkg }, $ex;
279       }
280     }
281
282     # and remember we've used the exemption
283     push @existing_exemptions, @new_exemptions;
284
285     $taxable_charged = sprintf( "%.2f", $taxable_charged);
286     next if $taxable_charged == 0;
287
288     my $this_tax_cents = $taxable_charged * $tax_object->tax;
289     if ( $round_per_line_item ) {
290       # Round the tax to the nearest cent for each line item, instead of
291       # across the whole invoice.
292       $this_tax_cents = sprintf('%.0f', $this_tax_cents);
293     } else {
294       # Otherwise truncate it so that rounding error is always positive.
295       $this_tax_cents = int($this_tax_cents);
296     }
297
298     my $locationnum;
299     if ( my $cust_pkg = $cust_bill_pkg->cust_pkg ) {
300       $locationnum = $cust_pkg->tax_locationnum;
301     } elsif ( $conf->exists('tax-ship_address') ) {
302       $locationnum = $cust_main->ship_locationnum;
303     } else {
304       $locationnum = $cust_main->bill_locationnum;
305     }
306
307     my $location = FS::cust_bill_pkg_tax_location->new({
308         'taxnum'                => $tax_object->taxnum,
309         'taxtype'               => ref($tax_object),
310         'cents'                 => $this_tax_cents,
311         'pkgnum'                => $cust_bill_pkg->pkgnum,
312         'locationnum'           => $locationnum,
313         'taxable_cust_bill_pkg' => $cust_bill_pkg,
314     });
315     push @tax_links, $location;
316
317     $taxable_total += $taxable_charged;
318     $tax_cents += $this_tax_cents;
319   } #foreach $cust_bill_pkg
320
321   # calculate tax and rounding error for the whole group: total taxable
322   # amount times tax rate (as cents per dollar), minus the tax already
323   # charged
324   # and force 0.5 to round up
325   my $extra_cents = sprintf('%.0f',
326     ($taxable_total * $tax_object->tax) - $tax_cents + 0.00000001
327   );
328
329   # if we're rounding per item, then ignore that and don't distribute any
330   # extra cents.
331   if ( $round_per_line_item ) {
332     $extra_cents = 0;
333   }
334
335   if ( $extra_cents < 0 ) {
336     die "nonsense extra_cents value $extra_cents";
337   }
338   $tax_cents += $extra_cents;
339   my $i = 0;
340   foreach (@tax_links) { # can never require more than a single pass, yes?
341     my $cents = $_->get('cents');
342     if ( $extra_cents > 0 ) {
343       $cents++;
344       $extra_cents--;
345     }
346     $_->set('amount', sprintf('%.2f', $cents/100));
347   }
348
349   return @tax_links;
350 }
351
352 sub info {
353  +{
354     batch       => 0,
355     override    => 0,
356     rate_table  => 'cust_main_county',
357     link_table  => 'cust_bill_pkg_tax_location',
358   }
359 }
360
361 1;