compliance solutions, RT#77676
[freeside.git] / FS / FS / TaxEngine / compliance_solutions.pm
1 package FS::TaxEngine::compliance_solutions;
2
3 #some false laziness w/ suretax... uses/based on cch data?  or just imitating
4 # parts of their interface?
5
6 use strict;
7 use base qw( FS::TaxEngine );
8 use FS::Conf;
9 use FS::Record qw( dbh ); #qw( qsearch qsearchs dbh);
10 use Data::Dumper;
11 use Date::Format;
12 use Cpanel::JSON::XS;
13 use SOAP::Lite;
14
15 our $DEBUG = 1; # prints progress messages
16    $DEBUG = 2; # prints decoded request and response (noisy, be careful)
17 #   $DEBUG = 3; # prints raw response from the API, ridiculously unreadable
18
19 our $json = Cpanel::JSON::XS->new->pretty(1);
20
21 our %taxproduct_cache;
22
23 our $conf;
24
25 FS::UID->install_callback( sub {
26     $conf = FS::Conf->new;
27     # should we enable conf caching here?
28 });
29
30 our %REGCODE = ( # can be selected per agent
31 #  ''          => '99',
32   'ILEC'      => '00',
33   'IXC'       => '01',
34   'CLEC'      => '02',
35   'VOIP'      => '03',
36   'ISP'       => '04',
37   'Wireless'  => '05',
38 );
39
40 sub info {
41   { batch    => 0,
42     override => 0, #?
43   }
44 }
45
46 sub add_sale { } # nothing to do here
47
48 sub build_input {
49   my( $self, $cust_bill ) = @_;
50
51   my $cust_main = $cust_bill->cust_main;
52
53   %taxproduct_cache = ();
54
55   # assemble invoice line items 
56   my @lines = map { $self->build_input_item($_, $cust_bill, $cust_main) }
57                   $cust_bill->cust_bill_pkg;
58
59   return if !@lines;
60
61   return \@lines;
62
63 }
64
65 sub build_input_item {
66   my( $self, $cust_bill_pkg, $cust_bill, $cust_main ) = @_;
67
68   # get the part_pkg/fee for this line item, and the relevant part of the
69   # taxproduct cache
70   my $part_item = $cust_bill_pkg->part_X;
71   my $taxproduct_of_class = do {
72     my $part_id = $part_item->table . '#' . $part_item->get($part_item->primary_key);
73     $taxproduct_cache{$part_id} ||= {};
74   };
75
76   my @items = ();
77
78   my $recur_without_usage = $cust_bill_pkg->recur;
79
80   ###
81   # Usage charges
82   ###
83
84   # cursor all this stuff; data sets can be LARGE
85   # (if it gets really out of hand, we can also incrementally write JSON
86   # to a file)
87
88   my $details = FS::Cursor->new('cust_bill_pkg_detail', {
89       billpkgnum  => $cust_bill_pkg->billpkgnum,
90       amount      => { op => '>', value => 0 }
91   }, dbh() );
92   while ( my $cust_bill_pkg_detail = $details->fetch ) {
93
94     # look up the tax product for this class
95     my $classnum = $cust_bill_pkg_detail->classnum;
96     my $taxproduct = $taxproduct_of_class->{ $classnum } ||= do {
97       my $part_pkg_taxproduct = $part_item->taxproduct($classnum);
98       $part_pkg_taxproduct ? $part_pkg_taxproduct->taxproduct : '';
99     };
100     die "no taxproduct configured for pkgpart ".$part_item->pkgpart.
101         ", usage class $classnum\n"
102         if !$taxproduct;
103
104     my $cdrs = FS::Cursor->new('cdr', {
105         detailnum       => $cust_bill_pkg_detail->detailnum,
106         freesidestatus  => 'done',
107     }, dbh() );
108     while ( my $cdr = $cdrs->fetch ) {
109       push @items, {
110         $self->generic_item($cust_bill, $cust_main),
111         record_type   => 'C',
112         unique_id     => 'cdr ' . $cdr->acctid.
113                          ' cust_bill_pkg '.$cust_bill_pkg->billpkgnum, 
114         productcode   => substr($taxproduct,0,4),
115         servicecode   => substr($taxproduct,4,3),
116         orig_Num      => $cdr->src,
117         term_Num      => $cdr->dst,
118         bill_Num      => $cdr->charged_party,
119         charge_amount => $cdr->rated_price, # 4 decimal places
120         minutes       => sprintf('%.1f', $cdr->billsec / 60 ),
121       };
122
123     } # while ($cdrs->fetch)
124
125     # decrement the recurring charge
126     $recur_without_usage -= $cust_bill_pkg_detail->amount;
127
128   } # while ($details->fetch)
129
130   ###
131   # Recurring charge
132   ###
133
134   if ( $recur_without_usage > 0 ) {
135     my $taxproduct = $taxproduct_of_class->{ 'recur' } ||= do {
136       my $part_pkg_taxproduct = $part_item->taxproduct('recur');
137       $part_pkg_taxproduct ? $part_pkg_taxproduct->taxproduct : '';
138     };
139     die "no taxproduct configured for pkgpart ".$part_item->pkgpart.
140         " recurring charge\n"
141         if !$taxproduct;
142
143     # when billing on cancellation there are no units
144     my $units = $self->{cancel} ? 0 : $cust_bill_pkg->units;
145     unshift @items, {
146       $self->generic_item($cust_bill, $cust_main),
147       record_type     => 'S',
148       unique_id       => 'cust_bill_pkg '. $cust_bill_pkg->billpkgnum. ' recur',
149       charge_amount   => $recur_without_usage,
150       location_a      => $cust_bill_pkg->tax_location->zip,
151       productcode     => substr($taxproduct,0,4),
152       servicecode     => substr($taxproduct,4,3),
153       units           => $units,
154     };
155   }
156
157   ###
158   # Setup charge
159   ###
160
161   if ( $cust_bill_pkg->setup > 0 ) {
162     my $taxproduct = $taxproduct_of_class->{ 'setup' } ||= do {
163       my $part_pkg_taxproduct = $part_item->taxproduct('setup');
164       $part_pkg_taxproduct ? $part_pkg_taxproduct->taxproduct : '';
165     };
166     die "no taxproduct configured for pkgpart ".$part_item->pkgpart.
167         " setup charge\n"
168         if !$taxproduct;
169
170     unshift @items, {
171       $self->generic_item($cust_bill, $cust_main),
172       record_type     => 'S',
173       unique_id       => 'cust_bill_pkg '. $cust_bill_pkg->billpkgnum. ' setup',
174       charge_amount   => $cust_bill_pkg->setup,
175       location_a      => $cust_bill_pkg->tax_location->zip,
176       productcode     => substr($taxproduct,0,4),
177       servicecode     => substr($taxproduct,4,3),
178       units           => $cust_bill_pkg->units,
179     };
180   }
181
182   return @items;
183
184 }
185
186 sub generic_item {
187   my( $self, $cust_bill, $cust_main ) = @_;
188
189   warn 'regcode '. $self->{regcode} if $DEBUG;
190
191   (
192     account_number            => $cust_bill->custnum,
193     customer_type             => ( $cust_main->company =~ /\S/ ? '01' : '00' ),
194     invoice_date              => time2str('%Y%m%d', $cust_bill->_date),
195     invoice_number            => $cust_bill->invnum,
196     provider                  => $self->{regcode},
197     safe_harbor_override_flag => 'N',
198     exempt_code               => $cust_main->tax,
199   );
200
201 }
202
203 sub make_taxlines {
204   my( $self, $cust_bill ) = @_;
205
206   die "compliance_solutions-regulatory_code setting is not configured\n"
207     unless $conf->config('compliance_solutions-regulatory_code', $cust_bill->cust_main->agentnum);
208
209   $self->{regcode} = $REGCODE{ $conf->config('compliance_solutions-regulatory_code', $cust_bill->cust_main->agentnum) };
210
211   warn 'regcode '. $self->{regcode} if $DEBUG;
212
213   # assemble the request hash
214   my $input = $self->build_input($cust_bill);
215   if (!$input) {
216     warn "no taxable items in invoice; skipping Compliance Solutions request\n" if $DEBUG;
217     return;
218   }
219
220   warn "sending Compliance Solutions request\n" if $DEBUG;
221   my $request_json = $json->encode(
222     {
223       'access_code' => $conf->config('compliance_solutions-access_code'),
224       'reference'   => 'Invoice #'. $cust_bill->invnum,
225       'input'       => $input,
226     }
227   );
228   warn $request_json if $DEBUG > 1;
229
230   my $soap = SOAP::Lite->service("http://tcms1.csilongwood.com/cgi-bin/taxcalc.wsdl");
231
232   $soap->soapversion('1.2'); #service appears to be flaky with the default 1.1
233
234   my $results = $soap->tax_rate($request_json);
235
236   my %json_result = %{ $json->decode( $results ) };
237   warn Dumper(%json_result) if $DEBUG > 1;
238
239   # handle $results is empty / API/connection failure?
240
241   # status OK
242   unless ( $json_result{status} =~ /^\s*OK\s*$/i ) {
243     warn Dumper($json_result{error_codes}) unless $DEBUG > 1;
244     die 'Compliance Solutions returned status '. $json_result{status}.
245            "; see log for error_codes detail\n";
246   }
247
248   # transmission_error No errors.
249   unless ( $json_result{transmission_error} =~ /^\s*No\s+errors\.\s*$/i ) {
250     warn Dumper($json_result{error_codes}) unless $DEBUG > 1;
251     die 'Compliance Solutions returned transmission_error '. $json_result{transmission_error}.
252            "; see log for error_codes detail\n";
253   }
254
255
256   # error_codes / No errors (for all records... check them individually in loop?
257
258   my @elements = ();
259
260   #handle the response
261   foreach my $tax_data ( @{ $json_result{tax_data} } ) {
262
263     # create a tax rate location if there isn't one yet
264     my $taxname = $tax_data->{descript};
265     my $tax_rate = FS::tax_rate->new({
266         data_vendor   => 'compliance_solutions',
267         taxname       => $taxname,
268         taxclassnum   => '',
269         taxauth       => $tax_data->{'taxauthtype'}, # federal / state / city / district
270         geocode       => $tax_data->{'geocode'},
271         tax           => 0, #not necessary because we query for rates on the
272         fee           => 0, # fly and only store this for the name -> code map??
273     });
274     my $error = $tax_rate->find_or_insert;
275     die "error inserting tax_rate record for '$taxname': $error\n"
276       if $error;
277     $tax_rate = $tax_rate->replace_old;
278
279     my $tax_rate_location = FS::tax_rate_location->new({
280         data_vendor => 'compliance_solutions',
281         geocode     => $tax_data->{'geocode'},
282         state       => $tax_data->{'state'},
283         country     => $tax_data->{'country'},
284     });
285     $error = $tax_rate_location->find_or_insert;
286     die 'error inserting tax_rate_location record for '.  $tax_data->{state}.
287         '/'. $tax_data->{country}. ' ('. $tax_data->{'geocode'}. "): $error\n"
288       if $error;
289     $tax_rate_location = $tax_rate_location->replace_old;
290
291     #unique id: a cust_bill_pkg (setup/recur) or cdr record
292
293     my $taxable_billpkgnum = '';
294     if ( $tax_data->{'unique_id'} =~ /^cust_bill_pkg (\d+)/ ) {
295       $taxable_billpkgnum = $1;
296     } elsif ( $tax_data->{'unique_id'} =~ /^cdr (\d+) cust_bill_pkg (\d+)$/ ) {
297       $taxable_billpkgnum = $2;
298     } else {
299       die 'unparseable unique_id '. $tax_data->{'unique_id'};
300     }
301
302     push @elements, FS::cust_bill_pkg_tax_rate_location->new({
303       taxable_billpkgnum  => $taxable_billpkgnum,
304       taxnum              => $tax_rate->taxnum,
305       taxtype             => 'FS::tax_rate',
306       taxratelocationnum  => $tax_rate_location->taxratelocationnum,
307       amount              => sprintf('%.2f', $tax_data->{taxamount}),
308     });
309
310   }
311
312   return @elements;
313 }
314
315 sub add_taxproduct {
316   my $class = shift;
317   my $desc = shift; # tax code and description, separated by a space.
318   if ($desc =~ s/^(\w{7}+) //) {
319     my $part_pkg_taxproduct = FS::part_pkg_taxproduct->new({
320         'data_vendor' => 'compliance_solutions',
321         'taxproduct'  => $1,
322         'description' => $desc,
323     });
324     # $obj_or_error
325     return $part_pkg_taxproduct->insert || $part_pkg_taxproduct;
326   } else {
327     return "illegal compliance solutions tax code '$desc'";
328   }
329 }
330
331 1;