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 return '' unless $conf->exists('payment_receipt');
452 my @invoicing_list = $cust_main->invoicing_list_emailonly;
453 return '' unless @invoicing_list;
455 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
459 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
460 || ! $conf->exists('invoice_html_statement')
465 if ( $conf->exists('payment_receipt_msgnum')
466 && $conf->config('payment_receipt_msgnum')
470 FS::msg_template->by_key($conf->config('payment_receipt_msgnum'));
471 $error = $msg_template->send('cust_main'=> $cust_main, 'object'=> $self);
473 } elsif ( $conf->exists('payment_receipt_email') ) {
475 my $receipt_template = new Text::Template (
477 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
479 warn "can't create payment receipt template: $Text::Template::ERROR";
483 my $payby = $self->payby;
484 my $payinfo = $self->payinfo;
485 $payby =~ s/^BILL$/Check/ if $payinfo;
486 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
487 $payinfo = $self->paymask
489 $payinfo = $self->decrypt($payinfo);
491 $payby =~ s/^CHEK$/Electronic check/;
494 'date' => time2str("%a %B %o, %Y", $self->_date),
495 'name' => $cust_main->name,
496 'paynum' => $self->paynum,
497 'paid' => sprintf("%.2f", $self->paid),
498 'payby' => ucfirst(lc($payby)),
499 'payinfo' => $payinfo,
500 'balance' => $cust_main->balance,
501 'company_name' => $conf->config('company_name', $cust_main->agentnum),
504 if ( $opt->{'cust_pkg'} ) {
505 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
506 #setup date, other things?
510 'from' => $conf->config('invoice_from', $cust_main->agentnum),
511 #invoice_from??? well as good as any
512 'to' => \@invoicing_list,
513 'subject' => 'Payment receipt',
514 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
519 warn "payment_receipt is on, but no payment_receipt_msgnum or invoice_html_statement is configured\n";
525 my $queue = new FS::queue {
526 'paynum' => $self->paynum,
527 'job' => 'FS::cust_bill::queueable_email',
530 $error = $queue->insert(
531 'invnum' => $cust_bill->invnum,
532 'template' => 'statement',
537 warn "send_receipt: $error\n" if $error;
542 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
549 map { $_ } #return $self->num_cust_bill_pay unless wantarray;
550 sort { $a->_date <=> $b->_date
551 || $a->invnum <=> $b->invnum }
552 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
556 =item cust_pay_refund
558 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
563 sub cust_pay_refund {
565 map { $_ } #return $self->num_cust_pay_refund unless wantarray;
566 sort { $a->_date <=> $b->_date }
567 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
574 Returns the amount of this payment that is still unapplied; which is
575 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
576 applications (see L<FS::cust_pay_refund>).
582 my $amount = $self->paid;
583 $amount -= $_->amount foreach ( $self->cust_bill_pay );
584 $amount -= $_->amount foreach ( $self->cust_pay_refund );
585 sprintf("%.2f", $amount );
590 Returns the amount of this payment that has not been refuned; which is
591 paid minus all refund applications (see L<FS::cust_pay_refund>).
597 my $amount = $self->paid;
598 $amount -= $_->amount foreach ( $self->cust_pay_refund );
599 sprintf("%.2f", $amount );
604 Returns the "paid" field.
619 =item batch_insert CUST_PAY_OBJECT, ...
621 Class method which inserts multiple payments. Takes a list of FS::cust_pay
622 objects. Returns a list, each element representing the status of inserting the
623 corresponding payment - empty. If there is an error inserting any payment, the
624 entire transaction is rolled back, i.e. all payments are inserted or none are.
628 my @errors = FS::cust_pay->batch_insert(@cust_pay);
629 my $num_errors = scalar(grep $_, @errors);
630 if ( $num_errors == 0 ) {
631 #success; all payments were inserted
633 #failure; no payments were inserted.
639 my $self = shift; #class method
641 local $SIG{HUP} = 'IGNORE';
642 local $SIG{INT} = 'IGNORE';
643 local $SIG{QUIT} = 'IGNORE';
644 local $SIG{TERM} = 'IGNORE';
645 local $SIG{TSTP} = 'IGNORE';
646 local $SIG{PIPE} = 'IGNORE';
648 my $oldAutoCommit = $FS::UID::AutoCommit;
649 local $FS::UID::AutoCommit = 0;
655 my $error = $_->insert( 'manual' => 1 );
659 $_->cust_main->apply_payments;
665 $dbh->rollback if $oldAutoCommit;
667 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
676 Returns an SQL fragment to retreive the unapplied amount.
681 my ($class, $start, $end) = @_;
682 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
683 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
684 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
685 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
689 ( SELECT SUM(amount) FROM cust_bill_pay
690 WHERE cust_pay.paynum = cust_bill_pay.paynum
691 $bill_start $bill_end )
695 ( SELECT SUM(amount) FROM cust_pay_refund
696 WHERE cust_pay.paynum = cust_pay_refund.paynum
697 $refund_start $refund_end )
706 # Used by FS::Upgrade to migrate to a new database.
710 sub _upgrade_data { #class method
711 my ($class, %opts) = @_;
713 warn "$me upgrading $class\n" if $DEBUG;
716 # otaker/ivan upgrade
719 #not the most efficient, but hey, it only has to run once
721 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
722 " AND usernum IS NULL ".
723 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
724 " WHERE cust_main.custnum = cust_pay.custnum ) ";
726 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
728 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
729 $sth->execute or die $sth->errstr;
730 my $total = $sth->fetchrow_arrayref->[0];
731 #warn "$total cust_pay records to update\n"
733 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
738 my @cust_pay = qsearch( {
739 'table' => 'cust_pay',
741 'extra_sql' => $where,
742 'order_by' => 'ORDER BY paynum',
745 foreach my $cust_pay (@cust_pay) {
747 my $h_cust_pay = $cust_pay->h_search('insert');
749 next if $cust_pay->otaker eq $h_cust_pay->history_user;
750 $cust_pay->otaker($h_cust_pay->history_user);
752 $cust_pay->otaker('legacy');
755 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
756 my $error = $cust_pay->replace;
759 warn " *** WARNING: Error updating order taker for payment paynum ".
760 $cust_pay->paynun. ": $error\n";
764 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
767 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
768 warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
775 # payinfo N/A upgrade
778 #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
780 my @na_cust_pay = qsearch( {
781 'table' => 'cust_pay',
782 'hashref' => {}, #could be encrypted# { 'payinfo' => 'N/A' },
783 'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
786 foreach my $na ( @na_cust_pay ) {
788 next unless $na->payinfo eq 'N/A';
790 my $cust_pay_pending =
791 qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
792 unless ( $cust_pay_pending ) {
793 warn " *** WARNING: not-yet recoverable N/A card for payment ".
794 $na->paynum. " (no cust_pay_pending)\n";
797 $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
798 my $error = $na->replace;
800 warn " *** WARNING: Error updating payinfo for payment paynum ".
801 $na->paynun. ": $error\n";
808 # otaker->usernum upgrade
811 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
812 $class->_upgrade_otaker(%opts);
813 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
823 =item batch_import HASHREF
825 Inserts new payments.
832 my $fh = $param->{filehandle};
833 my $agentnum = $param->{agentnum};
834 my $format = $param->{'format'};
835 my $paybatch = $param->{'paybatch'};
837 # here is the agent virtualization
838 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
842 if ( $format eq 'simple' ) {
843 @fields = qw( custnum agent_custid paid payinfo );
845 } elsif ( $format eq 'extended' ) {
846 die "unimplemented\n";
850 die "unknown format $format";
853 eval "use Text::CSV_XS;";
856 my $csv = new Text::CSV_XS;
860 local $SIG{HUP} = 'IGNORE';
861 local $SIG{INT} = 'IGNORE';
862 local $SIG{QUIT} = 'IGNORE';
863 local $SIG{TERM} = 'IGNORE';
864 local $SIG{TSTP} = 'IGNORE';
865 local $SIG{PIPE} = 'IGNORE';
867 my $oldAutoCommit = $FS::UID::AutoCommit;
868 local $FS::UID::AutoCommit = 0;
872 while ( defined($line=<$fh>) ) {
874 $csv->parse($line) or do {
875 $dbh->rollback if $oldAutoCommit;
876 return "can't parse: ". $csv->error_input();
879 my @columns = $csv->fields();
883 paybatch => $paybatch,
887 foreach my $field ( @fields ) {
889 if ( $field eq 'agent_custid'
891 && $columns[0] =~ /\S+/ )
894 my $agent_custid = $columns[0];
895 my %hash = ( 'agent_custid' => $agent_custid,
896 'agentnum' => $agentnum,
899 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
900 $dbh->rollback if $oldAutoCommit;
901 return "can't specify custnum with agent_custid $agent_custid";
904 $cust_main = qsearchs({
905 'table' => 'cust_main',
907 'extra_sql' => $extra_sql,
910 unless ( $cust_main ) {
911 $dbh->rollback if $oldAutoCommit;
912 return "can't find customer with agent_custid $agent_custid";
916 $columns[0] = $cust_main->custnum;
919 $cust_pay{$field} = shift @columns;
922 my $cust_pay = new FS::cust_pay( \%cust_pay );
923 my $error = $cust_pay->insert;
926 $dbh->rollback if $oldAutoCommit;
927 return "can't insert payment for $line: $error";
930 if ( $format eq 'simple' ) {
931 # include agentnum for less surprise?
932 $cust_main = qsearchs({
933 'table' => 'cust_main',
934 'hashref' => { 'custnum' => $cust_pay->custnum },
935 'extra_sql' => $extra_sql,
939 unless ( $cust_main ) {
940 $dbh->rollback if $oldAutoCommit;
941 return "can't find customer to which payments apply at line: $line";
944 $error = $cust_main->apply_payments_and_credits;
946 $dbh->rollback if $oldAutoCommit;
947 return "can't apply payments to customer for $line: $error";
955 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
957 return "Empty file!" unless $imported;
967 Delete and replace methods.
971 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
972 schema.html from the base documentation.