NENA2 export: supply a default value for class of service, #14049
[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
173   # validate some things
174   my ($self, $action, $svc) = @_;
175   if ( $svc->phonenum =~ /\D/ ) {
176     return "Can't export E911 information for a non-numeric phone number";
177   } elsif ( $svc->phonenum =~ /^011/ ) {
178     return "Can't export E911 information for a non-North American phone number";
179   }
180   '';
181 }
182
183 sub create_item {
184   my $self = shift;
185   my $action = shift;
186   my $svc = shift;
187   # pkg_change, suspend, unsuspend actions don't trigger anything here
188   return '' if !exists( $function_code{$action} ); 
189   if ( $action eq 'replace' ) {
190     my $old = shift;
191     # the one case where the old service is relevant: phone number change
192     # in that case, insert a batch item to delete the old number, then 
193     # continue as if this were an insert.
194     if ($old->phonenum ne $svc->phonenum) {
195       return $self->create_item('delete', $old)
196           || $self->create_item('insert', $svc);
197     }
198   }
199   $self->SUPER::create_item($action, $svc, @_);
200 }
201
202 sub data {
203   local $@;
204   eval "use Geo::StreetAddress::US";
205   if ($@) {
206     if ($@ =~ /^Can't locate/) {
207       return "Geo::StreetAddress::US must be installed to use the NENA2 export.";
208     } else {
209       die $@;
210     }
211   }
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
263   # customer name and class
264   $hash{customer_name} = $svc->phone_name_or_cust;
265   $hash{class_of_service} = $svc->e911_class;
266   if (!$hash{class_of_service}) {
267     # then guess
268     my $cust_main = $svc->cust_main;
269     if ($cust_main->company) {
270       $hash{class_of_service} = '2';
271     } else {
272       $hash{class_of_service} = '1';
273     }
274   }
275   $hash{type_of_service}  = $svc->e911_type || '0';
276
277   $hash{exchange} = '';
278   # the routing number for the local emergency service call center; 
279   # will be filled in by the service provider
280   $hash{esn} = '';
281
282   # Main Number (I guess for callbacks?)
283   # XXX this is probably not right, but we don't have a concept of "main 
284   # number for the site".
285   $hash{main_npa} = $hash{npa};
286   $hash{main_number} = $hash{calling_number};
287
288   # Order Number...is a foreign concept to us.  It's supposed to be the 
289   # transaction number that ordered this service change.  (Maybe the 
290   # number of the batch item?  That's really hard for a user to do anything
291   # with.)
292   $hash{order_number} = $svc->svcnum;
293   $hash{extract_date} = time2str('%m%d%y', time);
294
295   # $hash{county_id} is supposed to be the FIPS code for the county,
296   # but it's a four-digit field.  INCITS 31 county codes are 5 digits,
297   # so we can't comply.  NENA 3 fixed this...
298
299   $hash{company_id} = $self->option('company_id');
300   $hash{customer_code} = $self->option('customer_code') || '';
301   $hash{source_id} = $initial_load_hack ? 'C' : ' ';
302
303   @hash{'zip_code', 'zip_4'} = split('-', $cust_location->zip);
304  
305   $hash{x_coordinate} = $cust_location->longitude;
306   $hash{y_coordinate} = $cust_location->latitude;
307   # $hash{z_coordinate} = $cust_location->altitude; # not implemented, sadly
308
309   $hash{expanded_extract_date} = time2str('%Y%m%d', time);
310
311   # quirks mode
312   if ( $self->option('format') eq 'Intrado' ) { 
313     my $century = substr($hash{expanded_extract_date}, 0, 2);
314     $hash{expanded_extract_date} = '';
315     $hash{nena_reserved} = '   '.$century;
316     $hash{x_coordinate} = '';
317     $hash{y_coordinate} = '';
318   }
319   $hash{end_of_record} = '*';
320   return $item_format->pack(\%hash);
321 }
322
323 sub process {
324   my $self = shift;
325   my $batch = shift;
326   local $DEBUG = $self->option('debug');
327   local $FS::UID::AutoCommit = 0;
328   my $error;
329
330   my $cycle = $self->option('cycle_counter');
331   die "invalid cycle counter value '$cycle'" if $cycle =~ /\D/;
332
333   # mark the batch as closed
334   if ($batch->status eq 'open') {
335     $batch->set(status => 'closed');
336     $error = $batch->replace;
337     die "can't close batch: $error" if $error;
338     dbh->commit;
339   }
340
341   my @items = $batch->export_batch_item;
342   return unless @items;
343
344   my ($fh, $local_file) = tempfile();
345   warn "writing batch to $local_file\n" if $DEBUG;
346
347   # intrado documentation is inconsistent on this, but NENA 2.1 says to use
348   # leading spaces, not zeroes, for the cycle counter and record count
349
350   my %hash = ('header_indicator'      => 'UHL',
351               'extract_date'          => time2str('%m%d%y', $batch->_date),
352               'company_name'          => $self->option('company_name'),
353               'cycle_counter'         => $cycle,
354               # can add these fields if they're really necessary but it's
355               # a lot of work
356               'county_id'             => '',
357               'state'                 => '',
358               'general_use'           => '',
359               'release_number'        => '',
360               'format_version'        => '',
361               'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
362               'reserved'              => '',
363               'end_of_record'         => '*'
364              );
365
366   my $header = $header_format->pack(\%hash);
367   warn "HEADER: $header\n" if $DEBUG;
368   print $fh $header,"\r\n";
369
370   my %phonenum_item; # phonenum => batch item
371   foreach my $item (@items) {
372
373     # ignore items that have no data to add to the batch
374     next if $item->action eq 'suspend' or $item->action eq 'unsuspend';
375     
376     my $data = $item->data;
377     %hash = %{ $item_format->parse($data) };
378     my $phonenum = $hash{npa} . $hash{calling_number};
379
380     # reconcile multiple updates that affect a single phone number
381     # set 'data' to undef here to cancel the current update.
382     # we will ALWAYS remove the previous item, though.
383     my $prev_item = $phonenum_item{ $phonenum };
384     if ($prev_item) {
385       warn "$phonenum: reconciling ".
386             $prev_item->action.'#'.$prev_item->itemnum . ' with '.
387             $item->action.'#'.$item->itemnum . "\n"
388             if $DEBUG;
389
390       $error = $prev_item->delete;
391       delete $phonenum_item{ $phonenum };
392
393       if ($prev_item->action eq 'delete') {
394         if ( $item->action eq 'delete' ) {
395           warn "$phonenum was deleted, then deleted again; ignoring first delete\n";
396         } elsif ( $item->action eq 'insert' ) {
397           # delete + insert = replace
398           $item->action('replace');
399           $data =~ s/^I/C/;
400         } else {
401           # it's a replace action, which isn't really valid after the phonenum
402           # was deleted, but assume the delete was an error
403           warn "$phonenum was deleted, then replaced; ignoring delete action\n";
404         }
405       } elsif ($prev_item->action eq 'insert') {
406         if ( $item->action eq 'delete' ) {
407           # then negate both actions (this isn't an anomaly, don't warn)
408           undef $data;
409         } elsif ( $item->action eq 'insert' ) {
410           # assume this insert is correct
411           warn "$phonenum was inserted, then inserted again; ignoring first insert\n";
412         } else {
413           # insert + change = insert (with updated data)
414           $item->action('insert');
415           $data =~ s/^C/I/;
416         }
417       } else { # prev_item->action is replace/relocate
418         if ( $item->action eq 'delete' ) {
419           # then the previous replace doesn't matter
420         } elsif ( $item->action eq 'insert' ) {
421           # it was changed and then inserted...not sure what to do.
422           # assume the actions were queued out of order?  or there are multiple
423           # svcnums with this phone number? both are pretty nasty...
424           warn "$phonenum was replaced, then inserted; ignoring insert\n";
425           undef $data;
426         } else {
427           # replaced, then replaced again; perfectly normal, and the second
428           # replace will prevail
429         }
430       }
431     } # if $prev_item
432
433     # now, if reconciliation has changed this action, replace it
434     if (!defined $data) {
435       $error ||= $item->delete;
436     } elsif ($data ne $item->data) {
437       $item->set('data' => $data);
438       $error ||= $item->replace;
439     }
440     if ($error) {
441       dbh->rollback;
442       die "error reconciling NENA2 batch actions for $phonenum: $error\n";
443     }
444
445     next if !defined $data;
446     # set this action as the "current" update to perform on $phonenum
447     $phonenum_item{$phonenum} = $item;
448   }
449
450   # now, go through %phonenum_item and emit exactly one batch line affecting
451   # each phonenum
452
453   my $rows = 0;
454   foreach my $phonenum (sort {$a cmp $b} keys(%phonenum_item)) {
455     my $item = $phonenum_item{$phonenum};
456     print $fh $item->data, "\r\n";
457     $rows++;
458   }
459
460   # create trailer
461   %hash = ( 'trailer_indicator'     => 'UTL',
462             'extract_date'          => time2str('%m%d%y', $batch->_date),
463             'company_name'          => $self->option('company_name'),
464             'record_count'          => $rows,
465             'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
466             'reserved'              => '',
467             'end_of_record'         => '*',
468           );
469   my $trailer = $trailer_format->pack(\%hash);
470   print "TRAILER: $trailer\n\n" if $DEBUG;
471   print $fh $trailer, "\r\n";
472
473   close $fh;
474
475   return unless $self->option('target');
476
477   # appears to be correct for Intrado; maybe the config option should
478   # allow specifying the whole string, as the argument to time2str?
479   my $dest_file = $self->option('prefix') . time2str("%m%d%y", $batch->_date)
480                  . '.dat';
481
482   my $upload_target = FS::upload_target->by_key($self->option('target'))
483     or die "can't upload batch (target does not exist)\n";
484   warn "Uploading to ".$upload_target->label.".\n" if $DEBUG;
485   $error = $upload_target->put($local_file, $dest_file);
486
487   if ( $error ) {
488     dbh->rollback;
489     die "error uploading batch: $error" if $error;
490   }
491   warn "Success.\n" if $DEBUG;
492
493   # if it was successfully uploaded, check off the batch:
494   $batch->status('done');
495   $error = $batch->replace;
496
497   # and increment the cycle counter
498   $cycle++;
499   my $opt = qsearchs('part_export_option', {
500       optionname  => 'cycle_counter',
501       exportnum   => $self->exportnum,
502   });
503   $opt->set(optionvalue => $cycle);
504   $error ||= $opt->replace;
505   if ($error) {
506     dbh->rollback;
507     die "error recording batch status: $error\n";
508   }
509
510   dbh->commit;
511 }
512
513 1;