fix freeside-daily error checking LNP status, RT#75736, RT#73618
[freeside.git] / FS / FS / part_export / vitelity.pm
1 package FS::part_export::vitelity;
2 use base qw( FS::part_export );
3
4 use vars qw( %info );
5 use Tie::IxHash;
6 use Geo::StreetAddress::US;
7 use FS::Record qw( qsearch dbh );
8 use FS::phone_avail;
9 use FS::svc_phone;
10
11 tie my %options, 'Tie::IxHash',
12   'login'              => { label=>'Vitelity API login' },
13   'pass'               => { label=>'Vitelity API password' },
14   'routesip'           => { label=>'routesip (optional sub-account)' },
15   'type'               => { label=>'type (optional DID type to order)' },
16   'fax'                => { label=>'vfax service', type=>'checkbox' },
17   'restrict_selection' => { type    => 'select',
18                             label   => 'Restrict DID Selection', 
19                             options => [ '', 'tollfree', 'non-tollfree' ],
20                           },
21   'dry_run'            => { label => "Test mode - don't actually provision",
22                             type  => 'checkbox',
23                           },
24   'disable_e911'       => { label => "Disable E911 provisioning",
25                             type  => 'checkbox',
26                           },
27 ;
28
29 %info = (
30   'svc'        => 'svc_phone',
31   'desc'       => 'Provision phone numbers to Vitelity',
32   'options'    => \%options,
33   'no_machine' => 1,
34   'notes'      => <<'END'
35 Requires installation of
36 <a href="http://search.cpan.org/dist/Net-Vitelity">Net::Vitelity</a>
37 from CPAN.
38 <br><br>
39 routesip - optional Vitelity sub-account to which newly ordered DIDs will be routed
40 <br>type - optional DID type (perminute, unlimited, or your-pri)
41 END
42 );
43
44 sub rebless { shift; }
45
46 sub can_get_dids { 1; }
47 sub get_dids_can_tollfree { 1; };
48 sub can_lnp { 1; }
49
50 sub get_dids {
51   my $self = shift;
52   my %opt = ref($_[0]) ? %{$_[0]} : @_;
53
54   if ( $opt{'tollfree'} ) {
55     my $command = 'listtollfree';
56     $command = 'listdids' if $self->option('fax');
57     my @tollfree = $self->vitelity_command($command);
58     my @ret = ();
59
60     return [] if ( $tollfree[0] eq 'noneavailable' || $tollfree[0] eq 'none');
61
62     foreach my $did ( @tollfree ) {
63         $did =~ /^(\d{3})(\d{3})(\d{4})/ or die "unparsable did $did\n";
64         push @ret, $did;
65     }
66
67     my @sorted_ret = sort @ret;
68     return \@sorted_ret;
69
70   } elsif ( $opt{'ratecenter'} && $opt{'state'} ) { 
71
72     my %flushopts = ( 'state' => $opt{'state'}, 
73                     'ratecenter' => $opt{'ratecenter'},
74                     'exportnum' => $self->exportnum
75                   );
76     FS::phone_avail::flush( \%flushopts );
77       
78     local $SIG{HUP} = 'IGNORE';
79     local $SIG{INT} = 'IGNORE';
80     local $SIG{QUIT} = 'IGNORE';
81     local $SIG{TERM} = 'IGNORE';
82     local $SIG{TSTP} = 'IGNORE';
83     local $SIG{PIPE} = 'IGNORE';
84
85     my $oldAutoCommit = $FS::UID::AutoCommit;
86     local $FS::UID::AutoCommit = 0;
87     my $dbh = dbh;
88
89     my $errmsg = 'WARNING: error populating phone availability cache: ';
90
91     my $command = 'listlocal';
92     $command = 'listdids' if $self->option('fax');
93     my @dids = $self->vitelity_command( $command,
94                                         'state'      => $opt{'state'},
95                                         'ratecenter' => $opt{'ratecenter'},
96                                       );
97     # XXX: Options: type=unlimited OR type=pri
98
99     next if ( $dids[0] eq 'unavailable'  || $dids[0] eq 'noneavailable' );
100     die "missingdata error running Vitelity API" if $dids[0] eq 'missingdata';
101
102     foreach my $did ( @dids ) {
103       $did =~ /^(\d{3})(\d{3})(\d{4})/ or die "unparsable did $did\n";
104       my($npa, $nxx, $station) = ($1, $2, $3);
105
106       my $phone_avail = new FS::phone_avail {
107           'exportnum'   => $self->exportnum,
108           'countrycode' => '1', # vitelity is US/CA only now
109           'state'       => $opt{'state'},
110           'npa'         => $npa,
111           'nxx'         => $nxx,
112           'station'     => $station,
113           'name'        => $opt{'ratecenter'},
114       };
115
116       my $error = $phone_avail->insert();
117       if ( $error ) {
118           $dbh->rollback if $oldAutoCommit;
119           die $errmsg.$error;
120       }
121
122     }
123     $dbh->commit or warn $errmsg.$dbh->errstr if $oldAutoCommit;
124
125     return [
126       map { join('-', $_->npa, $_->nxx, $_->station ) }
127           qsearch({
128             'table'    => 'phone_avail',
129             'hashref'  => { 'exportnum'   => $self->exportnum,
130                             'countrycode' => '1', # vitelity is US/CA only now
131                             'name'         => $opt{'ratecenter'},
132                             'state'          => $opt{'state'},
133                           },
134             'order_by' => 'ORDER BY npa, nxx, station',
135           })
136     ];
137
138   } elsif ( $opt{'areacode'} ) { 
139
140     my @rc = map { $_->{'Hash'}->{name}.", ".$_->state } 
141           qsearch({
142             'select'   => 'DISTINCT name, state',
143             'table'    => 'phone_avail',
144             'hashref'  => { 'exportnum'   => $self->exportnum,
145                             'countrycode' => '1', # vitelity is US/CA only now
146                             'npa'         => $opt{'areacode'},
147                           },
148           });
149
150     my @sorted_rc = sort @rc;
151     return [ @sorted_rc ];
152
153   } elsif ( $opt{'state'} ) { #and not other things, then return areacode
154
155     my @avail = qsearch({
156       'select'   => 'DISTINCT npa',
157       'table'    => 'phone_avail',
158       'hashref'  => { 'exportnum'   => $self->exportnum,
159                       'countrycode' => '1', # vitelity is US/CA only now
160                       'state'       => $opt{'state'},
161                     },
162       'order_by' => 'ORDER BY npa',
163     });
164
165     return [ map $_->npa, @avail ] if @avail; #return cached area codes instead
166
167     #otherwise, search for em
168
169     my $command = 'listavailratecenters';
170     $command = 'listratecenters' if $self->option('fax');
171     my @ratecenters = $self->vitelity_command( $command,
172                                                  'state' => $opt{'state'}, 
173                                              );
174     # XXX: Options: type=unlimited OR type=pri
175
176     if ( $ratecenters[0] eq 'unavailable' || $ratecenters[0] eq 'none' ) {
177       return [];
178     } elsif ( $ratecenters[0] eq 'missingdata' ) {
179       die "missingdata error running Vitelity API"; #die?
180     }
181
182     local $SIG{HUP} = 'IGNORE';
183     local $SIG{INT} = 'IGNORE';
184     local $SIG{QUIT} = 'IGNORE';
185     local $SIG{TERM} = 'IGNORE';
186     local $SIG{TSTP} = 'IGNORE';
187     local $SIG{PIPE} = 'IGNORE';
188
189     my $oldAutoCommit = $FS::UID::AutoCommit;
190     local $FS::UID::AutoCommit = 0;
191     my $dbh = dbh;
192
193     my $errmsg = 'WARNING: error populating phone availability cache: ';
194
195     my %npa = ();
196     foreach my $ratecenter (@ratecenters) {
197
198      my $command = 'listlocal';
199       $command = 'listdids' if $self->option('fax');
200       my @dids = $self->vitelity_command( $command,
201                                             'state'      => $opt{'state'},
202                                             'ratecenter' => $ratecenter,
203                                         );
204     # XXX: Options: type=unlimited OR type=pri
205
206       if ( $dids[0] eq 'unavailable'  || $dids[0] eq 'noneavailable' ) {
207         next;
208       } elsif ( $dids[0] eq 'missingdata' ) {
209         die "missingdata error running Vitelity API"; #die?
210       }
211
212       foreach my $did ( @dids ) {
213         $did =~ /^(\d{3})(\d{3})(\d{4})/ or die "unparsable did $did\n";
214         my($npa, $nxx, $station) = ($1, $2, $3);
215         $npa{$npa}++;
216
217         my $phone_avail = new FS::phone_avail {
218           'exportnum'   => $self->exportnum,
219           'countrycode' => '1', # vitelity is US/CA only now
220           'state'       => $opt{'state'},
221           'npa'         => $npa,
222           'nxx'         => $nxx,
223           'station'     => $station,
224           'name'        => $ratecenter,
225         };
226
227         my $error = $phone_avail->insert();
228         if ( $error ) {
229           $dbh->rollback if $oldAutoCommit;
230           die $errmsg.$error;
231         }
232
233       }
234
235     }
236
237     $dbh->commit or warn $errmsg.$dbh->errstr if $oldAutoCommit;
238
239     my @return = sort { $a <=> $b } keys %npa;
240     return \@return;
241
242   } else {
243     die "get_dids called without state or areacode options";
244   }
245
246 }
247
248 sub vitelity_command {
249   my( $self, $command, @args ) = @_;
250
251   eval "use Net::Vitelity;";
252   die $@ if $@;
253
254   my $vitelity = Net::Vitelity->new(
255     'login' => $self->option('login'),
256     'pass'  => $self->option('pass'),
257     'apitype' => $self->option('fax') ? 'fax' : 'api',
258     #'debug'    => $debug,
259   );
260
261   $vitelity->$command(@args);
262 }
263
264 sub vitelity_lnp_command {
265   my( $self, $command, @args ) = @_;
266
267   eval "use Net::Vitelity 0.04;";
268   die $@ if $@;
269
270   my $vitelity = Net::Vitelity->new(
271     'login'   => $self->option('login'),
272     'pass'    => $self->option('pass'),
273     'apitype' => 'lnp',
274     #'debug'   => $debug,
275   );
276
277   $vitelity->$command(@args);
278 }
279
280 sub _export_insert {
281   my( $self, $svc_phone ) = (shift, shift);
282
283   return '' if $self->option('dry_run');
284
285   #we want to provision and catch errors now, not queue
286
287   #porting a number in?  different code path
288   if ( $svc_phone->lnp_status eq 'portingin' ) {
289
290     my %location = $svc_phone->location_hash;
291     my $sa = Geo::StreetAddress::US->parse_location( $location{'address1'} );
292
293     my $result = $self->vitelity_lnp_command('addport',
294       'portnumber'    => $svc_phone->phonenum,
295       'partial'       => 'no',
296       'wireless'      => 'no',
297       'carrier'       => $svc_phone->lnp_other_provider,
298       'company'       => $svc_phone->cust_svc->cust_pkg->cust_main->company,
299       'accnumber'     => $svc_phone->lnp_other_provider_account,
300       'name'          => $svc_phone->phone_name_or_cust,
301       'streetnumber'  => $sa->{number},
302       'streetprefix'  => $sa->{prefix},
303       'streetname'    => $sa->{street}. ' '. $street{type},
304       'streetsuffix'  => $sa->{suffix},
305       'unit'          => ( $sa->{sec_unit_num}
306                              ? $sa->{sec_unit_type}. ' '. $sa->{sec_unit_num}
307                              : ''
308                          ),
309       'city'          => $location{'city'},
310       'state'         => $location{'state'},
311       'zip'           => $location{'zip'},
312       'billnumber'    => $svc_phone->phonenum, #?? do we need a new field for this?
313       'contactnumber' => $svc_phone->cust_svc->cust_pkg->cust_main->daytime,
314     );
315
316     if ( $result =~ /^ok:/i ) {
317       my($ok, $portid, $sig, $bill) = split(':', $result);
318       $svc_phone->lnp_portid($portid);
319       $svc_phone->lnp_signature('Y') if $sig  =~ /y/i;
320       $svc_phone->lnp_bill('Y')      if $bill =~ /y/i;
321       return $svc_phone->replace;
322     } else {
323       return "Error initiating Vitelity port: $result";
324     }
325
326   }
327
328   ###
329   # 1. provision the DID
330   ###
331
332   my %vparams = ( 'did' => $svc_phone->phonenum );
333   $vparams{'routesip'} = $self->option('routesip') 
334     if defined $self->option('routesip');
335   $vparams{'type'} = $self->option('type') 
336     if defined $self->option('type');
337
338   my $command = 'getlocaldid';
339   my $success = 'success';
340
341   # this is OK as Vitelity for now is US/CA only; it's not a hack
342   $command = 'gettollfree' if $vparams{'did'} =~ /^800|^888|^877|^866|^855/;
343
344   if ($self->option('fax')) {
345     $command = 'getdid';
346     $success = 'ok';
347   }
348   
349   my $result = $self->vitelity_command($command,%vparams);
350
351   if ( $result ne $success ) {
352     return "Error running Vitelity $command: $result";
353   }
354
355   ###
356   # 2. Provision CNAM
357   ###
358
359   my $cnam_result = $self->vitelity_command('cnamenable',
360                                               'did'=>$svc_phone->phonenum,
361                                            );
362   if ( $result ne 'ok' ) {
363     #we already provisioned the DID, so...
364     warn "Vitelity error enabling CNAM for ". $svc_phone->phonenum. ": $result";
365   }
366
367   ###
368   # 3. Provision E911
369   ###
370
371   my $e911_error = $self->e911_send($svc_phone);
372
373   if ( $e911_error =~ /^(missingdata|invalid)/i ) {
374     #but we already provisioned the DID, so:
375     $self->vitelity_command('removedid', 'did'=> $svc_phone->phonenum,);
376     #and check the results?  if it failed, then what?
377
378     return $e911_error;
379   }
380
381   '';
382 }
383
384 sub e911send {
385   my($self, $svc_phone) = (shift, shift);
386
387   return '' if $self->option('disable_e911');
388
389   my %location = $svc_phone->location_hash;
390   my %e911send = (
391     'did'     => $svc_phone->phonenum,
392     'name'    => $svc_phone->phone_name_or_cust,
393     'address' => $location{'address1'},
394     'city'    => $location{'city'},
395     'state'   => $location{'state'},
396     'zip'     => $location{'zip'},
397   );
398   if ( $location{address2} =~ /^\s*(\w+)\W*(\d+)\s*$/ ) {
399     $e911send{'unittype'} = $1;
400     $e911send{'unitnumber'} = $2;
401   }
402
403   my $e911_result = $self->vitelity_command('e911send', %e911send);
404
405   return '' unless $result =~ /^(missingdata|invalid)/i;
406
407   return "Vitelity error provisioning E911 for". $svc_phone->phonenum.
408            ": $result";
409 }
410
411 sub _export_replace {
412   my( $self, $new, $old ) = (shift, shift, shift);
413
414   # Call Forwarding
415   if( $old->forwarddst ne $new->forwarddst ) {
416       my $result = $self->vitelity_command('callfw',
417         'did'           => $old->phonenum,
418         'forward'        => $new->forwarddst ? $new->forwarddst : 'none',
419       );
420       if ( $result ne 'ok' ) {
421         return "Error running Vitelity callfw: $result";
422       }
423   }
424
425   # vfax forwarding emails
426   if( $old->email ne $new->email && $self->option('fax') ) {
427       my $result = $self->vitelity_command('changeemail',
428         'did'           => $old->phonenum,
429         'emails'        => $new->email ? $new->email : '',
430       );
431       if ( $result ne 'ok' ) {
432         return "Error running Vitelity changeemail: $result";
433       }
434   }
435
436   $self->e911_send($new);
437 }
438
439 sub _export_delete {
440   my( $self, $svc_phone ) = (shift, shift);
441
442   return '' if $self->option('dry_run');
443
444   #probably okay to queue the deletion...?
445   #but hell, let's do it inline anyway, who wants phone numbers hanging around
446
447   return 'Deleting vfax DIDs is unsupported by Vitelity API' if $self->option('fax');
448
449   my $result = $self->vitelity_command('removedid',
450     'did'           => $svc_phone->phonenum,
451   );
452
453   if ( $result ne 'success' ) {
454     return "Error running Vitelity removedid: $result";
455   }
456
457   return '' if $self->option('disable_e911');
458
459   '';
460 }
461
462 sub _export_suspend {
463   my( $self, $svc_phone ) = (shift, shift);
464   #nop for now
465   '';
466 }
467
468 sub _export_unsuspend {
469   my( $self, $svc_phone ) = (shift, shift);
470   #nop for now
471   '';
472 }
473
474 sub check_lnp {
475   my $self = shift;
476
477   my $in_svcpart = 'IN ('. join( ',', map $_->svcpart, $self->export_svc). ')';
478
479   foreach my $svc_phone (
480     qsearch({ 'table'     => 'svc_phone',
481               'addl_from' => 'LEFT JOIN cust_svc USING (svcnum)',
482               'hashref'   => {lnp_status=>'portingin'},
483               'extra_sql' => "AND svcpart $in_svcpart",
484            })
485   ) {
486
487     my $result = $self->vitelity_lnp_command('checkstatus',
488                                                'portid'=>$svc_phone->lnp_portid,
489                                             );
490
491     if ( $result =~ /^Complete/i ) {
492
493       $svc_phone->lnp_status('portedin');
494       my $error = $self->_export_insert($svc_phone);
495       if ( $error ) {
496         #XXX log this using our internal log instead, so we can alert on it
497         # properly
498         warn "ERROR provisioning ported-in DID ". $svc_phone->phonenum. ": $error";
499       } else {
500         $error = $svc_phone->replace; #to set the lnp_status
501         #XXX log this using our internal log instead, so we can alert on it
502         warn "ERROR setting lnp_status for DID ". $svc_phone->phonenum. ": $error" if $error;
503       }
504
505     } elsif ( $result ne $svc_phone->lnp_reject_reason ) {
506       $svc_phone->lnp_reject_reason($result);
507       $error = $svc_phone->replace;
508       #XXX log this using our internal log instead, so we can alert on it
509       warn "ERROR setting lnp_reject_reason for DID ". $svc_phone->phonenum. ": $error" if $error;
510
511     }
512
513   }
514
515 }
516
517 1;
518