add anniversary date, RT#18631
[freeside.git] / FS / FS / cust_main / Import.pm
1 package FS::cust_main::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 File::Slurp qw( slurp );
9 use FS::Misc::DateTime qw( parse_datetime );
10 use FS::UID qw( dbh );
11 use FS::Record qw( qsearchs );
12 use FS::cust_main;
13 use FS::svc_acct;
14 use FS::svc_external;
15 use FS::svc_phone;
16 use FS::svc_hardware;
17 use FS::part_referral;
18
19 $DEBUG = 0;
20
21 install_callback FS::UID sub {
22   $conf = new FS::Conf;
23 };
24
25 =head1 NAME
26
27 FS::cust_main::Import - Batch customer importing
28
29 =head1 SYNOPSIS
30
31   use FS::cust_main::Import;
32
33   #import
34   FS::cust_main::Import::batch_import( {
35     file      => $file,      #filename
36     type      => $type,      #csv or xls
37     format    => $format,    #extended, extended-plus_company, svc_external,
38                              #extended-plus_company_and_options
39                              #extended-plus_options, or svc_external_svc_phone
40     agentnum  => $agentnum,
41     refnum    => $refnum,
42     pkgpart   => $pkgpart,
43     job       => $job,       #optional job queue job, for progressbar updates
44     custbatch => $custbatch, #optional batch unique identifier
45   } );
46   die $error if $error;
47
48   #ajax helper
49   use FS::UI::Web::JSRPC;
50   my $server =
51     new FS::UI::Web::JSRPC 'FS::cust_main::Import::process_batch_import', $cgi;
52   print $server->process;
53
54 =head1 DESCRIPTION
55
56 Batch customer importing.
57
58 =head1 SUBROUTINES
59
60 =item process_batch_import
61
62 Load a batch import as a queued JSRPC job
63
64 =cut
65
66 sub process_batch_import {
67   my $job = shift;
68
69   my $param = thaw(decode_base64(shift));
70   warn Dumper($param) if $DEBUG;
71   
72   my $files = $param->{'uploaded_files'}
73     or die "No files provided.\n";
74
75   my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
76
77   my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
78   my $file = $dir. $files{'file'};
79
80   my $type;
81   if ( $file =~ /\.(\w+)$/i ) {
82     $type = lc($1);
83   } else {
84     #or error out???
85     warn "can't parse file type from filename $file; defaulting to CSV";
86     $type = 'csv';
87   }
88
89   my $error =
90     FS::cust_main::Import::batch_import( {
91       job       => $job,
92       file      => $file,
93       type      => $type,
94       custbatch => $param->{custbatch},
95       agentnum  => $param->{'agentnum'},
96       refnum    => $param->{'refnum'},
97       pkgpart   => $param->{'pkgpart'},
98       #'fields'  => [qw( cust_pkg.setup dayphone first last address1 address2
99       #                 city state zip comments                          )],
100       'format'  => $param->{'format'},
101     } );
102
103   unlink $file;
104
105   die "$error\n" if $error;
106
107 }
108
109 =item batch_import
110
111 =cut
112
113
114 #some false laziness w/cdr.pm now
115 sub batch_import {
116   my $param = shift;
117
118   my $job       = $param->{job};
119
120   my $filename  = $param->{file};
121   my $type      = $param->{type} || 'csv';
122
123   my $custbatch = $param->{custbatch};
124
125   my $agentnum  = $param->{agentnum};
126   my $refnum    = $param->{refnum};
127   my $pkgpart   = $param->{pkgpart};
128
129   my $format    = $param->{'format'};
130
131   my @fields;
132   my $payby;
133   if ( $format eq 'simple' ) {
134     @fields = qw( cust_pkg.setup dayphone first last
135                   address1 address2 city state zip comments );
136     $payby = 'BILL';
137   } elsif ( $format eq 'extended' ) {
138     @fields = qw( agent_custid refnum
139                   last first address1 address2 city state zip country
140                   daytime night
141                   ship_last ship_first ship_address1 ship_address2
142                   ship_city ship_state ship_zip ship_country
143                   payinfo paycvv paydate
144                   invoicing_list
145                   cust_pkg.pkgpart
146                   svc_acct.username svc_acct._password 
147                 );
148     $payby = 'BILL';
149  } elsif ( $format eq 'extended-plus_options' ) {
150     @fields = qw( agent_custid refnum
151                   last first address1 address2 city state zip country
152                   daytime night
153                   ship_last ship_first ship_company ship_address1 ship_address2
154                   ship_city ship_state ship_zip ship_country
155                   payinfo paycvv paydate
156                   invoicing_list
157                   cust_pkg.pkgpart
158                   svc_acct.username svc_acct._password 
159                   customer_options
160                 );
161     $payby = 'BILL';
162  } elsif ( $format eq 'extended-plus_company' ) {
163     @fields = qw( agent_custid refnum
164                   last first company address1 address2 city state zip country
165                   daytime night
166                   ship_last ship_first ship_company ship_address1 ship_address2
167                   ship_city ship_state ship_zip ship_country
168                   payinfo paycvv paydate
169                   invoicing_list
170                   cust_pkg.pkgpart
171                   svc_acct.username svc_acct._password 
172                 );
173     $payby = 'BILL';
174  } elsif ( $format eq 'extended-plus_company_and_options' ) {
175     @fields = qw( agent_custid refnum
176                   last first company address1 address2 city state zip country
177                   daytime night
178                   ship_last ship_first ship_company ship_address1 ship_address2
179                   ship_city ship_state ship_zip ship_country
180                   payinfo paycvv paydate
181                   invoicing_list
182                   cust_pkg.pkgpart
183                   svc_acct.username svc_acct._password 
184                   customer_options
185                 );
186     $payby = 'BILL';
187  } elsif ( $format =~ /^svc_external/ ) {
188     @fields = qw( agent_custid refnum
189                   last first company address1 address2 city state zip country
190                   daytime night
191                   ship_last ship_first ship_company ship_address1 ship_address2
192                   ship_city ship_state ship_zip ship_country
193                   payinfo paycvv paydate
194                   invoicing_list
195                   cust_pkg.pkgpart cust_pkg.bill
196                   svc_external.id svc_external.title
197                 );
198     push @fields, map "svc_phone.$_", qw( countrycode phonenum sip_password pin)
199       if $format eq 'svc_external_svc_phone';
200     $payby = 'BILL';
201   } elsif ( $format eq 'birthdates-acct_phone_hardware') {
202     @fields = qw( agent_custid refnum
203                   last first company address1 address2 city state zip country
204                   daytime night
205                   ship_last ship_first ship_company ship_address1 ship_address2
206                   ship_city ship_state ship_zip ship_country
207                   birthdate spouse_birthdate
208                   payinfo paycvv paydate
209                   invoicing_list
210                   cust_pkg.pkgpart cust_pkg.bill
211                   svc_acct.username svc_acct._password 
212                 );
213    push @fields, map "svc_phone.$_", qw(countrycode phonenum sip_password pin);
214    push @fields, map "svc_hardware.$_", qw(typenum ip_addr hw_addr serial);
215
216     $payby = 'BILL';
217   } else {
218     die "unknown format $format";
219   }
220
221   my $count;
222   my $parser;
223   my @buffer = ();
224   if ( $type eq 'csv' ) {
225
226     eval "use Text::CSV_XS;";
227     die $@ if $@;
228
229     $parser = new Text::CSV_XS;
230
231     @buffer = split(/\r?\n/, slurp($filename) );
232     $count = scalar(@buffer);
233
234   } elsif ( $type eq 'xls' ) {
235
236     eval "use Spreadsheet::ParseExcel;";
237     die $@ if $@;
238
239     my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($filename);
240     $parser = $excel->{Worksheet}[0]; #first sheet
241
242     $count = $parser->{MaxRow} || $parser->{MinRow};
243     $count++;
244
245   } else {
246     die "Unknown file type $type\n";
247   }
248
249   #my $columns;
250
251   local $SIG{HUP} = 'IGNORE';
252   local $SIG{INT} = 'IGNORE';
253   local $SIG{QUIT} = 'IGNORE';
254   local $SIG{TERM} = 'IGNORE';
255   local $SIG{TSTP} = 'IGNORE';
256   local $SIG{PIPE} = 'IGNORE';
257
258   my $oldAutoCommit = $FS::UID::AutoCommit;
259   local $FS::UID::AutoCommit = 0;
260   my $dbh = dbh;
261
262   #implies ignore_expired_card
263   local($FS::cust_main::import) = 1;
264   local($FS::cust_main::import) = 1;
265   
266   my $line;
267   my $row = 0;
268   my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
269   while (1) {
270
271     my @columns = ();
272     if ( $type eq 'csv' ) {
273
274       last unless scalar(@buffer);
275       $line = shift(@buffer);
276
277       $parser->parse($line) or do {
278         $dbh->rollback if $oldAutoCommit;
279         return "can't parse: ". $parser->error_input();
280       };
281       @columns = $parser->fields();
282
283     } elsif ( $type eq 'xls' ) {
284
285       last if $row > ($parser->{MaxRow} || $parser->{MinRow})
286            || ! $parser->{Cells}[$row];
287
288       my @row = @{ $parser->{Cells}[$row] };
289       @columns = map $_->{Val}, @row;
290
291       #my $z = 'A';
292       #warn $z++. ": $_\n" for @columns;
293
294     } else {
295       die "Unknown file type $type\n";
296     }
297
298     #warn join('-',@columns);
299
300     my %cust_main = (
301       custbatch => $custbatch,
302       agentnum  => $agentnum,
303       refnum    => $refnum,
304       country   => $conf->config('countrydefault') || 'US',
305       payby     => $payby, #default
306       paydate   => '12/2037', #default
307     );
308     my $billtime = time;
309     my %cust_pkg = ( pkgpart => $pkgpart );
310     my %svc_x = ();
311     foreach my $field ( @fields ) {
312
313       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
314
315         #$cust_pkg{$1} = parse_datetime( shift @$columns );
316         if ( $1 eq 'pkgpart' ) {
317           $cust_pkg{$1} = shift @columns;
318         } elsif ( $1 eq 'setup' ) {
319           $billtime = parse_datetime(shift @columns);
320         } else {
321           $cust_pkg{$1} = parse_datetime( shift @columns );
322         } 
323
324       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
325
326         $svc_x{$1} = shift @columns;
327
328       } elsif ( $field =~ /^svc_external\.(id|title)$/ ) {
329
330         $svc_x{$1} = shift @columns;
331
332       } elsif ( $field =~ /^svc_phone\.(countrycode|phonenum|sip_password|pin)$/ ) {
333         $svc_x{$1} = shift @columns;
334       
335       } elsif ( $field =~ /^svc_hardware\.(typenum|ip_addr|hw_addr|serial)$/ ) {
336
337         $svc_x{$1} = shift @columns;
338
339       } else {
340
341         #refnum interception
342         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
343
344           my $referral = $columns[0];
345           my %hash = ( 'referral' => $referral,
346                        'agentnum' => $agentnum,
347                        'disabled' => '',
348                      );
349
350           my $part_referral = qsearchs('part_referral', \%hash )
351                               || new FS::part_referral \%hash;
352
353           unless ( $part_referral->refnum ) {
354             my $error = $part_referral->insert;
355             if ( $error ) {
356               $dbh->rollback if $oldAutoCommit;
357               return "can't auto-insert advertising source: $referral: $error";
358             }
359           }
360
361           $columns[0] = $part_referral->refnum;
362         }
363
364         my $value = shift @columns;
365         $cust_main{$field} = $value if length($value);
366       }
367     }
368
369     if ( defined $cust_main{'payinfo'} && length $cust_main{'payinfo'} ) {
370       $cust_main{'payby'} = 'CARD';
371       if ($cust_main{'payinfo'} =~ /\s*([AD]?)(.*)\s*$/) {
372         $cust_main{'payby'} = 'DCRD' if $1 eq 'D';
373         $cust_main{'payinfo'} = $2;
374       }
375     }
376
377     $cust_main{$_} = parse_datetime($cust_main{$_})
378       foreach grep $cust_main{$_},
379         qw( birthdate spouse_birthdate anniversary_date );
380
381     my $invoicing_list = $cust_main{'invoicing_list'}
382                            ? [ delete $cust_main{'invoicing_list'} ]
383                            : [];
384
385     my $customer_options = delete $cust_main{customer_options};
386     $cust_main{tax} = 'Y' if $customer_options =~ /taxexempt/i;
387     push @$invoicing_list, 'POST' if $customer_options =~ /postalinvoice/i;
388
389     my $cust_main = new FS::cust_main ( \%cust_main );
390
391     use Tie::RefHash;
392     tie my %hash, 'Tie::RefHash'; #this part is important
393
394     if ( $cust_pkg{'pkgpart'} ) {
395
396       unless ( $cust_pkg{'pkgpart'} =~ /^\d+$/ ) {
397         $dbh->rollback if $oldAutoCommit;
398         return 'illegal pkgpart: '. $cust_pkg{'pkgpart'};
399       }
400
401       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
402
403       my @svc_x = ();
404       my $svcdb = '';
405       if ( $svc_x{'username'} ) {
406         $svcdb = 'svc_acct';
407       } elsif ( $svc_x{'id'} || $svc_x{'title'} ) {
408         $svcdb = 'svc_external';
409       }
410
411       my $svc_phone = '';
412       if ( $svc_x{'countrycode'} || $svc_x{'phonenum'} ) {
413         $svc_phone = FS::svc_phone->new( {
414           map { $_ => delete($svc_x{$_}) }
415               qw( countrycode phonenum sip_password pin )
416         } );
417       }
418
419       my $svc_hardware = '';
420       if ( $svc_x{'typenum'} ) {
421         $svc_hardware = FS::svc_hardware->new( {
422           map { $_ => delete($svc_x{$_}) }
423             qw( typenum ip_addr hw_addr serial )
424         } );
425       }
426
427       if ( $svcdb || $svc_phone || $svc_hardware ) {
428         my $part_pkg = $cust_pkg->part_pkg;
429         unless ( $part_pkg ) {
430           $dbh->rollback if $oldAutoCommit;
431           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
432         } 
433         if ( $svcdb ) {
434           $svc_x{svcpart} = $part_pkg->svcpart_unique_svcdb( $svcdb );
435           my $class = "FS::$svcdb";
436           push @svc_x, $class->new( \%svc_x );
437         }
438         if ( $svc_phone ) {
439           $svc_phone->svcpart( $part_pkg->svcpart_unique_svcdb('svc_phone') );
440           push @svc_x, $svc_phone;
441         }
442         if ( $svc_hardware ) {
443           $svc_hardware->svcpart( $part_pkg->svcpart_unique_svcdb('svc_hardware') );
444           push @svc_x, $svc_hardware;
445         }
446
447       }
448
449       $hash{$cust_pkg} = \@svc_x;
450     }
451
452     my $error = $cust_main->insert( \%hash, $invoicing_list );
453
454     if ( $error ) {
455       $dbh->rollback if $oldAutoCommit;
456       return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
457     }
458
459     if ( $format eq 'simple' ) {
460
461       #false laziness w/bill.cgi
462       $error = $cust_main->bill( 'time' => $billtime );
463       if ( $error ) {
464         $dbh->rollback if $oldAutoCommit;
465         return "can't bill customer for $line: $error";
466       }
467   
468       $error = $cust_main->apply_payments_and_credits;
469       if ( $error ) {
470         $dbh->rollback if $oldAutoCommit;
471         return "can't bill customer for $line: $error";
472       }
473
474       $error = $cust_main->collect();
475       if ( $error ) {
476         $dbh->rollback if $oldAutoCommit;
477         return "can't collect customer for $line: $error";
478       }
479
480     }
481
482     $row++;
483
484     if ( $job && time - $min_sec > $last ) { #progress bar
485       $job->update_statustext( int(100 * $row / $count) );
486       $last = time;
487     }
488
489   }
490
491   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
492
493   return "Empty file!" unless $row;
494
495   ''; #no error
496
497 }
498
499 =head1 BUGS
500
501 Not enough documentation.
502
503 =head1 SEE ALSO
504
505 L<FS::cust_main>, L<FS::cust_pkg>,
506 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
507
508 =cut
509
510 1;