fix state selection w/voip innovations API, add better error logging, RT#15150
[freeside.git] / FS / FS / part_export / globalpops_voip.pm
1 package FS::part_export::globalpops_voip;
2
3 use vars qw(@ISA %info);
4 use Tie::IxHash;
5 use FS::Record qw(qsearch dbh);
6 use FS::part_export;
7 use FS::phone_avail;
8 use Data::Dumper;
9
10 @ISA = qw(FS::part_export);
11
12 tie my %options, 'Tie::IxHash',
13   'login'         => { label=>'VoIP Innovations API login' },
14   'password'      => { label=>'VoIP Innovations API password' },
15   'endpointgroup' => { label=>'VoIP Innovations endpoint group number' },
16   'dry_run'       => { label=>"Test mode - don't actually provision" },
17 ;
18
19 %info = (
20   'svc'     => 'svc_phone',
21   'desc'    => 'Provision phone numbers to VoIP Innovations (formerly GlobalPOPs VoIP)',
22   'options' => \%options,
23   'notes'   => <<'END'
24 Requires installation of
25 <a href="http://search.cpan.org/dist/Net-GlobalPOPs-MediaServicesAPI">Net::GlobalPOPs::MediaServicesAPI</a>
26 from CPAN.
27 END
28 );
29
30 sub rebless { shift; }
31
32 sub get_dids {
33   my $self = shift;
34   my %opt = ref($_[0]) ? %{$_[0]} : @_;
35
36   my %getdids = ();
37   #  'orderby' => 'npa', #but it doesn't seem to work :/
38
39   if ( $opt{'areacode'} && $opt{'exchange'} ) { #return numbers
40     %getdids = ( 'npa'   => $opt{'areacode'},
41                  'nxx'   => $opt{'exchange'},
42                );
43   } elsif ( $opt{'areacode'} ) { #return city (npa-nxx-XXXX)
44     %getdids = ( 'npa'   => $opt{'areacode'} );
45   } elsif ( $opt{'state'} ) {
46
47     my @avail = qsearch({
48       'table'    => 'phone_avail',
49       'hashref'  => { 'exportnum'   => $self->exportnum,
50                       'countrycode' => '1', #don't hardcode me when gp goes int'l
51                       'state'       => $opt{'state'},
52                     },
53       'order_by' => 'ORDER BY npa',
54     });
55
56     return [ map $_->npa, @avail ] if @avail; #return cached area codes instead
57
58     #otherwise, search for em
59     %getdids = ( 'state' => $opt{'state'} );
60
61   }
62
63   my $dids = $self->gp_command('getDIDs', %getdids);
64
65   if ( $dids->{'type'} eq 'Error' ) {
66     my $error =  "Error running VoIP Innovations getDIDs: ".
67         $dids->{'statuscode'}. ': '. $dids->{'status'}. "\n";
68     warn $error;
69     die $error;
70   }
71
72   my $search = $dids->{'search'};
73
74   if ( $search->{'statuscode'} == 302200 ) {
75     return [];
76   } elsif ( $search->{'statuscode'} != 100 ) {
77
78     my $error = "Error running VoIP Innovations getDIDs: ";
79     if ( $search->{'statuscode'} || $search->{'status'} ) {
80       $error .= $search->{'statuscode'}. ': '. $search->{'status'}. "\n";
81     } else {
82       $error .= Dumper($search);
83     }
84     warn $error;
85     die $error;
86   }
87
88   my @return = ();
89
90   #my $latas = $search->{state}{lata};
91   my %latas;
92   if ( grep $search->{state}{lata}{$_}, qw(name rate_center) ) {
93     %latas = map $search->{state}{lata}{$_},
94                  qw(name rate_center);
95   } else {
96     %latas = %{ $search->{state}{lata} };
97   } 
98
99   foreach my $lata ( keys %latas ) {
100
101     #warn "LATA $lata";
102     
103     #my $l = $latas{$lata};
104     #$l = $l->{rate_center} if exists $l->{rate_center};
105     
106     my $lata_dids = $self->gp_command('getDIDs', %getdids, 'lata'=>$lata);
107     my $lata_search = $lata_dids->{'search'};
108     unless ( $lata_search->{'statuscode'} == 100 ) {
109       die "Error running VoIP Innovations getDIDs: ". $lata_search->{'status'}; #die??
110     }
111    
112     my $l = $lata_search->{state}{lata}{'rate_center'};
113
114     #use Data::Dumper;
115     #warn Dumper($l);
116
117     my %rate_center;
118     if ( grep $l->{$_}, qw(name friendlyname) ) {
119       %rate_center = map $l->{$_},
120                          qw(name friendlyname);
121     } else {
122       %rate_center = %$l;
123     } 
124
125     foreach my $rate_center ( keys %rate_center ) {
126       
127       #warn "rate center $rate_center";
128
129       my $rc = $rate_center{$rate_center}; 
130       $rc = $rc->{friendlyname} if exists $rc->{friendlyname};
131
132       my @r = ();
133       if ( exists($rc->{npa}) ) {
134         @r = ($rc);
135       } else {
136         @r = map { { 'name'=>$_, %{ $rc->{$_} } }; } keys %$rc
137       }
138
139       foreach my $r (@r) {
140
141         my @npa = ();
142         if ( exists($r->{npa}{name}) ) {
143           @npa = ($r->{npa})
144         } else {
145           @npa = map { { 'name'=>$_, %{ $r->{npa}{$_} } } } keys %{ $r->{npa} };
146         }
147
148         foreach my $npa (@npa) {
149
150           if ( $opt{'areacode'} && $opt{'exchange'} ) { #return numbers
151
152             #warn Dumper($npa);
153
154             my $tn = $npa->{nxx}{tn} || $npa->{nxx}{$opt{'exchange'}}{tn};
155
156             my @tn = ref($tn) eq 'ARRAY' ? @$tn : ($tn);
157             #push @return, @tn;
158             push @return,
159               map {
160                     if ( /^\s*(\d{3})(\d{3})(\d{4})\s*$/ ) {
161                       "$1-$2-$3";
162                     } else {
163                       $_;
164                     }
165                   }
166                map { ref($_) eq 'HASH' ? $_->{'content'} : $_ } #tier always 2?
167                @tn;
168
169           } elsif ( $opt{'areacode'} ) { #return city (npa-nxx-XXXX)
170
171             if ( $npa->{nxx}{name} ) {
172               @nxx = ( $npa->{nxx}{name} );
173             } else {
174               @nxx = keys %{ $npa->{nxx} };
175             }
176
177             push @return, map { $r->{name}. ' ('. $npa->{name}. "-$_-XXXX)"; }
178                               @nxx;
179
180           } elsif ( $opt{'state'} ) { #and not other things, then return areacode
181             #my $ac = $npa->{name};
182             #use Data::Dumper;
183             #warn Dumper($r) unless length($ac) == 3;
184
185             push @return, $npa->{name}
186               unless grep { $_ eq $npa->{name} } @return;
187
188           } else {
189             warn "WARNING: returning nothing for get_dids without known options"; #?
190           }
191
192         } #foreach my $npa
193
194       } #foreach my $r
195
196     } #foreach my $rate_center
197
198   } #foreach my $lata
199
200   if ( $opt{'areacode'} && $opt{'exchange'} ) { #return numbers
201     @return = sort { $a cmp $b } @return; #string comparison actually dwiw
202   } elsif ( $opt{'areacode'} ) { #return city (npa-nxx-XXXX)
203     @return = sort { lc($a) cmp lc($b) } @return;
204   } elsif ( $opt{'state'} ) { #and not other things, then return areacode
205
206     #populate cache
207
208     local $SIG{HUP} = 'IGNORE';
209     local $SIG{INT} = 'IGNORE';
210     local $SIG{QUIT} = 'IGNORE';
211     local $SIG{TERM} = 'IGNORE';
212     local $SIG{TSTP} = 'IGNORE';
213     local $SIG{PIPE} = 'IGNORE';
214
215     my $oldAutoCommit = $FS::UID::AutoCommit;
216     local $FS::UID::AutoCommit = 0;
217     my $dbh = dbh;
218
219     my $errmsg = 'WARNING: error populating phone availability cache: ';
220     my $error = '';
221     foreach my $return (@return) {
222       my $phone_avail = new FS::phone_avail {
223         'exportnum'   => $self->exportnum,
224         'countrycode' => '1', #don't hardcode me when gp goes int'l
225         'state'       => $opt{'state'},
226         'npa'         => $return,
227       };
228       $error = $phone_avail->insert();
229       if ( $error ) {
230         warn $errmsg.$error;
231         last;
232       }
233     }
234
235     if ( $error ) {
236       $dbh->rollback if $oldAutoCommit;
237     } else {
238       $dbh->commit or warn $errmsg.$dbh->errstr if $oldAutoCommit;
239     }
240
241     #end populate cache
242
243     #@return = sort { (split(' ', $a))[0] <=> (split(' ', $b))[0] } @return;
244     @return = sort { $a <=> $b } @return;
245   } else {
246     warn "WARNING: returning nothing for get_dids without known options"; #?
247   }
248
249   \@return;
250
251 }
252
253 sub gp_command {
254   my( $self, $command, @args ) = @_;
255
256   eval "use Net::GlobalPOPs::MediaServicesAPI 0.03;";
257   if ( $@ ) {
258     warn $@;
259     die $@;
260   }
261
262   my $gp = Net::GlobalPOPs::MediaServicesAPI->new(
263     'login'    => $self->option('login'),
264     'password' => $self->option('password'),
265     #'debug'    => $debug,
266   );
267
268   $gp->$command(@args);
269 }
270
271
272 sub _export_insert {
273   my( $self, $svc_phone ) = (shift, shift);
274
275   return '' if $self->option('dry_run');
276
277   #we want to provision and catch errors now, not queue
278
279   my $r = $self->gp_command('reserveDID',
280     'did'           => $svc_phone->phonenum,
281     'minutes'       => 1,
282     'endpointgroup' => $self->option('endpointgroup'),
283   );
284
285   my $rdid = $r->{did};
286
287   if ( $rdid->{'statuscode'} != 100 ) {
288     return "Error running VoIP Innovations reserveDID: ".
289            $rdid->{'statuscode'}. ': '. $rdid->{'status'};
290   }
291
292   my $a = $self->gp_command('assignDID',
293     'did'           => $svc_phone->phonenum,
294     'endpointgroup' => $self->option('endpointgroup'),
295     #'rewrite'
296     #'cnam'
297   );
298
299   my $adid = $a->{did};
300
301   if ( $adid->{'statuscode'} != 100 ) {
302     return "Error running VoIP Innovations assignDID: ".
303            $adid->{'statuscode'}. ': '. $adid->{'status'};
304   }
305
306   '';
307 }
308
309 sub _export_replace {
310   my( $self, $new, $old ) = (shift, shift, shift);
311
312   #hmm, what's to change?
313   '';
314 }
315
316 sub _export_delete {
317   my( $self, $svc_phone ) = (shift, shift);
318
319   return '' if $self->option('dry_run');
320
321   #probably okay to queue the deletion...?
322   #but hell, let's do it inline anyway, who wants phone numbers hanging around
323
324   my $r = $self->gp_command('releaseDID',
325     'did'           => $svc_phone->phonenum,
326   );
327
328   my $rdid = $r->{did};
329
330   if ( $rdid->{'statuscode'} != 100 ) {
331     return "Error running VoIP Innovations releaseDID: ".
332            $rdid->{'statuscode'}. ': '. $rdid->{'status'};
333   }
334
335   '';
336 }
337
338 sub _export_suspend {
339   my( $self, $svc_phone ) = (shift, shift);
340   #nop for now
341   '';
342 }
343
344 sub _export_unsuspend {
345   my( $self, $svc_phone ) = (shift, shift);
346   #nop for now
347   '';
348 }
349
350 #hmm, might forgo queueing entirely for most things, data is too much of a pita
351 #sub globalpops_voip_queue {
352 #  my( $self, $svcnum, $method ) = (shift, shift, shift);
353 #  my $queue = new FS::queue {
354 #    'svcnum' => $svcnum,
355 #    'job'    => 'FS::part_export::globalpops_voip::globalpops_voip_command',
356 #  };
357 #  $queue->insert(
358 #    $self->option('login'),
359 #    $self->option('password'),
360 #    $method,
361 #    @_,
362 #  );
363 #}
364
365 sub globalpops_voip_command {
366   my($login, $password, $method, @args) = @_;
367
368   eval "use Net::GlobalPOPs::MediaServicesAPI 0.03;";
369   die $@ if $@;
370
371   my $gp = new Net::GlobalPOPs
372                  'login'    => $login,
373                  'password' => $password,
374                  #'debug'    => 1,
375                ;
376
377   my $return = $gp->$method( @args );
378
379   #$return->{'status'} 
380   #$return->{'statuscode'} 
381
382   die $return->{'status'} if $return->{'statuscode'};
383
384 }
385
386 1;
387