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