better support for batch-increment_expiration, RT#10453
[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 or fixed
206   my @fields              = @{ $info->{'fields'}};
207   my $formatre            = $info->{'formatre'};      # for fixed
208   my @all_values;
209   my $begin_condition     = $info->{'begin_condition'};
210   my $end_condition       = $info->{'end_condition'};
211   my $end_hook            = $info->{'end_hook'};
212   my $skip_condition      = $info->{'skip_condition'};
213   my $hook                = $info->{'hook'};
214   my $approved_condition  = $info->{'approved'};
215   my $declined_condition  = $info->{'declined'};
216
217   my $csv = new Text::CSV_XS;
218
219   local $SIG{HUP} = 'IGNORE';
220   local $SIG{INT} = 'IGNORE';
221   local $SIG{QUIT} = 'IGNORE';
222   local $SIG{TERM} = 'IGNORE';
223   local $SIG{TSTP} = 'IGNORE';
224   local $SIG{PIPE} = 'IGNORE';
225
226   my $oldAutoCommit = $FS::UID::AutoCommit;
227   local $FS::UID::AutoCommit = 0;
228   my $dbh = dbh;
229
230   my $reself = $self->select_for_update;
231
232   unless ( $reself->status eq 'I' ) {
233     $dbh->rollback if $oldAutoCommit;
234     return "batchnum ". $self->batchnum. "no longer in transit";
235   }
236
237   my $error = $self->set_status('R');
238   if ( $error ) {
239     $dbh->rollback if $oldAutoCommit;
240     return $error;
241   }
242
243   my $total = 0;
244   my $line;
245
246   # Order of operations has been changed here.
247   # We now slurp everything into @all_values, then 
248   # process one line at a time.
249
250   if ($filetype eq 'XML') {
251     eval "use XML::Simple";
252     die $@ if $@;
253     my @xmlkeys = @{ $info->{'xmlkeys'} };  # for XML
254     my $xmlrow  = $info->{'xmlrow'};        # also for XML
255
256     # Do everything differently.
257     my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
258     my $rows = $data;
259     # $xmlrow = [ RootKey, FirstLevelKey, SecondLevelKey... ]
260     $rows = $rows->{$_} foreach( @$xmlrow );
261     if(!defined($rows)) {
262       $dbh->rollback if $oldAutoCommit;
263       return "can't find rows in XML file";
264     }
265     $rows = [ $rows ] if ref($rows) ne 'ARRAY';
266     foreach my $row (@$rows) {
267       push @all_values, [ @{$row}{@xmlkeys}, $row ];
268     }
269   }
270   else {
271     while ( defined($line=<$fh>) ) {
272
273       next if $line =~ /^\s*$/; #skip blank lines
274
275       if ($filetype eq "CSV") {
276         $csv->parse($line) or do {
277           $dbh->rollback if $oldAutoCommit;
278           return "can't parse: ". $csv->error_input();
279         };
280         push @all_values, [ $csv->fields(), $line ];
281       }elsif ($filetype eq 'fixed'){
282         my @values = ( $line =~ /$formatre/ );
283         unless (@values) {
284           $dbh->rollback if $oldAutoCommit;
285           return "can't parse: ". $line;
286         };
287         push @values, $line;
288         push @all_values, \@values;
289       }else{
290         $dbh->rollback if $oldAutoCommit;
291         return "Unknown file type $filetype";
292       }
293     }
294   }
295
296   my $num = 0;
297   foreach (@all_values) {
298     if($job) {
299       $num++;
300       $job->update_statustext(int(100 * $num/scalar(@all_values)));
301     }
302     my @values = @$_;
303
304     my %hash;
305     my $line = pop @values;
306     foreach my $field ( @fields ) {
307       my $value = shift @values;
308       next unless $field;
309       $hash{$field} = $value;
310     }
311
312     if ( defined($begin_condition) ) {
313       if ( &{$begin_condition}(\%hash, $line) ) {
314         undef $begin_condition;
315       }
316       else {
317         next;
318       }
319     }
320
321     if ( defined($end_condition) and &{$end_condition}(\%hash, $line) ) {
322       my $error;
323       $error = &{$end_hook}(\%hash, $total, $line) if defined($end_hook);
324       if ( $error ) {
325         $dbh->rollback if $oldAutoCommit;
326         return $error;
327       }
328       last;
329     }
330
331     if ( defined($skip_condition) and &{$skip_condition}(\%hash, $line) ) {
332       next;
333     }
334
335     my $cust_pay_batch =
336       qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
337     unless ( $cust_pay_batch ) {
338       return "unknown paybatchnum $hash{'paybatchnum'}\n";
339     }
340     my $custnum = $cust_pay_batch->custnum,
341     my $payby = $cust_pay_batch->payby,
342
343     my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
344
345     &{$hook}(\%hash, $cust_pay_batch->hashref);
346
347     if ( &{$approved_condition}(\%hash) ) {
348
349       $new_cust_pay_batch->status('Approved');
350
351     } elsif ( &{$declined_condition}(\%hash) ) {
352
353       $new_cust_pay_batch->status('Declined');
354
355     }
356
357     my $error = $new_cust_pay_batch->replace($cust_pay_batch);
358     if ( $error ) {
359       $dbh->rollback if $oldAutoCommit;
360       return "error updating status of paybatchnum $hash{'paybatchnum'}: $error\n";
361     }
362
363     # purge CVV when the batch is processed
364     if ( $payby =~ /^(CARD|DCRD)$/ ) {
365       my $payinfo = $hash{'payinfo'} || $cust_pay_batch->payinfo;
366       if ( ! grep { $_ eq cardtype($payinfo) }
367           $conf->config('cvv-save') ) {
368         $new_cust_pay_batch->cust_main->remove_cvv;
369       }
370     }
371
372     if ( $new_cust_pay_batch->status =~ /Approved/i ) {
373
374       my $cust_pay = new FS::cust_pay ( {
375         'custnum'  => $custnum,
376         'payby'    => $payby,
377         'paybatch' => $hash{'paybatch'} || $self->batchnum,
378         'payinfo'  => ( $hash{'payinfo'} || $cust_pay_batch->payinfo ),
379         map { $_ => $hash{$_} } (qw( paid _date )),
380       } );
381       $error = $cust_pay->insert;
382       if ( $error ) {
383         $dbh->rollback if $oldAutoCommit;
384         return "error adding payment paybatchnum $hash{'paybatchnum'}: $error\n";
385       }
386       $total += $hash{'paid'};
387   
388       $cust_pay->cust_main->apply_payments;
389
390     } elsif ( $new_cust_pay_batch->status =~ /Declined/i ) {
391
392       #false laziness w/cust_main::collect
393
394       my $due_cust_event = $new_cust_pay_batch->cust_main->due_cust_event(
395         #'check_freq' => '1d', #?
396         'eventtable' => 'cust_pay_batch',
397         'objects'    => [ $new_cust_pay_batch ],
398       );
399       unless( ref($due_cust_event) ) {
400         $dbh->rollback if $oldAutoCommit;
401         return $due_cust_event;
402       }
403
404       foreach my $cust_event ( @$due_cust_event ) {
405         
406         #XXX lock event
407     
408         #re-eval event conditions (a previous event could have changed things)
409         next unless $cust_event->test_conditions;
410
411         if ( my $error = $cust_event->do_event() ) {
412           # gah, even with transactions.
413           #$dbh->commit if $oldAutoCommit; #well.
414           $dbh->rollback if $oldAutoCommit;
415           return $error;
416         }
417
418       }
419
420     }
421
422   }
423   
424   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
425   '';
426
427 }
428
429 use MIME::Base64;
430 use Storable 'thaw';
431 use Data::Dumper;
432 sub process_import_results {
433   my $job = shift;
434   my $param = thaw(decode_base64(shift));
435   $param->{'job'} = $job;
436   warn Dumper($param) if $DEBUG;
437   my $batchnum = delete $param->{'batchnum'} or die "no batchnum specified\n";
438   my $batch = FS::pay_batch->by_key($batchnum) or die "batchnum '$batchnum' not found\n";
439
440   my $file = $param->{'uploaded_files'} or die "no files provided\n";
441   $file =~ s/^(\w+):([\.\w]+)$/$2/;
442   my $dir = '%%%FREESIDE_CACHE%%%/cache.' . $FS::UID::datasrc;
443   open( $param->{'filehandle'}, 
444         '<',
445         "$dir/$file" )
446       or die "unable to open '$file'.\n";
447   my $error = $batch->import_results($param);
448   unlink $file;
449   die $error if $error;
450 }
451
452 # Formerly httemplate/misc/download-batch.cgi
453 sub export_batch {
454   my $self = shift;
455   my $conf = new FS::Conf;
456   my $format = shift || $conf->config('batch-default_format')
457                or die "No batch format configured\n";
458   my $info = $export_info{$format} or die "Format not found: '$format'\n";
459   &{$info->{'init'}}($conf) if exists($info->{'init'});
460
461   my $curuser = $FS::CurrentUser::CurrentUser;
462
463   my $oldAutoCommit = $FS::UID::AutoCommit;
464   local $FS::UID::AutoCommit = 0;
465   my $dbh = dbh;  
466
467   my $first_download;
468   my $status = $self->status;
469   if ($status eq 'O') {
470     $first_download = 1;
471     my $error = $self->set_status('I');
472     die "error updating pay_batch status: $error\n" if $error;
473   } elsif ($status eq 'I' && $curuser->access_right('Reprocess batches')) {
474     $first_download = 0;
475   } else {
476     die "No pending batch.\n";
477   }
478
479   my $batch = '';
480   my $batchtotal = 0;
481   my $batchcount = 0;
482
483   my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
484                       qsearch('cust_pay_batch', { batchnum => $self->batchnum } );
485   
486   # handle batch-increment_expiration option
487   if ( $self->payby eq 'CARD' ) {
488     my ($cmon, $cyear) = (localtime(time))[4,5];
489     foreach (@cust_pay_batch) {
490       my $etime = str2time($_->exp) or next;
491       my ($day, $mon, $year) = (localtime($etime))[3,4,5];
492       if( $conf->exists('batch-increment_expiration') ) {
493         $year++ while( $year < $cyear or ($year == $cyear and $mon <= $cmon) );
494         $_->exp( sprintf('%4u-%02u-%02u', $year + 1900, $mon+1, $day) );
495       }
496       $_->setfield('expmmyy', sprintf('%02u%02u', $mon+1, $year % 100));
497     }
498   }
499   my $h = $info->{'header'};
500   if(ref($h) eq 'CODE') {
501     $batch .= &$h($self, \@cust_pay_batch) . "\n";
502   }
503   else {
504     $batch .= $h . "\n";
505   }
506   foreach my $cust_pay_batch (@cust_pay_batch) {
507
508     if ($first_download) {
509       my $balance = $cust_pay_batch->cust_main->balance;
510       if ($balance <= 0) { # then don't charge this customer
511         my $error = $cust_pay_batch->delete;
512         if ( $error ) {
513           $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
514           die $error;
515         }
516         next;
517       } elsif ($balance < $cust_pay_batch->amount) {
518         # reduce the charge to the remaining balance
519         $cust_pay_batch->amount($balance);
520         my $error = $cust_pay_batch->replace;
521         if ( $error ) {
522           $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
523           die $error;
524         }
525       }
526       # else $balance >= $cust_pay_batch->amount
527     }
528
529     $batchcount++;
530     $batchtotal += $cust_pay_batch->amount;
531     $batch .= &{$info->{'row'}}($cust_pay_batch, $self, $batchcount, $batchtotal) . "\n";
532
533   }
534
535   my $f = $info->{'footer'};
536   if(ref($f) eq 'CODE') {
537     $batch .= &$f($self, $batchcount, $batchtotal) . "\n";
538   }
539   else {
540     $batch .= $f . "\n";
541   }
542
543   if ($info->{'autopost'}) {
544     my $error = &{$info->{'autopost'}}($self, $batch);
545     if($error) {
546       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
547       die $error;
548     }
549   }
550
551   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
552   return $batch;
553 }
554
555 =back
556
557 =head1 BUGS
558
559 status is somewhat redundant now that download and upload exist
560
561 =head1 SEE ALSO
562
563 L<FS::Record>, schema.html from the base documentation.
564
565 =cut
566
567 1;
568