1 package FS::cust_credit;
4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $conf $unsuspendauto $me $DEBUG
6 $otaker_upgrade_kludge $ignore_empty_reasonnum
8 use List::Util qw( min );
10 use FS::UID qw( dbh getotaker );
11 use FS::Misc qw(send_email);
12 use FS::Record qw( qsearch qsearchs dbdef );
17 use FS::cust_credit_bill;
25 $me = '[ FS::cust_credit ]';
28 $otaker_upgrade_kludge = 0;
29 $ignore_empty_reasonnum = 0;
31 #ask FS::UID to run this stuff for us later
32 $FS::UID::callback{'FS::cust_credit'} = sub {
35 $unsuspendauto = $conf->exists('unsuspendauto');
39 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
40 'cancel_credit_type' => 'Cancellation Credit',
41 'signup_credit_type' => 'Self-Service 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; }
126 sub cust_unlinked_msg {
128 "WARNING: can't find cust_main.custnum ". $self->custnum.
129 ' (cust_credit.crednum '. $self->crednum. ')';
134 Adds this credit to the database ("Posts" the credit). If there is an error,
135 returns the error, otherwise returns false.
140 my ($self, %options) = @_;
142 local $SIG{HUP} = 'IGNORE';
143 local $SIG{INT} = 'IGNORE';
144 local $SIG{QUIT} = 'IGNORE';
145 local $SIG{TERM} = 'IGNORE';
146 local $SIG{TSTP} = 'IGNORE';
147 local $SIG{PIPE} = 'IGNORE';
149 my $oldAutoCommit = $FS::UID::AutoCommit;
150 local $FS::UID::AutoCommit = 0;
153 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
154 my $old_balance = $cust_main->balance;
156 unless ($self->reasonnum) {
157 my $result = $self->reason( $self->getfield('reason'),
158 exists($options{ 'reason_type' })
159 ? ('reason_type' => $options{ 'reason_type' })
163 $dbh->rollback if $oldAutoCommit;
164 return "failed to set reason for $me"; #: ". $dbh->errstr;
168 $self->setfield('reason', '');
170 my $error = $self->SUPER::insert;
172 $dbh->rollback if $oldAutoCommit;
173 return "error inserting $self: $error";
176 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
178 #false laziness w/ cust_pay::insert
179 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
180 my @errors = $cust_main->unsuspend;
182 # side-fx with nested transactions? upstack rolls back?
183 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
189 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
197 Unless the closed flag is set, deletes this credit and all associated
198 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
199 the void method instead to leave a record of the deleted credit.
203 # very similar to FS::cust_pay::delete
206 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
208 local $SIG{HUP} = 'IGNORE';
209 local $SIG{INT} = 'IGNORE';
210 local $SIG{QUIT} = 'IGNORE';
211 local $SIG{TERM} = 'IGNORE';
212 local $SIG{TSTP} = 'IGNORE';
213 local $SIG{PIPE} = 'IGNORE';
215 my $oldAutoCommit = $FS::UID::AutoCommit;
216 local $FS::UID::AutoCommit = 0;
219 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
220 my $error = $cust_credit_bill->delete;
222 $dbh->rollback if $oldAutoCommit;
227 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
228 my $error = $cust_credit_refund->delete;
230 $dbh->rollback if $oldAutoCommit;
235 my $error = $self->SUPER::delete(@_);
237 $dbh->rollback if $oldAutoCommit;
241 if ( $conf->config('deletecredits') ne '' ) {
243 my $cust_main = $self->cust_main;
245 my $error = send_email(
246 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
247 #invoice_from??? well as good as any
248 'to' => $conf->config('deletecredits'),
249 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
251 "This is an automatic message from your Freeside installation\n",
252 "informing you that the following credit has been deleted:\n",
254 'crednum: '. $self->crednum. "\n",
255 'custnum: '. $self->custnum.
256 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
257 'amount: $'. sprintf("%.2f", $self->amount). "\n",
258 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
259 'reason: '. $self->reason. "\n",
264 $dbh->rollback if $oldAutoCommit;
265 return "can't send credit deletion notification: $error";
270 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
276 =item replace [ OLD_RECORD ]
278 You can, but probably shouldn't modify credits...
280 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
281 supplied, replaces this record. If there is an error, returns the error,
282 otherwise returns false.
288 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
289 $self->SUPER::replace(@_);
294 Checks all fields to make sure this is a valid credit. If there is an error,
295 returns the error, otherwise returns false. Called by the insert and replace
303 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
306 $self->ut_numbern('crednum')
307 || $self->ut_number('custnum')
308 || $self->ut_numbern('_date')
309 || $self->ut_money('amount')
310 || $self->ut_alphan('otaker')
311 || $self->ut_textn('reason')
312 || $self->ut_textn('addlinfo')
313 || $self->ut_enum('closed', [ '', 'Y' ])
314 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
315 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
316 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
317 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
318 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
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 cust_credit_refund
341 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
345 sub cust_credit_refund {
347 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
348 sort { $a->_date <=> $b->_date }
349 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
353 =item cust_credit_bill
355 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
360 sub cust_credit_bill {
362 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
363 sort { $a->_date <=> $b->_date }
364 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
370 Returns the amount of this credit that is still unapplied/outstanding;
371 amount minus all refund applications (see L<FS::cust_credit_refund>) and
372 applications to invoices (see L<FS::cust_credit_bill>).
378 my $amount = $self->amount;
379 $amount -= $_->amount foreach ( $self->cust_credit_refund );
380 $amount -= $_->amount foreach ( $self->cust_credit_bill );
381 sprintf( "%.2f", $amount );
386 Deprecated name for the unapplied method.
392 #carp "cust_credit->credited deprecated; use ->unapplied";
393 $self->unapplied(@_);
398 Returns the customer (see L<FS::cust_main>) for this credit.
404 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
410 Returns the text of the associated reason (see L<FS::reason>) for this credit.
415 my ($self, $value, %options) = @_;
418 my $typenum = $options{'reason_type'};
420 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
421 local $FS::UID::AutoCommit = 0; # a transaction if it matters
423 if ( defined( $value ) ) {
424 my $hashref = { 'reason' => $value };
425 $hashref->{'reason_type'} = $typenum if $typenum;
426 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
427 my $extra_sql = " AND reason_type.class='R'";
429 $reason = qsearchs( { 'table' => 'reason',
430 'hashref' => $hashref,
431 'addl_from' => $addl_from,
432 'extra_sql' => $extra_sql,
435 if (!$reason && $typenum) {
436 $reason = new FS::reason( { 'reason_type' => $typenum,
440 my $error = $reason->insert;
442 warn "error inserting reason: $error\n";
447 $self->reasonnum($reason ? $reason->reasonnum : '') ;
448 warn "$me reason used in set mode with non-existant reason -- clearing"
451 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
453 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
455 ( $reason ? $reason->reason : '' ).
456 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
461 # Used by FS::Upgrade to migrate to a new database.
463 sub _upgrade_data { # class method
464 my ($class, %opts) = @_;
466 warn "$me upgrading $class\n" if $DEBUG;
468 if (defined dbdef->table($class->table)->column('reason')) {
470 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
472 my @cust_credits = qsearch({ 'table' => $class->table,
474 'extra_sql' => 'WHERE reason IS NOT NULL',
477 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
478 warn "$me Found unmigrated reasons\n" if $DEBUG;
479 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
480 my $reason_type = qsearchs( 'reason_type', $hashref );
481 unless ($reason_type) {
482 $reason_type = new FS::reason_type( $hashref );
483 my $error = $reason_type->insert();
484 die "$class had error inserting FS::reason_type into database: $error\n"
488 $hashref = { 'reason_type' => $reason_type->typenum,
491 my $noreason = qsearchs( 'reason', $hashref );
493 $hashref->{'disabled'} = 'Y';
494 $noreason = new FS::reason( $hashref );
495 my $error = $noreason->insert();
496 die "can't insert legacy reason '(none)' into database: $error\n"
500 foreach my $cust_credit ( @cust_credits ) {
501 my $reason = $cust_credit->getfield('reason');
502 warn "Contemplating reason $reason\n" if $DEBUG > 1;
503 if ($reason =~ /\S/) {
504 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
505 or die "can't insert legacy reason $reason into database\n";
507 $cust_credit->reasonnum($noreason->reasonnum);
510 $cust_credit->setfield('reason', '');
511 my $error = $cust_credit->replace;
513 warn "*** WARNING: error replacing reason in $class ".
514 $cust_credit->crednum. ": $error ***\n"
519 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
521 foreach ( keys %reasontype_map ) {
522 unless ($conf->config($_)) { # hmmmm
523 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
524 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
525 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
526 my $reason_type = qsearchs( 'reason_type', $hashref );
527 unless ($reason_type) {
528 $reason_type = new FS::reason_type( $hashref );
529 my $error = $reason_type->insert();
530 die "$class had error inserting FS::reason_type into database: $error\n"
533 $conf->set($_, $reason_type->typenum);
537 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
539 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
540 my $reason_type = qsearchs( 'reason_type', $hashref );
541 unless ($reason_type) {
542 $reason_type = new FS::reason_type( $hashref );
543 my $error = $reason_type->insert();
544 die "$class had error inserting FS::reason_type into database: $error\n"
548 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
549 foreach my $plan ( @plans ) {
550 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
551 unless ($pkg->option('reason_type', 1) ) {
552 my $plandata = $pkg->plandata.
553 "reason_type=". $reason_type->typenum. "\n";
554 $pkg->plandata($plandata);
556 $pkg->replace( undef,
557 'pkg_svc' => { map { $_->svcpart => $_->quantity }
560 'primary_svc' => $pkg->svcpart,
562 die "failed setting reason_type option: $error"
569 local($otaker_upgrade_kludge) = 1;
570 local($ignore_empty_reasonnum) = 1;
571 $class->_upgrade_otaker(%opts);
583 Returns an SQL fragment to retreive the unapplied amount.
588 my ($class, $start, $end) = @_;
590 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
591 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
592 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
593 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
597 ( SELECT SUM(amount) FROM cust_credit_refund
598 WHERE cust_credit.crednum = cust_credit_refund.crednum
599 $refund_start $refund_end )
603 ( SELECT SUM(amount) FROM cust_credit_bill
604 WHERE cust_credit.crednum = cust_credit_bill.crednum
605 $bill_start $bill_end )
614 Deprecated name for the unapplied_sql method.
621 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
623 #$class->unapplied_sql(@_);
627 =item credit_lineitems
631 my $error = FS::cust_credit->credit_lineitems(
633 #the lineitems to credit
634 'billpkgnums' => \@billpkgnums,
635 'setuprecurs' => \@setuprecurs,
636 'amounts' => \@amounts,
637 'apply' => 1, #0 leaves the credit unapplied
640 'newreasonnum' => scalar($cgi->param('newreasonnum')),
641 'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
642 map { $_ => scalar($cgi->param($_)) }
643 #fields('cust_credit')
644 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
650 #maybe i should just be an insert with extra args instead of a class method
651 use FS::cust_bill_pkg;
652 sub credit_lineitems {
653 my( $class, %arg ) = @_;
654 my $curuser = $FS::CurrentUser::CurrentUser;
656 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
658 my $cust_main = qsearchs({
659 'table' => 'cust_main',
660 'hashref' => { 'custnum' => $arg{custnum} },
661 'extra_sql' => ' AND '. $curuser->agentnums_sql,
662 }) or return 'unknown customer';
665 local $SIG{HUP} = 'IGNORE';
666 local $SIG{INT} = 'IGNORE';
667 local $SIG{QUIT} = 'IGNORE';
668 local $SIG{TERM} = 'IGNORE';
669 local $SIG{TSTP} = 'IGNORE';
670 local $SIG{PIPE} = 'IGNORE';
672 my $oldAutoCommit = $FS::UID::AutoCommit;
673 local $FS::UID::AutoCommit = 0;
676 #my @cust_bill_pkg = qsearch({
677 # 'select' => 'cust_bill_pkg.*',
678 # 'table' => 'cust_bill_pkg',
679 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
680 # ' LEFT JOIN cust_main USING (custnum) ',
681 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
682 # join( ',', @{$arg{billpkgnums}} ). ')',
683 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
687 if ($arg{reasonnum} == -1) {
689 $error = 'Enter a new reason (or select an existing one)'
690 unless $arg{newreasonnum} !~ /^\s*$/;
691 my $reason = new FS::reason {
692 'reason' => $arg{newreasonnum},
693 'reason_type' => $arg{newreasonnum_type},
695 $error ||= $reason->insert;
697 $dbh->rollback if $oldAutoCommit;
698 return "Error inserting reason: $error";
700 $arg{reasonnum} = $reason->reasonnum;
703 my $cust_credit = new FS::cust_credit ( {
704 map { $_ => $arg{$_} }
705 #fields('cust_credit')
706 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
708 $error = $cust_credit->insert;
710 $dbh->rollback if $oldAutoCommit;
711 return "Error inserting credit: $error";
714 unless ( $arg{'apply'} ) {
715 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
720 # keys in all of these are invoice numbers
721 my %cust_credit_bill = ();
722 my %cust_bill_pkg = ();
723 my %cust_credit_bill_pkg = ();
724 my %taxlisthash = ();
725 my %unapplied_payments = (); #invoice numbers, and then billpaynums
726 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
727 my $setuprecur = shift @{$arg{setuprecurs}};
728 my $amount = shift @{$arg{amounts}};
730 my $cust_bill_pkg = qsearchs({
731 'table' => 'cust_bill_pkg',
732 'hashref' => { 'billpkgnum' => $billpkgnum },
733 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
734 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
735 }) or die "unknown billpkgnum $billpkgnum";
737 my $invnum = $cust_bill_pkg->invnum;
739 if ( $setuprecur eq 'setup' ) {
740 $cust_bill_pkg->setup($amount);
741 $cust_bill_pkg->recur(0);
742 $cust_bill_pkg->unitrecur(0);
743 $cust_bill_pkg->type('');
745 $setuprecur = 'recur'; #in case its a usage classnum?
746 $cust_bill_pkg->recur($amount);
747 $cust_bill_pkg->setup(0);
748 $cust_bill_pkg->unitsetup(0);
751 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
753 #unapply any payments applied to this line item (other credits too?)
754 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
755 $error = $cust_bill_pay_pkg->delete;
757 $dbh->rollback if $oldAutoCommit;
758 return "Error unapplying payment: $error";
760 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
761 += $cust_bill_pay_pkg->amount;
764 #$subtotal += $amount;
765 $cust_credit_bill{$invnum} += $amount;
766 push @{ $cust_credit_bill_pkg{$invnum} },
767 new FS::cust_credit_bill_pkg {
768 'billpkgnum' => $cust_bill_pkg->billpkgnum,
769 'amount' => sprintf('%.2f',$amount),
770 'setuprecur' => $setuprecur,
771 'sdate' => $cust_bill_pkg->sdate,
772 'edate' => $cust_bill_pkg->edate,
775 # recalculate taxes with new amounts
776 $taxlisthash{$invnum} ||= {};
777 my $part_pkg = $cust_bill_pkg->part_pkg;
778 $cust_main->_handle_taxes( $part_pkg,
779 $taxlisthash{$invnum},
781 $cust_bill_pkg->cust_pkg,
782 $cust_bill_pkg->cust_bill->_date, #invoice time
783 $cust_bill_pkg->cust_pkg->pkgpart,
788 # now loop through %cust_credit_bill and insert those
791 # (hack to prevent cust_credit_bill_pkg insertion)
792 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
794 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
796 my $arrayref_or_error =
797 $cust_main->calculate_taxes(
798 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
799 $taxlisthash{$invnum}, # list of tax-item bindings
800 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
803 unless ( ref( $arrayref_or_error ) ) {
804 $dbh->rollback if $oldAutoCommit;
805 return "Error calculating taxes: $arrayref_or_error";
808 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
811 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
812 my $billpkgnum = $cust_bill_pkg->billpkgnum;
813 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
814 # gather up existing tax links (we need their billpkgtaxlocationnums)
815 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
816 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
818 foreach ( @tax_links ) {
819 $tax_links{$_->billpkgnum} ||= {};
820 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
824 foreach my $taxline ( @$arrayref_or_error ) {
826 my $amount = $taxline->setup;
828 # find equivalent tax line item on the existing invoice
829 my $tax_item = qsearchs('cust_bill_pkg', {
832 'itemdesc' => $taxline->desc,
835 # or should we just exit if this happens?
836 $cust_credit->set('amount',
837 sprintf('%.2f', $cust_credit->get('amount') - $amount)
839 my $error = $cust_credit->replace;
841 $dbh->rollback if $oldAutoCommit;
842 return "error correcting credit for missing tax line: $error";
846 # but in the new era, we no longer have the problem of uniquely
847 # identifying the tax_Xlocation record. The billpkgnums of the
848 # tax and the taxed item are known.
850 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
851 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
853 # the existing tax_Xlocation object
855 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_billpkgnum};
857 next if !$old_loc; # apply the leftover amount nonspecifically
859 #support partial credits: use $amount if smaller
860 # (so just distribute to the first location? perhaps should
862 my $loc_amount = min( $amount, $new_loc->amount);
864 $amount -= $loc_amount;
866 $cust_credit_bill{$invnum} += $loc_amount;
867 push @{ $cust_credit_bill_pkg{$invnum} },
868 new FS::cust_credit_bill_pkg {
869 'billpkgnum' => $tax_item->billpkgnum,
870 'amount' => $loc_amount,
871 'setuprecur' => 'setup',
872 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
873 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
876 } #foreach my $new_loc
878 # we still have to deal with the possibility that the tax links don't
879 # cover the whole amount of tax because of an incomplete upgrade...
881 $cust_credit_bill{$invnum} += $amount;
882 push @{ $cust_credit_bill_pkg{$invnum} },
883 new FS::cust_credit_bill_pkg {
884 'billpkgnum' => $tax_item->billpkgnum,
886 'setuprecur' => 'setup',
891 #unapply any payments applied to the tax
892 foreach my $cust_bill_pay_pkg
893 ( $tax_item->cust_bill_pay_pkg('setup') )
895 $error = $cust_bill_pay_pkg->delete;
897 $dbh->rollback if $oldAutoCommit;
898 return "Error unapplying payment: $error";
900 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
901 += $cust_bill_pay_pkg->amount;
905 # if we unapplied any payments from line items, also unapply that
906 # amount from the invoice
907 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
908 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
909 or die "broken payment application $billpaynum";
910 my @subapps = $cust_bill_pay->lineitem_applications;
911 $error = $cust_bill_pay->delete; # can't replace
913 my $new_cust_bill_pay = FS::cust_bill_pay->new({
914 $cust_bill_pay->hash,
916 amount => sprintf('%.2f',
917 $cust_bill_pay->amount
918 - $unapplied_payments{$invnum}{$billpaynum}),
921 if ( $new_cust_bill_pay->amount > 0 ) {
922 $error ||= $new_cust_bill_pay->insert;
923 # Also reapply it to everything it was applied to before.
924 # Note that we've already deleted cust_bill_pay_pkg records for the
925 # items we're crediting, so they aren't on this list.
926 foreach my $cust_bill_pay_pkg (@subapps) {
927 $cust_bill_pay_pkg->billpaypkgnum('');
928 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
929 $error ||= $cust_bill_pay_pkg->insert;
933 $dbh->rollback if $oldAutoCommit;
934 return "Error unapplying payment: $error";
937 #insert cust_credit_bill
939 my $cust_credit_bill = new FS::cust_credit_bill {
940 'crednum' => $cust_credit->crednum,
942 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
944 $error = $cust_credit_bill->insert;
946 $dbh->rollback if $oldAutoCommit;
947 return "Error applying credit of $cust_credit_bill{$invnum} ".
948 " to invoice $invnum: $error";
951 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
952 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
953 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
954 $error = $cust_credit_bill_pkg->insert;
956 $dbh->rollback if $oldAutoCommit;
957 return "Error applying credit to line item: $error";
963 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
972 The delete method. The replace method.
974 B<credited> and B<credited_sql> are now called B<unapplied> and
975 B<unapplied_sql>. The old method names should start to give warnings.
979 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
980 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base