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