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