estimate tax on quotations, #32489
[freeside.git] / FS / FS / cust_main_county.pm
1 package FS::cust_main_county;
2 use base qw( FS::Record );
3
4 use strict;
5 use vars qw( @EXPORT_OK $conf
6              @cust_main_county %cust_main_county $countyflag ); # $cityflag );
7 use Exporter;
8 use FS::Record qw( qsearch qsearchs dbh );
9 use FS::cust_bill_pkg;
10 use FS::cust_bill;
11 use FS::cust_pkg;
12 use FS::part_pkg;
13 use FS::cust_tax_exempt;
14 use FS::cust_tax_exempt_pkg;
15
16 @EXPORT_OK = qw( regionselector );
17
18 @cust_main_county = ();
19 $countyflag = '';
20 #$cityflag = '';
21
22 #ask FS::UID to run this stuff for us later
23 $FS::UID::callback{'FS::cust_main_county'} = sub { 
24   $conf = new FS::Conf;
25 };
26
27 =head1 NAME
28
29 FS::cust_main_county - Object methods for cust_main_county objects
30
31 =head1 SYNOPSIS
32
33   use FS::cust_main_county;
34
35   $record = new FS::cust_main_county \%hash;
36   $record = new FS::cust_main_county { 'column' => 'value' };
37
38   $error = $record->insert;
39
40   $error = $new_record->replace($old_record);
41
42   $error = $record->delete;
43
44   $error = $record->check;
45
46   ($county_html, $state_html, $country_html) =
47     FS::cust_main_county::regionselector( $county, $state, $country );
48
49 =head1 DESCRIPTION
50
51 An FS::cust_main_county object represents a tax rate, defined by locale.
52 FS::cust_main_county inherits from FS::Record.  The following fields are
53 currently supported:
54
55 =over 4
56
57 =item taxnum - primary key (assigned automatically for new tax rates)
58
59 =item district - tax district (optional)
60
61 =item city
62
63 =item county
64
65 =item state
66
67 =item country
68
69 =item tax - percentage
70
71 =item taxclass
72
73 =item exempt_amount
74
75 =item taxname - if defined, printed on invoices instead of "Tax"
76
77 =item setuptax - if 'Y', this tax does not apply to setup fees
78
79 =item recurtax - if 'Y', this tax does not apply to recurring fees
80
81 =back
82
83 =head1 METHODS
84
85 =over 4
86
87 =item new HASHREF
88
89 Creates a new tax rate.  To add the tax rate to the database, see L<"insert">.
90
91 =cut
92
93 sub table { 'cust_main_county'; }
94
95 =item insert
96
97 Adds this tax rate to the database.  If there is an error, returns the error,
98 otherwise returns false.
99
100 =item delete
101
102 Deletes this tax rate from the database.  If there is an error, returns the
103 error, otherwise returns false.
104
105 =item replace OLD_RECORD
106
107 Replaces the OLD_RECORD with this one in the database.  If there is an error,
108 returns the error, otherwise returns false.
109
110 =item check
111
112 Checks all fields to make sure this is a valid tax rate.  If there is an error,
113 returns the error, otherwise returns false.  Called by the insert and replace
114 methods.
115
116 =cut
117
118 sub check {
119   my $self = shift;
120
121   $self->exempt_amount(0) unless $self->exempt_amount;
122
123   $self->ut_numbern('taxnum')
124     || $self->ut_alphan('district')
125     || $self->ut_textn('city')
126     || $self->ut_textn('county')
127     || $self->ut_anything('state')
128     || $self->ut_text('country')
129     || $self->ut_float('tax')
130     || $self->ut_textn('taxclass') # ...
131     || $self->ut_money('exempt_amount')
132     || $self->ut_textn('taxname')
133     || $self->ut_enum('setuptax', [ '', 'Y' ] )
134     || $self->ut_enum('recurtax', [ '', 'Y' ] )
135     || $self->SUPER::check
136     ;
137
138 }
139
140 =item label OPTIONS
141
142 Returns a label looking like "Anytown, Alameda County, CA, US".
143
144 If the taxname field is set, it will look like
145 "CA Sales Tax (Anytown, Alameda County, CA, US)".
146
147 If the taxclass is set, then it will be
148 "Anytown, Alameda County, CA, US (International)".
149
150 OPTIONS may contain "with_taxclass", "with_city", and "with_district" to show
151 those fields.  It may also contain "out", in which case, if this region 
152 (district+city+county+state+country) contains no non-zero taxes, the label 
153 will read "Out of taxable region(s)".
154
155 =cut
156
157 sub label {
158   my ($self, %opt) = @_;
159   if ( $opt{'out'} 
160        and $self->tax == 0
161        and !defined(qsearchs('cust_main_county', {
162            'district' => $self->district,
163            'city'     => $self->city,
164            'county'   => $self->county,
165            'state'    => $self->state,
166            'country'  => $self->country,
167            'tax'  => { op => '>', value => 0 },
168         })) )
169   {
170     return 'Out of taxable region(s)';
171   }
172   my $label = $self->country;
173   $label = $self->state.", $label" if $self->state;
174   $label = $self->county." County, $label" if $self->county;
175   if ($opt{with_city}) {
176     $label = $self->city.", $label" if $self->city;
177     if ($opt{with_district} and $self->district) {
178       $label = $self->district . ", $label";
179     }
180   }
181   # ugly labels when taxclass and taxname are both non-null...
182   # but this is how the tax report does it
183   if ($opt{with_taxclass}) {
184     $label = "$label (".$self->taxclass.')' if $self->taxclass;
185   }
186   $label = $self->taxname." ($label)" if $self->taxname;
187
188   $label;
189 }
190
191 =item sql_taxclass_sameregion
192
193 Returns an SQL WHERE fragment or the empty string to search for entries
194 with different tax classes.
195
196 =cut
197
198 #hmm, description above could be better...
199
200 sub sql_taxclass_sameregion {
201   my $self = shift;
202
203   my $same_query = 'SELECT DISTINCT taxclass FROM cust_main_county '.
204                    ' WHERE taxnum != ? AND country = ?';
205   my @same_param = ( 'taxnum', 'country' );
206   foreach my $opt_field (qw( state county )) {
207     if ( $self->$opt_field() ) {
208       $same_query .= " AND $opt_field = ?";
209       push @same_param, $opt_field;
210     } else {
211       $same_query .= " AND $opt_field IS NULL";
212     }
213   }
214
215   my @taxclasses = $self->_list_sql( \@same_param, $same_query );
216
217   return '' unless scalar(@taxclasses);
218
219   '( taxclass IS NULL OR ( '.  #only if !$self->taxclass ??
220      join(' AND ', map { 'taxclass != '.dbh->quote($_) } @taxclasses ). 
221   ' ) ) ';
222 }
223
224 sub _list_sql {
225   my( $self, $param, $sql ) = @_;
226   my $sth = dbh->prepare($sql) or die dbh->errstr;
227   $sth->execute( map $self->$_(), @$param )
228     or die "Unexpected error executing statement $sql: ". $sth->errstr;
229   map $_->[0], @{ $sth->fetchall_arrayref };
230 }
231
232 =item taxline TAXABLES_ARRAYREF, [ OPTION => VALUE ... ]
233
234 Takes an arrayref of L<FS::cust_bill_pkg> objects representing taxable
235 line items, and returns a new L<FS::cust_bill_pkg> object representing
236 the tax on them under this tax rate.
237
238 This will have a pseudo-field, "cust_bill_pkg_tax_location", containing 
239 an arrayref of L<FS::cust_bill_pkg_tax_location> objects.  Each of these 
240 will in turn have a "taxable_cust_bill_pkg" pseudo-field linking it to one
241 of the taxable items.  All of these links must be resolved as the objects
242 are inserted.
243
244 In addition to calculating the tax for the line items, this will calculate
245 any appropriate tax exemptions and attach them to the line items.
246
247 Options may include 'custnum' and 'invoice_time' in case the cust_bill_pkg
248 objects belong to an invoice that hasn't been inserted yet.
249
250 Options may include 'exemptions', an arrayref of L<FS::cust_tax_exempt_pkg>
251 objects belonging to the same customer, to be counted against the monthly 
252 tax exemption limit if there is one.
253
254 =cut
255
256 # XXX change tax_rate.pm to work like this
257
258 sub taxline {
259   my( $self, $taxables, %opt ) = @_;
260   return 'taxline called with no line items' unless @$taxables;
261
262   local $SIG{HUP} = 'IGNORE';
263   local $SIG{INT} = 'IGNORE';
264   local $SIG{QUIT} = 'IGNORE';
265   local $SIG{TERM} = 'IGNORE';
266   local $SIG{TSTP} = 'IGNORE';
267   local $SIG{PIPE} = 'IGNORE';
268
269   my $oldAutoCommit = $FS::UID::AutoCommit;
270   local $FS::UID::AutoCommit = 0;
271   my $dbh = dbh;
272
273   my $name = $self->taxname || 'Tax';
274   my $taxable_cents = 0;
275   my $tax_cents = 0;
276
277   my $cust_bill = $taxables->[0]->cust_bill;
278   my $custnum   = $cust_bill ? $cust_bill->custnum : $opt{'custnum'};
279   my $invoice_time = $cust_bill ? $cust_bill->_date : $opt{'invoice_time'};
280   my $cust_main = FS::cust_main->by_key($custnum) if $custnum > 0;
281   # (to avoid complications with estimated tax on quotations, assume it's
282   # taxable if there is no customer)
283   #if (!$cust_main) {
284     #die "unable to calculate taxes for an unknown customer\n";
285   #}
286
287   # set a flag if the customer is tax-exempt
288   my $exempt_cust;
289   my $conf = FS::Conf->new;
290   if ( $conf->exists('cust_class-tax_exempt') ) {
291     my $cust_class = $cust_main->cust_class;
292     $exempt_cust = $cust_class->tax if $cust_class;
293   } else {
294     $exempt_cust = $cust_main->tax;
295   }
296
297   # set a flag if the customer is exempt from this tax here
298   my $exempt_cust_taxname = $cust_main->tax_exemption($self->taxname)
299     if $self->taxname;
300
301   # Gather any exemptions that are already attached to these cust_bill_pkgs
302   # so that we can deduct them from the customer's monthly limit.
303   my @existing_exemptions = @{ $opt{'exemptions'} };
304   push @existing_exemptions, @{ $_->cust_tax_exempt_pkg }
305     for @$taxables;
306
307   my $tax_item = FS::cust_bill_pkg->new({
308       'pkgnum'    => 0,
309       'recur'     => 0,
310       'sdate'     => '',
311       'edate'     => '',
312       'itemdesc'  => $name,
313   });
314   my @tax_location;
315
316   foreach my $cust_bill_pkg (@$taxables) {
317     # careful... may be a cust_bill_pkg or a quotation_pkg
318
319     my $cust_pkg  = $cust_bill_pkg->cust_pkg;
320     my $part_pkg  = $cust_bill_pkg->part_pkg;
321     my $part_fee  = $cust_bill_pkg->part_fee;
322
323     my $locationnum = $cust_pkg
324                       ? $cust_pkg->locationnum
325                       : $cust_main->bill_locationnum;
326
327     my @new_exemptions;
328     my $taxable_charged = $cust_bill_pkg->setup + $cust_bill_pkg->recur
329       or next; # don't create zero-amount exemptions
330
331     # XXX the following procedure should probably be in cust_bill_pkg
332
333     if ( $exempt_cust ) {
334
335       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
336           amount => $taxable_charged,
337           exempt_cust => 'Y',
338         });
339       $taxable_charged = 0;
340
341     } elsif ( $exempt_cust_taxname ) {
342
343       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
344           amount => $taxable_charged,
345           exempt_cust_taxname => 'Y',
346         });
347       $taxable_charged = 0;
348
349     }
350
351     my $setup_exempt = ( ($part_fee and not $part_fee->taxable)
352                       or ($part_pkg and $part_pkg->setuptax)
353                       or $self->setuptax );
354
355     if ( $setup_exempt
356         and $cust_bill_pkg->setup > 0
357         and $taxable_charged > 0 ) {
358
359       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
360           amount => $cust_bill_pkg->setup,
361           exempt_setup => 'Y'
362       });
363       $taxable_charged -= $cust_bill_pkg->setup;
364
365     }
366
367     my $recur_exempt = ( ($part_fee and not $part_fee->taxable)
368                       or ($part_pkg and $part_pkg->recurtax)
369                       or $self->recurtax );
370
371     if ( $recur_exempt
372         and $cust_bill_pkg->recur > 0
373         and $taxable_charged > 0 ) {
374
375       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
376           amount => $cust_bill_pkg->recur,
377           exempt_recur => 'Y'
378       });
379       $taxable_charged -= $cust_bill_pkg->recur;
380     
381     }
382   
383     if ( $self->exempt_amount && $self->exempt_amount > 0 
384       and $taxable_charged > 0
385       and $cust_main ) {
386
387       # XXX monthly exemptions currently don't work on quotations
388
389       # If the billing period extends across multiple calendar months, 
390       # there may be several months of exemption available.
391       my $sdate = $cust_bill_pkg->sdate || $invoice_time;
392       my $start_month = (localtime($sdate))[4] + 1;
393       my $start_year  = (localtime($sdate))[5] + 1900;
394       my $edate = $cust_bill_pkg->edate || $invoice_time;
395       my $end_month   = (localtime($edate))[4] + 1;
396       my $end_year    = (localtime($edate))[5] + 1900;
397
398       # If the partial last month + partial first month <= one month,
399       # don't use the exemption in the last month
400       # (unless the last month is also the first month, e.g. one-time
401       # charges)
402       if ( (localtime($sdate))[3] >= (localtime($edate))[3]
403            and ($start_month != $end_month or $start_year != $end_year)
404       ) { 
405         $end_month--;
406         if ( $end_month == 0 ) {
407           $end_year--;
408           $end_month = 12;
409         }
410       }
411
412       # number of months of exemption available
413       my $freq = ($end_month - $start_month) +
414                  ($end_year  - $start_year) * 12 +
415                  1;
416
417       # divide equally among all of them
418       my $permonth = sprintf('%.2f', $taxable_charged / $freq);
419
420       #call the whole thing off if this customer has any old
421       #exemption records...
422       my @cust_tax_exempt =
423         qsearch( 'cust_tax_exempt' => { custnum=> $custnum } );
424       if ( @cust_tax_exempt ) {
425         $dbh->rollback if $oldAutoCommit;
426         return
427           'this customer still has old-style tax exemption records; '.
428           'run bin/fs-migrate-cust_tax_exempt?';
429       }
430
431       my ($mon, $year) = ($start_month, $start_year);
432       while ($taxable_charged > 0.005 and 
433              ($year < $end_year or
434                ($year == $end_year and $mon <= $end_month)
435              )
436       ) {
437  
438         # find the sum of the exemption used by this customer, for this tax,
439         # in this month
440         my $sql = "
441           SELECT SUM(amount)
442             FROM cust_tax_exempt_pkg
443               LEFT JOIN cust_bill_pkg USING ( billpkgnum )
444               LEFT JOIN cust_bill     USING ( invnum     )
445             WHERE custnum = ?
446               AND taxnum  = ?
447               AND year    = ?
448               AND month   = ?
449               AND exempt_monthly = 'Y'
450         ";
451         my $sth = dbh->prepare($sql) or do {
452           $dbh->rollback if $oldAutoCommit;
453           return "fatal: can't lookup existing exemption: ". dbh->errstr;
454         };
455         $sth->execute(
456           $custnum,
457           $self->taxnum,
458           $year,
459           $mon,
460         ) or do {
461           $dbh->rollback if $oldAutoCommit;
462           return "fatal: can't lookup existing exemption: ". dbh->errstr;
463         };
464         my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
465
466         # add any exemption we're already using for another line item
467         foreach ( grep { $_->taxnum == $self->taxnum &&
468                          $_->exempt_monthly eq 'Y'   &&
469                          $_->month  == $mon          &&
470                          $_->year   == $year 
471                        } @existing_exemptions
472                 )
473         {
474           $existing_exemption += $_->amount;
475         }
476
477         my $remaining_exemption =
478           $self->exempt_amount - $existing_exemption;
479         if ( $remaining_exemption > 0 ) {
480           my $addl = $remaining_exemption > $permonth
481             ? $permonth
482             : $remaining_exemption;
483           $addl = $taxable_charged if $addl > $taxable_charged;
484
485           push @new_exemptions, FS::cust_tax_exempt_pkg->new({
486               amount          => sprintf('%.2f', $addl),
487               exempt_monthly  => 'Y',
488               year            => $year,
489               month           => $mon,
490             });
491           $taxable_charged -= $addl;
492         }
493         # if they're using multiple months of exemption for a multi-month
494         # package, then record the exemptions in separate months
495         $mon++;
496         if ( $mon > 12 ) {
497           $mon -= 12;
498           $year++;
499         }
500
501       }
502     } # if exempt_amount and $cust_main
503
504     $_->taxnum($self->taxnum) foreach @new_exemptions;
505
506     # attach them to the line item
507     push @{ $cust_bill_pkg->cust_tax_exempt_pkg }, @new_exemptions;
508     push @existing_exemptions, @new_exemptions;
509
510     $taxable_charged = sprintf( "%.2f", $taxable_charged);
511     next if $taxable_charged == 0;
512
513     my $this_tax_cents = int($taxable_charged * $self->tax);
514     my $location = FS::cust_bill_pkg_tax_location->new({
515         'taxnum'      => $self->taxnum,
516         'taxtype'     => ref($self),
517         'cents'       => $this_tax_cents,
518         'pkgnum'      => $cust_bill_pkg->pkgnum,
519         'locationnum' => $locationnum,
520         'taxable_cust_bill_pkg' => $cust_bill_pkg,
521         'tax_cust_bill_pkg'     => $tax_item,
522     });
523     push @tax_location, $location;
524
525     $taxable_cents += $taxable_charged;
526     $tax_cents += $this_tax_cents;
527   } #foreach $cust_bill_pkg
528   
529   # now round and distribute
530   my $extra_cents = sprintf('%.2f', $taxable_cents * $self->tax / 100) * 100
531                     - $tax_cents;
532   # make sure we have an integer
533   $extra_cents = sprintf('%.0f', $extra_cents);
534   if ( $extra_cents < 0 ) {
535     die "nonsense extra_cents value $extra_cents";
536   }
537   $tax_cents += $extra_cents;
538   my $i = 0;
539   foreach (@tax_location) { # can never require more than a single pass, yes?
540     my $cents = $_->get('cents');
541     if ( $extra_cents > 0 ) {
542       $cents++;
543       $extra_cents--;
544     }
545     $_->set('amount', sprintf('%.2f', $cents/100));
546   }
547   $tax_item->set('setup' => sprintf('%.2f', $tax_cents / 100));
548   $tax_item->set('cust_bill_pkg_tax_location', \@tax_location);
549   
550   return $tax_item;
551 }
552
553 =back
554
555 =head1 SUBROUTINES
556
557 =over 4
558
559 =item regionselector [ COUNTY STATE COUNTRY [ PREFIX [ ONCHANGE [ DISABLED ] ] ] ]
560
561 =cut
562
563 sub regionselector {
564   my ( $selected_county, $selected_state, $selected_country,
565        $prefix, $onchange, $disabled ) = @_;
566
567   $prefix = '' unless defined $prefix;
568
569   $countyflag = 0;
570
571 #  unless ( @cust_main_county ) { #cache 
572     @cust_main_county = qsearch('cust_main_county', {} );
573     foreach my $c ( @cust_main_county ) {
574       $countyflag=1 if $c->county;
575       #push @{$cust_main_county{$c->country}{$c->state}}, $c->county;
576       $cust_main_county{$c->country}{$c->state}{$c->county} = 1;
577     }
578 #  }
579   $countyflag=1 if $selected_county;
580
581   my $script_html = <<END;
582     <SCRIPT>
583     function opt(what,value,text) {
584       var optionName = new Option(text, value, false, false);
585       var length = what.length;
586       what.options[length] = optionName;
587     }
588     function ${prefix}country_changed(what) {
589       country = what.options[what.selectedIndex].text;
590       for ( var i = what.form.${prefix}state.length; i >= 0; i-- )
591           what.form.${prefix}state.options[i] = null;
592 END
593       #what.form.${prefix}state.options[0] = new Option('', '', false, true);
594
595   foreach my $country ( sort keys %cust_main_county ) {
596     $script_html .= "\nif ( country == \"$country\" ) {\n";
597     foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
598       ( my $dstate = $state ) =~ s/[\n\r]//g;
599       my $text = $dstate || '(n/a)';
600       $script_html .= qq!opt(what.form.${prefix}state, "$dstate", "$text");\n!;
601     }
602     $script_html .= "}\n";
603   }
604
605   $script_html .= <<END;
606     }
607     function ${prefix}state_changed(what) {
608 END
609
610   if ( $countyflag ) {
611     $script_html .= <<END;
612       state = what.options[what.selectedIndex].text;
613       country = what.form.${prefix}country.options[what.form.${prefix}country.selectedIndex].text;
614       for ( var i = what.form.${prefix}county.length; i >= 0; i-- )
615           what.form.${prefix}county.options[i] = null;
616 END
617
618     foreach my $country ( sort keys %cust_main_county ) {
619       $script_html .= "\nif ( country == \"$country\" ) {\n";
620       foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
621         $script_html .= "\nif ( state == \"$state\" ) {\n";
622           #foreach my $county ( sort @{$cust_main_county{$country}{$state}} ) {
623           foreach my $county ( sort keys %{$cust_main_county{$country}{$state}} ) {
624             my $text = $county || '(n/a)';
625             $script_html .=
626               qq!opt(what.form.${prefix}county, "$county", "$text");\n!;
627           }
628         $script_html .= "}\n";
629       }
630       $script_html .= "}\n";
631     }
632   }
633
634   $script_html .= <<END;
635     }
636     </SCRIPT>
637 END
638
639   my $county_html = $script_html;
640   if ( $countyflag ) {
641     $county_html .= qq!<SELECT NAME="${prefix}county" onChange="$onchange" $disabled>!;
642     $county_html .= '</SELECT>';
643   } else {
644     $county_html .=
645       qq!<INPUT TYPE="hidden" NAME="${prefix}county" VALUE="$selected_county">!;
646   }
647
648   my $state_html = qq!<SELECT NAME="${prefix}state" !.
649                    qq!onChange="${prefix}state_changed(this); $onchange" $disabled>!;
650   foreach my $state ( sort keys %{ $cust_main_county{$selected_country} } ) {
651     my $text = $state || '(n/a)';
652     my $selected = $state eq $selected_state ? 'SELECTED' : '';
653     $state_html .= qq(\n<OPTION $selected VALUE="$state">$text</OPTION>);
654   }
655   $state_html .= '</SELECT>';
656
657   $state_html .= '</SELECT>';
658
659   my $country_html = qq!<SELECT NAME="${prefix}country" !.
660                      qq!onChange="${prefix}country_changed(this); $onchange" $disabled>!;
661   my $countrydefault = $conf->config('countrydefault') || 'US';
662   foreach my $country (
663     sort { ($b eq $countrydefault) <=> ($a eq $countrydefault) or $a cmp $b }
664       keys %cust_main_county
665   ) {
666     my $selected = $country eq $selected_country ? ' SELECTED' : '';
667     $country_html .= qq(\n<OPTION$selected VALUE="$country">$country</OPTION>");
668   }
669   $country_html .= '</SELECT>';
670
671   ($county_html, $state_html, $country_html);
672
673 }
674
675 =back
676
677 =head1 BUGS
678
679 regionselector?  putting web ui components in here?  they should probably live
680 somewhere else...
681
682 =head1 SEE ALSO
683
684 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill>, schema.html from the base
685 documentation.
686
687 =cut
688
689 1;
690