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