Merge branch 'patch-19' of https://github.com/gjones2/Freeside
[freeside.git] / FS / FS / cust_main_county.pm
1 package FS::cust_main_county;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $conf
5              @cust_main_county %cust_main_county $countyflag ); # $cityflag );
6 use Exporter;
7 use FS::Record qw( qsearch qsearchs dbh );
8 use FS::cust_bill_pkg;
9 use FS::cust_bill;
10 use FS::cust_pkg;
11 use FS::part_pkg;
12 use FS::cust_tax_exempt;
13 use FS::cust_tax_exempt_pkg;
14
15 @ISA = qw( FS::Record );
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_date' 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_date = $cust_bill ? $cust_bill->_date : $opt{'invoice_date'};
280   my $cust_main = FS::cust_main->by_key($custnum) if $custnum > 0;
281   if (!$cust_main) {
282     # better way to handle this?  should we just assume that it's taxable?
283     die "unable to calculate taxes for an unknown customer\n";
284   }
285
286   # set a flag if the customer is tax-exempt
287   my $exempt_cust;
288   my $conf = FS::Conf->new;
289   if ( $conf->exists('cust_class-tax_exempt') ) {
290     my $cust_class = $cust_main->cust_class;
291     $exempt_cust = $cust_class->tax if $cust_class;
292   } else {
293     $exempt_cust = $cust_main->tax;
294   }
295
296   # set a flag if the customer is exempt from this tax here
297   my $exempt_cust_taxname = $cust_main->tax_exemption($self->taxname)
298     if $self->taxname;
299
300   # Gather any exemptions that are already attached to these cust_bill_pkgs
301   # so that we can deduct them from the customer's monthly limit.
302   my @existing_exemptions = @{ $opt{'exemptions'} };
303   push @existing_exemptions, @{ $_->cust_tax_exempt_pkg }
304     for @$taxables;
305
306   my $tax_item = FS::cust_bill_pkg->new({
307       'pkgnum'    => 0,
308       'recur'     => 0,
309       'sdate'     => '',
310       'edate'     => '',
311       'itemdesc'  => $name,
312   });
313   my @tax_location;
314
315   foreach my $cust_bill_pkg (@$taxables) {
316
317     my $cust_pkg  = $cust_bill_pkg->cust_pkg;
318     my $part_pkg  = $cust_bill_pkg->part_pkg;
319
320     my @new_exemptions;
321     my $taxable_charged = $cust_bill_pkg->setup + $cust_bill_pkg->recur
322       or next; # don't create zero-amount exemptions
323
324     # XXX the following procedure should probably be in cust_bill_pkg
325
326     if ( $exempt_cust ) {
327
328       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
329           amount => $taxable_charged,
330           exempt_cust => 'Y',
331         });
332       $taxable_charged = 0;
333
334     } elsif ( $exempt_cust_taxname ) {
335
336       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
337           amount => $taxable_charged,
338           exempt_cust_taxname => 'Y',
339         });
340       $taxable_charged = 0;
341
342     }
343
344     if ( ($part_pkg->setuptax eq 'Y' or $self->setuptax eq 'Y')
345         and $cust_bill_pkg->setup > 0 and $taxable_charged > 0 ) {
346
347       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
348           amount => $cust_bill_pkg->setup,
349           exempt_setup => 'Y'
350       });
351       $taxable_charged -= $cust_bill_pkg->setup;
352
353     }
354     if ( ($part_pkg->recurtax eq 'Y' or $self->recurtax eq 'Y')
355         and $cust_bill_pkg->recur > 0 and $taxable_charged > 0 ) {
356
357       push @new_exemptions, FS::cust_tax_exempt_pkg->new({
358           amount => $cust_bill_pkg->recur,
359           exempt_recur => 'Y'
360       });
361       $taxable_charged -= $cust_bill_pkg->recur;
362     
363     }
364   
365     if ( $self->exempt_amount && $self->exempt_amount > 0 
366       and $taxable_charged > 0 ) {
367       #my ($mon,$year) = (localtime($cust_bill_pkg->sdate) )[4,5];
368       my ($mon,$year) =
369         (localtime( $cust_bill_pkg->sdate || $invoice_date ) )[4,5];
370       $mon++;
371       $year += 1900;
372       my $freq = $cust_bill_pkg->freq;
373       unless ($freq) {
374         $freq = $part_pkg->freq || 1;  # less trustworthy fallback
375       }
376       if ( $freq !~ /(\d+)$/ ) {
377         $dbh->rollback if $oldAutoCommit;
378         return "daily/weekly package definitions not (yet?)".
379                " compatible with monthly tax exemptions";
380       }
381       my $taxable_per_month =
382         sprintf("%.2f", $taxable_charged / $freq );
383
384       #call the whole thing off if this customer has any old
385       #exemption records...
386       my @cust_tax_exempt =
387         qsearch( 'cust_tax_exempt' => { custnum=> $custnum } );
388       if ( @cust_tax_exempt ) {
389         $dbh->rollback if $oldAutoCommit;
390         return
391           'this customer still has old-style tax exemption records; '.
392           'run bin/fs-migrate-cust_tax_exempt?';
393       }
394
395       foreach my $which_month ( 1 .. $freq ) {
396   
397         #maintain the new exemption table now
398         my $sql = "
399           SELECT SUM(amount)
400             FROM cust_tax_exempt_pkg
401               LEFT JOIN cust_bill_pkg USING ( billpkgnum )
402               LEFT JOIN cust_bill     USING ( invnum     )
403             WHERE custnum = ?
404               AND taxnum  = ?
405               AND year    = ?
406               AND month   = ?
407               AND exempt_monthly = 'Y'
408         ";
409         my $sth = dbh->prepare($sql) or do {
410           $dbh->rollback if $oldAutoCommit;
411           return "fatal: can't lookup exising exemption: ". dbh->errstr;
412         };
413         $sth->execute(
414           $custnum,
415           $self->taxnum,
416           $year,
417           $mon,
418         ) or do {
419           $dbh->rollback if $oldAutoCommit;
420           return "fatal: can't lookup exising exemption: ". dbh->errstr;
421         };
422         my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
423
424         foreach ( grep { $_->taxnum == $self->taxnum &&
425                          $_->exempt_monthly eq 'Y'   &&
426                          $_->month  == $mon          &&
427                          $_->year   == $year 
428                        } @existing_exemptions
429                 )
430         {
431           $existing_exemption += $_->amount;
432         }
433         
434         my $remaining_exemption =
435           $self->exempt_amount - $existing_exemption;
436         if ( $remaining_exemption > 0 ) {
437           my $addl = $remaining_exemption > $taxable_per_month
438             ? $taxable_per_month
439             : $remaining_exemption;
440           push @new_exemptions, FS::cust_tax_exempt_pkg->new({
441               amount          => sprintf('%.2f', $addl),
442               exempt_monthly  => 'Y',
443               year            => $year,
444               month           => $mon,
445             });
446           $taxable_charged -= $addl;
447         }
448         last if $taxable_charged < 0.005;
449         # if they're using multiple months of exemption for a multi-month
450         # package, then record the exemptions in separate months
451         $mon++;
452         if ( $mon > 12 ) {
453           $mon -= 12;
454           $year++;
455         }
456
457       } #foreach $which_month
458     } # if exempt_amount
459
460     $_->taxnum($self->taxnum) foreach @new_exemptions;
461
462     # attach them to the line item
463     push @{ $cust_bill_pkg->cust_tax_exempt_pkg }, @new_exemptions;
464     push @existing_exemptions, @new_exemptions;
465
466     $taxable_charged = sprintf( "%.2f", $taxable_charged);
467     next if $taxable_charged == 0;
468
469     my $this_tax_cents = int($taxable_charged * $self->tax);
470     my $location = FS::cust_bill_pkg_tax_location->new({
471         'taxnum'      => $self->taxnum,
472         'taxtype'     => ref($self),
473         'cents'       => $this_tax_cents,
474         'pkgnum'      => $cust_bill_pkg->pkgnum,
475         'locationnum' => $cust_bill_pkg->cust_pkg->tax_locationnum,
476         'taxable_cust_bill_pkg' => $cust_bill_pkg,
477         'tax_cust_bill_pkg'     => $tax_item,
478     });
479     push @tax_location, $location;
480
481     $taxable_cents += $taxable_charged;
482     $tax_cents += $this_tax_cents;
483   } #foreach $cust_bill_pkg
484   
485   # now round and distribute
486   my $extra_cents = sprintf('%.2f', $taxable_cents * $self->tax / 100) * 100
487                     - $tax_cents;
488   # make sure we have an integer
489   $extra_cents = sprintf('%.0f', $extra_cents);
490   if ( $extra_cents < 0 ) {
491     die "nonsense extra_cents value $extra_cents";
492   }
493   $tax_cents += $extra_cents;
494   my $i = 0;
495   foreach (@tax_location) { # can never require more than a single pass, yes?
496     my $cents = $_->get('cents');
497     if ( $extra_cents > 0 ) {
498       $cents++;
499       $extra_cents--;
500     }
501     $_->set('amount', sprintf('%.2f', $cents/100));
502   }
503   $tax_item->set('setup' => sprintf('%.2f', $tax_cents / 100));
504   $tax_item->set('cust_bill_pkg_tax_location', \@tax_location);
505   
506   return $tax_item;
507 }
508
509 =back
510
511 =head1 SUBROUTINES
512
513 =over 4
514
515 =item regionselector [ COUNTY STATE COUNTRY [ PREFIX [ ONCHANGE [ DISABLED ] ] ] ]
516
517 =cut
518
519 sub regionselector {
520   my ( $selected_county, $selected_state, $selected_country,
521        $prefix, $onchange, $disabled ) = @_;
522
523   $prefix = '' unless defined $prefix;
524
525   $countyflag = 0;
526
527 #  unless ( @cust_main_county ) { #cache 
528     @cust_main_county = qsearch('cust_main_county', {} );
529     foreach my $c ( @cust_main_county ) {
530       $countyflag=1 if $c->county;
531       #push @{$cust_main_county{$c->country}{$c->state}}, $c->county;
532       $cust_main_county{$c->country}{$c->state}{$c->county} = 1;
533     }
534 #  }
535   $countyflag=1 if $selected_county;
536
537   my $script_html = <<END;
538     <SCRIPT>
539     function opt(what,value,text) {
540       var optionName = new Option(text, value, false, false);
541       var length = what.length;
542       what.options[length] = optionName;
543     }
544     function ${prefix}country_changed(what) {
545       country = what.options[what.selectedIndex].text;
546       for ( var i = what.form.${prefix}state.length; i >= 0; i-- )
547           what.form.${prefix}state.options[i] = null;
548 END
549       #what.form.${prefix}state.options[0] = new Option('', '', false, true);
550
551   foreach my $country ( sort keys %cust_main_county ) {
552     $script_html .= "\nif ( country == \"$country\" ) {\n";
553     foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
554       ( my $dstate = $state ) =~ s/[\n\r]//g;
555       my $text = $dstate || '(n/a)';
556       $script_html .= qq!opt(what.form.${prefix}state, "$dstate", "$text");\n!;
557     }
558     $script_html .= "}\n";
559   }
560
561   $script_html .= <<END;
562     }
563     function ${prefix}state_changed(what) {
564 END
565
566   if ( $countyflag ) {
567     $script_html .= <<END;
568       state = what.options[what.selectedIndex].text;
569       country = what.form.${prefix}country.options[what.form.${prefix}country.selectedIndex].text;
570       for ( var i = what.form.${prefix}county.length; i >= 0; i-- )
571           what.form.${prefix}county.options[i] = null;
572 END
573
574     foreach my $country ( sort keys %cust_main_county ) {
575       $script_html .= "\nif ( country == \"$country\" ) {\n";
576       foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
577         $script_html .= "\nif ( state == \"$state\" ) {\n";
578           #foreach my $county ( sort @{$cust_main_county{$country}{$state}} ) {
579           foreach my $county ( sort keys %{$cust_main_county{$country}{$state}} ) {
580             my $text = $county || '(n/a)';
581             $script_html .=
582               qq!opt(what.form.${prefix}county, "$county", "$text");\n!;
583           }
584         $script_html .= "}\n";
585       }
586       $script_html .= "}\n";
587     }
588   }
589
590   $script_html .= <<END;
591     }
592     </SCRIPT>
593 END
594
595   my $county_html = $script_html;
596   if ( $countyflag ) {
597     $county_html .= qq!<SELECT NAME="${prefix}county" onChange="$onchange" $disabled>!;
598     $county_html .= '</SELECT>';
599   } else {
600     $county_html .=
601       qq!<INPUT TYPE="hidden" NAME="${prefix}county" VALUE="$selected_county">!;
602   }
603
604   my $state_html = qq!<SELECT NAME="${prefix}state" !.
605                    qq!onChange="${prefix}state_changed(this); $onchange" $disabled>!;
606   foreach my $state ( sort keys %{ $cust_main_county{$selected_country} } ) {
607     my $text = $state || '(n/a)';
608     my $selected = $state eq $selected_state ? 'SELECTED' : '';
609     $state_html .= qq(\n<OPTION $selected VALUE="$state">$text</OPTION>);
610   }
611   $state_html .= '</SELECT>';
612
613   $state_html .= '</SELECT>';
614
615   my $country_html = qq!<SELECT NAME="${prefix}country" !.
616                      qq!onChange="${prefix}country_changed(this); $onchange" $disabled>!;
617   my $countrydefault = $conf->config('countrydefault') || 'US';
618   foreach my $country (
619     sort { ($b eq $countrydefault) <=> ($a eq $countrydefault) or $a cmp $b }
620       keys %cust_main_county
621   ) {
622     my $selected = $country eq $selected_country ? ' SELECTED' : '';
623     $country_html .= qq(\n<OPTION$selected VALUE="$country">$country</OPTION>");
624   }
625   $country_html .= '</SELECT>';
626
627   ($county_html, $state_html, $country_html);
628
629 }
630
631 =back
632
633 =head1 BUGS
634
635 regionselector?  putting web ui components in here?  they should probably live
636 somewhere else...
637
638 =head1 SEE ALSO
639
640 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill>, schema.html from the base
641 documentation.
642
643 =cut
644
645 1;
646