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