f9cf1cb5c26bc1c092d427cedb15a59c233f99a9
[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 Storable qw(thaw);
6 use Data::Dumper;
7 use MIME::Base64;
8 use FS::Misc::DateTime qw( parse_datetime );
9 use FS::Record qw( qsearchs );
10 use FS::cust_pkg;
11 use FS::cust_main;
12 use FS::svc_acct;
13 use FS::svc_external;
14 use FS::svc_phone;
15 use FS::svc_domain;
16
17 $DEBUG = 0;
18
19 #install_callback FS::UID sub {
20 #  $conf = new FS::Conf;
21 #};
22
23 =head1 NAME
24
25 FS::cust_pkg::Import - Batch customer importing
26
27 =head1 SYNOPSIS
28
29   use FS::cust_pkg::Import;
30
31   #import
32   FS::cust_pkg::Import::batch_import( {
33     file      => $file,      #filename
34     type      => $type,      #csv or xls
35     format    => $format,    #extended, extended-plus_company, svc_external,
36                              # or svc_external_svc_phone
37     agentnum  => $agentnum,
38     job       => $job,       #optional job queue job, for progressbar updates
39     pkgbatch  => $pkgbatch, #optional batch unique identifier
40   } );
41   die $error if $error;
42
43   #ajax helper
44   use FS::UI::Web::JSRPC;
45   my $server =
46     new FS::UI::Web::JSRPC 'FS::cust_pkg::Import::process_batch_import', $cgi;
47   print $server->process;
48
49 =head1 DESCRIPTION
50
51 Batch package importing.
52
53 =head1 SUBROUTINES
54
55 =item process_batch_import
56
57 Load a batch import as a queued JSRPC job
58
59 =cut
60
61 sub process_batch_import {
62   my $job = shift;
63
64   my $param = thaw(decode_base64(shift));
65   warn Dumper($param) if $DEBUG;
66   
67   my $files = $param->{'uploaded_files'}
68     or die "No files provided.\n";
69
70   my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
71
72   my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
73   my $file = $dir. $files{'file'};
74
75   my $type;
76   if ( $file =~ /\.(\w+)$/i ) {
77     $type = lc($1);
78   } else {
79     #or error out???
80     warn "can't parse file type from filename $file; defaulting to CSV";
81     $type = 'csv';
82   }
83
84   my $error =
85     FS::cust_pkg::Import::batch_import( {
86       job      => $job,
87       file     => $file,
88       type     => $type,
89       'params' => { pkgbatch => $param->{pkgbatch} },
90       agentnum => $param->{'agentnum'},
91       'format' => $param->{'format'},
92     } );
93
94   unlink $file;
95
96   die "$error\n" if $error;
97
98 }
99
100 =item batch_import
101
102 =cut
103
104 my %formatfields = (
105   'default'      => [],
106   'svc_acct'     => [qw( username _password domsvc )],
107   'svc_phone'    => [qw( countrycode phonenum sip_password pin )],
108   'svc_external' => [qw( id title )],
109   'location'     => [qw( address1 address2 city state zip country )],
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     my @location_params = grep /^location\./, keys %$param;
122     if (@location_params) {
123       my $cust_location = FS::cust_location->new({
124           'custnum' => $record->custnum,
125       });
126       foreach my $p (@location_params) {
127         $p =~ /^location.(\w+)$/;
128         $cust_location->set($1, $param->{$p});
129       }
130
131       my $error = $cust_location->find_or_insert; # this avoids duplicates
132       return "error creating location: $error" if $error;
133       $record->set('locationnum', $cust_location->locationnum);
134     }
135     '';
136   },
137
138   'postinsert_callback' => sub {
139     my( $record, $param ) = @_;
140
141     my $formatfields = _formatfields;
142     foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
143
144       my $ff = $formatfields->{$svc_x};
145
146       if ( grep $param->{"$svc_x.$_"}, @$ff ) {
147         my $svc = "FS::$svc_x"->new( {
148           'pkgnum'  => $record->pkgnum,
149           'svcpart' => $record->part_pkg->svcpart($svc_x),
150           map { $_ => $param->{"$svc_x.$_"} } @$ff
151         } );
152
153         #this whole thing should be turned into a callback or config to turn on
154         if ( $svc_x eq 'svc_acct' && $svc->username =~ /\@/ ) {
155           my($username, $domain) = split(/\@/, $svc->username);
156           my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } )
157                          || new FS::svc_domain { 'svcpart' => 1,
158                                                  'domain'  => $domain, };
159           unless ( $svc_domain->svcnum ) {
160             my $error = $svc_domain->insert;
161             return "error auto-inserting domain: $error" if $error;
162           }
163           $svc->username($username);
164           $svc->domsvc($svc_domain->svcnum);
165         }
166
167         my $error = $svc->insert;
168         return "error inserting service: $error" if $error;
169       }
170
171     }
172
173     return ''; #no error
174
175   },
176 );
177
178 sub _import_options {
179   \%import_options;
180 }
181
182 sub batch_import {
183   my $opt = shift;
184
185   my $iopt = _import_options;
186   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
187
188   my $agentnum  = delete $opt->{agentnum}; # i like closures (delete though?)
189
190   my $format = delete $opt->{'format'};
191   my @fields = ();
192
193   if ( $format =~ /^(.*)-agent_custid(-agent_pkgid)?$/ ) {
194     $format = $1;
195     my $agent_pkgid = $2;
196     @fields = (
197       sub {
198         my( $self, $value ) = @_; # $conf, $param
199         my $cust_main = qsearchs('cust_main', {
200           'agentnum'     => $agentnum,
201           'agent_custid' => $value,
202         });
203         $self->custnum($cust_main->custnum) if $cust_main;
204       },
205     );
206     push @fields, 'agent_pkgid' if $agent_pkgid;
207   } else {
208     @fields = ( 'custnum' );
209   }
210
211   push @fields, ( 'pkgpart', 'discountnum' );
212
213   my @date_fields = ();
214   if ( $format =~ /all_dates/ ) {
215     @date_fields = qw(
216       order_date
217       start_date setup bill last_bill susp adjourn
218       resume
219       cancel expire
220       contract_end dundate
221     );
222   } else {
223     @date_fields = qw(
224       start_date setup bill last_bill susp adjourn
225       cancel expire
226     );
227   }
228
229   foreach my $field (@date_fields) { 
230     push @fields, sub {
231       my( $self, $value ) = @_; # $conf, $param
232       #->$field has undesirable effects
233       $self->set($field, parse_datetime($value) ); #$field closure
234     };
235   }
236
237   my $formatfields = _formatfields();
238
239   die "unknown format $format" unless $formatfields->{$format};
240
241   foreach my $field ( @{ $formatfields->{$format} } ) {
242
243     push @fields, sub {
244       my( $self, $value, $conf, $param ) = @_;
245       $param->{"$format.$field"} = $value;
246     };
247
248   }
249
250   $opt->{'fields'} = \@fields;
251
252   FS::Record::batch_import( $opt );
253
254 }
255
256 =for comment
257
258     my $billtime = time;
259     my %cust_pkg = ( pkgpart => $pkgpart );
260     my %svc_x = ();
261     foreach my $field ( @fields ) {
262
263       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
264
265         #$cust_pkg{$1} = parse_datetime( shift @$columns );
266         if ( $1 eq 'pkgpart' ) {
267           $cust_pkg{$1} = shift @columns;
268         } elsif ( $1 eq 'setup' ) {
269           $billtime = parse_datetime(shift @columns);
270         } else {
271           $cust_pkg{$1} = parse_datetime( shift @columns );
272         } 
273
274       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
275
276         $svc_x{$1} = shift @columns;
277
278       } elsif ( $field =~ /^svc_external\.(id|title)$/ ) {
279
280         $svc_x{$1} = shift @columns;
281
282       } elsif ( $field =~ /^svc_phone\.(countrycode|phonenum|sip_password|pin)$/ ) {
283         $svc_x{$1} = shift @columns;
284        
285       } else {
286
287         #refnum interception
288         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
289
290           my $referral = $columns[0];
291           my %hash = ( 'referral' => $referral,
292                        'agentnum' => $agentnum,
293                        'disabled' => '',
294                      );
295
296           my $part_referral = qsearchs('part_referral', \%hash )
297                               || new FS::part_referral \%hash;
298
299           unless ( $part_referral->refnum ) {
300             my $error = $part_referral->insert;
301             if ( $error ) {
302               $dbh->rollback if $oldAutoCommit;
303               return "can't auto-insert advertising source: $referral: $error";
304             }
305           }
306
307           $columns[0] = $part_referral->refnum;
308         }
309
310         my $value = shift @columns;
311         $cust_main{$field} = $value if length($value);
312       }
313     }
314
315     $cust_main{'payby'} = 'CARD'
316       if defined $cust_main{'payinfo'}
317       && length  $cust_main{'payinfo'};
318
319     my $invoicing_list = $cust_main{'invoicing_list'}
320                            ? [ delete $cust_main{'invoicing_list'} ]
321                            : [];
322
323     my $cust_main = new FS::cust_main ( \%cust_main );
324
325     use Tie::RefHash;
326     tie my %hash, 'Tie::RefHash'; #this part is important
327
328     if ( $cust_pkg{'pkgpart'} ) {
329       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
330
331       my @svc_x = ();
332       my $svcdb = '';
333       if ( $svc_x{'username'} ) {
334         $svcdb = 'svc_acct';
335       } elsif ( $svc_x{'id'} || $svc_x{'title'} ) {
336         $svcdb = 'svc_external';
337       }
338
339       my $svc_phone = '';
340       if ( $svc_x{'countrycode'} || $svc_x{'phonenum'} ) {
341         $svc_phone = FS::svc_phone->new( {
342           map { $_ => delete($svc_x{$_}) }
343               qw( countrycode phonenum sip_password pin)
344         } );
345       }
346
347       if ( $svcdb || $svc_phone ) {
348         my $part_pkg = $cust_pkg->part_pkg;
349         unless ( $part_pkg ) {
350           $dbh->rollback if $oldAutoCommit;
351           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
352         } 
353         if ( $svcdb ) {
354           $svc_x{svcpart} = $part_pkg->svcpart_unique_svcdb( $svcdb );
355           my $class = "FS::$svcdb";
356           push @svc_x, $class->new( \%svc_x );
357         }
358         if ( $svc_phone ) {
359           $svc_phone->svcpart( $part_pkg->svcpart_unique_svcdb('svc_phone') );
360           push @svc_x, $svc_phone;
361         }
362       }
363
364       $hash{$cust_pkg} = \@svc_x;
365     }
366
367     my $error = $cust_main->insert( \%hash, $invoicing_list );
368
369     if ( $error ) {
370       $dbh->rollback if $oldAutoCommit;
371       return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
372     }
373
374     if ( $format eq 'simple' ) {
375
376       #false laziness w/bill.cgi
377       $error = $cust_main->bill( 'time' => $billtime );
378       if ( $error ) {
379         $dbh->rollback if $oldAutoCommit;
380         return "can't bill customer for $line: $error";
381       }
382   
383       $error = $cust_main->apply_payments_and_credits;
384       if ( $error ) {
385         $dbh->rollback if $oldAutoCommit;
386         return "can't bill customer for $line: $error";
387       }
388
389       $error = $cust_main->collect();
390       if ( $error ) {
391         $dbh->rollback if $oldAutoCommit;
392         return "can't collect customer for $line: $error";
393       }
394
395     }
396
397     $row++;
398
399     if ( $job && time - $min_sec > $last ) { #progress bar
400       $job->update_statustext( int(100 * $row / $count) );
401       $last = time;
402     }
403
404   }
405
406   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
407
408   return "Empty file!" unless $row;
409
410   ''; #no error
411
412 }
413
414 =head1 BUGS
415
416 Not enough documentation.
417
418 =head1 SEE ALSO
419
420 L<FS::cust_main>, L<FS::cust_pkg>,
421 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
422
423 =cut
424
425 1;