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