1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
6 use vars qw( $conf $me $DEBUG
7 $otaker_upgrade_kludge $ignore_empty_reasonnum
9 use List::Util qw( min );
11 use FS::UID qw( dbh );
12 use FS::Record qw( qsearch qsearchs dbdef );
16 use FS::cust_credit_bill;
23 use FS::cust_credit_void;
24 use FS::cust_bill_pkg;
25 use FS::upgrade_journal;
27 $me = '[ FS::cust_credit ]';
30 $otaker_upgrade_kludge = 0;
31 $ignore_empty_reasonnum = 0;
33 #ask FS::UID to run this stuff for us later
34 $FS::UID::callback{'FS::cust_credit'} = sub {
40 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
41 'cancel_credit_type' => 'Cancellation Credit',
46 FS::cust_credit - Object methods for cust_credit records
52 $record = new FS::cust_credit \%hash;
53 $record = new FS::cust_credit { 'column' => 'value' };
55 $error = $record->insert;
57 $error = $new_record->replace($old_record);
59 $error = $record->delete;
61 $error = $record->check;
65 An FS::cust_credit object represents a credit; the equivalent of a negative
66 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
67 FS::Record. The following fields are currently supported:
73 Primary key (assigned automatically for new credits)
77 Customer (see L<FS::cust_main>)
85 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
86 L<Time::Local> and L<Date::Parse> for conversion functions.
90 Order taker (see L<FS::access_user>)
98 Reason (see L<FS::reason>)
106 Books closed flag, empty or `Y'
110 Desired pkgnum when using experimental package balances.
120 Creates a new credit. To add the credit to the database, see L<"insert">.
124 sub table { 'cust_credit'; }
125 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
126 sub cust_unlinked_msg {
128 "WARNING: can't find cust_main.custnum ". $self->custnum.
129 ' (cust_credit.crednum '. $self->crednum. ')';
132 =item insert [ OPTION => VALUE ... ]
134 Adds this credit to the database ("Posts" the credit). If there is an error,
135 returns the error, otherwise returns false.
137 Ooptions are passed as a list of keys and values. Available options:
143 L<FS::reason_type|Reason> type for newly-inserted reason
145 =item cust_credit_source_bill_pkg
148 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
149 They will have their crednum set and will be inserted along with this credit.
156 my ($self, %options) = @_;
158 local $SIG{HUP} = 'IGNORE';
159 local $SIG{INT} = 'IGNORE';
160 local $SIG{QUIT} = 'IGNORE';
161 local $SIG{TERM} = 'IGNORE';
162 local $SIG{TSTP} = 'IGNORE';
163 local $SIG{PIPE} = 'IGNORE';
165 my $oldAutoCommit = $FS::UID::AutoCommit;
166 local $FS::UID::AutoCommit = 0;
169 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
170 my $old_balance = $cust_main->balance;
172 if (!$self->reasonnum) {
173 my $reason_text = $self->get('reason')
174 or return "reason text or existing reason required";
175 my $reason_type = $options{'reason_type'}
176 or return "reason type required";
179 my $reason = FS::reason->new_or_existing(
180 reason => $reason_text,
181 type => $reason_type,
185 $dbh->rollback if $oldAutoCommit;
186 return "failed to set credit reason: $@";
188 $self->set('reasonnum', $reason->reasonnum);
191 $self->setfield('reason', '');
193 my $error = $self->SUPER::insert;
195 $dbh->rollback if $oldAutoCommit;
196 return "error inserting $self: $error";
199 if ( $options{'cust_credit_source_bill_pkg'} ) {
200 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
201 $ccsbr->crednum( $self->crednum );
202 $error = $ccsbr->insert;
204 $dbh->rollback if $oldAutoCommit;
205 return "error inserting $ccsbr: $error";
210 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
212 # possibly trigger package unsuspend, doesn't abort transaction on failure
213 $self->unsuspend_balance if $old_balance;
215 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
223 Unless the closed flag is set, deletes this credit and all associated
224 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
225 the void method instead to leave a record of the deleted credit.
229 # very similar to FS::cust_pay::delete
234 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
236 local $SIG{HUP} = 'IGNORE';
237 local $SIG{INT} = 'IGNORE';
238 local $SIG{QUIT} = 'IGNORE';
239 local $SIG{TERM} = 'IGNORE';
240 local $SIG{TSTP} = 'IGNORE';
241 local $SIG{PIPE} = 'IGNORE';
243 my $oldAutoCommit = $FS::UID::AutoCommit;
244 local $FS::UID::AutoCommit = 0;
247 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
248 my $error = $cust_credit_bill->delete;
250 $dbh->rollback if $oldAutoCommit;
255 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
256 my $error = $cust_credit_refund->delete;
258 $dbh->rollback if $oldAutoCommit;
263 my $error = $self->SUPER::delete(@_);
265 $dbh->rollback if $oldAutoCommit;
269 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
275 =item replace [ OLD_RECORD ]
277 You can, but probably shouldn't modify credits...
279 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
280 supplied, replaces this record. If there is an error, returns the error,
281 otherwise returns false.
287 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
288 $self->SUPER::replace(@_);
293 Checks all fields to make sure this is a valid credit. If there is an error,
294 returns the error, otherwise returns false. Called by the insert and replace
302 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
305 $self->ut_numbern('crednum')
306 || $self->ut_number('custnum')
307 || $self->ut_numbern('_date')
308 || $self->ut_money('amount')
309 || $self->ut_alphan('otaker')
310 || $self->ut_textn('reason')
311 || $self->ut_textn('addlinfo')
312 || $self->ut_enum('closed', [ '', 'Y' ])
313 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
314 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
315 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
316 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
317 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
318 || $self->ut_foreign_keyn('commission_invnum', 'cust_bill', 'invnum')
320 return $error if $error;
322 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
323 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
324 return $error if $error;
326 return "amount must be > 0 " if $self->amount <= 0;
328 return "amount must be greater or equal to amount applied"
329 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
331 return "Unknown customer"
332 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
334 $self->_date(time) unless $self->_date;
339 =item void [ REASON ]
341 Voids this credit: deletes the credit and all associated applications and
342 adds a record of the voided credit to the cust_credit_void table.
350 unless (ref($reason) || !$reason) {
351 $reason = FS::reason->new_or_existing(
353 'type' => 'Void credit',
358 local $SIG{HUP} = 'IGNORE';
359 local $SIG{INT} = 'IGNORE';
360 local $SIG{QUIT} = 'IGNORE';
361 local $SIG{TERM} = 'IGNORE';
362 local $SIG{TSTP} = 'IGNORE';
363 local $SIG{PIPE} = 'IGNORE';
365 my $oldAutoCommit = $FS::UID::AutoCommit;
366 local $FS::UID::AutoCommit = 0;
369 my $cust_credit_void = new FS::cust_credit_void ( {
370 map { $_ => $self->get($_) } $self->fields
372 $cust_credit_void->set('void_reasonnum', $reason->reasonnum) if $reason;
373 my $error = $cust_credit_void->insert;
375 $dbh->rollback if $oldAutoCommit;
379 $error = $self->delete();
381 $dbh->rollback if $oldAutoCommit;
385 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
391 =item cust_credit_refund
393 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
397 sub cust_credit_refund {
399 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
400 sort { $a->_date <=> $b->_date }
401 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
405 =item cust_credit_bill
407 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
412 sub cust_credit_bill {
414 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
415 sort { $a->_date <=> $b->_date }
416 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
422 Returns the amount of this credit that is still unapplied/outstanding;
423 amount minus all refund applications (see L<FS::cust_credit_refund>) and
424 applications to invoices (see L<FS::cust_credit_bill>).
430 my $amount = $self->amount;
431 $amount -= $_->amount foreach ( $self->cust_credit_refund );
432 $amount -= $_->amount foreach ( $self->cust_credit_bill );
433 sprintf( "%.2f", $amount );
438 Deprecated name for the unapplied method.
444 #carp "cust_credit->credited deprecated; use ->unapplied";
445 $self->unapplied(@_);
450 Returns the customer (see L<FS::cust_main>) for this credit.
456 # Used by FS::Upgrade to migrate to a new database.
458 sub _upgrade_data { # class method
459 my ($class, %opts) = @_;
461 warn "$me upgrading $class\n" if $DEBUG;
463 $class->_upgrade_reasonnum(%opts);
465 if (defined dbdef->table($class->table)->column('reason')) {
467 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
469 foreach ( keys %reasontype_map ) {
470 unless ($conf->config($_)) { # hmmmm
471 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
472 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
473 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
474 my $reason_type = qsearchs( 'reason_type', $hashref );
475 unless ($reason_type) {
476 $reason_type = new FS::reason_type( $hashref );
477 my $error = $reason_type->insert();
478 die "$class had error inserting FS::reason_type into database: $error\n"
481 $conf->set($_, $reason_type->typenum);
485 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
487 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
488 my $reason_type = qsearchs( 'reason_type', $hashref );
489 unless ($reason_type) {
490 $reason_type = new FS::reason_type( $hashref );
491 my $error = $reason_type->insert();
492 die "$class had error inserting FS::reason_type into database: $error\n"
496 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
497 foreach my $plan ( @plans ) {
498 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
499 unless ($pkg->option('reason_type', 1) ) {
500 my $plandata = $pkg->plandata.
501 "reason_type=". $reason_type->typenum. "\n";
502 $pkg->plandata($plandata);
504 $pkg->replace( undef,
505 'pkg_svc' => { map { $_->svcpart => $_->quantity }
508 'primary_svc' => $pkg->svcpart,
510 die "failed setting reason_type option: $error"
517 local($otaker_upgrade_kludge) = 1;
518 local($ignore_empty_reasonnum) = 1;
519 $class->_upgrade_otaker(%opts);
521 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
522 and !$conf->config('tax_data_vendor') ) {
523 # RT#25458: fix credit line item applications that should refer to a
524 # specific tax allocation
525 my @cust_credit_bill_pkg = qsearch({
526 table => 'cust_credit_bill_pkg',
527 select => 'cust_credit_bill_pkg.*',
528 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
530 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
531 'AND cust_bill_pkg.pkgnum = 0', # is a tax
535 foreach (@cust_credit_bill_pkg) {
536 my $billpkgnum = $_->billpkgnum;
537 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
538 $credits{$billpkgnum} ||= [];
539 push @{ $credits{$billpkgnum} }, $_;
541 TAX_ITEM: foreach my $tax_item (values %tax_items) {
542 my $billpkgnum = $tax_item->billpkgnum;
543 # get all pkg/location/taxrate allocations of this tax line item
544 my @allocations = sort {$b->amount <=> $a->amount}
545 qsearch('cust_bill_pkg_tax_location', {
546 billpkgnum => $billpkgnum
548 # and these are all credit applications to it
549 my @credits = sort {$b->amount <=> $a->amount}
550 @{ $credits{$billpkgnum} };
551 my $c = shift @credits;
552 my $a = shift @allocations; # we will NOT modify these
554 if ( abs($c->amount - $a->amount) < 0.005 ) {
555 # by far the most common case: the tax line item is for a single
556 # tax, so we just fill in the billpkgtaxlocationnum
557 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
558 my $error = $c->replace;
560 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
564 $a = shift @allocations;
565 } elsif ( $c->amount > $a->amount ) {
566 # fairly common: the tax line contains tax for multiple packages
567 # (or multiple taxes) but the credit isn't divided up
568 my $new_link = FS::cust_credit_bill_pkg->new({
569 creditbillnum => $c->creditbillnum,
570 billpkgnum => $c->billpkgnum,
571 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
572 amount => $a->amount,
573 setuprecur => 'setup',
575 my $error = $new_link->insert;
577 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
580 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
581 $a = shift @allocations;
582 } elsif ( $c->amount < 0.005 ) {
583 # also fairly common; we can delete these with no harm
584 my $error = $c->delete;
585 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
587 } elsif ( $c->amount < $a->amount ) {
588 # should never happen, but if it does, handle it gracefully
589 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
590 my $error = $c->replace;
592 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
595 $a->set(amount => $a->amount - $c->amount);
600 if ( $c->amount < 0.005 ) {
601 my $error = $c->delete;
602 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
603 } elsif ( $c->modified ) {
604 # then we've allocated part of it, so reduce the nonspecific
605 # application by that much
606 my $error = $c->replace;
607 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
609 # else there are probably no allocations, i.e. this is a pre-3.x
610 # record that was never migrated over, so leave it alone
612 } # foreach $tax_item
613 FS::upgrade_journal->set_done('cust_credit__tax_link');
625 Returns an SQL fragment to retreive the unapplied amount.
630 my ($class, $start, $end) = @_;
632 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
633 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
634 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
635 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
639 ( SELECT SUM(amount) FROM cust_credit_refund
640 WHERE cust_credit.crednum = cust_credit_refund.crednum
641 $refund_start $refund_end )
645 ( SELECT SUM(amount) FROM cust_credit_bill
646 WHERE cust_credit.crednum = cust_credit_bill.crednum
647 $bill_start $bill_end )
656 Deprecated name for the unapplied_sql method.
663 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
665 #$class->unapplied_sql(@_);
669 =item calculate_tax_adjustment PARAMS
671 Calculate the amount of tax that needs to be credited as part of a lineitem
676 - billpkgnums: arrayref identifying the line items to credit
677 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
678 the lineitem charge is being credited
679 - amounts: arrayref of the amounts to credit on each line item
680 - custnum: the customer all of these invoices belong to, for error checking
682 Returns a hash containing:
683 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
684 - taxtotal: the total tax amount to be credited
685 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
686 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
687 - num: the key within that table
688 - credit: the credit amount to apply to that line
692 sub calculate_tax_adjustment {
693 my ($class, %arg) = @_;
700 my (%cust_bill_pkg, %cust_bill);
702 for (my $i = 0; ; $i++) {
703 my $billpkgnum = $arg{billpkgnums}[$i]
705 my $setuprecur = $arg{setuprecurs}[$i];
706 my $amount = $arg{amounts}[$i];
707 next if $amount == 0;
708 $subtotal += $amount;
709 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
710 ||= FS::cust_bill_pkg->by_key($billpkgnum)
711 or die "lineitem #$billpkgnum not found\n";
713 my $invnum = $cust_bill_pkg->invnum;
714 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
715 $cust_bill{ $invnum}->custnum == $arg{custnum}
716 or die "lineitem #$billpkgnum not found\n";
718 # tax_Xlocation records don't distinguish setup and recur, so calculate
719 # the fraction of setup+recur (after deducting credits) that's setup. This
720 # will also be the fraction of tax (after deducting credits) that's tax on
723 $setup = $cust_bill_pkg->get('setup') || 0;
725 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
727 $recur = $cust_bill_pkg->get('recur') || 0;
729 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
731 my $setup_ratio = $setup / ($setup + $recur);
733 # Calculate the fraction of tax to credit: it's the fraction of this charge
734 # (either setup or recur) that's being credited.
735 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
736 next if $charged == 0; # shouldn't happen, but still...
738 if ($charged < $amount) {
739 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
742 my $credit_ratio = $amount / $charged;
744 # gather taxes that apply to the selected item
746 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
748 foreach my $tax_link (
749 qsearch($table, { taxable_billpkgnum => $billpkgnum })
751 my $tax_amount = $tax_link->amount;
752 # deduct existing credits applied to the tax, for the same reason as
754 foreach ($tax_link->cust_credit_bill_pkg) {
755 $tax_amount -= $_->amount;
757 # split tax amount based on setuprecur
758 # (this method ensures that, if you credit both setup and recur tax,
759 # it always equals the entire tax despite any rounding)
760 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
761 if ( $setuprecur eq 'setup' ) {
762 $tax_amount = $setup_tax;
764 $tax_amount = $tax_amount - $setup_tax;
766 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
767 my $pkey = $tax_link->get($tax_link->primary_key);
771 credit => $tax_credit,
773 $taxtotal += $tax_credit;
775 } #foreach cust_bill_pkg_tax_(rate_)?location
777 } # foreach $billpkgnum
780 subtotal => sprintf('%.2f', $subtotal),
781 taxtotal => sprintf('%.2f', $taxtotal),
782 taxlines => \@taxlines,
786 =item credit_lineitems OPTIONS
788 Creates a credit to a group of line items, with a specified amount applied
789 to each. This will also calculate the tax adjustments for those amounts and
790 credit the appropriate tax line items.
794 my $error = FS::cust_credit->credit_lineitems(
796 #the lineitems to credit
797 'billpkgnums' => \@billpkgnums,
798 'setuprecurs' => \@setuprecurs,
799 'amounts' => \@amounts,
800 'apply' => 1, #0 leaves the credit unapplied
801 'set_source' => 1, #creates credit source records for the line items
804 map { $_ => scalar($cgi->param($_)) }
805 #fields('cust_credit')
806 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
810 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
811 arrays. Each one indicates an amount of credit to be applied to either the
812 setup or recur portion of a (non-tax) line item.
814 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
815 credit before it's inserted.
817 C<amount> is the total amount. If unspecified, the credit will be the sum
818 of the per-line-item amounts and their tax adjustments.
822 #maybe i should just be an insert with extra args instead of a class method
823 sub credit_lineitems {
824 my( $class, %arg ) = @_;
825 my $curuser = $FS::CurrentUser::CurrentUser;
827 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
829 my $cust_main = qsearchs({
830 'table' => 'cust_main',
831 'hashref' => { 'custnum' => $arg{custnum} },
832 'extra_sql' => ' AND '. $curuser->agentnums_sql,
833 }) or return 'unknown customer';
836 local $SIG{HUP} = 'IGNORE';
837 local $SIG{INT} = 'IGNORE';
838 local $SIG{QUIT} = 'IGNORE';
839 local $SIG{TERM} = 'IGNORE';
840 local $SIG{TSTP} = 'IGNORE';
841 local $SIG{PIPE} = 'IGNORE';
843 my $oldAutoCommit = $FS::UID::AutoCommit;
844 local $FS::UID::AutoCommit = 0;
847 #my @cust_bill_pkg = qsearch({
848 # 'select' => 'cust_bill_pkg.*',
849 # 'table' => 'cust_bill_pkg',
850 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
851 # ' LEFT JOIN cust_main USING (custnum) ',
852 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
853 # join( ',', @{$arg{billpkgnums}} ). ')',
854 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
859 # first, determine the tax adjustments
860 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
861 # and determine the amount automatically if it wasn't specified
862 if ( !exists( $arg{amount} ) ) {
863 $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
866 my $set_source = $arg{set_source};
869 my $cust_credit = new FS::cust_credit ( {
870 map { $_ => $arg{$_} }
871 #fields('cust_credit')
872 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
874 $error = $cust_credit->insert;
876 $dbh->rollback if $oldAutoCommit;
877 return "Error inserting credit: $error";
880 unless ( $arg{'apply'} ) {
881 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
886 # keys in all of these are invoice numbers
887 my %cust_credit_bill = ();
888 my %cust_bill_pkg = ();
889 my %cust_credit_bill_pkg = ();
890 my %unapplied_payments = (); #invoice numbers, and then billpaynums
893 # little private function to unapply payments from a cust_bill_pkg until
894 # there's a specified amount of unpaid balance on it.
895 # it's a separate sub because we do it for both tax and nontax items. it's
896 # private because it needs access to some local data structures.
897 my $unapply_sub = sub {
898 my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
900 my $invnum = $cust_bill_pkg->invnum;
902 $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
903 next if $need_to_unapply < 0.005;
906 # then unapply payments one at a time (partially if need be) until the
907 # unpaid balance = the credit amount.
908 foreach my $cust_bill_pay_pkg (
909 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
911 my $this_amount = $cust_bill_pay_pkg->amount;
912 if ( $this_amount > $need_to_unapply ) {
913 # unapply the needed amount
914 $cust_bill_pay_pkg->set('amount',
915 sprintf('%.2f', $this_amount - $need_to_unapply));
916 $error = $cust_bill_pay_pkg->replace;
917 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
918 last; # and we're done
922 $error = $cust_bill_pay_pkg->delete;
923 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
925 $need_to_unapply -= $this_amount;
928 } # foreach $cust_bill_pay_pkg
930 # return an error if we somehow still have leftover $need_to_unapply?
936 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
937 my $setuprecur = shift @{$arg{setuprecurs}};
938 my $amount = shift @{$arg{amounts}};
940 my $cust_bill_pkg = qsearchs({
941 'table' => 'cust_bill_pkg',
942 'hashref' => { 'billpkgnum' => $billpkgnum },
943 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
944 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
945 }) or die "unknown billpkgnum $billpkgnum";
947 my $invnum = $cust_bill_pkg->invnum;
949 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
951 $cust_credit_bill{$invnum} += $amount;
952 push @{ $cust_credit_bill_pkg{$invnum} },
953 new FS::cust_credit_bill_pkg {
954 'billpkgnum' => $billpkgnum,
955 'amount' => sprintf('%.2f',$amount),
956 'setuprecur' => $setuprecur,
957 'sdate' => $cust_bill_pkg->sdate,
958 'edate' => $cust_bill_pkg->edate,
961 # unapply payments if necessary
962 $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
965 $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
966 my $source = FS::cust_credit_source_bill_pkg->new({
967 'crednum' => $cust_credit->crednum,
968 'billpkgnum' => $billpkgnum,
970 'currency' => $currency{invnum},
972 $error ||= $source->insert;
976 $dbh->rollback if $oldAutoCommit;
977 return "Error unapplying payment: $error";
981 # do the same for taxes
982 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
983 my $table = $tax_credit->{table};
984 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
985 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
987 my $billpkgnum = $tax_link->billpkgnum;
988 my $cust_bill_pkg = qsearchs({
989 'table' => 'cust_bill_pkg',
990 'hashref' => { 'billpkgnum' => $billpkgnum },
991 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
992 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
993 }) or die "unknown billpkgnum $billpkgnum";
995 my $invnum = $cust_bill_pkg->invnum;
996 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
998 my $amount = $tax_credit->{credit};
999 $cust_credit_bill{$invnum} += $amount;
1001 # create a credit application record to the tax line item, earmarked
1002 # to the specific cust_bill_pkg_Xlocation
1003 push @{ $cust_credit_bill_pkg{$invnum} },
1004 new FS::cust_credit_bill_pkg {
1005 'billpkgnum' => $billpkgnum,
1006 'amount' => sprintf('%.2f', $amount),
1007 'setuprecur' => 'setup',
1008 $tax_link->primary_key, $tax_credit->{num}
1011 $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1013 # I guess it's correct to do this for taxes also?
1014 if ( $set_source ) {
1015 $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
1016 my $source = FS::cust_credit_source_bill_pkg->new({
1017 'crednum' => $cust_credit->crednum,
1018 'billpkgnum' => $billpkgnum,
1019 'amount' => $amount,
1020 'currency' => $currency{invnum},
1022 $error ||= $source->insert;
1026 $dbh->rollback if $oldAutoCommit;
1027 return "Error unapplying payment: $error";
1032 # now loop through %cust_credit_bill and insert those
1035 # (hack to prevent cust_credit_bill_pkg insertion)
1036 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1038 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1040 # if we unapplied any payments from line items, also unapply that
1041 # amount from the invoice
1042 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1043 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1044 or die "broken payment application $billpaynum";
1045 my @subapps = $cust_bill_pay->lineitem_applications;
1046 $error = $cust_bill_pay->delete; # can't replace
1048 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1049 $cust_bill_pay->hash,
1051 amount => sprintf('%.2f',
1052 $cust_bill_pay->amount
1053 - $unapplied_payments{$invnum}{$billpaynum}),
1056 if ( $new_cust_bill_pay->amount > 0 ) {
1057 $error ||= $new_cust_bill_pay->insert;
1058 # Also reapply it to everything it was applied to before.
1059 # Note that we've already deleted cust_bill_pay_pkg records for the
1060 # items we're crediting, so they aren't on this list.
1061 foreach my $cust_bill_pay_pkg (@subapps) {
1062 $cust_bill_pay_pkg->billpaypkgnum('');
1063 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1064 $error ||= $cust_bill_pay_pkg->insert;
1068 $dbh->rollback if $oldAutoCommit;
1069 return "Error unapplying payment: $error";
1072 #insert cust_credit_bill
1074 my $cust_credit_bill = new FS::cust_credit_bill {
1075 'crednum' => $cust_credit->crednum,
1076 'invnum' => $invnum,
1077 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1079 $error = $cust_credit_bill->insert;
1081 $dbh->rollback if $oldAutoCommit;
1082 return "Error applying credit of $cust_credit_bill{$invnum} ".
1083 " to invoice $invnum: $error";
1086 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1087 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1088 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1089 $error = $cust_credit_bill_pkg->insert;
1091 $dbh->rollback if $oldAutoCommit;
1092 return "Error applying credit to line item: $error";
1098 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1103 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1105 =item refund_to_unapply
1107 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1108 (all currently applied refunds that aren't closed.)
1109 Returns empty list if credit itself is closed.
1113 sub refund_to_unapply {
1115 return () if $self->closed;
1117 'table' => 'cust_credit_refund',
1118 'hashref' => { 'crednum' => $self->crednum },
1119 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1120 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1124 =item unapply_refund
1126 Deletes all objects returned by L</refund_to_unapply>.
1130 sub unapply_refund {
1133 local $SIG{HUP} = 'IGNORE';
1134 local $SIG{INT} = 'IGNORE';
1135 local $SIG{QUIT} = 'IGNORE';
1136 local $SIG{TERM} = 'IGNORE';
1137 local $SIG{TSTP} = 'IGNORE';
1138 local $SIG{PIPE} = 'IGNORE';
1140 my $oldAutoCommit = $FS::UID::AutoCommit;
1141 local $FS::UID::AutoCommit = 0;
1143 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1144 my $error = $cust_credit_refund->delete;
1146 dbh->rollback if $oldAutoCommit;
1151 dbh->commit or die dbh->errstr if $oldAutoCommit;
1161 =item process_batch_import
1165 use List::Util qw( min );
1167 use FS::cust_credit_bill;
1168 sub process_batch_import {
1171 # some false laziness with FS::cust_pay::process_batch_import
1174 my $custnum = $hash{'custnum'};
1175 my $agent_custid = $hash{'agent_custid'};
1176 # translate agent_custid into regular custnum
1177 if ($custnum && $agent_custid) {
1178 die "can't specify both custnum and agent_custid\n";
1179 } elsif ($agent_custid) {
1180 # here is the agent virtualization
1181 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1183 $search{'agent_custid'} = $agent_custid
1185 $search{'custnum'} = $custnum
1187 my $cust_main = qsearchs({
1188 'table' => 'cust_main',
1189 'hashref' => \%search,
1190 'extra_sql' => $extra_sql,
1192 die "can't find customer with" .
1193 ($custnum ? " custnum $custnum" : '') .
1194 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1196 die "mismatched customer number\n"
1197 if $custnum && ($custnum ne $cust_main->custnum);
1198 $custnum = $cust_main->custnum;
1200 $hash{'custnum'} = $custnum;
1201 delete($hash{'agent_custid'});
1205 my $opt = { 'table' => 'cust_credit',
1206 'params' => [ '_date', 'credbatch' ],
1207 'formats' => { 'simple' =>
1208 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1211 'format_hash_callbacks' => { 'simple' => $hashcb },
1212 'postinsert_callback' => sub {
1213 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1215 if ( $cust_credit->invnum ) {
1217 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1218 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1220 my $cust_credit_bill = new FS::cust_credit_bill ( {
1221 'crednum' => $cust_credit->crednum,
1222 'invnum' => $cust_bill->invnum,
1223 'amount' => $amount,
1225 my $error = $cust_credit_bill->insert;
1226 return '' unless $error;
1230 #apply_payments_and_credits ?
1231 $cust_credit->cust_main->apply_credits;
1238 FS::Record::process_batch_import( $job, $opt, @_ );
1246 The delete method. The replace method.
1248 B<credited> and B<credited_sql> are now called B<unapplied> and
1249 B<unapplied_sql>. The old method names should start to give warnings.
1253 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1254 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base