communigate provisioning phase 2: add svc_domain.trailer -> communigate TrailerText...
[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 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 city
60
61 =item county
62
63 =item state
64
65 =item country
66
67 =item tax - percentage
68
69 =item taxclass
70
71 =item exempt_amount
72
73 =item taxname - if defined, printed on invoices instead of "Tax"
74
75 =item setuptax - if 'Y', this tax does not apply to setup fees
76
77 =item recurtax - if 'Y', this tax does not apply to recurring fees
78
79 =back
80
81 =head1 METHODS
82
83 =over 4
84
85 =item new HASHREF
86
87 Creates a new tax rate.  To add the tax rate to the database, see L<"insert">.
88
89 =cut
90
91 sub table { 'cust_main_county'; }
92
93 =item insert
94
95 Adds this tax rate to the database.  If there is an error, returns the error,
96 otherwise returns false.
97
98 =item delete
99
100 Deletes this tax rate from the database.  If there is an error, returns the
101 error, otherwise returns false.
102
103 =item replace OLD_RECORD
104
105 Replaces the OLD_RECORD with this one in the database.  If there is an error,
106 returns the error, otherwise returns false.
107
108 =item check
109
110 Checks all fields to make sure this is a valid tax rate.  If there is an error,
111 returns the error, otherwise returns false.  Called by the insert and replace
112 methods.
113
114 =cut
115
116 sub check {
117   my $self = shift;
118
119   $self->exempt_amount(0) unless $self->exempt_amount;
120
121   $self->ut_numbern('taxnum')
122     || $self->ut_textn('city')
123     || $self->ut_textn('county')
124     || $self->ut_anything('state')
125     || $self->ut_text('country')
126     || $self->ut_float('tax')
127     || $self->ut_textn('taxclass') # ...
128     || $self->ut_money('exempt_amount')
129     || $self->ut_textn('taxname')
130     || $self->ut_enum('setuptax', [ '', 'Y' ] )
131     || $self->ut_enum('recurtax', [ '', 'Y' ] )
132     || $self->SUPER::check
133     ;
134
135 }
136
137 sub taxname {
138   my $self = shift;
139   if ( $self->dbdef_table->column('taxname') ) {
140     return $self->setfield('taxname', $_[0]) if @_;
141     return $self->getfield('taxname');
142   }  
143   return '';
144 }
145
146 sub setuptax {
147   my $self = shift;
148   if ( $self->dbdef_table->column('setuptax') ) {
149     return $self->setfield('setuptax', $_[0]) if @_;
150     return $self->getfield('setuptax');
151   }  
152   return '';
153 }
154
155 sub recurtax {
156   my $self = shift;
157   if ( $self->dbdef_table->column('recurtax') ) {
158     return $self->setfield('recurtax', $_[0]) if @_;
159     return $self->getfield('recurtax');
160   }  
161   return '';
162 }
163
164 =item sql_taxclass_sameregion
165
166 Returns an SQL WHERE fragment or the empty string to search for entries
167 with different tax classes.
168
169 =cut
170
171 #hmm, description above could be better...
172
173 sub sql_taxclass_sameregion {
174   my $self = shift;
175
176   my $same_query = 'SELECT taxclass FROM cust_main_county '.
177                    ' WHERE taxnum != ? AND country = ?';
178   my @same_param = ( 'taxnum', 'country' );
179   foreach my $opt_field (qw( state county )) {
180     if ( $self->$opt_field() ) {
181       $same_query .= " AND $opt_field = ?";
182       push @same_param, $opt_field;
183     } else {
184       $same_query .= " AND $opt_field IS NULL";
185     }
186   }
187
188   my @taxclasses = $self->_list_sql( \@same_param, $same_query );
189
190   return '' unless scalar(@taxclasses);
191
192   '( taxclass IS NULL OR ( '.  #only if !$self->taxclass ??
193      join(' AND ', map { 'taxclass != '.dbh->quote($_) } @taxclasses ). 
194   ' ) ) ';
195 }
196
197 sub _list_sql {
198   my( $self, $param, $sql ) = @_;
199   my $sth = dbh->prepare($sql) or die dbh->errstr;
200   $sth->execute( map $self->$_(), @$param )
201     or die "Unexpected error executing statement $sql: ". $sth->errstr;
202   map $_->[0], @{ $sth->fetchall_arrayref };
203 }
204
205 =item taxline TAXABLES_ARRAYREF, [ OPTION => VALUE ... ]
206
207 Returns a listref of a name and an amount of tax calculated for the list of
208 packages or amounts referenced by TAXABLES_ARRAYREF.  Returns a scalar error
209 message on error.  
210
211 Options include custnum and invoice_date and are hints to this method
212
213 =cut
214
215 sub taxline {
216   my( $self, $taxables, %opt ) = @_;
217
218   my @exemptions = ();
219   push @exemptions, @{ $_->_cust_tax_exempt_pkg }
220     for grep { ref($_) } @$taxables;
221     
222   local $SIG{HUP} = 'IGNORE';
223   local $SIG{INT} = 'IGNORE';
224   local $SIG{QUIT} = 'IGNORE';
225   local $SIG{TERM} = 'IGNORE';
226   local $SIG{TSTP} = 'IGNORE';
227   local $SIG{PIPE} = 'IGNORE';
228
229   my $oldAutoCommit = $FS::UID::AutoCommit;
230   local $FS::UID::AutoCommit = 0;
231   my $dbh = dbh;
232
233   my $name = $self->taxname || 'Tax';
234   my $amount = 0;
235
236   foreach my $cust_bill_pkg (@$taxables) {
237
238     my $cust_pkg  = $cust_bill_pkg->cust_pkg;
239     my $cust_bill = $cust_pkg->cust_bill if $cust_pkg;
240     my $custnum   = $cust_pkg ? $cust_pkg->custnum : $opt{custnum};
241     my $part_pkg  = $cust_bill_pkg->part_pkg;
242     my $invoice_date = $cust_bill ? $cust_bill->_date : $opt{invoice_date};
243   
244     my $taxable_charged = 0;
245     $taxable_charged += $cust_bill_pkg->setup
246       unless $part_pkg->setuptax =~ /^Y$/i
247           || $self->setuptax =~ /^Y$/i;
248     $taxable_charged += $cust_bill_pkg->recur
249       unless $part_pkg->recurtax =~ /^Y$/i
250           || $self->recurtax =~ /^Y$/i;
251
252     next unless $taxable_charged;
253   
254     if ( $self->exempt_amount && $self->exempt_amount > 0 ) {
255       #my ($mon,$year) = (localtime($cust_bill_pkg->sdate) )[4,5];
256       my ($mon,$year) =
257         (localtime( $cust_bill_pkg->sdate || $invoice_date ) )[4,5];
258       $mon++;
259       my $freq = $part_pkg->freq || 1;
260       if ( $freq !~ /(\d+)$/ ) {
261         $dbh->rollback if $oldAutoCommit;
262         return "daily/weekly package definitions not (yet?)".
263                " compatible with monthly tax exemptions";
264       }
265       my $taxable_per_month =
266         sprintf("%.2f", $taxable_charged / $freq );
267
268       #call the whole thing off if this customer has any old
269       #exemption records...
270       my @cust_tax_exempt =
271         qsearch( 'cust_tax_exempt' => { custnum=> $custnum } );
272       if ( @cust_tax_exempt ) {
273         $dbh->rollback if $oldAutoCommit;
274         return
275           'this customer still has old-style tax exemption records; '.
276           'run bin/fs-migrate-cust_tax_exempt?';
277       }
278
279       foreach my $which_month ( 1 .. $freq ) {
280   
281         #maintain the new exemption table now
282         my $sql = "
283           SELECT SUM(amount)
284             FROM cust_tax_exempt_pkg
285               LEFT JOIN cust_bill_pkg USING ( billpkgnum )
286               LEFT JOIN cust_bill     USING ( invnum     )
287             WHERE custnum = ?
288               AND taxnum  = ?
289               AND year    = ?
290               AND month   = ?
291         ";
292         my $sth = dbh->prepare($sql) or do {
293           $dbh->rollback if $oldAutoCommit;
294           return "fatal: can't lookup exising exemption: ". dbh->errstr;
295         };
296         $sth->execute(
297           $custnum,
298           $self->taxnum,
299           1900+$year,
300           $mon,
301         ) or do {
302           $dbh->rollback if $oldAutoCommit;
303           return "fatal: can't lookup exising exemption: ". dbh->errstr;
304         };
305         my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
306
307         foreach ( grep { $_->taxnum == $self->taxnum &&
308                          $_->month  == $mon          &&
309                          $_->year   == 1900+$year
310                        } @exemptions
311                 )
312         {
313           $existing_exemption += $_->amount;
314         }
315         
316         my $remaining_exemption =
317           $self->exempt_amount - $existing_exemption;
318         if ( $remaining_exemption > 0 ) {
319           my $addl = $remaining_exemption > $taxable_per_month
320             ? $taxable_per_month
321             : $remaining_exemption;
322           $taxable_charged -= $addl;
323
324           my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
325             'taxnum'     => $self->taxnum,
326             'year'       => 1900+$year,
327             'month'      => $mon,
328             'amount'     => sprintf("%.2f", $addl ),
329           } );
330           if ($cust_bill_pkg->billpkgnum) {
331             $cust_tax_exempt_pkg->billpkgnum($cust_bill_pkg->billpkgnum);
332             my $error = $cust_tax_exempt_pkg->insert;
333             if ( $error ) {
334               $dbh->rollback if $oldAutoCommit;
335               return "fatal: can't insert cust_tax_exempt_pkg: $error";
336             }
337           }else{
338             push @exemptions, $cust_tax_exempt_pkg;
339             push @{ $cust_bill_pkg->_cust_tax_exempt_pkg }, $cust_tax_exempt_pkg;
340           } # if $cust_bill_pkg->billpkgnum
341         } # if $remaining_exemption > 0
342
343         #++
344         $mon++;
345         #until ( $mon < 12 ) { $mon -= 12; $year++; }
346         until ( $mon < 13 ) { $mon -= 12; $year++; }
347
348       } #foreach $which_month
349
350     } #if $tax->exempt_amount
351
352     $taxable_charged = sprintf( "%.2f", $taxable_charged);
353
354     $amount += $taxable_charged * $self->tax / 100
355   }
356
357   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
358
359   return {
360     'name'   => $name,
361     'amount' => $amount,
362   };
363
364 }
365
366 =back
367
368 =head1 SUBROUTINES
369
370 =over 4
371
372 =item regionselector [ COUNTY STATE COUNTRY [ PREFIX [ ONCHANGE [ DISABLED ] ] ] ]
373
374 =cut
375
376 sub regionselector {
377   my ( $selected_county, $selected_state, $selected_country,
378        $prefix, $onchange, $disabled ) = @_;
379
380   $prefix = '' unless defined $prefix;
381
382   $countyflag = 0;
383
384 #  unless ( @cust_main_county ) { #cache 
385     @cust_main_county = qsearch('cust_main_county', {} );
386     foreach my $c ( @cust_main_county ) {
387       $countyflag=1 if $c->county;
388       #push @{$cust_main_county{$c->country}{$c->state}}, $c->county;
389       $cust_main_county{$c->country}{$c->state}{$c->county} = 1;
390     }
391 #  }
392   $countyflag=1 if $selected_county;
393
394   my $script_html = <<END;
395     <SCRIPT>
396     function opt(what,value,text) {
397       var optionName = new Option(text, value, false, false);
398       var length = what.length;
399       what.options[length] = optionName;
400     }
401     function ${prefix}country_changed(what) {
402       country = what.options[what.selectedIndex].text;
403       for ( var i = what.form.${prefix}state.length; i >= 0; i-- )
404           what.form.${prefix}state.options[i] = null;
405 END
406       #what.form.${prefix}state.options[0] = new Option('', '', false, true);
407
408   foreach my $country ( sort keys %cust_main_county ) {
409     $script_html .= "\nif ( country == \"$country\" ) {\n";
410     foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
411       ( my $dstate = $state ) =~ s/[\n\r]//g;
412       my $text = $dstate || '(n/a)';
413       $script_html .= qq!opt(what.form.${prefix}state, "$dstate", "$text");\n!;
414     }
415     $script_html .= "}\n";
416   }
417
418   $script_html .= <<END;
419     }
420     function ${prefix}state_changed(what) {
421 END
422
423   if ( $countyflag ) {
424     $script_html .= <<END;
425       state = what.options[what.selectedIndex].text;
426       country = what.form.${prefix}country.options[what.form.${prefix}country.selectedIndex].text;
427       for ( var i = what.form.${prefix}county.length; i >= 0; i-- )
428           what.form.${prefix}county.options[i] = null;
429 END
430
431     foreach my $country ( sort keys %cust_main_county ) {
432       $script_html .= "\nif ( country == \"$country\" ) {\n";
433       foreach my $state ( sort keys %{$cust_main_county{$country}} ) {
434         $script_html .= "\nif ( state == \"$state\" ) {\n";
435           #foreach my $county ( sort @{$cust_main_county{$country}{$state}} ) {
436           foreach my $county ( sort keys %{$cust_main_county{$country}{$state}} ) {
437             my $text = $county || '(n/a)';
438             $script_html .=
439               qq!opt(what.form.${prefix}county, "$county", "$text");\n!;
440           }
441         $script_html .= "}\n";
442       }
443       $script_html .= "}\n";
444     }
445   }
446
447   $script_html .= <<END;
448     }
449     </SCRIPT>
450 END
451
452   my $county_html = $script_html;
453   if ( $countyflag ) {
454     $county_html .= qq!<SELECT NAME="${prefix}county" onChange="$onchange" $disabled>!;
455     $county_html .= '</SELECT>';
456   } else {
457     $county_html .=
458       qq!<INPUT TYPE="hidden" NAME="${prefix}county" VALUE="$selected_county">!;
459   }
460
461   my $state_html = qq!<SELECT NAME="${prefix}state" !.
462                    qq!onChange="${prefix}state_changed(this); $onchange" $disabled>!;
463   foreach my $state ( sort keys %{ $cust_main_county{$selected_country} } ) {
464     my $text = $state || '(n/a)';
465     my $selected = $state eq $selected_state ? 'SELECTED' : '';
466     $state_html .= qq(\n<OPTION $selected VALUE="$state">$text</OPTION>);
467   }
468   $state_html .= '</SELECT>';
469
470   $state_html .= '</SELECT>';
471
472   my $country_html = qq!<SELECT NAME="${prefix}country" !.
473                      qq!onChange="${prefix}country_changed(this); $onchange" $disabled>!;
474   my $countrydefault = $conf->config('countrydefault') || 'US';
475   foreach my $country (
476     sort { ($b eq $countrydefault) <=> ($a eq $countrydefault) or $a cmp $b }
477       keys %cust_main_county
478   ) {
479     my $selected = $country eq $selected_country ? ' SELECTED' : '';
480     $country_html .= qq(\n<OPTION$selected VALUE="$country">$country</OPTION>");
481   }
482   $country_html .= '</SELECT>';
483
484   ($county_html, $state_html, $country_html);
485
486 }
487
488 =back
489
490 =head1 BUGS
491
492 regionselector?  putting web ui components in here?  they should probably live
493 somewhere else...
494
495 =head1 SEE ALSO
496
497 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill>, schema.html from the base
498 documentation.
499
500 =cut
501
502 1;
503