ef529c4a5332e265981eef9b93894964e12c8838
[freeside.git] / FS / FS / Cron / tax_rate_update.pm
1 #!/usr/bin/perl
2
3 =head1 NAME
4
5 FS::Cron::tax_rate_update
6
7 =head1 DESCRIPTION
8
9 Cron routine to update city/district sales tax rates in I<cust_main_county>.
10 Currently supports sales tax in the state of Washington.
11
12 =head2 wa_sales
13
14 =item Tax Rate Download
15
16 Once each month, update the tax tables from the WA DOR website.
17
18 =item Customer Address Rate Classification
19
20 Find cust_location rows in WA with no tax district.  Try to determine
21 a tax district.  Otherwise, generate a log error that address needs
22 to be correctd.
23
24 =cut
25
26 use strict;
27 use warnings;
28 use feature 'state';
29
30 use Exporter;
31 our @EXPORT_OK = qw(
32   tax_rate_update
33   wa_sales_update_tax_table
34   wa_sales_log_customer_without_tax_district
35 );
36
37 use Carp qw(croak);
38 use DateTime;
39 use File::Temp 'tempdir';
40 use File::Slurp qw(read_file write_file);
41 use LWP::UserAgent;
42 use Spreadsheet::XLSX;
43 use Text::CSV;
44
45 use FS::Conf;
46 use FS::cust_main;
47 use FS::cust_main_county;
48 use FS::geocode_Mixin;
49 use FS::Log;
50 use FS::part_pkg_taxclass;
51 use FS::Record qw(qsearch qsearchs dbh);
52 use FS::upgrade_journal;
53
54 our $DEBUG = 0;
55
56 =head1 FUNCTIONS
57
58 =head2 tax_rate_update
59
60 Cron routine for freeside_daily.
61
62 Run one of the available cron functions based on conf value tax_district_method
63
64 =cut
65
66 sub tax_rate_update {
67
68   # Currently only wa_sales is supported
69   my $tax_district_method = conf_tax_district_method();
70
71   return unless $tax_district_method;
72
73   if ( exists &{$tax_district_method} ) {
74     my $func = \&{$tax_district_method};
75     $func->();
76   } else {
77     my $log = FS::Log->new('tax_rate_update');
78     $log->error( "Unhandled tax_district_method($tax_district_method)" );
79   }
80
81 }
82
83 =head2 wa_sales
84
85 Monthly:   Update the complete WA state tax tables
86 Every Run: Log errors for cust_location records without a district
87
88 =cut
89
90 sub wa_sales {
91
92   return
93     unless conf_tax_district_method()
94         && conf_tax_district_method() eq 'wa_sales';
95
96   my $dt_now  = DateTime->now;
97   my $year    = $dt_now->year;
98   my $quarter = $dt_now->quarter;
99
100   my $journal_label =
101     sprintf 'wa_sales_update_tax_table_%sQ%s', $year, $quarter;
102
103   unless ( FS::upgrade_journal->is_done( $journal_label ) ) {
104     local $@;
105
106     eval{ wa_sales_update_tax_table(); };
107     log_error_and_die( "Error updating tax tables: $@" )
108       if $@;
109     FS::upgrade_journal->set_done( $journal_label );
110   }
111
112   wa_sales_log_customer_without_tax_district();
113
114   '';
115
116 }
117
118 =head2 wa_sales_log_customer_without_tax_district
119
120 For any cust_location records
121 * In WA state
122 * Attached to non cancelled packages
123 * With no tax district
124
125 Classify the tax district for the record using the WA State Dept of
126 Revenue API.  If this fails, generate an error into system log so
127 address can be corrected
128
129 =cut
130
131 sub wa_sales_log_customer_without_tax_district {
132
133   return
134     unless conf_tax_district_method()
135         && conf_tax_district_method() eq 'wa_sales';
136
137   my %qsearch_cust_location = (
138     table => 'cust_location',
139     select => '
140       cust_location.locationnum,
141       cust_location.custnum,
142       cust_location.address1,
143       cust_location.city,
144       cust_location.state,
145       cust_location.zip
146     ',
147     addl_from => '
148       LEFT JOIN cust_main USING (custnum)
149       LEFT JOIN cust_pkg ON cust_location.locationnum = cust_pkg.locationnum
150     ',
151     extra_sql => sprintf(q{
152         WHERE cust_location.state = 'WA'
153         AND (
154              cust_location.district IS NULL
155           or cust_location.district = ''
156         )
157         AND cust_pkg.pkgnum IS NOT NULL
158         AND (
159              cust_pkg.cancel > %s
160           OR cust_pkg.cancel IS NULL
161         )
162       }, time()
163     ),
164   );
165
166   for my $cust_location ( qsearch( \%qsearch_cust_location )) {
167     local $@;
168     log_info_and_warn(
169       sprintf
170         'Attempting to classify district for cust_location ' .
171         'locationnum(%s) address(%s)',
172           $cust_location->locationnum,
173           $cust_location->address1,
174     );
175
176     eval {
177       FS::geocode_Mixin::process_district_update(
178         'FS::cust_location',
179         $cust_location->locationnum
180       );
181     };
182
183     if ( $@ ) {
184       # Error indicates a crash, not an error looking up district
185       # process_district_udpate will generate log messages for those errors
186       log_error_and_warn(
187         sprintf "Classify district error for cust_location(%s): %s",
188           $cust_location->locationnum,
189           $@
190       );
191     }
192
193     sleep 1; # Be polite to WA DOR API
194   }
195
196   for my $cust_location ( qsearch( \%qsearch_cust_location )) {
197     log_error_and_warn(
198       sprintf
199         "Customer address in WA lacking tax district classification. ".
200         "custnum(%s) ".
201         "locationnum(%s) ".
202         "address(%s, %s %s, %s) ".
203         "[https://webgis.dor.wa.gov/taxratelookup/SalesTax.aspx]",
204           map { $cust_location->$_ }
205           qw( custnum locationnum address1 city state zip )
206     );
207   }
208
209 }
210
211
212 =head2 wa_sales_update_tax_table \%args
213
214 Update city/district sales tax rates in L<FS::cust_main_county> from the
215 Washington State Department of Revenue published data files.
216
217 Creates, or updates, a L<FS::cust_main_county> row for every tax district
218 in Washington state. Some cities have different tax rates based on the
219 address, within the city.  Because of this, some cities have multiple
220 districts.
221
222 If tax classes are enabled, a row is created in every tax class for
223 every district.
224
225 Customer addresses aren't classified into districts here.  Instead,
226 when a Washington state address is inserted or changed in L<FS::cust_location>,
227 a job is queued for FS::geocode_Mixin::process_district_update, to ask the
228 Washington state API which tax district to use for this address.
229
230 All arguments are optional:
231
232   filename: Skip file download, and process the specified filename instead
233
234   taxname:  Updated or created records will be set to the given tax name.
235             If not specified, conf value 'tax_district_taxname' is used
236
237   year:     Specify year for tax table download.  Defaults to current year
238
239   quarter:  Specify quarter for tax table download.  Defaults to current quarter
240
241 =head3 Washington State Department of Revenue Resources
242
243 The state of Washington makes data files available via their public website.
244 It's possible the availability or format of these files may change.  As of now,
245 the only data file that contains both city and county names is published in
246 XLSX format.
247
248 =over 4
249
250 =item WA Dept of Revenue
251
252 https://dor.wa.gov
253
254 =item Data file downloads
255
256 https://dor.wa.gov/find-taxes-rates/sales-and-use-tax-rates/downloadable-database
257
258 =item XLSX file example
259
260 https://dor.wa.gov/sites/default/files/legacy/Docs/forms/ExcsTx/LocSalUseTx/ExcelLocalSlsUserates_19_Q1.xlsx
261
262 =item CSV file example
263
264 https://dor.wa.gov/sites/default/files/legacy/downloads/Add_DataRates2018Q4.zip
265
266
267 =item Address lookup API tool
268
269 http://webgis.dor.wa.gov/webapi/AddressRates.aspx?output=xml&addr=410 Terry Ave. North&city=&zip=98100
270
271 =back
272
273 =cut
274
275 sub wa_sales_update_tax_table {
276   my $args = shift;
277
278   croak 'wa_sales_update_tax_table requires \$args hashref'
279     if $args && !ref $args;
280
281   return
282     unless conf_tax_district_method()
283         && conf_tax_district_method() eq 'wa_sales';
284
285   $args->{taxname} ||= FS::Conf->new->config('tax_district_taxname');
286   $args->{year}    ||= DateTime->now->year;
287   $args->{quarter} ||= DateTime->now->quarter;
288
289   log_info_and_warn(
290     "Begin wa_sales_update_tax_table() ".
291     join ', ' => (
292       map{ "$_ => ". ( $args->{$_} || 'undef' ) }
293       sort keys %$args
294     )
295   );
296
297   $args->{temp_dir} ||= tempdir();
298
299   $args->{filename} ||= wa_sales_fetch_xlsx_file( $args );
300
301   $args->{tax_districts} = wa_sales_parse_xlsx_file( $args );
302
303   wa_sales_update_cust_main_county( $args );
304
305   log_info_and_warn( 'Finished wa_sales_update_tax_table()' );
306 }
307
308 =head2 wa_sales_update_cust_main_county \%args
309
310 Create or update the L<FS::cust_main_county> records with new data
311
312 =cut
313
314 sub wa_sales_update_cust_main_county {
315   my $args = shift;
316
317   return
318     unless conf_tax_district_method()
319         && conf_tax_district_method() eq 'wa_sales';
320
321   croak 'wa_sales_update_cust_main_county requires $args hashref'
322     unless ref $args
323         && ref $args->{tax_districts};
324
325   my $insert_count = 0;
326   my $update_count = 0;
327   my $same_count   = 0;
328
329   # Work within a SQL transaction
330   local $FS::UID::AutoCommit = 0;
331
332   for my $taxclass ( FS::part_pkg_taxclass->taxclass_names ) {
333     $taxclass ||= undef; # trap empty string when taxclasses are disabled
334
335     my %cust_main_county =
336       map { $_->district => $_ }
337       qsearch(
338         cust_main_county => {
339           district => { op => '!=', value => undef },
340           state    => 'WA',
341           country  => 'US',
342           source   => 'wa_sales',
343           taxclass => $taxclass,
344         }
345       );
346
347     for my $district ( @{ $args->{tax_districts} } ) {
348       if ( my $row = $cust_main_county{ $district->{district} } ) {
349
350         # District already exists in this taxclass, update if necessary
351         #
352         # If admin updates value of conf tax_district_taxname, instead of
353         # creating an entire separate set of tax rows with
354         # the new taxname, update the taxname on existing records
355
356         {
357           # Supress warning on taxname comparison, when taxname is undef
358           no warnings 'uninitialized';
359
360           if (
361             $row->tax == ( $district->{tax_combined} * 100 )
362             &&    $row->taxname eq    $args->{taxname}
363             && uc $row->county  eq uc $district->{county}
364             && uc $row->city    eq uc $district->{city}
365           ) {
366             $same_count++;
367             next;
368           }
369         }
370
371         $row->city( uc $district->{city} );
372         $row->county( uc $district->{county} );
373         $row->taxclass( $taxclass );
374         $row->taxname( $args->{taxname} || undef );
375         $row->tax( $district->{tax_combined} * 100 );
376
377         if ( my $error = $row->replace ) {
378           dbh->rollback;
379           local $FS::UID::AutoCommit = 1;
380           log_error_and_die(
381             sprintf
382               "Error updating cust_main_county row %s for district %s: %s",
383               $row->taxnum,
384               $district->{district},
385               $error
386           );
387         }
388
389         $update_count++;
390
391       } else {
392
393         # District doesn't exist, create row
394
395         my $row = FS::cust_main_county->new({
396           district => $district->{district},
397           city     => uc $district->{city},
398           county   => uc $district->{county},
399           state    => 'WA',
400           country  => 'US',
401           taxclass => $taxclass,
402           taxname  => $args->{taxname} || undef,
403           tax      => $district->{tax_combined} * 100,
404           source   => 'wa_sales',
405         });
406
407         if ( my $error = $row->insert ) {
408           dbh->rollback;
409           local $FS::UID::AutoCommit = 1;
410           log_error_and_die(
411             sprintf
412               "Error inserting cust_main_county row for district %s: %s",
413               $district->{district},
414               $error
415           );
416         }
417
418         $cust_main_county{ $district->{district} } = $row;
419         $insert_count++;
420       }
421
422     } # /foreach $district
423   } # /foreach $taxclass
424
425   dbh->commit;
426
427   local $FS::UID::AutoCommit = 1;
428   log_info_and_warn(
429     sprintf
430       "WA tax table update completed. ".
431       "Inserted %s rows, updated %s rows, identical %s rows",
432       $insert_count,
433       $update_count,
434       $same_count
435   );
436
437 }
438
439 =head2 wa_sales_parse_xlsx_file \%args
440
441 Parse given XLSX file for tax district information
442 Return an arrayref of district information hashrefs
443
444 =cut
445
446 sub wa_sales_parse_xlsx_file {
447   my $args = shift;
448
449   croak 'wa_sales_parse_xlsx_file requires $args hashref containing a filename'
450     unless ref $args
451         && $args->{filename};
452
453   # About the file format:
454   #
455   # The current spreadsheet contains the following @columns.
456   # Rows 1 and 2 are a marquee header
457   # Row 3 is the column labels.  We will test these to detect
458   #   changes in the data format
459   # Rows 4+ are the tax district data
460   #
461   # The "city" column is being parsed from "Location"
462
463   my @columns = qw( city county district tax_local tax_state tax_combined );
464
465   log_error_and_die( "Unable to access XLSX file: $args->{filename}" )
466     unless -r $args->{filename};
467
468   my $xls_parser = Spreadsheet::XLSX->new( $args->{filename} )
469     or log_error_and_die( "Error parsing XLSX file: $!" );
470
471   my $sheet = $xls_parser->{Worksheet}->[0]
472     or log_error_and_die(" Unable to access worksheet 1 in XLSX file" );
473
474   my $cells = $sheet->{Cells}
475     or log_error_and_die( "Unable to read cells in XLSX file" );
476
477   # Read the column labels and verify
478   my %labels =
479     map{ $columns[$_] => $cells->[2][$_]->{Val} }
480     0 .. scalar(@columns)-1;
481
482   my %expected_labels = (
483     city         => 'Location',
484     county       => 'County',
485     district     => 'Location Code',
486     tax_local    => 'Local Rate',
487     tax_state    => 'State Rate',
488     tax_combined => 'Combined Sales Tax',
489   );
490
491   if (
492     my @error_labels =
493       grep { lc $labels{$_} ne lc $expected_labels{$_} }
494       @columns
495   ) {
496     my $error = "Error parsing XLS file - ".
497                 "Data format may have been updated with WA DOR! ";
498     $error .= "Expected column $expected_labels{$_}, found $labels{$_}! "
499       for @error_labels;
500     log_error_and_die( $error );
501   }
502
503   # Parse the rows into an array of hashes
504   my @districts;
505   for my $row ( 3..$sheet->{MaxRow} ) {
506     my %district = (
507       map { $columns[$_] => $cells->[$row][$_]->{Val} }
508       0 .. scalar(@columns)-1
509     );
510
511     if (
512          $district{city}
513       && $district{county}
514       && $district{district}     =~ /^\d+$/
515       && $district{tax_local}    =~ /^\d?\.\d+$/
516       && $district{tax_state}    =~ /^\d?\.\d+$/
517       && $district{tax_combined} =~ /^\d?\.\d+$/
518     ) {
519
520       # For some reason, city may contain line breaks!
521       $district{city} =~ s/[\r\n]//g;
522
523       push @districts, \%district;
524     } else {
525       log_warn_and_warn(
526         "Non-usable row found in spreadsheet:\n" . Dumper( \%district )
527       );
528     }
529
530   }
531
532   log_error_and_die( "No \@districts found in data file!" )
533     unless @districts;
534
535   log_info_and_warn(
536     sprintf "Parsed %s districts from data file", scalar @districts
537   );
538
539   \@districts;
540
541 }
542
543 =head2 wa_sales_fetch_xlsx_file \%args
544
545 Download data file from WA state DOR to temporary storage,
546 return filename
547
548 =cut
549
550 sub wa_sales_fetch_xlsx_file {
551   my $args = shift;
552
553   return
554     unless conf_tax_district_method()
555         && conf_tax_district_method() eq 'wa_sales';
556
557   croak 'wa_sales_fetch_xlsx_file requires \$args hashref'
558     unless ref $args
559         && $args->{temp_dir};
560
561   my $url_base = 'https://dor.wa.gov'.
562                  '/sites/default/files/legacy/Docs/forms/ExcsTx/LocSalUseTx';
563
564   my $year    = $args->{year}    || DateTime->now->year;
565   my $quarter = $args->{quarter} || DateTime->now->quarter;
566   $year = substr( $year, 2, 2 ) if $year >= 1000;
567
568   my $fn = sprintf( 'ExcelLocalSlsUserates_%s_Q%s.xlsx', $year, $quarter );
569   my $url = "$url_base/$fn";
570
571   my $write_fn = "$args->{temp_dir}/$fn";
572
573   log_info_and_warn( "Begin download from url: $url" );
574
575   my $ua = LWP::UserAgent->new;
576   my $res = $ua->get( $url );
577
578   log_error_and_die( "Download error: ".$res->status_line )
579     unless $res->is_success;
580
581   local $@;
582   eval { write_file( $write_fn, $res->decoded_content ); };
583   log_error_and_die( "Problem writing download to disk: $@" )
584     if $@;
585
586   log_info_and_warn( "Temporary file: $write_fn" );
587   $write_fn;
588
589 }
590
591 sub log {
592   state $log = FS::Log->new('tax_rate_update');
593   $log;
594 }
595
596 sub log_info_and_warn {
597   my $log_message = shift;
598   warn "$log_message\n";
599   &log()->info( $log_message );
600 }
601
602 sub log_warn_and_warn {
603   my $log_message = shift;
604   warn "$log_message\n";
605   &log()->warn( $log_message );
606 }
607
608 sub log_error_and_die {
609   my $log_message = shift;
610   &log()->error( $log_message );
611   die( "$log_message\n" );
612 }
613
614 sub log_error_and_warn {
615   my $log_message = shift;
616   warn "$log_message\n";
617   &log()->error( $log_message );
618 }
619
620 sub conf_tax_district_method {
621   state $tax_district_method = FS::Conf->new->config('tax_district_method');
622   $tax_district_method;
623 }
624
625
626 1;