4 use base qw( FS::otaker_Mixin FS::payinfo_transaction_Mixin FS::cust_main_Mixin
6 use vars qw( $DEBUG $me $conf @encrypted_fields
7 $unsuspendauto $ignore_noapply
10 use Business::CreditCard;
12 use FS::UID qw( getotaker );
13 use FS::Misc qw( send_email );
14 use FS::Record qw( dbh qsearch qsearchs );
17 use FS::cust_main_Mixin;
18 use FS::payinfo_transaction_Mixin;
20 use FS::cust_bill_pay;
21 use FS::cust_pay_refund;
24 use FS::cust_pay_void;
28 $me = '[FS::cust_pay]';
32 #ask FS::UID to run this stuff for us later
33 FS::UID->install_callback( sub {
35 $unsuspendauto = $conf->exists('unsuspendauto');
38 @encrypted_fields = ('payinfo');
42 FS::cust_pay - Object methods for cust_pay objects
48 $record = new FS::cust_pay \%hash;
49 $record = new FS::cust_pay { 'column' => 'value' };
51 $error = $record->insert;
53 $error = $new_record->replace($old_record);
55 $error = $record->delete;
57 $error = $record->check;
61 An FS::cust_pay object represents a payment; the transfer of money from a
62 customer. FS::cust_pay inherits from FS::Record. The following fields are
69 primary key (assigned automatically for new payments)
73 customer (see L<FS::cust_main>)
77 specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
78 L<Time::Local> and L<Date::Parse> for conversion functions.
82 Amount of this payment
86 order taker (see L<FS::access_user>)
90 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
94 Payment Information (See L<FS::payinfo_Mixin> for data format)
98 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
102 text field for tracking card processing or other batch grouping
106 Optional unique identifer to prevent duplicate transactions.
110 books closed flag, empty or `Y'
114 Desired pkgnum when using experimental package balances.
124 Creates a new payment. To add the payment to the databse, see L<"insert">.
128 sub table { 'cust_pay'; }
129 sub cust_linked { $_[0]->cust_main_custnum; }
130 sub cust_unlinked_msg {
132 "WARNING: can't find cust_main.custnum ". $self->custnum.
133 ' (cust_pay.paynum '. $self->paynum. ')';
136 =item insert [ OPTION => VALUE ... ]
138 Adds this payment to the database.
140 For backwards-compatibility and convenience, if the additional field invnum
141 is defined, an FS::cust_bill_pay record for the full amount of the payment
142 will be created. In this case, custnum is optional.
144 If the additional field discount_term is defined then a prepayment discount
145 is taken for that length of time. It is an error for the customer to owe
146 after this payment is made.
148 A hash of optional arguments may be passed. Currently "manual" is supported.
149 If true, a payment receipt is sent instead of a statement when
150 'payment_receipt_email' configuration option is set.
155 my($self, %options) = @_;
157 local $SIG{HUP} = 'IGNORE';
158 local $SIG{INT} = 'IGNORE';
159 local $SIG{QUIT} = 'IGNORE';
160 local $SIG{TERM} = 'IGNORE';
161 local $SIG{TSTP} = 'IGNORE';
162 local $SIG{PIPE} = 'IGNORE';
164 my $oldAutoCommit = $FS::UID::AutoCommit;
165 local $FS::UID::AutoCommit = 0;
169 if ( $self->invnum ) {
170 $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
172 $dbh->rollback if $oldAutoCommit;
173 return "Unknown cust_bill.invnum: ". $self->invnum;
175 $self->custnum($cust_bill->custnum );
178 my $error = $self->check;
179 return $error if $error;
181 my $cust_main = $self->cust_main;
182 my $old_balance = $cust_main->balance;
184 $error = $self->SUPER::insert;
186 $dbh->rollback if $oldAutoCommit;
187 return "error inserting cust_pay: $error";
190 if ( my $credit_type = $conf->config('prepayment_discounts-credit_type') ) {
191 if ( my $months = $self->discount_term ) {
192 # XXX this should be moved out somewhere, but discount_term_values
194 my ($cust_bill) = ($cust_main->cust_bill)[-1]; # most recent invoice
195 return "can't accept prepayment for an unbilled customer" if !$cust_bill;
197 my %billing_pkgs = map { $_->pkgnum => $_ } $cust_main->billing_pkgs;
198 my $credit = 0; # sum of recurring charges from that invoice
199 my $last_bill_date = 0; # the real bill date
200 foreach my $item ( $cust_bill->cust_bill_pkg ) {
201 next if !exists($billing_pkgs{$item->pkgnum}); # skip inactive packages
202 $credit += $item->recur;
203 $last_bill_date = $item->cust_pkg->last_bill
204 if defined($item->cust_pkg)
205 and $item->cust_pkg->last_bill > $last_bill_date
208 my $cust_credit = new FS::cust_credit {
209 'custnum' => $self->custnum,
210 'amount' => sprintf('%.2f', $credit),
211 'reason' => 'customer chose to prepay for discount',
213 $error = $cust_credit->insert('reason_type' => $credit_type);
215 $dbh->rollback if $oldAutoCommit;
216 return "error inserting prepayment credit: $error";
220 # bill for the entire term
221 $_->bill($_->last_bill) foreach (values %billing_pkgs);
222 $error = $cust_main->bill(
223 # no recurring_only, we want unbilled packages with start dates to
225 'no_usage_reset' => 1,
226 'time' => $last_bill_date, # not $cust_bill->_date
227 'pkg_list' => [ values %billing_pkgs ],
228 'freq_override' => $months,
231 $dbh->rollback if $oldAutoCommit;
232 return "error inserting cust_pay: $error";
234 $error = $cust_main->apply_payments_and_credits;
236 $dbh->rollback if $oldAutoCommit;
237 return "error inserting cust_pay: $error";
239 my $new_balance = $cust_main->balance;
240 if ($new_balance > 0) {
241 $dbh->rollback if $oldAutoCommit;
242 return "balance after prepay discount attempt: $new_balance";
244 # user friendly: override the "apply only to this invoice" mode
251 if ( $self->invnum ) {
252 my $cust_bill_pay = new FS::cust_bill_pay {
253 'invnum' => $self->invnum,
254 'paynum' => $self->paynum,
255 'amount' => $self->paid,
256 '_date' => $self->_date,
258 $error = $cust_bill_pay->insert(%options);
260 if ( $ignore_noapply ) {
261 warn "warning: error inserting cust_bill_pay: $error ".
262 "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
264 $dbh->rollback if $oldAutoCommit;
265 return "error inserting cust_bill_pay: $error";
270 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
272 #false laziness w/ cust_credit::insert
273 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
274 my @errors = $cust_main->unsuspend;
276 # side-fx with nested transactions? upstack rolls back?
277 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
283 #bill setup fees for voip_cdr bill_every_call packages
284 #some false laziness w/search in freeside-cdrd
286 'LEFT JOIN part_pkg USING ( pkgpart ) '.
287 "LEFT JOIN part_pkg_option
288 ON ( cust_pkg.pkgpart = part_pkg_option.pkgpart
289 AND part_pkg_option.optionname = 'bill_every_call' )";
291 my $extra_sql = " AND plan = 'voip_cdr' AND optionvalue = '1' ".
292 " AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 ) ";
294 my @cust_pkg = qsearch({
295 'table' => 'cust_pkg',
296 'addl_from' => $addl_from,
297 'hashref' => { 'custnum' => $self->custnum,
301 'extra_sql' => $extra_sql,
305 warn "voip_cdr bill_every_call packages found; billing customer\n";
306 my $bill_error = $self->cust_main->bill_and_collect( 'fatal' => 'return' );
308 warn "WARNING: Error billing customer: $bill_error\n";
311 #end of billing setup fees for voip_cdr bill_every_call packages
313 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
316 my $trigger = $conf->config('payment_receipt-trigger',
317 $self->cust_main->agentnum) || 'cust_pay';
318 if ( $trigger eq 'cust_pay' ) {
319 my $error = $self->send_receipt(
320 'manual' => $options{'manual'},
321 'cust_bill' => $cust_bill,
322 'cust_main' => $cust_main,
324 warn "can't send payment receipt/statement: $error" if $error;
331 =item void [ REASON ]
333 Voids this payment: deletes the payment and all associated applications and
334 adds a record of the voided payment to the FS::cust_pay_void table.
341 local $SIG{HUP} = 'IGNORE';
342 local $SIG{INT} = 'IGNORE';
343 local $SIG{QUIT} = 'IGNORE';
344 local $SIG{TERM} = 'IGNORE';
345 local $SIG{TSTP} = 'IGNORE';
346 local $SIG{PIPE} = 'IGNORE';
348 my $oldAutoCommit = $FS::UID::AutoCommit;
349 local $FS::UID::AutoCommit = 0;
352 my $cust_pay_void = new FS::cust_pay_void ( {
353 map { $_ => $self->get($_) } $self->fields
355 $cust_pay_void->reason(shift) if scalar(@_);
356 my $error = $cust_pay_void->insert;
358 $dbh->rollback if $oldAutoCommit;
362 $error = $self->delete;
364 $dbh->rollback if $oldAutoCommit;
368 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
376 Unless the closed flag is set, deletes this payment and all associated
377 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>). In most
378 cases, you want to use the void method instead to leave a record of the
383 # very similar to FS::cust_credit::delete
386 return "Can't delete closed payment" if $self->closed =~ /^Y/i;
388 local $SIG{HUP} = 'IGNORE';
389 local $SIG{INT} = 'IGNORE';
390 local $SIG{QUIT} = 'IGNORE';
391 local $SIG{TERM} = 'IGNORE';
392 local $SIG{TSTP} = 'IGNORE';
393 local $SIG{PIPE} = 'IGNORE';
395 my $oldAutoCommit = $FS::UID::AutoCommit;
396 local $FS::UID::AutoCommit = 0;
399 foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
400 my $error = $app->delete;
402 $dbh->rollback if $oldAutoCommit;
407 my $error = $self->SUPER::delete(@_);
409 $dbh->rollback if $oldAutoCommit;
413 if ( $conf->exists('deletepayments')
414 && $conf->config('deletepayments') ne '' ) {
416 my $cust_main = $self->cust_main;
418 my $error = send_email(
419 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
420 #invoice_from??? well as good as any
421 'to' => $conf->config('deletepayments'),
422 'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
424 "This is an automatic message from your Freeside installation\n",
425 "informing you that the following payment has been deleted:\n",
427 'paynum: '. $self->paynum. "\n",
428 'custnum: '. $self->custnum.
429 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
430 'paid: $'. sprintf("%.2f", $self->paid). "\n",
431 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
432 'payby: '. $self->payby. "\n",
433 'payinfo: '. $self->paymask. "\n",
434 'paybatch: '. $self->paybatch. "\n",
439 $dbh->rollback if $oldAutoCommit;
440 return "can't send payment deletion notification: $error";
445 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
451 =item replace [ OLD_RECORD ]
453 You can, but probably shouldn't modify payments...
455 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
456 supplied, replaces this record. If there is an error, returns the error,
457 otherwise returns false.
463 return "Can't modify closed payment" if $self->closed =~ /^Y/i;
464 $self->SUPER::replace(@_);
469 Checks all fields to make sure this is a valid payment. If there is an error,
470 returns the error, otherwise returns false. Called by the insert method.
477 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
480 $self->ut_numbern('paynum')
481 || $self->ut_numbern('custnum')
482 || $self->ut_numbern('_date')
483 || $self->ut_money('paid')
484 || $self->ut_alphan('otaker')
485 || $self->ut_textn('paybatch')
486 || $self->ut_textn('payunique')
487 || $self->ut_enum('closed', [ '', 'Y' ])
488 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
489 || $self->payinfo_check()
490 || $self->ut_numbern('discount_term')
492 return $error if $error;
494 return "paid must be > 0 " if $self->paid <= 0;
496 return "unknown cust_main.custnum: ". $self->custnum
498 || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
500 $self->_date(time) unless $self->_date;
502 return "invalid discount_term"
503 if ($self->discount_term && $self->discount_term < 2);
505 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
506 # # UNIQUE index should catch this too, without race conditions, but this
507 # # should give a better error message the other 99.9% of the time...
508 # if ( length($self->payunique)
509 # && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
510 # #well, it *could* be a better error message
511 # return "duplicate transaction".
512 # " - a payment with unique identifer ". $self->payunique.
519 =item send_receipt HASHREF | OPTION => VALUE ...
521 Sends a payment receipt for this payment..
529 Flag indicating the payment is being made manually.
533 Invoice (FS::cust_bill) object. If not specified, the most recent invoice
538 Customer (FS::cust_main) object (for efficiency).
546 my $opt = ref($_[0]) ? shift : { @_ };
548 my $cust_bill = $opt->{'cust_bill'};
549 my $cust_main = $opt->{'cust_main'} || $self->cust_main;
551 my $conf = new FS::Conf;
553 return '' unless $conf->exists('payment_receipt', $cust_main->agentnum);
555 my @invoicing_list = $cust_main->invoicing_list_emailonly;
556 return '' unless @invoicing_list;
558 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
562 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
563 #|| ! $conf->exists('invoice_html_statement')
567 my $msgnum = $conf->config('payment_receipt_msgnum', $cust_main->agentnum);
569 my $msg_template = FS::msg_template->by_key($msgnum);
570 $error = $msg_template->send(
571 'cust_main' => $cust_main,
573 'from_config' => 'payment_receipt_from',
576 } elsif ( $conf->exists('payment_receipt_email') ) {
578 my $receipt_template = new Text::Template (
580 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
582 warn "can't create payment receipt template: $Text::Template::ERROR";
586 my $payby = $self->payby;
587 my $payinfo = $self->payinfo;
588 $payby =~ s/^BILL$/Check/ if $payinfo;
589 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
590 $payinfo = $self->paymask
592 $payinfo = $self->decrypt($payinfo);
594 $payby =~ s/^CHEK$/Electronic check/;
597 'date' => time2str("%a %B %o, %Y", $self->_date),
598 'name' => $cust_main->name,
599 'paynum' => $self->paynum,
600 'paid' => sprintf("%.2f", $self->paid),
601 'payby' => ucfirst(lc($payby)),
602 'payinfo' => $payinfo,
603 'balance' => $cust_main->balance,
604 'company_name' => $conf->config('company_name', $cust_main->agentnum),
607 if ( $opt->{'cust_pkg'} ) {
608 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
609 #setup date, other things?
613 'from' => $conf->config('invoice_from', $cust_main->agentnum),
614 #invoice_from??? well as good as any
615 'to' => \@invoicing_list,
616 'subject' => 'Payment receipt',
617 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
622 warn "payment_receipt is on, but no payment_receipt_msgnum\n";
628 my $queue = new FS::queue {
629 'paynum' => $self->paynum,
630 'job' => 'FS::cust_bill::queueable_email',
633 $error = $queue->insert(
634 'invnum' => $cust_bill->invnum,
635 'template' => 'statement',
636 'notice_name' => 'Statement',
642 warn "send_receipt: $error\n" if $error;
647 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
654 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
655 sort { $a->_date <=> $b->_date
656 || $a->invnum <=> $b->invnum }
657 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
661 =item cust_pay_refund
663 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
668 sub cust_pay_refund {
670 map { $_ } #return $self->num_cust_pay_refund unless wantarray;
671 sort { $a->_date <=> $b->_date }
672 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
679 Returns the amount of this payment that is still unapplied; which is
680 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
681 applications (see L<FS::cust_pay_refund>).
687 my $amount = $self->paid;
688 $amount -= $_->amount foreach ( $self->cust_bill_pay );
689 $amount -= $_->amount foreach ( $self->cust_pay_refund );
690 sprintf("%.2f", $amount );
695 Returns the amount of this payment that has not been refuned; which is
696 paid minus all refund applications (see L<FS::cust_pay_refund>).
702 my $amount = $self->paid;
703 $amount -= $_->amount foreach ( $self->cust_pay_refund );
704 sprintf("%.2f", $amount );
709 Returns the "paid" field.
724 =item batch_insert CUST_PAY_OBJECT, ...
726 Class method which inserts multiple payments. Takes a list of FS::cust_pay
727 objects. Returns a list, each element representing the status of inserting the
728 corresponding payment - empty. If there is an error inserting any payment, the
729 entire transaction is rolled back, i.e. all payments are inserted or none are.
733 my @errors = FS::cust_pay->batch_insert(@cust_pay);
734 my $num_errors = scalar(grep $_, @errors);
735 if ( $num_errors == 0 ) {
736 #success; all payments were inserted
738 #failure; no payments were inserted.
744 my $self = shift; #class method
746 local $SIG{HUP} = 'IGNORE';
747 local $SIG{INT} = 'IGNORE';
748 local $SIG{QUIT} = 'IGNORE';
749 local $SIG{TERM} = 'IGNORE';
750 local $SIG{TSTP} = 'IGNORE';
751 local $SIG{PIPE} = 'IGNORE';
753 my $oldAutoCommit = $FS::UID::AutoCommit;
754 local $FS::UID::AutoCommit = 0;
760 my $error = $_->insert( 'manual' => 1 );
764 $_->cust_main->apply_payments;
770 $dbh->rollback if $oldAutoCommit;
772 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
781 Returns an SQL fragment to retreive the unapplied amount.
786 my ($class, $start, $end) = @_;
787 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
788 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
789 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
790 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
794 ( SELECT SUM(amount) FROM cust_bill_pay
795 WHERE cust_pay.paynum = cust_bill_pay.paynum
796 $bill_start $bill_end )
800 ( SELECT SUM(amount) FROM cust_pay_refund
801 WHERE cust_pay.paynum = cust_pay_refund.paynum
802 $refund_start $refund_end )
811 # Used by FS::Upgrade to migrate to a new database.
815 sub _upgrade_data { #class method
816 my ($class, %opts) = @_;
818 warn "$me upgrading $class\n" if $DEBUG;
821 # otaker/ivan upgrade
824 #not the most efficient, but hey, it only has to run once
826 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
827 " AND usernum IS NULL ".
828 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
829 " WHERE cust_main.custnum = cust_pay.custnum ) ";
831 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
833 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
834 $sth->execute or die $sth->errstr;
835 my $total = $sth->fetchrow_arrayref->[0];
836 #warn "$total cust_pay records to update\n"
838 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
843 my @cust_pay = qsearch( {
844 'table' => 'cust_pay',
846 'extra_sql' => $where,
847 'order_by' => 'ORDER BY paynum',
850 foreach my $cust_pay (@cust_pay) {
852 my $h_cust_pay = $cust_pay->h_search('insert');
854 next if $cust_pay->otaker eq $h_cust_pay->history_user;
855 #$cust_pay->otaker($h_cust_pay->history_user);
856 $cust_pay->set('otaker', $h_cust_pay->history_user);
858 $cust_pay->set('otaker', 'legacy');
861 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
862 my $error = $cust_pay->replace;
865 warn " *** WARNING: Error updating order taker for payment paynum ".
866 $cust_pay->paynun. ": $error\n";
870 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
873 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
874 warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
881 # payinfo N/A upgrade
884 #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
886 my @na_cust_pay = qsearch( {
887 'table' => 'cust_pay',
888 'hashref' => {}, #could be encrypted# { 'payinfo' => 'N/A' },
889 'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
892 foreach my $na ( @na_cust_pay ) {
894 next unless $na->payinfo eq 'N/A';
896 my $cust_pay_pending =
897 qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
898 unless ( $cust_pay_pending ) {
899 warn " *** WARNING: not-yet recoverable N/A card for payment ".
900 $na->paynum. " (no cust_pay_pending)\n";
903 $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
904 my $error = $na->replace;
906 warn " *** WARNING: Error updating payinfo for payment paynum ".
907 $na->paynun. ": $error\n";
914 # otaker->usernum upgrade
917 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
918 $class->_upgrade_otaker(%opts);
919 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
929 =item batch_import HASHREF
931 Inserts new payments.
938 my $fh = $param->{filehandle};
939 my $agentnum = $param->{agentnum};
940 my $format = $param->{'format'};
941 my $paybatch = $param->{'paybatch'};
943 # here is the agent virtualization
944 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
948 if ( $format eq 'simple' ) {
949 @fields = qw( custnum agent_custid paid payinfo );
951 } elsif ( $format eq 'extended' ) {
952 die "unimplemented\n";
956 die "unknown format $format";
959 eval "use Text::CSV_XS;";
962 my $csv = new Text::CSV_XS;
966 local $SIG{HUP} = 'IGNORE';
967 local $SIG{INT} = 'IGNORE';
968 local $SIG{QUIT} = 'IGNORE';
969 local $SIG{TERM} = 'IGNORE';
970 local $SIG{TSTP} = 'IGNORE';
971 local $SIG{PIPE} = 'IGNORE';
973 my $oldAutoCommit = $FS::UID::AutoCommit;
974 local $FS::UID::AutoCommit = 0;
978 while ( defined($line=<$fh>) ) {
980 $csv->parse($line) or do {
981 $dbh->rollback if $oldAutoCommit;
982 return "can't parse: ". $csv->error_input();
985 my @columns = $csv->fields();
989 paybatch => $paybatch,
993 foreach my $field ( @fields ) {
995 if ( $field eq 'agent_custid'
997 && $columns[0] =~ /\S+/ )
1000 my $agent_custid = $columns[0];
1001 my %hash = ( 'agent_custid' => $agent_custid,
1002 'agentnum' => $agentnum,
1005 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
1006 $dbh->rollback if $oldAutoCommit;
1007 return "can't specify custnum with agent_custid $agent_custid";
1010 $cust_main = qsearchs({
1011 'table' => 'cust_main',
1012 'hashref' => \%hash,
1013 'extra_sql' => $extra_sql,
1016 unless ( $cust_main ) {
1017 $dbh->rollback if $oldAutoCommit;
1018 return "can't find customer with agent_custid $agent_custid";
1022 $columns[0] = $cust_main->custnum;
1025 $cust_pay{$field} = shift @columns;
1028 my $cust_pay = new FS::cust_pay( \%cust_pay );
1029 my $error = $cust_pay->insert;
1032 $dbh->rollback if $oldAutoCommit;
1033 return "can't insert payment for $line: $error";
1036 if ( $format eq 'simple' ) {
1037 # include agentnum for less surprise?
1038 $cust_main = qsearchs({
1039 'table' => 'cust_main',
1040 'hashref' => { 'custnum' => $cust_pay->custnum },
1041 'extra_sql' => $extra_sql,
1045 unless ( $cust_main ) {
1046 $dbh->rollback if $oldAutoCommit;
1047 return "can't find customer to which payments apply at line: $line";
1050 $error = $cust_main->apply_payments_and_credits;
1052 $dbh->rollback if $oldAutoCommit;
1053 return "can't apply payments to customer for $line: $error";
1061 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1063 return "Empty file!" unless $imported;
1073 Delete and replace methods.
1077 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
1078 schema.html from the base documentation.