This commit was generated by cvs2svn to compensate for changes in r11022,
[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   'svc_acct'     => [qw( username _password domsvc )],
107   'svc_phone'    => [qw( countrycode phonenum sip_password pin )],
108   'svc_external' => [qw( id title )],
109 );
110
111 sub _formatfields {
112   \%formatfields;
113 }
114
115 my %import_options = (
116   'table'         => 'cust_pkg',
117
118   'postinsert_callback' => sub {
119     my( $record, $param ) = @_;
120
121     my $formatfields = _formatfields;
122     foreach my $svc_x ( grep { $_ ne 'default' } keys %$formatfields ) {
123
124       my $ff = $formatfields->{$svc_x};
125
126       if ( grep $param->{"$svc_x.$_"}, @$ff ) {
127         my $svc = "FS::$svc_x"->new( {
128           'pkgnum'  => $record->pkgnum,
129           'svcpart' => $record->part_pkg->svcpart($svc_x),
130           map { $_ => $param->{"$svc_x.$_"} } @$ff
131         } );
132
133         #this whole thing should be turned into a callback or config to turn on
134         if ( $svc_x eq 'svc_acct' && $svc->username =~ /\@/ ) {
135           my($username, $domain) = split(/\@/, $svc->username);
136           my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } )
137                          || new FS::svc_domain { 'svcpart' => 1,
138                                                  'domain'  => $domain, };
139           unless ( $svc_domain->svcnum ) {
140             my $error = $svc_domain->insert;
141             return "error auto-inserting domain: $error" if $error;
142           }
143           $svc->username($username);
144           $svc->domsvc($svc_domain->svcnum);
145         }
146
147         my $error = $svc->insert;
148         return "error inserting service: $error" if $error;
149       }
150
151     }
152
153     return ''; #no error
154
155   },
156 );
157
158 sub _import_options {
159   \%import_options;
160 }
161
162 sub batch_import {
163   my $opt = shift;
164
165   my $iopt = _import_options;
166   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
167
168   my $agentnum  = delete $opt->{agentnum}; # i like closures (delete though?)
169
170   my $format = delete $opt->{'format'};
171   my @fields = ();
172
173   if ( $format =~ /^(.*)-agent_custid(-agent_pkgid)?$/ ) {
174     $format = $1;
175     my $agent_pkgid = $2;
176     @fields = (
177       sub {
178         my( $self, $value ) = @_; # $conf, $param
179         my $cust_main = qsearchs('cust_main', {
180           'agentnum'     => $agentnum,
181           'agent_custid' => $value,
182         });
183         $self->custnum($cust_main->custnum) if $cust_main;
184       },
185     );
186     push @fields, 'agent_pkgid' if $agent_pkgid;
187   } else {
188     @fields = ( 'custnum' );
189   }
190
191   push @fields, ( 'pkgpart', 'discountnum' );
192
193   foreach my $field ( 
194     qw( start_date setup bill last_bill susp adjourn cancel expire )
195   ) {
196     push @fields, sub {
197       my( $self, $value ) = @_; # $conf, $param
198       #->$field has undesirable effects
199       $self->set($field, parse_datetime($value) ); #$field closure
200     };
201   }
202
203   my $formatfields = _formatfields();
204
205   die "unknown format $format" unless $formatfields->{$format};
206
207   foreach my $field ( @{ $formatfields->{$format} } ) {
208
209     push @fields, sub {
210       my( $self, $value, $conf, $param ) = @_;
211       $param->{"$format.$field"} = $value;
212     };
213
214   }
215
216   $opt->{'fields'} = \@fields;
217
218   FS::Record::batch_import( $opt );
219
220 }
221
222 =for comment
223
224     my $billtime = time;
225     my %cust_pkg = ( pkgpart => $pkgpart );
226     my %svc_x = ();
227     foreach my $field ( @fields ) {
228
229       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
230
231         #$cust_pkg{$1} = parse_datetime( shift @$columns );
232         if ( $1 eq 'pkgpart' ) {
233           $cust_pkg{$1} = shift @columns;
234         } elsif ( $1 eq 'setup' ) {
235           $billtime = parse_datetime(shift @columns);
236         } else {
237           $cust_pkg{$1} = parse_datetime( shift @columns );
238         } 
239
240       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
241
242         $svc_x{$1} = shift @columns;
243
244       } elsif ( $field =~ /^svc_external\.(id|title)$/ ) {
245
246         $svc_x{$1} = shift @columns;
247
248       } elsif ( $field =~ /^svc_phone\.(countrycode|phonenum|sip_password|pin)$/ ) {
249         $svc_x{$1} = shift @columns;
250        
251       } else {
252
253         #refnum interception
254         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
255
256           my $referral = $columns[0];
257           my %hash = ( 'referral' => $referral,
258                        'agentnum' => $agentnum,
259                        'disabled' => '',
260                      );
261
262           my $part_referral = qsearchs('part_referral', \%hash )
263                               || new FS::part_referral \%hash;
264
265           unless ( $part_referral->refnum ) {
266             my $error = $part_referral->insert;
267             if ( $error ) {
268               $dbh->rollback if $oldAutoCommit;
269               return "can't auto-insert advertising source: $referral: $error";
270             }
271           }
272
273           $columns[0] = $part_referral->refnum;
274         }
275
276         my $value = shift @columns;
277         $cust_main{$field} = $value if length($value);
278       }
279     }
280
281     $cust_main{'payby'} = 'CARD'
282       if defined $cust_main{'payinfo'}
283       && length  $cust_main{'payinfo'};
284
285     my $invoicing_list = $cust_main{'invoicing_list'}
286                            ? [ delete $cust_main{'invoicing_list'} ]
287                            : [];
288
289     my $cust_main = new FS::cust_main ( \%cust_main );
290
291     use Tie::RefHash;
292     tie my %hash, 'Tie::RefHash'; #this part is important
293
294     if ( $cust_pkg{'pkgpart'} ) {
295       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
296
297       my @svc_x = ();
298       my $svcdb = '';
299       if ( $svc_x{'username'} ) {
300         $svcdb = 'svc_acct';
301       } elsif ( $svc_x{'id'} || $svc_x{'title'} ) {
302         $svcdb = 'svc_external';
303       }
304
305       my $svc_phone = '';
306       if ( $svc_x{'countrycode'} || $svc_x{'phonenum'} ) {
307         $svc_phone = FS::svc_phone->new( {
308           map { $_ => delete($svc_x{$_}) }
309               qw( countrycode phonenum sip_password pin)
310         } );
311       }
312
313       if ( $svcdb || $svc_phone ) {
314         my $part_pkg = $cust_pkg->part_pkg;
315         unless ( $part_pkg ) {
316           $dbh->rollback if $oldAutoCommit;
317           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
318         } 
319         if ( $svcdb ) {
320           $svc_x{svcpart} = $part_pkg->svcpart_unique_svcdb( $svcdb );
321           my $class = "FS::$svcdb";
322           push @svc_x, $class->new( \%svc_x );
323         }
324         if ( $svc_phone ) {
325           $svc_phone->svcpart( $part_pkg->svcpart_unique_svcdb('svc_phone') );
326           push @svc_x, $svc_phone;
327         }
328       }
329
330       $hash{$cust_pkg} = \@svc_x;
331     }
332
333     my $error = $cust_main->insert( \%hash, $invoicing_list );
334
335     if ( $error ) {
336       $dbh->rollback if $oldAutoCommit;
337       return "can't insert customer". ( $line ? " for $line" : '' ). ": $error";
338     }
339
340     if ( $format eq 'simple' ) {
341
342       #false laziness w/bill.cgi
343       $error = $cust_main->bill( 'time' => $billtime );
344       if ( $error ) {
345         $dbh->rollback if $oldAutoCommit;
346         return "can't bill customer for $line: $error";
347       }
348   
349       $error = $cust_main->apply_payments_and_credits;
350       if ( $error ) {
351         $dbh->rollback if $oldAutoCommit;
352         return "can't bill customer for $line: $error";
353       }
354
355       $error = $cust_main->collect();
356       if ( $error ) {
357         $dbh->rollback if $oldAutoCommit;
358         return "can't collect customer for $line: $error";
359       }
360
361     }
362
363     $row++;
364
365     if ( $job && time - $min_sec > $last ) { #progress bar
366       $job->update_statustext( int(100 * $row / $count) );
367       $last = time;
368     }
369
370   }
371
372   $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
373
374   return "Empty file!" unless $row;
375
376   ''; #no error
377
378 }
379
380 =head1 BUGS
381
382 Not enough documentation.
383
384 =head1 SEE ALSO
385
386 L<FS::cust_main>, L<FS::cust_pkg>,
387 L<FS::svc_acct>, L<FS::svc_external>, L<FS::svc_phone>
388
389 =cut
390
391 1;