wireless broadband service import, RT#38986
[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 Data::Dumper;
6 use File::Slurp qw( slurp );
7 use FS::Misc::DateTime qw( parse_datetime );
8 use FS::UID qw( dbh );
9 use FS::Record qw( qsearchs );
10 use FS::cust_main;
11 use FS::svc_acct;
12 use FS::svc_broadband;
13 use FS::svc_external;
14 use FS::svc_phone;
15 use FS::svc_hardware;
16 use FS::part_referral;
17
18 $DEBUG = 0;
19
20 install_callback FS::UID sub {
21   $conf = new FS::Conf;
22 };
23
24 my %is_location = map { $_ => 1 } FS::cust_main::Location->location_fields;
25
26 =head1 NAME
27
28 FS::cust_main::Import - Batch customer importing
29
30 =head1 SYNOPSIS
31
32   use FS::cust_main::Import;
33
34   #import
35   FS::cust_main::Import::batch_import( {
36     file      => $file,      #filename
37     type      => $type,      #csv or xls
38     format    => $format,    #extended, extended-plus_company, svc_external,
39                              #extended-plus_company_and_options
40                              #extended-plus_options, or svc_external_svc_phone
41     agentnum  => $agentnum,
42     refnum    => $refnum,
43     pkgpart   => $pkgpart,
44     job       => $job,       #optional job queue job, for progressbar updates
45     custbatch => $custbatch, #optional batch unique identifier
46   } );
47   die $error if $error;
48
49   #ajax helper
50   use FS::UI::Web::JSRPC;
51   my $server =
52     new FS::UI::Web::JSRPC 'FS::cust_main::Import::process_batch_import', $cgi;
53   print $server->process;
54
55 =head1 DESCRIPTION
56
57 Batch customer importing.
58
59 =head1 SUBROUTINES
60
61 =item process_batch_import
62
63 Load a batch import as a queued JSRPC job
64
65 =cut
66
67 sub process_batch_import {
68   my $job = shift;
69   my $param = 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_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_broadband/ ) {
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                 );
197     push @fields, map "svc_broadband.$_", qw( ip_addr mac_addr sectornum );
198     $payby = 'BILL';
199  } elsif ( $format =~ /^svc_external/ ) {
200     @fields = qw( agent_custid refnum
201                   last first company address1 address2 city state zip country
202                   daytime night
203                   ship_last ship_first ship_company ship_address1 ship_address2
204                   ship_city ship_state ship_zip ship_country
205                   payinfo paycvv paydate
206                   invoicing_list
207                   cust_pkg.pkgpart cust_pkg.bill
208                   svc_external.id svc_external.title
209                 );
210     push @fields, map "svc_phone.$_", qw( countrycode phonenum sip_password pin)
211       if $format eq 'svc_external_svc_phone';
212     $payby = 'BILL';
213   } elsif ( $format eq 'birthdates-acct_phone_hardware') {
214     @fields = qw( agent_custid refnum
215                   last first company address1 address2 city state zip country
216                   daytime night
217                   ship_last ship_first ship_company ship_address1 ship_address2
218                   ship_city ship_state ship_zip ship_country
219                   birthdate spouse_birthdate
220                   payinfo paycvv paydate
221                   invoicing_list
222                   cust_pkg.pkgpart cust_pkg.bill
223                   svc_acct.username svc_acct._password 
224                 );
225     push @fields, map "svc_phone.$_", qw(countrycode phonenum sip_password pin);
226     push @fields, map "svc_hardware.$_", qw(typenum ip_addr hw_addr serial);
227
228     $payby = 'BILL';
229   } elsif ( $format eq 'national_id-acct_phone') {
230     @fields = qw( agent_custid refnum
231                   last first company address1 address2 city state zip country
232                   daytime night
233                   ship_last ship_first ship_company ship_address1 ship_address2
234                   ship_city ship_state ship_zip ship_country
235                   national_id
236                   payinfo paycvv paydate
237                   invoicing_list
238                   cust_pkg.pkgpart cust_pkg.bill
239                   svc_acct.username svc_acct._password svc_acct.slipip
240                 );
241     push @fields, map "svc_phone.$_", qw(countrycode phonenum sip_password pin);
242
243     $payby = 'BILL';
244   } else {
245     die "unknown format $format";
246   }
247
248   my $count;
249   my $parser;
250   my @buffer = ();
251   if ( $type eq 'csv' ) {
252
253     eval "use Text::CSV_XS;";
254     die $@ if $@;
255
256     $parser = new Text::CSV_XS;
257
258     @buffer = split(/\r?\n/, slurp($filename) );
259     $count = scalar(@buffer);
260
261   } elsif ( $type eq 'xls' ) {
262
263     eval "use Spreadsheet::ParseExcel;";
264     die $@ if $@;
265
266     my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($filename);
267     $parser = $excel->{Worksheet}[0]; #first sheet
268
269     $count = $parser->{MaxRow} || $parser->{MinRow};
270     $count++;
271
272   } else {
273     die "Unknown file type $type\n";
274   }
275
276   #my $columns;
277
278   local $SIG{HUP} = 'IGNORE';
279   local $SIG{INT} = 'IGNORE';
280   local $SIG{QUIT} = 'IGNORE';
281   local $SIG{TERM} = 'IGNORE';
282   local $SIG{TSTP} = 'IGNORE';
283   local $SIG{PIPE} = 'IGNORE';
284
285   my $oldAutoCommit = $FS::UID::AutoCommit;
286   local $FS::UID::AutoCommit = 0;
287   my $dbh = dbh;
288
289   #implies ignore_expired_card
290   local($FS::cust_main::import) = 1;
291   local($FS::cust_main::import) = 1;
292   
293   my $line;
294   my $row = 0;
295   my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
296   while (1) {
297
298     my @columns = ();
299     if ( $type eq 'csv' ) {
300
301       last unless scalar(@buffer);
302       $line = shift(@buffer);
303
304       $parser->parse($line) or do {
305         $dbh->rollback if $oldAutoCommit;
306         return "can't parse: ". $parser->error_input();
307       };
308       @columns = $parser->fields();
309
310     } elsif ( $type eq 'xls' ) {
311
312       last if $row > ($parser->{MaxRow} || $parser->{MinRow})
313            || ! $parser->{Cells}[$row];
314
315       my @row = @{ $parser->{Cells}[$row] };
316       @columns = map $_->{Val}, @row;
317
318       #my $z = 'A';
319       #warn $z++. ": $_\n" for @columns;
320
321     } else {
322       die "Unknown file type $type\n";
323     }
324
325     #warn join('-',@columns);
326
327     my %cust_main = (
328       custbatch => $custbatch,
329       agentnum  => $agentnum,
330       refnum    => $refnum,
331       payby     => $payby, #default
332       paydate   => '12/2037', #default
333     );
334     my $billtime = time;
335     my %cust_pkg = ( pkgpart => $pkgpart );
336     my %svc_x = ();
337     my %bill_location = ();
338     my %ship_location = ();
339     foreach my $field ( @fields ) {
340
341       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
342
343         #$cust_pkg{$1} = parse_datetime( shift @$columns );
344         if ( $1 eq 'pkgpart' ) {
345           $cust_pkg{$1} = shift @columns;
346         } elsif ( $1 eq 'setup' ) {
347           $billtime = parse_datetime(shift @columns);
348         } else {
349           $cust_pkg{$1} = parse_datetime( shift @columns );
350         } 
351
352       } elsif ( $field =~ /^svc_acct\.(username|_password|slipip)$/ ) {
353
354         $svc_x{$1} = shift @columns;
355
356       } elsif ( $field =~ /^svc_broadband\.(ip_addr|mac_addr|sectornum)$/ ) {
357
358         $svc_x{$1} = shift @columns;
359
360       } elsif ( $field =~ /^svc_external\.(id|title)$/ ) {
361
362         $svc_x{$1} = shift @columns;
363
364       } elsif ( $field =~ /^svc_phone\.(countrycode|phonenum|sip_password|pin)$/ ) {
365         $svc_x{$1} = shift @columns;
366       
367       } elsif ( $field =~ /^svc_hardware\.(typenum|ip_addr|hw_addr|serial)$/ ) {
368
369         $svc_x{$1} = shift @columns;
370
371       } elsif ( $is_location{$field} ) {
372
373         $bill_location{$field} = shift @columns;
374
375       } elsif ( $field =~ /^ship_(.*)$/ and $is_location{$1} ) {
376
377         $ship_location{$1} = shift @columns;
378       
379       } else {
380
381         #refnum interception
382         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
383
384           my $referral = $columns[0];
385           my %hash = ( 'referral' => $referral,
386                        'agentnum' => $agentnum,
387                        'disabled' => '',
388                      );
389
390           my $part_referral = qsearchs('part_referral', \%hash )
391                               || new FS::part_referral \%hash;
392
393           unless ( $part_referral->refnum ) {
394             my $error = $part_referral->insert;
395             if ( $error ) {
396               $dbh->rollback if $oldAutoCommit;
397               return "can't auto-insert advertising source: $referral: $error";
398             }
399           }
400
401           $columns[0] = $part_referral->refnum;
402         }
403
404         my $value = shift @columns;
405         $cust_main{$field} = $value if length($value);
406       }
407     } # foreach my $field
408     # finished importing columns
409
410     $bill_location{'country'} ||= $conf->config('countrydefault') || 'US';
411     $cust_main{'bill_location'} = FS::cust_location->new(\%bill_location);
412     if ( grep $_, values(%ship_location) ) {
413       $ship_location{'country'} ||= $conf->config('countrydefault') || 'US';
414       $cust_main{'ship_location'} = FS::cust_location->new(\%ship_location);
415     } else {
416       $cust_main{'ship_location'} = $cust_main{'bill_location'};
417     }
418
419     if ( defined $cust_main{'payinfo'} && length $cust_main{'payinfo'} ) {
420
421       if ( $cust_main{'payinfo'} =~ /^\s*(\d+\@[\d\.]+)\s*$/ ) {
422
423         $cust_main{'payby'}   = 'CHEK';
424         $cust_main{'payinfo'} = $1;
425
426       } else {
427
428         $cust_main{'payby'} = 'CARD';
429
430         if ($cust_main{'payinfo'} =~ /^\s*([AD]?)(.*)\s*$/) {
431           $cust_main{'payby'} = 'DCRD' if $1 eq 'D';
432           $cust_main{'payinfo'} = $2;
433         }
434
435       }
436
437     }
438
439     $cust_main{$_} = parse_datetime($cust_main{$_})
440       foreach grep $cust_main{$_},
441         qw( birthdate spouse_birthdate anniversary_date );
442
443     my $invoicing_list = $cust_main{'invoicing_list'}
444                            ? [ delete $cust_main{'invoicing_list'} ]
445                            : [];
446
447     my $customer_options = delete $cust_main{customer_options};
448     $cust_main{tax} = 'Y' if $customer_options =~ /taxexempt/i;
449     push @$invoicing_list, 'POST' if $customer_options =~ /postalinvoice/i;
450
451     my $cust_main = new FS::cust_main ( \%cust_main );
452
453     use Tie::RefHash;
454     tie my %hash, 'Tie::RefHash'; #this part is important
455
456     if ( $cust_pkg{'pkgpart'} ) {
457
458       unless ( $cust_pkg{'pkgpart'} =~ /^\d+$/ ) {
459         $dbh->rollback if $oldAutoCommit;
460         return 'illegal pkgpart: '. $cust_pkg{'pkgpart'};
461       }
462
463       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
464
465       my @svc_x = ();
466       my $svcdb = '';
467       if ( $svc_x{'username'} ) {
468         $svcdb = 'svc_acct';
469       } elsif ( $svc_x{'id'} || $svc_x{'title'} ) {
470         $svcdb = 'svc_external';
471       } elsif ( $svc_x{ip_addr} || $svc_x{mac_addr} ) {
472         $svcdb = 'svc_broadband';
473       }
474
475       my $svc_phone = '';
476       if ( $svc_x{'countrycode'} || $svc_x{'phonenum'} ) {
477         $svc_phone = FS::svc_phone->new( {
478           map { $_ => delete($svc_x{$_}) }
479               qw( countrycode phonenum sip_password pin )
480         } );
481       }
482
483       my $svc_hardware = '';
484       if ( $svc_x{'typenum'} ) {
485         $svc_hardware = FS::svc_hardware->new( {
486           map { $_ => delete($svc_x{$_}) }
487             qw( typenum ip_addr hw_addr serial )
488         } );
489       }
490
491       if ( $svcdb || $svc_phone || $svc_hardware ) {
492         my $part_pkg = $cust_pkg->part_pkg;
493         unless ( $part_pkg ) {
494           $dbh->rollback if $oldAutoCommit;
495           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
496         } 
497         if ( $svcdb ) {
498           $svc_x{svcpart} = $part_pkg->svcpart_unique_svcdb( $svcdb );
499           my $class = "FS::$svcdb";
500           push @svc_x, $class->new( \%svc_x );
501         }
502         if ( $svc_phone ) {
503           $svc_phone->svcpart( $part_pkg->svcpart_unique_svcdb('svc_phone') );
504           push @svc_x, $svc_phone;
505         }
506         if ( $svc_hardware ) {
507           $svc_hardware->svcpart( $part_pkg->svcpart_unique_svcdb('svc_hardware') );
508           push @svc_x, $svc_hardware;
509         }
510
511       }
512
513       $hash{$cust_pkg} = \@svc_x;
514     }
515
516     my $error = $cust_main->insert( \%hash, $invoicing_list );
517
518     if ( $error ) {
519       $dbh->rollback if $oldAutoCommit;
520       return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
521     }
522
523     if ( $format eq 'simple' ) {
524
525       #false laziness w/bill.cgi
526       $error = $cust_main->bill( 'time' => $billtime );
527       if ( $error ) {
528         $dbh->rollback if $oldAutoCommit;
529         return "can't bill customer for $line: $error";
530       }
531   
532       $error = $cust_main->apply_payments_and_credits;
533       if ( $error ) {
534         $dbh->rollback if $oldAutoCommit;
535         return "can't bill customer for $line: $error";
536       }
537
538       $error = $cust_main->collect();
539       if ( $error ) {
540         $dbh->rollback if $oldAutoCommit;
541         return "can't collect customer for $line: $error";
542       }
543
544     }
545
546     $row++;
547
548     if ( $job && time - $min_sec > $last ) { #progress bar
549       $job->update_statustext( int(100 * $row / $count) );
550       $last = time;
551     }
552
553   }
554
555   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
556
557   return "Empty file!" unless $row;
558
559   ''; #no error
560
561 }
562
563 =head1 BUGS
564
565 Not enough documentation.
566
567 =head1 SEE ALSO
568
569 L<FS::cust_main>, L<FS::cust_pkg>,
570 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
571
572 =cut
573
574 1;