1 package FS::part_export::nena2;
3 use base 'FS::part_export::batch_Common';
5 use FS::Record qw(qsearch qsearchs dbh);
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);
16 tie our %parsing_rules, 'Tie::IxHash', (
17 'no_street_suffix' => 'Avoid street suffix',
18 'no_postdir' => 'Avoid post directional',
19 # add others as we learn about them
22 tie %options, 'Tie::IxHash', (
23 'company_name' => { label => 'Company name for header record',
26 'company_id' => { label => 'NENA company ID',
29 'customer_code' => { label => 'Customer code',
32 'area_code' => { label => 'Default area code for 7 digit numbers',
35 'prefix' => { label => 'File name prefix',
38 'format' => { label => 'Format variant',
40 options => [ '', 'Intrado' ],
42 'target' => { label => 'Upload destination',
44 option_values => sub {
46 map { $_->targetnum, $_->label }
47 qsearch('upload_target');
48 sort keys (%upload_targets);
51 $upload_targets{$_[0]}
54 'cycle_counter' => { label => 'Cycle counter',
58 'debug' => { label => 'Enable debugging',
60 'parsing_rules' => { label => 'Address parsing rules',
63 map({ $_ => { label => $parsing_rules{$_}, type => 'checkbox' } }
71 'desc' => 'Export a NENA 2 E911 data file',
72 'options' => \%options,
76 <p>Export the physical location of a telephone service to a NENA 2.1 file
77 for use by an ALI database provider.</p>
80 <li><b>Company name</b> is the company name that should appear in your header
81 and trailer records.<li>
82 <li><b>Company ID</b> is your <a href="http://www.nena.org/?CompanyID">NENA
83 assigned company ID</a>.</li>
84 <li><b>File name prefix</b> is the prefix to use in your upload file names.
85 The rest of the file name will be the date (in mmddyy format) followed by
87 <li><b>Format variant</b> is the modification of the NENA format required
88 by your database provider. We support the Intrado variant used by
89 Qwest/CenturyLink. To produce a pure standard-compliant file, leave this
91 <li><b>Upload destination</b> is the <a href="../browse/upload_target.html">
92 upload target</a> to send the file to.</li>
93 <li><b>Cycle counter</b> is the sequence number of the next batch to be sent.
94 This will be automatically incremented with each batch.</li>
100 $initial_load_hack = 0; # set to 1 if running from a re-export script
102 # All field names and sizes are taken from the NENA-2-010 standard, May 1999
105 my $item_format = Parse::FixedLength->new([ qw(
108 calling_number:7:5:11
109 house_number:10:12:21
110 house_number_suffix:4:22:25
111 prefix_directional:2:26:27
113 street_suffix:4:88:91
114 post_directional:2:92:93
115 community_name:32:94:125
118 customer_name:32:188:219
119 class_of_service:1:220:220
120 type_of_service:1:221:221
124 main_number:7:234:240
125 order_number:10:241:250
126 extract_date:6:251:256
132 general_use:11:276:286
133 customer_code:3:287:289
135 x_coordinate:9:320:328
136 y_coordinate:9:329:337
137 z_coordinate:5:338:342
143 expanded_extract_date:8:387:394
144 nena_reserved:86:395:480
145 dbms_reserved:31:481:511
146 end_of_record:1:512:512
150 my $header_format = Parse::FixedLength->new([ qw(
151 header_indicator:5:1:5
153 company_name:50:12:61
154 cycle_counter:6R:62:67
158 release_number:3:94:96
159 format_version:1:97:97
160 expanded_extract_date:8:98:105
162 end_of_record:1:512:512
166 my $trailer_format = Parse::FixedLength->new([ qw(
167 trailer_indicator:5:1:5
169 company_name:50:12:61
170 record_count:9R:62:70
171 expanded_extract_date:8:71:78
173 end_of_record:1:512:512
177 my %function_code = (
186 # validate some things
187 my ($self, $action, $svc) = @_;
188 if ( $svc->phonenum =~ /\D/ ) {
189 return "Can't export E911 information for a non-numeric phone number";
190 } elsif ( $svc->phonenum =~ /^011/ ) {
191 return "Can't export E911 information for a non-North American phone number";
200 # pkg_change, suspend, unsuspend actions don't trigger anything here
201 return '' if !exists( $function_code{$action} );
202 if ( $action eq 'replace' ) {
204 # the one case where the old service is relevant: phone number change
205 # in that case, insert a batch item to delete the old number, then
206 # continue as if this were an insert.
207 if ($old->phonenum ne $svc->phonenum) {
208 return $self->create_item('delete', $old)
209 || $self->create_item('insert', $svc);
212 $self->SUPER::create_item($action, $svc, @_);
217 eval "use Geo::StreetAddress::US";
219 if ($@ =~ /^Can't locate/) {
220 return "Geo::StreetAddress::US must be installed to use the NENA2 export.";
225 # generate the entire record here. reconciliation of multiple updates to
226 # the same service can be done at process time.
232 my $locationnum = $svc->locationnum
233 || $svc->cust_svc->cust_pkg->locationnum;
234 my $cust_location = FS::cust_location->by_key($locationnum);
236 # initialize with empty strings
237 my %hash = map { $_ => '' } @{ $item_format->names };
239 $hash{function_code} = $function_code{$action};
241 # Add default area code if phonenum is 7 digits
242 my $phonenum = $svc->phonenum;
243 if ($self->option('area_code') =~ /^\d{3}$/ && $phonenum =~ /^\d{7}$/ ){
244 $phonenum = $self->option('area_code'). $svc->phonenum;
248 $phonenum =~ /^(\d{3})(\d*)$/;
250 $hash{calling_number} = $2;
254 my $full_address = $cust_location->address1;
255 my $address2 = $cust_location->address2;
256 if (length($address2)) {
257 # correct 'Sp', 'Sp.', 'sp ', etc. to the word SPACE for convenience
258 $address2 =~ s/^sp\b\.? ?/SPACE /i;
259 # and join it to $full_address with a space, not a comma
260 $full_address .= ' ' . $address2;
263 Geo::StreetAddress::US->avoid_redundant_street_type(1);
265 my $location_hash = Geo::StreetAddress::US->parse_address(
266 uc( join(', ', $full_address,
267 $cust_location->city,
268 $cust_location->state,
272 if ( length($address2) ) {
273 # be careful how we handle this
274 if ( !defined $location_hash ) {
275 # then it did successfully parse. BUT.
276 # if there's no sec_unit_type, then the address2 was parsed as part
277 # of the street name, which is wrong. Then reparse.
278 if ( !$location_hash->{sec_unit_type} ) {
279 undef $location_hash;
282 # then parsing failed. Try again without the address2.
283 $location_hash = Geo::StreetAddress::US->parse_address(
285 $cust_location->address1,
286 $cust_location->city,
287 $cust_location->state,
291 # this should not produce an address with sec_unit_type,
292 # so 'location' will be set to address2
294 if ( $location_hash ) {
296 $hash{house_number} = $location_hash->{number};
297 $hash{house_number_suffix} = ''; # we don't support this, do we?
298 $hash{prefix_directional} = $location_hash->{prefix};
299 $hash{street_name} = $location_hash->{street};
300 $hash{community_name} = $location_hash->{city};
301 $hash{state} = $location_hash->{state};
303 if ($location_hash->{sec_unit_type}) {
304 $hash{location} = $location_hash->{sec_unit_type} . ' ' .
305 $location_hash->{sec_unit_num};
307 # if sec_unit_type was not set, then put address2 in 'location'
308 $hash{location} = $address2;
311 if ( $self->option('no_street_suffix') and $location_hash->{type} ) {
312 my $type = $location_hash->{type};
313 $hash{street_name} .= ' ' . uc($location_hash->{type});
315 $hash{street_suffix} = uc($location_hash->{type});
318 if ( $self->option('no_postdir') and $location_hash->{suffix} ) {
319 $hash{street_name} .= ' ' . $location_hash->{suffix};
321 $hash{post_directional} = $location_hash->{suffix};
325 # then it still wouldn't parse; happens when the address has no house
326 # number (which is allowed in NENA 2 format). so just put all the
327 # information we have into the record. (Parse::FixedLength will trim
328 # it to fit if necessary.)
329 $hash{street_name} = uc($cust_location->address1);
330 $hash{location} = uc($address2);
331 $hash{community_name} = uc($cust_location->city);
332 $hash{state} = uc($cust_location->state);
335 # customer name and class
336 $hash{customer_name} = $svc->phone_name_or_cust;
337 $hash{class_of_service} = $svc->e911_class;
338 if (!$hash{class_of_service}) {
340 my $cust_main = $svc->cust_main;
341 if ($cust_main->company) {
342 $hash{class_of_service} = '2';
344 $hash{class_of_service} = '1';
347 $hash{type_of_service} = $svc->e911_type || '0';
349 $hash{exchange} = '';
350 # the routing number for the local emergency service call center;
351 # will be filled in by the service provider
354 # Main Number (I guess for callbacks?)
355 # XXX this is probably not right, but we don't have a concept of "main
356 # number for the site".
357 $hash{main_npa} = $hash{npa};
358 $hash{main_number} = $hash{calling_number};
360 # Order Number...is a foreign concept to us. It's supposed to be the
361 # transaction number that ordered this service change. (Maybe the
362 # number of the batch item? That's really hard for a user to do anything
364 $hash{order_number} = $svc->svcnum;
365 $hash{extract_date} = time2str('%m%d%y', time);
367 # $hash{county_id} is supposed to be the FIPS code for the county,
368 # but it's a four-digit field. INCITS 31 county codes are 5 digits,
369 # so we can't comply. NENA 3 fixed this...
371 $hash{company_id} = $self->option('company_id');
372 $hash{customer_code} = $self->option('customer_code') || '';
373 $hash{source_id} = $initial_load_hack ? 'C' : ' ';
375 @hash{'zip_code', 'zip_4'} = split('-', $cust_location->zip);
377 $hash{x_coordinate} = $cust_location->longitude;
378 $hash{y_coordinate} = $cust_location->latitude;
379 # $hash{z_coordinate} = $cust_location->altitude; # not implemented, sadly
381 $hash{expanded_extract_date} = time2str('%Y%m%d', time);
384 if ( $self->option('format') eq 'Intrado' ) {
385 my $century = substr($hash{expanded_extract_date}, 0, 2);
386 $hash{expanded_extract_date} = '';
387 $hash{nena_reserved} = ' '.$century;
388 $hash{x_coordinate} = '';
389 $hash{y_coordinate} = '';
391 $hash{end_of_record} = '*';
392 return $item_format->pack(\%hash);
398 local $DEBUG = $self->option('debug');
399 local $FS::UID::AutoCommit = 0;
402 my $cycle = $self->option('cycle_counter');
403 die "invalid cycle counter value '$cycle'" if $cycle =~ /\D/;
405 # mark the batch as closed
406 if ($batch->status eq 'open') {
407 $batch->set(status => 'closed');
408 $error = $batch->replace;
409 die "can't close batch: $error" if $error;
413 my @items = $batch->export_batch_item;
414 return unless @items;
416 my ($fh, $local_file) = tempfile();
417 warn "writing batch to $local_file\n" if $DEBUG;
419 # intrado documentation is inconsistent on this, but NENA 2.1 says to use
420 # leading spaces, not zeroes, for the cycle counter and record count
422 my %hash = ('header_indicator' => 'UHL',
423 'extract_date' => time2str('%m%d%y', $batch->_date),
424 'company_name' => $self->option('company_name'),
425 'cycle_counter' => $cycle,
426 # can add these fields if they're really necessary but it's
431 'release_number' => '',
432 'format_version' => '',
433 'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
435 'end_of_record' => '*'
438 my $header = $header_format->pack(\%hash);
439 warn "HEADER: $header\n" if $DEBUG;
440 print $fh $header,"\r\n";
442 my %phonenum_item; # phonenum => batch item
443 foreach my $item (@items) {
445 # ignore items that have no data to add to the batch
446 next if $item->action eq 'suspend' or $item->action eq 'unsuspend';
448 my $data = $item->data;
449 %hash = %{ $item_format->parse($data) };
450 my $phonenum = $hash{npa} . $hash{calling_number};
452 # reconcile multiple updates that affect a single phone number
453 # set 'data' to undef here to cancel the current update.
454 # we will ALWAYS remove the previous item, though.
455 my $prev_item = $phonenum_item{ $phonenum };
457 warn "$phonenum: reconciling ".
458 $prev_item->action.'#'.$prev_item->itemnum . ' with '.
459 $item->action.'#'.$item->itemnum . "\n"
462 $error = $prev_item->delete;
463 delete $phonenum_item{ $phonenum };
465 if ($prev_item->action eq 'delete') {
466 if ( $item->action eq 'delete' ) {
467 warn "$phonenum was deleted, then deleted again; ignoring first delete\n";
468 } elsif ( $item->action eq 'insert' ) {
469 # delete + insert = replace
470 $item->action('replace');
473 # it's a replace action, which isn't really valid after the phonenum
474 # was deleted, but assume the delete was an error
475 warn "$phonenum was deleted, then replaced; ignoring delete action\n";
477 } elsif ($prev_item->action eq 'insert') {
478 if ( $item->action eq 'delete' ) {
479 # then negate both actions (this isn't an anomaly, don't warn)
481 } elsif ( $item->action eq 'insert' ) {
482 # assume this insert is correct
483 warn "$phonenum was inserted, then inserted again; ignoring first insert\n";
485 # insert + change = insert (with updated data)
486 $item->action('insert');
489 } else { # prev_item->action is replace/relocate
490 if ( $item->action eq 'delete' ) {
491 # then the previous replace doesn't matter
492 } elsif ( $item->action eq 'insert' ) {
493 # it was changed and then inserted...not sure what to do.
494 # assume the actions were queued out of order? or there are multiple
495 # svcnums with this phone number? both are pretty nasty...
496 warn "$phonenum was replaced, then inserted; ignoring insert\n";
499 # replaced, then replaced again; perfectly normal, and the second
500 # replace will prevail
505 # now, if reconciliation has changed this action, replace it
506 if (!defined $data) {
507 $error ||= $item->delete;
508 } elsif ($data ne $item->data) {
509 $item->set('data' => $data);
510 $error ||= $item->replace;
514 die "error reconciling NENA2 batch actions for $phonenum: $error\n";
517 next if !defined $data;
518 # set this action as the "current" update to perform on $phonenum
519 $phonenum_item{$phonenum} = $item;
522 # now, go through %phonenum_item and emit exactly one batch line affecting
526 foreach my $phonenum (sort {$a cmp $b} keys(%phonenum_item)) {
527 my $item = $phonenum_item{$phonenum};
528 print $fh $item->data, "\r\n";
533 %hash = ( 'trailer_indicator' => 'UTL',
534 'extract_date' => time2str('%m%d%y', $batch->_date),
535 'company_name' => $self->option('company_name'),
536 'record_count' => $rows,
537 'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
539 'end_of_record' => '*',
541 my $trailer = $trailer_format->pack(\%hash);
542 print "TRAILER: $trailer\n\n" if $DEBUG;
543 print $fh $trailer, "\r\n";
547 return unless $self->option('target');
549 # appears to be correct for Intrado; maybe the config option should
550 # allow specifying the whole string, as the argument to time2str?
551 my $dest_file = $self->option('prefix') . time2str("%m%d%y", $batch->_date)
554 my $upload_target = FS::upload_target->by_key($self->option('target'))
555 or die "can't upload batch (target does not exist)\n";
556 warn "Uploading to ".$upload_target->label.".\n" if $DEBUG;
557 $error = $upload_target->put($local_file, $dest_file);
561 die "error uploading batch: $error" if $error;
563 warn "Success.\n" if $DEBUG;
565 # if it was successfully uploaded, check off the batch:
566 $batch->status('done');
567 $error = $batch->replace;
569 # and increment the cycle counter
571 my $opt = qsearchs('part_export_option', {
572 optionname => 'cycle_counter',
573 exportnum => $self->exportnum,
575 $opt->set(optionvalue => $cycle);
576 $error ||= $opt->replace;
579 die "error recording batch status: $error\n";