4 use vars qw( @ISA $DEBUG %import_info %export_info $conf );
7 use FS::Record qw( dbh qsearch qsearchs );
11 use Date::Parse qw(str2time);
12 use Business::CreditCard qw(cardtype);
14 @ISA = qw(FS::Record);
18 FS::pay_batch - Object methods for pay_batch records
24 $record = new FS::pay_batch \%hash;
25 $record = new FS::pay_batch { 'column' => 'value' };
27 $error = $record->insert;
29 $error = $new_record->replace($old_record);
31 $error = $record->delete;
33 $error = $record->check;
37 An FS::pay_batch object represents an payment batch. FS::pay_batch inherits
38 from FS::Record. The following fields are currently supported:
42 =item batchnum - primary key
44 =item agentnum - optional agent number for agent batches
46 =item payby - CARD or CHEK
48 =item status - O (Open), I (In-transit), or R (Resolved)
63 Creates a new batch. To add the batch to the database, see L<"insert">.
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.
70 # the new method can be inherited from FS::Record, if a table method is defined
72 sub table { 'pay_batch'; }
76 Adds this record to the database. If there is an error, returns the error,
77 otherwise returns false.
81 # the insert method can be inherited from FS::Record
85 Delete this record from the database.
89 # the delete method can be inherited from FS::Record
91 =item replace OLD_RECORD
93 Replaces the OLD_RECORD with this one in the database. If there is an error,
94 returns the error, otherwise returns false.
98 # the replace method can be inherited from FS::Record
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
108 # the check method should currently be supplied - FS::Record contains some
109 # data checking routines
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')
120 return $error if $error;
127 Returns the L<FS::agent> object for this template.
132 qsearchs('agent', { 'agentnum' => $_[0]->agentnum });
149 $self->status(shift);
150 $self->download(time)
151 if $self->status eq 'I' && ! $self->download;
153 if $self->status eq 'R' && ! $self->upload;
157 # further false laziness
159 %import_info = %export_info = ();
160 foreach my $INC (@INC) {
161 warn "globbing $INC/FS/pay_batch/*.pm\n" if $DEBUG;
162 foreach my $file ( glob("$INC/FS/pay_batch/*.pm")) {
163 warn "attempting to load batch format from $file\n" if $DEBUG;
164 $file =~ /\/(\w+)\.pm$/;
167 my ($import, $export, $name) =
168 eval "use FS::pay_batch::$mod;
169 ( \\%FS::pay_batch::$mod\::import_info,
170 \\%FS::pay_batch::$mod\::export_info,
171 \$FS::pay_batch::$mod\::name)";
172 $name ||= $mod; # in case it's not defined
174 # in FS::cdr this is a die, not a warn. That's probably a bug.
175 warn "error using FS::pay_batch::$mod (skipping): $@\n";
178 if(!keys(%$import)) {
179 warn "no \%import_info found in FS::pay_batch::$mod (skipping)\n";
182 $import_info{$name} = $import;
184 if(!keys(%$export)) {
185 warn "no \%export_info found in FS::pay_batch::$mod (skipping)\n";
188 $export_info{$name} = $export;
193 =item import_results OPTION => VALUE, ...
195 Import batch results.
199 I<filehandle> - open filehandle of results file.
201 I<format> - "csv-td_canada_trust-merchant_pc_batch", "csv-chase_canada-E-xactBatch", "ach-spiritone", or "PAP"
208 my $param = ref($_[0]) ? shift : { @_ };
209 my $fh = $param->{'filehandle'};
210 my $format = $param->{'format'};
211 my $info = $import_info{$format}
212 or die "unknown format $format";
214 my $job = $param->{'job'};
215 $job->update_statustext(0) if $job;
217 my $conf = new FS::Conf;
219 my $filetype = $info->{'filetype'}; # CSV, fixed, variable
220 my @fields = @{ $info->{'fields'}};
221 my $formatre = $info->{'formatre'}; # for fixed
222 my $parse = $info->{'parse'}; # for variable
224 my $begin_condition = $info->{'begin_condition'};
225 my $end_condition = $info->{'end_condition'};
226 my $end_hook = $info->{'end_hook'};
227 my $skip_condition = $info->{'skip_condition'};
228 my $hook = $info->{'hook'};
229 my $approved_condition = $info->{'approved'};
230 my $declined_condition = $info->{'declined'};
231 my $close_condition = $info->{'close_condition'};
233 my $csv = new Text::CSV_XS;
235 local $SIG{HUP} = 'IGNORE';
236 local $SIG{INT} = 'IGNORE';
237 local $SIG{QUIT} = 'IGNORE';
238 local $SIG{TERM} = 'IGNORE';
239 local $SIG{TSTP} = 'IGNORE';
240 local $SIG{PIPE} = 'IGNORE';
242 my $oldAutoCommit = $FS::UID::AutoCommit;
243 local $FS::UID::AutoCommit = 0;
246 my $reself = $self->select_for_update;
248 if ( $reself->status ne 'I'
249 and !$conf->exists('batch-manual_approval') ) {
250 $dbh->rollback if $oldAutoCommit;
251 return "batchnum ". $self->batchnum. "no longer in transit";
257 # Order of operations has been changed here.
258 # We now slurp everything into @all_values, then
259 # process one line at a time.
261 if ($filetype eq 'XML') {
262 eval "use XML::Simple";
264 my @xmlkeys = @{ $info->{'xmlkeys'} }; # for XML
265 my $xmlrow = $info->{'xmlrow'}; # also for XML
267 # Do everything differently.
268 my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
270 # $xmlrow = [ RootKey, FirstLevelKey, SecondLevelKey... ]
271 $rows = $rows->{$_} foreach( @$xmlrow );
272 if(!defined($rows)) {
273 $dbh->rollback if $oldAutoCommit;
274 return "can't find rows in XML file";
276 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
277 foreach my $row (@$rows) {
278 push @all_values, [ @{$row}{@xmlkeys}, $row ];
282 while ( defined($line=<$fh>) ) {
284 next if $line =~ /^\s*$/; #skip blank lines
286 if ($filetype eq "CSV") {
287 $csv->parse($line) or do {
288 $dbh->rollback if $oldAutoCommit;
289 return "can't parse: ". $csv->error_input();
291 push @all_values, [ $csv->fields(), $line ];
292 }elsif ($filetype eq 'fixed'){
293 my @values = ( $line =~ /$formatre/ );
295 $dbh->rollback if $oldAutoCommit;
296 return "can't parse: ". $line;
299 push @all_values, \@values;
301 elsif ($filetype eq 'variable') {
302 my @values = ( eval { $parse->($self, $line) } );
304 $dbh->rollback if $oldAutoCommit;
308 push @all_values, \@values;
311 $dbh->rollback if $oldAutoCommit;
312 return "Unknown file type $filetype";
318 foreach (@all_values) {
321 $job->update_statustext(int(100 * $num/scalar(@all_values)));
326 my $line = pop @values;
327 foreach my $field ( @fields ) {
328 my $value = shift @values;
330 $hash{$field} = $value;
333 if ( defined($begin_condition) ) {
334 if ( &{$begin_condition}(\%hash, $line) ) {
335 undef $begin_condition;
342 if ( defined($end_condition) and &{$end_condition}(\%hash, $line) ) {
344 $error = &{$end_hook}(\%hash, $total, $line) if defined($end_hook);
346 $dbh->rollback if $oldAutoCommit;
352 if ( defined($skip_condition) and &{$skip_condition}(\%hash, $line) ) {
357 qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
358 unless ( $cust_pay_batch ) {
359 return "unknown paybatchnum $hash{'paybatchnum'}\n";
361 my $custnum = $cust_pay_batch->custnum,
362 my $payby = $cust_pay_batch->payby,
364 &{$hook}(\%hash, $cust_pay_batch->hashref);
366 my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
369 if ( &{$approved_condition}(\%hash) ) {
371 foreach ('paid', '_date', 'payinfo') {
372 $new_cust_pay_batch->$_($hash{$_}) if $hash{$_};
374 $error = $new_cust_pay_batch->approve($hash{'paybatch'});
375 $total += $hash{'paid'};
377 } elsif ( &{$declined_condition}(\%hash) ) {
379 $error = $new_cust_pay_batch->decline($hash{'error_message'});;
384 $dbh->rollback if $oldAutoCommit;
388 # purge CVV when the batch is processed
389 if ( $payby =~ /^(CARD|DCRD)$/ ) {
390 my $payinfo = $hash{'payinfo'} || $cust_pay_batch->payinfo;
391 if ( ! grep { $_ eq cardtype($payinfo) }
392 $conf->config('cvv-save') ) {
393 $new_cust_pay_batch->cust_main->remove_cvv;
398 } # foreach (@all_values)
401 if ( defined($close_condition) ) {
402 # Allow the module to decide whether to close the batch.
403 # $close_condition can also die() to abort the whole import.
404 $close = eval { $close_condition->($self) };
411 my $error = $self->set_status('R');
413 $dbh->rollback if $oldAutoCommit;
418 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
426 sub process_import_results {
428 my $param = thaw(decode_base64(shift));
429 $param->{'job'} = $job;
430 warn Dumper($param) if $DEBUG;
431 my $batchnum = delete $param->{'batchnum'} or die "no batchnum specified\n";
432 my $batch = FS::pay_batch->by_key($batchnum) or die "batchnum '$batchnum' not found\n";
434 my $file = $param->{'uploaded_files'} or die "no files provided\n";
435 $file =~ s/^(\w+):([\.\w]+)$/$2/;
436 my $dir = '%%%FREESIDE_CACHE%%%/cache.' . $FS::UID::datasrc;
437 open( $param->{'filehandle'},
440 or die "unable to open '$file'.\n";
441 my $error = $batch->import_results($param);
443 die $error if $error;
446 # Formerly httemplate/misc/download-batch.cgi
449 my $conf = new FS::Conf;
450 my $format = shift || $conf->config('batch-default_format')
451 or die "No batch format configured\n";
452 my $info = $export_info{$format} or die "Format not found: '$format'\n";
453 &{$info->{'init'}}($conf) if exists($info->{'init'});
455 my $curuser = $FS::CurrentUser::CurrentUser;
457 my $oldAutoCommit = $FS::UID::AutoCommit;
458 local $FS::UID::AutoCommit = 0;
462 my $status = $self->status;
463 if ($status eq 'O') {
465 my $error = $self->set_status('I');
466 die "error updating pay_batch status: $error\n" if $error;
467 } elsif ($status eq 'I' && $curuser->access_right('Reprocess batches')) {
470 die "No pending batch.\n";
477 my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
478 qsearch('cust_pay_batch', { batchnum => $self->batchnum } );
480 # handle batch-increment_expiration option
481 if ( $self->payby eq 'CARD' ) {
482 my ($cmon, $cyear) = (localtime(time))[4,5];
483 foreach (@cust_pay_batch) {
484 my $etime = str2time($_->exp) or next;
485 my ($day, $mon, $year) = (localtime($etime))[3,4,5];
486 if( $conf->exists('batch-increment_expiration') ) {
487 $year++ while( $year < $cyear or ($year == $cyear and $mon <= $cmon) );
488 $_->exp( sprintf('%4u-%02u-%02u', $year + 1900, $mon+1, $day) );
490 $_->setfield('expmmyy', sprintf('%02u%02u', $mon+1, $year % 100));
494 if ($first_download) { #remove or reduce entries if customer's balance changed
497 foreach my $cust_pay_batch (@cust_pay_batch) {
499 my $balance = $cust_pay_batch->cust_main->balance;
500 if ($balance <= 0) { # then don't charge this customer
501 my $error = $cust_pay_batch->delete;
503 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
507 } elsif ($balance < $cust_pay_batch->amount) {
508 # reduce the charge to the remaining balance
509 $cust_pay_batch->amount($balance);
510 my $error = $cust_pay_batch->replace;
512 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
516 # else $balance >= $cust_pay_batch->amount
518 push @new, $cust_pay_batch;
520 @cust_pay_batch = @new;
524 my $delim = exists($info->{'delimiter'}) ? $info->{'delimiter'} : "\n";
526 my $h = $info->{'header'};
527 if (ref($h) eq 'CODE') {
528 $batch .= &$h($self, \@cust_pay_batch). $delim;
530 $batch .= $h. $delim;
533 foreach my $cust_pay_batch (@cust_pay_batch) {
535 $batchtotal += $cust_pay_batch->amount;
537 &{$info->{'row'}}($cust_pay_batch, $self, $batchcount, $batchtotal).
541 my $f = $info->{'footer'};
542 if (ref($f) eq 'CODE') {
543 $batch .= &$f($self, $batchcount, $batchtotal). $delim;
545 $batch .= $f. $delim;
548 if ($info->{'autopost'}) {
549 my $error = &{$info->{'autopost'}}($self, $batch);
551 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
556 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
564 my $usernum = $opt{'usernum'} || die "manual approval requires a usernum";
565 my $conf = FS::Conf->new;
566 return 'manual batch approval disabled'
567 if ( ! $conf->exists('batch-manual_approval') );
568 return 'batch already resolved' if $self->status eq 'R';
569 return 'batch not yet submitted' if $self->status eq 'O';
571 local $SIG{HUP} = 'IGNORE';
572 local $SIG{INT} = 'IGNORE';
573 local $SIG{QUIT} = 'IGNORE';
574 local $SIG{TERM} = 'IGNORE';
575 local $SIG{TSTP} = 'IGNORE';
576 local $SIG{PIPE} = 'IGNORE';
578 my $oldAutoCommit = $FS::UID::AutoCommit;
579 local $FS::UID::AutoCommit = 0;
583 foreach my $cust_pay_batch (
584 qsearch('cust_pay_batch', { batchnum => $self->batchnum,
587 my $new_cust_pay_batch = new FS::cust_pay_batch {
588 $cust_pay_batch->hash,
589 'paid' => $cust_pay_batch->amount,
591 'usernum' => $usernum,
593 my $error = $new_cust_pay_batch->approve();
594 # there are no approval options here (authorization, order_number, etc.)
595 # because the transaction wasn't really approved
598 return 'paybatchnum '.$cust_pay_batch->paybatchnum.": $error";
602 $self->set_status('R');
611 status is somewhat redundant now that download and upload exist
615 L<FS::Record>, schema.html from the base documentation.