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