Ikano / svc_dsl / qualification improvements, 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_result {
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     my %pkglist = ();
329     my $result = { 'header' => 'Qualifying Packages',
330                    'pkglist' => \%pkglist,
331                  };
332
333     my @part_pkgs = qsearch( 'part_pkg', { 'disabled' => '' } );
334     foreach my $part_pkg ( @part_pkgs ) {
335         my %vendor_pkg_ids = $part_pkg->vendor_pkg_ids;
336         my $externalid = $vendor_pkg_ids{$self->exportnum} 
337             if defined $vendor_pkg_ids{$self->exportnum};
338         if ( $externalid && grep( $_ eq $externalid, @externalids )) {
339             $pkglist{$part_pkg->pkgpart} = $part_pkg->pkg." - ".$part_pkg->comment;
340         }
341     }
342
343     $result;
344 }
345
346 sub quals_by_cust_and_pkg { 
347     my($self, $custnum, $pkgpart) = (shift,shift,shift);
348
349     die "invalid custnum or pkgpart"
350         unless ($custnum =~ /^\d+$/ && $pkgpart =~ /^\d+$/);
351
352     my $part_pkg = qsearchs('part_pkg', { 'pkgpart' => $pkgpart } );
353     die "no part_pkg found" unless $part_pkg;
354     my %vendor_pkg_ids = $part_pkg->vendor_pkg_ids;
355     my $external_id = $vendor_pkg_ids{$self->exportnum};
356     die "no vendor package id defined on this package" unless $external_id;
357     
358     my $extra_sql = "where custnum = $custnum or locationnum in (select "
359         . "locationnum from cust_location where custnum = $custnum)";
360     my @quals = qsearch( { 'table' => 'qual', 'extra_sql' => $extra_sql, } );
361
362     my @filtered_quals;
363     foreach my $qual ( @quals ) {
364         my %qual_options = $qual->options;
365         my( $optionname, $optionvalue );
366         while (($optionname, $optionvalue) = each %qual_options) {
367            push @filtered_quals, $qual
368               if ( $optionname =~ /^ikano_Network_(\d+)_ProductGroup_(\d+)_Product_(\d+)_ProductCustomId$/
369                     && $optionvalue eq $external_id );
370         }
371     }
372
373     @filtered_quals;
374 }
375
376 sub notes_html { 
377     my($self,$svc_dsl) = (shift,shift);
378     my $conf = new FS::Conf;
379     my $date_format = $conf->config('date_format') || '%m/%d/%Y';
380     my @notes = $svc_dsl->notes;
381     my $html = '<TABLE border="1" cellspacing="2" cellpadding="2" id="dsl_notes">
382         <TR><TH>Date</TH><TH>By</TH><TH>Priority</TH><TH>Note</TH></TR>';
383     foreach my $note ( @notes ) {
384         $html .= "<TR>
385             <TD>".time2str("$date_format %H:%M",$note->date)."</TD>
386             <TD>".$note->by."</TD>
387             <TD>". ($note->priority eq 'N' ? 'Normal' : 'High') ."</TD>
388             <TD>".$note->note."</TD></TR>";
389     }
390     $html .= '</TABLE>';
391     $html;
392 }
393
394 sub loop_type_long { # sub, not a method
395     my($svc_dsl) = (shift);
396     return $loopType{$svc_dsl->loop_type};
397 }
398
399 sub ikano_command {
400   my( $self, $command, $args ) = @_;
401
402   $self->loadmod;
403
404   my $ikano = Net::Ikano->new(
405     'keyid' => $self->option('keyid'),
406     'username'  => $self->option('username'),
407     'password'  => $self->option('password'),
408     'debug'    => $self->option('debug'),
409   );
410
411   $ikano->$command($args);
412 }
413
414 sub loadmod {
415   eval "use Net::Ikano;";
416   die $@ if $@;
417 }
418
419 sub valid_order {
420   my( $self, $svc_dsl, $action ) = (shift, shift, shift);
421  
422   $self->loadmod;
423   
424   warn "$me valid_order action=$action svc_dsl:\n". Dumper($svc_dsl)
425         if $self->option('debug');
426
427   # common to all order types/status/loop_type
428   my $error = !($svc_dsl->desired_due_date
429             &&  grep($_ eq $svc_dsl->vendor_order_type, Net::Ikano->orderTypes)
430             &&  $svc_dsl->first
431             &&  $svc_dsl->last
432             &&  defined $svc_dsl->loop_type
433             &&  $svc_dsl->vendor_qual_id
434             );
435   return 'Missing or invalid order data' if $error;
436  
437   my %vendor_pkg_ids = $svc_dsl->cust_svc->cust_pkg->part_pkg->vendor_pkg_ids;
438   return 'Package does not have an external id configured'
439     unless defined $vendor_pkg_ids{$self->exportnum};
440
441   return 'No valid qualification for this order' 
442     unless qsearch( 'qual', { 'vendor_qual_id' => $svc_dsl->vendor_qual_id });
443
444   # now go by order type
445   # weird ifs & long lines for readability and ease of understanding - don't change
446   if($svc_dsl->vendor_order_type eq 'NEW') {
447     if($svc_dsl->pushed) {
448         $error = !( ($action eq 'pull' || $action eq 'statuschg' 
449                         || $action eq 'delete' || $action eq 'expire')
450             &&  length($svc_dsl->vendor_order_id) > 0
451             &&  length($svc_dsl->vendor_order_status) > 0
452                 );
453         return 'Invalid order data' if $error;
454
455         return 'Phone number required for status change'
456             if ($action eq 'statuschg' && length($svc_dsl->phonenum) < 1);
457     }
458     else { # unpushed New order - cannot do anything other than push it
459         $error = !($action eq 'insert'
460             &&  length($svc_dsl->vendor_order_id) < 1
461             &&  length($svc_dsl->vendor_order_status) < 1
462             && ( ($svc_dsl->phonenum eq '' && $svc_dsl->loop_type eq '0') # dry
463               || ($svc_dsl->phonenum ne '' && $svc_dsl->loop_type eq '') # line-share
464                )
465             );  
466         return 'Invalid order data' if $error;
467     }
468   }
469   elsif($svc_dsl->vendor_order_type eq 'CANCEL') {
470   }
471   elsif($svc_dsl->vendor_order_type eq 'CHANGE') {
472   }
473
474  '';
475 }
476
477 sub qual2termsid {
478     my ($self,$vendor_qual_id,$ProductCustomId) = (shift,shift,shift);
479     my $qual = qsearchs( 'qual', { 'vendor_qual_id' => $vendor_qual_id });
480     return '' unless $qual;
481     my %qual_options = $qual->options;
482     my( $optionname, $optionvalue );
483     while (($optionname, $optionvalue) = each %qual_options) {
484         if ( $optionname =~ /^ikano_Network_(\d+)_ProductGroup_(\d+)_Product_(\d+)_ProductCustomId$/ 
485             && $optionvalue eq $ProductCustomId ) {
486             my $network = $1;
487             my $productgroup = $2;
488             return $qual->option("ikano_Network_".$network."_ProductGroup_".$productgroup."_TermsId");
489         }
490     }
491     '';
492 }
493
494 sub _export_insert {
495   my( $self, $svc_dsl ) = (shift, shift);
496
497   my $result = $self->valid_order($svc_dsl,'insert');
498   return $result unless $result eq '';
499
500   my $isp_chg = $svc_dsl->isp_chg eq 'Y' ? 'YES' : 'NO';
501   my $contactTN = $svc_dsl->cust_svc->cust_pkg->cust_main->daytime;
502   $contactTN =~ s/[^0-9]//g;
503
504   my %vendor_pkg_ids = $svc_dsl->cust_svc->cust_pkg->part_pkg->vendor_pkg_ids;
505   my $ProductCustomId = $vendor_pkg_ids{$self->exportnum};
506
507   my $args = {
508         orderType => 'NEW',
509         ProductCustomId => $ProductCustomId,
510         TermsId => $self->qual2termsid($svc_dsl->vendor_qual_id,$ProductCustomId),
511         DSLPhoneNumber => $svc_dsl->loop_type eq '0' ? 'STANDALONE'
512                                                     : $svc_dsl->phonenum,
513         Password => $svc_dsl->password,
514         PrequalId => $svc_dsl->vendor_qual_id,
515         CompanyName => $svc_dsl->company,
516         FirstName => $svc_dsl->first,
517         LastName => $svc_dsl->last,
518         MiddleName => '',
519         ContactMethod => 'PHONE',
520         ContactPhoneNumber => $contactTN,
521         ContactEmail => 'x@x.xx',
522         ContactFax => '',
523         DateToOrder => time2str("%Y-%m-%d",$svc_dsl->desired_due_date),
524         RequestClientIP => '127.0.0.1',
525         IspChange => $isp_chg,
526         IspPrevious => $isp_chg eq 'YES' ? $svc_dsl->isp_prev : '',
527         CurrentProvider => $isp_chg eq 'NO' ? $svc_dsl->isp_prev : '',
528   };
529
530   $result = $self->ikano_command('ORDER',$args); 
531   return $result unless ref($result); # scalar (string) is an error
532
533   # now we're getting an OrderResponse which should have one Order in it
534   warn "$me _export_insert OrderResponse hash:\n".Dumper($result)
535         if $self->option('debug');
536   
537   return 'Invalid order response' unless defined $result->{'Order'};
538   $result = $result->{'Order'};
539
540   return 'No/invalid order id or status returned' 
541     unless defined $result->{'Status'} && defined $result->{'OrderId'}
542         && grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus);
543
544   $svc_dsl->pushed(time);
545   $svc_dsl->last_pull((time)+1); 
546   $svc_dsl->vendor_order_id($result->{'OrderId'});
547   $svc_dsl->vendor_order_status($result->{'Status'});
548   $svc_dsl->username($result->{'Username'});
549   local $FS::svc_Common::noexport_hack = 1;
550   $result = $svc_dsl->replace; 
551   return "Error setting DSL fields: $result" if $result;
552   '';
553 }
554
555 sub _export_replace {
556   my( $self, $new, $old ) = (shift, shift, shift);
557 # XXX only supports password changes now, but should return error if 
558 # another change is attempted?
559
560   if($new->password ne $old->password) {
561       my $result = $self->valid_order($new,'statuschg');
562       return $result unless $result eq '';
563       
564       $result = $self->ikano_command('PASSWORDCHANGE',
565             { DSLPhoneNumber => $new->phonenum,
566               NewPassword => $new->password,
567             } ); 
568       return $result unless ref($result); # scalar (string) is an error
569
570       return 'Error changing password' unless defined $result->{'Password'}
571         && $result->{'Password'} eq $new->password;
572   }
573
574   '';
575 }
576
577 sub _export_delete {
578   my( $self, $svc_dsl ) = (shift, shift);
579   
580   my $result = $self->valid_order($svc_dsl,'delete');
581   return $result unless $result eq '';
582
583   # for now allow an immediate cancel only on New orders in New/Pending status
584   #XXX: add support for Change and Cancel orders in New/Pending status later
585
586   if($svc_dsl->vendor_order_type eq 'NEW') {
587     if($svc_dsl->vendor_order_status eq 'NEW' 
588             || $svc_dsl->vendor_order_status eq 'PENDING') {
589         my $result = $self->ikano_command('CANCEL', 
590             { OrderId => $svc_dsl->vendor_order_id, } );
591         return $result unless ref($result); # scalar (string) is an error
592         return 'Unable to cancel order' unless $result->{'Order'};
593         $result = $result->{'Order'};
594         return 'Invalid cancellation response' 
595             unless $result->{'Status'} eq 'CANCELLED' 
596                 && $result->{'OrderId'} eq $svc_dsl->vendor_order_id;
597
598         # we're supposed to do a pull, but it will break everything, so don't
599         # this is very wrong...
600     }
601     else {
602         return "Cannot cancel a NEW order unless it's in NEW or PENDING status";
603     }
604   }
605   elsif($svc_dsl->vendor_order_type eq 'CANCEL') {
606      return 'Cannot cancel a CANCEL order unless expire was set'
607         unless $svc_dsl->cust_svc->cust_pkg->expire > 0;
608   }
609   else {
610     return 'Canceling orders other than NEW orders is not currently implemented';
611   }
612
613   '';
614 }
615
616 sub export_expire {
617   my($self, $svc_dsl, $date) = (shift, shift, shift);
618   
619   my $result = $self->valid_order($svc_dsl,'expire');
620   return $result unless $result eq '';
621   
622   # for now allow a proper cancel only on New orders in Completed status
623   #XXX: add support for some other cases in future
624   
625   if($svc_dsl->vendor_order_type eq 'NEW' 
626         && $svc_dsl->vendor_order_status eq 'COMPLETED') {
627     
628           my $contactTN = $svc_dsl->cust_svc->cust_pkg->cust_main->daytime;
629           $contactTN =~ s/[^0-9]//g;
630
631           my %vendor_pkg_ids = $svc_dsl->cust_svc->cust_pkg->part_pkg->vendor_pkg_ids;
632           my $ProductCustomId = $vendor_pkg_ids{$self->exportnum};
633
634           # we are now a cancel order
635           $svc_dsl->desired_due_date($date);
636           $svc_dsl->vendor_order_type('CANCEL');
637
638           my $args = {
639                 orderType => 'CANCEL',
640                 ProductCustomId => $ProductCustomId,
641                 TermsId => $self->qual2termsid($svc_dsl->vendor_qual_id,$ProductCustomId),
642                 DSLPhoneNumber => $svc_dsl->loop_type eq '0' ? 'STANDALONE'
643                                                             : $svc_dsl->phonenum,
644                 Password => $svc_dsl->password,
645                 PrequalId => $svc_dsl->vendor_qual_id,
646                 CompanyName => $svc_dsl->company,
647                 FirstName => $svc_dsl->first,
648                 LastName => $svc_dsl->last,
649                 MiddleName => '',
650                 ContactMethod => 'PHONE',
651                 ContactPhoneNumber => $contactTN,
652                 ContactEmail => 'x@x.xx',
653                 ContactFax => '',
654                 DateToOrder => time2str("%Y-%m-%d",$date),
655                 RequestClientIP => '127.0.0.1',
656                 IspChange => 'NO',
657                 IspPrevious => '',
658                 CurrentProvider => '',
659           };
660
661           $args->{'VirtualPhoneNumber'} = $svc_dsl->phonenum 
662             if $svc_dsl->loop_type eq '0';
663
664           $result = $self->ikano_command('ORDER',$args); 
665           return $result unless ref($result); # scalar (string) is an error
666
667           # now we're getting an OrderResponse which should have one Order in it
668           warn "$me _export_insert OrderResponse hash:\n".Dumper($result)
669                 if $self->option('debug');
670           
671           return 'Invalid order response' unless defined $result->{'Order'};
672           $result = $result->{'Order'};
673
674           return 'No/invalid order id or status returned' 
675             unless defined $result->{'Status'} && defined $result->{'OrderId'}
676                 && grep($_ eq $result->{'Status'}, @Net::Ikano::orderStatus);
677
678           $svc_dsl->pushed(time);
679           $svc_dsl->last_pull((time)+1); 
680           $svc_dsl->vendor_order_id($result->{'OrderId'});
681           $svc_dsl->vendor_order_status($result->{'Status'});
682           $svc_dsl->monitored('Y');
683           local $FS::svc_Common::noexport_hack = 1;
684           $result = $svc_dsl->replace; 
685           return "Error setting DSL fields: $result" if $result;
686   }
687   else {
688     return "Cancelling anything other than NEW orders in COMPLETED status is "
689         . "not currently implemented";
690   }
691  '';
692 }
693
694 sub statuschg {
695   my( $self, $svc_dsl, $type ) = (shift, shift, shift);
696
697   my $result = $self->valid_order($svc_dsl,'statuschg');
698   return $result unless $result eq '';
699
700   # get the DSLServiceId
701   $result = $self->ikano_command('CUSTOMERLOOKUP',
702         { PhoneNumber => $svc_dsl->phonenum } ); 
703   return $result unless ref($result); # scalar (string) is an error
704   return 'No DSLServiceId found' unless defined $result->{'DSLServiceId'};
705   my $DSLServiceId = $result->{'DSLServiceId'};
706
707   $result = $self->ikano_command('ACCOUNTSTATUSCHANGE',
708         { DSLPhoneNumber => $svc_dsl->phonenum,
709           DSLServiceId => $DSLServiceId,
710           type => $type,
711         } ); 
712   return $result unless ref($result); # scalar (string) is an error
713   ''; 
714 }
715
716 sub _export_suspend {
717   my( $self, $svc_dsl ) = (shift, shift);
718   $self->statuschg($svc_dsl,"SUSPEND");
719 }
720
721 sub _export_unsuspend {
722   my( $self, $svc_dsl ) = (shift, shift);
723   $self->statuschg($svc_dsl,"UNSUSPEND");
724 }
725
726 1;