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