RT# 78356 - created import format for broadband service
[freeside.git] / FS / FS / cust_pkg / Import.pm
1 package FS::cust_pkg::Import;
2
3 use strict;
4 use vars qw( $DEBUG ); #$conf );
5 use Data::Dumper;
6 use FS::Misc::DateTime qw( parse_datetime );
7 use FS::Record qw( qsearchs );
8 use FS::cust_pkg;
9 use FS::cust_main;
10 use FS::svc_acct;
11 use FS::svc_external;
12 use FS::svc_phone;
13 use FS::svc_domain;
14
15 $DEBUG = 0;
16
17 #install_callback FS::UID sub {
18 #  $conf = new FS::Conf;
19 #};
20
21 =head1 NAME
22
23 FS::cust_pkg::Import - Batch customer importing
24
25 =head1 SYNOPSIS
26
27   use FS::cust_pkg::Import;
28
29   #import
30   FS::cust_pkg::Import::batch_import( {
31     file      => $file,      #filename
32     type      => $type,      #csv or xls
33     format    => $format,    #extended, extended-plus_company, svc_external,
34                              # or svc_external_svc_phone
35     agentnum  => $agentnum,
36     job       => $job,       #optional job queue job, for progressbar updates
37     pkgbatch  => $pkgbatch, #optional batch unique identifier
38   } );
39   die $error if $error;
40
41   #ajax helper
42   use FS::UI::Web::JSRPC;
43   my $server =
44     new FS::UI::Web::JSRPC 'FS::cust_pkg::Import::process_batch_import', $cgi;
45   print $server->process;
46
47 =head1 DESCRIPTION
48
49 Batch package importing.
50
51 =head1 SUBROUTINES
52
53 =item process_batch_import
54
55 Load a batch import as a queued JSRPC job
56
57 =cut
58
59 sub process_batch_import {
60   my $job = shift;
61   my $param = shift;
62   warn Dumper($param) if $DEBUG;
63   
64   my $files = $param->{'uploaded_files'}
65     or die "No files provided.\n";
66
67   my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
68
69   my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
70   my $file = $dir. $files{'file'};
71
72   my $type;
73   if ( $file =~ /\.(\w+)$/i ) {
74     $type = lc($1);
75   } else {
76     #or error out???
77     warn "can't parse file type from filename $file; defaulting to CSV";
78     $type = 'csv';
79   }
80
81   my $error =
82     FS::cust_pkg::Import::batch_import( {
83       job      => $job,
84       file     => $file,
85       type     => $type,
86       'params' => { pkgbatch => $param->{pkgbatch} },
87       agentnum => $param->{'agentnum'},
88       'format' => $param->{'format'},
89     } );
90
91   unlink $file;
92
93   die "$error\n" if $error;
94
95 }
96
97 =item batch_import
98
99 =cut
100
101 my %formatfields = (
102   'default'      => [],
103   'all_dates'    => [],
104   'svc_acct'     => [qw( username _password domsvc )],
105   'svc_broadband' => [qw( ip_addr description routernum blocknum sectornum speed_up speed_down )],
106   'svc_phone'    => [qw( countrycode phonenum sip_password pin )],
107   'svc_external' => [qw( id title )],
108   'location'     => [qw( address1 address2 city state zip country )],
109   'quan_price'   => [qw( quantity setup_fee recur_fee invoice_details )],
110 );
111
112 sub _formatfields {
113   \%formatfields;
114 }
115
116 my %import_options = (
117   'table'         => 'cust_pkg',
118
119   'preinsert_callback'  => sub {
120     my($record, $param) = @_;
121
122     my @location_params = grep { /^location\./ && length($param->{$_}) }
123                             keys %$param;
124     if (@location_params) {
125       my $cust_location = FS::cust_location->new({
126           'custnum' => $record->custnum,
127       });
128       foreach my $p (@location_params) {
129         $p =~ /^location.(\w+)$/;
130         $cust_location->set($1, $param->{$p});
131       }
132
133       my $error = $cust_location->find_or_insert; # this avoids duplicates
134       return "error creating location: $error" if $error;
135       $record->set('locationnum', $cust_location->locationnum);
136     }
137
138     $record->quantity( $param->{'quan_price.quantity'} )
139       if $param->{'quan_price.quantity'} > 0;
140     
141     my $s = $param->{'quan_price.setup_fee'};
142     my $r = $param->{'quan_price.recur_fee'};
143     my $part_pkg = $record->part_pkg;
144     if (    ( length($s) && $s != $part_pkg->option('setup_fee') )
145          or ( length($r) && $r != $part_pkg->option('recur_fee') )
146        )
147     {
148
149       local($FS::part_pkg::skip_pkg_svc_hack) = 1;
150
151       my $custom_part_pkg = $part_pkg->clone;
152       $custom_part_pkg->disabled('Y');
153       my %options = $part_pkg->options;
154       $options{'setup_fee'} = $s if length($s);
155       $options{'recur_fee'} = $r if length($r);
156       my $error = $custom_part_pkg->insert( options=>\%options );
157       return "error customizing package: $error" if $error;
158
159       #not ->pkg_svc, we want to ignore links and clone the actual package def
160       foreach my $pkg_svc ( $part_pkg->_pkg_svc ) {
161         my $c_pkg_svc = new FS::pkg_svc { $pkg_svc->hash };
162         $c_pkg_svc->pkgsvcnum('');
163         $c_pkg_svc->pkgpart( $custom_part_pkg->pkgpart );
164         my $error = $c_pkg_svc->insert;
165         return "error customizing package: $error" if $error;
166       }
167
168       $record->pkgpart( $custom_part_pkg->pkgpart );
169     }
170
171
172     '';
173   },
174
175   'postinsert_callback' => sub {
176     my( $record, $param ) = @_;
177
178     if ( $param->{'quan_price.invoice_details'} ) {
179
180       my $weight = 0;
181       foreach my $detail (split(/\|/, $param->{'quan_price.invoice_details'})) {
182
183         my $cust_pkg_detail = new FS::cust_pkg_detail {
184           'pkgnum'     => $record->pkgnum,
185           'detail'     => $detail,
186           'detailtype' => 'I',
187           'weight'     => $weight++,
188         };
189
190         my $error = $cust_pkg_detail->insert;
191         return "error inserting invoice detail: $error" if $error;
192
193       }
194
195     }
196
197     my $formatfields = _formatfields;
198     foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
199
200       my $ff = $formatfields->{$svc_x};
201
202       if ( grep $param->{"$svc_x.$_"}, @$ff ) {
203
204         my $svc = "FS::$svc_x"->new( {
205           'pkgnum'  => $record->pkgnum,
206           'svcpart' => $record->part_pkg->svcpart($svc_x),
207           map { $_ => $param->{"$svc_x.$_"} } @$ff
208         } );
209
210         #this whole thing should be turned into a callback or config to turn on
211         if ( $svc_x eq 'svc_acct' && $svc->username =~ /\@/ ) {
212           my($username, $domain) = split(/\@/, $svc->username);
213           my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } )
214                          || new FS::svc_domain { 'svcpart' => 1,
215                                                  'domain'  => $domain, };
216           unless ( $svc_domain->svcnum ) {
217             my $error = $svc_domain->insert;
218             return "error auto-inserting domain: $error" if $error;
219           }
220           $svc->username($username);
221           $svc->domsvc($svc_domain->svcnum);
222         }
223
224         my $error = $svc->insert;
225         return "error inserting service: $error" if $error;
226       }
227
228     }
229
230     return ''; #no error
231
232   },
233 );
234
235 sub _import_options {
236   \%import_options;
237 }
238
239 sub batch_import {
240   my $opt = shift;
241
242   my $iopt = _import_options;
243   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
244
245   my $agentnum  = delete $opt->{agentnum}; # i like closures (delete though?)
246
247   my $format = delete $opt->{'format'};
248   my @fields = ();
249
250   if ( $format =~ /^(.*)-agent_custid(-agent_pkgid)?$/ ) {
251     $format = $1;
252     my $agent_pkgid = $2;
253     @fields = (
254       sub {
255         my( $self, $value ) = @_; # $conf, $param
256         my $cust_main = qsearchs('cust_main', {
257           'agentnum'     => $agentnum,
258           'agent_custid' => $value,
259         });
260         $self->custnum($cust_main->custnum) if $cust_main;
261       },
262     );
263     push @fields, 'agent_pkgid' if $agent_pkgid;
264   } else {
265     @fields = ( 'custnum' );
266   }
267
268   if ( $format =~ /^(.*)-locationnum$/ ) {
269     $format = $1;
270     push @fields, 'locationnum';
271   }
272
273   if ( $format =~ /^bulk_(.*)$/ ) {
274
275     $format = $1;
276
277     $opt->{'postinsert_callback'} = sub {
278       my( $record, $param ) = @_;
279
280       my $formatfields = _formatfields;
281       foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
282
283         my $ff = $formatfields->{$svc_x};
284
285         if ( grep $param->{"$svc_x.$_"}, @$ff ) {
286
287           $param->{'svc_phone.phonenum'} =~ /^\s*(\d+)\s*\-\s*(\d+)\s*$/
288             or return 'Enter a phone number range, with dash as the separator';
289           my($start, $end) = ($1, $2);
290           if ( length($end) < length($start) ) {
291             $end = substr($start, 0, length($start) - length($end) ). $end;
292           }
293
294           foreach my $phonenum ( "$start" .. "$end" ) {
295
296             my $svc = "FS::$svc_x"->new( {
297               'pkgnum'  => $record->pkgnum,
298               'svcpart' => $record->part_pkg->svcpart($svc_x),
299               map { $_ => $param->{"$svc_x.$_"} } @$ff
300             } );
301
302             $svc->phonenum($phonenum);
303             #$svc->set_default_and_fixed;
304             my $error = $svc->insert;
305             return "error inserting service: $error" if $error;
306
307           }
308
309         }
310
311       }
312
313       return ''; #no error
314
315     };
316
317   }
318
319   push @fields, ( 'pkgpart', 'discountnum' );
320
321   my @date_fields = ();
322   if ( $format =~ /all_dates/ ) {
323     @date_fields = qw(
324       order_date
325       start_date setup bill last_bill susp adjourn
326       resume
327       cancel expire
328       contract_end dundate
329     );
330   } else {
331     @date_fields = qw(
332       start_date setup bill last_bill susp adjourn
333       cancel expire
334     );
335   }
336
337   foreach my $field (@date_fields) { 
338     push @fields, sub {
339       my( $self, $value ) = @_; # $conf, $param
340       #->$field has undesirable effects
341       $self->set($field, parse_datetime($value) ); #$field closure
342     };
343   }
344
345   my @formats = split /-/, $format;
346   foreach my $f (@formats){
347
348     my $formatfields = _formatfields();
349     die "unknown format $format" unless $formatfields->{$f};
350
351     foreach my $field ( @{ $formatfields->{$f} } ) {
352
353       push @fields, sub {
354         my( $self, $value, $conf, $param ) = @_;
355         $param->{"$f.$field"} = $value;
356       };
357
358     }
359   }
360
361   $opt->{'fields'} = \@fields;
362
363   FS::Record::batch_import( $opt );
364
365 }
366
367 =head1 BUGS
368
369 Not enough documentation.
370
371 =head1 SEE ALSO
372
373 L<FS::cust_main>, L<FS::cust_pkg>,
374 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
375
376 =cut
377
378 1;