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 'prefix' => { label => 'File name prefix',
26 'format' => { label => 'Format variant',
28 options => [ '', 'Intrado' ],
30 'target' => { label => 'Upload destination',
32 option_values => sub {
34 map { $_->targetnum, $_->label }
35 qsearch('upload_target');
36 sort keys (%upload_targets);
39 $upload_targets{$_[0]}
42 'cycle_counter' => { label => 'Cycle counter',
46 'debug' => { label => 'Enable debugging',
52 'desc' => 'Export a NENA 2 E911 data file',
53 'options' => \%options,
57 <p>Export the physical location of a telephone service to a NENA 2.1 file
58 for use by an ALI database provider.</p>
61 <li><b>Company name</b> is the company name that should appear in your header
62 and trailer records.<li>
63 <li><b>Company ID</b> is your <a href="http://www.nena.org/?CompanyID">NENA
64 assigned company ID</a>.</li>
65 <li><b>File name prefix</b> is the prefix to use in your upload file names.
66 The rest of the file name will be the date (in mmddyy format) followed by
68 <li><b>Format variant</b> is the modification of the NENA format required
69 by your database provider. We support the Intrado variant used by
70 Qwest/CenturyLink. To produce a pure standard-compliant file, leave this
72 <li><b>Upload destination</b> is the <a href="../browse/upload_target.html">
73 upload target</a> to send the file to.</li>
74 <li><b>Cycle counter</b> is the sequence number of the next batch to be sent.
75 This will be automatically incremented with each batch.</li>
81 $initial_load_hack = 0; # set to 1 if running from a re-export script
83 # All field names and sizes are taken from the NENA-2-010 standard, May 1999
86 my $item_format = Parse::FixedLength->new([ qw(
91 house_number_suffix:4:22:25
92 prefix_directional:2:26:27
95 post_directional:2:92:93
96 community_name:32:94:125
99 customer_name:32:188:219
100 class_of_service:1:220:220
101 type_of_service:1:221:221
105 main_number:7:234:240
106 order_number:10:241:250
107 extract_date:6:251:256
113 general_use:11:276:286
114 customer_code:3:287:289
116 x_coordinate:9:320:328
117 y_coordinate:9:329:337
118 z_coordinate:5:338:342
124 expanded_extract_date:8:387:394
125 nena_reserved:86:395:480
126 dbms_reserved:31:481:511
127 end_of_record:1:512:512
131 my $header_format = Parse::FixedLength->new([ qw(
132 header_indicator:5:1:5
134 company_name:50:12:61
135 cycle_counter:6R:62:67
139 release_number:3:94:96
140 format_version:1:97:97
141 expanded_extract_date:8:98:105
143 end_of_record:1:512:512
147 my $trailer_format = Parse::FixedLength->new([ qw(
148 trailer_indicator:5:1:5
150 company_name:50:12:61
151 record_count:9R:62:70
152 expanded_extract_date:8:71:78
154 end_of_record:1:512:512
158 my %function_code = (
167 eval "use Geo::StreetAddress::US";
169 if ($@ =~ /^Can't locate/) {
170 return "Geo::StreetAddress::US must be installed to use the NENA2 export.";
176 # validate some things
177 my ($self, $action, $svc) = @_;
178 if ( $svc->phonenum =~ /\D/ ) {
179 return "Can't export E911 information for a non-numeric phone number";
180 } elsif ( $svc->phonenum =~ /^011/ ) {
181 return "Can't export E911 information for a non-North American phone number";
190 # pkg_change, suspend, unsuspend actions don't trigger anything here
191 return '' if !exists( $function_code{$action} );
192 if ( $action eq 'replace' ) {
194 # the one case where the old service is relevant: phone number change
195 # in that case, insert a batch item to delete the old number, then
196 # continue as if this were an insert.
197 if ($old->phonenum ne $svc->phonenum) {
198 return $self->create_item('delete', $old)
199 || $self->create_item('insert', $svc);
202 $self->SUPER::create_item($action, $svc, @_);
206 # generate the entire record here. reconciliation of multiple updates to
207 # the same service can be done at process time.
213 my $locationnum = $svc->locationnum
214 || $svc->cust_svc->cust_pkg->locationnum;
215 my $cust_location = FS::cust_location->by_key($locationnum);
217 # initialize with empty strings
218 my %hash = map { $_ => '' } $item_format->names;
220 $hash{function_code} = $function_code{$action};
223 $svc->phonenum =~ /^(\d{3})(\d*)$/;
225 $hash{calling_number} = $2;
228 my $location_hash = Geo::StreetAddress::US->parse_address(
229 uc( join(', ', $cust_location->address1,
230 $cust_location->address2,
231 $cust_location->city,
232 $cust_location->state,
236 $hash{house_number} = $location_hash->{number};
237 $hash{house_number_suffix} = ''; # we don't support this, do we?
238 $hash{prefix_directional} = $location_hash->{prefix};
239 $hash{street_name} = $location_hash->{street};
240 $hash{street_suffix} = $location_hash->{type};
241 $hash{post_directional} = $location_hash->{suffix};
242 $hash{community_name} = $location_hash->{city};
243 $hash{state} = $location_hash->{state};
244 if ($location_hash->{sec_unit_type}) {
245 $hash{location} = $location_hash->{sec_unit_type} . ' ' .
246 $location_hash->{sec_unit_num};
248 $hash{location} = $cust_location->address2;
250 $hash{location} = $location_hash->{address2};
252 # customer name and class
253 $hash{customer_name} = $svc->phone_name_or_cust;
254 $hash{class_of_service} = $svc->e911_class;
255 $hash{type_of_service} = $svc->e911_type || '0';
257 $hash{exchange} = '';
258 # the routing number for the local emergency service call center;
259 # will be filled in by the service provider
262 # Main Number (I guess for callbacks?)
263 # XXX this is probably not right, but we don't have a concept of "main
264 # number for the site".
265 $hash{main_npa} = $hash{npa};
266 $hash{main_number} = $hash{calling_number};
268 # Order Number...is a foreign concept to us. It's supposed to be the
269 # transaction number that ordered this service change. (Maybe the
270 # number of the batch item? That's really hard for a user to do anything
272 $hash{order_number} = $svc->svcnum;
273 $hash{extract_date} = time2str('%m%d%y', time);
275 # $hash{county_id} is supposed to be the FIPS code for the county,
276 # but it's a four-digit field. INCITS 31 county codes are 5 digits,
277 # so we can't comply. NENA 3 fixed this...
279 $hash{company_id} = $self->option('company_id');
280 $hash{source_id} = $initial_load_hack ? 'C' : ' ';
282 @hash{'zip', 'zip_'} = split('-', $cust_location->zip);
284 # $hash{customer_code} is supposed to "uniquely identify a customer" but
285 # they give us 3 alphanumeric characters. Not sure how that works.
287 $hash{x_coordinate} = $cust_location->longitude;
288 $hash{y_coordinate} = $cust_location->latitude;
289 # $hash{z_coordinate} = $cust_location->altitude; # not implemented, sadly
291 $hash{expanded_extract_date} = time2str('%Y%m%d', time);
294 if ( $self->option('format') eq 'Intrado' ) {
295 my $century = substr($hash{expanded_extract_date}, 0, 2);
296 $hash{expanded_extract_date} = '';
297 $hash{nena_reserved} = ' '.$century;
298 $hash{x_coordinate} = '';
299 $hash{y_coordinate} = '';
301 $hash{end_of_record} = '*';
302 return $item_format->pack(\%hash);
308 local $DEBUG = $self->option('debug');
309 local $FS::UID::AutoCommit = 0;
312 my $cycle = $self->option('cycle_counter');
313 die "invalid cycle counter value '$cycle'" if $cycle =~ /\D/;
315 # mark the batch as closed
316 if ($batch->status eq 'open') {
317 $batch->set(status => 'closed');
318 $error = $batch->replace;
319 die "can't close batch: $error" if $error;
323 my @items = $batch->export_batch_item;
324 return unless @items;
326 my ($fh, $local_file) = tempfile();
327 warn "writing batch to $local_file\n" if $DEBUG;
329 # intrado documentation is inconsistent on this, but NENA 2.1 says to use
330 # leading spaces, not zeroes, for the cycle counter and record count
332 my %hash = ('header_indicator' => 'UHL',
333 'extract_date' => time2str('%m%d%y', $batch->_date),
334 'company_name' => $self->option('company_name'),
335 'cycle_counter' => $cycle,
336 # can add these fields if they're really necessary but it's
341 'release_number' => '',
342 'format_version' => '',
343 'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
345 'end_of_record' => '*'
348 my $header = $header_format->pack(\%hash);
349 warn "HEADER: $header\n" if $DEBUG;
350 print $fh $header,"\r\n";
352 my %phonenum_item; # phonenum => batch item
353 foreach my $item (@items) {
355 # ignore items that have no data to add to the batch
356 next if $item->action eq 'suspend' or $item->action eq 'unsuspend';
358 my $data = $item->data;
359 %hash = %{ $item_format->parse($data) };
360 my $phonenum = $hash{npa} . $hash{calling_number};
362 # reconcile multiple updates that affect a single phone number
363 # set 'data' to undef here to cancel the current update.
364 # we will ALWAYS remove the previous item, though.
365 my $prev_item = $phonenum_item{ $phonenum };
367 warn "$phonenum: reconciling ".
368 $prev_item->action.'#'.$prev_item->itemnum . ' with '.
369 $item->action.'#'.$item->itemnum . "\n"
372 $error = $prev_item->delete;
373 delete $phonenum_item{ $phonenum };
375 if ($prev_item->action eq 'delete') {
376 if ( $item->action eq 'delete' ) {
377 warn "$phonenum was deleted, then deleted again; ignoring first delete\n";
378 } elsif ( $item->action eq 'insert' ) {
379 # delete + insert = replace
380 $item->action('replace');
383 # it's a replace action, which isn't really valid after the phonenum
384 # was deleted, but assume the delete was an error
385 warn "$phonenum was deleted, then replaced; ignoring delete action\n";
387 } elsif ($prev_item->action eq 'insert') {
388 if ( $item->action eq 'delete' ) {
389 # then negate both actions (this isn't an anomaly, don't warn)
391 } elsif ( $item->action eq 'insert' ) {
392 # assume this insert is correct
393 warn "$phonenum was inserted, then inserted again; ignoring first insert\n";
395 # insert + change = insert (with updated data)
396 $item->action('insert');
399 } else { # prev_item->action is replace/relocate
400 if ( $item->action eq 'delete' ) {
401 # then the previous replace doesn't matter
402 } elsif ( $item->action eq 'insert' ) {
403 # it was changed and then inserted...not sure what to do.
404 # assume the actions were queued out of order? or there are multiple
405 # svcnums with this phone number? both are pretty nasty...
406 warn "$phonenum was replaced, then inserted; ignoring insert\n";
409 # replaced, then replaced again; perfectly normal, and the second
410 # replace will prevail
415 # now, if reconciliation has changed this action, replace it
416 if (!defined $data) {
417 $error ||= $item->delete;
418 } elsif ($data ne $item->data) {
419 $item->set('data' => $data);
420 $error ||= $item->replace;
424 die "error reconciling NENA2 batch actions for $phonenum: $error\n";
427 next if !defined $data;
428 # set this action as the "current" update to perform on $phonenum
429 $phonenum_item{$phonenum} = $item;
432 # now, go through %phonenum_item and emit exactly one batch line affecting
436 foreach my $phonenum (sort {$a cmp $b} keys(%phonenum_item)) {
437 my $item = $phonenum_item{$phonenum};
438 print $fh $item->data, "\r\n";
443 %hash = ( 'trailer_indicator' => 'UTL',
444 'extract_date' => time2str('%m%d%y', $batch->_date),
445 'company_name' => $self->option('company_name'),
446 'record_count' => $rows,
447 'expanded_extract_date' => time2str('%Y%m%d', $batch->_date),
449 'end_of_record' => '*',
451 my $trailer = $trailer_format->pack(\%hash);
452 print "TRAILER: $trailer\n\n" if $DEBUG;
453 print $fh $trailer, "\r\n";
457 return unless $self->option('target');
459 # appears to be correct for Intrado; maybe the config option should
460 # allow specifying the whole string, as the argument to time2str?
461 my $dest_file = $self->option('prefix') . time2str("%m%d%y", $batch->_date)
464 my $upload_target = FS::upload_target->by_key($self->option('target'))
465 or die "can't upload batch (target does not exist)\n";
466 warn "Uploading to ".$upload_target->label.".\n" if $DEBUG;
467 $error = $upload_target->put($local_file, $dest_file);
471 die "error uploading batch: $error" if $error;
473 warn "Success.\n" if $DEBUG;
475 # if it was successfully uploaded, check off the batch:
476 $batch->status('done');
477 $error = $batch->replace;
479 # and increment the cycle counter
481 my $opt = qsearchs('part_export_option', {
482 optionname => 'cycle_counter',
483 exportnum => $self->exportnum,
485 $opt->set(optionvalue => $cycle);
486 $error ||= $opt->replace;
489 die "error recording batch status: $error\n";