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;
139 $self->status(shift);
140 $self->download(time)
141 if $self->status eq 'I' && ! $self->download;
143 if $self->status eq 'R' && ! $self->upload;
147 # further false laziness
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$/;
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
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";
168 if(!keys(%$import)) {
169 warn "no \%import_info found in FS::pay_batch::$mod (skipping)\n";
172 $import_info{$name} = $import;
174 if(!keys(%$export)) {
175 warn "no \%export_info found in FS::pay_batch::$mod (skipping)\n";
178 $export_info{$name} = $export;
183 =item import_results OPTION => VALUE, ...
185 Import batch results.
189 I<filehandle> - open filehandle of results file.
191 I<format> - "csv-td_canada_trust-merchant_pc_batch", "csv-chase_canada-E-xactBatch", "ach-spiritone", or "PAP"
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";
204 my $job = $param->{'job'};
205 $job->update_statustext(0) if $job;
207 my $conf = new FS::Conf;
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
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'};
223 my $csv = new Text::CSV_XS;
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';
232 my $oldAutoCommit = $FS::UID::AutoCommit;
233 local $FS::UID::AutoCommit = 0;
236 my $reself = $self->select_for_update;
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";
247 # Order of operations has been changed here.
248 # We now slurp everything into @all_values, then
249 # process one line at a time.
251 if ($filetype eq 'XML') {
252 eval "use XML::Simple";
254 my @xmlkeys = @{ $info->{'xmlkeys'} }; # for XML
255 my $xmlrow = $info->{'xmlrow'}; # also for XML
257 # Do everything differently.
258 my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
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";
266 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
267 foreach my $row (@$rows) {
268 push @all_values, [ @{$row}{@xmlkeys}, $row ];
272 while ( defined($line=<$fh>) ) {
274 next if $line =~ /^\s*$/; #skip blank lines
276 if ($filetype eq "CSV") {
277 $csv->parse($line) or do {
278 $dbh->rollback if $oldAutoCommit;
279 return "can't parse: ". $csv->error_input();
281 push @all_values, [ $csv->fields(), $line ];
282 }elsif ($filetype eq 'fixed'){
283 my @values = ( $line =~ /$formatre/ );
285 $dbh->rollback if $oldAutoCommit;
286 return "can't parse: ". $line;
289 push @all_values, \@values;
291 elsif ($filetype eq 'variable') {
292 my @values = ( eval { $parse->($self, $line) } );
294 $dbh->rollback if $oldAutoCommit;
298 push @all_values, \@values;
301 $dbh->rollback if $oldAutoCommit;
302 return "Unknown file type $filetype";
308 foreach (@all_values) {
311 $job->update_statustext(int(100 * $num/scalar(@all_values)));
316 my $line = pop @values;
317 foreach my $field ( @fields ) {
318 my $value = shift @values;
320 $hash{$field} = $value;
323 if ( defined($begin_condition) ) {
324 if ( &{$begin_condition}(\%hash, $line) ) {
325 undef $begin_condition;
332 if ( defined($end_condition) and &{$end_condition}(\%hash, $line) ) {
334 $error = &{$end_hook}(\%hash, $total, $line) if defined($end_hook);
336 $dbh->rollback if $oldAutoCommit;
342 if ( defined($skip_condition) and &{$skip_condition}(\%hash, $line) ) {
347 qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
348 unless ( $cust_pay_batch ) {
349 return "unknown paybatchnum $hash{'paybatchnum'}\n";
351 my $custnum = $cust_pay_batch->custnum,
352 my $payby = $cust_pay_batch->payby,
354 &{$hook}(\%hash, $cust_pay_batch->hashref);
356 my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
359 if ( &{$approved_condition}(\%hash) ) {
361 foreach ('paid', '_date', 'payinfo') {
362 $new_cust_pay_batch->$_($hash{$_}) if $hash{$_};
364 $error = $new_cust_pay_batch->approve($hash{'paybatch'} || $self->batchnum);
365 $total += $hash{'paid'};
367 } elsif ( &{$declined_condition}(\%hash) ) {
369 $error = $new_cust_pay_batch->decline;
374 $dbh->rollback if $oldAutoCommit;
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;
388 } # foreach (@all_values)
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) };
401 my $error = $self->set_status('R');
403 $dbh->rollback if $oldAutoCommit;
408 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
416 sub process_import_results {
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";
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'},
430 or die "unable to open '$file'.\n";
431 my $error = $batch->import_results($param);
433 die $error if $error;
436 # Formerly httemplate/misc/download-batch.cgi
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'});
445 my $curuser = $FS::CurrentUser::CurrentUser;
447 my $oldAutoCommit = $FS::UID::AutoCommit;
448 local $FS::UID::AutoCommit = 0;
452 my $status = $self->status;
453 if ($status eq 'O') {
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')) {
460 die "No pending batch.\n";
467 my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
468 qsearch('cust_pay_batch', { batchnum => $self->batchnum } );
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) );
480 $_->setfield('expmmyy', sprintf('%02u%02u', $mon+1, $year % 100));
484 if ($first_download) { #remove or reduce entries if customer's balance changed
487 foreach my $cust_pay_batch (@cust_pay_batch) {
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;
493 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
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;
502 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
506 # else $balance >= $cust_pay_batch->amount
508 push @new, $cust_pay_batch;
510 @cust_pay_batch = @new;
514 my $delim = exists($info->{'delimiter'}) ? $info->{'delimiter'} : "\n";
516 my $h = $info->{'header'};
517 if (ref($h) eq 'CODE') {
518 $batch .= &$h($self, \@cust_pay_batch). $delim;
520 $batch .= $h. $delim;
523 foreach my $cust_pay_batch (@cust_pay_batch) {
525 $batchtotal += $cust_pay_batch->amount;
527 &{$info->{'row'}}($cust_pay_batch, $self, $batchcount, $batchtotal).
531 my $f = $info->{'footer'};
532 if (ref($f) eq 'CODE') {
533 $batch .= &$f($self, $batchcount, $batchtotal). $delim;
535 $batch .= $f. $delim;
538 if ($info->{'autopost'}) {
539 my $error = &{$info->{'autopost'}}($self, $batch);
541 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
546 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
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';
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';
569 my $oldAutoCommit = $FS::UID::AutoCommit;
570 local $FS::UID::AutoCommit = 0;
574 foreach my $cust_pay_batch (
575 qsearch('cust_pay_batch', { batchnum => $self->batchnum,
578 my $new_cust_pay_batch = new FS::cust_pay_batch {
579 $cust_pay_batch->hash,
580 'paid' => $cust_pay_batch->amount,
582 'usernum' => $usernum,
584 my $error = $new_cust_pay_batch->approve($paybatch);
587 return 'paybatchnum '.$cust_pay_batch->paybatchnum.": $error";
591 $self->set_status('R');
600 status is somewhat redundant now that download and upload exist
604 L<FS::Record>, schema.html from the base documentation.