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 A hash of optional arguments may be passed. Currently "manual" is supported.
145 If true, a payment receipt is sent instead of a statement when
146 'payment_receipt_email' configuration option is set.
151 my($self, %options) = @_;
153 local $SIG{HUP} = 'IGNORE';
154 local $SIG{INT} = 'IGNORE';
155 local $SIG{QUIT} = 'IGNORE';
156 local $SIG{TERM} = 'IGNORE';
157 local $SIG{TSTP} = 'IGNORE';
158 local $SIG{PIPE} = 'IGNORE';
160 my $oldAutoCommit = $FS::UID::AutoCommit;
161 local $FS::UID::AutoCommit = 0;
165 if ( $self->invnum ) {
166 $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
168 $dbh->rollback if $oldAutoCommit;
169 return "Unknown cust_bill.invnum: ". $self->invnum;
171 $self->custnum($cust_bill->custnum );
174 my $error = $self->check;
175 return $error if $error;
177 my $cust_main = $self->cust_main;
178 my $old_balance = $cust_main->balance;
180 $error = $self->SUPER::insert;
182 $dbh->rollback if $oldAutoCommit;
183 return "error inserting cust_pay: $error";
186 if ( $self->invnum ) {
187 my $cust_bill_pay = new FS::cust_bill_pay {
188 'invnum' => $self->invnum,
189 'paynum' => $self->paynum,
190 'amount' => $self->paid,
191 '_date' => $self->_date,
193 $error = $cust_bill_pay->insert(%options);
195 if ( $ignore_noapply ) {
196 warn "warning: error inserting cust_bill_pay: $error ".
197 "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
199 $dbh->rollback if $oldAutoCommit;
200 return "error inserting cust_bill_pay: $error";
205 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
207 #false laziness w/ cust_credit::insert
208 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
209 my @errors = $cust_main->unsuspend;
211 # side-fx with nested transactions? upstack rolls back?
212 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
218 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
221 my $trigger = $conf->config('payment_receipt-trigger') || 'cust_pay';
222 if ( $trigger eq 'cust_pay' ) {
223 my $error = $self->send_receipt(
224 'manual' => $options{'manual'},
225 'cust_bill' => $cust_bill,
226 'cust_main' => $cust_main,
228 warn "can't send payment receipt/statement: $error" if $error;
235 =item void [ REASON ]
237 Voids this payment: deletes the payment and all associated applications and
238 adds a record of the voided payment to the FS::cust_pay_void table.
245 local $SIG{HUP} = 'IGNORE';
246 local $SIG{INT} = 'IGNORE';
247 local $SIG{QUIT} = 'IGNORE';
248 local $SIG{TERM} = 'IGNORE';
249 local $SIG{TSTP} = 'IGNORE';
250 local $SIG{PIPE} = 'IGNORE';
252 my $oldAutoCommit = $FS::UID::AutoCommit;
253 local $FS::UID::AutoCommit = 0;
256 my $cust_pay_void = new FS::cust_pay_void ( {
257 map { $_ => $self->get($_) } $self->fields
259 $cust_pay_void->reason(shift) if scalar(@_);
260 my $error = $cust_pay_void->insert;
262 $dbh->rollback if $oldAutoCommit;
266 $error = $self->delete;
268 $dbh->rollback if $oldAutoCommit;
272 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280 Unless the closed flag is set, deletes this payment and all associated
281 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>). In most
282 cases, you want to use the void method instead to leave a record of the
287 # very similar to FS::cust_credit::delete
290 return "Can't delete closed payment" if $self->closed =~ /^Y/i;
292 local $SIG{HUP} = 'IGNORE';
293 local $SIG{INT} = 'IGNORE';
294 local $SIG{QUIT} = 'IGNORE';
295 local $SIG{TERM} = 'IGNORE';
296 local $SIG{TSTP} = 'IGNORE';
297 local $SIG{PIPE} = 'IGNORE';
299 my $oldAutoCommit = $FS::UID::AutoCommit;
300 local $FS::UID::AutoCommit = 0;
303 foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
304 my $error = $app->delete;
306 $dbh->rollback if $oldAutoCommit;
311 my $error = $self->SUPER::delete(@_);
313 $dbh->rollback if $oldAutoCommit;
317 if ( $conf->exists('deletepayments')
318 && $conf->config('deletepayments') ne '' ) {
320 my $cust_main = $self->cust_main;
322 my $error = send_email(
323 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
324 #invoice_from??? well as good as any
325 'to' => $conf->config('deletepayments'),
326 'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
328 "This is an automatic message from your Freeside installation\n",
329 "informing you that the following payment has been deleted:\n",
331 'paynum: '. $self->paynum. "\n",
332 'custnum: '. $self->custnum.
333 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
334 'paid: $'. sprintf("%.2f", $self->paid). "\n",
335 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
336 'payby: '. $self->payby. "\n",
337 'payinfo: '. $self->paymask. "\n",
338 'paybatch: '. $self->paybatch. "\n",
343 $dbh->rollback if $oldAutoCommit;
344 return "can't send payment deletion notification: $error";
349 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
355 =item replace OLD_RECORD
357 You can, but probably shouldn't modify payments...
362 #return "Can't modify payment!"
364 return "Can't modify closed payment" if $self->closed =~ /^Y/i;
365 $self->SUPER::replace(@_);
370 Checks all fields to make sure this is a valid payment. If there is an error,
371 returns the error, otherwise returns false. Called by the insert method.
378 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
381 $self->ut_numbern('paynum')
382 || $self->ut_numbern('custnum')
383 || $self->ut_numbern('_date')
384 || $self->ut_money('paid')
385 || $self->ut_alphan('otaker')
386 || $self->ut_textn('paybatch')
387 || $self->ut_textn('payunique')
388 || $self->ut_enum('closed', [ '', 'Y' ])
389 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
390 || $self->payinfo_check()
392 return $error if $error;
394 return "paid must be > 0 " if $self->paid <= 0;
396 return "unknown cust_main.custnum: ". $self->custnum
398 || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
400 $self->_date(time) unless $self->_date;
402 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
403 # # UNIQUE index should catch this too, without race conditions, but this
404 # # should give a better error message the other 99.9% of the time...
405 # if ( length($self->payunique)
406 # && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
407 # #well, it *could* be a better error message
408 # return "duplicate transaction".
409 # " - a payment with unique identifer ". $self->payunique.
416 =item send_receipt HASHREF | OPTION => VALUE ...
418 Sends a payment receipt for this payment..
426 Flag indicating the payment is being made manually.
430 Invoice (FS::cust_bill) object. If not specified, the most recent invoice
435 Customer (FS::cust_main) object (for efficiency).
443 my $opt = ref($_[0]) ? shift : { @_ };
445 my $cust_bill = $opt->{'cust_bill'};
446 my $cust_main = $opt->{'cust_main'} || $self->cust_main;
448 my $conf = new FS::Conf;
450 my @invoicing_list = $cust_main->invoicing_list_emailonly;
451 return '' unless @invoicing_list;
453 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
455 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
456 || ! $conf->exists('invoice_html_statement') # XXX msg_template
462 if ( $conf->exists('payment_receipt_msgnum')
463 && $conf->config('payment_receipt_msgnum')
467 FS::msg_template->by_key($conf->config('payment_receipt_msgnum'));
468 $error = $msg_template->send('cust_main'=> $cust_main, 'object'=> $self);
470 } elsif ( $conf->exists('payment_receipt_email') ) {
471 my $receipt_template = new Text::Template (
473 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
475 warn "can't create payment receipt template: $Text::Template::ERROR";
479 my $payby = $self->payby;
480 my $payinfo = $self->payinfo;
481 $payby =~ s/^BILL$/Check/ if $payinfo;
482 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
483 $payinfo = $self->paymask
485 $payinfo = $self->decrypt($payinfo);
487 $payby =~ s/^CHEK$/Electronic check/;
490 'date' => time2str("%a %B %o, %Y", $self->_date),
491 'name' => $cust_main->name,
492 'paynum' => $self->paynum,
493 'paid' => sprintf("%.2f", $self->paid),
494 'payby' => ucfirst(lc($payby)),
495 'payinfo' => $payinfo,
496 'balance' => $cust_main->balance,
497 'company_name' => $conf->config('company_name', $cust_main->agentnum),
500 if ( $opt->{'cust_pkg'} ) {
501 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
502 #setup date, other things?
506 'from' => $conf->config('invoice_from', $cust_main->agentnum),
507 #invoice_from??? well as good as any
508 'to' => \@invoicing_list,
509 'subject' => 'Payment receipt',
510 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
513 } else { # no payment_receipt_msgnum or payment_receipt_email
515 my $queue = new FS::queue {
516 'paynum' => $self->paynum,
517 'job' => 'FS::cust_bill::queueable_email',
521 'invnum' => $cust_bill->invnum,
522 'template' => 'statement',
526 warn "send_receipt: $error\n" if $error;
527 } #$opt{manual} || no invoice_html_statement || customer has no invoices
532 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
539 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
540 sort { $a->_date <=> $b->_date
541 || $a->invnum <=> $b->invnum }
542 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
546 =item cust_pay_refund
548 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
553 sub cust_pay_refund {
555 map { $_ } #return $self->num_cust_pay_refund unless wantarray;
556 sort { $a->_date <=> $b->_date }
557 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
564 Returns the amount of this payment that is still unapplied; which is
565 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
566 applications (see L<FS::cust_pay_refund>).
572 my $amount = $self->paid;
573 $amount -= $_->amount foreach ( $self->cust_bill_pay );
574 $amount -= $_->amount foreach ( $self->cust_pay_refund );
575 sprintf("%.2f", $amount );
580 Returns the amount of this payment that has not been refuned; which is
581 paid minus all refund applications (see L<FS::cust_pay_refund>).
587 my $amount = $self->paid;
588 $amount -= $_->amount foreach ( $self->cust_pay_refund );
589 sprintf("%.2f", $amount );
594 Returns the "paid" field.
609 =item batch_insert CUST_PAY_OBJECT, ...
611 Class method which inserts multiple payments. Takes a list of FS::cust_pay
612 objects. Returns a list, each element representing the status of inserting the
613 corresponding payment - empty. If there is an error inserting any payment, the
614 entire transaction is rolled back, i.e. all payments are inserted or none are.
618 my @errors = FS::cust_pay->batch_insert(@cust_pay);
619 my $num_errors = scalar(grep $_, @errors);
620 if ( $num_errors == 0 ) {
621 #success; all payments were inserted
623 #failure; no payments were inserted.
629 my $self = shift; #class method
631 local $SIG{HUP} = 'IGNORE';
632 local $SIG{INT} = 'IGNORE';
633 local $SIG{QUIT} = 'IGNORE';
634 local $SIG{TERM} = 'IGNORE';
635 local $SIG{TSTP} = 'IGNORE';
636 local $SIG{PIPE} = 'IGNORE';
638 my $oldAutoCommit = $FS::UID::AutoCommit;
639 local $FS::UID::AutoCommit = 0;
645 my $error = $_->insert( 'manual' => 1 );
649 $_->cust_main->apply_payments;
655 $dbh->rollback if $oldAutoCommit;
657 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
666 Returns an SQL fragment to retreive the unapplied amount.
671 my ($class, $start, $end) = @_;
672 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
673 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
674 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
675 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
679 ( SELECT SUM(amount) FROM cust_bill_pay
680 WHERE cust_pay.paynum = cust_bill_pay.paynum
681 $bill_start $bill_end )
685 ( SELECT SUM(amount) FROM cust_pay_refund
686 WHERE cust_pay.paynum = cust_pay_refund.paynum
687 $refund_start $refund_end )
696 # Used by FS::Upgrade to migrate to a new database.
700 sub _upgrade_data { #class method
701 my ($class, %opts) = @_;
703 warn "$me upgrading $class\n" if $DEBUG;
706 # otaker/ivan upgrade
709 #not the most efficient, but hey, it only has to run once
711 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
712 " AND usernum IS NULL ".
713 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
714 " WHERE cust_main.custnum = cust_pay.custnum ) ";
716 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
718 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
719 $sth->execute or die $sth->errstr;
720 my $total = $sth->fetchrow_arrayref->[0];
721 #warn "$total cust_pay records to update\n"
723 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
728 my @cust_pay = qsearch( {
729 'table' => 'cust_pay',
731 'extra_sql' => $where,
732 'order_by' => 'ORDER BY paynum',
735 foreach my $cust_pay (@cust_pay) {
737 my $h_cust_pay = $cust_pay->h_search('insert');
739 next if $cust_pay->otaker eq $h_cust_pay->history_user;
740 $cust_pay->otaker($h_cust_pay->history_user);
742 $cust_pay->otaker('legacy');
745 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
746 my $error = $cust_pay->replace;
749 warn " *** WARNING: Error updating order taker for payment paynum ".
750 $cust_pay->paynun. ": $error\n";
754 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
757 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
758 warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
765 # payinfo N/A upgrade
768 #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
770 my @na_cust_pay = qsearch( {
771 'table' => 'cust_pay',
772 'hashref' => {}, #could be encrypted# { 'payinfo' => 'N/A' },
773 'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
776 foreach my $na ( @na_cust_pay ) {
778 next unless $na->payinfo eq 'N/A';
780 my $cust_pay_pending =
781 qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
782 unless ( $cust_pay_pending ) {
783 warn " *** WARNING: not-yet recoverable N/A card for payment ".
784 $na->paynum. " (no cust_pay_pending)\n";
787 $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
788 my $error = $na->replace;
790 warn " *** WARNING: Error updating payinfo for payment paynum ".
791 $na->paynun. ": $error\n";
798 # otaker->usernum upgrade
801 $class->_upgrade_otaker(%opts);
811 =item batch_import HASHREF
813 Inserts new payments.
820 my $fh = $param->{filehandle};
821 my $agentnum = $param->{agentnum};
822 my $format = $param->{'format'};
823 my $paybatch = $param->{'paybatch'};
825 # here is the agent virtualization
826 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
830 if ( $format eq 'simple' ) {
831 @fields = qw( custnum agent_custid paid payinfo );
833 } elsif ( $format eq 'extended' ) {
834 die "unimplemented\n";
838 die "unknown format $format";
841 eval "use Text::CSV_XS;";
844 my $csv = new Text::CSV_XS;
848 local $SIG{HUP} = 'IGNORE';
849 local $SIG{INT} = 'IGNORE';
850 local $SIG{QUIT} = 'IGNORE';
851 local $SIG{TERM} = 'IGNORE';
852 local $SIG{TSTP} = 'IGNORE';
853 local $SIG{PIPE} = 'IGNORE';
855 my $oldAutoCommit = $FS::UID::AutoCommit;
856 local $FS::UID::AutoCommit = 0;
860 while ( defined($line=<$fh>) ) {
862 $csv->parse($line) or do {
863 $dbh->rollback if $oldAutoCommit;
864 return "can't parse: ". $csv->error_input();
867 my @columns = $csv->fields();
871 paybatch => $paybatch,
875 foreach my $field ( @fields ) {
877 if ( $field eq 'agent_custid'
879 && $columns[0] =~ /\S+/ )
882 my $agent_custid = $columns[0];
883 my %hash = ( 'agent_custid' => $agent_custid,
884 'agentnum' => $agentnum,
887 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
888 $dbh->rollback if $oldAutoCommit;
889 return "can't specify custnum with agent_custid $agent_custid";
892 $cust_main = qsearchs({
893 'table' => 'cust_main',
895 'extra_sql' => $extra_sql,
898 unless ( $cust_main ) {
899 $dbh->rollback if $oldAutoCommit;
900 return "can't find customer with agent_custid $agent_custid";
904 $columns[0] = $cust_main->custnum;
907 $cust_pay{$field} = shift @columns;
910 my $cust_pay = new FS::cust_pay( \%cust_pay );
911 my $error = $cust_pay->insert;
914 $dbh->rollback if $oldAutoCommit;
915 return "can't insert payment for $line: $error";
918 if ( $format eq 'simple' ) {
919 # include agentnum for less surprise?
920 $cust_main = qsearchs({
921 'table' => 'cust_main',
922 'hashref' => { 'custnum' => $cust_pay->custnum },
923 'extra_sql' => $extra_sql,
927 unless ( $cust_main ) {
928 $dbh->rollback if $oldAutoCommit;
929 return "can't find customer to which payments apply at line: $line";
932 $error = $cust_main->apply_payments_and_credits;
934 $dbh->rollback if $oldAutoCommit;
935 return "can't apply payments to customer for $line: $error";
943 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
945 return "Empty file!" unless $imported;
955 Delete and replace methods.
959 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
960 schema.html from the base documentation.