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