3eae5586cab18189c5eb98a5fef9cce71d3066dd
[freeside.git] / FS / FS / part_export / saisei.pm
1 package FS::part_export::saisei;
2
3 use strict;
4 use vars qw( @ISA %info );
5 use base qw( FS::part_export );
6 use Date::Format 'time2str';
7 use Cpanel::JSON::XS;
8 use Storable qw(thaw);
9 use MIME::Base64;
10 use REST::Client;
11 use Data::Dumper;
12 use FS::Conf;
13
14 =pod
15
16 =head1 NAME
17
18 FS::part_export::saisei
19
20 =head1 SYNOPSIS
21
22 Saisei integration for Freeside
23
24 =head1 DESCRIPTION
25
26 This export offers basic svc_broadband provisioning for Saisei.
27
28 This is a customer integration with Saisei.  This will set up a rate plan and tie
29 the rate plan to a host and the access point via the Saisei API when the broadband service is provisioned.
30 It will also untie the host from the rate plan, setting it to the default rate plan via the API upon unprovisioning of the broadband service.
31
32 This will create and modify the rate plans at Saisei as soon as the broadband service attached to this export is created or modified.
33 This will also create and modify an access point at Saisei as soon as the tower is created or modified.
34
35 To use this export, follow the below instructions:
36
37 Create a new service definition and set the table to svc_broadband.  The service name will become the Saisei rate plan name.
38 Set the upload and download speed for the service. This is required to be able to export the service to Saisei.
39 Attach this Saisei export to this service.
40
41 Create a tower and add a sector to that tower.  The sector name will be the name of the access point,
42 Make sure you have set the up and down rate limit for the tower and the sector.  This is required to be able to export the access point.
43 The tower and sector will be set up as access points at Saisei upon the creation of the tower or sector.  They will be modified at Saisei when modified in freeside.
44 Each sector will be attached to its tower access point using the Saisei uplink field.
45
46 Create a package for the above created service, and order this package for a customer.
47
48 Provision the service, making sure to enter the IP address associated with this service and select the tower and sector for it's access point.
49 This provisioned service will then be exported as a host to Saisei.
50
51 Unprovisioning this service will set the host entry at Saisei to the default rate plan with the user and access point set to <none>.
52
53 After this export is set up and attached to a service, you can export the already provisioned services by clicking the link Export provisioned services attached to this export.
54 Clicking on this link will export all services attached to this export not currently exported to Saisei.
55
56 This module also provides generic methods for working through the L</Saisei API>.
57
58 =cut
59
60 tie my %scripts, 'Tie::IxHash',
61   'export_provisioned_services'  => { component => '/elements/popup_link.html',
62                                       label     => 'Export provisioned services',
63                                       description => 'will export provisioned services of part service with Saisei export attached.',
64                                       html_label => '<b>Export provisioned services attached to this export.</b>',
65                                     },
66 ;
67
68 tie my %options, 'Tie::IxHash',
69   'port'             => { label => 'Port',
70                           default => 5000 },
71   'username'         => { label => 'Saisei API User Name',
72                           default => '' },
73   'password'         => { label => 'Saisei API Password',
74                           default => '' },
75   'debug'            => { type => 'checkbox',
76                           label => 'Enable debug warnings' },
77 ;
78
79 %info = (
80   'svc'             => 'svc_broadband',
81   'desc'            => 'Export broadband service/account to Saisei',
82   'options'         => \%options,
83   'scripts'         => \%scripts,
84   'notes'           => <<'END',
85 This is a customer integration with Saisei.  This will set up a rate plan and tie
86 the rate plan to a host and the access point via the Saisei API when the broadband service is provisioned.
87 It will also untie the host from the rate plan, setting it to the default rate plan via the API upon unprovisioning of the broadband service.
88 <P>
89 This will create and modify the rate plans at Saisei as soon as the broadband service attached to this export is created or modified.
90 This will also create and modify an access point at Saisei as soon as the tower is created or modified.
91 <P>
92 To use this export, follow the below instructions:
93 <P>
94 <OL>
95 <LI>
96 Create a new service definition and set the table to svc_broadband.  The service name will become the Saisei rate plan name.
97 Set the upload and download speed for the service. This is required to be able to export the service to Saisei.
98 Attach this Saisei export to this service.
99 </LI>
100 <P>
101 <LI>
102 Create a tower and add a sector to that tower.  The sector name will be the name of the access point,
103 Make sure you have set the up and down rate limit for the tower and the sector.  This is required to be able to export the access point.
104 The tower and sector will be set up as access points at Saisei upon the creation of the tower or sector.  They will be modified at Saisei when modified in freeside.
105 Each sector will be attached to its tower access point using the Saisei uplink field.
106 </LI>
107 <P>
108 <LI>
109 Create a package for the above created service, and order this package for a customer.
110 </LI>
111 <P>
112 <LI>
113 Provision the service, making sure to enter the IP address associated with this service and select the tower and sector for it's access point.
114 This provisioned service will then be exported as a host to Saisei.
115 <P>
116 Unprovisioning this service will set the host entry at Saisei to the default rate plan with the user and access point set to <i>none</i>.
117 </LI>
118 <P>
119 <LI>
120 After this export is set up and attached to a service, you can export the already provisioned services by clicking the link <b>Export provisioned services attached to this export</b>.
121 Clicking on this link will export all services attached to this export not currently exported to Saisei.
122 </LI>
123 </OL>
124 <P>
125
126 END
127 );
128
129 sub _export_insert {
130   my ($self, $svc_broadband) = @_;
131
132   my $rateplan_name = $self->get_rateplan_name($svc_broadband);
133
134   # check for existing rate plan
135   my $existing_rateplan;
136   $existing_rateplan = $self->api_get_rateplan($rateplan_name) unless $self->{'__saisei_error'};
137
138   # if no existing rate plan create one and modify it.
139   $self->api_create_rateplan($svc_broadband, $rateplan_name) unless $existing_rateplan;
140   $self->api_modify_rateplan($svc_broadband, $rateplan_name) unless ($self->{'__saisei_error'} || $existing_rateplan);
141   return $self->api_error if $self->{'__saisei_error'};
142
143   # set rateplan to existing one or newly created one.
144   my $rateplan = $existing_rateplan ? $existing_rateplan : $self->api_get_rateplan($rateplan_name);
145
146   my $username = $svc_broadband->{Hash}->{svcnum};
147   my $description = $svc_broadband->{Hash}->{description};
148
149   if (!$username) {
150     $self->{'__saisei_error'} = 'no username - can not export';
151     return $self->api_error;
152   }
153   else {
154     # check for existing user.
155     my $existing_user;
156     $existing_user = $self->api_get_user($username) unless $self->{'__saisei_error'};
157  
158     # if no existing user create one.
159     $self->api_create_user($username, $description) unless $existing_user;
160     return $self->api_error if $self->{'__saisei_error'};
161
162     # set user to existing one or newly created one.
163     my $user = $existing_user ? $existing_user : $self->api_get_user($username);
164
165     ## add access point
166     my $tower_sector = FS::Record::qsearchs({
167       'table'     => 'tower_sector',
168       'select'    => 'tower.towername,
169                       tower.up_rate_limit as tower_upratelimit,
170                       tower.down_rate_limit as tower_downratelimit,
171                       tower_sector.sectorname,
172                       tower_sector.up_rate_limit as sector_upratelimit,
173                       tower_sector.down_rate_limit as sector_downratelimit ',
174       'addl_from' => 'LEFT JOIN tower USING ( towernum )',
175       'hashref'   => {
176                         'sectornum' => $svc_broadband->{Hash}->{sectornum},
177                      },
178     });
179
180     my $tower_name = $tower_sector->{Hash}->{towername};
181     $tower_name =~ s/\s/_/g;
182
183     my $tower_opt = {
184       'tower_name'           => $tower_name,
185       'tower_uprate_limit'   => $tower_sector->{Hash}->{tower_upratelimit},
186       'tower_downrate_limit' => $tower_sector->{Hash}->{tower_downratelimit},
187     };
188
189     my $tower_ap = process_tower($self, $tower_opt);
190     return $self->api_error if $self->{'__saisei_error'};
191
192     my $sector_name = $tower_sector->{Hash}->{sectorname};
193     $sector_name =~ s/\s/_/g;
194
195     my $sector_opt = {
196       'tower_name'            => $tower_name,
197       'sector_name'           => $sector_name,
198       'sector_uprate_limit'   => $tower_sector->{Hash}->{sector_upratelimit},
199       'sector_downrate_limit' => $tower_sector->{Hash}->{sector_downratelimit},
200     };
201     my $accesspoint = process_sector($self, $sector_opt);
202     return $self->api_error if $self->{'__saisei_error'};
203
204 ## get custnum and pkgpart from cust_pkg for virtual access point
205     my $cust_pkg = FS::Record::qsearchs({
206       'table'     => 'cust_pkg',
207       'hashref'   => { 'pkgnum' => $svc_broadband->{Hash}->{pkgnum}, },
208     });
209     my $virtual_ap_name = $cust_pkg->{Hash}->{custnum}.'_'.$cust_pkg->{Hash}->{pkgpart}.'_'.$svc_broadband->{Hash}->{speed_down}.'_'.$svc_broadband->{Hash}->{speed_up};
210
211     my $virtual_ap_opt = {
212       'virtual_name'           => $virtual_ap_name,
213       'sector_name'            => $sector_name,
214       'virtual_uprate_limit'   => $svc_broadband->{Hash}->{speed_up},
215       'virtual_downrate_limit' => $svc_broadband->{Hash}->{speed_down},
216     };
217     my $virtual_ap = process_virtual_ap($self, $virtual_ap_opt);
218     return $self->api_error if $self->{'__saisei_error'};
219
220     ## tie host to user add sector name as access point.
221     $self->api_add_host_to_user(
222       $user->{collection}->[0]->{name},
223       $rateplan->{collection}->[0]->{name},
224       $svc_broadband->{Hash}->{ip_addr},
225       $virtual_ap->{collection}->[0]->{name},
226     ) unless $self->{'__saisei_error'};
227   }
228
229   return $self->api_error;
230
231 }
232
233 sub _export_replace {
234   my ($self, $svc_broadband) = @_;
235   my $error = $self->_export_insert($svc_broadband);
236   return $error;
237 }
238
239 sub _export_delete {
240   my ($self, $svc_broadband) = @_;
241
242   my $rateplan_name = $self->get_rateplan_name($svc_broadband);
243
244   my $username = $svc_broadband->{Hash}->{svcnum};
245
246   ## untie host to user
247   $self->api_delete_host_to_user($username, $rateplan_name, $svc_broadband->{Hash}->{ip_addr}) unless $self->{'__saisei_error'};
248
249   return '';
250 }
251
252 sub _export_suspend {
253   my ($self, $svc_broadband) = @_;
254   return '';
255 }
256
257 sub _export_unsuspend {
258   my ($self, $svc_broadband) = @_;
259   return '';
260 }
261
262 sub export_partsvc {
263   my ($self, $svc_part) = @_;
264
265   my $fcc_477_speeds;
266   if ($svc_part->{Hash}->{svc_broadband__speed_down} eq "down" || $svc_part->{Hash}->{svc_broadband__speed_up} eq "up") {
267     for my $type (qw( down up )) {
268       my $speed_type = "broadband_".$type."stream";
269       foreach my $pkg_svc (FS::Record::qsearch({
270         'table'     => 'pkg_svc',
271         'select'    => 'pkg_svc.*, part_pkg_fcc_option.fccoptionname, part_pkg_fcc_option.optionvalue',
272         'addl_from' => ' LEFT JOIN part_pkg_fcc_option USING (pkgpart) ',
273         'extra_sql' => " WHERE pkg_svc.svcpart = ".$svc_part->{Hash}->{svcpart}." AND pkg_svc.quantity > 0 AND part_pkg_fcc_option.fccoptionname = '".$speed_type."'",
274       })) { $fcc_477_speeds->{
275         $pkg_svc->{Hash}->{pkgpart}}->{$speed_type} = $pkg_svc->{Hash}->{optionvalue} * 1000 unless !$pkg_svc->{Hash}->{optionvalue}; }
276     }
277   }
278   else {
279     $fcc_477_speeds->{1}->{broadband_downstream} = $svc_part->{Hash}->{"svc_broadband__speed_down"};
280     $fcc_477_speeds->{1}->{broadband_upstream} = $svc_part->{Hash}->{"svc_broadband__speed_up"};
281   }
282
283   foreach my $key (keys %$fcc_477_speeds) {
284
285     $svc_part->{Hash}->{speed_down} = $fcc_477_speeds->{$key}->{broadband_downstream};
286     $svc_part->{Hash}->{speed_up} = $fcc_477_speeds->{$key}->{broadband_upstream};
287     $svc_part->{Hash}->{svc_broadband__speed_down} = $fcc_477_speeds->{$key}->{broadband_downstream};
288     $svc_part->{Hash}->{svc_broadband__speed_up} = $fcc_477_speeds->{$key}->{broadband_upstream};
289
290     my $temp_svc = $svc_part->{Hash};
291     my $svc_broadband = {};
292     map { if ($_ =~ /^svc_broadband__(.*)$/) { $svc_broadband->{Hash}->{$1} = $temp_svc->{$_}; }  } keys %$temp_svc;
293
294     my $rateplan_name = $self->get_rateplan_name($svc_broadband, $svc_part->{Hash}->{svc});
295
296     # check for existing rate plan
297     my $existing_rateplan;
298     $existing_rateplan = $self->api_get_rateplan($rateplan_name) unless $self->{'__saisei_error'};
299
300     # Modify the existing rate plan with new service data.
301     $self->api_modify_existing_rateplan($svc_broadband, $rateplan_name) unless ($self->{'__saisei_error'} || !$existing_rateplan);
302
303     # if no existing rate plan create one and modify it.
304     $self->api_create_rateplan($svc_broadband, $rateplan_name) unless $existing_rateplan;
305     $self->api_modify_rateplan($svc_part, $rateplan_name) unless ($self->{'__saisei_error'} || $existing_rateplan);
306
307   }
308
309   return $self->api_error;
310
311 }
312
313 sub export_tower_sector {
314   my ($self, $tower) = @_;
315
316   #modify tower or create it.
317   my $tower_name = $tower->{Hash}->{towername};
318   $tower_name =~ s/\s/_/g;
319   my $tower_opt = {
320     'tower_name'           => $tower_name,
321     'tower_uprate_limit'   => $tower->{Hash}->{up_rate_limit},
322     'tower_downrate_limit' => $tower->{Hash}->{down_rate_limit},
323     'modify_existing'      => '1', # modify an existing access point with this info
324   };
325
326   my $tower_access_point = process_tower($self, $tower_opt);
327
328   #get list of all access points
329   my $hash_opt = {
330       'table'     => 'tower_sector',
331       'select'    => '*',
332       'hashref'   => { 'towernum' => $tower->{Hash}->{towernum}, },
333   };
334
335   #for each one modify or create it.
336   foreach my $tower_sector ( FS::Record::qsearch($hash_opt) ) {
337     my $sector_name = $tower_sector->{Hash}->{sectorname};
338     $sector_name =~ s/\s/_/g;
339     my $sector_opt = {
340       'tower_name'            => $tower_name,
341       'sector_name'           => $sector_name,
342       'sector_uprate_limit'   => $tower_sector->{Hash}->{up_rate_limit},
343       'sector_downrate_limit' => $tower_sector->{Hash}->{down_rate_limit},
344       'modify_existing'       => '1', # modify an existing access point with this info
345     };
346     my $sector_access_point = process_sector($self, $sector_opt);
347   }
348
349   return $self->api_error;
350 }
351
352 ## creates the rateplan name
353 sub get_rateplan_name {
354   my ($self, $svc_broadband, $svc_name) = @_;
355
356   my $service_part = FS::Record::qsearchs( 'part_svc', { 'svcpart' => $svc_broadband->{Hash}->{svcpart} } ) unless $svc_name;
357   my $service_name = $svc_name ? $svc_name : $service_part->{Hash}->{svc};
358
359   my $rateplan_name = $service_name . " " . $svc_broadband->{Hash}->{speed_down} . "-" . $svc_broadband->{Hash}->{speed_up};
360   $rateplan_name =~ s/\s/_/g;
361
362   return $rateplan_name;
363 }
364
365 =head1 Saisei API
366
367 These methods allow access to the Saisei API using the credentials
368 set in the export options.
369
370 =cut
371
372 =head2 api_call
373
374 Accepts I<$method>, I<$path>, I<$params> hashref and optional.
375 Places an api call to the specified path and method with the specified params.
376 Returns the decoded json object returned by the api call.
377 Returns empty on failure;  retrieve error messages using L</api_error>.
378
379 =cut
380
381 sub api_call {
382   my ($self,$method,$path,$params) = @_;
383
384   $self->{'__saisei_error'} = '';
385   my $auth_info = $self->option('username') . ':' . $self->option('password');
386   $params ||= {};
387
388   warn "Calling $method on http://"
389     .$self->{Hash}->{machine}.':'.$self->option('port')
390     ."/rest/top/configurations/running/$path\n" if $self->option('debug');
391
392   my $data = encode_json($params) if keys %{ $params };
393
394   my $client = REST::Client->new();
395   $client->addHeader("Authorization", "Basic ".encode_base64($auth_info));
396   $client->setHost('http://'.$self->{Hash}->{machine}.':'.$self->option('port'));
397   $client->$method('/rest/top/configurations/running'.$path, $data, { "Content-type" => 'application/json'});
398
399   warn "Response Code is ".$client->responseCode()."\n" if $self->option('debug');
400
401   my $result;
402
403   if ($client->responseCode() eq '200' || $client->responseCode() eq '201') {
404     eval { $result = decode_json($client->responseContent()) };
405     unless ($result) {
406       $self->{'__saisei_error'} = "Error decoding json: $@";
407       return;
408     }
409   }
410   elsif ($client->responseCode() eq '404') {
411     eval { $result = decode_json($client->responseContent()) };
412     unless ($result) {
413       $self->{'__saisei_error'} = "Error decoding json: $@";
414       return;
415     }
416     ## check if message is for empty hash.
417     my($does_not_exist) = $result->{message} =~ /'(.*)' does not exist$/;
418     $self->{'__saisei_error'} = "Error ".$result->{message} unless $does_not_exist;
419     warn "Response Content is\n".$client->responseContent."\n" if ($self->option('debug') && !$does_not_exist);
420     return;
421   }
422   elsif ($client->responseCode() eq '500') {
423     $self->{'__saisei_error'} = "Can't connect to host during $method , received responce code: " . $client->responseCode() . " and message: " . $client->responseContent();
424     warn "Response Content is\n".$client->responseContent."\n" if $self->option('debug');
425     return;
426   }
427   else {
428     $self->{'__saisei_error'} = "Bad response from server during $method , received responce code: " . $client->responseCode() . " and message: " . $client->responseContent();
429 #    unless ($method eq "GET");
430     warn "Response Content is\n".$client->responseContent."\n" if $self->option('debug');
431     return; 
432   }
433
434   return $result;
435   
436 }
437
438 =head2 api_error
439
440 Returns the error string set by L</Saisei API> methods,
441 or a blank string if most recent call produced no errors.
442
443 =cut
444
445 sub api_error {
446   my $self = shift;
447   return $self->{'__saisei_error'} || '';
448 }
449
450 =head2 api_get_policies
451
452 Gets a list of global policies.
453
454 =cut
455
456 sub api_get_policies {
457   my $self = shift;
458
459   my $get_policies = $self->api_call("GET", '/policies/?token=1&order=name&start=0&limit=20&select=name%2Cpercent_rate%2Cassured%2C');
460   return if $self->api_error;
461   $self->{'__saisei_error'} = "Did not receive any global policies"
462     unless $get_policies;
463
464   return $get_policies->{collection};
465 }
466
467 =head2 api_get_rateplan
468
469 Gets rateplan info for specific rateplan.
470
471 =cut
472
473 sub api_get_rateplan {
474   my $self = shift;
475   my $rateplan = shift;
476
477   my $get_rateplan = $self->api_call("GET", "/rate_plans/$rateplan");
478   return if $self->api_error;
479
480   return $get_rateplan;
481 }
482
483 =head2 api_get_user
484
485 Gets user info for specific user.
486
487 =cut
488
489 sub api_get_user {
490   my $self = shift;
491   my $user = shift;
492
493   my $get_user = $self->api_call("GET", "/users/$user");
494   return if $self->api_error;
495
496   return $get_user;
497 }
498
499 =head2 api_get_accesspoint
500
501 Gets user info for specific access point.
502
503 =cut
504
505 sub api_get_accesspoint {
506   my $self = shift;
507   my $accesspoint = shift;
508
509   my $get_accesspoint = $self->api_call("GET", "/access_points/$accesspoint");
510   return if $self->api_error;
511
512   return $get_accesspoint;
513 }
514
515 =head2 api_get_host
516
517 Gets user info for specific host.
518
519 =cut
520
521 sub api_get_host {
522   my $self = shift;
523   my $ip = shift;
524
525   my $get_host = $self->api_call("GET", "/hosts/$ip");
526
527   return $self->api_error if $self->api_error;
528
529   return $get_host;
530 }
531
532 =head2 api_create_rateplan
533
534 Creates a rateplan.
535
536 =cut
537
538 sub api_create_rateplan {
539   my ($self, $svc, $rateplan) = @_;
540
541   $self->{'__saisei_error'} = "No downrate listed for service $rateplan" if !$svc->{Hash}->{speed_down};
542   $self->{'__saisei_error'} = "No uprate listed for service $rateplan" if !$svc->{Hash}->{speed_up};
543
544   my $new_rateplan = $self->api_call(
545       "PUT", 
546       "/rate_plans/$rateplan",
547       {
548         'downstream_rate' => $svc->{Hash}->{speed_down},
549         'upstream_rate' => $svc->{Hash}->{speed_up},
550       },
551   ) unless $self->{'__saisei_error'};
552
553   $self->{'__saisei_error'} = "Rate Plan not created"
554     unless ($new_rateplan || $self->{'__saisei_error'});
555
556   return $new_rateplan;
557
558 }
559
560 =head2 api_modify_rateplan
561
562 Modify a new rateplan.
563
564 =cut
565
566 sub api_modify_rateplan {
567   my ($self,$svc,$rateplan_name) = @_;
568
569   # get policy list
570   my $policies = $self->api_get_policies();
571
572   foreach my $policy (@$policies) {
573     my $policyname = $policy->{name};
574     my $rate_multiplier = '';
575     if ($policy->{background}) { $rate_multiplier = ".01"; }
576     my $modified_rateplan = $self->api_call(
577       "PUT", 
578       "/rate_plans/$rateplan_name/partitions/$policyname",
579       {
580         'restricted'      =>  $policy->{assured},         # policy_assured_flag
581         'rate_multiplier' => $rate_multiplier,           # policy_background 0.1
582         'rate'            =>  $policy->{percent_rate}, # policy_percent_rate
583       },
584     );
585
586     $self->{'__saisei_error'} = "Rate Plan not modified after create"
587       unless ($modified_rateplan || $self->{'__saisei_error'}); # should never happen
588     
589   }
590
591   return;
592  
593 }
594
595 =head2 api_modify_existing_rateplan
596
597 Modify a existing rateplan.
598
599 =cut
600
601 sub api_modify_existing_rateplan {
602   my ($self,$svc,$rateplan_name) = @_;
603
604   my $modified_rateplan = $self->api_call(
605     "PUT",
606     "/rate_plans/$rateplan_name",
607     {
608       'downstream_rate' => $svc->{Hash}->{speed_down},
609       'upstream_rate' => $svc->{Hash}->{speed_up},
610     },
611   );
612
613     $self->{'__saisei_error'} = "Rate Plan not modified"
614       unless ($modified_rateplan || $self->{'__saisei_error'}); # should never happen
615
616   return;
617
618 }
619
620 =head2 api_create_user
621
622 Creates a user.
623
624 =cut
625
626 sub api_create_user {
627   my ($self,$user, $description) = @_;
628
629   my $new_user = $self->api_call(
630       "PUT", 
631       "/users/$user",
632       {
633         'description' => $description,
634       },
635   );
636
637   $self->{'__saisei_error'} = "User not created"
638     unless ($new_user || $self->{'__saisei_error'}); # should never happen
639
640   return $new_user;
641
642 }
643
644 =head2 api_create_accesspoint
645
646 Creates a access point.
647
648 =cut
649
650 sub api_create_accesspoint {
651   my ($self,$accesspoint, $upratelimit, $downratelimit) = @_;
652
653   # this has not been tested, but should work, if needed.
654   my $new_accesspoint = $self->api_call(
655       "PUT",
656       "/access_points/$accesspoint",
657       {
658          'downstream_rate_limit' => $downratelimit,
659          'upstream_rate_limit' => $upratelimit,
660       },
661   );
662
663   $self->{'__saisei_error'} = "Access point not created"
664     unless ($new_accesspoint || $self->{'__saisei_error'}); # should never happen
665   return;
666
667 }
668
669 =head2 api_modify_accesspoint
670
671 Modify a new access point.
672
673 =cut
674
675 sub api_modify_accesspoint {
676   my ($self, $accesspoint, $uplink) = @_;
677
678   my $modified_accesspoint = $self->api_call(
679     "PUT",
680     "/access_points/$accesspoint",
681     {
682       'uplink' => $uplink, # name of attached access point
683     },
684   );
685
686   $self->{'__saisei_error'} = "Rate Plan not modified"
687     unless ($modified_accesspoint || $self->{'__saisei_error'}); # should never happen
688
689   return;
690
691 }
692
693 =head2 api_modify_existing_accesspoint
694
695 Modify a existing accesspoint.
696
697 =cut
698
699 sub api_modify_existing_accesspoint {
700   my ($self, $accesspoint, $uplink, $upratelimit, $downratelimit) = @_;
701
702   my $modified_accesspoint = $self->api_call(
703     "PUT",
704     "/access_points/$accesspoint",
705     {
706       'downstream_rate_limit' => $downratelimit,
707       'upstream_rate_limit' => $upratelimit,
708 #      'uplink' => $uplink, # name of attached access point
709     },
710   );
711
712     $self->{'__saisei_error'} = "Access point not modified"
713       unless ($modified_accesspoint || $self->{'__saisei_error'}); # should never happen
714
715   return;
716
717 }
718
719 =head2 api_add_host_to_user
720
721 ties host to user, rateplan and default access point.
722
723 =cut
724
725 sub api_add_host_to_user {
726   my ($self,$user, $rateplan, $ip, $accesspoint) = @_;
727
728   my $new_host = $self->api_call(
729       "PUT", 
730       "/hosts/$ip",
731       {
732         'user'      => $user,
733         'rate_plan' => $rateplan,
734         'access_point' => $accesspoint,
735       },
736   );
737
738   $self->{'__saisei_error'} = "Host not created"
739     unless ($new_host || $self->{'__saisei_error'}); # should never happen
740
741   return $new_host;
742
743 }
744
745 =head2 api_delete_host_to_user
746
747 unties host from user and rateplan.
748 this will set the host entry at Saisei to the default rate plan with the user and access point set to <none>.
749
750 =cut
751
752 sub api_delete_host_to_user {
753   my ($self,$user, $rateplan, $ip) = @_;
754
755   my $default_rate_plan = $self->api_call("GET", '?token=1&select=default_rate_plan');
756     return if $self->api_error;
757   $self->{'__saisei_error'} = "Did not receive a default rate plan"
758     unless $default_rate_plan;
759
760   my $default_rateplan_name = $default_rate_plan->{collection}->[0]->{default_rate_plan}->{link}->{name};
761
762   my $delete_host = $self->api_call(
763       "PUT",
764       "/hosts/$ip",
765       {
766         'user'          => '<none>',
767         'access_point'  => '<none>',
768         'rate_plan'     => $default_rateplan_name,
769       },
770   );
771
772   $self->{'__saisei_error'} = "Host not created"
773     unless ($delete_host || $self->{'__saisei_error'}); # should never happen
774
775   return $delete_host;
776
777 }
778
779 sub process_tower {
780   my ($self, $opt) = @_;
781
782   my $existing_tower_ap;
783   my $tower_name = $opt->{tower_name};
784
785   #check if tower has been set up as an access point.
786   $existing_tower_ap = $self->api_get_accesspoint($tower_name) unless $self->{'__saisei_error'};
787
788   # modify the existing accesspoint if changing tower .
789   $self->api_modify_existing_accesspoint (
790     $tower_name,
791     '', # tower does not have a uplink on sectors.
792     $opt->{tower_uprate_limit},
793     $opt->{tower_downrate_limit},
794   ) if $existing_tower_ap && $opt->{modify_existing};
795
796   #if tower does not exist as an access point create it.
797   $self->api_create_accesspoint(
798       $tower_name,
799       $opt->{tower_uprate_limit},
800       $opt->{tower_downrate_limit}
801   ) unless $existing_tower_ap;
802
803   my $accesspoint = $self->api_get_accesspoint($tower_name);
804
805   return $accesspoint;
806 }
807
808 sub process_sector {
809   my ($self, $opt) = @_;
810
811   my $existing_sector_ap;
812   my $sector_name = $opt->{sector_name};
813
814   #check if sector has been set up as an access point.
815   $existing_sector_ap = $self->api_get_accesspoint($sector_name);
816
817   # modify the existing accesspoint if changing sector .
818   $self->api_modify_existing_accesspoint (
819     $sector_name,
820     $opt->{tower_name},
821     $opt->{sector_uprate_limit},
822     $opt->{sector_downrate_limit},
823   ) if $existing_sector_ap && $opt->{modify_existing};
824
825   #if sector does not exist as an access point create it.
826   $self->api_create_accesspoint(
827     $sector_name,
828     $opt->{sector_uprate_limit},
829     $opt->{sector_downrate_limit},
830   ) unless $existing_sector_ap;
831
832   # Attach newly created sector to it's tower.
833   $self->api_modify_accesspoint($sector_name, $opt->{tower_name}) unless ($self->{'__saisei_error'} || $existing_sector_ap);
834
835   # set access point to existing one or newly created one.
836   my $accesspoint = $existing_sector_ap ? $existing_sector_ap : $self->api_get_accesspoint($sector_name);
837
838   return $accesspoint;
839 }
840
841 sub process_virtual_ap {
842   my ($self, $opt) = @_;
843
844   my $existing_virtual_ap;
845   my $virtual_name = $opt->{virtual_name};
846
847   #check if virtual_ap has been set up as an access point.
848   $existing_virtual_ap = $self->api_get_accesspoint($virtual_name);
849
850   # modify the existing virtual accesspoint if changing it. this should never happen
851   $self->api_modify_existing_accesspoint (
852     $virtual_name,
853     $opt->{sector_name},
854     $opt->{virtual_uprate_limit},
855     $opt->{virtual_downrate_limit},
856   ) if $existing_virtual_ap && $opt->{modify_existing};
857
858   #if virtual ap does not exist as an access point create it.
859   $self->api_create_accesspoint(
860     $virtual_name,
861     $opt->{virtual_uprate_limit},
862     $opt->{virtual_downrate_limit},
863   ) unless $existing_virtual_ap;
864
865 my $update_sector;
866 if ($existing_virtual_ap && (ref $existing_virtual_ap->{collection}->[0]->{uplink} eq "HASH") && ($existing_virtual_ap->{collection}->[0]->{uplink}->{link}->{name} ne $opt->{sector_name})) {
867   $update_sector = 1;
868 }
869
870   # Attach newly created virtual ap to tower sector ap or if sector has changed.
871   $self->api_modify_accesspoint($virtual_name, $opt->{sector_name}) unless ($self->{'__saisei_error'} || ($existing_virtual_ap && !$update_sector));
872
873   # set access point to existing one or newly created one.
874   my $accesspoint = $existing_virtual_ap ? $existing_virtual_ap : $self->api_get_accesspoint($virtual_name);
875
876   return $accesspoint;
877 }
878
879 sub export_provisioned_services {
880   my $job = shift;
881   my $param = thaw(decode_base64(shift));
882
883   my $part_export = FS::Record::qsearchs('part_export', { 'exportnum' => $param->{export_provisioned_services_exportnum}, } )
884   or die "unknown exportnum $param->{export_provisioned_services_exportnum}";
885   bless $part_export;
886
887   my @svcparts = FS::Record::qsearch({
888     'table' => 'export_svc',
889     'addl_from' => 'LEFT JOIN part_svc USING ( svcpart  ) ',
890     'hashref'   => { 'exportnum' => $param->{export_provisioned_services_exportnum}, },
891   });
892   my $part_count = scalar @svcparts;
893
894   my $parts = join "', '", map { $_->{Hash}->{svcpart} } @svcparts;
895
896   my @svcs = FS::Record::qsearch({
897     'table' => 'cust_svc',
898     'addl_from' => 'LEFT JOIN svc_broadband USING ( svcnum  ) ',
899     'extra_sql' => " WHERE svcpart in ('".$parts."')",
900   }) unless !$parts;
901
902   my $svc_count = scalar @svcs;
903
904   my %status = {};
905   for (my $c=1; $c <=100; $c=$c+1) { $status{int($svc_count * ($c/100))} = $c; }
906
907   my $process_count=0;
908   foreach my $svc (@svcs) {
909     if ($status{$process_count}) { my $s = $status{$process_count}; $job->update_statustext($s); }
910     ## check if service exists as host if not export it.
911     my $host = api_get_host($part_export, $svc->{Hash}->{ip_addr});
912     die $host->{message} if $host->{message};
913     warn "Exporting service ".$svc->{Hash}->{ip_addr}."\n" if ($part_export->option('debug'));
914     my $export_error = _export_insert($part_export,$svc) unless $host->{collection};
915     die $export_error if $export_error;
916     $process_count++;
917   }
918
919   return;
920
921 }
922
923 =head1 SEE ALSO
924
925 L<FS::part_export>
926
927 =cut
928
929 1;