73f962c2c628aadedd7450a69932c0c539c59a07
[freeside.git] / FS / FS / part_export / ikano.pm
1 package FS::part_export::ikano;
2
3 use strict;
4 use warnings;
5 use vars qw(@ISA %info %loopType $me);
6 use Tie::IxHash;
7 use Date::Format qw( time2str );
8 use Date::Parse qw( str2time );
9 use FS::Record qw(qsearch qsearchs dbh);
10 use FS::part_export;
11 use FS::svc_dsl;
12 use Data::Dumper;
13
14 @ISA = qw(FS::part_export);
15 $me= '[' .  __PACKAGE__ . ']';
16
17 tie my %options, 'Tie::IxHash',
18   'keyid'         => { label=>'Ikano keyid' },
19   'username'      => { label=>'Ikano username',
20                         default => 'admin',
21                         },
22   'password'      => { label=>'Ikano password' },
23   'check_networks' => { label => 'Check Networks',
24                     default => 'ATT,BELLCA',
25                     },
26   'debug' => { label => 'Debug Mode',  type => 'checkbox' },
27 ;
28
29 %info = (
30   'svc'     => 'svc_dsl',
31   'desc'    => 'Provision DSL to Ikano',
32   'options' => \%options,
33   'notes'   => <<'END'
34 Requires installation of
35 <a href="http://search.cpan.org/dist/Net-Ikano">Net::Ikano</a> from CPAN.
36 END
37 );
38     
39 %loopType = ( '' => 'Line-share', '0' => 'Standalone' );
40
41 sub rebless { shift; }
42
43 sub dsl_pull {
44 # we distinguish between invalid new data (return error) versus data that
45 # has legitimately changed (may eventually execute hooks; now just update)
46 # if we do add hooks later, we should work on a copy of svc_dsl and pass
47 # the old and new svc_dsl to the hooks so they know what changed
48 #
49 # current assumptions of what won't change (from their side):
50 # vendor_order_id, vendor_qual_id, vendor_order_type, pushed, monitored,
51 # last_pull, address (from qual), contact info, ProductCustomId
52     my($self, $svc_dsl) = (shift, shift);
53     $self->loadmod;
54     my $result = $self->valid_order($svc_dsl,'pull');
55     return $result unless $result eq '';
56   
57     $result = $self->ikano_command('ORDERSTATUS', 
58         { OrderId => $svc_dsl->vendor_order_id } ); 
59     return $result unless ref($result); # scalar (string) is an error
60
61     # now we're getting an OrderResponse which should have one Order in it
62     warn "$me pull OrderResponse hash:\n".Dumper($result) 
63         if $self->option('debug');
64   
65     return 'Invalid order response' unless defined $result->{'Order'};
66     $result = $result->{'Order'};
67
68     return 'No order id or status returned' 
69         unless defined $result->{'Status'} && defined $result->{'OrderId'};
70         
71     local $SIG{HUP} = 'IGNORE';
72     local $SIG{INT} = 'IGNORE';
73     local $SIG{QUIT} = 'IGNORE';
74     local $SIG{TERM} = 'IGNORE';
75     local $SIG{TSTP} = 'IGNORE';
76     local $SIG{PIPE} = 'IGNORE';
77
78     my $oldAutoCommit = $FS::UID::AutoCommit;
79     local $FS::UID::AutoCommit = 0;
80     my $dbh = dbh;
81
82     # 1. status 
83     my $order_status = grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus)
84                             ? $result->{'Status'} : '';
85     return 'Invalid new status' if $order_status eq '';
86     $svc_dsl->vendor_order_status($order_status) 
87         if($svc_dsl->vendor_order_status ne $order_status);
88     $svc_dsl->monitored('') 
89             if ($order_status eq 'CANCELLED' || $order_status eq 'COMPLETED');
90
91     # 2. fields we don't care much about
92     my %justUpdate = ( 'first' => 'FirstName',
93                     'last' => 'LastName',
94                     'company' => 'CompanyName',
95                     'username' => 'Username',
96                     'password' => 'Password' );
97
98     my($fsf, $ikanof);
99     while (($fsf, $ikanof) = each %justUpdate) {
100        $svc_dsl->$fsf($result->{$ikanof}) 
101             if $result->{$ikanof} ne $svc_dsl->$fsf;
102     }
103
104     # let's look inside the <Product> response element
105     my @product = $result->{'Product'}; 
106     return 'Invalid number of products on order' if scalar(@product) != 1;
107     my $product = $result->{'Product'}[0];
108
109     # 3. phonenum 
110     if($svc_dsl->loop_type eq '') { # line-share
111 # TN may change only if sub changes it and New or Change order in Completed status
112         my $tn = $product->{'PhoneNumber'};
113         if($tn ne $svc_dsl->phonenum) {
114             if( ($svc_dsl->vendor_order_type eq 'NEW' 
115                 || $svc_dsl->vendor_order_type eq 'CHANGE')
116                && $svc_dsl->vendor_order_status eq 'COMPLETED' ) {
117                 $svc_dsl->phonenum($tn);
118             }
119             else { return 'TN has changed in an invalid state'; }
120         }
121     }
122     elsif($svc_dsl->loop_type eq '0') { # dry loop
123 # TN may change only if it's assigned while a New or Change order is in progress
124         return 'Invalid PhoneNumber value for a dry loop' 
125             if $product->{'PhoneNumber'} ne 'STANDALONE';
126         my $tn = $product->{'VirtualPhoneNumber'};
127         if($tn ne $svc_dsl->phonenum) {
128             if( ($svc_dsl->vendor_order_type eq 'NEW' 
129                 || $svc_dsl->vendor_order_type eq 'CHANGE')
130               && $svc_dsl->vendor_order_status ne 'COMPLETED'
131               && $svc_dsl->vendor_order_status ne 'CANCELLED') {
132                 $svc_dsl->phonenum($tn);
133             }
134             else { return 'TN has changed in an invalid state'; }
135         }
136     }
137     
138     # 4. desired_due_date - may change if manually changed
139     if($svc_dsl->vendor_order_type eq 'NEW' 
140             || $svc_dsl->vendor_order_type eq 'CHANGE'){
141         my $f = str2time($product->{'DateToOrder'});
142         return 'Invalid DateToOrder' unless $f;
143         $svc_dsl->desired_due_date($f) if $svc_dsl->desired_due_date ne $f;
144         # XXX: optionally sync back to start_date or whatever... 
145     }
146     elsif($svc_dsl->vendor_order_type eq 'CANCEL'){
147         my $f = str2time($product->{'DateToDisconnect'});
148         return 'Invalid DateToDisconnect' unless $f;
149         $svc_dsl->desired_due_date($f) if $svc_dsl->desired_due_date ne $f;
150         # XXX: optionally sync back to expire or whatever... 
151     }
152
153     # 5. due_date
154     if($svc_dsl->vendor_order_type eq 'NEW' 
155           || $svc_dsl->vendor_order_type eq 'CHANGE') {
156         my $f = str2time($product->{'ActivationDate'});
157         if($svc_dsl->vendor_order_status ne 'NEW'
158             && $svc_dsl->vendor_order_status ne 'CANCELLED') {
159             return 'Invalid ActivationDate' unless $f;
160             $svc_dsl->due_date($f) if $svc_dsl->due_date ne $f;
161         }
162     }
163     # Ikano API does not implement the proper disconnect date,
164     # so we can't do anything about it
165
166     # 6. staticips - for now just comma-separate them
167     my $tstatics = $result->{'StaticIps'};
168     my @istatics = defined $tstatics ? @$tstatics : ();
169     my $ostatics = $svc_dsl->staticips;
170     my @ostatics = split(',',$ostatics);
171     # more horrible search/sync code below...
172     my $staticsChanged = 0;
173     foreach my $istatic ( @istatics ) { # they have, we don't
174         unless ( grep($_ eq $istatic, @ostatics) ) {
175             push @ostatics, $istatic;
176             $staticsChanged = 1;
177         }
178     }
179     for(my $i=0; $i < scalar(@ostatics); $i++) {
180         unless ( grep($_ eq $ostatics[$i], @istatics) ) {
181             splice(@ostatics,$i,1);
182             $i--;
183             $staticsChanged = 1;
184         }
185     }
186     $svc_dsl->staticips(join(',',@ostatics)) if $staticsChanged;
187
188     # 7. notes - put them into the common format and compare
189     my $tnotes = $result->{'OrderNotes'}; 
190     my @tnotes = defined $tnotes ? @$tnotes : ();
191     my @inotes = (); # all Ikano OrderNotes as FS::dsl_note objects
192     my $notesChanged = 0; 
193     foreach my $tnote ( @tnotes ) {
194         my $inote = $self->ikano2fsnote($tnote,$svc_dsl->svcnum);
195         return 'Cannot parse note' unless ref($inote);
196         push @inotes, $inote;
197     }
198     my @onotes = $svc_dsl->notes;
199     # assume notes we already have don't change & no notes added from our side
200     # so using the horrible code below just find what we're missing and add it
201     my $error;
202     foreach my $inote ( @inotes ) {
203         my $found = 0;
204         foreach my $onote ( @onotes ) {
205             if($onote->date == $inote->date && $onote->note eq $inote->note) {
206                 $found = 1;
207                 last;
208             }
209         }
210         $error = $inote->insert unless ( $found );
211         if ( $error ) {
212           $dbh->rollback if $oldAutoCommit;
213           return "Cannot add note: $error";
214         }
215     }
216     
217     $svc_dsl->last_pull((time));
218     local $FS::svc_Common::noexport_hack = 1;
219     $error = $svc_dsl->replace; 
220     if ( $error ) {
221       $dbh->rollback if $oldAutoCommit;
222       return "Cannot update DSL data: $error";
223     }
224
225     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
226
227     '';
228 }
229
230 sub ikano2fsnote {
231     my($self,$n,$svcnum) = (shift,shift,shift);
232     my @ikanoRequired = qw( HighPriority StaffId Date Text CompanyStaffId );
233     return '' unless defined $n->{'HighPriority'}
234                 && defined $n->{'StaffId'}
235                 && defined $n->{'CompanyStaffId'}
236                 && defined $n->{'Date'}
237                 && defined $n->{'Text'}
238                 ;
239     my $by = 'Unknown';
240     $by = "Ikano" if $n->{'CompanyStaffId'} == -1 && $n->{'StaffId'} != -1;
241     $by = "Us" if $n->{'StaffId'} == -1 && $n->{'CompanyStaffId'} != -1;
242
243     new FS::dsl_note( {
244         'svcnum' => $svcnum,
245         'by' => $by,
246         'priority' => $n->{'HighPriority'} eq 'false' ? 'N' : 'H',
247         'date' => int(str2time($n->{'Date'})),
248         'note' => $n->{'Text'},
249      } );
250 }
251
252 sub qual {
253     '';
254 }
255
256 sub notes_html { 
257     my($self,$svc_dsl) = (shift,shift);
258     my $conf = new FS::Conf;
259     my $date_format = $conf->config('date_format') || '%m/%d/%Y';
260     my @notes = $svc_dsl->notes;
261     my $html = '<TABLE border="1" cellspacing="2" cellpadding="2" id="dsl_notes">
262         <TR><TH>Date</TH><TH>By</TH><TH>Priority</TH><TH>Note</TH></TR>';
263     foreach my $note ( @notes ) {
264         $html .= "<TR>
265             <TD>".time2str("$date_format %H:%M",$note->date)."</TD>
266             <TD>".$note->by."</TD>
267             <TD>". ($note->priority eq 'N' ? 'Normal' : 'High') ."</TD>
268             <TD>".$note->note."</TD></TR>";
269     }
270     $html .= '</TABLE>';
271     $html;
272 }
273
274 sub loop_type_long { # sub, not a method
275     my($svc_dsl) = (shift);
276     return $loopType{$svc_dsl->loop_type};
277 }
278
279 sub ikano_command {
280   my( $self, $command, $args ) = @_;
281
282   $self->loadmod;
283
284   my $ikano = Net::Ikano->new(
285     'keyid' => $self->option('keyid'),
286     'username'  => $self->option('username'),
287     'password'  => $self->option('password'),
288     'debug'    => $self->option('debug'),
289   );
290
291   $ikano->$command($args);
292 }
293
294 sub loadmod {
295   eval "use Net::Ikano;";
296   die $@ if $@;
297 }
298
299 sub valid_order {
300   my( $self, $svc_dsl, $action ) = (shift, shift, shift);
301  
302   $self->loadmod;
303   
304   warn "$me valid_order action=$action svc_dsl:\n". Dumper($svc_dsl)
305         if $self->option('debug');
306
307   # common to all order types/status/loop_type
308   my $error = !($svc_dsl->desired_due_date
309             &&  grep($_ eq $svc_dsl->vendor_order_type, Net::Ikano->orderTypes)
310             &&  $svc_dsl->first
311             &&  $svc_dsl->last
312             &&  defined $svc_dsl->loop_type
313             &&  $svc_dsl->vendor_qual_id
314             );
315   return 'Missing or invalid order data' if $error;
316   
317   return 'Package does not have an external id configured'
318     if $svc_dsl->cust_svc->cust_pkg->part_pkg->options('externalid',1) eq '';
319
320   return 'No valid qualification for this order' 
321     unless qsearch( 'qual', { 'vendor_qual_id' => $svc_dsl->vendor_qual_id });
322
323   # now go by order type
324   # weird ifs & long lines for readability and ease of understanding - don't change
325   if($svc_dsl->vendor_order_type eq 'NEW') {
326     if($svc_dsl->pushed) {
327         $error = !( ($action eq 'pull' || $action eq 'statuschg' 
328                         || $action eq 'delete')
329             &&  length($svc_dsl->vendor_order_id) > 0
330             &&  length($svc_dsl->vendor_order_status) > 0
331                 );
332         return 'Invalid order data' if $error;
333
334         return 'Phone number required for status change'
335             if ($action eq 'statuschg' && length($svc_dsl->phonenum) < 1);
336     }
337     else { # unpushed New order - cannot do anything other than push it
338         $error = !($action eq 'insert'
339             &&  length($svc_dsl->vendor_order_id) < 1
340             &&  length($svc_dsl->vendor_order_status) < 1
341             && ( ($svc_dsl->phonenum eq '' && $svc_dsl->loop_type eq '0') # dry
342               || ($svc_dsl->phonenum ne '' && $svc_dsl->loop_type eq '') # line-share
343                )
344             );  
345         return 'Invalid order data' if $error;
346     }
347   }
348   elsif($svc_dsl->vendor_order_type eq 'CANCEL') {
349   }
350   elsif($svc_dsl->vendor_order_type eq 'CHANGE') {
351   }
352
353  '';
354 }
355
356 sub qual2termsid {
357     my ($self,$vendor_qual_id,$ProductCustomId) = (shift,shift,shift);
358     my $qual = qsearchs( 'qual', { 'vendor_qual_id' => $vendor_qual_id });
359     return '' unless $qual;
360     my %qual_options = $qual->options;
361     my( $optionname, $optionvalue );
362     while (($optionname, $optionvalue) = each %qual_options) {
363         if ( $optionname =~ /^ikano_Network_(\d+)_ProductGroup_(\d+)_Product_(\d+)_ProductCustomId$/ 
364             && $optionvalue eq $ProductCustomId ) {
365             my $network = $1;
366             my $productgroup = $2;
367             return $qual->option("ikano_Network_".$network."_ProductGroup_".$productgroup."_TermsId");
368         }
369     }
370     '';
371 }
372
373 sub _export_insert {
374   my( $self, $svc_dsl ) = (shift, shift);
375
376   $self->loadmod;
377
378   my $result = $self->valid_order($svc_dsl,'insert');
379   return $result unless $result eq '';
380
381   my $isp_chg = $svc_dsl->isp_chg eq 'Y' ? 'YES' : 'NO';
382   my $contactTN = $svc_dsl->cust_svc->cust_pkg->cust_main->daytime;
383   $contactTN =~ s/[^0-9]//g;
384
385   my $ProductCustomId = $svc_dsl->cust_svc->cust_pkg->part_pkg->option('externalid',1);
386
387   my $args = {
388         orderType => 'NEW',
389         ProductCustomId => $ProductCustomId,
390         TermsId => $self->qual2termsid($svc_dsl->vendor_qual_id,$ProductCustomId),
391         DSLPhoneNumber => $svc_dsl->loop_type eq '0' ? 'STANDALONE'
392                                                     : $svc_dsl->phonenum,
393         Password => $svc_dsl->password,
394         PrequalId => $svc_dsl->vendor_qual_id,
395         CompanyName => $svc_dsl->company,
396         FirstName => $svc_dsl->first,
397         LastName => $svc_dsl->last,
398         MiddleName => '',
399         ContactMethod => 'PHONE',
400         ContactPhoneNumber => $contactTN,
401         ContactEmail => 'x@x.xx',
402         ContactFax => '',
403         DateToOrder => time2str("%Y-%m-%d",$svc_dsl->desired_due_date),
404         RequestClientIP => '127.0.0.1',
405         IspChange => $isp_chg,
406         IspPrevious => $isp_chg eq 'YES' ? $svc_dsl->isp_prev : '',
407         CurrentProvider => $isp_chg eq 'NO' ? $svc_dsl->isp_prev : '',
408   };
409
410   $result = $self->ikano_command('ORDER',$args); 
411   return $result unless ref($result); # scalar (string) is an error
412
413   # now we're getting an OrderResponse which should have one Order in it
414   warn "$me _export_insert OrderResponse hash:\n".Dumper($result)
415         if $self->option('debug');
416   
417   return 'Invalid order response' unless defined $result->{'Order'};
418   $result = $result->{'Order'};
419
420   return 'No/invalid order id or status returned' 
421     unless defined $result->{'Status'} && defined $result->{'OrderId'}
422         && grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus);
423
424   $svc_dsl->pushed(time);
425   $svc_dsl->last_pull((time)+1); 
426   $svc_dsl->vendor_order_id($result->{'OrderId'});
427   $svc_dsl->vendor_order_status($result->{'Status'});
428   $svc_dsl->username($result->{'Username'});
429   local $FS::svc_Common::noexport_hack = 1;
430   $result = $svc_dsl->replace; 
431   return "Error setting DSL fields: $result" if $result;
432   '';
433 }
434
435 sub _export_replace {
436   my( $self, $new, $old ) = (shift, shift, shift);
437 # XXX only supports password changes now, but should return error if 
438 # another change is attempted?
439
440   if($new->password ne $old->password) {
441       my $result = $self->valid_order($new,'statuschg');
442       return $result unless $result eq '';
443       
444       $result = $self->ikano_command('PASSWORDCHANGE',
445             { DSLPhoneNumber => $new->phonenum,
446               NewPassword => $new->password,
447             } ); 
448       return $result unless ref($result); # scalar (string) is an error
449
450       return 'Error changing password' unless defined $result->{'Password'}
451         && $result->{'Password'} eq $new->password;
452   }
453
454   '';
455 }
456
457 sub _export_delete {
458   my( $self, $svc_dsl ) = (shift, shift);
459   
460   my $result = $self->valid_order($svc_dsl,'delete');
461   return $result unless $result eq '';
462
463   # for now allow an immediate cancel only on New orders in New/Pending status
464   #XXX: add support for Chance and Cancel orders in New/Pending status later
465
466   if($svc_dsl->vendor_order_type eq 'NEW') {
467     if($svc_dsl->vendor_order_status eq 'NEW' 
468             || $svc_dsl->vendor_order_status eq 'PENDING') {
469         my $result = $self->ikano_command('CANCEL', 
470             { OrderId => $svc_dsl->vendor_order_id, } );
471         return $result unless ref($result); # scalar (string) is an error
472
473         return $self->dsl_pull($svc_dsl);
474     }
475     else {
476         return "Cannot cancel a NEW order unless it's in NEW or PENDING status";
477     }
478   }
479   else {
480     return 'Canceling orders other than NEW orders is not currently implemented';
481   }
482
483   '';
484 }
485
486 sub statuschg {
487   my( $self, $svc_dsl, $type ) = (shift, shift, shift);
488
489   my $result = $self->valid_order($svc_dsl,'statuschg');
490   return $result unless $result eq '';
491
492   # get the DSLServiceId
493   $result = $self->ikano_command('CUSTOMERLOOKUP',
494         { PhoneNumber => $svc_dsl->phonenum } ); 
495   return $result unless ref($result); # scalar (string) is an error
496   return 'No DSLServiceId found' unless defined $result->{'DSLServiceId'};
497   my $DSLServiceId = $result->{'DSLServiceId'};
498
499   $result = $self->ikano_command('ACCOUNTSTATUSCHANGE',
500         { DSLPhoneNumber => $svc_dsl->phonenum,
501           DSLServiceId => $DSLServiceId,
502           type => $type,
503         } ); 
504   return $result unless ref($result); # scalar (string) is an error
505   ''; 
506 }
507
508 sub _export_suspend {
509   my( $self, $svc_dsl ) = (shift, shift);
510   $self->statuschg($svc_dsl,"SUSPEND");
511 }
512
513 sub _export_unsuspend {
514   my( $self, $svc_dsl ) = (shift, shift);
515   $self->statuschg($svc_dsl,"UNSUSPEND");
516 }
517
518 1;