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