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