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;
24 use FS::cust_credit_void;
26 $me = '[ FS::cust_credit ]';
29 $otaker_upgrade_kludge = 0;
30 $ignore_empty_reasonnum = 0;
32 #ask FS::UID to run this stuff for us later
33 $FS::UID::callback{'FS::cust_credit'} = sub {
36 $unsuspendauto = $conf->exists('unsuspendauto');
40 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
41 'cancel_credit_type' => 'Cancellation Credit',
42 'signup_credit_type' => 'Self-Service Credit',
47 FS::cust_credit - Object methods for cust_credit records
53 $record = new FS::cust_credit \%hash;
54 $record = new FS::cust_credit { 'column' => 'value' };
56 $error = $record->insert;
58 $error = $new_record->replace($old_record);
60 $error = $record->delete;
62 $error = $record->check;
66 An FS::cust_credit object represents a credit; the equivalent of a negative
67 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
68 FS::Record. The following fields are currently supported:
74 Primary key (assigned automatically for new credits)
78 Customer (see L<FS::cust_main>)
86 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
87 L<Time::Local> and L<Date::Parse> for conversion functions.
91 Order taker (see L<FS::access_user>)
99 Reason (see L<FS::reason>)
107 Books closed flag, empty or `Y'
111 Desired pkgnum when using experimental package balances.
121 Creates a new credit. To add the credit to the database, see L<"insert">.
125 sub table { 'cust_credit'; }
126 sub cust_linked { $_[0]->cust_main_custnum; }
127 sub cust_unlinked_msg {
129 "WARNING: can't find cust_main.custnum ". $self->custnum.
130 ' (cust_credit.crednum '. $self->crednum. ')';
135 Adds this credit to the database ("Posts" the credit). If there is an error,
136 returns the error, otherwise returns false.
141 my ($self, %options) = @_;
143 local $SIG{HUP} = 'IGNORE';
144 local $SIG{INT} = 'IGNORE';
145 local $SIG{QUIT} = 'IGNORE';
146 local $SIG{TERM} = 'IGNORE';
147 local $SIG{TSTP} = 'IGNORE';
148 local $SIG{PIPE} = 'IGNORE';
150 my $oldAutoCommit = $FS::UID::AutoCommit;
151 local $FS::UID::AutoCommit = 0;
154 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
155 my $old_balance = $cust_main->balance;
157 unless ($self->reasonnum) {
158 my $result = $self->reason( $self->getfield('reason'),
159 exists($options{ 'reason_type' })
160 ? ('reason_type' => $options{ 'reason_type' })
164 $dbh->rollback if $oldAutoCommit;
165 return "failed to set reason for $me"; #: ". $dbh->errstr;
169 $self->setfield('reason', '');
171 my $error = $self->SUPER::insert;
173 $dbh->rollback if $oldAutoCommit;
174 return "error inserting $self: $error";
177 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
179 #false laziness w/ cust_pay::insert
180 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
181 my @errors = $cust_main->unsuspend;
183 # side-fx with nested transactions? upstack rolls back?
184 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
190 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
198 Unless the closed flag is set, deletes this credit and all associated
199 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
200 the void method instead to leave a record of the deleted credit.
204 # very similar to FS::cust_pay::delete
209 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
211 local $SIG{HUP} = 'IGNORE';
212 local $SIG{INT} = 'IGNORE';
213 local $SIG{QUIT} = 'IGNORE';
214 local $SIG{TERM} = 'IGNORE';
215 local $SIG{TSTP} = 'IGNORE';
216 local $SIG{PIPE} = 'IGNORE';
218 my $oldAutoCommit = $FS::UID::AutoCommit;
219 local $FS::UID::AutoCommit = 0;
222 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
223 my $error = $cust_credit_bill->delete;
225 $dbh->rollback if $oldAutoCommit;
230 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
231 my $error = $cust_credit_refund->delete;
233 $dbh->rollback if $oldAutoCommit;
238 my $error = $self->SUPER::delete(@_);
240 $dbh->rollback if $oldAutoCommit;
244 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
246 my $cust_main = $self->cust_main;
248 my $error = send_email(
249 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
250 #invoice_from??? well as good as any
251 'to' => $conf->config('deletecredits'),
252 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
254 "This is an automatic message from your Freeside installation\n",
255 "informing you that the following credit has been deleted:\n",
257 'crednum: '. $self->crednum. "\n",
258 'custnum: '. $self->custnum.
259 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
260 'amount: $'. sprintf("%.2f", $self->amount). "\n",
261 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
262 'reason: '. $self->reason. "\n",
267 $dbh->rollback if $oldAutoCommit;
268 return "can't send credit deletion notification: $error";
273 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
279 =item replace [ OLD_RECORD ]
281 You can, but probably shouldn't modify credits...
283 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
284 supplied, replaces this record. If there is an error, returns the error,
285 otherwise returns false.
291 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
292 $self->SUPER::replace(@_);
297 Checks all fields to make sure this is a valid credit. If there is an error,
298 returns the error, otherwise returns false. Called by the insert and replace
306 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
309 $self->ut_numbern('crednum')
310 || $self->ut_number('custnum')
311 || $self->ut_numbern('_date')
312 || $self->ut_money('amount')
313 || $self->ut_alphan('otaker')
314 || $self->ut_textn('reason')
315 || $self->ut_textn('addlinfo')
316 || $self->ut_enum('closed', [ '', 'Y' ])
317 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
318 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
319 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
320 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
321 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
323 return $error if $error;
325 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
326 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
327 return $error if $error;
329 return "amount must be > 0 " if $self->amount <= 0;
331 return "amount must be greater or equal to amount applied"
332 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
334 return "Unknown customer"
335 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
337 $self->_date(time) unless $self->_date;
342 =item void [ REASON ]
344 Voids this credit: deletes the credit and all associated applications and
345 adds a record of the voided credit to the cust_credit_void table.
349 # yes, false laziness with cust_pay and cust_bill
350 # but frankly I don't have time to fix it now
356 local $SIG{HUP} = 'IGNORE';
357 local $SIG{INT} = 'IGNORE';
358 local $SIG{QUIT} = 'IGNORE';
359 local $SIG{TERM} = 'IGNORE';
360 local $SIG{TSTP} = 'IGNORE';
361 local $SIG{PIPE} = 'IGNORE';
363 my $oldAutoCommit = $FS::UID::AutoCommit;
364 local $FS::UID::AutoCommit = 0;
367 my $cust_credit_void = new FS::cust_credit_void ( {
368 map { $_ => $self->get($_) } $self->fields
370 $cust_credit_void->set('void_reason', $reason);
371 my $error = $cust_credit_void->insert;
373 $dbh->rollback if $oldAutoCommit;
377 $error = $self->delete(void => 1); # suppress deletecredits warning
379 $dbh->rollback if $oldAutoCommit;
383 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
389 =item cust_credit_refund
391 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
395 sub cust_credit_refund {
397 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
398 sort { $a->_date <=> $b->_date }
399 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
403 =item cust_credit_bill
405 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
410 sub cust_credit_bill {
412 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
413 sort { $a->_date <=> $b->_date }
414 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
420 Returns the amount of this credit that is still unapplied/outstanding;
421 amount minus all refund applications (see L<FS::cust_credit_refund>) and
422 applications to invoices (see L<FS::cust_credit_bill>).
428 my $amount = $self->amount;
429 $amount -= $_->amount foreach ( $self->cust_credit_refund );
430 $amount -= $_->amount foreach ( $self->cust_credit_bill );
431 sprintf( "%.2f", $amount );
436 Deprecated name for the unapplied method.
442 #carp "cust_credit->credited deprecated; use ->unapplied";
443 $self->unapplied(@_);
448 Returns the customer (see L<FS::cust_main>) for this credit.
454 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
460 Returns the text of the associated reason (see L<FS::reason>) for this credit.
465 my ($self, $value, %options) = @_;
468 my $typenum = $options{'reason_type'};
470 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
471 local $FS::UID::AutoCommit = 0; # a transaction if it matters
473 if ( defined( $value ) ) {
474 my $hashref = { 'reason' => $value };
475 $hashref->{'reason_type'} = $typenum if $typenum;
476 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
477 my $extra_sql = " AND reason_type.class='R'";
479 $reason = qsearchs( { 'table' => 'reason',
480 'hashref' => $hashref,
481 'addl_from' => $addl_from,
482 'extra_sql' => $extra_sql,
485 if (!$reason && $typenum) {
486 $reason = new FS::reason( { 'reason_type' => $typenum,
490 my $error = $reason->insert;
492 warn "error inserting reason: $error\n";
497 $self->reasonnum($reason ? $reason->reasonnum : '') ;
498 warn "$me reason used in set mode with non-existant reason -- clearing"
501 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
503 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
505 ( $reason ? $reason->reason : '' ).
506 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
511 # Used by FS::Upgrade to migrate to a new database.
513 sub _upgrade_data { # class method
514 my ($class, %opts) = @_;
516 warn "$me upgrading $class\n" if $DEBUG;
518 if (defined dbdef->table($class->table)->column('reason')) {
520 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
522 my @cust_credits = qsearch({ 'table' => $class->table,
524 'extra_sql' => 'WHERE reason IS NOT NULL',
527 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
528 warn "$me Found unmigrated reasons\n" if $DEBUG;
529 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
530 my $reason_type = qsearchs( 'reason_type', $hashref );
531 unless ($reason_type) {
532 $reason_type = new FS::reason_type( $hashref );
533 my $error = $reason_type->insert();
534 die "$class had error inserting FS::reason_type into database: $error\n"
538 $hashref = { 'reason_type' => $reason_type->typenum,
541 my $noreason = qsearchs( 'reason', $hashref );
543 $hashref->{'disabled'} = 'Y';
544 $noreason = new FS::reason( $hashref );
545 my $error = $noreason->insert();
546 die "can't insert legacy reason '(none)' into database: $error\n"
550 foreach my $cust_credit ( @cust_credits ) {
551 my $reason = $cust_credit->getfield('reason');
552 warn "Contemplating reason $reason\n" if $DEBUG > 1;
553 if ($reason =~ /\S/) {
554 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
555 or die "can't insert legacy reason $reason into database\n";
557 $cust_credit->reasonnum($noreason->reasonnum);
560 $cust_credit->setfield('reason', '');
561 my $error = $cust_credit->replace;
563 warn "*** WARNING: error replacing reason in $class ".
564 $cust_credit->crednum. ": $error ***\n"
569 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
571 foreach ( keys %reasontype_map ) {
572 unless ($conf->config($_)) { # hmmmm
573 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
574 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
575 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
576 my $reason_type = qsearchs( 'reason_type', $hashref );
577 unless ($reason_type) {
578 $reason_type = new FS::reason_type( $hashref );
579 my $error = $reason_type->insert();
580 die "$class had error inserting FS::reason_type into database: $error\n"
583 $conf->set($_, $reason_type->typenum);
587 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
589 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
590 my $reason_type = qsearchs( 'reason_type', $hashref );
591 unless ($reason_type) {
592 $reason_type = new FS::reason_type( $hashref );
593 my $error = $reason_type->insert();
594 die "$class had error inserting FS::reason_type into database: $error\n"
598 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
599 foreach my $plan ( @plans ) {
600 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
601 unless ($pkg->option('reason_type', 1) ) {
602 my $plandata = $pkg->plandata.
603 "reason_type=". $reason_type->typenum. "\n";
604 $pkg->plandata($plandata);
606 $pkg->replace( undef,
607 'pkg_svc' => { map { $_->svcpart => $_->quantity }
610 'primary_svc' => $pkg->svcpart,
612 die "failed setting reason_type option: $error"
619 local($otaker_upgrade_kludge) = 1;
620 local($ignore_empty_reasonnum) = 1;
621 $class->_upgrade_otaker(%opts);
633 Returns an SQL fragment to retreive the unapplied amount.
638 my ($class, $start, $end) = @_;
640 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
641 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
642 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
643 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
647 ( SELECT SUM(amount) FROM cust_credit_refund
648 WHERE cust_credit.crednum = cust_credit_refund.crednum
649 $refund_start $refund_end )
653 ( SELECT SUM(amount) FROM cust_credit_bill
654 WHERE cust_credit.crednum = cust_credit_bill.crednum
655 $bill_start $bill_end )
664 Deprecated name for the unapplied_sql method.
671 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
673 #$class->unapplied_sql(@_);
677 =item credit_lineitems
681 my $error = FS::cust_credit->credit_lineitems(
683 #the lineitems to credit
684 'billpkgnums' => \@billpkgnums,
685 'setuprecurs' => \@setuprecurs,
686 'amounts' => \@amounts,
687 'apply' => 1, #0 leaves the credit unapplied
690 'newreasonnum' => scalar($cgi->param('newreasonnum')),
691 'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
692 map { $_ => scalar($cgi->param($_)) }
693 #fields('cust_credit')
694 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
700 #maybe i should just be an insert with extra args instead of a class method
701 use FS::cust_bill_pkg;
702 sub credit_lineitems {
703 my( $class, %arg ) = @_;
704 my $curuser = $FS::CurrentUser::CurrentUser;
706 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
708 my $cust_main = qsearchs({
709 'table' => 'cust_main',
710 'hashref' => { 'custnum' => $arg{custnum} },
711 'extra_sql' => ' AND '. $curuser->agentnums_sql,
712 }) or return 'unknown customer';
715 local $SIG{HUP} = 'IGNORE';
716 local $SIG{INT} = 'IGNORE';
717 local $SIG{QUIT} = 'IGNORE';
718 local $SIG{TERM} = 'IGNORE';
719 local $SIG{TSTP} = 'IGNORE';
720 local $SIG{PIPE} = 'IGNORE';
722 my $oldAutoCommit = $FS::UID::AutoCommit;
723 local $FS::UID::AutoCommit = 0;
726 #my @cust_bill_pkg = qsearch({
727 # 'select' => 'cust_bill_pkg.*',
728 # 'table' => 'cust_bill_pkg',
729 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
730 # ' LEFT JOIN cust_main USING (custnum) ',
731 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
732 # join( ',', @{$arg{billpkgnums}} ). ')',
733 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
737 if ($arg{reasonnum} == -1) {
739 $error = 'Enter a new reason (or select an existing one)'
740 unless $arg{newreasonnum} !~ /^\s*$/;
741 my $reason = new FS::reason {
742 'reason' => $arg{newreasonnum},
743 'reason_type' => $arg{newreasonnum_type},
745 $error ||= $reason->insert;
747 $dbh->rollback if $oldAutoCommit;
748 return "Error inserting reason: $error";
750 $arg{reasonnum} = $reason->reasonnum;
753 my $cust_credit = new FS::cust_credit ( {
754 map { $_ => $arg{$_} }
755 #fields('cust_credit')
756 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
758 $error = $cust_credit->insert;
760 $dbh->rollback if $oldAutoCommit;
761 return "Error inserting credit: $error";
764 unless ( $arg{'apply'} ) {
765 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
770 # keys in all of these are invoice numbers
771 my %cust_credit_bill = ();
772 my %cust_bill_pkg = ();
773 my %cust_credit_bill_pkg = ();
774 my %taxlisthash = ();
775 my %unapplied_payments = (); #invoice numbers, and then billpaynums
776 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
777 my $setuprecur = shift @{$arg{setuprecurs}};
778 my $amount = shift @{$arg{amounts}};
780 my $cust_bill_pkg = qsearchs({
781 'table' => 'cust_bill_pkg',
782 'hashref' => { 'billpkgnum' => $billpkgnum },
783 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
784 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
785 }) or die "unknown billpkgnum $billpkgnum";
787 my $invnum = $cust_bill_pkg->invnum;
789 if ( $setuprecur eq 'setup' ) {
790 $cust_bill_pkg->setup($amount);
791 $cust_bill_pkg->recur(0);
792 $cust_bill_pkg->unitrecur(0);
793 $cust_bill_pkg->type('');
795 $setuprecur = 'recur'; #in case its a usage classnum?
796 $cust_bill_pkg->recur($amount);
797 $cust_bill_pkg->setup(0);
798 $cust_bill_pkg->unitsetup(0);
801 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
803 #unapply any payments applied to this line item (other credits too?)
804 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
805 $error = $cust_bill_pay_pkg->delete;
807 $dbh->rollback if $oldAutoCommit;
808 return "Error unapplying payment: $error";
810 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
811 += $cust_bill_pay_pkg->amount;
814 #$subtotal += $amount;
815 $cust_credit_bill{$invnum} += $amount;
816 push @{ $cust_credit_bill_pkg{$invnum} },
817 new FS::cust_credit_bill_pkg {
818 'billpkgnum' => $cust_bill_pkg->billpkgnum,
819 'amount' => sprintf('%.2f',$amount),
820 'setuprecur' => $setuprecur,
821 'sdate' => $cust_bill_pkg->sdate,
822 'edate' => $cust_bill_pkg->edate,
825 # recalculate taxes with new amounts
826 $taxlisthash{$invnum} ||= {};
827 my $part_pkg = $cust_bill_pkg->part_pkg;
828 $cust_main->_handle_taxes( $part_pkg,
829 $taxlisthash{$invnum},
831 $cust_bill_pkg->cust_pkg,
832 $cust_bill_pkg->cust_bill->_date, #invoice time
833 $cust_bill_pkg->cust_pkg->pkgpart,
838 # now loop through %cust_credit_bill and insert those
841 # (hack to prevent cust_credit_bill_pkg insertion)
842 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
844 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
846 my $arrayref_or_error =
847 $cust_main->calculate_taxes(
848 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
849 $taxlisthash{$invnum}, # list of tax-item bindings
850 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
853 unless ( ref( $arrayref_or_error ) ) {
854 $dbh->rollback if $oldAutoCommit;
855 return "Error calculating taxes: $arrayref_or_error";
858 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
861 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
862 my $billpkgnum = $cust_bill_pkg->billpkgnum;
863 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
864 # gather up existing tax links (we need their billpkgtaxlocationnums)
865 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
866 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
868 foreach ( @tax_links ) {
869 $tax_links{$_->billpkgnum} ||= {};
870 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
874 foreach my $taxline ( @$arrayref_or_error ) {
876 my $amount = $taxline->setup;
878 # find equivalent tax line item on the existing invoice
879 my $tax_item = qsearchs('cust_bill_pkg', {
882 'itemdesc' => $taxline->desc,
885 # or should we just exit if this happens?
886 $cust_credit->set('amount',
887 sprintf('%.2f', $cust_credit->get('amount') - $amount)
889 my $error = $cust_credit->replace;
891 $dbh->rollback if $oldAutoCommit;
892 return "error correcting credit for missing tax line: $error";
896 # but in the new era, we no longer have the problem of uniquely
897 # identifying the tax_Xlocation record. The billpkgnums of the
898 # tax and the taxed item are known.
900 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
901 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
903 # the existing tax_Xlocation object
905 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_billpkgnum};
907 next if !$old_loc; # apply the leftover amount nonspecifically
909 #support partial credits: use $amount if smaller
910 # (so just distribute to the first location? perhaps should
912 my $loc_amount = min( $amount, $new_loc->amount);
914 $amount -= $loc_amount;
916 $cust_credit_bill{$invnum} += $loc_amount;
917 push @{ $cust_credit_bill_pkg{$invnum} },
918 new FS::cust_credit_bill_pkg {
919 'billpkgnum' => $tax_item->billpkgnum,
920 'amount' => $loc_amount,
921 'setuprecur' => 'setup',
922 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
923 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
926 } #foreach my $new_loc
928 # we still have to deal with the possibility that the tax links don't
929 # cover the whole amount of tax because of an incomplete upgrade...
931 $cust_credit_bill{$invnum} += $amount;
932 push @{ $cust_credit_bill_pkg{$invnum} },
933 new FS::cust_credit_bill_pkg {
934 'billpkgnum' => $tax_item->billpkgnum,
936 'setuprecur' => 'setup',
941 #unapply any payments applied to the tax
942 foreach my $cust_bill_pay_pkg
943 ( $tax_item->cust_bill_pay_pkg('setup') )
945 $error = $cust_bill_pay_pkg->delete;
947 $dbh->rollback if $oldAutoCommit;
948 return "Error unapplying payment: $error";
950 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
951 += $cust_bill_pay_pkg->amount;
955 # if we unapplied any payments from line items, also unapply that
956 # amount from the invoice
957 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
958 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
959 or die "broken payment application $billpaynum";
960 my @subapps = $cust_bill_pay->lineitem_applications;
961 $error = $cust_bill_pay->delete; # can't replace
963 my $new_cust_bill_pay = FS::cust_bill_pay->new({
964 $cust_bill_pay->hash,
966 amount => sprintf('%.2f',
967 $cust_bill_pay->amount
968 - $unapplied_payments{$invnum}{$billpaynum}),
971 if ( $new_cust_bill_pay->amount > 0 ) {
972 $error ||= $new_cust_bill_pay->insert;
973 # Also reapply it to everything it was applied to before.
974 # Note that we've already deleted cust_bill_pay_pkg records for the
975 # items we're crediting, so they aren't on this list.
976 foreach my $cust_bill_pay_pkg (@subapps) {
977 $cust_bill_pay_pkg->billpaypkgnum('');
978 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
979 $error ||= $cust_bill_pay_pkg->insert;
983 $dbh->rollback if $oldAutoCommit;
984 return "Error unapplying payment: $error";
987 #insert cust_credit_bill
989 my $cust_credit_bill = new FS::cust_credit_bill {
990 'crednum' => $cust_credit->crednum,
992 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
994 $error = $cust_credit_bill->insert;
996 $dbh->rollback if $oldAutoCommit;
997 return "Error applying credit of $cust_credit_bill{$invnum} ".
998 " to invoice $invnum: $error";
1001 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1002 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1003 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1004 $error = $cust_credit_bill_pkg->insert;
1006 $dbh->rollback if $oldAutoCommit;
1007 return "Error applying credit to line item: $error";
1013 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1022 The delete method. The replace method.
1024 B<credited> and B<credited_sql> are now called B<unapplied> and
1025 B<unapplied_sql>. The old method names should start to give warnings.
1029 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1030 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base