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