1 package FS::TaxEngine::internal;
4 use base 'FS::TaxEngine';
5 use FS::Record qw(dbh qsearch qsearchs);
9 FS::UID->install_callback(sub {
10 $conf = FS::Conf->new;
15 FS::TaxEngine::internal: the classic Freeside "internal tax engine".
16 Uses tax rates and localities defined in L<FS::cust_main_county>.
23 my ($self, $cust_bill_pkg) = @_;
25 my $part_item = $cust_bill_pkg->part_X;
26 my $location = $cust_bill_pkg->tax_location
28 my $custnum = $self->{cust_main}->custnum;
30 push @{ $self->{items} }, $cust_bill_pkg;
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'));
37 $taxhash{'taxclass'} = $part_item->taxclass;
39 my @taxes = (); # entries are cust_main_county objects
40 my %taxhash_elim = %taxhash;
41 my @elim = qw( district city county state );
44 #first try a match with taxclass
45 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
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 );
54 $taxhash_elim{ shift(@elim) } = '';
55 } while ( !scalar(@taxes) && scalar(@elim) );
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;
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} ||= [];
72 my $taxable_total = 0;
75 my $round_per_line_item = $conf->exists('tax-round_per_line_item');
77 my $cust_main = $self->{cust_main};
78 my $custnum = $cust_main->custnum;
79 my $invoice_time = $self->{invoice_time};
81 # set a flag if the customer is tax-exempt
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;
88 $exempt_cust = $cust_main->tax;
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;
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 }
102 foreach my $cust_bill_pkg (@$taxables) {
105 my $taxable_charged = $cust_bill_pkg->setup + $cust_bill_pkg->recur
106 or next; # don't create zero-amount exemptions
108 # XXX the following procedure should probably be in cust_bill_pkg
110 if ( $exempt_cust ) {
112 push @new_exemptions, FS::cust_tax_exempt_pkg->new({
113 amount => $taxable_charged,
116 $taxable_charged = 0;
118 } elsif ( $exempt_cust_taxname ) {
120 push @new_exemptions, FS::cust_tax_exempt_pkg->new({
121 amount => $taxable_charged,
122 exempt_cust_taxname => 'Y',
124 $taxable_charged = 0;
128 if ( my $part_pkg = $cust_bill_pkg->part_pkg ) {
130 if ( ($part_pkg->setuptax eq 'Y' or $tax_object->setuptax eq 'Y')
131 and $cust_bill_pkg->setup > 0 and $taxable_charged > 0 ) {
133 push @new_exemptions, FS::cust_tax_exempt_pkg->new({
134 amount => $cust_bill_pkg->setup,
137 $taxable_charged -= $cust_bill_pkg->setup;
140 if ( ($part_pkg->recurtax eq 'Y' or $tax_object->recurtax eq 'Y')
141 and $cust_bill_pkg->recur > 0 and $taxable_charged > 0 ) {
143 push @new_exemptions, FS::cust_tax_exempt_pkg->new({
144 amount => $cust_bill_pkg->recur,
147 $taxable_charged -= $cust_bill_pkg->recur;
152 if ( $tax_object->exempt_amount && $tax_object->exempt_amount > 0
153 and $taxable_charged > 0 ) {
154 # If the billing period extends across multiple calendar months,
155 # there may be several months of exemption available.
156 my $sdate = $cust_bill_pkg->sdate || $invoice_time;
157 my $start_month = (localtime($sdate))[4] + 1;
158 my $start_year = (localtime($sdate))[5] + 1900;
159 my $edate = $cust_bill_pkg->edate || $invoice_time;
160 my $end_month = (localtime($edate))[4] + 1;
161 my $end_year = (localtime($edate))[5] + 1900;
163 # If the partial last month + partial first month <= one month,
164 # don't use the exemption in the last month
165 # (unless the last month is also the first month, e.g. one-time
167 if ( (localtime($sdate))[3] >= (localtime($edate))[3]
168 and ($start_month != $end_month or $start_year != $end_year)
171 if ( $end_month == 0 ) {
177 # number of months of exemption available
178 my $freq = ($end_month - $start_month) +
179 ($end_year - $start_year) * 12 +
182 # divide equally among all of them
183 my $permonth = sprintf('%.2f', $taxable_charged / $freq);
185 #call the whole thing off if this customer has any old
186 #exemption records...
187 my @cust_tax_exempt =
188 qsearch( 'cust_tax_exempt' => { custnum=> $custnum } );
189 if ( @cust_tax_exempt ) {
191 'this customer still has old-style tax exemption records; '.
192 'run bin/fs-migrate-cust_tax_exempt?';
195 my ($mon, $year) = ($start_month, $start_year);
196 while ($taxable_charged > 0.005 and
197 ($year < $end_year or
198 ($year == $end_year and $mon <= $end_month)
202 # find the sum of the exemption used by this customer, for this tax,
206 FROM cust_tax_exempt_pkg
207 LEFT JOIN cust_bill_pkg USING ( billpkgnum )
208 LEFT JOIN cust_bill USING ( invnum )
213 AND exempt_monthly = 'Y'
215 my $sth = dbh->prepare($sql) or
216 return "fatal: can't lookup existing exemption: ". dbh->errstr;
223 return "fatal: can't lookup existing exemption: ". dbh->errstr;
224 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
226 # add any exemption we're already using for another line item
227 foreach ( grep { $_->taxnum == $tax_object->taxnum &&
228 $_->exempt_monthly eq 'Y' &&
231 } @existing_exemptions
234 $existing_exemption += $_->amount;
237 my $remaining_exemption =
238 $tax_object->exempt_amount - $existing_exemption;
239 if ( $remaining_exemption > 0 ) {
240 my $addl = $remaining_exemption > $permonth
242 : $remaining_exemption;
243 $addl = $taxable_charged if $addl > $taxable_charged;
245 push @new_exemptions, FS::cust_tax_exempt_pkg->new({
246 amount => sprintf('%.2f', $addl),
247 exempt_monthly => 'Y',
252 $taxable_charged -= $addl;
254 # if they're using multiple months of exemption for a multi-month
255 # package, then record the exemptions in separate months
265 # attach them to the line item
266 foreach my $ex (@new_exemptions) {
268 $ex->set('taxnum', $taxnum);
270 if ( $cust_bill_pkg->billpkgnum ) {
271 # the exempted item is already inserted (it should be, these days) so
272 # insert the exemption record now:
273 $ex->set('billpkgnum', $cust_bill_pkg->billpkgnum);
274 my $error = $ex->insert;
275 return "inserting tax exemption record: $error" if $error;
278 # defer it until the item is inserted
279 push @{ $cust_bill_pkg->cust_tax_exempt_pkg }, $ex;
283 # and remember we've used the exemption
284 push @existing_exemptions, @new_exemptions;
286 $taxable_charged = sprintf( "%.2f", $taxable_charged);
287 next if $taxable_charged == 0;
289 my $this_tax_cents = $taxable_charged * $tax_object->tax;
290 if ( $round_per_line_item ) {
291 # Round the tax to the nearest cent for each line item, instead of
292 # across the whole invoice.
293 $this_tax_cents = sprintf('%.0f', $this_tax_cents);
295 # Otherwise truncate it so that rounding error is always positive.
296 $this_tax_cents = int($this_tax_cents);
300 if ( my $cust_pkg = $cust_bill_pkg->cust_pkg ) {
301 $locationnum = $cust_pkg->tax_locationnum;
302 } elsif ( $conf->exists('tax-ship_address') ) {
303 $locationnum = $cust_main->ship_locationnum;
305 $locationnum = $cust_main->bill_locationnum;
308 my $location = FS::cust_bill_pkg_tax_location->new({
309 'taxnum' => $tax_object->taxnum,
310 'taxtype' => ref($tax_object),
311 'cents' => $this_tax_cents,
312 'pkgnum' => $cust_bill_pkg->pkgnum,
313 'locationnum' => $locationnum,
314 'taxable_cust_bill_pkg' => $cust_bill_pkg,
316 push @tax_links, $location;
318 $taxable_total += $taxable_charged;
319 $tax_cents += $this_tax_cents;
320 } #foreach $cust_bill_pkg
322 # calculate tax and rounding error for the whole group: total taxable
323 # amount times tax rate (as cents per dollar), minus the tax already
325 # and force 0.5 to round up
326 my $extra_cents = sprintf('%.0f',
327 ($taxable_total * $tax_object->tax) - $tax_cents + 0.00000001
330 # if we're rounding per item, then ignore that and don't distribute any
332 if ( $round_per_line_item ) {
336 if ( $extra_cents < 0 ) {
337 die "nonsense extra_cents value $extra_cents";
339 $tax_cents += $extra_cents;
341 foreach (@tax_links) { # can never require more than a single pass, yes?
342 my $cents = $_->get('cents');
343 if ( $extra_cents > 0 ) {
347 $_->set('amount', sprintf('%.2f', $cents/100));
357 rate_table => 'cust_main_county',
358 link_table => 'cust_bill_pkg_tax_location',