4 use vars qw( @ISA $DEBUG %import_info %export_info $conf );
7 use FS::Record qw( dbh qsearch qsearchs );
11 @ISA = qw(FS::Record);
15 FS::pay_batch - Object methods for pay_batch records
21 $record = new FS::pay_batch \%hash;
22 $record = new FS::pay_batch { 'column' => 'value' };
24 $error = $record->insert;
26 $error = $new_record->replace($old_record);
28 $error = $record->delete;
30 $error = $record->check;
34 An FS::pay_batch object represents an payment batch. FS::pay_batch inherits
35 from FS::Record. The following fields are currently supported:
39 =item batchnum - primary key
41 =item payby - CARD or CHEK
43 =item status - O (Open), I (In-transit), or R (Resolved)
58 Creates a new batch. To add the batch to the database, see L<"insert">.
60 Note that this stores the hash reference, not a distinct copy of the hash it
61 points to. You can ask the object for a copy with the I<hash> method.
65 # the new method can be inherited from FS::Record, if a table method is defined
67 sub table { 'pay_batch'; }
71 Adds this record to the database. If there is an error, returns the error,
72 otherwise returns false.
76 # the insert method can be inherited from FS::Record
80 Delete this record from the database.
84 # the delete method can be inherited from FS::Record
86 =item replace OLD_RECORD
88 Replaces the OLD_RECORD with this one in the database. If there is an error,
89 returns the error, otherwise returns false.
93 # the replace method can be inherited from FS::Record
97 Checks all fields to make sure this is a valid batch. If there is
98 an error, returns the error, otherwise returns false. Called by the insert
103 # the check method should currently be supplied - FS::Record contains some
104 # data checking routines
110 $self->ut_numbern('batchnum')
111 || $self->ut_enum('payby', [ 'CARD', 'CHEK' ])
112 || $self->ut_enum('status', [ 'O', 'I', 'R' ])
114 return $error if $error;
133 $self->status(shift);
134 $self->download(time)
135 if $self->status eq 'I' && ! $self->download;
137 if $self->status eq 'R' && ! $self->upload;
141 # further false laziness
143 %import_info = %export_info = ();
144 foreach my $INC (@INC) {
145 warn "globbing $INC/FS/pay_batch/*.pm\n" if $DEBUG;
146 foreach my $file ( glob("$INC/FS/pay_batch/*.pm")) {
147 warn "attempting to load batch format from $file\n" if $DEBUG;
148 $file =~ /\/(\w+)\.pm$/;
151 my ($import, $export, $name) =
152 eval "use FS::pay_batch::$mod;
153 ( \\%FS::pay_batch::$mod\::import_info,
154 \\%FS::pay_batch::$mod\::export_info,
155 \$FS::pay_batch::$mod\::name)";
156 $name ||= $mod; # in case it's not defined
158 # in FS::cdr this is a die, not a warn. That's probably a bug.
159 warn "error using FS::pay_batch::$mod (skipping): $@\n";
162 if(!keys(%$import)) {
163 warn "no \%import_info found in FS::pay_batch::$mod (skipping)\n";
166 $import_info{$name} = $import;
168 if(!keys(%$export)) {
169 warn "no \%export_info found in FS::pay_batch::$mod (skipping)\n";
172 $export_info{$name} = $export;
177 =item import_results OPTION => VALUE, ...
179 Import batch results.
183 I<filehandle> - open filehandle of results file.
185 I<format> - "csv-td_canada_trust-merchant_pc_batch", "csv-chase_canada-E-xactBatch", "ach-spiritone", or "PAP"
192 my $param = ref($_[0]) ? shift : { @_ };
193 my $fh = $param->{'filehandle'};
194 my $format = $param->{'format'};
195 my $info = $import_info{$format}
196 or die "unknown format $format";
198 my $filetype = $info->{'filetype'}; # CSV or fixed
199 my @fields = @{ $info->{'fields'} };
200 my $formatre = $info->{'formatre'}; # for fixed
202 my $begin_condition = $info->{'begin_condition'};
203 my $end_condition = $info->{'end_condition'};
204 my $end_hook = $info->{'end_hook'};
205 my $hook = $info->{'hook'};
206 my $approved_condition = $info->{'approved'};
207 my $declined_condition = $info->{'declined'};
209 my $csv = new Text::CSV_XS;
211 local $SIG{HUP} = 'IGNORE';
212 local $SIG{INT} = 'IGNORE';
213 local $SIG{QUIT} = 'IGNORE';
214 local $SIG{TERM} = 'IGNORE';
215 local $SIG{TSTP} = 'IGNORE';
216 local $SIG{PIPE} = 'IGNORE';
218 my $oldAutoCommit = $FS::UID::AutoCommit;
219 local $FS::UID::AutoCommit = 0;
222 my $reself = $self->select_for_update;
224 unless ( $reself->status eq 'I' ) {
225 $dbh->rollback if $oldAutoCommit;
226 return "batchnum ". $self->batchnum. "no longer in transit";
229 my $error = $self->set_status('R');
231 $dbh->rollback if $oldAutoCommit;
238 # Order of operations has been changed here.
239 # We now slurp everything into @all_values, then
240 # process one line at a time.
242 if ($filetype eq 'XML') {
243 eval "use XML::Simple";
245 my @xmlkeys = @{ $info->{'xmlkeys'} }; # for XML
246 my $xmlrow = $info->{'xmlrow'}; # also for XML
248 # Do everything differently.
249 my $data = XML::Simple::XMLin($fh, KeepRoot => 1);
251 # $xmlrow = [ RootKey, FirstLevelKey, SecondLevelKey... ]
252 $rows = $rows->{$_} foreach( @$xmlrow );
253 if(!defined($rows)) {
254 $dbh->rollback if $oldAutoCommit;
255 return "can't find rows in XML file";
257 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
258 foreach my $row (@$rows) {
259 push @all_values, [ @{$row}{@xmlkeys} ];
263 while ( defined($line=<$fh>) ) {
265 next if $line =~ /^\s*$/; #skip blank lines
267 if ($filetype eq "CSV") {
268 $csv->parse($line) or do {
269 $dbh->rollback if $oldAutoCommit;
270 return "can't parse: ". $csv->error_input();
272 push @all_values, [ $csv->fields() ];
273 }elsif ($filetype eq 'fixed'){
274 my @values = $line =~ /$formatre/;
276 $dbh->rollback if $oldAutoCommit;
277 return "can't parse: ". $line;
279 push @all_values, \@values;
281 $dbh->rollback if $oldAutoCommit;
282 return "Unknown file type $filetype";
287 foreach (@all_values) {
291 foreach my $field ( @fields ) {
292 my $value = shift @values;
294 $hash{$field} = $value;
297 if ( defined($end_condition) and &{$end_condition}(\%hash) ) {
299 $error = &{$end_hook}(\%hash, $total) if defined($end_hook);
301 $dbh->rollback if $oldAutoCommit;
308 qsearchs('cust_pay_batch', { 'paybatchnum' => $hash{'paybatchnum'}+0 } );
309 unless ( $cust_pay_batch ) {
310 return "unknown paybatchnum $hash{'paybatchnum'}\n";
312 my $custnum = $cust_pay_batch->custnum,
313 my $payby = $cust_pay_batch->payby,
315 my $new_cust_pay_batch = new FS::cust_pay_batch { $cust_pay_batch->hash };
317 &{$hook}(\%hash, $cust_pay_batch->hashref);
319 if ( &{$approved_condition}(\%hash) ) {
321 $new_cust_pay_batch->status('Approved');
323 } elsif ( &{$declined_condition}(\%hash) ) {
325 $new_cust_pay_batch->status('Declined');
329 my $error = $new_cust_pay_batch->replace($cust_pay_batch);
331 $dbh->rollback if $oldAutoCommit;
332 return "error updating status of paybatchnum $hash{'paybatchnum'}: $error\n";
335 if ( $new_cust_pay_batch->status =~ /Approved/i ) {
337 my $cust_pay = new FS::cust_pay ( {
338 'custnum' => $custnum,
340 'paybatch' => $self->batchnum,
341 map { $_ => $hash{$_} } (qw( paid _date payinfo )),
343 $error = $cust_pay->insert;
345 $dbh->rollback if $oldAutoCommit;
346 return "error adding payment paybatchnum $hash{'paybatchnum'}: $error\n";
348 $total += $hash{'paid'};
350 $cust_pay->cust_main->apply_payments;
352 } elsif ( $new_cust_pay_batch->status =~ /Declined/i ) {
354 #false laziness w/cust_main::collect
356 my $due_cust_event = $new_cust_pay_batch->cust_main->due_cust_event(
357 #'check_freq' => '1d', #?
358 'eventtable' => 'cust_pay_batch',
359 'objects' => [ $new_cust_pay_batch ],
361 unless( ref($due_cust_event) ) {
362 $dbh->rollback if $oldAutoCommit;
363 return $due_cust_event;
366 foreach my $cust_event ( @$due_cust_event ) {
370 #re-eval event conditions (a previous event could have changed things)
371 next unless $cust_event->test_conditions;
373 if ( my $error = $cust_event->do_event() ) {
374 # gah, even with transactions.
375 #$dbh->commit if $oldAutoCommit; #well.
376 $dbh->rollback if $oldAutoCommit;
386 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
392 # Formerly httemplate/misc/download-batch.cgi
394 my $conf = new FS::Conf;
395 my $format = shift || $conf->config('batch-default_format')
396 or die "No batch format configured\n";
397 my $info = $export_info{$format} or die "Format not found: '$format'\n";
398 &{$info->{'init'}}($conf) if exists($info->{'init'});
400 my $oldAutoCommit = $FS::UID::AutoCommit;
401 local $FS::UID::AutoCommit = 0;
407 if($self->status eq 'O') {
410 elsif($self->status eq 'I' and
411 $FS::CurrentUser::CurrentUser->access_right('Reprocess batches')) {
415 die "No pending batch.\n"
418 $error = $self->set_status('I');
419 die "error updating pay_batch status: $error\n" if $error;
425 my @cust_pay_batch = sort { $a->paybatchnum <=> $b->paybatchnum }
426 qsearch('cust_pay_batch', { batchnum => $self->batchnum } );
428 my $h = $info->{'header'};
429 if(ref($h) eq 'CODE') {
430 $batch .= &$h($self, \@cust_pay_batch) . "\n";
435 foreach my $cust_pay_batch (@cust_pay_batch) {
436 if($first_download) {
437 my $balance = $cust_pay_batch->cust_main->balance;
439 if($balance <= 0) { # then don't charge this customer
440 $error = $cust_pay_batch->delete;
441 undef $cust_pay_batch;
443 elsif($balance < $cust_pay_batch->amount) { # then reduce the charge to the remaining balance
444 $cust_pay_batch->amount($balance);
445 $error = $cust_pay_batch->replace;
447 # else $balance >= $cust_pay_batch->amount
449 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
453 if($cust_pay_batch) { # that is, it wasn't deleted
455 $batchtotal += $cust_pay_batch->amount;
456 $batch .= &{$info->{'row'}}($cust_pay_batch, $self) . "\n";
459 my $f = $info->{'footer'};
460 if(ref($f) eq 'CODE') {
461 $batch .= &$f($self, $batchcount, $batchtotal) . "\n";
467 if ($info->{'autopost'}) {
468 $error = &{$info->{'autopost'}}($self, $batch);
470 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
475 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
483 status is somewhat redundant now that download and upload exist
487 L<FS::Record>, schema.html from the base documentation.