summaryrefslogtreecommitdiff
path: root/FS/FS/tax_class.pm
blob: 904b575e4df0b722fe81185b93e50c07ad045482 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package FS::tax_class;

use strict;
use vars qw( @ISA );
use FS::UID qw(dbh);
use FS::Record qw( qsearch qsearchs );
use FS::Misc qw( csv_from_fixed );
use FS::part_pkg_taxrate;
use FS::part_pkg_taxoverride;

@ISA = qw(FS::Record);

=head1 NAME

FS::tax_class - Object methods for tax_class records

=head1 SYNOPSIS

  use FS::tax_class;

  $record = new FS::tax_class \%hash;
  $record = new FS::tax_class { 'column' => 'value' };

  $error = $record->insert;

  $error = $new_record->replace($old_record);

  $error = $record->delete;

  $error = $record->check;

=head1 DESCRIPTION

An FS::tax_class object represents a class of tax definitions.  FS::tax_class
inherits from FS::Record.

This should not be confused with L<FS::part_pkg_taxclass>, which defines tax
classes for I<package> definitions.  The two kinds of tax classes are 
completely unrelated.

The following fields are currently supported:

=over 4

=item taxclassnum - Primary key

=item data_vendor - Vendor of the tax data ('cch' or 'billsoft')

=item taxclass - The identifier used in the tax tables for this class.

=item description -  Human readable description of the tax class.

=back

=head1 METHODS

=over 4

=item new HASHREF

Creates a new tax class.  To add the tax class to the database, see L<"insert">.

Note that this stores the hash reference, not a distinct copy of the hash it
points to.  You can ask the object for a copy with the I<hash> method.

=cut

sub table { 'tax_class'; }

=item insert

Adds this record to the database.  If there is an error, returns the error,
otherwise returns false.

=cut

=item delete

Delete this record from the database.

=cut

sub delete {
  my $self = shift;

  #return "Can't delete a tax class which has package tax rates!"
  #if qsearch( 'part_pkg_taxrate', { 'taxclassnumtaxed' => $self->taxclassnum    
  # If this tax class is manually assigned to a package,
  # then return a useful error message instead of just having a conniption.
  my @overrides = qsearch( 'part_pkg_taxoverride', {
                    'taxclassnum' => $self->taxclassnum
                  } );
  if (@overrides) {
    return "Tried to delete tax class " . $self->taxclass .
      ", which is assigned to package definition " .
      join(', ', map { '#'.$_->pkgpart} @overrides) .
      ".";
  }

  # part_pkg_taxrate.taxclass identifies taxes belonging to this taxclass.
  # part_pkg_taxrate.taxclassnumtaxed identifies taxes applying to this 
  # taxclass.
  # If this taxclass goes away, remove all of them. (CCH upgrade CAN'T 
  # remove them, because it removes the tax_class first and then doesn't 
  # know what the taxclassnum was. Yeah, I know. So it will just skip 
  # over them at the TXMATRIX stage.)
  my @part_pkg_taxrate = (
    qsearch('part_pkg_taxrate', { 'taxclassnum' => $self->taxclassnum }),
    qsearch('part_pkg_taxrate', { 'taxclassnumtaxed' => $self->taxclassnum })
  );
  foreach (@part_pkg_taxrate) {
    my $error = $_->delete;
    return "when deleting taxclass ".$self->taxclass.": $error"
      if $error;
  }

  $self->SUPER::delete(@_);

}

=item replace OLD_RECORD

Replaces the OLD_RECORD with this one in the database.  If there is an error,
returns the error, otherwise returns false.

=cut

=item check

Checks all fields to make sure this is a valid tax class.  If there is
an error, returns the error, otherwise returns false.  Called by the insert
and replace methods.

=cut

sub check {
  my $self = shift;

  my $error = 
    $self->ut_numbern('taxclassnum')
    || $self->ut_text('taxclass')
    || $self->ut_textn('data_vendor')
    || $self->ut_textn('description')
  ;
  return $error if $error;

  $self->SUPER::check;
}

=item batch_import

Loads part_pkg_taxrate records from an external CSV file.  If there is
an error, returns the error, otherwise returns false. 

=cut 

