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