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;
25 use FS::upgrade_journal;
29 $me = '[FS::cust_pay]';
33 #ask FS::UID to run this stuff for us later
34 FS::UID->install_callback( sub {
36 $unsuspendauto = $conf->exists('unsuspendauto');
39 @encrypted_fields = ('payinfo');
40 sub nohistory_fields { ('payinfo'); }
44 FS::cust_pay - Object methods for cust_pay objects
50 $record = new FS::cust_pay \%hash;
51 $record = new FS::cust_pay { 'column' => 'value' };
53 $error = $record->insert;
55 $error = $new_record->replace($old_record);
57 $error = $record->delete;
59 $error = $record->check;
63 An FS::cust_pay object represents a payment; the transfer of money from a
64 customer. FS::cust_pay inherits from FS::Record. The following fields are
71 primary key (assigned automatically for new payments)
75 customer (see L<FS::cust_main>)
79 specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
80 L<Time::Local> and L<Date::Parse> for conversion functions.
84 Amount of this payment
88 order taker (see L<FS::access_user>)
92 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
96 Payment Information (See L<FS::payinfo_Mixin> for data format)
100 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
104 text field for tracking card processing or other batch grouping
108 Optional unique identifer to prevent duplicate transactions.
112 books closed flag, empty or `Y'
116 Desired pkgnum when using experimental package balances.
120 The bank where the payment was deposited.
124 The name of the depositor.
128 The deposit account number.
142 Creates a new payment. To add the payment to the databse, see L<"insert">.
146 sub table { 'cust_pay'; }
147 sub cust_linked { $_[0]->cust_main_custnum; }
148 sub cust_unlinked_msg {
150 "WARNING: can't find cust_main.custnum ". $self->custnum.
151 ' (cust_pay.paynum '. $self->paynum. ')';
154 =item insert [ OPTION => VALUE ... ]
156 Adds this payment to the database.
158 For backwards-compatibility and convenience, if the additional field invnum
159 is defined, an FS::cust_bill_pay record for the full amount of the payment
160 will be created. In this case, custnum is optional.
162 If the additional field discount_term is defined then a prepayment discount
163 is taken for that length of time. It is an error for the customer to owe
164 after this payment is made.
166 A hash of optional arguments may be passed. Currently "manual" is supported.
167 If true, a payment receipt is sent instead of a statement when
168 'payment_receipt_email' configuration option is set.
173 my($self, %options) = @_;
175 local $SIG{HUP} = 'IGNORE';
176 local $SIG{INT} = 'IGNORE';
177 local $SIG{QUIT} = 'IGNORE';
178 local $SIG{TERM} = 'IGNORE';
179 local $SIG{TSTP} = 'IGNORE';
180 local $SIG{PIPE} = 'IGNORE';
182 my $oldAutoCommit = $FS::UID::AutoCommit;
183 local $FS::UID::AutoCommit = 0;
187 if ( $self->invnum ) {
188 $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
190 $dbh->rollback if $oldAutoCommit;
191 return "Unknown cust_bill.invnum: ". $self->invnum;
193 $self->custnum($cust_bill->custnum );
196 my $error = $self->check;
197 return $error if $error;
199 my $cust_main = $self->cust_main;
200 my $old_balance = $cust_main->balance;
202 $error = $self->SUPER::insert;
204 $dbh->rollback if $oldAutoCommit;
205 return "error inserting cust_pay: $error";
208 if ( my $credit_type = $conf->config('prepayment_discounts-credit_type') ) {
209 if ( my $months = $self->discount_term ) {
210 # XXX this should be moved out somewhere, but discount_term_values
212 my ($cust_bill) = ($cust_main->cust_bill)[-1]; # most recent invoice
213 return "can't accept prepayment for an unbilled customer" if !$cust_bill;
215 # %billing_pkgs contains this customer's active monthly packages.
216 # Recurring fees for those packages will be credited and then rebilled
217 # for the full discount term. Other packages on the last invoice
218 # (canceled, non-monthly recurring, or one-time charges) will be
220 my %billing_pkgs = map { $_->pkgnum => $_ }
221 grep { $_->part_pkg->freq eq '1' }
222 $cust_main->billing_pkgs;
223 my $credit = 0; # sum of recurring charges from that invoice
224 my $last_bill_date = 0; # the real bill date
225 foreach my $item ( $cust_bill->cust_bill_pkg ) {
226 next if !exists($billing_pkgs{$item->pkgnum}); # skip inactive packages
227 $credit += $item->recur;
228 $last_bill_date = $item->cust_pkg->last_bill
229 if defined($item->cust_pkg)
230 and $item->cust_pkg->last_bill > $last_bill_date
233 my $cust_credit = new FS::cust_credit {
234 'custnum' => $self->custnum,
235 'amount' => sprintf('%.2f', $credit),
236 'reason' => 'customer chose to prepay for discount',
238 $error = $cust_credit->insert('reason_type' => $credit_type);
240 $dbh->rollback if $oldAutoCommit;
241 return "error inserting prepayment credit: $error";
245 # bill for the entire term
246 $_->bill($_->last_bill) foreach (values %billing_pkgs);
247 $error = $cust_main->bill(
248 # no recurring_only, we want unbilled packages with start dates to
250 'no_usage_reset' => 1,
251 'time' => $last_bill_date, # not $cust_bill->_date
252 'pkg_list' => [ values %billing_pkgs ],
253 'freq_override' => $months,
256 $dbh->rollback if $oldAutoCommit;
257 return "error inserting cust_pay: $error";
259 $error = $cust_main->apply_payments_and_credits;
261 $dbh->rollback if $oldAutoCommit;
262 return "error inserting cust_pay: $error";
264 my $new_balance = $cust_main->balance;
265 if ($new_balance > 0) {
266 $dbh->rollback if $oldAutoCommit;
267 return "balance after prepay discount attempt: $new_balance";
269 # user friendly: override the "apply only to this invoice" mode
276 if ( $self->invnum ) {
277 my $cust_bill_pay = new FS::cust_bill_pay {
278 'invnum' => $self->invnum,
279 'paynum' => $self->paynum,
280 'amount' => $self->paid,
281 '_date' => $self->_date,
283 $error = $cust_bill_pay->insert(%options);
285 if ( $ignore_noapply ) {
286 warn "warning: error inserting cust_bill_pay: $error ".
287 "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
289 $dbh->rollback if $oldAutoCommit;
290 return "error inserting cust_bill_pay: $error";
295 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
297 #false laziness w/ cust_credit::insert
298 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
299 my @errors = $cust_main->unsuspend;
301 # side-fx with nested transactions? upstack rolls back?
302 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
308 #bill setup fees for voip_cdr bill_every_call packages
309 #some false laziness w/search in freeside-cdrd
311 'LEFT JOIN part_pkg USING ( pkgpart ) '.
312 "LEFT JOIN part_pkg_option
313 ON ( cust_pkg.pkgpart = part_pkg_option.pkgpart
314 AND part_pkg_option.optionname = 'bill_every_call' )";
316 my $extra_sql = " AND plan = 'voip_cdr' AND optionvalue = '1' ".
317 " AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 ) ";
319 my @cust_pkg = qsearch({
320 'table' => 'cust_pkg',
321 'addl_from' => $addl_from,
322 'hashref' => { 'custnum' => $self->custnum,
326 'extra_sql' => $extra_sql,
330 warn "voip_cdr bill_every_call packages found; billing customer\n";
331 my $bill_error = $self->cust_main->bill_and_collect( 'fatal' => 'return' );
333 warn "WARNING: Error billing customer: $bill_error\n";
336 #end of billing setup fees for voip_cdr bill_every_call packages
338 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
341 my $trigger = $conf->config('payment_receipt-trigger',
342 $self->cust_main->agentnum) || 'cust_pay';
343 if ( $trigger eq 'cust_pay' ) {
344 my $error = $self->send_receipt(
345 'manual' => $options{'manual'},
346 'cust_bill' => $cust_bill,
347 'cust_main' => $cust_main,
349 warn "can't send payment receipt/statement: $error" if $error;
356 =item void [ REASON ]
358 Voids this payment: deletes the payment and all associated applications and
359 adds a record of the voided payment to the FS::cust_pay_void table.
366 local $SIG{HUP} = 'IGNORE';
367 local $SIG{INT} = 'IGNORE';
368 local $SIG{QUIT} = 'IGNORE';
369 local $SIG{TERM} = 'IGNORE';
370 local $SIG{TSTP} = 'IGNORE';
371 local $SIG{PIPE} = 'IGNORE';
373 my $oldAutoCommit = $FS::UID::AutoCommit;
374 local $FS::UID::AutoCommit = 0;
377 my $cust_pay_void = new FS::cust_pay_void ( {
378 map { $_ => $self->get($_) } $self->fields
380 $cust_pay_void->reason(shift) if scalar(@_);
381 my $error = $cust_pay_void->insert;
383 $dbh->rollback if $oldAutoCommit;
387 $error = $self->delete;
389 $dbh->rollback if $oldAutoCommit;
393 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
401 Unless the closed flag is set, deletes this payment and all associated
402 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>). In most
403 cases, you want to use the void method instead to leave a record of the
408 # very similar to FS::cust_credit::delete
411 return "Can't delete closed payment" if $self->closed =~ /^Y/i;
413 local $SIG{HUP} = 'IGNORE';
414 local $SIG{INT} = 'IGNORE';
415 local $SIG{QUIT} = 'IGNORE';
416 local $SIG{TERM} = 'IGNORE';
417 local $SIG{TSTP} = 'IGNORE';
418 local $SIG{PIPE} = 'IGNORE';
420 my $oldAutoCommit = $FS::UID::AutoCommit;
421 local $FS::UID::AutoCommit = 0;
424 foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
425 my $error = $app->delete;
427 $dbh->rollback if $oldAutoCommit;
432 my $error = $self->SUPER::delete(@_);
434 $dbh->rollback if $oldAutoCommit;
438 if ( $conf->exists('deletepayments')
439 && $conf->config('deletepayments') ne '' ) {
441 my $cust_main = $self->cust_main;
443 my $error = send_email(
444 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
445 #invoice_from??? well as good as any
446 'to' => $conf->config('deletepayments'),
447 'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
449 "This is an automatic message from your Freeside installation\n",
450 "informing you that the following payment has been deleted:\n",
452 'paynum: '. $self->paynum. "\n",
453 'custnum: '. $self->custnum.
454 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
455 'paid: $'. sprintf("%.2f", $self->paid). "\n",
456 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
457 'payby: '. $self->payby. "\n",
458 'payinfo: '. $self->paymask. "\n",
459 'paybatch: '. $self->paybatch. "\n",
464 $dbh->rollback if $oldAutoCommit;
465 return "can't send payment deletion notification: $error";
470 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
476 =item replace [ OLD_RECORD ]
478 You can, but probably shouldn't modify payments...
480 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
481 supplied, replaces this record. If there is an error, returns the error,
482 otherwise returns false.
488 return "Can't modify closed payment" if $self->closed =~ /^Y/i;
489 $self->SUPER::replace(@_);
494 Checks all fields to make sure this is a valid payment. If there is an error,
495 returns the error, otherwise returns false. Called by the insert method.
502 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
505 $self->ut_numbern('paynum')
506 || $self->ut_numbern('custnum')
507 || $self->ut_numbern('_date')
508 || $self->ut_money('paid')
509 || $self->ut_alphan('otaker')
510 || $self->ut_textn('paybatch')
511 || $self->ut_textn('payunique')
512 || $self->ut_enum('closed', [ '', 'Y' ])
513 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
514 || $self->ut_textn('bank')
515 || $self->ut_alphan('depositor')
516 || $self->ut_numbern('account')
517 || $self->ut_numbern('teller')
518 || $self->payinfo_check()
520 return $error if $error;
522 return "paid must be > 0 " if $self->paid <= 0;
524 return "unknown cust_main.custnum: ". $self->custnum
526 || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
528 $self->_date(time) unless $self->_date;
530 return "invalid discount_term"
531 if ($self->discount_term && $self->discount_term < 2);
533 if ( $self->payby eq 'CASH' and $conf->exists('require_cash_deposit_info') ) {
534 foreach (qw(bank depositor account teller)) {
535 return "$_ required" if $self->get($_) eq '';
539 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
540 # # UNIQUE index should catch this too, without race conditions, but this
541 # # should give a better error message the other 99.9% of the time...
542 # if ( length($self->payunique)
543 # && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
544 # #well, it *could* be a better error message
545 # return "duplicate transaction".
546 # " - a payment with unique identifer ". $self->payunique.
553 =item send_receipt HASHREF | OPTION => VALUE ...
555 Sends a payment receipt for this payment..
563 Flag indicating the payment is being made manually.
567 Invoice (FS::cust_bill) object. If not specified, the most recent invoice
572 Customer (FS::cust_main) object (for efficiency).
580 my $opt = ref($_[0]) ? shift : { @_ };
582 my $cust_bill = $opt->{'cust_bill'};
583 my $cust_main = $opt->{'cust_main'} || $self->cust_main;
585 my $conf = new FS::Conf;
587 return '' unless $conf->config_bool('payment_receipt', $cust_main->agentnum);
589 my @invoicing_list = $cust_main->invoicing_list_emailonly;
590 return '' unless @invoicing_list;
592 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
596 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
597 #|| ! $conf->exists('invoice_html_statement')
601 my $msgnum = $conf->config('payment_receipt_msgnum', $cust_main->agentnum);
603 my $msg_template = FS::msg_template->by_key($msgnum);
604 $error = $msg_template->send(
605 'cust_main' => $cust_main,
607 'from_config' => 'payment_receipt_from',
610 } elsif ( $conf->exists('payment_receipt_email') ) {
612 my $receipt_template = new Text::Template (
614 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
616 warn "can't create payment receipt template: $Text::Template::ERROR";
620 my $payby = $self->payby;
621 my $payinfo = $self->payinfo;
622 $payby =~ s/^BILL$/Check/ if $payinfo;
623 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
624 $payinfo = $self->paymask
626 $payinfo = $self->decrypt($payinfo);
628 $payby =~ s/^CHEK$/Electronic check/;
631 'date' => time2str("%a %B %o, %Y", $self->_date),
632 'name' => $cust_main->name,
633 'paynum' => $self->paynum,
634 'paid' => sprintf("%.2f", $self->paid),
635 'payby' => ucfirst(lc($payby)),
636 'payinfo' => $payinfo,
637 'balance' => $cust_main->balance,
638 'company_name' => $conf->config('company_name', $cust_main->agentnum),
641 if ( $opt->{'cust_pkg'} ) {
642 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
643 #setup date, other things?
647 'from' => $conf->config('invoice_from', $cust_main->agentnum),
648 #invoice_from??? well as good as any
649 'to' => \@invoicing_list,
650 'subject' => 'Payment receipt',
651 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
656 warn "payment_receipt is on, but no payment_receipt_msgnum\n";
660 } elsif ( ! $cust_main->invoice_noemail ) { #not manual
662 my $queue = new FS::queue {
663 'paynum' => $self->paynum,
664 'job' => 'FS::cust_bill::queueable_email',
667 $error = $queue->insert(
668 'invnum' => $cust_bill->invnum,
669 'template' => 'statement',
670 'notice_name' => 'Statement',
676 warn "send_receipt: $error\n" if $error;
681 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
688 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
689 sort { $a->_date <=> $b->_date
690 || $a->invnum <=> $b->invnum }
691 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
695 =item cust_pay_refund
697 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
702 sub cust_pay_refund {
704 map { $_ } #return $self->num_cust_pay_refund unless wantarray;
705 sort { $a->_date <=> $b->_date }
706 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
713 Returns the amount of this payment that is still unapplied; which is
714 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
715 applications (see L<FS::cust_pay_refund>).
721 my $amount = $self->paid;
722 $amount -= $_->amount foreach ( $self->cust_bill_pay );
723 $amount -= $_->amount foreach ( $self->cust_pay_refund );
724 sprintf("%.2f", $amount );
729 Returns the amount of this payment that has not been refuned; which is
730 paid minus all refund applications (see L<FS::cust_pay_refund>).
736 my $amount = $self->paid;
737 $amount -= $_->amount foreach ( $self->cust_pay_refund );
738 sprintf("%.2f", $amount );
743 Returns the "paid" field.
758 =item batch_insert CUST_PAY_OBJECT, ...
760 Class method which inserts multiple payments. Takes a list of FS::cust_pay
761 objects. Returns a list, each element representing the status of inserting the
762 corresponding payment - empty. If there is an error inserting any payment, the
763 entire transaction is rolled back, i.e. all payments are inserted or none are.
767 my @errors = FS::cust_pay->batch_insert(@cust_pay);
768 my $num_errors = scalar(grep $_, @errors);
769 if ( $num_errors == 0 ) {
770 #success; all payments were inserted
772 #failure; no payments were inserted.
778 my $self = shift; #class method
780 local $SIG{HUP} = 'IGNORE';
781 local $SIG{INT} = 'IGNORE';
782 local $SIG{QUIT} = 'IGNORE';
783 local $SIG{TERM} = 'IGNORE';
784 local $SIG{TSTP} = 'IGNORE';
785 local $SIG{PIPE} = 'IGNORE';
787 my $oldAutoCommit = $FS::UID::AutoCommit;
788 local $FS::UID::AutoCommit = 0;
794 my $error = $_->insert( 'manual' => 1 );
798 $_->cust_main->apply_payments;
804 $dbh->rollback if $oldAutoCommit;
806 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
815 Returns an SQL fragment to retreive the unapplied amount.
820 my ($class, $start, $end) = @_;
821 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
822 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
823 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
824 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
828 ( SELECT SUM(amount) FROM cust_bill_pay
829 WHERE cust_pay.paynum = cust_bill_pay.paynum
830 $bill_start $bill_end )
834 ( SELECT SUM(amount) FROM cust_pay_refund
835 WHERE cust_pay.paynum = cust_pay_refund.paynum
836 $refund_start $refund_end )
845 # Used by FS::Upgrade to migrate to a new database.
849 sub _upgrade_data { #class method
850 my ($class, %opts) = @_;
852 warn "$me upgrading $class\n" if $DEBUG;
855 # otaker/ivan upgrade
858 unless ( FS::upgrade_journal->is_done('cust_pay__otaker_ivan') ) {
860 #not the most efficient, but hey, it only has to run once
862 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
863 " AND usernum IS NULL ".
864 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
865 " WHERE cust_main.custnum = cust_pay.custnum ) ";
867 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
869 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
870 $sth->execute or die $sth->errstr;
871 my $total = $sth->fetchrow_arrayref->[0];
872 #warn "$total cust_pay records to update\n"
874 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
879 my @cust_pay = qsearch( {
880 'table' => 'cust_pay',
882 'extra_sql' => $where,
883 'order_by' => 'ORDER BY paynum',
886 foreach my $cust_pay (@cust_pay) {
888 my $h_cust_pay = $cust_pay->h_search('insert');
890 next if $cust_pay->otaker eq $h_cust_pay->history_user;
891 #$cust_pay->otaker($h_cust_pay->history_user);
892 $cust_pay->set('otaker', $h_cust_pay->history_user);
894 $cust_pay->set('otaker', 'legacy');
897 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
898 my $error = $cust_pay->replace;
901 warn " *** WARNING: Error updating order taker for payment paynum ".
902 $cust_pay->paynun. ": $error\n";
906 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
909 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
910 warn "$me $count/$total (".sprintf('%.2f',100*$count/$total). '%)'."\n";
916 FS::upgrade_journal->set_done('cust_pay__otaker_ivan');
920 # payinfo N/A upgrade
923 unless ( FS::upgrade_journal->is_done('cust_pay__payinfo_na') ) {
925 #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
927 my @na_cust_pay = qsearch( {
928 'table' => 'cust_pay',
929 'hashref' => {}, #could be encrypted# { 'payinfo' => 'N/A' },
930 'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
933 foreach my $na ( @na_cust_pay ) {
935 next unless $na->payinfo eq 'N/A';
937 my $cust_pay_pending =
938 qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
939 unless ( $cust_pay_pending ) {
940 warn " *** WARNING: not-yet recoverable N/A card for payment ".
941 $na->paynum. " (no cust_pay_pending)\n";
944 $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
945 my $error = $na->replace;
947 warn " *** WARNING: Error updating payinfo for payment paynum ".
948 $na->paynun. ": $error\n";
954 FS::upgrade_journal->set_done('cust_pay__payinfo_na');
958 # otaker->usernum upgrade
961 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
962 $class->_upgrade_otaker(%opts);
963 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
973 =item batch_import HASHREF
975 Inserts new payments.
982 my $fh = $param->{filehandle};
983 my $agentnum = $param->{agentnum};
984 my $format = $param->{'format'};
985 my $paybatch = $param->{'paybatch'};
987 # here is the agent virtualization
988 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
992 if ( $format eq 'simple' ) {
993 @fields = qw( custnum agent_custid paid payinfo );
995 } elsif ( $format eq 'extended' ) {
996 die "unimplemented\n";
1000 die "unknown format $format";
1003 eval "use Text::CSV_XS;";
1006 my $csv = new Text::CSV_XS;
1010 local $SIG{HUP} = 'IGNORE';
1011 local $SIG{INT} = 'IGNORE';
1012 local $SIG{QUIT} = 'IGNORE';
1013 local $SIG{TERM} = 'IGNORE';
1014 local $SIG{TSTP} = 'IGNORE';
1015 local $SIG{PIPE} = 'IGNORE';
1017 my $oldAutoCommit = $FS::UID::AutoCommit;
1018 local $FS::UID::AutoCommit = 0;
1022 while ( defined($line=<$fh>) ) {
1024 $csv->parse($line) or do {
1025 $dbh->rollback if $oldAutoCommit;
1026 return "can't parse: ". $csv->error_input();
1029 my @columns = $csv->fields();
1033 paybatch => $paybatch,
1037 foreach my $field ( @fields ) {
1039 if ( $field eq 'agent_custid'
1041 && $columns[0] =~ /\S+/ )
1044 my $agent_custid = $columns[0];
1045 my %hash = ( 'agent_custid' => $agent_custid,
1046 'agentnum' => $agentnum,
1049 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
1050 $dbh->rollback if $oldAutoCommit;
1051 return "can't specify custnum with agent_custid $agent_custid";
1054 $cust_main = qsearchs({
1055 'table' => 'cust_main',
1056 'hashref' => \%hash,
1057 'extra_sql' => $extra_sql,
1060 unless ( $cust_main ) {
1061 $dbh->rollback if $oldAutoCommit;
1062 return "can't find customer with agent_custid $agent_custid";
1066 $columns[0] = $cust_main->custnum;
1069 $cust_pay{$field} = shift @columns;
1072 my $cust_pay = new FS::cust_pay( \%cust_pay );
1073 my $error = $cust_pay->insert;
1076 $dbh->rollback if $oldAutoCommit;
1077 return "can't insert payment for $line: $error";
1080 if ( $format eq 'simple' ) {
1081 # include agentnum for less surprise?
1082 $cust_main = qsearchs({
1083 'table' => 'cust_main',
1084 'hashref' => { 'custnum' => $cust_pay->custnum },
1085 'extra_sql' => $extra_sql,
1089 unless ( $cust_main ) {
1090 $dbh->rollback if $oldAutoCommit;
1091 return "can't find customer to which payments apply at line: $line";
1094 $error = $cust_main->apply_payments_and_credits;
1096 $dbh->rollback if $oldAutoCommit;
1097 return "can't apply payments to customer for $line: $error";
1105 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1107 return "Empty file!" unless $imported;
1117 Delete and replace methods.
1121 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
1122 schema.html from the base documentation.