fix import of 0 custom price, RT#76992
[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_phone'    => [qw( countrycode phonenum sip_password pin )],
106   'svc_external' => [qw( id title )],
107   'location'     => [qw( address1 address2 city state zip country )],
108   'quan_price'   => [qw( quantity setup_fee recur_fee invoice_details )],
109 );
110
111 sub _formatfields {
112   \%formatfields;
113 }
114
115 my %import_options = (
116   'table'         => 'cust_pkg',
117
118   'preinsert_callback'  => sub {
119     my($record, $param) = @_;
120
121     my @location_params = grep { /^location\./ && length($param->{$_}) }
122                             keys %$param;
123     if (@location_params) {
124 warn join('-', @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       my $custom_part_pkg = $part_pkg->clone;
149       $custom_part_pkg->disabled('Y');
150       my %options = $part_pkg->options;
151       $options{'setup_fee'} = $s if length($s);
152       $options{'recur_fee'} = $r if length($r);
153       my $error = $custom_part_pkg->insert( options=>\%options );
154       return "error customizing package: $error" if $error;
155       $record->pkgpart( $custom_part_pkg->pkgpart );
156     }
157
158
159     '';
160   },
161
162   'postinsert_callback' => sub {
163     my( $record, $param ) = @_;
164
165     if ( $param->{'quan_price.invoice_details'} ) {
166
167       my $weight = 0;
168       foreach my $detail (split(/\|/, $param->{'quan_price.invoice_details'})) {
169
170         my $cust_pkg_detail = new FS::cust_pkg_detail {
171           'pkgnum'     => $record->pkgnum,
172           'detail'     => $detail,
173           'detailtype' => 'I',
174           'weight'     => $weight++,
175         };
176
177         my $error = $cust_pkg_detail->insert;
178         return "error inserting invoice detail: $error" if $error;
179
180       }
181
182     }
183
184     my $formatfields = _formatfields;
185     foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
186
187       my $ff = $formatfields->{$svc_x};
188
189       if ( grep $param->{"$svc_x.$_"}, @$ff ) {
190         my $svc = "FS::$svc_x"->new( {
191           'pkgnum'  => $record->pkgnum,
192           'svcpart' => $record->part_pkg->svcpart($svc_x),
193           map { $_ => $param->{"$svc_x.$_"} } @$ff
194         } );
195
196         #this whole thing should be turned into a callback or config to turn on
197         if ( $svc_x eq 'svc_acct' && $svc->username =~ /\@/ ) {
198           my($username, $domain) = split(/\@/, $svc->username);
199           my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } )
200                          || new FS::svc_domain { 'svcpart' => 1,
201                                                  'domain'  => $domain, };
202           unless ( $svc_domain->svcnum ) {
203             my $error = $svc_domain->insert;
204             return "error auto-inserting domain: $error" if $error;
205           }
206           $svc->username($username);
207           $svc->domsvc($svc_domain->svcnum);
208         }
209
210         my $error = $svc->insert;
211         return "error inserting service: $error" if $error;
212       }
213
214     }
215
216     return ''; #no error
217
218   },
219 );
220
221 sub _import_options {
222   \%import_options;
223 }
224
225 sub batch_import {
226   my $opt = shift;
227
228   my $iopt = _import_options;
229   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
230
231   my $agentnum  = delete $opt->{agentnum}; # i like closures (delete though?)
232
233   my $format = delete $opt->{'format'};
234   my @fields = ();
235
236   if ( $format =~ /^(.*)-agent_custid(-agent_pkgid)?$/ ) {
237     $format = $1;
238     my $agent_pkgid = $2;
239     @fields = (
240       sub {
241         my( $self, $value ) = @_; # $conf, $param
242         my $cust_main = qsearchs('cust_main', {
243           'agentnum'     => $agentnum,
244           'agent_custid' => $value,
245         });
246         $self->custnum($cust_main->custnum) if $cust_main;
247       },
248     );
249     push @fields, 'agent_pkgid' if $agent_pkgid;
250   } else {
251     @fields = ( 'custnum' );
252   }
253
254   if ( $format =~ /^(.*)-locationnum$/ ) {
255     $format = $1;
256     push @fields, 'locationnum';
257   }
258
259   if ( $format =~ /^bulk_(.*)$/ ) {
260
261     $format = $1;
262
263     $opt->{'postinsert_callback'} = sub {
264       my( $record, $param ) = @_;
265
266       my $formatfields = _formatfields;
267       foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
268
269         my $ff = $formatfields->{$svc_x};
270
271         if ( grep $param->{"$svc_x.$_"}, @$ff ) {
272
273           $param->{'svc_phone.phonenum'} =~ /^\s*(\d+)\s*\-\s*(\d+)\s*$/
274             or return 'Enter a phone number range, with dash as the separator';
275           my($start, $end) = ($1, $2);
276           if ( length($end) < length($start) ) {
277             $end = substr($start, 0, length($start) - length($end) ). $end;
278           }
279
280           foreach my $phonenum ( "$start" .. "$end" ) {
281
282             my $svc = "FS::$svc_x"->new( {
283               'pkgnum'  => $record->pkgnum,
284               'svcpart' => $record->part_pkg->svcpart($svc_x),
285               map { $_ => $param->{"$svc_x.$_"} } @$ff
286             } );
287
288             $svc->phonenum($phonenum);
289             #$svc->set_default_and_fixed;
290             my $error = $svc->insert;
291             return "error inserting service: $error" if $error;
292
293           }
294
295         }
296
297       }
298
299       return ''; #no error
300
301     };
302
303   }
304
305   push @fields, ( 'pkgpart', 'discountnum' );
306
307   my @date_fields = ();
308   if ( $format =~ /all_dates/ ) {
309     @date_fields = qw(
310       order_date
311       start_date setup bill last_bill susp adjourn
312       resume
313       cancel expire
314       contract_end dundate
315     );
316   } else {
317     @date_fields = qw(
318       start_date setup bill last_bill susp adjourn
319       cancel expire
320     );
321   }
322
323   foreach my $field (@date_fields) { 
324     push @fields, sub {
325       my( $self, $value ) = @_; # $conf, $param
326       #->$field has undesirable effects
327       $self->set($field, parse_datetime($value) ); #$field closure
328     };
329   }
330
331   my @formats = split /-/, $format;
332   foreach my $f (@formats){
333
334     my $formatfields = _formatfields();
335     die "unknown format $format" unless $formatfields->{$f};
336
337     foreach my $field ( @{ $formatfields->{$f} } ) {
338
339       push @fields, sub {
340         my( $self, $value, $conf, $param ) = @_;
341         $param->{"$f.$field"} = $value;
342       };
343
344     }
345   }
346
347   $opt->{'fields'} = \@fields;
348
349   FS::Record::batch_import( $opt );
350
351 }
352
353 =head1 BUGS
354
355 Not enough documentation.
356
357 =head1 SEE ALSO
358
359 L<FS::cust_main>, L<FS::cust_pkg>,
360 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
361
362 =cut
363
364 1;