2 use base qw( FS::Record );
5 use vars qw( $DEBUG %import_info %export_info $conf );
6 use Scalar::Util qw(blessed);
8 use List::Util qw(sum);
11 use Date::Parse qw(str2time);
12 use Business::CreditCard qw(cardtype);
13 use FS::Misc qw(send_email); # for error notification
14 use FS::Record qw( dbh qsearch qsearchs );
20 FS::pay_batch - Object methods for pay_batch records
26 $record = new FS::pay_batch \%hash;
27 $record = new FS::pay_batch { 'column' => 'value' };
29 $error = $record->insert;
31 $error = $new_record->replace($old_record);
33 $error = $record->delete;
35 $error = $record->check;
39 An FS::pay_batch object represents an payment batch. FS::pay_batch inherits
40 from FS::Record. The following fields are currently supported:
44 =item batchnum - primary key
46 =item agentnum - optional agent number for agent batches
48 =item payby - CARD or CHEK
50 =item status - O (Open), I (In-transit), or R (Resolved)
52 =item download - time when the batch was first downloaded
54 =item upload - time when the batch was first uploaded
56 =item title - unique batch identifier
58 For incoming batches, the combination of 'title', 'payby', and 'agentnum'
69 Creates a new batch. To add the batch to the database, see L<"insert">.
71 Note that this stores the hash reference, not a distinct copy of the hash it
72 points to. You can ask the object for a copy with the I<hash> method.
76 # the new method can be inherited from FS::Record, if a table method is defined
78 sub table { 'pay_batch'; }
82 Adds this record to the database. If there is an error, returns the error,
83 otherwise returns false.
87 # the insert method can be inherited from FS::Record
91 Delete this record from the database.
95 # the delete method can be inherited from FS::Record
97 =item replace OLD_RECORD
99 Replaces the OLD_RECORD with this one in the database. If there is an error,
100 returns the error, otherwise returns false.
104 # the replace method can be inherited from FS::Record
108 Checks all fields to make sure this is a valid batch. If there is
109 an error, returns the error, otherwise returns false. Called by the insert
114 # the check method should currently be supplied - FS::Record contains some
115 # data checking routines
121 $self->ut_numbern('batchnum')
122 || $self->ut_enum('payby', [ 'CARD', 'CHEK' ])
123 || $self->ut_enum('status', [ 'O', 'I', 'R' ])
124 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
125 || $self->ut_alphan('title')
127 return $error if $error;
129 if ( $self->title ) {
131 grep { !$self->batchnum or $_->batchnum != $self->batchnum }
132 qsearch('pay_batch', {
133 payby => $self->payby,
134 agentnum => $self->agentnum,
135 title => $self->title,
137 return "Batch already exists as batchnum ".$existing[0]->batchnum
146 Returns the L<FS::agent> object for this batch.
150 Returns all L<FS::cust_pay_batch> objects for this batch.
166 $self->status(shift);
167 $self->download(time)
168 if $self->status eq 'I' && ! $self->download;
170 if $self->status eq 'R' && ! $self->upload;
174 # further false laziness
176 %import_info = %export_info = ();
177 foreach my $INC (@INC) {
178 warn "globbing $INC/FS/pay_batch/*.pm\n" if $DEBUG;
179 foreach my $file ( glob("$INC/FS/pay_batch/*.pm")) {
180 warn "attempting to load batch format from $file\n" if $DEBUG;
181 $file =~ /\/(\w+)\.pm$/;
184 my ($import, $export, $name) =
185 eval "use FS::pay_batch::$mod;
186 ( \\%FS::pay_batch::$mod\::import_info,
187 \\%FS::pay_batch::$mod\::export_info,
188 \$FS::pay_batch::$mod\::name)";
189 $name ||= $mod; # in case it's not defined
191 # in FS::cdr this is a die, not a warn. That's probably a bug.
192 warn "error using FS::pay_batch::$mod (skipping): $@\n";
195 if(!keys(%$import)) {
196 warn "no \%import_info found in FS::pay_batch::$mod (skipping)\n";
199 $import_info{$name} = $import;
201 if(!keys(%$export)) {
202 warn "no \%export_info found in FS::pay_batch::$mod (skipping)\n";
205 $export_info{$name} = $export;
210 =item import_results OPTION => VALUE, ...
212 Import batch results.
216 I<filehandle> - open filehandle of results file.
218 I<format> - an L<FS::pay_batch> module
220 I<gateway> - an L<FS::payment_gateway> object for a batch gateway. This
221 takes precedence over I<format>.
223 Supported format keys (defined in the specified FS::pay_batch module) are:
225 I<filetype> - required, can be CSV, fixed, variable, XML
227 I<fields> - required list of field names for each row/line
229 I<formatre> - regular expression for fixed filetype
231 I<parse> - required for variable filetype
233 I<xmlkeys> - required for XML filetype
235 I<xmlrow> - required for XML filetype
237 I<begin_condition> - sub, ignore all lines before this returns true
239 I<end_condition> - sub, stop processing lines when this returns true
241 I<end_hook> - sub, runs immediately after end_condition returns true
243 I<skip_condition> - sub, skip lines when this returns true
245 I<hook> - required, sub, runs before approved/declined conditions are checked
247 I<approved> - required, sub, returns true when approved
249 I<declined> - required, sub, returns true when declined
251 I<close_condition> - sub, decide whether or not to close the batch
258 my $param = ref($_[0]) ? shift : { @_ };
259 my $fh = $param->{'filehandle'};
260 my $job = $param->{'job'};
261 $job->update_statustext(0) if $job;
263 my $format = $param->{'format'};
264 my $info = $import_info{$format}
265 or die "unknown format $format";
267 my $conf = new FS::Conf;
269 my $filetype = $info->{'filetype'}; # CSV, fixed, variable
270 my @fields = @{ $info->{'fields'}};
271 my $formatre = $info->{'formatre'}; # for fixed
272 my $parse = $info->{'parse'}; # for variable
274 my $begin_condition = $info->{'begin_condition'};
275 my $end_condition = $info->{'end_condition'};
276 my $end_hook = $info->{'end_hook'};
277 my $skip_condition = $info->{'skip_condition'};
278 my $hook = $info->{'hook'};
279 my $approved_condition = $info->{'approved'};
280 my $declined_condition = $info->{'declined'};
281 my $close_condition = $info->{'close_condition'};
283 my $csv = new Text::CSV_XS;
285 local $SIG{HUP} = 'IGNORE';
286 local $SIG{INT} = 'IGNORE';
287 local $SIG{QUIT} = 'IGNORE';
288 local $SIG{TERM} = 'IGNORE';
289 local $SIG{TSTP} = 'IGNORE';
290 local $SIG{PIPE} = 'IGNORE';
292 my $oldAutoCommit = $FS::UID::AutoCommit;
293 local $FS::UID::AutoCommit = 0;
296 my $reself = $self->select_for_update;
298 if ( $reself->status ne 'I'
299 and !$conf->exists('batch-manual_approval') ) {
300 $dbh->rollback if $oldAutoCommit;
301 return "batchnum ". $self->batchnum. "no longer in transit";
307 if ($filetype eq 'XML') {
308 eval "use XML::Simple";
310 my @xmlkeys = @{ $info->{'xmlkeys'} }; # for XML
311 my $xmlrow = $info->{'xmlrow'}; # also for XML
313 # Do everything differently.
314 my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
316 # $xmlrow = [ RootKey, FirstLevelKey, SecondLevelKey... ]
317 $rows = $rows->{$_} foreach( @$xmlrow );
318 if(!defined($rows)) {
319 $dbh->rollback if $oldAutoCommit;
320 return "can't find rows in XML file";
322 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
323 foreach my $row (@$rows) {
324 push @all_values, [ @{$row}{@xmlkeys}, $row ];
328 while ( defined($line=<$fh>) ) {
330 next if $line =~ /^\s*$/; #skip blank lines
332 if ($filetype eq "CSV") {
333 $csv->parse($line) or do {
334 $dbh->rollback if $oldAutoCommit;
335 return "can't parse: ". $csv->error_input();
337 push @all_values, [ $csv->fields(), $line ];
338 }elsif ($filetype eq 'fixed'){
339 my @values = ( $line =~ /$formatre/ );
341 $dbh->rollback if $oldAutoCommit;
342 return "can't parse: ". $line;
345 push @all_values, \@values;
347 elsif ($filetype eq 'variable') {
348 my @values = ( eval { $parse->($self, $line) } );
350 $dbh->rollback if $oldAutoCommit;
354 push @all_values, \@values;
357 $dbh->rollback if $oldAutoCommit;
358 return "Unknown file type $filetype";
364 foreach (@all_values) {
367 $job->update_statustext(int(100 * $num/scalar(@all_values)));
372 my $line = pop @values;
373 foreach my $field ( @fields ) {
374 my $value = shift @values;
376 $hash{$field} = $value;
379 if ( defined($begin_condition) ) {
380 if ( &{$begin_condition}(\%hash, $line) ) {
381 undef $begin_condition;
388 if ( defined($end_condition) and &{$end_condition}(\%hash, $line) ) {
390 $error = &{$end_hook}(\%hash, $total, $line) if defined($end_hook);
392 $dbh->rollback if $oldAutoCommit;
398 if ( defined($skip_condition) and &{$skip_condition}(\%hash, $line) ) {
403 qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
404 unless ( $cust_pay_batch ) {
405 return "unknown paybatchnum $hash{'paybatchnum'}\n";
407 my $custnum = $cust_pay_batch->custnum,
408 my $payby = $cust_pay_batch->payby,
410 &{$hook}(\%hash, $cust_pay_batch->hashref);
412 my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
415 if ( &{$approved_condition}(\%hash) ) {
417 foreach ('paid', '_date', 'payinfo') {
418 $new_cust_pay_batch->$_($hash{$_}) if $hash{$_};
420 $error = $new_cust_pay_batch->approve(%hash);
421 $total += $hash{'paid'};
423 } elsif ( &{$declined_condition}(\%hash) ) {
425 $error = $new_cust_pay_batch->decline($hash{'error_message'});;
430 $dbh->rollback if $oldAutoCommit;
434 # purge CVV when the batch is processed
435 if ( $payby =~ /^(CARD|DCRD)$/ ) {
436 my $payinfo = $hash{'payinfo'} || $cust_pay_batch->payinfo;
437 if ( ! grep { $_ eq cardtype($payinfo) }
438 $conf->config('cvv-save') ) {
439 $new_cust_pay_batch->cust_main->remove_cvv;
444 } # foreach (@all_values)
447 if ( defined($close_condition) ) {
448 # Allow the module to decide whether to close the batch.
449 # $close_condition can also die() to abort the whole import.
450 $close = eval { $close_condition->($self) };
457 my $error = $self->set_status('R');
459 $dbh->rollback if $oldAutoCommit;
464 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
470 sub process_import_results {
473 $param->{'job'} = $job;
474 warn Dumper($param) if $DEBUG;
475 my $gatewaynum = delete $param->{'gatewaynum'};
477 $param->{'gateway'} = FS::payment_gateway->by_key($gatewaynum)
478 or die "gatewaynum '$gatewaynum' not found\n";
479 delete $param->{'format'}; # to avoid confusion
482 my $file = $param->{'uploaded_files'} or die "no files provided\n";
483 $file =~ s/^(\w+):([\.\w]+)$/$2/;
484 my $dir = '%%%FREESIDE_CACHE%%%/cache.' . $FS::UID::datasrc;
485 open( $param->{'filehandle'},
488 or die "unable to open '$file'.\n";
491 if ( $param->{gateway} ) {
492 $error = FS::pay_batch->import_from_gateway(%$param);
494 my $batchnum = delete $param->{'batchnum'} or die "no batchnum specified\n";
495 my $batch = FS::pay_batch->by_key($batchnum) or die "batchnum '$batchnum' not found\n";
496 $error = $batch->import_results($param);
499 die $error if $error;
502 =item import_from_gateway [ OPTIONS ]
504 Import results from a L<FS::payment_gateway>, using Business::BatchPayment,
505 and apply them. GATEWAY must use the Business::BatchPayment namespace.
507 This is a class method, since results can be applied to any batch.
508 The 'batch-reconsider' option determines whether an already-approved
509 or declined payment can have its status changed by a later import.
513 - gateway: the L<FS::payment_gateway>, required
514 - filehandle: a file name or handle to use as a data source.
515 - job: an L<FS::queue> object to update with progress messages.
519 sub import_from_gateway {
522 my $gateway = $opt{'gateway'};
523 my $conf = FS::Conf->new;
525 # unavoidable duplication with import_batch, for now
526 local $SIG{HUP} = 'IGNORE';
527 local $SIG{INT} = 'IGNORE';
528 local $SIG{QUIT} = 'IGNORE';
529 local $SIG{TERM} = 'IGNORE';
530 local $SIG{TSTP} = 'IGNORE';
531 local $SIG{PIPE} = 'IGNORE';
533 my $oldAutoCommit = $FS::UID::AutoCommit;
534 local $FS::UID::AutoCommit = 0;
537 my $job = delete($opt{'job'});
538 $job->update_statustext(0) if $job;
541 return "import_from_gateway requires a payment_gateway"
542 unless eval { $gateway->isa('FS::payment_gateway') };
545 'input' => $opt{'filehandle'}, # will do nothing if it's empty
546 # any other constructor options go here
550 my $mail_on_error = $conf->config('batch-errors_to');
551 if ( $mail_on_error ) {
552 # construct error trap
553 $proc_opt{'on_parse_error'} = sub {
554 my ($self, $line, $error) = @_;
555 push @item_errors, " '$line'\n$error";
559 my $processor = $gateway->batch_processor(%proc_opt);
561 my @batches = $processor->receive;
565 my $total_items = sum( map{$_->count} @batches);
567 # whether to allow items to change status
568 my $reconsider = $conf->exists('batch-reconsider');
570 # mutex all affected batches
571 my %pay_batch_for_update;
573 my %bop2payby = (CC => 'CARD', ECHECK => 'CHEK');
575 BATCH: foreach my $batch (@batches) {
577 my %incoming_batch = (
582 ITEM: foreach my $item ($batch->elements) {
584 my $cust_pay_batch; # the new batch entry (with status)
585 my $pay_batch; # the freeside batch it belongs to
586 my $payby; # CARD or CHEK
589 my $paybatch = $gateway->gatewaynum . '-' . $gateway->gateway_module .
590 ':' . $item->authorization . ':' . $item->order_number;
592 if ( $batch->incoming ) {
593 # This is a one-way batch.
594 # Locate the customer, find an open batch correct for them,
595 # create a payment. Don't bother creating a cust_pay_batch
598 if ( defined($item->customer_id)
599 and $item->customer_id =~ /^\d+$/
600 and $item->customer_id > 0 ) {
602 $cust_main = FS::cust_main->by_key($item->customer_id)
603 || qsearchs('cust_main',
604 { 'agent_custid' => $item->customer_id }
607 push @item_errors, "Unknown customer_id ".$item->customer_id;
612 push @item_errors, "Illegal customer_id '".$item->customer_id."'";
615 # it may also make sense to allow selecting the customer by
616 # invoice_number, but no modules currently work that way
618 $payby = $bop2payby{ $item->payment_type };
620 $agentnum = $cust_main->agentnum if $conf->exists('batch-spoolagent');
622 # create a batch if necessary
623 $pay_batch = $incoming_batch{$payby}->{$agentnum} ||=
625 status => 'R', # pre-resolve it
627 agentnum => $agentnum,
629 title => $batch->batch_id,
631 if ( !$pay_batch->batchnum ) {
632 $error = $pay_batch->insert;
633 die $error if $error; # can't do anything if this fails
636 if ( !$item->approved ) {
637 $error ||= "payment rejected - ".$item->error_message;
639 if ( !defined($item->amount) or $item->amount <= 0 ) {
640 $error ||= "no amount in item $num";
644 if ( $item->check_number ) {
645 $payby = 'BILL'; # right?
646 $payinfo = $item->check_number;
647 } elsif ( $item->assigned_token ) {
648 $payinfo = $item->assigned_token;
651 my $cust_pay = FS::cust_pay->new(
653 custnum => $cust_main->custnum,
654 _date => $item->payment_date->epoch,
655 paid => sprintf('%.2f',$item->amount),
657 invnum => $item->invoice_number,
658 batchnum => $pay_batch->batchnum,
660 gatewaynum => $gateway->gatewaynum,
661 processor => $gateway->gateway_module,
662 auth => $item->authorization,
663 order_number => $item->order_number,
666 $error ||= $cust_pay->insert;
667 eval { $cust_main->apply_payments };
671 push @item_errors, 'Payment for customer '.$item->customer_id."\n$error";
675 # This is a request/reply batch.
676 # Locate the request (the 'tid' attribute is the paybatchnum).
677 my $paybatchnum = $item->tid;
678 $cust_pay_batch = FS::cust_pay_batch->by_key($paybatchnum);
679 if (!$cust_pay_batch) {
680 push @item_errors, "paybatchnum $paybatchnum not found";
683 $payby = $cust_pay_batch->payby;
685 my $batchnum = $cust_pay_batch->batchnum;
686 if ( $batch->batch_id and $batch->batch_id != $batchnum ) {
687 warn "batch ID ".$batch->batch_id.
688 " does not match batchnum ".$cust_pay_batch->batchnum."\n";
691 # lock the batch and check its status
692 $pay_batch = FS::pay_batch->by_key($batchnum);
693 $pay_batch_for_update{$batchnum} ||= $pay_batch->select_for_update;
694 if ( $pay_batch->status ne 'I' and !$reconsider ) {
695 $error = "batch $batchnum no longer in transit";
698 if ( $cust_pay_batch->status ) {
699 my $new_status = $item->approved ? 'approved' : 'declined';
700 if ( lc( $cust_pay_batch->status ) eq $new_status ) {
701 # already imported with this status, so don't touch
704 elsif ( !$reconsider ) {
705 # then we're not allowed to change its status, so bail out
706 $error = "paybatchnum ".$item->tid.
707 " already resolved with status '". $cust_pay_batch->status . "'";
712 push @item_errors, "Payment for customer ".$cust_pay_batch->custnum."\n$error";
717 # update payinfo, if needed
718 if ( $item->assigned_token ) {
719 $new_payinfo = $item->assigned_token;
720 } elsif ( $payby eq 'CARD' ) {
721 $new_payinfo = $item->card_number if $item->card_number;
722 } else { #$payby eq 'CHEK'
723 $new_payinfo = $item->account_number . '@' . $item->routing_code
724 if $item->account_number;
726 $cust_pay_batch->set('payinfo', $new_payinfo) if $new_payinfo;
728 # set "paid" pseudo-field (transfers to cust_pay) to the actual amount
729 # paid, if the batch says it's different from the amount requested
730 if ( defined $item->amount ) {
731 $cust_pay_batch->set('paid', $item->amount);
733 $cust_pay_batch->set('paid', $cust_pay_batch->amount);
736 # set payment date to when it was processed
737 $cust_pay_batch->_date($item->payment_date->epoch)
738 if $item->payment_date;
741 if ( $item->approved ) {
742 # follow Billing_Realtime format for paybatch
743 $error = $cust_pay_batch->approve(
744 'gatewaynum' => $gateway->gatewaynum,
745 'processor' => $gateway->gateway_module,
746 'auth' => $item->authorization,
747 'order_number' => $item->order_number,
749 $total += $cust_pay_batch->paid;
752 $error = $cust_pay_batch->decline($item->error_message,
753 $item->failure_status);
757 push @item_errors, "Payment for customer ".$cust_pay_batch->custnum."\n$error";
763 $job->update_statustext(int(100 * $num/( $total_items ) ),
764 'Importing batch items')
769 } #foreach $batch (input batch, not pay_batch)
771 # Format an error message
772 if ( @item_errors ) {
773 my $error_text = join("\n\n",
774 "Errors during batch import: ".scalar(@item_errors),
777 if ( $mail_on_error ) {
778 my $subject = "Batch import errors"; #?
779 my $body = "Import from gateway ".$gateway->label."\n".$error_text;
781 to => $mail_on_error,
782 from => $conf->invoice_from_full(),
788 $dbh->rollback if $oldAutoCommit;
793 # Auto-resolve (with brute-force error handling)
794 foreach my $pay_batch (values %pay_batch_for_update) {
795 my $error = $pay_batch->try_to_resolve;
798 $dbh->rollback if $oldAutoCommit;
803 $dbh->commit if $oldAutoCommit;
809 Resolve this batch if possible. A batch can be resolved if all of its
810 entries have status. If the system options 'batch-auto_resolve_days'
811 and 'batch-auto_resolve_status' are set, and the batch's download date is
812 at least (batch-auto_resolve_days) before the current time, then it can
813 be auto-resolved; entries with no status will be approved or declined
814 according to the batch-auto_resolve_status setting.
820 my $conf = FS::Conf->new;;
822 return if $self->status ne 'I';
824 my @unresolved = qsearch('cust_pay_batch',
826 batchnum => $self->batchnum,
831 if ( @unresolved and $conf->exists('batch-auto_resolve_days') ) {
832 my $days = $conf->config('batch-auto_resolve_days'); # can be zero
833 # either 'approve' or 'decline'
834 my $action = $conf->config('batch-auto_resolve_status') || '';
838 time > ($self->download + 86400 * $days)
842 foreach my $cpb (@unresolved) {
843 if ( $action eq 'approve' ) {
844 # approve it for the full amount
845 $cpb->set('paid', $cpb->amount) unless ($cpb->paid || 0) > 0;
846 $error = $cpb->approve($self->batchnum);
848 elsif ( $action eq 'decline' ) {
849 $error = $cpb->decline('No response from processor');
851 return $error if $error;
853 } elsif ( @unresolved ) {
854 # auto resolve is not enabled, and we're not ready to resolve
858 $self->set_status('R');
861 =item prepare_for_export
863 Prepare the batch to be exported. This will:
864 - Set the status to "in transit".
865 - If batch-increment_expiration is set and this is a credit card batch,
866 increment expiration dates that are in the past.
867 - If this is the first download for this batch, adjust payment amounts to
868 not be greater than the customer's current balance. If the customer's
869 balance is zero, the entry will be removed.
871 Use this within a transaction.
875 sub prepare_for_export {
877 my $conf = FS::Conf->new;
878 my $curuser = $FS::CurrentUser::CurrentUser;
881 my $status = $self->status;
882 if ($status eq 'O') {
884 my $error = $self->set_status('I');
885 return "error updating pay_batch status: $error\n" if $error;
886 } elsif ($status eq 'I' && $curuser->access_right('Reprocess batches')) {
888 } elsif ($status eq 'R' &&
889 $curuser->access_right('Redownload resolved batches')) {
892 die "No pending batch.\n";
895 my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
896 $self->cust_pay_batch;
898 # handle batch-increment_expiration option
899 if ( $self->payby eq 'CARD' ) {
900 my ($cmon, $cyear) = (localtime(time))[4,5];
901 foreach (@cust_pay_batch) {
902 my $etime = str2time($_->exp) or next;
903 my ($day, $mon, $year) = (localtime($etime))[3,4,5];
904 if( $conf->exists('batch-increment_expiration') ) {
905 $year++ while( $year < $cyear or ($year == $cyear and $mon <= $cmon) );
906 $_->exp( sprintf('%4u-%02u-%02u', $year + 1900, $mon+1, $day) );
908 my $error = $_->replace;
909 return $error if $error;
913 if ($first_download) { #remove or reduce entries if customer's balance changed
915 foreach my $cust_pay_batch (@cust_pay_batch) {
917 my $balance = $cust_pay_batch->cust_main->balance;
918 if ($balance <= 0) { # then don't charge this customer
919 my $error = $cust_pay_batch->delete;
920 return $error if $error;
921 } elsif ($balance < $cust_pay_batch->amount) {
922 # reduce the charge to the remaining balance
923 $cust_pay_batch->amount($balance);
924 my $error = $cust_pay_batch->replace;
925 return $error if $error;
927 # else $balance >= $cust_pay_batch->amount
929 } #if $first_download
934 =item export_batch [ format => FORMAT | gateway => GATEWAY ]
936 Export batch for processing. FORMAT is the name of an L<FS::pay_batch>
937 module, in which case the configuration options are in 'batchconfig-FORMAT'.
939 Alternatively, GATEWAY can be an L<FS::payment_gateway> object set to a
940 L<Business::BatchPayment> module.
948 my $conf = new FS::Conf;
951 my $gateway = $opt{'gateway'};
953 # welcome to the future
954 my $fh = IO::Scalar->new(\$batch);
955 $self->export_to_gateway($gateway, 'file' => $fh);
959 my $format = $opt{'format'} || $conf->config('batch-default_format')
960 or die "No batch format configured\n";
962 my $info = $export_info{$format} or die "Format not found: '$format'\n";
964 &{$info->{'init'}}($conf, $self->agentnum) if exists($info->{'init'});
966 my $oldAutoCommit = $FS::UID::AutoCommit;
967 local $FS::UID::AutoCommit = 0;
970 my $error = $self->prepare_for_export;
972 die $error if $error;
976 my @cust_pay_batch = $self->cust_pay_batch;
978 my $delim = exists($info->{'delimiter'}) ? $info->{'delimiter'} : "\n";
980 my $h = $info->{'header'};
981 if (ref($h) eq 'CODE') {
982 $batch .= &$h($self, \@cust_pay_batch). $delim;
984 $batch .= $h. $delim;
987 foreach my $cust_pay_batch (@cust_pay_batch) {
989 $batchtotal += $cust_pay_batch->amount;
991 &{$info->{'row'}}($cust_pay_batch, $self, $batchcount, $batchtotal).
995 my $f = $info->{'footer'};
996 if (ref($f) eq 'CODE') {
997 $batch .= &$f($self, $batchcount, $batchtotal). $delim;
999 $batch .= $f. $delim;
1002 if ($info->{'autopost'}) {
1003 my $error = &{$info->{'autopost'}}($self, $batch);
1005 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1010 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1014 =item export_to_gateway GATEWAY OPTIONS
1016 Given L<FS::payment_gateway> GATEWAY, export the items in this batch to
1017 that gateway via Business::BatchPayment. OPTIONS may include:
1019 - file: override the default transport and write to this file (name or handle)
1023 sub export_to_gateway {
1025 my ($self, $gateway, %opt) = @_;
1027 my $oldAutoCommit = $FS::UID::AutoCommit;
1028 local $FS::UID::AutoCommit = 0;
1031 my $error = $self->prepare_for_export;
1032 die $error if $error;
1035 'output' => $opt{'file'}, # will do nothing if it's empty
1036 # any other constructor options go here
1038 my $processor = $gateway->batch_processor(%proc_opt);
1040 my @items = map { $_->request_item } $self->cust_pay_batch;
1041 my $batch = Business::BatchPayment->create(Batch =>
1042 batch_id => $self->batchnum,
1045 $processor->submit($batch);
1047 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1051 sub manual_approve {
1055 my $usernum = $opt{'usernum'} || die "manual approval requires a usernum";
1056 my $conf = FS::Conf->new;
1057 return 'manual batch approval disabled'
1058 if ( ! $conf->exists('batch-manual_approval') );
1059 return 'batch already resolved' if $self->status eq 'R';
1060 return 'batch not yet submitted' if $self->status eq 'O';
1062 local $SIG{HUP} = 'IGNORE';
1063 local $SIG{INT} = 'IGNORE';
1064 local $SIG{QUIT} = 'IGNORE';
1065 local $SIG{TERM} = 'IGNORE';
1066 local $SIG{TSTP} = 'IGNORE';
1067 local $SIG{PIPE} = 'IGNORE';
1069 my $oldAutoCommit = $FS::UID::AutoCommit;
1070 local $FS::UID::AutoCommit = 0;
1074 foreach my $cust_pay_batch (
1075 qsearch('cust_pay_batch', { batchnum => $self->batchnum,
1078 my $new_cust_pay_batch = new FS::cust_pay_batch {
1079 $cust_pay_batch->hash,
1080 'paid' => $cust_pay_batch->amount,
1082 'usernum' => $usernum,
1084 my $error = $new_cust_pay_batch->approve();
1085 # there are no approval options here (authorization, order_number, etc.)
1086 # because the transaction wasn't really approved
1089 return 'paybatchnum '.$cust_pay_batch->paybatchnum.": $error";
1093 $self->set_status('R');
1099 # Set up configuration for gateways that have a Business::BatchPayment
1102 eval "use Class::MOP;";
1104 warn "Moose/Class::MOP not available.\n$@\nSkipping pay_batch upgrade.\n";
1107 my $conf = FS::Conf->new;
1108 for my $format (keys %export_info) {
1109 my $mod = "FS::pay_batch::$format";
1110 if ( $mod->can('_upgrade_gateway')
1111 and $conf->exists("batchconfig-$format") ) {
1114 my ($module, %gw_options) = $mod->_upgrade_gateway;
1115 my $gateway = FS::payment_gateway->new({
1116 gateway_namespace => 'Business::BatchPayment',
1117 gateway_module => $module,
1119 my $error = $gateway->insert(%gw_options);
1121 warn "Failed to migrate '$format' to a Business::BatchPayment::$module gateway:\n$error\n";
1125 # test whether it loads
1126 my $processor = eval { $gateway->batch_processor };
1127 if ( !$processor ) {
1128 warn "Couldn't load Business::BatchPayment module for '$format'.\n";
1129 # if not, remove it so it doesn't hang around and break things
1133 # remove the batchconfig-*
1134 warn "Created Business::BatchPayment gateway '".$gateway->label.
1135 "' for '$format' batch processing.\n";
1136 $conf->delete("batchconfig-$format");
1138 # and if appropriate, make it the system default
1139 for my $payby (qw(CARD CHEK)) {
1140 if ( ($conf->config("batch-fixed_format-$payby") || '') eq $format ) {
1141 warn "Setting as default for $payby.\n";
1142 $conf->set("batch-gateway-$payby", $gateway->gatewaynum);
1143 $conf->delete("batch-fixed_format-$payby");
1147 } #if can('_upgrade_gateway') and batchconfig-$format
1157 status is somewhat redundant now that download and upload exist
1161 L<FS::Record>, schema.html from the base documentation.