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