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