fix cch update adding a TAXCAT, RT#21687
[freeside.git] / FS / FS / tax_class.pm
1 package FS::tax_class;
2
3 use strict;
4 use vars qw( @ISA );
5 use FS::UID qw(dbh);
6 use FS::Record qw( qsearch qsearchs );
7 use FS::Misc qw( csv_from_fixed );
8
9 @ISA = qw(FS::Record);
10
11 =head1 NAME
12
13 FS::tax_class - Object methods for tax_class records
14
15 =head1 SYNOPSIS
16
17   use FS::tax_class;
18
19   $record = new FS::tax_class \%hash;
20   $record = new FS::tax_class { 'column' => 'value' };
21
22   $error = $record->insert;
23
24   $error = $new_record->replace($old_record);
25
26   $error = $record->delete;
27
28   $error = $record->check;
29
30 =head1 DESCRIPTION
31
32 An FS::tax_class object represents a tax class.  FS::tax_class
33 inherits from FS::Record.  The following fields are currently supported:
34
35 =over 4
36
37 =item taxclassnum
38
39 Primary key
40
41 =item data_vendor
42
43 Vendor of the tax data
44
45 =item taxclass
46
47 Tax class
48
49 =item description
50
51 Human readable description of the tax class
52
53 =back
54
55 =head1 METHODS
56
57 =over 4
58
59 =item new HASHREF
60
61 Creates a new tax class.  To add the tax class to the database, see L<"insert">.
62
63 Note that this stores the hash reference, not a distinct copy of the hash it
64 points to.  You can ask the object for a copy with the I<hash> method.
65
66 =cut
67
68 sub table { 'tax_class'; }
69
70 =item insert
71
72 Adds this record to the database.  If there is an error, returns the error,
73 otherwise returns false.
74
75 =cut
76
77 =item delete
78
79 Delete this record from the database.
80
81 =cut
82
83 sub delete {
84   my $self = shift;
85
86   return "Can't delete a tax class which has package tax rates!"
87     if qsearch( 'part_pkg_taxrate', { 'taxclassnum' => $self->taxclassnum } );
88
89   return "Can't delete a tax class which has package tax rates!"
90     if qsearch( 'part_pkg_taxrate', { 'taxclassnumtaxed' => $self->taxclassnum } );
91
92   return "Can't delete a tax class which has package tax overrides!"
93     if qsearch( 'part_pkg_taxoverride', { 'taxclassnum' => $self->taxclassnum } );
94
95   local $SIG{HUP} = 'IGNORE';
96   local $SIG{INT} = 'IGNORE';
97   local $SIG{QUIT} = 'IGNORE';
98   local $SIG{TERM} = 'IGNORE';
99   local $SIG{TSTP} = 'IGNORE';
100   local $SIG{PIPE} = 'IGNORE';
101
102   my $oldAutoCommit = $FS::UID::AutoCommit;
103   local $FS::UID::AutoCommit = 0;
104   my $dbh = dbh;
105
106   foreach my $tax_rate (
107     qsearch( 'tax_rate', { taxclassnum=>$self->taxclassnum } )
108   ) {
109     my $error = $tax_rate->delete;
110     if ( $error ) {
111       $dbh->rollback if $oldAutoCommit;
112       return $error;
113     }
114   }
115
116   my $error = $self->SUPER::delete(@_);
117   if ( $error ) {
118     $dbh->rollback if $oldAutoCommit;
119     return $error;
120   }
121
122   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
123
124   '';
125
126 }
127
128 =item replace OLD_RECORD
129
130 Replaces the OLD_RECORD with this one in the database.  If there is an error,
131 returns the error, otherwise returns false.
132
133 =cut
134
135 =item check
136
137 Checks all fields to make sure this is a valid tax class.  If there is
138 an error, returns the error, otherwise returns false.  Called by the insert
139 and replace methods.
140
141 =cut
142
143 sub check {
144   my $self = shift;
145
146   my $error = 
147     $self->ut_numbern('taxclassnum')
148     || $self->ut_text('taxclass')
149     || $self->ut_textn('data_vendor')
150     || $self->ut_textn('description')
151   ;
152   return $error if $error;
153
154   $self->SUPER::check;
155 }
156
157 =item batch_import
158
159 Loads part_pkg_taxrate records from an external CSV file.  If there is
160 an error, returns the error, otherwise returns false. 
161
162 =cut 
163
164 sub batch_import {
165   my ($param, $job) = @_;
166
167   my $fh = $param->{filehandle};
168   my $format = $param->{'format'};
169
170   my @fields;
171   my $hook;
172   my $endhook;
173   my $data = {};
174   my $imported = 0;
175   my $dbh = dbh;
176
177   my @column_lengths = ();
178   my @column_callbacks = ();
179   if ( $format eq 'cch-fixed' || $format eq 'cch-fixed-update' ) {
180     $format =~ s/-fixed//;
181     push @column_lengths, qw( 8 10 3 2 2 10 100 );
182     push @column_lengths, 1 if $format eq 'cch-update';
183   }
184
185   my $line;
186   my ( $count, $last, $min_sec ) = (0, time, 5); #progressbar
187   if ( $job || scalar(@column_lengths) ) {
188     my $error = csv_from_fixed(\$fh, \$count, \@column_lengths);
189     return $error if $error;
190   }
191
192   if ( $format eq 'cch' || $format eq 'cch-update' ) {
193     @fields = qw( table name pos length number value description );
194     push @fields, 'actionflag' if $format eq 'cch-update';
195
196     $hook = sub { 
197       my $hash = shift;
198
199       if ($hash->{'table'} eq 'DETAIL') {
200         push @{$data->{'taxcat'}}, [ $hash->{'value'}, $hash->{'description'} ]
201           if ($hash->{'name'} eq 'TAXCAT' &&
202              (!exists($hash->{actionflag}) || $hash->{actionflag} eq 'I') );
203
204         push @{$data->{'taxtype'}}, [ $hash->{'value'}, $hash->{'description'} ]
205           if ($hash->{'name'} eq 'TAXTYPE' &&
206              (!exists($hash->{actionflag}) || $hash->{actionflag} eq 'I') );
207
208         if (exists($hash->{actionflag}) && $hash->{actionflag} eq 'D') {
209           my $name = $hash->{'name'};
210           my $value = $hash->{'value'};
211           return "Bad value for $name: $value"
212             unless $value =~ /^\d+$/;
213
214           if ($name eq 'TAXCAT' || $name eq 'TAXTYPE') {
215             my @tax_class = qsearch( 'tax_class',
216                                      { 'data_vendor' => 'cch' },
217                                      '',
218                                      "AND taxclass LIKE '".
219                                        ($name eq 'TAXTYPE' ? $value : '%').":".
220                                        ($name eq 'TAXCAT' ? $value : '%')."'",
221                                    );
222             foreach (@tax_class) {
223               my $error = $_->delete;
224               return $error if $error;
225             }
226           }
227         }
228
229       }
230
231       delete($hash->{$_})
232         for qw( data_vendor table name pos length number value description );
233       delete($hash->{actionflag}) if exists($hash->{actionflag});
234
235       '';
236
237     };
238
239     $endhook = sub { 
240
241       my $sql = "SELECT DISTINCT ".
242          "substring(taxclass from 1 for position(':' in taxclass)-1),".
243          "substring(description from 1 for position(':' in description)-1) ".
244          "FROM tax_class WHERE data_vendor='cch'";
245
246       my $sth = $dbh->prepare($sql) or die $dbh->errstr;
247       $sth->execute or die $sth->errstr;
248       my @old_types = @{$sth->fetchall_arrayref};
249
250       $sql = "SELECT DISTINCT ".
251          "substring(taxclass from position(':' in taxclass)+1),".
252          "substring(description from position(':' in description)+1) ".
253          "FROM tax_class WHERE data_vendor='cch'";
254
255       $sth = $dbh->prepare($sql) or die $dbh->errstr;
256       $sth->execute or die $sth->errstr;
257       my @old_cats = @{$sth->fetchall_arrayref};
258
259       my $catcount  = exists($data->{'taxcat'})  ? scalar(@{$data->{'taxcat'}})
260                                                  : 0;
261       my $typecount = exists($data->{'taxtype'}) ? scalar(@{$data->{'taxtype'}})
262                                                  : 0;
263
264       my $count = scalar(@old_types) * $catcount
265                 + $typecount * (scalar(@old_cats) + $catcount);
266
267       $imported = 1 if $format eq 'cch-update';  #empty file ok
268
269       foreach my $type (@old_types) {
270         foreach my $cat (@{$data->{'taxcat'}}) {
271
272           if ( $job ) {  # progress bar
273             if ( time - $min_sec > $last ) {
274               my $error = $job->update_statustext(
275                 int( 100 * $imported / $count ). ",Importing tax classes"
276               );
277               die $error if $error;
278               $last = time;
279             }
280           }
281
282           my %hash = ( 'data_vendor' => 'cch',
283                        'taxclass'    => $type->[0].':'.$cat->[0],
284                        'description' => $type->[1].':'.$cat->[1],
285                      );
286           unless ( qsearchs('tax_class', \%hash) ) {
287             my $tax_class = new FS::tax_class \%hash;
288             my $error = $tax_class->insert;
289
290             return "can't insert tax_class for ".
291                    " old TAXTYPE ". $type->[0].':'.$type->[1].
292                    " and new TAXCAT ". $cat->[0].':'. $cat->[1].
293                    " : $error"
294               if $error;
295           }
296
297           $imported++;
298           
299         }
300       }
301
302       foreach my $type (@{$data->{'taxtype'}}) {
303         foreach my $cat (@old_cats, @{$data->{'taxcat'}}) {
304
305           if ( $job ) {  # progress bar
306             if ( time - $min_sec > $last ) {
307               my $error = $job->update_statustext(
308                 int( 100 * $imported / $count ). ",Importing tax classes"
309               );
310               die $error if $error;
311               $last = time;
312             }
313           }
314
315           my $tax_class =
316             new FS::tax_class( { 'data_vendor' => 'cch',
317                                  'taxclass'    => $type->[0].':'.$cat->[0],
318                                  'description' => $type->[1].':'.$cat->[1],
319                              } );
320           my $error = $tax_class->insert;
321           return "can't insert tax_class for new TAXTYPE $type and TAXCAT $cat: $error" if $error;
322           $imported++;
323         }
324       }
325
326       '';
327     };
328
329   } elsif ( $format eq 'extended' ) {
330     die "unimplemented\n";
331     @fields = qw( );
332     $hook = sub {};
333   } else {
334     die "unknown format $format";
335   }
336
337   eval "use Text::CSV_XS;";
338   die $@ if $@;
339
340   my $csv = new Text::CSV_XS;
341
342   local $SIG{HUP} = 'IGNORE';
343   local $SIG{INT} = 'IGNORE';
344   local $SIG{QUIT} = 'IGNORE';
345   local $SIG{TERM} = 'IGNORE';
346   local $SIG{TSTP} = 'IGNORE';
347   local $SIG{PIPE} = 'IGNORE';
348
349   my $oldAutoCommit = $FS::UID::AutoCommit;
350   local $FS::UID::AutoCommit = 0;
351   
352   while ( defined($line=<$fh>) ) {
353
354     if ( $job ) {  # progress bar
355       if ( time - $min_sec > $last ) {
356         my $error = $job->update_statustext(
357           int( 100 * $imported / $count ). ",Importing tax classes"
358         );
359         die $error if $error;
360         $last = time;
361       }
362     }
363
364     $csv->parse($line) or do {
365       $dbh->rollback if $oldAutoCommit;
366       return "can't parse: ". $csv->error_input();
367     };
368
369     my @columns = $csv->fields();
370
371     my %tax_class = ( 'data_vendor' => $format );
372     foreach my $field ( @fields ) {
373       $tax_class{$field} = shift @columns; 
374     }
375     if ( scalar( @columns ) ) {
376       $dbh->rollback if $oldAutoCommit;
377       return "Unexpected trailing columns in line (wrong format?) importing tax_class: $line";
378     }
379
380     my $error = &{$hook}(\%tax_class);
381     if ( $error ) {
382       $dbh->rollback if $oldAutoCommit;
383       return $error;
384     }
385
386     next unless scalar(keys %tax_class);
387
388     my $tax_class = new FS::tax_class( \%tax_class );
389     $error = $tax_class->insert;
390     if ( $error ) {
391       $dbh->rollback if $oldAutoCommit;
392       return "can't insert tax_class for $line: $error";
393     }
394
395     $imported++;
396   }
397
398   my $error = &{$endhook}();
399   if ( $error ) {
400     $dbh->rollback if $oldAutoCommit;
401     return "can't run end hook: $error";
402   }
403
404   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
405
406   return "Empty File!" unless ($imported || $format eq 'cch-update');
407
408   ''; #no error
409
410 }
411
412 =back
413
414 =head1 BUGS
415
416 =head1 SEE ALSO
417
418 L<FS::Record>, schema.html from the base documentation.
419
420 =cut
421
422 1;
423
424