sub batch_import {
  my ($param, $job) = @_;

  my $fh = $param->{filehandle};
  my $format = $param->{'format'};

  my @fields;
  my $hook;
  my $endhook;
  my $data = {};
  my $imported = 0;
  my $dbh = dbh;

  my @column_lengths = ();
  my @column_callbacks = ();
  if ( $format eq 'cch-fixed' || $format eq 'cch-fixed-update' ) {
    $format =~ s/-fixed//;
    push @column_lengths, qw( 8 10 3 2 2 10 100 );
    push @column_lengths, 1 if $format eq 'cch-update';
  }

  my $line;
  my ( $count, $last, $min_sec ) = (0, time, 5); #progressbar
  if ( $job || scalar(@column_lengths) ) {
    my $error = csv_from_fixed(\$fh, \$count, \@column_lengths);
    return $error if $error;
  }

  if ( $format eq 'cch' || $format eq 'cch-update' ) {
    @fields = qw( table name pos length number value description );
    push @fields, 'actionflag' if $format eq 'cch-update';

    $hook = sub { 
      my $hash = shift;

      if ($hash->{'table'} eq 'DETAIL') {
        push @{$data->{'taxcat'}}, [ $hash->{'value'}, $hash->{'description'} ]
          if ($hash->{'name'} eq 'TAXCAT' &&
             (!exists($hash->{actionflag}) || $hash->{actionflag} eq 'I') );

        push @{$data->{'taxtype'}}, [ $hash->{'value'}, $hash->{'description'} ]
          if ($hash->{'name'} eq 'TAXTYPE' &&
             (!exists($hash->{actionflag}) || $hash->{actionflag} eq 'I') );

        if (exists($hash->{actionflag}) && $hash->{actionflag} eq 'D') {
          my $name = $hash->{'name'};
          my $value = $hash->{'value'};
          return "Bad value for $name: $value"
            unless $value =~ /^\d+$/;

          if ($name eq 'TAXCAT' || $name eq 'TAXTYPE') {
            my @tax_class = qsearch( 'tax_class',
                                     { 'data_vendor' => 'cch' },
                                     '',
                                     "AND taxclass LIKE '".
                                       ($name eq 'TAXTYPE' ? $value : '%').":".
                                       ($name eq 'TAXCAT' ? $value : '%')."'",
                                   );
            foreach (@tax_class) {
              my $error = $_->delete;
              return $error if $error;
            }
          }
        }

      }

      delete($hash->{$_})
        for qw( data_vendor table name pos length number value description );
      delete($hash->{actionflag}) if exists($hash->{actionflag});

      '';

    };

    $endhook = sub { 

      my $sql = "SELECT DISTINCT ".
         "substring(taxclass from 1 for position(':' in taxclass)-1),".
         "substring(description from 1 for position(':' in description)-1) ".
         "FROM tax_class WHERE data_vendor='cch'";

      my $sth = $dbh->prepare($sql) or die $dbh->errstr;
      $sth->execute or die $sth->errstr;
      my @old_types = @{$sth->fetchall_arrayref};

      $sql = "SELECT DISTINCT ".
         "substring(taxclass from position(':' in taxclass)+1),".
         "substring(description from position(':' in description)+1) ".
         "FROM tax_class WHERE data_vendor='cch'";

      $sth = $dbh->prepare($sql) or die $dbh->errstr;
      $sth->execute or die $sth->errstr;
      my @old_cats = @{$sth->fetchall_arrayref};

      my $catcount  = exists($data->{'taxcat'})  ? scalar(@{$data->{'taxcat'}})
                                                 : 0;
      my $typecount = exists($data->{'taxtype'}) ? scalar(@{$data->{'taxtype'}})
                                                 : 0;

      my $count = scalar(@old_types) * $catcount
                + $typecount * (scalar(@old_cats) + $catcount);

      $imported = 1 if $format eq 'cch-update';  #empty file ok

      foreach my $type (@old_types) {
        foreach my $cat (@{$data->{'taxcat'}}) {

          if ( $job ) {  # progress bar
            if ( time - $min_sec > $last ) {
              my $error = $job->update_statustext(
                int( 100 * $imported / $count ). ",Importing tax classes"
              );
              die $error if $error;
              $last = time;
            }
          }

          my %hash = ( 'data_vendor' => 'cch',
                       'taxclass'    => $type->[0].':'.$cat->[0],
                       'description' => $type->[1].':'.$cat->[1],
                     );
          unless ( qsearchs('tax_class', \%hash) ) {
            my $tax_class = new FS::tax_class \%hash;
            my $error = $tax_class->insert;

            return "can't insert tax_class for ".
                   " old TAXTYPE ". $type->[0].':'.$type->[1].
                   " and new TAXCAT ". $cat->[0].':'. $cat->[1].
                   " : $error"
              if $error;
          }

          $imported++;
          
        }
      }

      foreach my $type (@{$data->{'taxtype'}}) {
        foreach my $cat (@old_cats, @{$data->{'taxcat'}}) {

          if ( $job ) {  # progress bar
            if ( time - $min_sec > $last ) {
              my $error = $job->update_statustext(
                int( 100 * $imported / $count ). ",Importing tax classes"
              );
              die $error if $error;
              $last = time;
            }
          }

          my $tax_class =
            new FS::tax_class( { 'data_vendor' => 'cch',
                                 'taxclass'    => $type->[0].':'.$cat->[0],
                                 'description' => $type->[1].':'.$cat->[1],
                             } );
          my $error = $tax_class->insert;
          return "can't insert tax_class for new TAXTYPE $type and TAXCAT $cat: $error" if $error;
          $imported++;
        }
      }

      '';
    };

  } elsif ( $format eq 'billsoft' ) {
    # Billsoft doesn't actually have a format for this; it's just my own
    # invention to have a way to load the list of tax classes from the 
    # documentation.
    @fields = qw( taxclass description );
    $endhook = $hook = sub {};

  } elsif ( $format eq 'extended' ) {
    die "unimplemented\n";
    @fields = qw( );
    $hook = sub {};
  } else {
    die "unknown format $format";
  }

  eval "use Text::CSV_XS;";
  die $@ if $@;

  my $csv = new Text::CSV_XS;

  local $SIG{HUP} = 'IGNORE';
  local $SIG{INT} = 'IGNORE';
  local $SIG{QUIT} = 'IGNORE';
  local $SIG{TERM} = 'IGNORE';
  local $SIG{TSTP} = 'IGNORE';
  local $SIG{PIPE} = 'IGNORE';

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;
  
  while ( defined($line=<$fh>) ) {

    if ( $job ) {  # progress bar
      if ( time - $min_sec > $last ) {
        my $error = $job->update_statustext(
          int( 100 * $imported / $count ). ",Importing tax classes"
        );
        die $error if $error;
        $last = time;
      }
    }

    $csv->parse($line) or do {
      $dbh->rollback if $oldAutoCommit;
      return "can't parse: ". $csv->error_input();
    };

    my @columns = $csv->fields();

    my %tax_class = ( 'data_vendor' => $format );
    foreach my $field ( @fields ) {
      $tax_class{$field} = shift @columns; 
    }
    if ( scalar( @columns ) ) {
      $dbh->rollback if $oldAutoCommit;
      return "Unexpected trailing columns in line (wrong format?) importing tax_class: $line";
    }

    my $error = &{$hook}(\%tax_class);
    if ( $error ) {
      $dbh->rollback if $oldAutoCommit;
      return $error;
    }

    next unless scalar(keys %tax_class);

    my $tax_class = new FS::tax_class( \%tax_class );
    $error = $tax_class->insert;
    if ( $error ) {
      $dbh->rollback if $oldAutoCommit;
      return "can't insert tax_class for $line: $error";
    }

    $imported++;
  }

  my $error = &{$endhook}();
  if ( $error ) {
    $dbh->rollback if $oldAutoCommit;
    return "can't run end hook: $error";
  }

  $dbh->commit or die $dbh->errstr if $oldAutoCommit;

  return "Empty File!" unless ($imported || $format eq 'cch-update');

  ''; #no error

}

=back

=head1 BUGS

=head1 SEE ALSO

L<FS::Record>, schema.html from the base documentation.

=cut

1;