Ikano - when we become a CANCELORDER, we need to become monitored, RT7111
[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 external_pkg_map { 1; }
44
45 sub dsl_pull {
46 # we distinguish between invalid new data (return error) versus data that
47 # has legitimately changed (may eventually execute hooks; now just update)
48 # if we do add hooks later, we should work on a copy of svc_dsl and pass
49 # the old and new svc_dsl to the hooks so they know what changed
50 #
51 # current assumptions of what won't change (from their side):
52 # vendor_order_id, vendor_qual_id, vendor_order_type, pushed, monitored,
53 # last_pull, address (from qual), contact info, ProductCustomId
54     my($self, $svc_dsl, $threshold) = (shift, shift, shift);
55     my $result = $self->valid_order($svc_dsl,'pull');
56     return $result unless $result eq '';
57
58     my $now = time;
59     if($now - $svc_dsl->last_pull < $threshold) {
60         warn "$me skipping pull since threshold not reached (svcnum="
61             . $svc_dsl->svcnum . ",now=$now,threshold=$threshold,last_pull="
62             . $svc_dsl->last_pull .")" if $self->option('debug');
63         return '';
64     }
65   
66     $result = $self->ikano_command('ORDERSTATUS', 
67         { OrderId => $svc_dsl->vendor_order_id } ); 
68     return $result unless ref($result); # scalar (string) is an error
69
70     # now we're getting an OrderResponse which should have one Order in it
71     warn "$me pull OrderResponse hash:\n".Dumper($result) 
72         if $self->option('debug');
73   
74     return 'Invalid order response' unless defined $result->{'Order'};
75     $result = $result->{'Order'};
76
77     return 'No order id or status returned' 
78         unless defined $result->{'Status'} && defined $result->{'OrderId'};
79         
80     local $SIG{HUP} = 'IGNORE';
81     local $SIG{INT} = 'IGNORE';
82     local $SIG{QUIT} = 'IGNORE';
83     local $SIG{TERM} = 'IGNORE';
84     local $SIG{TSTP} = 'IGNORE';
85     local $SIG{PIPE} = 'IGNORE';
86
87     my $oldAutoCommit = $FS::UID::AutoCommit;
88     local $FS::UID::AutoCommit = 0;
89     my $dbh = dbh;
90
91     # 1. status 
92     my $order_status = grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus)
93                             ? $result->{'Status'} : '';
94     return 'Invalid new status' if $order_status eq '';
95     $svc_dsl->vendor_order_status($order_status) 
96         if($svc_dsl->vendor_order_status ne $order_status);
97     $svc_dsl->monitored('') 
98             if ($order_status eq 'CANCELLED' || $order_status eq 'COMPLETED');
99
100     # 2. fields we don't care much about
101     my %justUpdate = ( 'first' => 'FirstName',
102                     'last' => 'LastName',
103                     'company' => 'CompanyName',
104                     'username' => 'Username',
105                     'password' => 'Password' );
106
107     my($fsf, $ikanof);
108     while (($fsf, $ikanof) = each %justUpdate) {
109        $svc_dsl->$fsf($result->{$ikanof}) 
110             if $result->{$ikanof} ne $svc_dsl->$fsf;
111     }
112
113     # let's look inside the <Product> response element
114     my @product = $result->{'Product'}; 
115     return 'Invalid number of products on order' if scalar(@product) != 1;
116     my $product = $result->{'Product'}[0];
117
118     # 3. phonenum 
119     if($svc_dsl->loop_type eq '') { # line-share
120 # TN may change only if sub changes it and New or Change order in Completed status
121         my $tn = $product->{'PhoneNumber'};
122         if($tn ne $svc_dsl->phonenum) {
123             if( ($svc_dsl->vendor_order_type eq 'NEW' 
124                 || $svc_dsl->vendor_order_type eq 'CHANGE')
125                && $svc_dsl->vendor_order_status eq 'COMPLETED' ) {
126                 $svc_dsl->phonenum($tn);
127             }
128             else { return 'TN has changed in an invalid state'; }
129         }
130     }
131     elsif($svc_dsl->loop_type eq '0') { # dry loop
132 # TN may change only if it's assigned while a New or Change order is in progress
133         return 'Invalid PhoneNumber value for a dry loop' 
134             if $product->{'PhoneNumber'} ne 'STANDALONE';
135         my $tn = $product->{'VirtualPhoneNumber'};
136         if($tn ne $svc_dsl->phonenum) {
137             if( ($svc_dsl->vendor_order_type eq 'NEW' 
138                 || $svc_dsl->vendor_order_type eq 'CHANGE')
139               && $svc_dsl->vendor_order_status ne 'COMPLETED'
140               && $svc_dsl->vendor_order_status ne 'CANCELLED') {
141                 $svc_dsl->phonenum($tn);
142             }
143             else { return 'TN has changed in an invalid state'; }
144         }
145     }
146     
147     # 4. desired_due_date - may change if manually changed
148     if($svc_dsl->vendor_order_type eq 'NEW' 
149             || $svc_dsl->vendor_order_type eq 'CHANGE'){
150         my $f = str2time($product->{'DateToOrder'});
151         return 'Invalid DateToOrder' unless $f;
152         $svc_dsl->desired_due_date($f) if $svc_dsl->desired_due_date ne $f;
153         # XXX: optionally sync back to start_date or whatever... 
154     }
155     elsif($svc_dsl->vendor_order_type eq 'CANCEL'){
156         my $f = str2time($product->{'DateToDisconnect'});
157         return 'Invalid DateToDisconnect' unless $f;
158         $svc_dsl->desired_due_date($f) if $svc_dsl->desired_due_date ne $f;
159         # XXX: optionally sync back to expire or whatever... 
160     }
161
162     # 5. due_date
163     if($svc_dsl->vendor_order_type eq 'NEW' 
164           || $svc_dsl->vendor_order_type eq 'CHANGE') {
165         my $f = str2time($product->{'ActivationDate'});
166         if($svc_dsl->vendor_order_status ne 'NEW'
167             && $svc_dsl->vendor_order_status ne 'CANCELLED') {
168             return 'Invalid ActivationDate' unless $f;
169             $svc_dsl->due_date($f) if $svc_dsl->due_date ne $f;
170         }
171     }
172     # Ikano API does not implement the proper disconnect date,
173     # so we can't do anything about it
174
175     # 6. staticips - for now just comma-separate them
176     my $tstatics = $result->{'StaticIps'};
177     my @istatics = defined $tstatics ? @$tstatics : ();
178     my $ostatics = $svc_dsl->staticips;
179     my @ostatics = split(',',$ostatics);
180     # more horrible search/sync code below...
181     my $staticsChanged = 0;
182     foreach my $istatic ( @istatics ) { # they have, we don't
183         unless ( grep($_ eq $istatic, @ostatics) ) {
184             push @ostatics, $istatic;
185             $staticsChanged = 1;
186         }
187     }
188     for(my $i=0; $i < scalar(@ostatics); $i++) {
189         unless ( grep($_ eq $ostatics[$i], @istatics) ) {
190             splice(@ostatics,$i,1);
191             $i--;
192             $staticsChanged = 1;
193         }
194     }
195     $svc_dsl->staticips(join(',',@ostatics)) if $staticsChanged;
196
197     # 7. notes - put them into the common format and compare
198     my $tnotes = $result->{'OrderNotes'}; 
199     my @tnotes = defined $tnotes ? @$tnotes : ();
200     my @inotes = (); # all Ikano OrderNotes as FS::dsl_note objects
201     my $notesChanged = 0; 
202     foreach my $tnote ( @tnotes ) {
203         my $inote = $self->ikano2fsnote($tnote,$svc_dsl->svcnum);
204         return 'Cannot parse note' unless ref($inote);
205         push @inotes, $inote;
206     }
207     my @onotes = $svc_dsl->notes;
208     # assume notes we already have don't change & no notes added from our side
209     # so using the horrible code below just find what we're missing and add it
210     my $error;
211     foreach my $inote ( @inotes ) {
212         my $found = 0;
213         foreach my $onote ( @onotes ) {
214             if($onote->date == $inote->date && $onote->note eq $inote->note) {
215                 $found = 1;
216                 last;
217             }
218         }
219         $error = $inote->insert unless ( $found );
220         if ( $error ) {
221           $dbh->rollback if $oldAutoCommit;
222           return "Cannot add note: $error";
223         }
224     }
225     
226     $svc_dsl->last_pull((time));
227     local $FS::svc_Common::noexport_hack = 1;
228     $error = $svc_dsl->replace; 
229     if ( $error ) {
230       $dbh->rollback if $oldAutoCommit;
231       return "Cannot update DSL data: $error";
232     }
233
234     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
235
236     '';
237 }
238
239 sub ikano2fsnote {
240     my($self,$n,$svcnum) = (shift,shift,shift);
241     my @ikanoRequired = qw( HighPriority StaffId Date Text CompanyStaffId );
242     return '' unless defined $n->{'HighPriority'}
243                 && defined $n->{'StaffId'}
244                 && defined $n->{'CompanyStaffId'}
245                 && defined $n->{'Date'}
246                 && defined $n->{'Text'}
247                 ;
248     my $by = 'Unknown';
249     $by = "Ikano" if $n->{'CompanyStaffId'} == -1 && $n->{'StaffId'} != -1;
250     $by = "Us" if $n->{'StaffId'} == -1 && $n->{'CompanyStaffId'} != -1;
251
252     new FS::dsl_note( {
253         'svcnum' => $svcnum,
254         'author' => $by,
255         'priority' => $n->{'HighPriority'} eq 'false' ? 'N' : 'H',
256         '_date' => int(str2time($n->{'Date'})),
257         'note' => $n->{'Text'},
258      } );
259 }
260
261 sub qual {
262     my($self,$qual) = (shift,shift);
263 # address always required for Ikano qual, TN optional (assume dry if not given)
264
265     my %location_hash = $qual->location; 
266     return 'No address provided' unless %location_hash;
267     my $svctn = $qual->phonenum;
268
269     my $result = $self->ikano_command('PREQUAL',
270       { AddressLine1 => $location_hash{address1},
271         AddressUnitType => $location_hash{location_type},
272         AddressUnitValue => $location_hash{location_number},
273         AddressCity => $location_hash{city},
274         AddressState => $location_hash{state},
275         ZipCode => $location_hash{zip},
276         Country => $location_hash{country},
277         LocationType => $location_hash{location_kind},
278         PhoneNumber => length($svctn) > 1 ? $svctn : "STANDALONE",
279         RequestClientIP => '127.0.0.1',
280         CheckNetworks => $self->option('check_networks'),
281       } ); 
282     return $result unless ref($result); # error case
283     return 'Invalid prequal response' unless defined $result->{'PrequalId'};
284
285     my $qoptions = {};
286     # lame data structure traversal...
287     # don't spend much time here, just get TermsId and ProductCustomId
288     my $networks = $result->{'Network'};
289     my @networks = defined $networks ? @$networks : ();
290     my $netcount = 0;
291     foreach my $network ( @networks ) { 
292         my $productgroups = $network->{'ProductGroup'};
293         my @productgroups = defined $productgroups ? @$productgroups : ();
294         my $pgcount = 0;
295         foreach my $productgroup ( @productgroups ) {
296             my $prefix = "ikano_Network_$netcount"."_ProductGroup_$pgcount"."_";
297             $qoptions->{$prefix."TermsId"} = $productgroup->{'TermsId'};
298             my $products = $productgroup->{'Product'};
299             my @products = defined $products ? @$products : ();
300             my $prodcount = 0;
301             foreach my $product ( @products ) {
302                 $qoptions->{$prefix."Product_$prodcount"."_ProductCustomId"} = $product->{'ProductCustomId'};
303                 $prodcount++;
304             }
305             $pgcount++;
306         }
307         $netcount++;
308     }
309
310     {   'vendor_qual_id' => $result->{'PrequalId'},
311         'status' => scalar(@networks) ? 'Q' : 'D',
312         'options' => $qoptions,
313     };
314 }
315
316 sub qual_html {
317     my($self,$qual) = (shift,shift);
318     
319     my %qual_options = $qual->options;
320     my @externalids = ();
321     my( $optionname, $optionvalue );
322     while (($optionname, $optionvalue) = each %qual_options) {
323         push @externalids, $optionvalue 
324             if ( $optionname =~ /^ikano_Network_(\d+)_ProductGroup_(\d+)_Product_(\d+)_ProductCustomId$/
325                 && $optionvalue ne '' );
326     }
327
328     # XXX: eventually perhaps this should return both the packages a link to
329     # order each package and go to the svc prov with the prequal id filled in
330     # but only if cust, not prospect!
331     my $list = "<B>Qualifying Packages:</B><UL>";
332     my @part_pkgs = qsearch( 'part_pkg', { 'disabled' => '' } );
333     foreach my $part_pkg ( @part_pkgs ) {
334         my %vendor_pkg_ids = $part_pkg->vendor_pkg_ids;
335         my $externalid = $vendor_pkg_ids{$self->exportnum} 
336             if defined $vendor_pkg_ids{$self->exportnum};
337         if ( $externalid ) {
338             $list .= "<LI>".$part_pkg->pkgpart.": ".$part_pkg->pkg." - "
339                 .$part_pkg->comment."</LI>" 
340               if grep( $_ eq $externalid, @externalids );
341         }
342     }
343     $list .= "</UL>";
344     $list;
345 }
346
347 sub notes_html { 
348     my($self,$svc_dsl) = (shift,shift);
349     my $conf = new FS::Conf;
350     my $date_format = $conf->config('date_format') || '%m/%d/%Y';
351     my @notes = $svc_dsl->notes;
352     my $html = '<TABLE border="1" cellspacing="2" cellpadding="2" id="dsl_notes">
353         <TR><TH>Date</TH><TH>By</TH><TH>Priority</TH><TH>Note</TH></TR>';
354     foreach my $note ( @notes ) {
355         $html .= "<TR>
356             <TD>".time2str("$date_format %H:%M",$note->date)."</TD>
357             <TD>".$note->by."</TD>
358             <TD>". ($note->priority eq 'N' ? 'Normal' : 'High') ."</TD>
359             <TD>".$note->note."</TD></TR>";
360     }
361     $html .= '</TABLE>';
362     $html;
363 }
364
365 sub loop_type_long { # sub, not a method
366     my($svc_dsl) = (shift);
367     return $loopType{$svc_dsl->loop_type};
368 }
369
370 sub ikano_command {
371   my( $self, $command, $args ) = @_;
372
373   $self->loadmod;
374
375   my $ikano = Net::Ikano->new(
376     'keyid' => $self->option('keyid'),
377     'username'  => $self->option('username'),
378     'password'  => $self->option('password'),
379     'debug'    => $self->option('debug'),
380   );
381
382   $ikano->$command($args);
383 }
384
385 sub loadmod {
386   eval "use Net::Ikano;";
387   die $@ if $@;
388 }
389
390 sub valid_order {
391   my( $self, $svc_dsl, $action ) = (shift, shift, shift);
392  
393   $self->loadmod;
394   
395   warn "$me valid_order action=$action svc_dsl:\n". Dumper($svc_dsl)
396         if $self->option('debug');
397
398   # common to all order types/status/loop_type
399   my $error = !($svc_dsl->desired_due_date
400             &&  grep($_ eq $svc_dsl->vendor_order_type, Net::Ikano->orderTypes)
401             &&  $svc_dsl->first
402             &&  $svc_dsl->last
403             &&  defined $svc_dsl->loop_type
404             &&  $svc_dsl->vendor_qual_id
405             );
406   return 'Missing or invalid order data' if $error;
407  
408   my %vendor_pkg_ids = $svc_dsl->cust_svc->cust_pkg->part_pkg->vendor_pkg_ids;
409   return 'Package does not have an external id configured'
410     unless defined $vendor_pkg_ids{$self->exportnum};
411
412   return 'No valid qualification for this order' 
413     unless qsearch( 'qual', { 'vendor_qual_id' => $svc_dsl->vendor_qual_id });
414
415   # now go by order type
416   # weird ifs & long lines for readability and ease of understanding - don't change
417   if($svc_dsl->vendor_order_type eq 'NEW') {
418     if($svc_dsl->pushed) {
419         $error = !( ($action eq 'pull' || $action eq 'statuschg' 
420                         || $action eq 'delete' || $action eq 'expire')
421             &&  length($svc_dsl->vendor_order_id) > 0
422             &&  length($svc_dsl->vendor_order_status) > 0
423                 );
424         return 'Invalid order data' if $error;
425
426         return 'Phone number required for status change'
427             if ($action eq 'statuschg' && length($svc_dsl->phonenum) < 1);
428     }
429     else { # unpushed New order - cannot do anything other than push it
430         $error = !($action eq 'insert'
431             &&  length($svc_dsl->vendor_order_id) < 1
432             &&  length($svc_dsl->vendor_order_status) < 1
433             && ( ($svc_dsl->phonenum eq '' && $svc_dsl->loop_type eq '0') # dry
434               || ($svc_dsl->phonenum ne '' && $svc_dsl->loop_type eq '') # line-share
435                )
436             );  
437         return 'Invalid order data' if $error;
438     }
439   }
440   elsif($svc_dsl->vendor_order_type eq 'CANCEL') {
441   }
442   elsif($svc_dsl->vendor_order_type eq 'CHANGE') {
443   }
444
445  '';
446 }
447
448 sub qual2termsid {
449     my ($self,$vendor_qual_id,$ProductCustomId) = (shift,shift,shift);
450     my $qual = qsearchs( 'qual', { 'vendor_qual_id' => $vendor_qual_id });
451     return '' unless $qual;
452     my %qual_options = $qual->options;
453     my( $optionname, $optionvalue );
454     while (($optionname, $optionvalue) = each %qual_options) {
455         if ( $optionname =~ /^ikano_Network_(\d+)_ProductGroup_(\d+)_Product_(\d+)_ProductCustomId$/ 
456             && $optionvalue eq $ProductCustomId ) {
457             my $network = $1;
458             my $productgroup = $2;
459             return $qual->option("ikano_Network_".$network."_ProductGroup_".$productgroup."_TermsId");
460         }
461     }
462     '';
463 }
464
465 sub _export_insert {
466   my( $self, $svc_dsl ) = (shift, shift);
467
468   my $result = $self->valid_order($svc_dsl,'insert');
469   return $result unless $result eq '';
470
471   my $isp_chg = $svc_dsl->isp_chg eq 'Y' ? 'YES' : 'NO';
472   my $contactTN = $svc_dsl->cust_svc->cust_pkg->cust_main->daytime;
473   $contactTN =~ s/[^0-9]//g;
474
475   my %vendor_pkg_ids = $svc_dsl->cust_svc->cust_pkg->part_pkg->vendor_pkg_ids;
476   my $ProductCustomId = $vendor_pkg_ids{$self->exportnum};
477
478   my $args = {
479         orderType => 'NEW',
480         ProductCustomId => $ProductCustomId,
481         TermsId => $self->qual2termsid($svc_dsl->vendor_qual_id,$ProductCustomId),
482         DSLPhoneNumber => $svc_dsl->loop_type eq '0' ? 'STANDALONE'
483                                                     : $svc_dsl->phonenum,
484         Password => $svc_dsl->password,
485         PrequalId => $svc_dsl->vendor_qual_id,
486         CompanyName => $svc_dsl->company,
487         FirstName => $svc_dsl->first,
488         LastName => $svc_dsl->last,
489         MiddleName => '',
490         ContactMethod => 'PHONE',
491         ContactPhoneNumber => $contactTN,
492         ContactEmail => 'x@x.xx',
493         ContactFax => '',
494         DateToOrder => time2str("%Y-%m-%d",$svc_dsl->desired_due_date),
495         RequestClientIP => '127.0.0.1',
496         IspChange => $isp_chg,
497         IspPrevious => $isp_chg eq 'YES' ? $svc_dsl->isp_prev : '',
498         CurrentProvider => $isp_chg eq 'NO' ? $svc_dsl->isp_prev : '',
499   };
500
501   $result = $self->ikano_command('ORDER',$args); 
502   return $result unless ref($result); # scalar (string) is an error
503
504   # now we're getting an OrderResponse which should have one Order in it
505   warn "$me _export_insert OrderResponse hash:\n".Dumper($result)
506         if $self->option('debug');
507   
508   return 'Invalid order response' unless defined $result->{'Order'};
509   $result = $result->{'Order'};
510
511   return 'No/invalid order id or status returned' 
512     unless defined $result->{'Status'} && defined $result->{'OrderId'}
513         && grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus);
514
515   $svc_dsl->pushed(time);
516   $svc_dsl->last_pull((time)+1); 
517   $svc_dsl->vendor_order_id($result->{'OrderId'});
518   $svc_dsl->vendor_order_status($result->{'Status'});
519   $svc_dsl->username($result->{'Username'});
520   local $FS::svc_Common::noexport_hack = 1;
521   $result = $svc_dsl->replace; 
522   return "Error setting DSL fields: $result" if $result;
523   '';
524 }
525
526 sub _export_replace {
527   my( $self, $new, $old ) = (shift, shift, shift);
528 # XXX only supports password changes now, but should return error if 
529 # another change is attempted?
530
531   if($new->password ne $old->password) {
532       my $result = $self->valid_order($new,'statuschg');
533       return $result unless $result eq '';
534       
535       $result = $self->ikano_command('PASSWORDCHANGE',
536             { DSLPhoneNumber => $new->phonenum,
537               NewPassword => $new->password,
538             } ); 
539       return $result unless ref($result); # scalar (string) is an error
540
541       return 'Error changing password' unless defined $result->{'Password'}
542         && $result->{'Password'} eq $new->password;
543   }
544
545   '';
546 }
547
548 sub _export_delete {
549   my( $self, $svc_dsl ) = (shift, shift);
550   
551   my $result = $self->valid_order($svc_dsl,'delete');
552   return $result unless $result eq '';
553
554   # for now allow an immediate cancel only on New orders in New/Pending status
555   #XXX: add support for Change and Cancel orders in New/Pending status later
556
557   if($svc_dsl->vendor_order_type eq 'NEW') {
558     if($svc_dsl->vendor_order_status eq 'NEW' 
559             || $svc_dsl->vendor_order_status eq 'PENDING') {
560         my $result = $self->ikano_command('CANCEL', 
561             { OrderId => $svc_dsl->vendor_order_id, } );
562         return $result unless ref($result); # scalar (string) is an error
563         return 'Unable to cancel order' unless $result->{'Order'};
564         $result = $result->{'Order'};
565         return 'Invalid cancellation response' 
566             unless $result->{'Status'} eq 'CANCELLED' 
567                 && $result->{'OrderId'} eq $svc_dsl->vendor_order_id;
568
569         # we're supposed to do a pull, but it will break everything, so don't
570         # this is very wrong...
571     }
572     else {
573         return "Cannot cancel a NEW order unless it's in NEW or PENDING status";
574     }
575   }
576   elsif($svc_dsl->vendor_order_type eq 'CANCEL') {
577      return 'Cannot cancel a CANCEL order unless expire was set'
578         unless $svc_dsl->cust_svc->cust_pkg->expire > 0;
579   }
580   else {
581     return 'Canceling orders other than NEW orders is not currently implemented';
582   }
583
584   '';
585 }
586
587 sub export_expire {
588   my($self, $svc_dsl, $date) = (shift, shift, shift);
589   
590   my $result = $self->valid_order($svc_dsl,'expire');
591   return $result unless $result eq '';
592   
593   # for now allow a proper cancel only on New orders in Completed status
594   #XXX: add support for some other cases in future
595   
596   if($svc_dsl->vendor_order_type eq 'NEW' 
597         && $svc_dsl->vendor_order_status eq 'COMPLETED') {
598     
599           my $contactTN = $svc_dsl->cust_svc->cust_pkg->cust_main->daytime;
600           $contactTN =~ s/[^0-9]//g;
601
602           my %vendor_pkg_ids = $svc_dsl->cust_svc->cust_pkg->part_pkg->vendor_pkg_ids;
603           my $ProductCustomId = $vendor_pkg_ids{$self->exportnum};
604
605           # we are now a cancel order
606           $svc_dsl->desired_due_date($date);
607           $svc_dsl->vendor_order_type('CANCEL');
608
609           my $args = {
610                 orderType => 'CANCEL',
611                 ProductCustomId => $ProductCustomId,
612                 TermsId => $self->qual2termsid($svc_dsl->vendor_qual_id,$ProductCustomId),
613                 DSLPhoneNumber => $svc_dsl->loop_type eq '0' ? 'STANDALONE'
614                                                             : $svc_dsl->phonenum,
615                 Password => $svc_dsl->password,
616                 PrequalId => $svc_dsl->vendor_qual_id,
617                 CompanyName => $svc_dsl->company,
618                 FirstName => $svc_dsl->first,
619                 LastName => $svc_dsl->last,
620                 MiddleName => '',
621                 ContactMethod => 'PHONE',
622                 ContactPhoneNumber => $contactTN,
623                 ContactEmail => 'x@x.xx',
624                 ContactFax => '',
625                 DateToOrder => time2str("%Y-%m-%d",$date),
626                 RequestClientIP => '127.0.0.1',
627                 IspChange => 'NO',
628                 IspPrevious => '',
629                 CurrentProvider => '',
630           };
631
632           $args->{'VirtualPhoneNumber'} = $svc_dsl->phonenum 
633             if $svc_dsl->loop_type eq '0';
634
635           $result = $self->ikano_command('ORDER',$args); 
636           return $result unless ref($result); # scalar (string) is an error
637
638           # now we're getting an OrderResponse which should have one Order in it
639           warn "$me _export_insert OrderResponse hash:\n".Dumper($result)
640                 if $self->option('debug');
641           
642           return 'Invalid order response' unless defined $result->{'Order'};
643           $result = $result->{'Order'};
644
645           return 'No/invalid order id or status returned' 
646             unless defined $result->{'Status'} && defined $result->{'OrderId'}
647                 && grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus);
648
649           $svc_dsl->pushed(time);
650           $svc_dsl->last_pull((time)+1); 
651           $svc_dsl->vendor_order_id($result->{'OrderId'});
652           $svc_dsl->vendor_order_status($result->{'Status'});
653           $svc_dsl->monitored('Y');
654           local $FS::svc_Common::noexport_hack = 1;
655           $result = $svc_dsl->replace; 
656           return "Error setting DSL fields: $result" if $result;
657   }
658   else {
659     return "Cancelling anything other than NEW orders in COMPLETED status is "
660         . "not currently implemented";
661   }
662  '';
663 }
664
665 sub statuschg {
666   my( $self, $svc_dsl, $type ) = (shift, shift, shift);
667
668   my $result = $self->valid_order($svc_dsl,'statuschg');
669   return $result unless $result eq '';
670
671   # get the DSLServiceId
672   $result = $self->ikano_command('CUSTOMERLOOKUP',
673         { PhoneNumber => $svc_dsl->phonenum } ); 
674   return $result unless ref($result); # scalar (string) is an error
675   return 'No DSLServiceId found' unless defined $result->{'DSLServiceId'};
676   my $DSLServiceId = $result->{'DSLServiceId'};
677
678   $result = $self->ikano_command('ACCOUNTSTATUSCHANGE',
679         { DSLPhoneNumber => $svc_dsl->phonenum,
680           DSLServiceId => $DSLServiceId,
681           type => $type,
682         } ); 
683   return $result unless ref($result); # scalar (string) is an error
684   ''; 
685 }
686
687 sub _export_suspend {
688   my( $self, $svc_dsl ) = (shift, shift);
689   $self->statuschg($svc_dsl,"SUSPEND");
690 }
691
692 sub _export_unsuspend {
693   my( $self, $svc_dsl ) = (shift, shift);
694   $self->statuschg($svc_dsl,"UNSUSPEND");
695 }
696
697 1;