4 use vars qw( @ISA $DEBUG $me $conf @encrypted_fields
5 $unsuspendauto $ignore_noapply
8 use Business::CreditCard;
10 use FS::UID qw( getotaker );
11 use FS::Misc qw( send_email );
12 use FS::Record qw( dbh qsearch qsearchs );
14 use FS::cust_main_Mixin;
15 use FS::payinfo_transaction_Mixin;
17 use FS::cust_bill_pay;
18 use FS::cust_pay_refund;
21 use FS::cust_pay_void;
23 @ISA = qw( FS::payinfo_transaction_Mixin FS::cust_main_Mixin FS::Record );
27 $me = '[FS::cust_pay]';
31 #ask FS::UID to run this stuff for us later
32 FS::UID->install_callback( sub {
34 $unsuspendauto = $conf->exists('unsuspendauto');
37 @encrypted_fields = ('payinfo');
41 FS::cust_pay - Object methods for cust_pay objects
47 $record = new FS::cust_pay \%hash;
48 $record = new FS::cust_pay { 'column' => 'value' };
50 $error = $record->insert;
52 $error = $new_record->replace($old_record);
54 $error = $record->delete;
56 $error = $record->check;
60 An FS::cust_pay object represents a payment; the transfer of money from a
61 customer. FS::cust_pay inherits from FS::Record. The following fields are
68 primary key (assigned automatically for new payments)
72 customer (see L<FS::cust_main>)
76 specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
77 L<Time::Local> and L<Date::Parse> for conversion functions.
81 Amount of this payment
85 order taker (assigned automatically, see L<FS::UID>)
89 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
93 Payment Information (See L<FS::payinfo_Mixin> for data format)
97 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
101 text field for tracking card processing or other batch grouping
105 Optional unique identifer to prevent duplicate transactions.
109 books closed flag, empty or `Y'
113 Desired pkgnum when using experimental package balances.
123 Creates a new payment. To add the payment to the databse, see L<"insert">.
127 sub table { 'cust_pay'; }
128 sub cust_linked { $_[0]->cust_main_custnum; }
129 sub cust_unlinked_msg {
131 "WARNING: can't find cust_main.custnum ". $self->custnum.
132 ' (cust_pay.paynum '. $self->paynum. ')';
135 =item insert [ OPTION => VALUE ... ]
137 Adds this payment to the database.
139 For backwards-compatibility and convenience, if the additional field invnum
140 is defined, an FS::cust_bill_pay record for the full amount of the payment
141 will be created. In this case, custnum is optional.
143 A hash of optional arguments may be passed. Currently "manual" is supported.
144 If true, a payment receipt is sent instead of a statement when
145 'payment_receipt_email' configuration option is set.
150 my($self, %options) = @_;
152 local $SIG{HUP} = 'IGNORE';
153 local $SIG{INT} = 'IGNORE';
154 local $SIG{QUIT} = 'IGNORE';
155 local $SIG{TERM} = 'IGNORE';
156 local $SIG{TSTP} = 'IGNORE';
157 local $SIG{PIPE} = 'IGNORE';
159 my $oldAutoCommit = $FS::UID::AutoCommit;
160 local $FS::UID::AutoCommit = 0;
164 if ( $self->invnum ) {
165 $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
167 $dbh->rollback if $oldAutoCommit;
168 return "Unknown cust_bill.invnum: ". $self->invnum;
170 $self->custnum($cust_bill->custnum );
173 my $error = $self->check;
174 return $error if $error;
176 my $cust_main = $self->cust_main;
177 my $old_balance = $cust_main->balance;
179 $error = $self->SUPER::insert;
181 $dbh->rollback if $oldAutoCommit;
182 return "error inserting $self: $error";
185 if ( $self->invnum ) {
186 my $cust_bill_pay = new FS::cust_bill_pay {
187 'invnum' => $self->invnum,
188 'paynum' => $self->paynum,
189 'amount' => $self->paid,
190 '_date' => $self->_date,
192 $error = $cust_bill_pay->insert(%options);
194 if ( $ignore_noapply ) {
195 warn "warning: error inserting $cust_bill_pay: $error ".
196 "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
198 $dbh->rollback if $oldAutoCommit;
199 return "error inserting $cust_bill_pay: $error";
204 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
206 #false laziness w/ cust_credit::insert
207 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
208 my @errors = $cust_main->unsuspend;
210 # side-fx with nested transactions? upstack rolls back?
211 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
217 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
220 my $trigger = $conf->config('payment_receipt-trigger') || 'cust_pay';
221 if ( $trigger eq 'cust_pay' ) {
222 my $error = $self->send_receipt(
223 'manual' => $options{'manual'},
224 'cust_bill' => $cust_bill,
225 'cust_main' => $cust_main,
227 warn "can't send payment receipt/statement: $error" if $error;
234 =item void [ REASON ]
236 Voids this payment: deletes the payment and all associated applications and
237 adds a record of the voided payment to the FS::cust_pay_void table.
244 local $SIG{HUP} = 'IGNORE';
245 local $SIG{INT} = 'IGNORE';
246 local $SIG{QUIT} = 'IGNORE';
247 local $SIG{TERM} = 'IGNORE';
248 local $SIG{TSTP} = 'IGNORE';
249 local $SIG{PIPE} = 'IGNORE';
251 my $oldAutoCommit = $FS::UID::AutoCommit;
252 local $FS::UID::AutoCommit = 0;
255 my $cust_pay_void = new FS::cust_pay_void ( {
256 map { $_ => $self->get($_) } $self->fields
258 $cust_pay_void->reason(shift) if scalar(@_);
259 my $error = $cust_pay_void->insert;
261 $dbh->rollback if $oldAutoCommit;
265 $error = $self->delete;
267 $dbh->rollback if $oldAutoCommit;
271 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
279 Unless the closed flag is set, deletes this payment and all associated
280 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>). In most
281 cases, you want to use the void method instead to leave a record of the
286 # very similar to FS::cust_credit::delete
289 return "Can't delete closed payment" if $self->closed =~ /^Y/i;
291 local $SIG{HUP} = 'IGNORE';
292 local $SIG{INT} = 'IGNORE';
293 local $SIG{QUIT} = 'IGNORE';
294 local $SIG{TERM} = 'IGNORE';
295 local $SIG{TSTP} = 'IGNORE';
296 local $SIG{PIPE} = 'IGNORE';
298 my $oldAutoCommit = $FS::UID::AutoCommit;
299 local $FS::UID::AutoCommit = 0;
302 foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
303 my $error = $app->delete;
305 $dbh->rollback if $oldAutoCommit;
310 my $error = $self->SUPER::delete(@_);
312 $dbh->rollback if $oldAutoCommit;
316 if ( $conf->exists('deletepayments')
317 && $conf->config('deletepayments') ne '' ) {
319 my $cust_main = $self->cust_main;
321 my $error = send_email(
322 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
323 #invoice_from??? well as good as any
324 'to' => $conf->config('deletepayments'),
325 'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
327 "This is an automatic message from your Freeside installation\n",
328 "informing you that the following payment has been deleted:\n",
330 'paynum: '. $self->paynum. "\n",
331 'custnum: '. $self->custnum.
332 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
333 'paid: $'. sprintf("%.2f", $self->paid). "\n",
334 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
335 'payby: '. $self->payby. "\n",
336 'payinfo: '. $self->paymask. "\n",
337 'paybatch: '. $self->paybatch. "\n",
342 $dbh->rollback if $oldAutoCommit;
343 return "can't send payment deletion notification: $error";
348 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
354 =item replace OLD_RECORD
356 You can, but probably shouldn't modify payments...
361 #return "Can't modify payment!"
363 return "Can't modify closed payment" if $self->closed =~ /^Y/i;
364 $self->SUPER::replace(@_);
369 Checks all fields to make sure this is a valid payment. If there is an error,
370 returns the error, otherwise returns false. Called by the insert method.
377 $self->otaker(getotaker) unless ($self->otaker);
380 $self->ut_numbern('paynum')
381 || $self->ut_numbern('custnum')
382 || $self->ut_numbern('_date')
383 || $self->ut_money('paid')
384 || $self->ut_alpha('otaker')
385 || $self->ut_textn('paybatch')
386 || $self->ut_textn('payunique')
387 || $self->ut_enum('closed', [ '', 'Y' ])
388 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
389 || $self->payinfo_check()
391 return $error if $error;
393 return "paid must be > 0 " if $self->paid <= 0;
395 return "unknown cust_main.custnum: ". $self->custnum
397 || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
399 $self->_date(time) unless $self->_date;
401 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
402 # # UNIQUE index should catch this too, without race conditions, but this
403 # # should give a better error message the other 99.9% of the time...
404 # if ( length($self->payunique)
405 # && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
406 # #well, it *could* be a better error message
407 # return "duplicate transaction".
408 # " - a payment with unique identifer ". $self->payunique.
415 =item send_receipt HASHREF | OPTION => VALUE ...
417 Sends a payment receipt for this payment..
425 Flag indicating the payment is being made manually.
429 Invoice (FS::cust_bill) object. If not specified, the most recent invoice
434 Customer (FS::cust_main) object (for efficiency).
442 my $opt = ref($_[0]) ? shift : { @_ };
444 my $cust_bill = $opt->{'cust_bill'};
445 my $cust_main = $opt->{'cust_main'} || $self->cust_main;
447 my $conf = new FS::Conf;
449 my @invoicing_list = $cust_main->invoicing_list_emailonly;
450 return '' unless @invoicing_list;
452 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
454 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
455 || ! $conf->exists('invoice_html_statement') # XXX msg_template
461 if( $conf->exists('payment_receipt_msgnum') ) {
463 FS::msg_template->by_key($conf->config('payment_receipt_msgnum'));
464 $error = $msg_template->send('cust_main'=> $cust_main, 'object'=> $self);
466 elsif ( $conf->exists('payment_receipt_email') ) {
467 my $receipt_template = new Text::Template (
469 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
471 warn "can't create payment receipt template: $Text::Template::ERROR";
475 my $payby = $self->payby;
476 my $payinfo = $self->payinfo;
477 $payby =~ s/^BILL$/Check/ if $payinfo;
478 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
479 $payinfo = $self->paymask
481 $payinfo = $self->decrypt($payinfo);
483 $payby =~ s/^CHEK$/Electronic check/;
486 'date' => time2str("%a %B %o, %Y", $self->_date),
487 'name' => $cust_main->name,
488 'paynum' => $self->paynum,
489 'paid' => sprintf("%.2f", $self->paid),
490 'payby' => ucfirst(lc($payby)),
491 'payinfo' => $payinfo,
492 'balance' => $cust_main->balance,
493 'company_name' => $conf->config('company_name', $cust_main->agentnum),
496 if ( $opt->{'cust_pkg'} ) {
497 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
498 #setup date, other things?
502 'from' => $conf->config('invoice_from', $cust_main->agentnum),
503 #invoice_from??? well as good as any
504 'to' => \@invoicing_list,
505 'subject' => 'Payment receipt',
506 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
510 else { # no payment_receipt_msgnum or payment_receipt_email
512 my $queue = new FS::queue {
513 'paynum' => $self->paynum,
514 'job' => 'FS::cust_bill::queueable_email',
518 'invnum' => $cust_bill->invnum,
519 'template' => 'statement',
523 warn "send_receipt: $error\n" if $error;
524 } #$opt{manual} || no invoice_html_statement || customer has no invoices
529 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
536 sort { $a->_date <=> $b->_date
537 || $a->invnum <=> $b->invnum }
538 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
542 =item cust_pay_refund
544 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
549 sub cust_pay_refund {
551 sort { $a->_date <=> $b->_date }
552 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
559 Returns the amount of this payment that is still unapplied; which is
560 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
561 applications (see L<FS::cust_pay_refund>).
567 my $amount = $self->paid;
568 $amount -= $_->amount foreach ( $self->cust_bill_pay );
569 $amount -= $_->amount foreach ( $self->cust_pay_refund );
570 sprintf("%.2f", $amount );
575 Returns the amount of this payment that has not been refuned; which is
576 paid minus all refund applications (see L<FS::cust_pay_refund>).
582 my $amount = $self->paid;
583 $amount -= $_->amount foreach ( $self->cust_pay_refund );
584 sprintf("%.2f", $amount );
589 Returns the "paid" field.
604 =item batch_insert CUST_PAY_OBJECT, ...
606 Class method which inserts multiple payments. Takes a list of FS::cust_pay
607 objects. Returns a list, each element representing the status of inserting the
608 corresponding payment - empty. If there is an error inserting any payment, the
609 entire transaction is rolled back, i.e. all payments are inserted or none are.
613 my @errors = FS::cust_pay->batch_insert(@cust_pay);
614 my $num_errors = scalar(grep $_, @errors);
615 if ( $num_errors == 0 ) {
616 #success; all payments were inserted
618 #failure; no payments were inserted.
624 my $self = shift; #class method
626 local $SIG{HUP} = 'IGNORE';
627 local $SIG{INT} = 'IGNORE';
628 local $SIG{QUIT} = 'IGNORE';
629 local $SIG{TERM} = 'IGNORE';
630 local $SIG{TSTP} = 'IGNORE';
631 local $SIG{PIPE} = 'IGNORE';
633 my $oldAutoCommit = $FS::UID::AutoCommit;
634 local $FS::UID::AutoCommit = 0;
640 my $error = $_->insert( 'manual' => 1 );
644 $_->cust_main->apply_payments;
650 $dbh->rollback if $oldAutoCommit;
652 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
661 Returns an SQL fragment to retreive the unapplied amount.
666 my ($class, $start, $end) = @_;
667 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
668 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
669 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
670 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
674 ( SELECT SUM(amount) FROM cust_bill_pay
675 WHERE cust_pay.paynum = cust_bill_pay.paynum
676 $bill_start $bill_end )
680 ( SELECT SUM(amount) FROM cust_pay_refund
681 WHERE cust_pay.paynum = cust_pay_refund.paynum
682 $refund_start $refund_end )
691 # Used by FS::Upgrade to migrate to a new database.
695 sub _upgrade_data { #class method
696 my ($class, %opts) = @_;
698 warn "$me upgrading $class\n" if $DEBUG;
700 #not the most efficient, but hey, it only has to run once
702 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
703 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
704 " WHERE cust_main.custnum = cust_pay.custnum ) ";
706 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
708 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
709 $sth->execute or die $sth->errstr;
710 my $total = $sth->fetchrow_arrayref->[0];
711 #warn "$total cust_pay records to update\n"
713 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
718 my @cust_pay = qsearch( {
719 'table' => 'cust_pay',
721 'extra_sql' => $where,
722 'order_by' => 'ORDER BY paynum',
725 foreach my $cust_pay (@cust_pay) {
727 my $h_cust_pay = $cust_pay->h_search('insert');
729 next if $cust_pay->otaker eq $h_cust_pay->history_user;
730 $cust_pay->otaker($h_cust_pay->history_user);
732 $cust_pay->otaker('legacy');
735 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
736 my $error = $cust_pay->replace;
739 warn " *** WARNING: Error updating order taker for payment paynum ".
740 $cust_pay->paynun. ": $error\n";
744 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
747 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
748 warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
762 =item batch_import HASHREF
764 Inserts new payments.
771 my $fh = $param->{filehandle};
772 my $agentnum = $param->{agentnum};
773 my $format = $param->{'format'};
774 my $paybatch = $param->{'paybatch'};
776 # here is the agent virtualization
777 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
781 if ( $format eq 'simple' ) {
782 @fields = qw( custnum agent_custid paid payinfo );
784 } elsif ( $format eq 'extended' ) {
785 die "unimplemented\n";
789 die "unknown format $format";
792 eval "use Text::CSV_XS;";
795 my $csv = new Text::CSV_XS;
799 local $SIG{HUP} = 'IGNORE';
800 local $SIG{INT} = 'IGNORE';
801 local $SIG{QUIT} = 'IGNORE';
802 local $SIG{TERM} = 'IGNORE';
803 local $SIG{TSTP} = 'IGNORE';
804 local $SIG{PIPE} = 'IGNORE';
806 my $oldAutoCommit = $FS::UID::AutoCommit;
807 local $FS::UID::AutoCommit = 0;
811 while ( defined($line=<$fh>) ) {
813 $csv->parse($line) or do {
814 $dbh->rollback if $oldAutoCommit;
815 return "can't parse: ". $csv->error_input();
818 my @columns = $csv->fields();
822 paybatch => $paybatch,
826 foreach my $field ( @fields ) {
828 if ( $field eq 'agent_custid'
830 && $columns[0] =~ /\S+/ )
833 my $agent_custid = $columns[0];
834 my %hash = ( 'agent_custid' => $agent_custid,
835 'agentnum' => $agentnum,
838 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
839 $dbh->rollback if $oldAutoCommit;
840 return "can't specify custnum with agent_custid $agent_custid";
843 $cust_main = qsearchs({
844 'table' => 'cust_main',
846 'extra_sql' => $extra_sql,
849 unless ( $cust_main ) {
850 $dbh->rollback if $oldAutoCommit;
851 return "can't find customer with agent_custid $agent_custid";
855 $columns[0] = $cust_main->custnum;
858 $cust_pay{$field} = shift @columns;
861 my $cust_pay = new FS::cust_pay( \%cust_pay );
862 my $error = $cust_pay->insert;
865 $dbh->rollback if $oldAutoCommit;
866 return "can't insert payment for $line: $error";
869 if ( $format eq 'simple' ) {
870 # include agentnum for less surprise?
871 $cust_main = qsearchs({
872 'table' => 'cust_main',
873 'hashref' => { 'custnum' => $cust_pay->custnum },
874 'extra_sql' => $extra_sql,
878 unless ( $cust_main ) {
879 $dbh->rollback if $oldAutoCommit;
880 return "can't find customer to which payments apply at line: $line";
883 $error = $cust_main->apply_payments_and_credits;
885 $dbh->rollback if $oldAutoCommit;
886 return "can't apply payments to customer for $line: $error";
894 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
896 return "Empty file!" unless $imported;
906 Delete and replace methods.
910 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
911 schema.html from the base documentation.