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 %options, 'Tie::IxHash', (
17 'company_name' => { label => 'Company name for header record',
20 'company_id' => { label => 'NENA company ID',
23 'customer_code' => { label => 'Customer code',
26 'area_code' => { label => 'Default area code for 7 digit numbers',
29 'prefix' => { label => 'File name prefix',
32 'format' => { label => 'Format variant',
34 options => [ '', 'Intrado' ],
36 'target' => { label => 'Upload destination',
38 option_values => sub {
40 map { $_->targetnum, $_->label }
41 qsearch('upload_target');
42 sort keys (%upload_targets);
45 $upload_targets{$_[0]}
48 'cycle_counter' => { label => 'Cycle counter',
52 'debug' => { label => 'Enable debugging',
58 'desc' => 'Export a NENA 2 E911 data file',
59 'options' => \%options,
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>
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
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
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>
87 $initial_load_hack = 0; # set to 1 if running from a re-export script
89 # All field names and sizes are taken from the NENA-2-010 standard, May 1999
92 my $item_format = Parse::FixedLength->new([ qw(
97 house_number_suffix:4:22:25
98 prefix_directional:2:26:27
100 street_suffix:4:88:91
101 post_directional:2:92:93
102 community_name:32:94:125
105 customer_name:32:188:219
106 class_of_service:1:220:220
107 type_of_service:1:221:221
111 main_number:7:234:240
112 order_number:10:241:250
113 extract_date:6:251:256
119 general_use:11:276:286
120 customer_code:3:287:289
122 x_coordinate:9:320:328
123 y_coordinate:9:329:337
124 z_coordinate:5:338:342
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
137 my $header_format = Parse::FixedLength->new([ qw(
138 header_indicator:5:1:5
140 company_name:50:12:61
141 cycle_counter:6R:62:67
145 release_number:3:94:96
146 format_version:1:97:97
147 expanded_extract_date:8:98:105
149 end_of_record:1:512:512
153 my $trailer_format = Parse::FixedLength->new([ qw(
154 trailer_indicator:5:1:5
156 company_name:50:12:61
157 record_count:9R:62:70
158 expanded_extract_date:8:71:78
160 end_of_record:1:512:512
164 my %function_code = (
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";
187 # pkg_change, suspend, unsuspend actions don't trigger anything here
188 return '' if !exists( $function_code{$action} );
189 if ( $action eq 'replace' ) {
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);
199 $self->SUPER::create_item($action, $svc, @_);
204 eval "use Geo::StreetAddress::US";
206 if ($@ =~ /^Can't locate/) {
207 return "Geo::StreetAddress::US must be installed to use the NENA2 export.";
212 # generate the entire record here. reconciliation of multiple updates to
213 # the same service can be done at process time.
219 my $locationnum = $svc->locationnum
220 || $svc->cust_svc->cust_pkg->locationnum;
221 my $cust_location = FS::cust_location->by_key($locationnum);
223 # initialize with empty strings
224 my %hash = map { $_ => '' } @{ $item_format->names };
226 $hash{function_code} = $function_code{$action};
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;
235 $phonenum =~ /^(\d{3})(\d*)$/;
237 $hash{calling_number} = $2;
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,
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};
260 $hash{location} = $cust_location->address2;
263 # customer name and class
264 $hash{customer_name} = $svc->phone_name_or_cust;
265 $hash{class_of_service} = $svc->e911_class;
266 $hash{type_of_service} = $svc->e911_type || '0';
268 $hash{exchange} = '';
269 # the routing number for the local emergency service call center;
270 # will be filled in by the service provider
273 # Main Number (I guess for callbacks?)
274 # XXX this is probably not right, but we don't have a concept of "main
275 # number for the site".
276 $hash{main_npa} = $hash{npa};
277 $hash{main_number} = $hash{calling_number};
279 # Order Number...is a foreign concept to us. It's supposed to be the
280 # transaction number that ordered this service change. (Maybe the
281 # number of the batch item? That's really hard for a user to do anything
283 $hash{order_number} = $svc->svcnum;
284 $hash{extract_date} = time2str('%m%d%y', time);
286 # $hash{county_id} is supposed to be the FIPS code for the county,
287 # but it's a four-digit field. INCITS 31 county codes are 5 digits,
288 # so we can't comply. NENA 3 fixed this...
290 $hash{company_id} = $self->option('company_id');
291 $hash{customer_code} = $self->option('customer_code') || '';
292 $hash{source_id} = $initial_load_hack ? 'C' : ' ';
294 @hash{'zip_code', 'zip_4'} = split('-', $cust_location->zip);
296 $hash{x_coordinate} = $cust_location->longitude;
297 $hash{y_coordinate} = $cust_location->latitude;
298 # $hash{z_coordinate} = $cust_location->altitude; # not implemented, sadly
300 $hash{expanded_extract_date} = time2str('%Y%m%d', time);
303 if ( $self->option('format') eq 'Intrado' ) {
304 my $century = substr($hash{expanded_extract_date}, 0, 2);
305 $hash{expanded_extract_date} = '';
306 $hash{nena_reserved} = ' '.$century;
307 $hash{x_coordinate} = '';
308 $hash{y_coordinate} = '';
310 $hash{end_of_record} = '*';
311 return $item_format->pack(\%hash);
317 local $DEBUG = $self->option('debug');
318 local $FS::UID::AutoCommit = 0;
321 my $cycle = $self->option('cycle_counter');
322 die "invalid cycle counter value '$cycle'" if $cycle =~ /\D/;
324 # mark the batch as closed
325 if ($batch->status eq 'open') {
326 $batch->set(status => 'closed');
327 $error = $batch->replace;
328 die "can't close batch: $error" if $error;
332 my @items = $batch->export_batch_item;
333 return unless @items;
335 my ($fh, $local_file) = tempfile();
336 warn "writing batch to $local_file\n" if $DEBUG;
338 # intrado documentation is inconsistent on this, but NENA 2.1 says to use
339 # leading spaces, not zeroes, for the cycle counter and record count
341 my %hash = ('header_indicator' => 'UHL',
342 'extract_date' => time2str('%m%d%y', $batch->_date),
343 'company_name' => $self->option('company_name'),
344 'cycle_counter' => $cycle,
345 # can add these fields if they're really necessary but it's
350 'release_number' => '',
351 'format_version' => '',
352 'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
354 'end_of_record' => '*'
357 my $header = $header_format->pack(\%hash);
358 warn "HEADER: $header\n" if $DEBUG;
359 print $fh $header,"\r\n";
361 my %phonenum_item; # phonenum => batch item
362 foreach my $item (@items) {
364 # ignore items that have no data to add to the batch
365 next if $item->action eq 'suspend' or $item->action eq 'unsuspend';
367 my $data = $item->data;
368 %hash = %{ $item_format->parse($data) };
369 my $phonenum = $hash{npa} . $hash{calling_number};
371 # reconcile multiple updates that affect a single phone number
372 # set 'data' to undef here to cancel the current update.
373 # we will ALWAYS remove the previous item, though.
374 my $prev_item = $phonenum_item{ $phonenum };
376 warn "$phonenum: reconciling ".
377 $prev_item->action.'#'.$prev_item->itemnum . ' with '.
378 $item->action.'#'.$item->itemnum . "\n"
381 $error = $prev_item->delete;
382 delete $phonenum_item{ $phonenum };
384 if ($prev_item->action eq 'delete') {
385 if ( $item->action eq 'delete' ) {
386 warn "$phonenum was deleted, then deleted again; ignoring first delete\n";
387 } elsif ( $item->action eq 'insert' ) {
388 # delete + insert = replace
389 $item->action('replace');
392 # it's a replace action, which isn't really valid after the phonenum
393 # was deleted, but assume the delete was an error
394 warn "$phonenum was deleted, then replaced; ignoring delete action\n";
396 } elsif ($prev_item->action eq 'insert') {
397 if ( $item->action eq 'delete' ) {
398 # then negate both actions (this isn't an anomaly, don't warn)
400 } elsif ( $item->action eq 'insert' ) {
401 # assume this insert is correct
402 warn "$phonenum was inserted, then inserted again; ignoring first insert\n";
404 # insert + change = insert (with updated data)
405 $item->action('insert');
408 } else { # prev_item->action is replace/relocate
409 if ( $item->action eq 'delete' ) {
410 # then the previous replace doesn't matter
411 } elsif ( $item->action eq 'insert' ) {
412 # it was changed and then inserted...not sure what to do.
413 # assume the actions were queued out of order? or there are multiple
414 # svcnums with this phone number? both are pretty nasty...
415 warn "$phonenum was replaced, then inserted; ignoring insert\n";
418 # replaced, then replaced again; perfectly normal, and the second
419 # replace will prevail
424 # now, if reconciliation has changed this action, replace it
425 if (!defined $data) {
426 $error ||= $item->delete;
427 } elsif ($data ne $item->data) {
428 $item->set('data' => $data);
429 $error ||= $item->replace;
433 die "error reconciling NENA2 batch actions for $phonenum: $error\n";
436 next if !defined $data;
437 # set this action as the "current" update to perform on $phonenum
438 $phonenum_item{$phonenum} = $item;
441 # now, go through %phonenum_item and emit exactly one batch line affecting
445 foreach my $phonenum (sort {$a cmp $b} keys(%phonenum_item)) {
446 my $item = $phonenum_item{$phonenum};
447 print $fh $item->data, "\r\n";
452 %hash = ( 'trailer_indicator' => 'UTL',
453 'extract_date' => time2str('%m%d%y', $batch->_date),
454 'company_name' => $self->option('company_name'),
455 'record_count' => $rows,
456 'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
458 'end_of_record' => '*',
460 my $trailer = $trailer_format->pack(\%hash);
461 print "TRAILER: $trailer\n\n" if $DEBUG;
462 print $fh $trailer, "\r\n";
466 return unless $self->option('target');
468 # appears to be correct for Intrado; maybe the config option should
469 # allow specifying the whole string, as the argument to time2str?
470 my $dest_file = $self->option('prefix') . time2str("%m%d%y", $batch->_date)
473 my $upload_target = FS::upload_target->by_key($self->option('target'))
474 or die "can't upload batch (target does not exist)\n";
475 warn "Uploading to ".$upload_target->label.".\n" if $DEBUG;
476 $error = $upload_target->put($local_file, $dest_file);
480 die "error uploading batch: $error" if $error;
482 warn "Success.\n" if $DEBUG;
484 # if it was successfully uploaded, check off the batch:
485 $batch->status('done');
486 $error = $batch->replace;
488 # and increment the cycle counter
490 my $opt = qsearchs('part_export_option', {
491 optionname => 'cycle_counter',
492 exportnum => $self->exportnum,
494 $opt->set(optionvalue => $cycle);
495 $error ||= $opt->replace;
498 die "error recording batch status: $error\n";