RT# 76992 - Added 3 new import formats that combine Location and Phone Service
[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   'all_dates'    => [],
107   'svc_acct'     => [qw( username _password domsvc )],
108   'svc_phone'    => [qw( countrycode phonenum sip_password pin )],
109   'svc_external' => [qw( id title )],
110   'location'     => [qw( address1 address2 city state zip country )],
111 );
112
113 sub _formatfields {
114   \%formatfields;
115 }
116
117 my %import_options = (
118   'table'         => 'cust_pkg',
119
120   'preinsert_callback'  => sub {
121     my($record, $param) = @_;
122     my @location_params = grep /^location\./, keys %$param;
123     if (@location_params) {
124       my $cust_location = FS::cust_location->new({
125           'custnum' => $record->custnum,
126       });
127       foreach my $p (@location_params) {
128         $p =~ /^location.(\w+)$/;
129         $cust_location->set($1, $param->{$p});
130       }
131
132       my $error = $cust_location->find_or_insert; # this avoids duplicates
133       return "error creating location: $error" if $error;
134       $record->set('locationnum', $cust_location->locationnum);
135     }
136     '';
137   },
138
139   'postinsert_callback' => sub {
140     my( $record, $param ) = @_;
141
142     my $formatfields = _formatfields;
143     foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
144
145       my $ff = $formatfields->{$svc_x};
146
147       if ( grep $param->{"$svc_x.$_"}, @$ff ) {
148         my $svc = "FS::$svc_x"->new( {
149           'pkgnum'  => $record->pkgnum,
150           'svcpart' => $record->part_pkg->svcpart($svc_x),
151           map { $_ => $param->{"$svc_x.$_"} } @$ff
152         } );
153
154         #this whole thing should be turned into a callback or config to turn on
155         if ( $svc_x eq 'svc_acct' && $svc->username =~ /\@/ ) {
156           my($username, $domain) = split(/\@/, $svc->username);
157           my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } )
158                          || new FS::svc_domain { 'svcpart' => 1,
159                                                  'domain'  => $domain, };
160           unless ( $svc_domain->svcnum ) {
161             my $error = $svc_domain->insert;
162             return "error auto-inserting domain: $error" if $error;
163           }
164           $svc->username($username);
165           $svc->domsvc($svc_domain->svcnum);
166         }
167
168         my $error = $svc->insert;
169         return "error inserting service: $error" if $error;
170       }
171
172     }
173
174     return ''; #no error
175
176   },
177 );
178
179 sub _import_options {
180   \%import_options;
181 }
182
183 sub batch_import {
184   my $opt = shift;
185
186   my $iopt = _import_options;
187   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
188
189   my $agentnum  = delete $opt->{agentnum}; # i like closures (delete though?)
190
191   my $format = delete $opt->{'format'};
192   my @fields = ();
193
194   if ( $format =~ /^(.*)-agent_custid(-agent_pkgid)?$/ ) {
195     $format = $1;
196     my $agent_pkgid = $2;
197     @fields = (
198       sub {
199         my( $self, $value ) = @_; # $conf, $param
200         my $cust_main = qsearchs('cust_main', {
201           'agentnum'     => $agentnum,
202           'agent_custid' => $value,
203         });
204         $self->custnum($cust_main->custnum) if $cust_main;
205       },
206     );
207     push @fields, 'agent_pkgid' if $agent_pkgid;
208   } else {
209     @fields = ( 'custnum' );
210   }
211
212   if ( $format =~ /^(.*)-locationnum$/ ) {
213     $format = $1;
214     push @fields, 'locationnum';
215   }
216
217   if ( $format =~ /^bulk_(.*)$/ ) {
218
219     $format = $1;
220
221     $opt->{'postinsert_callback'} = sub {
222       my( $record, $param ) = @_;
223
224       my $formatfields = _formatfields;
225       foreach my $svc_x ( grep /^svc/, keys %$formatfields ) {
226
227         my $ff = $formatfields->{$svc_x};
228
229         if ( grep $param->{"$svc_x.$_"}, @$ff ) {
230
231           $param->{'svc_phone.phonenum'} =~ /^\s*(\d+)\s*\-\s*(\d+)\s*$/
232             or return 'Enter a phone number range, with dash as the separator';
233           my($start, $end) = ($1, $2);
234           if ( length($end) < length($start) ) {
235             $end = substr($start, 0, length($start) - length($end) ). $end;
236           }
237
238           foreach my $phonenum ( "$start" .. "$end" ) {
239
240             my $svc = "FS::$svc_x"->new( {
241               'pkgnum'  => $record->pkgnum,
242               'svcpart' => $record->part_pkg->svcpart($svc_x),
243               map { $_ => $param->{"$svc_x.$_"} } @$ff
244             } );
245
246             $svc->phonenum($phonenum);
247             #$svc->set_default_and_fixed;
248             my $error = $svc->insert;
249             return "error inserting service: $error" if $error;
250
251           }
252
253         }
254
255       }
256
257       return ''; #no error
258
259     };
260
261   }
262
263   push @fields, ( 'pkgpart', 'discountnum' );
264
265   my @date_fields = ();
266   if ( $format =~ /all_dates/ ) {
267     @date_fields = qw(
268       order_date
269       start_date setup bill last_bill susp adjourn
270       resume
271       cancel expire
272       contract_end dundate
273     );
274   } else {
275     @date_fields = qw(
276       start_date setup bill last_bill susp adjourn
277       cancel expire
278     );
279   }
280
281   foreach my $field (@date_fields) { 
282     push @fields, sub {
283       my( $self, $value ) = @_; # $conf, $param
284       #->$field has undesirable effects
285       $self->set($field, parse_datetime($value) ); #$field closure
286     };
287   }
288
289   #probably can delete below - moved to line 292
290   #my $formatfields = _formatfields();
291
292   my @formats = split /-/, $format;
293   foreach my $f (@formats){
294
295     my $formatfields = _formatfields();
296     die "unknown format $format" unless $formatfields->{$f};
297
298     foreach my $field ( @{ $formatfields->{$f} } ) {
299
300       push @fields, sub {
301         my( $self, $value, $conf, $param ) = @_;
302         $param->{"$f.$field"} = $value;
303       };
304
305     }
306   }
307
308   $opt->{'fields'} = \@fields;
309
310   FS::Record::batch_import( $opt );
311
312 }
313
314 =for comment
315
316     my $billtime = time;
317     my %cust_pkg = ( pkgpart => $pkgpart );
318     my %svc_x = ();
319     foreach my $field ( @fields ) {
320
321       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
322
323         #$cust_pkg{$1} = parse_datetime( shift @$columns );
324         if ( $1 eq 'pkgpart' ) {
325           $cust_pkg{$1} = shift @columns;
326         } elsif ( $1 eq 'setup' ) {
327           $billtime = parse_datetime(shift @columns);
328         } else {
329           $cust_pkg{$1} = parse_datetime( shift @columns );
330         } 
331
332       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
333
334         $svc_x{$1} = shift @columns;
335
336       } elsif ( $field =~ /^svc_external\.(id|title)$/ ) {
337
338         $svc_x{$1} = shift @columns;
339
340       } elsif ( $field =~ /^svc_phone\.(countrycode|phonenum|sip_password|pin)$/ ) {
341         $svc_x{$1} = shift @columns;
342        
343       } else {
344
345         #refnum interception
346         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
347
348           my $referral = $columns[0];
349           my %hash = ( 'referral' => $referral,
350                        'agentnum' => $agentnum,
351                        'disabled' => '',
352                      );
353
354           my $part_referral = qsearchs('part_referral', \%hash )
355                               || new FS::part_referral \%hash;
356
357           unless ( $part_referral->refnum ) {
358             my $error = $part_referral->insert;
359             if ( $error ) {
360               $dbh->rollback if $oldAutoCommit;
361               return "can't auto-insert advertising source: $referral: $error";
362             }
363           }
364
365           $columns[0] = $part_referral->refnum;
366         }
367
368         my $value = shift @columns;
369         $cust_main{$field} = $value if length($value);
370       }
371     }
372
373     $cust_main{'payby'} = 'CARD'
374       if defined $cust_main{'payinfo'}
375       && length  $cust_main{'payinfo'};
376
377     my $invoicing_list = $cust_main{'invoicing_list'}
378                            ? [ delete $cust_main{'invoicing_list'} ]
379                            : [];
380
381     my $cust_main = new FS::cust_main ( \%cust_main );
382
383     use Tie::RefHash;
384     tie my %hash, 'Tie::RefHash'; #this part is important
385
386     if ( $cust_pkg{'pkgpart'} ) {
387       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
388
389       my @svc_x = ();
390       my $svcdb = '';
391       if ( $svc_x{'username'} ) {
392         $svcdb = 'svc_acct';
393       } elsif ( $svc_x{'id'} || $svc_x{'title'} ) {
394         $svcdb = 'svc_external';
395       }
396
397       my $svc_phone = '';
398       if ( $svc_x{'countrycode'} || $svc_x{'phonenum'} ) {
399         $svc_phone = FS::svc_phone->new( {
400           map { $_ => delete($svc_x{$_}) }
401               qw( countrycode phonenum sip_password pin)
402         } );
403       }
404
405       if ( $svcdb || $svc_phone ) {
406         my $part_pkg = $cust_pkg->part_pkg;
407         unless ( $part_pkg ) {
408           $dbh->rollback if $oldAutoCommit;
409           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
410         } 
411         if ( $svcdb ) {
412           $svc_x{svcpart} = $part_pkg->svcpart_unique_svcdb( $svcdb );
413           my $class = "FS::$svcdb";
414           push @svc_x, $class->new( \%svc_x );
415         }
416         if ( $svc_phone ) {
417           $svc_phone->svcpart( $part_pkg->svcpart_unique_svcdb('svc_phone') );
418           push @svc_x, $svc_phone;
419         }
420       }
421
422       $hash{$cust_pkg} = \@svc_x;
423     }
424
425     my $error = $cust_main->insert( \%hash, $invoicing_list );
426
427     if ( $error ) {
428       $dbh->rollback if $oldAutoCommit;
429       return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
430     }
431
432     if ( $format eq 'simple' ) {
433
434       #false laziness w/bill.cgi
435       $error = $cust_main->bill( 'time' => $billtime );
436       if ( $error ) {
437         $dbh->rollback if $oldAutoCommit;
438         return "can't bill customer for $line: $error";
439       }
440   
441       $error = $cust_main->apply_payments_and_credits;
442       if ( $error ) {
443         $dbh->rollback if $oldAutoCommit;
444         return "can't bill customer for $line: $error";
445       }
446
447       $error = $cust_main->collect();
448       if ( $error ) {
449         $dbh->rollback if $oldAutoCommit;
450         return "can't collect customer for $line: $error";
451       }
452
453     }
454
455     $row++;
456
457     if ( $job && time - $min_sec > $last ) { #progress bar
458       $job->update_statustext( int(100 * $row / $count) );
459       $last = time;
460     }
461
462   }
463
464   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
465
466   return "Empty file!" unless $row;
467
468   ''; #no error
469
470 }
471
472 =head1 BUGS
473
474 Not enough documentation.
475
476 =head1 SEE ALSO
477
478 L<FS::cust_main>, L<FS::cust_pkg>,
479 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
480
481 =cut
482
483 1;