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