summaryrefslogtreecommitdiff
path: root/FS/FS/TaxEngine/compliance_solutions.pm
blob: 2cb9cb55147376074242d042bc189b5c85adb888 (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
package FS::TaxEngine::compliance_solutions;

#some false laziness w/ suretax... uses/based on cch data?  or just imitating
# parts of their interface?

use strict;
use base qw( FS::TaxEngine );
use FS::Conf;
use FS::Record qw( dbh ); #qw( qsearch qsearchs dbh);
use Data::Dumper;
use Date::Format;
use Cpanel::JSON::XS;
use SOAP::Lite;

our $DEBUG = 1; # prints progress messages
   $DEBUG = 2; # prints decoded request and response (noisy, be careful)
#   $DEBUG = 3; # prints raw response from the API, ridiculously unreadable

our $json = Cpanel::JSON::XS->new->pretty(1);

our %taxproduct_cache;

our $conf;

FS::UID->install_callback( sub {
    $conf = FS::Conf->new;
    # should we enable conf caching here?
});

our %REGCODE = ( # can be selected per agent
#  ''          => '99',
  'ILEC'      => '00',
  'IXC'       => '01',
  'CLEC'      => '02',
  'VOIP'      => '03',
  'ISP'       => '04',
  'Wireless'  => '05',
);

sub info {
  { batch    => 0,
    override => 0, #?
  }
}

sub add_sale { } # nothing to do here

sub build_input {
  my( $self, $cust_bill ) = @_;

  my $cust_main = $cust_bill->cust_main;

  %taxproduct_cache = ();

  # assemble invoice line items 
  my @lines = map { $self->build_input_item($_, $cust_bill, $cust_main) }
                  $cust_bill->cust_bill_pkg;

  return if !@lines;

  return \@lines;

}

sub build_input_item {
  my( $self, $cust_bill_pkg, $cust_bill, $cust_main ) = @_;

  # get the part_pkg/fee for this line item, and the relevant part of the
  # taxproduct cache
  my $part_item = $cust_bill_pkg->part_X;
  my $taxproduct_of_class = do {
    my $part_id = $part_item->table . '#' . $part_item->get($part_item->primary_key);
    $taxproduct_cache{$part_id} ||= {};
  };

  my @items = ();

  my $recur_without_usage = $cust_bill_pkg->recur;

  ###
  # Usage charges
  ###

  # cursor all this stuff; data sets can be LARGE
  # (if it gets really out of hand, we can also incrementally write JSON
  # to a file)

  my $details = FS::Cursor->new('cust_bill_pkg_detail', {
      billpkgnum  => $cust_bill_pkg->billpkgnum,
      amount      => { op => '>', value => 0 }
  }, dbh() );
  while ( my $cust_bill_pkg_detail = $details->fetch ) {

    # look up the tax product for this class
    my $classnum = $cust_bill_pkg_detail->classnum;
    my $taxproduct = $taxproduct_of_class->{ $classnum } ||= do {
      my $part_pkg_taxproduct = $part_item->taxproduct($classnum);
      $part_pkg_taxproduct ? $part_pkg_taxproduct->taxproduct : '';
    };
    die "no taxproduct configured for pkgpart ".$part_item->pkgpart.
        ", usage class $classnum\n"
        if !$taxproduct;

    my $cdrs = FS::Cursor->new('cdr', {
        detailnum       => $cust_bill_pkg_detail->detailnum,
        freesidestatus  => 'done',
    }, dbh() );
    while ( my $cdr = $cdrs->fetch ) {
      push @items, {
        $self->generic_item($cust_bill, $cust_main),
        record_type   => 'C',
        unique_id     => 'cdr ' . $cdr->acctid.
                         ' cust_bill_pkg '.$cust_bill_pkg->billpkgnum, 
        productcode   => substr($taxproduct,0,4),
        servicecode   => substr($taxproduct,4,3),
        orig_Num      => $cdr->src,
        term_Num      => $cdr->dst,
        bill_Num      => $cdr->charged_party,
        charge_amount => $cdr->rated_price, # 4 decimal places
        minutes       => sprintf('%.1f', $cdr->billsec / 60 ),
      };

    } # while ($cdrs->fetch)

    # decrement the recurring charge
    $recur_without_usage -= $cust_bill_pkg_detail->amount;

  } # while ($details->fetch)

  ###
  # Recurring charge
  ###

  if ( $recur_without_usage > 0 ) {
    my $taxproduct = $taxproduct_of_class->{ 'recur' } ||= do {
      my $part_pkg_taxproduct = $part_item->taxproduct('recur');
      $part_pkg_taxproduct ? $part_pkg_taxproduct->taxproduct : '';
    };
    die "no taxproduct configured for pkgpart ".$part_item->pkgpart.
        " recurring charge\n"
        if !$taxproduct;

    my %item = (
      $self->generic_item($cust_bill, $cust_main),
      record_type     => 'S',
      unique_id       => 'cust_bill_pkg '. $cust_bill_pkg->billpkgnum. ' recur',
      charge_amount   => $recur_without_usage,
      productcode     => substr($taxproduct,0,4),
      servicecode     => substr($taxproduct,4,3),
    );

    # when billing on cancellation there are no units
    $item{units} = $self->{cancel} ? 0 : $cust_bill_pkg->units;

    my $location =  $cust_bill_pkg->tax_location
                 || ( $conf->exists('tax-ship_address')
                        ? $cust_main->ship_location
                        : $cust_main->bill_location
                    );
    $item{location_a} = $location->zip;

    unshift @items, \%item;
  }

  ###
  # Setup charge
  ###

  if ( $cust_bill_pkg->setup > 0 ) {
    my $taxproduct = $taxproduct_of_class->{ 'setup' } ||= do {
      my $part_pkg_taxproduct = $part_item->taxproduct('setup');
      $part_pkg_taxproduct ? $part_pkg_taxproduct->taxproduct : '';
    };
    die "no taxproduct configured for pkgpart ".$part_item->pkgpart.
        " setup charge\n"
        if !$taxproduct;

    my %item = (
      $self->generic_item($cust_bill, $cust_main),
      record_type     => 'S',
      unique_id       => 'cust_bill_pkg '. $cust_bill_pkg->billpkgnum. ' setup',
      charge_amount   => $cust_bill_pkg->setup,
      productcode     => substr($taxproduct,0,4),
      servicecode     => substr($taxproduct,4,3),
      units           => $cust_bill_pkg->units,
    );

    my $location =  $cust_bill_pkg->tax_location
                 || ( $conf->exists('tax-ship_address')
                        ? $cust_main->ship_location
                        : $cust_main->bill_location
                    );
    $item{location_a} = $location->zip;

    unshift @items, \%item;
  }

  return @items;

}

sub generic_item {
  my( $self, $cust_bill, $cust_main ) = @_;

  warn 'regcode '. $self->{regcode} if $DEBUG;

  (
    account_number            => $cust_bill->custnum,
    customer_type             => ( $cust_main->company =~ /\S/ ? '01' : '00' ),
    invoice_date              => time2str('%Y%m%d', $cust_bill->_date),
    invoice_number            => $cust_bill->invnum,
    provider                  => $self->{regcode},
    safe_harbor_override_flag => 'N',
    exempt_code               => $cust_main->tax,
  );

}

sub make_taxlines {
  my( $self, $cust_bill ) = @_;

  die "compliance_solutions-regulatory_code setting is not configured\n"
    unless $conf->config('compliance_solutions-regulatory_code', $cust_bill->cust_main->agentnum);

  $self->{regcode} = $REGCODE{ $conf->config('compliance_solutions-regulatory_code', $cust_bill->cust_main->agentnum) };

  warn 'regcode '. $self->{regcode} if $DEBUG;

  # assemble the request hash
  my $input = $self->build_input($cust_bill);
  if (!$input) {
    warn "no taxable items in invoice; skipping Compliance Solutions request\n" if $DEBUG;
    return;
  }

  warn "sending Compliance Solutions request\n" if $DEBUG;
  my $request_json = $json->encode(
    {
      'access_code' => $conf->config('compliance_solutions-access_code'),
      'reference'   => 'Invoice #'. $cust_bill->invnum,
      'input'       => $input,
    }
  );
  warn $request_json if $DEBUG > 1;
  $cust_bill->taxengine_request($request_json);

  my $soap = SOAP::Lite->service("http://tcms1.csilongwood.com/cgi-bin/taxcalc.wsdl");

  $soap->soapversion('1.2'); #service appears to be flaky with the default 1.1

  my $results = $soap->tax_rate($request_json);

  my %json_result = %{ $json->decode( $results ) };
  warn Dumper(%json_result) if $DEBUG > 1;

  # handle $results is empty / API/connection failure?

  # status OK
  unless ( $json_result{status} =~ /^\s*OK\s*$/i ) {
    warn Dumper($json_result{error_codes}) unless $DEBUG > 1;
    die 'Compliance Solutions returned status '. $json_result{status}.
           "; see log for error_codes detail\n";
  }

  # transmission_error No errors.
  unless ( $json_result{transmission_error} =~ /^\s*No\s+errors\.\s*$/i ) {
    warn Dumper($json_result{error_codes}) unless $DEBUG > 1;
    die 'Compliance Solutions returned transmission_error '. $json_result{transmission_error}.
           "; see log for error_codes detail\n";
  }


  # error_codes / No errors (for all records... check them individually in loop?

  my @elements = ();

  #handle the response
  foreach my $tax_data ( @{ $json_result{tax_data} } ) {

    # create a tax rate location if there isn't one yet
    my $taxname = $tax_data->{descript};
    my $tax_rate = FS::tax_rate->new({
        data_vendor   => 'compliance_solutions',
        taxname       => $taxname,
        taxclassnum   => '',
        taxauth       => $tax_data->{'taxauthtype'}, # federal / state / city / district
        geocode       => $tax_data->{'geocode'},
        tax           => 0, #not necessary because we query for rates on the
        fee           => 0, # fly and only store this for the name -> code map??
    });
    my $error = $tax_rate->find_or_insert;
    die "error inserting tax_rate record for '$taxname': $error\n"
      if $error;
    $tax_rate = $tax_rate->replace_old;

    my $tax_rate_location = FS::tax_rate_location->new({
        data_vendor => 'compliance_solutions',
        geocode     => $tax_data->{'geocode'},
        district    => $tax_data->{'geo_district'},
        state       => $tax_data->{'geo_state'},
        county      => $tax_data->{'geo_county'},
        country     => 'US',
    });
    $error = $tax_rate_location->find_or_insert;
    die 'error inserting tax_rate_location record for '.  $tax_data->{state}.
        '/'. $tax_data->{country}. ' ('. $tax_data->{'geocode'}. "): $error\n"
      if $error;
    $tax_rate_location = $tax_rate_location->replace_old;

    #unique id: a cust_bill_pkg (setup/recur) or cdr record

    my $taxable_billpkgnum = '';
    if ( $tax_data->{'unique_id'} =~ /^cust_bill_pkg (\d+)/ ) {
      $taxable_billpkgnum = $1;
    } elsif ( $tax_data->{'unique_id'} =~ /^cdr (\d+) cust_bill_pkg (\d+)$/ ) {
      $taxable_billpkgnum = $2;
    } else {
      die 'unparseable unique_id '. $tax_data->{'unique_id'};
    }

    push @elements, FS::cust_bill_pkg_tax_rate_location->new({
      taxable_billpkgnum  => $taxable_billpkgnum,
      taxnum              => $tax_rate->taxnum,
      taxtype             => 'FS::tax_rate',
      taxratelocationnum  => $tax_rate_location->taxratelocationnum,
      amount              => sprintf('%.2f', $tax_data->{taxamount}),
    });

  }

  return @elements;
}

sub add_taxproduct {
  my $class = shift;
  my $desc = shift; # tax code and description, separated by a space.
  if ($desc =~ s/^(\w{7}+) //) {
    my $part_pkg_taxproduct = FS::part_pkg_taxproduct->new({
        'data_vendor' => 'compliance_solutions',
        'taxproduct'  => $1,
        'description' => $desc,
    });
    # $obj_or_error
    return $part_pkg_taxproduct->insert || $part_pkg_taxproduct;
  } else {
    return "illegal compliance solutions tax code '$desc'";
  }
}

1;