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 # %billing_pkgs contains this customer's active monthly packages.
198 # Recurring fees for those packages will be credited and then rebilled
199 # for the full discount term. Other packages on the last invoice
200 # (canceled, non-monthly recurring, or one-time charges) will be
202 my %billing_pkgs = map { $_->pkgnum => $_ }
203 grep { $_->part_pkg->freq eq '1' }
204 $cust_main->billing_pkgs;
205 my $credit = 0; # sum of recurring charges from that invoice
206 my $last_bill_date = 0; # the real bill date
207 foreach my $item ( $cust_bill->cust_bill_pkg ) {
208 next if !exists($billing_pkgs{$item->pkgnum}); # skip inactive packages
209 $credit += $item->recur;
210 $last_bill_date = $item->cust_pkg->last_bill
211 if defined($item->cust_pkg)
212 and $item->cust_pkg->last_bill > $last_bill_date
215 my $cust_credit = new FS::cust_credit {
216 'custnum' => $self->custnum,
217 'amount' => sprintf('%.2f', $credit),
218 'reason' => 'customer chose to prepay for discount',
220 $error = $cust_credit->insert('reason_type' => $credit_type);
222 $dbh->rollback if $oldAutoCommit;
223 return "error inserting prepayment credit: $error";
227 # bill for the entire term
228 $_->bill($_->last_bill) foreach (values %billing_pkgs);
229 $error = $cust_main->bill(
230 # no recurring_only, we want unbilled packages with start dates to
232 'no_usage_reset' => 1,
233 'time' => $last_bill_date, # not $cust_bill->_date
234 'pkg_list' => [ values %billing_pkgs ],
235 'freq_override' => $months,
238 $dbh->rollback if $oldAutoCommit;
239 return "error inserting cust_pay: $error";
241 $error = $cust_main->apply_payments_and_credits;
243 $dbh->rollback if $oldAutoCommit;
244 return "error inserting cust_pay: $error";
246 my $new_balance = $cust_main->balance;
247 if ($new_balance > 0) {
248 $dbh->rollback if $oldAutoCommit;
249 return "balance after prepay discount attempt: $new_balance";
251 # user friendly: override the "apply only to this invoice" mode
258 if ( $self->invnum ) {
259 my $cust_bill_pay = new FS::cust_bill_pay {
260 'invnum' => $self->invnum,
261 'paynum' => $self->paynum,
262 'amount' => $self->paid,
263 '_date' => $self->_date,
265 $error = $cust_bill_pay->insert(%options);
267 if ( $ignore_noapply ) {
268 warn "warning: error inserting cust_bill_pay: $error ".
269 "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
271 $dbh->rollback if $oldAutoCommit;
272 return "error inserting cust_bill_pay: $error";
277 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
279 #false laziness w/ cust_credit::insert
280 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
281 my @errors = $cust_main->unsuspend;
283 # side-fx with nested transactions? upstack rolls back?
284 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
290 #bill setup fees for voip_cdr bill_every_call packages
291 #some false laziness w/search in freeside-cdrd
293 'LEFT JOIN part_pkg USING ( pkgpart ) '.
294 "LEFT JOIN part_pkg_option
295 ON ( cust_pkg.pkgpart = part_pkg_option.pkgpart
296 AND part_pkg_option.optionname = 'bill_every_call' )";
298 my $extra_sql = " AND plan = 'voip_cdr' AND optionvalue = '1' ".
299 " AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 ) ";
301 my @cust_pkg = qsearch({
302 'table' => 'cust_pkg',
303 'addl_from' => $addl_from,
304 'hashref' => { 'custnum' => $self->custnum,
308 'extra_sql' => $extra_sql,
312 warn "voip_cdr bill_every_call packages found; billing customer\n";
313 my $bill_error = $self->cust_main->bill_and_collect( 'fatal' => 'return' );
315 warn "WARNING: Error billing customer: $bill_error\n";
318 #end of billing setup fees for voip_cdr bill_every_call packages
320 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
323 my $trigger = $conf->config('payment_receipt-trigger',
324 $self->cust_main->agentnum) || 'cust_pay';
325 if ( $trigger eq 'cust_pay' ) {
326 my $error = $self->send_receipt(
327 'manual' => $options{'manual'},
328 'cust_bill' => $cust_bill,
329 'cust_main' => $cust_main,
331 warn "can't send payment receipt/statement: $error" if $error;
338 =item void [ REASON ]
340 Voids this payment: deletes the payment and all associated applications and
341 adds a record of the voided payment to the FS::cust_pay_void table.
348 local $SIG{HUP} = 'IGNORE';
349 local $SIG{INT} = 'IGNORE';
350 local $SIG{QUIT} = 'IGNORE';
351 local $SIG{TERM} = 'IGNORE';
352 local $SIG{TSTP} = 'IGNORE';
353 local $SIG{PIPE} = 'IGNORE';
355 my $oldAutoCommit = $FS::UID::AutoCommit;
356 local $FS::UID::AutoCommit = 0;
359 my $cust_pay_void = new FS::cust_pay_void ( {
360 map { $_ => $self->get($_) } $self->fields
362 $cust_pay_void->reason(shift) if scalar(@_);
363 my $error = $cust_pay_void->insert;
365 $dbh->rollback if $oldAutoCommit;
369 $error = $self->delete;
371 $dbh->rollback if $oldAutoCommit;
375 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
383 Unless the closed flag is set, deletes this payment and all associated
384 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>). In most
385 cases, you want to use the void method instead to leave a record of the
390 # very similar to FS::cust_credit::delete
393 return "Can't delete closed payment" if $self->closed =~ /^Y/i;
395 local $SIG{HUP} = 'IGNORE';
396 local $SIG{INT} = 'IGNORE';
397 local $SIG{QUIT} = 'IGNORE';
398 local $SIG{TERM} = 'IGNORE';
399 local $SIG{TSTP} = 'IGNORE';
400 local $SIG{PIPE} = 'IGNORE';
402 my $oldAutoCommit = $FS::UID::AutoCommit;
403 local $FS::UID::AutoCommit = 0;
406 foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
407 my $error = $app->delete;
409 $dbh->rollback if $oldAutoCommit;
414 my $error = $self->SUPER::delete(@_);
416 $dbh->rollback if $oldAutoCommit;
420 if ( $conf->exists('deletepayments')
421 && $conf->config('deletepayments') ne '' ) {
423 my $cust_main = $self->cust_main;
425 my $error = send_email(
426 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
427 #invoice_from??? well as good as any
428 'to' => $conf->config('deletepayments'),
429 'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
431 "This is an automatic message from your Freeside installation\n",
432 "informing you that the following payment has been deleted:\n",
434 'paynum: '. $self->paynum. "\n",
435 'custnum: '. $self->custnum.
436 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
437 'paid: $'. sprintf("%.2f", $self->paid). "\n",
438 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
439 'payby: '. $self->payby. "\n",
440 'payinfo: '. $self->paymask. "\n",
441 'paybatch: '. $self->paybatch. "\n",
446 $dbh->rollback if $oldAutoCommit;
447 return "can't send payment deletion notification: $error";
452 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
458 =item replace [ OLD_RECORD ]
460 You can, but probably shouldn't modify payments...
462 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
463 supplied, replaces this record. If there is an error, returns the error,
464 otherwise returns false.
470 return "Can't modify closed payment" if $self->closed =~ /^Y/i;
471 $self->SUPER::replace(@_);
476 Checks all fields to make sure this is a valid payment. If there is an error,
477 returns the error, otherwise returns false. Called by the insert method.
484 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
487 $self->ut_numbern('paynum')
488 || $self->ut_numbern('custnum')
489 || $self->ut_numbern('_date')
490 || $self->ut_money('paid')
491 || $self->ut_alphan('otaker')
492 || $self->ut_textn('paybatch')
493 || $self->ut_textn('payunique')
494 || $self->ut_enum('closed', [ '', 'Y' ])
495 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
496 || $self->payinfo_check()
497 || $self->ut_numbern('discount_term')
499 return $error if $error;
501 return "paid must be > 0 " if $self->paid <= 0;
503 return "unknown cust_main.custnum: ". $self->custnum
505 || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
507 $self->_date(time) unless $self->_date;
509 return "invalid discount_term"
510 if ($self->discount_term && $self->discount_term < 2);
512 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
513 # # UNIQUE index should catch this too, without race conditions, but this
514 # # should give a better error message the other 99.9% of the time...
515 # if ( length($self->payunique)
516 # && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
517 # #well, it *could* be a better error message
518 # return "duplicate transaction".
519 # " - a payment with unique identifer ". $self->payunique.
526 =item send_receipt HASHREF | OPTION => VALUE ...
528 Sends a payment receipt for this payment..
536 Flag indicating the payment is being made manually.
540 Invoice (FS::cust_bill) object. If not specified, the most recent invoice
545 Customer (FS::cust_main) object (for efficiency).
553 my $opt = ref($_[0]) ? shift : { @_ };
555 my $cust_bill = $opt->{'cust_bill'};
556 my $cust_main = $opt->{'cust_main'} || $self->cust_main;
558 my $conf = new FS::Conf;
560 return '' unless $conf->exists('payment_receipt', $cust_main->agentnum);
562 my @invoicing_list = $cust_main->invoicing_list_emailonly;
563 return '' unless @invoicing_list;
565 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
569 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
570 #|| ! $conf->exists('invoice_html_statement')
574 my $msgnum = $conf->config('payment_receipt_msgnum', $cust_main->agentnum);
576 my $msg_template = FS::msg_template->by_key($msgnum);
577 $error = $msg_template->send(
578 'cust_main' => $cust_main,
580 'from_config' => 'payment_receipt_from',
583 } elsif ( $conf->exists('payment_receipt_email') ) {
585 my $receipt_template = new Text::Template (
587 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
589 warn "can't create payment receipt template: $Text::Template::ERROR";
593 my $payby = $self->payby;
594 my $payinfo = $self->payinfo;
595 $payby =~ s/^BILL$/Check/ if $payinfo;
596 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
597 $payinfo = $self->paymask
599 $payinfo = $self->decrypt($payinfo);
601 $payby =~ s/^CHEK$/Electronic check/;
604 'date' => time2str("%a %B %o, %Y", $self->_date),
605 'name' => $cust_main->name,
606 'paynum' => $self->paynum,
607 'paid' => sprintf("%.2f", $self->paid),
608 'payby' => ucfirst(lc($payby)),
609 'payinfo' => $payinfo,
610 'balance' => $cust_main->balance,
611 'company_name' => $conf->config('company_name', $cust_main->agentnum),
614 if ( $opt->{'cust_pkg'} ) {
615 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
616 #setup date, other things?
620 'from' => $conf->config('invoice_from', $cust_main->agentnum),
621 #invoice_from??? well as good as any
622 'to' => \@invoicing_list,
623 'subject' => 'Payment receipt',
624 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
629 warn "payment_receipt is on, but no payment_receipt_msgnum\n";
635 my $queue = new FS::queue {
636 'paynum' => $self->paynum,
637 'job' => 'FS::cust_bill::queueable_email',
640 $error = $queue->insert(
641 'invnum' => $cust_bill->invnum,
642 'template' => 'statement',
643 'notice_name' => 'Statement',
649 warn "send_receipt: $error\n" if $error;
654 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
661 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
662 sort { $a->_date <=> $b->_date
663 || $a->invnum <=> $b->invnum }
664 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
668 =item cust_pay_refund
670 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
675 sub cust_pay_refund {
677 map { $_ } #return $self->num_cust_pay_refund unless wantarray;
678 sort { $a->_date <=> $b->_date }
679 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
686 Returns the amount of this payment that is still unapplied; which is
687 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
688 applications (see L<FS::cust_pay_refund>).
694 my $amount = $self->paid;
695 $amount -= $_->amount foreach ( $self->cust_bill_pay );
696 $amount -= $_->amount foreach ( $self->cust_pay_refund );
697 sprintf("%.2f", $amount );
702 Returns the amount of this payment that has not been refuned; which is
703 paid minus all refund applications (see L<FS::cust_pay_refund>).
709 my $amount = $self->paid;
710 $amount -= $_->amount foreach ( $self->cust_pay_refund );
711 sprintf("%.2f", $amount );
716 Returns the "paid" field.
731 =item batch_insert CUST_PAY_OBJECT, ...
733 Class method which inserts multiple payments. Takes a list of FS::cust_pay
734 objects. Returns a list, each element representing the status of inserting the
735 corresponding payment - empty. If there is an error inserting any payment, the
736 entire transaction is rolled back, i.e. all payments are inserted or none are.
740 my @errors = FS::cust_pay->batch_insert(@cust_pay);
741 my $num_errors = scalar(grep $_, @errors);
742 if ( $num_errors == 0 ) {
743 #success; all payments were inserted
745 #failure; no payments were inserted.
751 my $self = shift; #class method
753 local $SIG{HUP} = 'IGNORE';
754 local $SIG{INT} = 'IGNORE';
755 local $SIG{QUIT} = 'IGNORE';
756 local $SIG{TERM} = 'IGNORE';
757 local $SIG{TSTP} = 'IGNORE';
758 local $SIG{PIPE} = 'IGNORE';
760 my $oldAutoCommit = $FS::UID::AutoCommit;
761 local $FS::UID::AutoCommit = 0;
767 my $error = $_->insert( 'manual' => 1 );
771 $_->cust_main->apply_payments;
777 $dbh->rollback if $oldAutoCommit;
779 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
788 Returns an SQL fragment to retreive the unapplied amount.
793 my ($class, $start, $end) = @_;
794 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
795 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
796 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
797 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
801 ( SELECT SUM(amount) FROM cust_bill_pay
802 WHERE cust_pay.paynum = cust_bill_pay.paynum
803 $bill_start $bill_end )
807 ( SELECT SUM(amount) FROM cust_pay_refund
808 WHERE cust_pay.paynum = cust_pay_refund.paynum
809 $refund_start $refund_end )
818 # Used by FS::Upgrade to migrate to a new database.
822 sub _upgrade_data { #class method
823 my ($class, %opts) = @_;
825 warn "$me upgrading $class\n" if $DEBUG;
828 # otaker/ivan upgrade
831 #not the most efficient, but hey, it only has to run once
833 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
834 " AND usernum IS NULL ".
835 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
836 " WHERE cust_main.custnum = cust_pay.custnum ) ";
838 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
840 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
841 $sth->execute or die $sth->errstr;
842 my $total = $sth->fetchrow_arrayref->[0];
843 #warn "$total cust_pay records to update\n"
845 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
850 my @cust_pay = qsearch( {
851 'table' => 'cust_pay',
853 'extra_sql' => $where,
854 'order_by' => 'ORDER BY paynum',
857 foreach my $cust_pay (@cust_pay) {
859 my $h_cust_pay = $cust_pay->h_search('insert');
861 next if $cust_pay->otaker eq $h_cust_pay->history_user;
862 #$cust_pay->otaker($h_cust_pay->history_user);
863 $cust_pay->set('otaker', $h_cust_pay->history_user);
865 $cust_pay->set('otaker', 'legacy');
868 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
869 my $error = $cust_pay->replace;
872 warn " *** WARNING: Error updating order taker for payment paynum ".
873 $cust_pay->paynun. ": $error\n";
877 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
880 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
881 warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
888 # payinfo N/A upgrade
891 #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
893 my @na_cust_pay = qsearch( {
894 'table' => 'cust_pay',
895 'hashref' => {}, #could be encrypted# { 'payinfo' => 'N/A' },
896 'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
899 foreach my $na ( @na_cust_pay ) {
901 next unless $na->payinfo eq 'N/A';
903 my $cust_pay_pending =
904 qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
905 unless ( $cust_pay_pending ) {
906 warn " *** WARNING: not-yet recoverable N/A card for payment ".
907 $na->paynum. " (no cust_pay_pending)\n";
910 $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
911 my $error = $na->replace;
913 warn " *** WARNING: Error updating payinfo for payment paynum ".
914 $na->paynun. ": $error\n";
921 # otaker->usernum upgrade
924 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
925 $class->_upgrade_otaker(%opts);
926 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
936 =item batch_import HASHREF
938 Inserts new payments.
945 my $fh = $param->{filehandle};
946 my $agentnum = $param->{agentnum};
947 my $format = $param->{'format'};
948 my $paybatch = $param->{'paybatch'};
950 # here is the agent virtualization
951 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
955 if ( $format eq 'simple' ) {
956 @fields = qw( custnum agent_custid paid payinfo );
958 } elsif ( $format eq 'extended' ) {
959 die "unimplemented\n";
963 die "unknown format $format";
966 eval "use Text::CSV_XS;";
969 my $csv = new Text::CSV_XS;
973 local $SIG{HUP} = 'IGNORE';
974 local $SIG{INT} = 'IGNORE';
975 local $SIG{QUIT} = 'IGNORE';
976 local $SIG{TERM} = 'IGNORE';
977 local $SIG{TSTP} = 'IGNORE';
978 local $SIG{PIPE} = 'IGNORE';
980 my $oldAutoCommit = $FS::UID::AutoCommit;
981 local $FS::UID::AutoCommit = 0;
985 while ( defined($line=<$fh>) ) {
987 $csv->parse($line) or do {
988 $dbh->rollback if $oldAutoCommit;
989 return "can't parse: ". $csv->error_input();
992 my @columns = $csv->fields();
996 paybatch => $paybatch,
1000 foreach my $field ( @fields ) {
1002 if ( $field eq 'agent_custid'
1004 && $columns[0] =~ /\S+/ )
1007 my $agent_custid = $columns[0];
1008 my %hash = ( 'agent_custid' => $agent_custid,
1009 'agentnum' => $agentnum,
1012 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
1013 $dbh->rollback if $oldAutoCommit;
1014 return "can't specify custnum with agent_custid $agent_custid";
1017 $cust_main = qsearchs({
1018 'table' => 'cust_main',
1019 'hashref' => \%hash,
1020 'extra_sql' => $extra_sql,
1023 unless ( $cust_main ) {
1024 $dbh->rollback if $oldAutoCommit;
1025 return "can't find customer with agent_custid $agent_custid";
1029 $columns[0] = $cust_main->custnum;
1032 $cust_pay{$field} = shift @columns;
1035 my $cust_pay = new FS::cust_pay( \%cust_pay );
1036 my $error = $cust_pay->insert;
1039 $dbh->rollback if $oldAutoCommit;
1040 return "can't insert payment for $line: $error";
1043 if ( $format eq 'simple' ) {
1044 # include agentnum for less surprise?
1045 $cust_main = qsearchs({
1046 'table' => 'cust_main',
1047 'hashref' => { 'custnum' => $cust_pay->custnum },
1048 'extra_sql' => $extra_sql,
1052 unless ( $cust_main ) {
1053 $dbh->rollback if $oldAutoCommit;
1054 return "can't find customer to which payments apply at line: $line";
1057 $error = $cust_main->apply_payments_and_credits;
1059 $dbh->rollback if $oldAutoCommit;
1060 return "can't apply payments to customer for $line: $error";
1068 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1070 return "Empty file!" unless $imported;
1080 Delete and replace methods.
1084 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
1085 schema.html from the base documentation.