#14049 Fix error
[freeside.git] / FS / FS / part_export / nena2.pm
1 package FS::part_export::nena2;
2
3 use base 'FS::part_export::batch_Common';
4 use strict;
5 use FS::Record qw(qsearch qsearchs dbh);
6 use FS::svc_phone;
7 use FS::upload_target;
8 use Tie::IxHash;
9 use Date::Format qw(time2str);
10 use Parse::FixedLength;
11 use File::Temp qw(tempfile);
12 use vars qw(%info %options $initial_load_hack $DEBUG);
13
14 my %upload_targets;
15
16 tie %options, 'Tie::IxHash', (
17   'company_name'    => {  label => 'Company name for header record',
18                           type  => 'text',
19                        },
20   'company_id'      => {  label => 'NENA company ID',
21                           type  => 'text',
22                        },
23   'customer_code'   => {  label => 'Customer code',
24                           type  => 'text',
25                        },
26   'area_code'       => {  label => 'Default area code for 7 digit numbers',
27                           type  => 'text',
28                        },
29   'prefix'          => {  label => 'File name prefix',
30                           type  => 'text',
31                        },
32   'format'          => {  label => 'Format variant',
33                           type  => 'select',
34                           options => [ '', 'Intrado' ],
35                        },
36   'target'          => {  label => 'Upload destination',
37                           type => 'select',
38                           option_values => sub {
39                             %upload_targets = 
40                               map { $_->targetnum, $_->label } 
41                               qsearch('upload_target');
42                             sort keys (%upload_targets);
43                           },
44                           option_label => sub {
45                             $upload_targets{$_[0]}
46                           },
47                         },
48   'cycle_counter'   => { label => 'Cycle counter',
49                          type => 'text',
50                          default => '1'
51                        },
52   'debug'           => { label => 'Enable debugging',
53                          type => 'checkbox' },
54 );
55
56 %info = (
57   'svc'       => 'svc_phone',
58   'desc'      => 'Export a NENA 2 E911 data file',
59   'options'   => \%options,
60   'nodomain'  => 'Y',
61   'no_machine'=> 1,
62   'notes'     => qq!
63 <p>Export the physical location of a telephone service to a NENA 2.1 file
64 for use by an ALI database provider.</p>
65 <p>Options:
66 <ul>
67 <li><b>Company name</b> is the company name that should appear in your header
68 and trailer records.<li>
69 <li><b>Company ID</b> is your <a href="http://www.nena.org/?CompanyID">NENA 
70 assigned company ID</a>.</li>
71 <li><b>File name prefix</b> is the prefix to use in your upload file names.
72 The rest of the file name will be the date (in mmddyy format) followed by 
73 ".dat".</li>
74 <li><b>Format variant</b> is the modification of the NENA format required 
75 by your database provider.  We support the Intrado variant used by
76 Qwest/CenturyLink.  To produce a pure standard-compliant file, leave this
77 blank.</li>
78 <li><b>Upload destination</b> is the <a href="../browse/upload_target.html">
79 upload target</a> to send the file to.</li>
80 <li><b>Cycle counter</b> is the sequence number of the next batch to be sent.
81 This will be automatically incremented with each batch.</li>
82 </ul>
83 </p>
84   !,
85 );
86
87 $initial_load_hack = 0; # set to 1 if running from a re-export script
88
89 # All field names and sizes are taken from the NENA-2-010 standard, May 1999 
90 # version.
91
92 my $item_format = Parse::FixedLength->new([ qw(
93     function_code:1:1:1
94     npa:3:2:4
95     calling_number:7:5:11
96     house_number:10:12:21
97     house_number_suffix:4:22:25
98     prefix_directional:2:26:27
99     street_name:60:28:87
100     street_suffix:4:88:91
101     post_directional:2:92:93
102     community_name:32:94:125
103     state:2:126:127
104     location:60:128:187
105     customer_name:32:188:219
106     class_of_service:1:220:220
107     type_of_service:1:221:221
108     exchange:4:222:225
109     esn:5:226:230
110     main_npa:3:231:233
111     main_number:7:234:240
112     order_number:10:241:250
113     extract_date:6:251:256
114     county_id:4:257:260
115     company_id:5:261:265
116     source_id:1:266:266
117     zip_code:5:267:271
118     zip_4:4:272:275
119     general_use:11:276:286
120     customer_code:3:287:289
121     comments:30:290:319
122     x_coordinate:9:320:328
123     y_coordinate:9:329:337
124     z_coordinate:5:338:342
125     cell_id:6:343:348
126     sector_id:1:349:349
127     tar_code:6:350:355
128     reserved:21:356:376
129     alt:10:377:386
130     expanded_extract_date:8:387:394
131     nena_reserved:86:395:480
132     dbms_reserved:31:481:511
133     end_of_record:1:512:512
134   )]
135 );
136
137 my $header_format = Parse::FixedLength->new([ qw(
138     header_indicator:5:1:5
139     extract_date:6:6:11
140     company_name:50:12:61
141     cycle_counter:6R:62:67
142     county_id:4:68:71
143     state:2:72:73
144     general_use:20:74:93
145     release_number:3:94:96
146     format_version:1:97:97
147     expanded_extract_date:8:98:105
148     reserved:406:106:511
149     end_of_record:1:512:512
150   )]
151 );
152
153 my $trailer_format = Parse::FixedLength->new([ qw(
154     trailer_indicator:5:1:5
155     extract_date:6:6:11
156     company_name:50:12:61
157     record_count:9R:62:70
158     expanded_extract_date:8:71:78
159     reserved:433:79:511
160     end_of_record:1:512:512
161   )]
162 );
163
164 my %function_code = (
165   'insert'    => 'I',
166   'delete'    => 'D',
167   'replace'   => 'C',
168   'relocate'  => 'C',
169 );
170
171 sub immediate {
172   local $@;
173   eval "use Geo::StreetAddress::US";
174   if ($@) {
175     if ($@ =~ /^Can't locate/) {
176       return "Geo::StreetAddress::US must be installed to use the NENA2 export.";
177     } else {
178       die $@;
179     }
180   }
181
182   # validate some things
183   my ($self, $action, $svc) = @_;
184   if ( $svc->phonenum =~ /\D/ ) {
185     return "Can't export E911 information for a non-numeric phone number";
186   } elsif ( $svc->phonenum =~ /^011/ ) {
187     return "Can't export E911 information for a non-North American phone number";
188   }
189   '';
190 }
191
192 sub create_item {
193   my $self = shift;
194   my $action = shift;
195   my $svc = shift;
196   # pkg_change, suspend, unsuspend actions don't trigger anything here
197   return '' if !exists( $function_code{$action} ); 
198   if ( $action eq 'replace' ) {
199     my $old = shift;
200     # the one case where the old service is relevant: phone number change
201     # in that case, insert a batch item to delete the old number, then 
202     # continue as if this were an insert.
203     if ($old->phonenum ne $svc->phonenum) {
204       return $self->create_item('delete', $old)
205           || $self->create_item('insert', $svc);
206     }
207   }
208   $self->SUPER::create_item($action, $svc, @_);
209 }
210
211 sub data {
212   # generate the entire record here.  reconciliation of multiple updates to 
213   # the same service can be done at process time.
214   my $self = shift;
215   my $action = shift;
216
217   my $svc = shift;
218
219   my $locationnum =    $svc->locationnum
220                     || $svc->cust_svc->cust_pkg->locationnum;
221   my $cust_location = FS::cust_location->by_key($locationnum);
222
223   # initialize with empty strings
224   my %hash = map { $_ => '' } @{ $item_format->names };
225
226   $hash{function_code} = $function_code{$action};
227   
228   # Add default area code if phonenum is 7 digits
229   my $phonenum = $svc->phonenum;
230   if ($self->option('area_code') =~ /^\d{3}$/ && $phonenum =~ /^\d{7}$/ ){
231   $phonenum = $self->option('area_code'). $svc->phonenum;
232   }
233  
234   # phone number
235   $phonenum =~ /^(\d{3})(\d*)$/;
236   $hash{npa} = $1;
237   $hash{calling_number} = $2;
238
239   # street address
240   my $location_hash = Geo::StreetAddress::US->parse_address(
241     uc( join(', ', $cust_location->address1,
242                    $cust_location->address2,
243                    $cust_location->city,
244                    $cust_location->state,
245                    $cust_location->zip
246     ) )
247   );
248   $hash{house_number}         = $location_hash->{number};
249   $hash{house_number_suffix}  = ''; # we don't support this, do we?
250   $hash{prefix_directional}   = $location_hash->{prefix};
251   $hash{street_name}          = $location_hash->{street};
252   $hash{street_suffix}        = $location_hash->{type};
253   $hash{post_directional}     = $location_hash->{suffix};
254   $hash{community_name}       = $location_hash->{city};
255   $hash{state}                = $location_hash->{state};
256   if ($location_hash->{sec_unit_type}) {
257     $hash{location} = $location_hash->{sec_unit_type} . ' ' .
258                       $location_hash->{sec_unit_num};
259   } else {
260     $hash{location} = $cust_location->address2;
261   }
262   $hash{location}             = $location_hash->{address2};
263
264   # customer name and class
265   $hash{customer_name} = $svc->phone_name_or_cust;
266   $hash{class_of_service} = $svc->e911_class;
267   $hash{type_of_service}  = $svc->e911_type || '0';
268
269   $hash{exchange} = '';
270   # the routing number for the local emergency service call center; 
271   # will be filled in by the service provider
272   $hash{esn} = '';
273
274   # Main Number (I guess for callbacks?)
275   # XXX this is probably not right, but we don't have a concept of "main 
276   # number for the site".
277   $hash{main_npa} = $hash{npa};
278   $hash{main_number} = $hash{calling_number};
279
280   # Order Number...is a foreign concept to us.  It's supposed to be the 
281   # transaction number that ordered this service change.  (Maybe the 
282   # number of the batch item?  That's really hard for a user to do anything
283   # with.)
284   $hash{order_number} = $svc->svcnum;
285   $hash{extract_date} = time2str('%m%d%y', time);
286
287   # $hash{county_id} is supposed to be the FIPS code for the county,
288   # but it's a four-digit field.  INCITS 31 county codes are 5 digits,
289   # so we can't comply.  NENA 3 fixed this...
290
291   $hash{company_id} = $self->option('company_id');
292   $hash{customer_code} = $self->option('customer_code') || '';
293   $hash{source_id} = $initial_load_hack ? 'C' : ' ';
294
295   @hash{'zip_code', 'zip_4'} = split('-', $cust_location->zip);
296  
297   $hash{x_coordinate} = $cust_location->longitude;
298   $hash{y_coordinate} = $cust_location->latitude;
299   # $hash{z_coordinate} = $cust_location->altitude; # not implemented, sadly
300
301   $hash{expanded_extract_date} = time2str('%Y%m%d', time);
302
303   # quirks mode
304   if ( $self->option('format') eq 'Intrado' ) { 
305     my $century = substr($hash{expanded_extract_date}, 0, 2);
306     $hash{expanded_extract_date} = '';
307     $hash{nena_reserved} = '   '.$century;
308     $hash{x_coordinate} = '';
309     $hash{y_coordinate} = '';
310   }
311   $hash{end_of_record} = '*';
312   return $item_format->pack(\%hash);
313 }
314
315 sub process {
316   my $self = shift;
317   my $batch = shift;
318   local $DEBUG = $self->option('debug');
319   local $FS::UID::AutoCommit = 0;
320   my $error;
321
322   my $cycle = $self->option('cycle_counter');
323   die "invalid cycle counter value '$cycle'" if $cycle =~ /\D/;
324
325   # mark the batch as closed
326   if ($batch->status eq 'open') {
327     $batch->set(status => 'closed');
328     $error = $batch->replace;
329     die "can't close batch: $error" if $error;
330     dbh->commit;
331   }
332
333   my @items = $batch->export_batch_item;
334   return unless @items;
335
336   my ($fh, $local_file) = tempfile();
337   warn "writing batch to $local_file\n" if $DEBUG;
338
339   # intrado documentation is inconsistent on this, but NENA 2.1 says to use
340   # leading spaces, not zeroes, for the cycle counter and record count
341
342   my %hash = ('header_indicator'      => 'UHL',
343               'extract_date'          => time2str('%m%d%y', $batch->_date),
344               'company_name'          => $self->option('company_name'),
345               'cycle_counter'         => $cycle,
346               # can add these fields if they're really necessary but it's
347               # a lot of work
348               'county_id'             => '',
349               'state'                 => '',
350               'general_use'           => '',
351               'release_number'        => '',
352               'format_version'        => '',
353               'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
354               'reserved'              => '',
355               'end_of_record'         => '*'
356              );
357
358   my $header = $header_format->pack(\%hash);
359   warn "HEADER: $header\n" if $DEBUG;
360   print $fh $header,"\r\n";
361
362   my %phonenum_item; # phonenum => batch item
363   foreach my $item (@items) {
364
365     # ignore items that have no data to add to the batch
366     next if $item->action eq 'suspend' or $item->action eq 'unsuspend';
367     
368     my $data = $item->data;
369     %hash = %{ $item_format->parse($data) };
370     my $phonenum = $hash{npa} . $hash{calling_number};
371
372     # reconcile multiple updates that affect a single phone number
373     # set 'data' to undef here to cancel the current update.
374     # we will ALWAYS remove the previous item, though.
375     my $prev_item = $phonenum_item{ $phonenum };
376     if ($prev_item) {
377       warn "$phonenum: reconciling ".
378             $prev_item->action.'#'.$prev_item->itemnum . ' with '.
379             $item->action.'#'.$item->itemnum . "\n"
380             if $DEBUG;
381
382       $error = $prev_item->delete;
383       delete $phonenum_item{ $phonenum };
384
385       if ($prev_item->action eq 'delete') {
386         if ( $item->action eq 'delete' ) {
387           warn "$phonenum was deleted, then deleted again; ignoring first delete\n";
388         } elsif ( $item->action eq 'insert' ) {
389           # delete + insert = replace
390           $item->action('replace');
391           $data =~ s/^I/C/;
392         } else {
393           # it's a replace action, which isn't really valid after the phonenum
394           # was deleted, but assume the delete was an error
395           warn "$phonenum was deleted, then replaced; ignoring delete action\n";
396         }
397       } elsif ($prev_item->action eq 'insert') {
398         if ( $item->action eq 'delete' ) {
399           # then negate both actions (this isn't an anomaly, don't warn)
400           undef $data;
401         } elsif ( $item->action eq 'insert' ) {
402           # assume this insert is correct
403           warn "$phonenum was inserted, then inserted again; ignoring first insert\n";
404         } else {
405           # insert + change = insert (with updated data)
406           $item->action('insert');
407           $data =~ s/^C/I/;
408         }
409       } else { # prev_item->action is replace/relocate
410         if ( $item->action eq 'delete' ) {
411           # then the previous replace doesn't matter
412         } elsif ( $item->action eq 'insert' ) {
413           # it was changed and then inserted...not sure what to do.
414           # assume the actions were queued out of order?  or there are multiple
415           # svcnums with this phone number? both are pretty nasty...
416           warn "$phonenum was replaced, then inserted; ignoring insert\n";
417           undef $data;
418         } else {
419           # replaced, then replaced again; perfectly normal, and the second
420           # replace will prevail
421         }
422       }
423     } # if $prev_item
424
425     # now, if reconciliation has changed this action, replace it
426     if (!defined $data) {
427       $error ||= $item->delete;
428     } elsif ($data ne $item->data) {
429       $item->set('data' => $data);
430       $error ||= $item->replace;
431     }
432     if ($error) {
433       dbh->rollback;
434       die "error reconciling NENA2 batch actions for $phonenum: $error\n";
435     }
436
437     next if !defined $data;
438     # set this action as the "current" update to perform on $phonenum
439     $phonenum_item{$phonenum} = $item;
440   }
441
442   # now, go through %phonenum_item and emit exactly one batch line affecting
443   # each phonenum
444
445   my $rows = 0;
446   foreach my $phonenum (sort {$a cmp $b} keys(%phonenum_item)) {
447     my $item = $phonenum_item{$phonenum};
448     print $fh $item->data, "\r\n";
449     $rows++;
450   }
451
452   # create trailer
453   %hash = ( 'trailer_indicator'     => 'UTL',
454             'extract_date'          => time2str('%m%d%y', $batch->_date),
455             'company_name'          => $self->option('company_name'),
456             'record_count'          => $rows,
457             'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
458             'reserved'              => '',
459             'end_of_record'         => '*',
460           );
461   my $trailer = $trailer_format->pack(\%hash);
462   print "TRAILER: $trailer\n\n" if $DEBUG;
463   print $fh $trailer, "\r\n";
464
465   close $fh;
466
467   return unless $self->option('target');
468
469   # appears to be correct for Intrado; maybe the config option should
470   # allow specifying the whole string, as the argument to time2str?
471   my $dest_file = $self->option('prefix') . time2str("%m%d%y", $batch->_date)
472                  . '.dat';
473
474   my $upload_target = FS::upload_target->by_key($self->option('target'))
475     or die "can't upload batch (target does not exist)\n";
476   warn "Uploading to ".$upload_target->label.".\n" if $DEBUG;
477   $error = $upload_target->put($local_file, $dest_file);
478
479   if ( $error ) {
480     dbh->rollback;
481     die "error uploading batch: $error" if $error;
482   }
483   warn "Success.\n" if $DEBUG;
484
485   # if it was successfully uploaded, check off the batch:
486   $batch->status('done');
487   $error = $batch->replace;
488
489   # and increment the cycle counter
490   $cycle++;
491   my $opt = qsearchs('part_export_option', {
492       optionname  => 'cycle_counter',
493       exportnum   => $self->exportnum,
494   });
495   $opt->set(optionvalue => $cycle);
496   $error ||= $opt->replace;
497   if ($error) {
498     dbh->rollback;
499     die "error recording batch status: $error\n";
500   }
501
502   dbh->commit;
503 }
504
505 1;