RT#5683: payment batch upload uses job queue and progressbar
[freeside.git] / FS / FS / pay_batch.pm
1 package FS::pay_batch;
2
3 use strict;
4 use vars qw( @ISA $DEBUG %import_info %export_info $conf );
5 use Time::Local;
6 use Text::CSV_XS;
7 use FS::Record qw( dbh qsearch qsearchs );
8 use FS::cust_pay;
9 use FS::Conf;
10
11 @ISA = qw(FS::Record);
12
13 =head1 NAME
14
15 FS::pay_batch - Object methods for pay_batch records
16
17 =head1 SYNOPSIS
18
19   use FS::pay_batch;
20
21   $record = new FS::pay_batch \%hash;
22   $record = new FS::pay_batch { 'column' => 'value' };
23
24   $error = $record->insert;
25
26   $error = $new_record->replace($old_record);
27
28   $error = $record->delete;
29
30   $error = $record->check;
31
32 =head1 DESCRIPTION
33
34 An FS::pay_batch object represents an payment batch.  FS::pay_batch inherits
35 from FS::Record.  The following fields are currently supported:
36
37 =over 4
38
39 =item batchnum - primary key
40
41 =item payby - CARD or CHEK
42
43 =item status - O (Open), I (In-transit), or R (Resolved)
44
45 =item download - 
46
47 =item upload - 
48
49
50 =back
51
52 =head1 METHODS
53
54 =over 4
55
56 =item new HASHREF
57
58 Creates a new batch.  To add the batch to the database, see L<"insert">.
59
60 Note that this stores the hash reference, not a distinct copy of the hash it
61 points to.  You can ask the object for a copy with the I<hash> method.
62
63 =cut
64
65 # the new method can be inherited from FS::Record, if a table method is defined
66
67 sub table { 'pay_batch'; }
68
69 =item insert
70
71 Adds this record to the database.  If there is an error, returns the error,
72 otherwise returns false.
73
74 =cut
75
76 # the insert method can be inherited from FS::Record
77
78 =item delete
79
80 Delete this record from the database.
81
82 =cut
83
84 # the delete method can be inherited from FS::Record
85
86 =item replace OLD_RECORD
87
88 Replaces the OLD_RECORD with this one in the database.  If there is an error,
89 returns the error, otherwise returns false.
90
91 =cut
92
93 # the replace method can be inherited from FS::Record
94
95 =item check
96
97 Checks all fields to make sure this is a valid batch.  If there is
98 an error, returns the error, otherwise returns false.  Called by the insert
99 and replace methods.
100
101 =cut
102
103 # the check method should currently be supplied - FS::Record contains some
104 # data checking routines
105
106 sub check {
107   my $self = shift;
108
109   my $error = 
110     $self->ut_numbern('batchnum')
111     || $self->ut_enum('payby', [ 'CARD', 'CHEK' ])
112     || $self->ut_enum('status', [ 'O', 'I', 'R' ])
113   ;
114   return $error if $error;
115
116   $self->SUPER::check;
117 }
118
119 =item rebalance
120
121 =cut
122
123 sub rebalance {
124   my $self = shift;
125 }
126
127 =item set_status 
128
129 =cut
130
131 sub set_status {
132   my $self = shift;
133   $self->status(shift);
134   $self->download(time)
135     if $self->status eq 'I' && ! $self->download;
136   $self->upload(time)
137     if $self->status eq 'R' && ! $self->upload;
138   $self->replace();
139 }
140
141 # further false laziness
142
143 %import_info = %export_info = ();
144 foreach my $INC (@INC) {
145   warn "globbing $INC/FS/pay_batch/*.pm\n" if $DEBUG;
146   foreach my $file ( glob("$INC/FS/pay_batch/*.pm")) {
147     warn "attempting to load batch format from $file\n" if $DEBUG;
148     $file =~ /\/(\w+)\.pm$/;
149     next if !$1;
150     my $mod = $1;
151     my ($import, $export, $name) = 
152       eval "use FS::pay_batch::$mod; 
153            ( \\%FS::pay_batch::$mod\::import_info,
154              \\%FS::pay_batch::$mod\::export_info,
155              \$FS::pay_batch::$mod\::name)";
156     $name ||= $mod; # in case it's not defined
157     if( $@) {
158       # in FS::cdr this is a die, not a warn.  That's probably a bug.
159       warn "error using FS::pay_batch::$mod (skipping): $@\n";
160       next;
161     }
162     if(!keys(%$import)) {
163       warn "no \%import_info found in FS::pay_batch::$mod (skipping)\n";
164     }
165     else {
166       $import_info{$name} = $import;
167     }
168     if(!keys(%$export)) {
169       warn "no \%export_info found in FS::pay_batch::$mod (skipping)\n";
170     }
171     else {
172       $export_info{$name} = $export;
173     }
174   }
175 }
176
177 =item import_results OPTION => VALUE, ...
178
179 Import batch results.
180
181 Options are:
182
183 I<filehandle> - open filehandle of results file.
184
185 I<format> - "csv-td_canada_trust-merchant_pc_batch", "csv-chase_canada-E-xactBatch", "ach-spiritone", or "PAP"
186
187 =cut
188
189 sub import_results {
190   my $self = shift;
191
192   my $param = ref($_[0]) ? shift : { @_ };
193   my $fh = $param->{'filehandle'};
194   my $format = $param->{'format'};
195   my $info = $import_info{$format}
196     or die "unknown format $format";
197
198   my $job = $param->{'job'};
199   $job->update_statustext(0) if $job;
200
201   my $filetype            = $info->{'filetype'};      # CSV or fixed
202   my @fields              = @{ $info->{'fields'}};
203   my $formatre            = $info->{'formatre'};      # for fixed
204   my @all_values;
205   my $begin_condition     = $info->{'begin_condition'};
206   my $end_condition       = $info->{'end_condition'};
207   my $end_hook            = $info->{'end_hook'};
208   my $skip_condition      = $info->{'skip_condition'};
209   my $hook                = $info->{'hook'};
210   my $approved_condition  = $info->{'approved'};
211   my $declined_condition  = $info->{'declined'};
212
213   my $csv = new Text::CSV_XS;
214
215   local $SIG{HUP} = 'IGNORE';
216   local $SIG{INT} = 'IGNORE';
217   local $SIG{QUIT} = 'IGNORE';
218   local $SIG{TERM} = 'IGNORE';
219   local $SIG{TSTP} = 'IGNORE';
220   local $SIG{PIPE} = 'IGNORE';
221
222   my $oldAutoCommit = $FS::UID::AutoCommit;
223   local $FS::UID::AutoCommit = 0;
224   my $dbh = dbh;
225
226   my $reself = $self->select_for_update;
227
228   unless ( $reself->status eq 'I' ) {
229     $dbh->rollback if $oldAutoCommit;
230     return "batchnum ". $self->batchnum. "no longer in transit";
231   }
232
233   my $error = $self->set_status('R');
234   if ( $error ) {
235     $dbh->rollback if $oldAutoCommit;
236     return $error;
237   }
238
239   my $total = 0;
240   my $line;
241
242   # Order of operations has been changed here.
243   # We now slurp everything into @all_values, then 
244   # process one line at a time.
245
246   if ($filetype eq 'XML') {
247     eval "use XML::Simple";
248     die $@ if $@;
249     my @xmlkeys = @{ $info->{'xmlkeys'} };  # for XML
250     my $xmlrow  = $info->{'xmlrow'};        # also for XML
251
252     # Do everything differently.
253     my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
254     my $rows = $data;
255     # $xmlrow = [ RootKey, FirstLevelKey, SecondLevelKey... ]
256     $rows = $rows->{$_} foreach( @$xmlrow );
257     if(!defined($rows)) {
258       $dbh->rollback if $oldAutoCommit;
259       return "can't find rows in XML file";
260     }
261     $rows = [ $rows ] if ref($rows) ne 'ARRAY';
262     foreach my $row (@$rows) {
263       push @all_values, [ @{$row}{@xmlkeys}, $row ];
264     }
265   }
266   else {
267     while ( defined($line=<$fh>) ) {
268
269       next if $line =~ /^\s*$/; #skip blank lines
270
271       if ($filetype eq "CSV") {
272         $csv->parse($line) or do {
273           $dbh->rollback if $oldAutoCommit;
274           return "can't parse: ". $csv->error_input();
275         };
276         push @all_values, [ $csv->fields(), $line ];
277       }elsif ($filetype eq 'fixed'){
278         my @values = ( $line =~ /$formatre/ );
279         unless (@values) {
280           $dbh->rollback if $oldAutoCommit;
281           return "can't parse: ". $line;
282         };
283         push @values, $line;
284         push @all_values, \@values;
285       }else{
286         $dbh->rollback if $oldAutoCommit;
287         return "Unknown file type $filetype";
288       }
289     }
290   }
291
292   my $num = 0;
293   foreach (@all_values) {
294     if($job) {
295       $num++;
296       $job->update_statustext(int(100 * $num/scalar(@all_values)));
297     }
298     my @values = @$_;
299
300     my %hash;
301     my $line = pop @values;
302     foreach my $field ( @fields ) {
303       my $value = shift @values;
304       next unless $field;
305       $hash{$field} = $value;
306     }
307
308     if ( defined($begin_condition) ) {
309       if ( &{$begin_condition}(\%hash, $line) ) {
310         undef $begin_condition;
311       }
312       else {
313         next;
314       }
315     }
316
317     if ( defined($end_condition) and &{$end_condition}(\%hash, $line) ) {
318       my $error;
319       $error = &{$end_hook}(\%hash, $total, $line) if defined($end_hook);
320       if ( $error ) {
321         $dbh->rollback if $oldAutoCommit;
322         return $error;
323       }
324       last;
325     }
326
327     if ( defined($skip_condition) and &{$skip_condition}(\%hash, $line) ) {
328       next;
329     }
330
331     my $cust_pay_batch =
332       qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
333     unless ( $cust_pay_batch ) {
334       return "unknown paybatchnum $hash{'paybatchnum'}\n";
335     }
336     my $custnum = $cust_pay_batch->custnum,
337     my $payby = $cust_pay_batch->payby,
338
339     my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
340
341     &{$hook}(\%hash, $cust_pay_batch->hashref);
342
343     if ( &{$approved_condition}(\%hash) ) {
344
345       $new_cust_pay_batch->status('Approved');
346
347     } elsif ( &{$declined_condition}(\%hash) ) {
348
349       $new_cust_pay_batch->status('Declined');
350
351     }
352
353     my $error = $new_cust_pay_batch->replace($cust_pay_batch);
354     if ( $error ) {
355       $dbh->rollback if $oldAutoCommit;
356       return "error updating status of paybatchnum $hash{'paybatchnum'}: $error\n";
357     }
358
359     if ( $new_cust_pay_batch->status =~ /Approved/i ) {
360
361       my $cust_pay = new FS::cust_pay ( {
362         'custnum'  => $custnum,
363         'payby'    => $payby,
364         'paybatch' => $self->batchnum,
365         map { $_ => $hash{$_} } (qw( paid _date payinfo )),
366       } );
367       $error = $cust_pay->insert;
368       if ( $error ) {
369         $dbh->rollback if $oldAutoCommit;
370         return "error adding payment paybatchnum $hash{'paybatchnum'}: $error\n";
371       }
372       $total += $hash{'paid'};
373   
374       $cust_pay->cust_main->apply_payments;
375
376     } elsif ( $new_cust_pay_batch->status =~ /Declined/i ) {
377
378       #false laziness w/cust_main::collect
379
380       my $due_cust_event = $new_cust_pay_batch->cust_main->due_cust_event(
381         #'check_freq' => '1d', #?
382         'eventtable' => 'cust_pay_batch',
383         'objects'    => [ $new_cust_pay_batch ],
384       );
385       unless( ref($due_cust_event) ) {
386         $dbh->rollback if $oldAutoCommit;
387         return $due_cust_event;
388       }
389
390       foreach my $cust_event ( @$due_cust_event ) {
391         
392         #XXX lock event
393     
394         #re-eval event conditions (a previous event could have changed things)
395         next unless $cust_event->test_conditions;
396
397         if ( my $error = $cust_event->do_event() ) {
398           # gah, even with transactions.
399           #$dbh->commit if $oldAutoCommit; #well.
400           $dbh->rollback if $oldAutoCommit;
401           return $error;
402         }
403
404       }
405
406     }
407
408   }
409   
410   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
411   '';
412
413 }
414
415 use MIME::Base64;
416 use Storable 'thaw';
417 use Data::Dumper;
418 sub process_import_results {
419   my $job = shift;
420   my $param = thaw(decode_base64(shift));
421   $param->{'job'} = $job;
422   warn Dumper($param) if $DEBUG;
423   my $batchnum = delete $param->{'batchnum'} or die "no batchnum specified\n";
424   my $batch = FS::pay_batch->by_key($batchnum) or die "batchnum '$batchnum' not found\n";
425
426   my $file = $param->{'uploaded_files'} or die "no files provided\n";
427   $file =~ s/^(\w+):([\.\w]+)$/$2/;
428   my $dir = '%%%FREESIDE_CACHE%%%/cache.' . $FS::UID::datasrc;
429   open( $param->{'filehandle'}, 
430         '<',
431         "$dir/$file" )
432       or die "unable to open '$file'.\n";
433   my $error = $batch->import_results($param);
434   unlink $file;
435   die $error if $error;
436 }
437
438 # Formerly httemplate/misc/download-batch.cgi
439 sub export_batch {
440   my $self = shift;
441   my $conf = new FS::Conf;
442   my $format = shift || $conf->config('batch-default_format')
443                or die "No batch format configured\n";
444   my $info = $export_info{$format} or die "Format not found: '$format'\n";
445   &{$info->{'init'}}($conf) if exists($info->{'init'});
446
447   my $curuser = $FS::CurrentUser::CurrentUser;
448
449   my $oldAutoCommit = $FS::UID::AutoCommit;
450   local $FS::UID::AutoCommit = 0;
451   my $dbh = dbh;  
452
453   my $first_download;
454   my $status = $self->status;
455   if ($status eq 'O') {
456     $first_download = 1;
457     my $error = $self->set_status('I');
458     die "error updating pay_batch status: $error\n" if $error;
459   } elsif ($status eq 'I' && $curuser->access_right('Reprocess batches')) {
460     $first_download = 0;
461   } else {
462     die "No pending batch.\n";
463   }
464
465   my $batch = '';
466   my $batchtotal = 0;
467   my $batchcount = 0;
468
469   my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
470                       qsearch('cust_pay_batch', { batchnum => $self->batchnum } );
471
472   my $h = $info->{'header'};
473   if(ref($h) eq 'CODE') {
474     $batch .= &$h($self, \@cust_pay_batch) . "\n";
475   }
476   else {
477     $batch .= $h . "\n";
478   }
479   foreach my $cust_pay_batch (@cust_pay_batch) {
480     if($first_download) {
481       my $balance = $cust_pay_batch->cust_main->balance;
482       my $error = '';
483       if($balance <= 0) { # then don't charge this customer
484         $error = $cust_pay_batch->delete;
485         undef $cust_pay_batch;
486       }
487       elsif($balance < $cust_pay_batch->amount) { # then reduce the charge to the remaining balance
488         $cust_pay_batch->amount($balance);
489         $error = $cust_pay_batch->replace;
490       }
491       # else $balance >= $cust_pay_batch->amount
492       if($error) {
493         $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
494         die $error;
495       }
496     }
497     if($cust_pay_batch) { # that is, it wasn't deleted
498       $batchcount++;
499       $batchtotal += $cust_pay_batch->amount;
500       $batch .= &{$info->{'row'}}($cust_pay_batch, $self, $batchcount, $batchtotal) . "\n";
501     }
502   }
503   my $f = $info->{'footer'};
504   if(ref($f) eq 'CODE') {
505     $batch .= &$f($self, $batchcount, $batchtotal) . "\n";
506   }
507   else {
508     $batch .= $f . "\n";
509   }
510
511   if ($info->{'autopost'}) {
512     my $error = &{$info->{'autopost'}}($self, $batch);
513     if($error) {
514       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
515       die $error;
516     }
517   }
518
519   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
520   return $batch;
521 }
522
523 =back
524
525 =head1 BUGS
526
527 status is somewhat redundant now that download and upload exist
528
529 =head1 SEE ALSO
530
531 L<FS::Record>, schema.html from the base documentation.
532
533 =cut
534
535 1;
536