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 #bill setup fees for voip_cdr bill_every_call packages
218 #some false laziness w/search in freeside-cdrd
220 'LEFT JOIN part_pkg USING ( pkgpart ) '.
221 "LEFT JOIN part_pkg_option
222 ON ( cust_pkg.pkgpart = part_pkg_option.pkgpart
223 AND part_pkg_option.optionname = 'bill_every_call' )";
225 my $extra_sql = " AND plan = 'voip_cdr' AND optionvalue = '1' ".
226 " AND ( cust_pkg.setup IS NULL OR cust_pkg.setup = 0 ) ";
228 my @cust_pkg = qsearch({
229 'table' => 'cust_pkg',
230 'addl_from' => $addl_from,
231 'hashref' => { 'custnum' => $self->custnum,
235 'extra_sql' => $extra_sql,
239 warn "voip_cdr bill_every_call packages found; billing customer\n";
240 my $bill_error = $self->cust_main->bill_and_collect( 'fatal' => 'return' );
242 warn "WARNING: Error billing customer: $bill_error\n";
245 #end of billing setup fees for voip_cdr bill_every_call packages
247 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
250 my $trigger = $conf->config('payment_receipt-trigger') || 'cust_pay';
251 if ( $trigger eq 'cust_pay' ) {
252 my $error = $self->send_receipt(
253 'manual' => $options{'manual'},
254 'cust_bill' => $cust_bill,
255 'cust_main' => $cust_main,
257 warn "can't send payment receipt/statement: $error" if $error;
264 =item void [ REASON ]
266 Voids this payment: deletes the payment and all associated applications and
267 adds a record of the voided payment to the FS::cust_pay_void table.
274 local $SIG{HUP} = 'IGNORE';
275 local $SIG{INT} = 'IGNORE';
276 local $SIG{QUIT} = 'IGNORE';
277 local $SIG{TERM} = 'IGNORE';
278 local $SIG{TSTP} = 'IGNORE';
279 local $SIG{PIPE} = 'IGNORE';
281 my $oldAutoCommit = $FS::UID::AutoCommit;
282 local $FS::UID::AutoCommit = 0;
285 my $cust_pay_void = new FS::cust_pay_void ( {
286 map { $_ => $self->get($_) } $self->fields
288 $cust_pay_void->reason(shift) if scalar(@_);
289 my $error = $cust_pay_void->insert;
291 $dbh->rollback if $oldAutoCommit;
295 $error = $self->delete;
297 $dbh->rollback if $oldAutoCommit;
301 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
309 Unless the closed flag is set, deletes this payment and all associated
310 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>). In most
311 cases, you want to use the void method instead to leave a record of the
316 # very similar to FS::cust_credit::delete
319 return "Can't delete closed payment" if $self->closed =~ /^Y/i;
321 local $SIG{HUP} = 'IGNORE';
322 local $SIG{INT} = 'IGNORE';
323 local $SIG{QUIT} = 'IGNORE';
324 local $SIG{TERM} = 'IGNORE';
325 local $SIG{TSTP} = 'IGNORE';
326 local $SIG{PIPE} = 'IGNORE';
328 my $oldAutoCommit = $FS::UID::AutoCommit;
329 local $FS::UID::AutoCommit = 0;
332 foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
333 my $error = $app->delete;
335 $dbh->rollback if $oldAutoCommit;
340 my $error = $self->SUPER::delete(@_);
342 $dbh->rollback if $oldAutoCommit;
346 if ( $conf->exists('deletepayments')
347 && $conf->config('deletepayments') ne '' ) {
349 my $cust_main = $self->cust_main;
351 my $error = send_email(
352 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
353 #invoice_from??? well as good as any
354 'to' => $conf->config('deletepayments'),
355 'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
357 "This is an automatic message from your Freeside installation\n",
358 "informing you that the following payment has been deleted:\n",
360 'paynum: '. $self->paynum. "\n",
361 'custnum: '. $self->custnum.
362 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
363 'paid: $'. sprintf("%.2f", $self->paid). "\n",
364 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
365 'payby: '. $self->payby. "\n",
366 'payinfo: '. $self->paymask. "\n",
367 'paybatch: '. $self->paybatch. "\n",
372 $dbh->rollback if $oldAutoCommit;
373 return "can't send payment deletion notification: $error";
378 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
384 =item replace OLD_RECORD
386 You can, but probably shouldn't modify payments...
391 #return "Can't modify payment!"
393 return "Can't modify closed payment" if $self->closed =~ /^Y/i;
394 $self->SUPER::replace(@_);
399 Checks all fields to make sure this is a valid payment. If there is an error,
400 returns the error, otherwise returns false. Called by the insert method.
407 $self->otaker(getotaker) unless ($self->otaker);
410 $self->ut_numbern('paynum')
411 || $self->ut_numbern('custnum')
412 || $self->ut_numbern('_date')
413 || $self->ut_money('paid')
414 || $self->ut_alpha('otaker')
415 || $self->ut_textn('paybatch')
416 || $self->ut_textn('payunique')
417 || $self->ut_enum('closed', [ '', 'Y' ])
418 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
419 || $self->payinfo_check()
421 return $error if $error;
423 return "paid must be > 0 " if $self->paid <= 0;
425 return "unknown cust_main.custnum: ". $self->custnum
427 || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
429 $self->_date(time) unless $self->_date;
431 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
432 # # UNIQUE index should catch this too, without race conditions, but this
433 # # should give a better error message the other 99.9% of the time...
434 # if ( length($self->payunique)
435 # && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
436 # #well, it *could* be a better error message
437 # return "duplicate transaction".
438 # " - a payment with unique identifer ". $self->payunique.
445 =item send_receipt HASHREF | OPTION => VALUE ...
447 Sends a payment receipt for this payment..
455 Flag indicating the payment is being made manually.
459 Invoice (FS::cust_bill) object. If not specified, the most recent invoice
464 Customer (FS::cust_main) object (for efficiency).
472 my $opt = ref($_[0]) ? shift : { @_ };
474 my $cust_bill = $opt->{'cust_bill'};
475 my $cust_main = $opt->{'cust_main'} || $self->cust_main;
477 my $conf = new FS::Conf;
479 return '' unless $conf->exists('payment_receipt');
481 my @invoicing_list = $cust_main->invoicing_list_emailonly;
482 return '' unless @invoicing_list;
484 $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
488 if ( ( exists($opt->{'manual'}) && $opt->{'manual'} )
489 || ! $conf->exists('invoice_html_statement')
494 if ( $conf->exists('payment_receipt_msgnum')
495 && $conf->config('payment_receipt_msgnum')
499 FS::msg_template->by_key($conf->config('payment_receipt_msgnum'));
500 $error = $msg_template->send('cust_main'=> $cust_main, 'object'=> $self);
502 } elsif ( $conf->exists('payment_receipt_email') ) {
504 my $receipt_template = new Text::Template (
506 SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
508 warn "can't create payment receipt template: $Text::Template::ERROR";
512 my $payby = $self->payby;
513 my $payinfo = $self->payinfo;
514 $payby =~ s/^BILL$/Check/ if $payinfo;
515 if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
516 $payinfo = $self->paymask
518 $payinfo = $self->decrypt($payinfo);
520 $payby =~ s/^CHEK$/Electronic check/;
523 'date' => time2str("%a %B %o, %Y", $self->_date),
524 'name' => $cust_main->name,
525 'paynum' => $self->paynum,
526 'paid' => sprintf("%.2f", $self->paid),
527 'payby' => ucfirst(lc($payby)),
528 'payinfo' => $payinfo,
529 'balance' => $cust_main->balance,
530 'company_name' => $conf->config('company_name', $cust_main->agentnum),
533 if ( $opt->{'cust_pkg'} ) {
534 $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
535 #setup date, other things?
539 'from' => $conf->config('invoice_from', $cust_main->agentnum),
540 #invoice_from??? well as good as any
541 'to' => \@invoicing_list,
542 'subject' => 'Payment receipt',
543 'body' => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
548 warn "payment_receipt is on, but no payment_receipt_msgnum or invoice_html_statement is configured\n";
554 my $queue = new FS::queue {
555 'paynum' => $self->paynum,
556 'job' => 'FS::cust_bill::queueable_email',
559 $error = $queue->insert(
560 'invnum' => $cust_bill->invnum,
561 'template' => 'statement',
566 warn "send_receipt: $error\n" if $error;
571 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
578 sort { $a->_date <=> $b->_date
579 || $a->invnum <=> $b->invnum }
580 qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
584 =item cust_pay_refund
586 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
591 sub cust_pay_refund {
593 sort { $a->_date <=> $b->_date }
594 qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
601 Returns the amount of this payment that is still unapplied; which is
602 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
603 applications (see L<FS::cust_pay_refund>).
609 my $amount = $self->paid;
610 $amount -= $_->amount foreach ( $self->cust_bill_pay );
611 $amount -= $_->amount foreach ( $self->cust_pay_refund );
612 sprintf("%.2f", $amount );
617 Returns the amount of this payment that has not been refuned; which is
618 paid minus all refund applications (see L<FS::cust_pay_refund>).
624 my $amount = $self->paid;
625 $amount -= $_->amount foreach ( $self->cust_pay_refund );
626 sprintf("%.2f", $amount );
631 Returns the "paid" field.
646 =item batch_insert CUST_PAY_OBJECT, ...
648 Class method which inserts multiple payments. Takes a list of FS::cust_pay
649 objects. Returns a list, each element representing the status of inserting the
650 corresponding payment - empty. If there is an error inserting any payment, the
651 entire transaction is rolled back, i.e. all payments are inserted or none are.
655 my @errors = FS::cust_pay->batch_insert(@cust_pay);
656 my $num_errors = scalar(grep $_, @errors);
657 if ( $num_errors == 0 ) {
658 #success; all payments were inserted
660 #failure; no payments were inserted.
666 my $self = shift; #class method
668 local $SIG{HUP} = 'IGNORE';
669 local $SIG{INT} = 'IGNORE';
670 local $SIG{QUIT} = 'IGNORE';
671 local $SIG{TERM} = 'IGNORE';
672 local $SIG{TSTP} = 'IGNORE';
673 local $SIG{PIPE} = 'IGNORE';
675 my $oldAutoCommit = $FS::UID::AutoCommit;
676 local $FS::UID::AutoCommit = 0;
682 my $error = $_->insert( 'manual' => 1 );
686 $_->cust_main->apply_payments;
692 $dbh->rollback if $oldAutoCommit;
694 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
703 Returns an SQL fragment to retreive the unapplied amount.
708 my ($class, $start, $end) = @_;
709 my $bill_start = $start ? "AND cust_bill_pay._date <= $start" : '';
710 my $bill_end = $end ? "AND cust_bill_pay._date > $end" : '';
711 my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
712 my $refund_end = $end ? "AND cust_pay_refund._date > $end" : '';
716 ( SELECT SUM(amount) FROM cust_bill_pay
717 WHERE cust_pay.paynum = cust_bill_pay.paynum
718 $bill_start $bill_end )
722 ( SELECT SUM(amount) FROM cust_pay_refund
723 WHERE cust_pay.paynum = cust_pay_refund.paynum
724 $refund_start $refund_end )
733 # Used by FS::Upgrade to migrate to a new database.
737 sub _upgrade_data { #class method
738 my ($class, %opts) = @_;
740 warn "$me upgrading $class\n" if $DEBUG;
742 #not the most efficient, but hey, it only has to run once
744 my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
745 " AND 0 < ( SELECT COUNT(*) FROM cust_main ".
746 " WHERE cust_main.custnum = cust_pay.custnum ) ";
748 my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
750 my $sth = dbh->prepare($count_sql) or die dbh->errstr;
751 $sth->execute or die $sth->errstr;
752 my $total = $sth->fetchrow_arrayref->[0];
753 #warn "$total cust_pay records to update\n"
755 local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
760 my @cust_pay = qsearch( {
761 'table' => 'cust_pay',
763 'extra_sql' => $where,
764 'order_by' => 'ORDER BY paynum',
767 foreach my $cust_pay (@cust_pay) {
769 my $h_cust_pay = $cust_pay->h_search('insert');
771 next if $cust_pay->otaker eq $h_cust_pay->history_user;
772 $cust_pay->otaker($h_cust_pay->history_user);
774 $cust_pay->otaker('legacy');
777 delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
778 my $error = $cust_pay->replace;
781 warn " *** WARNING: Error updating order taker for payment paynum ".
782 $cust_pay->paynun. ": $error\n";
786 $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
789 if ( $DEBUG > 1 && $lastprog + 30 < time ) {
790 warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
804 =item batch_import HASHREF
806 Inserts new payments.
813 my $fh = $param->{filehandle};
814 my $agentnum = $param->{agentnum};
815 my $format = $param->{'format'};
816 my $paybatch = $param->{'paybatch'};
818 # here is the agent virtualization
819 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
823 if ( $format eq 'simple' ) {
824 @fields = qw( custnum agent_custid paid payinfo );
826 } elsif ( $format eq 'extended' ) {
827 die "unimplemented\n";
831 die "unknown format $format";
834 eval "use Text::CSV_XS;";
837 my $csv = new Text::CSV_XS;
841 local $SIG{HUP} = 'IGNORE';
842 local $SIG{INT} = 'IGNORE';
843 local $SIG{QUIT} = 'IGNORE';
844 local $SIG{TERM} = 'IGNORE';
845 local $SIG{TSTP} = 'IGNORE';
846 local $SIG{PIPE} = 'IGNORE';
848 my $oldAutoCommit = $FS::UID::AutoCommit;
849 local $FS::UID::AutoCommit = 0;
853 while ( defined($line=<$fh>) ) {
855 $csv->parse($line) or do {
856 $dbh->rollback if $oldAutoCommit;
857 return "can't parse: ". $csv->error_input();
860 my @columns = $csv->fields();
864 paybatch => $paybatch,
868 foreach my $field ( @fields ) {
870 if ( $field eq 'agent_custid'
872 && $columns[0] =~ /\S+/ )
875 my $agent_custid = $columns[0];
876 my %hash = ( 'agent_custid' => $agent_custid,
877 'agentnum' => $agentnum,
880 if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
881 $dbh->rollback if $oldAutoCommit;
882 return "can't specify custnum with agent_custid $agent_custid";
885 $cust_main = qsearchs({
886 'table' => 'cust_main',
888 'extra_sql' => $extra_sql,
891 unless ( $cust_main ) {
892 $dbh->rollback if $oldAutoCommit;
893 return "can't find customer with agent_custid $agent_custid";
897 $columns[0] = $cust_main->custnum;
900 $cust_pay{$field} = shift @columns;
903 my $cust_pay = new FS::cust_pay( \%cust_pay );
904 my $error = $cust_pay->insert;
907 $dbh->rollback if $oldAutoCommit;
908 return "can't insert payment for $line: $error";
911 if ( $format eq 'simple' ) {
912 # include agentnum for less surprise?
913 $cust_main = qsearchs({
914 'table' => 'cust_main',
915 'hashref' => { 'custnum' => $cust_pay->custnum },
916 'extra_sql' => $extra_sql,
920 unless ( $cust_main ) {
921 $dbh->rollback if $oldAutoCommit;
922 return "can't find customer to which payments apply at line: $line";
925 $error = $cust_main->apply_payments_and_credits;
927 $dbh->rollback if $oldAutoCommit;
928 return "can't apply payments to customer for $line: $error";
936 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
938 return "Empty file!" unless $imported;
948 Delete and replace methods.
952 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
953 schema.html from the base documentation.