4 use vars qw( @ISA $DEBUG %import_info %export_info $conf );
7 use FS::Record qw( dbh qsearch qsearchs );
10 use Date::Parse qw(str2time);
11 use Business::CreditCard qw(cardtype);
13 @ISA = qw(FS::Record);
17 FS::pay_batch - Object methods for pay_batch records
23 $record = new FS::pay_batch \%hash;
24 $record = new FS::pay_batch { 'column' => 'value' };
26 $error = $record->insert;
28 $error = $new_record->replace($old_record);
30 $error = $record->delete;
32 $error = $record->check;
36 An FS::pay_batch object represents an payment batch. FS::pay_batch inherits
37 from FS::Record. The following fields are currently supported:
41 =item batchnum - primary key
43 =item payby - CARD or CHEK
45 =item status - O (Open), I (In-transit), or R (Resolved)
60 Creates a new batch. To add the batch to the database, see L<"insert">.
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.
67 # the new method can be inherited from FS::Record, if a table method is defined
69 sub table { 'pay_batch'; }
73 Adds this record to the database. If there is an error, returns the error,
74 otherwise returns false.
78 # the insert method can be inherited from FS::Record
82 Delete this record from the database.
86 # the delete method can be inherited from FS::Record
88 =item replace OLD_RECORD
90 Replaces the OLD_RECORD with this one in the database. If there is an error,
91 returns the error, otherwise returns false.
95 # the replace method can be inherited from FS::Record
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
105 # the check method should currently be supplied - FS::Record contains some
106 # data checking routines
112 $self->ut_numbern('batchnum')
113 || $self->ut_enum('payby', [ 'CARD', 'CHEK' ])
114 || $self->ut_enum('status', [ 'O', 'I', 'R' ])
116 return $error if $error;
135 $self->status(shift);
136 $self->download(time)
137 if $self->status eq 'I' && ! $self->download;
139 if $self->status eq 'R' && ! $self->upload;
143 # further false laziness
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$/;
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
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";
164 if(!keys(%$import)) {
165 warn "no \%import_info found in FS::pay_batch::$mod (skipping)\n";
168 $import_info{$name} = $import;
170 if(!keys(%$export)) {
171 warn "no \%export_info found in FS::pay_batch::$mod (skipping)\n";
174 $export_info{$name} = $export;
179 =item import_results OPTION => VALUE, ...
181 Import batch results.
185 I<filehandle> - open filehandle of results file.
187 I<format> - "csv-td_canada_trust-merchant_pc_batch", "csv-chase_canada-E-xactBatch", "ach-spiritone", or "PAP"
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";
200 my $job = $param->{'job'};
201 $job->update_statustext(0) if $job;
203 my $conf = new FS::Conf;
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
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'};
219 my $csv = new Text::CSV_XS;
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';
228 my $oldAutoCommit = $FS::UID::AutoCommit;
229 local $FS::UID::AutoCommit = 0;
232 my $reself = $self->select_for_update;
234 if ( $reself->status ne 'I'
235 and !$conf->exists('batch-manual_approval') ) {
236 $dbh->rollback if $oldAutoCommit;
237 return "batchnum ". $self->batchnum. "no longer in transit";
243 # Order of operations has been changed here.
244 # We now slurp everything into @all_values, then
245 # process one line at a time.
247 if ($filetype eq 'XML') {
248 eval "use XML::Simple";
250 my @xmlkeys = @{ $info->{'xmlkeys'} }; # for XML
251 my $xmlrow = $info->{'xmlrow'}; # also for XML
253 # Do everything differently.
254 my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
256 # $xmlrow = [ RootKey, FirstLevelKey, SecondLevelKey... ]
257 $rows = $rows->{$_} foreach( @$xmlrow );
258 if(!defined($rows)) {
259 $dbh->rollback if $oldAutoCommit;
260 return "can't find rows in XML file";
262 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
263 foreach my $row (@$rows) {
264 push @all_values, [ @{$row}{@xmlkeys}, $row ];
268 while ( defined($line=<$fh>) ) {
270 next if $line =~ /^\s*$/; #skip blank lines
272 if ($filetype eq "CSV") {
273 $csv->parse($line) or do {
274 $dbh->rollback if $oldAutoCommit;
275 return "can't parse: ". $csv->error_input();
277 push @all_values, [ $csv->fields(), $line ];
278 }elsif ($filetype eq 'fixed'){
279 my @values = ( $line =~ /$formatre/ );
281 $dbh->rollback if $oldAutoCommit;
282 return "can't parse: ". $line;
285 push @all_values, \@values;
287 elsif ($filetype eq 'variable') {
288 my @values = ( eval { $parse->($self, $line) } );
290 $dbh->rollback if $oldAutoCommit;
294 push @all_values, \@values;
297 $dbh->rollback if $oldAutoCommit;
298 return "Unknown file type $filetype";
304 foreach (@all_values) {
307 $job->update_statustext(int(100 * $num/scalar(@all_values)));
312 my $line = pop @values;
313 foreach my $field ( @fields ) {
314 my $value = shift @values;
316 $hash{$field} = $value;
319 if ( defined($begin_condition) ) {
320 if ( &{$begin_condition}(\%hash, $line) ) {
321 undef $begin_condition;
328 if ( defined($end_condition) and &{$end_condition}(\%hash, $line) ) {
330 $error = &{$end_hook}(\%hash, $total, $line) if defined($end_hook);
332 $dbh->rollback if $oldAutoCommit;
338 if ( defined($skip_condition) and &{$skip_condition}(\%hash, $line) ) {
343 qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
344 unless ( $cust_pay_batch ) {
345 return "unknown paybatchnum $hash{'paybatchnum'}\n";
347 my $custnum = $cust_pay_batch->custnum,
348 my $payby = $cust_pay_batch->payby,
350 &{$hook}(\%hash, $cust_pay_batch->hashref);
352 my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
355 if ( &{$approved_condition}(\%hash) ) {
357 foreach ('paid', '_date', 'payinfo') {
358 $new_cust_pay_batch->$_($hash{$_}) if $hash{$_};
360 $error = $new_cust_pay_batch->approve($hash{'paybatch'} || $self->batchnum);
361 $total += $hash{'paid'};
363 } elsif ( &{$declined_condition}(\%hash) ) {
365 $error = $new_cust_pay_batch->decline;
370 $dbh->rollback if $oldAutoCommit;
374 # purge CVV when the batch is processed
375 if ( $payby =~ /^(CARD|DCRD)$/ ) {
376 my $payinfo = $hash{'payinfo'} || $cust_pay_batch->payinfo;
377 if ( ! grep { $_ eq cardtype($payinfo) }
378 $conf->config('cvv-save') ) {
379 $new_cust_pay_batch->cust_main->remove_cvv;
384 } # foreach (@all_values)
387 if ( defined($close_condition) ) {
388 # Allow the module to decide whether to close the batch.
389 # $close_condition can also die() to abort the whole import.
390 $close = eval { $close_condition->($self) };
397 my $error = $self->set_status('R');
399 $dbh->rollback if $oldAutoCommit;
404 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
412 sub process_import_results {
414 my $param = thaw(decode_base64(shift));
415 $param->{'job'} = $job;
416 warn Dumper($param) if $DEBUG;
417 my $batchnum = delete $param->{'batchnum'} or die "no batchnum specified\n";
418 my $batch = FS::pay_batch->by_key($batchnum) or die "batchnum '$batchnum' not found\n";
420 my $file = $param->{'uploaded_files'} or die "no files provided\n";
421 $file =~ s/^(\w+):([\.\w]+)$/$2/;
422 my $dir = '%%%FREESIDE_CACHE%%%/cache.' . $FS::UID::datasrc;
423 open( $param->{'filehandle'},
426 or die "unable to open '$file'.\n";
427 my $error = $batch->import_results($param);
429 die $error if $error;
432 # Formerly httemplate/misc/download-batch.cgi
435 my $conf = new FS::Conf;
436 my $format = shift || $conf->config('batch-default_format')
437 or die "No batch format configured\n";
438 my $info = $export_info{$format} or die "Format not found: '$format'\n";
439 &{$info->{'init'}}($conf) if exists($info->{'init'});
441 my $curuser = $FS::CurrentUser::CurrentUser;
443 my $oldAutoCommit = $FS::UID::AutoCommit;
444 local $FS::UID::AutoCommit = 0;
448 my $status = $self->status;
449 if ($status eq 'O') {
451 my $error = $self->set_status('I');
452 die "error updating pay_batch status: $error\n" if $error;
453 } elsif ($status eq 'I' && $curuser->access_right('Reprocess batches')) {
456 die "No pending batch.\n";
463 my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
464 qsearch('cust_pay_batch', { batchnum => $self->batchnum } );
466 # handle batch-increment_expiration option
467 if ( $self->payby eq 'CARD' ) {
468 my ($cmon, $cyear) = (localtime(time))[4,5];
469 foreach (@cust_pay_batch) {
470 my $etime = str2time($_->exp) or next;
471 my ($day, $mon, $year) = (localtime($etime))[3,4,5];
472 if( $conf->exists('batch-increment_expiration') ) {
473 $year++ while( $year < $cyear or ($year == $cyear and $mon <= $cmon) );
474 $_->exp( sprintf('%4u-%02u-%02u', $year + 1900, $mon+1, $day) );
476 $_->setfield('expmmyy', sprintf('%02u%02u', $mon+1, $year % 100));
480 my $delim = exists($info->{'delimiter'}) ? $info->{'delimiter'} : "\n";
482 my $h = $info->{'header'};
483 if(ref($h) eq 'CODE') {
484 $batch .= &$h($self, \@cust_pay_batch) . $delim;
487 $batch .= $h . $delim;
489 foreach my $cust_pay_batch (@cust_pay_batch) {
491 if ($first_download) {
492 my $balance = $cust_pay_batch->cust_main->balance;
493 if ($balance <= 0) { # then don't charge this customer
494 my $error = $cust_pay_batch->delete;
496 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
500 } elsif ($balance < $cust_pay_batch->amount) {
501 # reduce the charge to the remaining balance
502 $cust_pay_batch->amount($balance);
503 my $error = $cust_pay_batch->replace;
505 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
509 # else $balance >= $cust_pay_batch->amount
513 $batchtotal += $cust_pay_batch->amount;
514 $batch .= &{$info->{'row'}}($cust_pay_batch, $self, $batchcount, $batchtotal) . $delim;
518 my $f = $info->{'footer'};
519 if(ref($f) eq 'CODE') {
520 $batch .= &$f($self, $batchcount, $batchtotal) . $delim;
523 $batch .= $f . $delim;
526 if ($info->{'autopost'}) {
527 my $error = &{$info->{'autopost'}}($self, $batch);
529 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
534 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
542 my $paybatch = $opt{'paybatch'} || $self->batchnum;
543 my $usernum = $opt{'usernum'} || die "manual approval requires a usernum";
544 my $conf = FS::Conf->new;
545 return 'manual batch approval disabled'
546 if ( ! $conf->exists('batch-manual_approval') );
547 return 'batch already resolved' if $self->status eq 'R';
548 return 'batch not yet submitted' if $self->status eq 'O';
550 local $SIG{HUP} = 'IGNORE';
551 local $SIG{INT} = 'IGNORE';
552 local $SIG{QUIT} = 'IGNORE';
553 local $SIG{TERM} = 'IGNORE';
554 local $SIG{TSTP} = 'IGNORE';
555 local $SIG{PIPE} = 'IGNORE';
557 my $oldAutoCommit = $FS::UID::AutoCommit;
558 local $FS::UID::AutoCommit = 0;
562 foreach my $cust_pay_batch (
563 qsearch('cust_pay_batch', { batchnum => $self->batchnum,
566 my $new_cust_pay_batch = new FS::cust_pay_batch {
567 $cust_pay_batch->hash,
568 'paid' => $cust_pay_batch->amount,
570 'usernum' => $usernum,
572 my $error = $new_cust_pay_batch->approve($paybatch);
575 return 'paybatchnum '.$cust_pay_batch->paybatchnum.": $error";
579 $self->set_status('R');
588 status is somewhat redundant now that download and upload exist
592 L<FS::Record>, schema.html from the base documentation.