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;
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 {
37 $unsuspendauto = $conf->exists('unsuspendauto');
41 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
42 'cancel_credit_type' => 'Cancellation Credit',
43 'signup_credit_type' => 'Self-Service Credit',
48 FS::cust_credit - Object methods for cust_credit records
54 $record = new FS::cust_credit \%hash;
55 $record = new FS::cust_credit { 'column' => 'value' };
57 $error = $record->insert;
59 $error = $new_record->replace($old_record);
61 $error = $record->delete;
63 $error = $record->check;
67 An FS::cust_credit object represents a credit; the equivalent of a negative
68 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
69 FS::Record. The following fields are currently supported:
75 Primary key (assigned automatically for new credits)
79 Customer (see L<FS::cust_main>)
87 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
88 L<Time::Local> and L<Date::Parse> for conversion functions.
92 Order taker (see L<FS::access_user>)
100 Reason (see L<FS::reason>)
108 Books closed flag, empty or `Y'
112 Desired pkgnum when using experimental package balances.
122 Creates a new credit. To add the credit to the database, see L<"insert">.
126 sub table { 'cust_credit'; }
127 sub cust_linked { $_[0]->cust_main_custnum; }
128 sub cust_unlinked_msg {
130 "WARNING: can't find cust_main.custnum ". $self->custnum.
131 ' (cust_credit.crednum '. $self->crednum. ')';
136 Adds this credit to the database ("Posts" the credit). If there is an error,
137 returns the error, otherwise returns false.
142 my ($self, %options) = @_;
144 local $SIG{HUP} = 'IGNORE';
145 local $SIG{INT} = 'IGNORE';
146 local $SIG{QUIT} = 'IGNORE';
147 local $SIG{TERM} = 'IGNORE';
148 local $SIG{TSTP} = 'IGNORE';
149 local $SIG{PIPE} = 'IGNORE';
151 my $oldAutoCommit = $FS::UID::AutoCommit;
152 local $FS::UID::AutoCommit = 0;
155 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
156 my $old_balance = $cust_main->balance;
158 unless ($self->reasonnum) {
159 my $result = $self->reason( $self->getfield('reason'),
160 exists($options{ 'reason_type' })
161 ? ('reason_type' => $options{ 'reason_type' })
165 $dbh->rollback if $oldAutoCommit;
166 return "failed to set reason for $me"; #: ". $dbh->errstr;
170 $self->setfield('reason', '');
172 my $error = $self->SUPER::insert;
174 $dbh->rollback if $oldAutoCommit;
175 return "error inserting $self: $error";
178 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
180 #false laziness w/ cust_pay::insert
181 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
182 my @errors = $cust_main->unsuspend;
184 # side-fx with nested transactions? upstack rolls back?
185 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
191 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
199 Unless the closed flag is set, deletes this credit and all associated
200 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
201 the void method instead to leave a record of the deleted credit.
205 # very similar to FS::cust_pay::delete
210 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
212 local $SIG{HUP} = 'IGNORE';
213 local $SIG{INT} = 'IGNORE';
214 local $SIG{QUIT} = 'IGNORE';
215 local $SIG{TERM} = 'IGNORE';
216 local $SIG{TSTP} = 'IGNORE';
217 local $SIG{PIPE} = 'IGNORE';
219 my $oldAutoCommit = $FS::UID::AutoCommit;
220 local $FS::UID::AutoCommit = 0;
223 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
224 my $error = $cust_credit_bill->delete;
226 $dbh->rollback if $oldAutoCommit;
231 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
232 my $error = $cust_credit_refund->delete;
234 $dbh->rollback if $oldAutoCommit;
239 my $error = $self->SUPER::delete(@_);
241 $dbh->rollback if $oldAutoCommit;
245 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
247 my $cust_main = $self->cust_main;
249 my $error = send_email(
250 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
251 #invoice_from??? well as good as any
252 'to' => $conf->config('deletecredits'),
253 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
255 "This is an automatic message from your Freeside installation\n",
256 "informing you that the following credit has been deleted:\n",
258 'crednum: '. $self->crednum. "\n",
259 'custnum: '. $self->custnum.
260 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
261 'amount: $'. sprintf("%.2f", $self->amount). "\n",
262 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
263 'reason: '. $self->reason. "\n",
268 $dbh->rollback if $oldAutoCommit;
269 return "can't send credit deletion notification: $error";
274 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280 =item replace [ OLD_RECORD ]
282 You can, but probably shouldn't modify credits...
284 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
285 supplied, replaces this record. If there is an error, returns the error,
286 otherwise returns false.
292 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
293 $self->SUPER::replace(@_);
298 Checks all fields to make sure this is a valid credit. If there is an error,
299 returns the error, otherwise returns false. Called by the insert and replace
307 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
310 $self->ut_numbern('crednum')
311 || $self->ut_number('custnum')
312 || $self->ut_numbern('_date')
313 || $self->ut_money('amount')
314 || $self->ut_alphan('otaker')
315 || $self->ut_textn('reason')
316 || $self->ut_textn('addlinfo')
317 || $self->ut_enum('closed', [ '', 'Y' ])
318 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
319 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
320 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
321 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
322 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
324 return $error if $error;
326 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
327 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
328 return $error if $error;
330 return "amount must be > 0 " if $self->amount <= 0;
332 return "amount must be greater or equal to amount applied"
333 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
335 return "Unknown customer"
336 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
338 $self->_date(time) unless $self->_date;
343 =item void [ REASON ]
345 Voids this credit: deletes the credit and all associated applications and
346 adds a record of the voided credit to the cust_credit_void table.
350 # yes, false laziness with cust_pay and cust_bill
351 # but frankly I don't have time to fix it now
357 local $SIG{HUP} = 'IGNORE';
358 local $SIG{INT} = 'IGNORE';
359 local $SIG{QUIT} = 'IGNORE';
360 local $SIG{TERM} = 'IGNORE';
361 local $SIG{TSTP} = 'IGNORE';
362 local $SIG{PIPE} = 'IGNORE';
364 my $oldAutoCommit = $FS::UID::AutoCommit;
365 local $FS::UID::AutoCommit = 0;
368 my $cust_credit_void = new FS::cust_credit_void ( {
369 map { $_ => $self->get($_) } $self->fields
371 $cust_credit_void->set('void_reason', $reason);
372 my $error = $cust_credit_void->insert;
374 $dbh->rollback if $oldAutoCommit;
378 $error = $self->delete(void => 1); # suppress deletecredits warning
380 $dbh->rollback if $oldAutoCommit;
384 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
390 =item cust_credit_refund
392 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
396 sub cust_credit_refund {
398 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
399 sort { $a->_date <=> $b->_date }
400 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
404 =item cust_credit_bill
406 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
411 sub cust_credit_bill {
413 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
414 sort { $a->_date <=> $b->_date }
415 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
421 Returns the amount of this credit that is still unapplied/outstanding;
422 amount minus all refund applications (see L<FS::cust_credit_refund>) and
423 applications to invoices (see L<FS::cust_credit_bill>).
429 my $amount = $self->amount;
430 $amount -= $_->amount foreach ( $self->cust_credit_refund );
431 $amount -= $_->amount foreach ( $self->cust_credit_bill );
432 sprintf( "%.2f", $amount );
437 Deprecated name for the unapplied method.
443 #carp "cust_credit->credited deprecated; use ->unapplied";
444 $self->unapplied(@_);
449 Returns the customer (see L<FS::cust_main>) for this credit.
455 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
461 Returns the text of the associated reason (see L<FS::reason>) for this credit.
466 my ($self, $value, %options) = @_;
469 my $typenum = $options{'reason_type'};
471 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
472 local $FS::UID::AutoCommit = 0; # a transaction if it matters
474 if ( defined( $value ) ) {
475 my $hashref = { 'reason' => $value };
476 $hashref->{'reason_type'} = $typenum if $typenum;
477 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
478 my $extra_sql = " AND reason_type.class='R'";
480 $reason = qsearchs( { 'table' => 'reason',
481 'hashref' => $hashref,
482 'addl_from' => $addl_from,
483 'extra_sql' => $extra_sql,
486 if (!$reason && $typenum) {
487 $reason = new FS::reason( { 'reason_type' => $typenum,
491 my $error = $reason->insert;
493 warn "error inserting reason: $error\n";
498 $self->reasonnum($reason ? $reason->reasonnum : '') ;
499 warn "$me reason used in set mode with non-existant reason -- clearing"
502 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
504 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
506 ( $reason ? $reason->reason : '' ).
507 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
512 # Used by FS::Upgrade to migrate to a new database.
514 sub _upgrade_data { # class method
515 my ($class, %opts) = @_;
517 warn "$me upgrading $class\n" if $DEBUG;
519 if (defined dbdef->table($class->table)->column('reason')) {
521 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
523 my @cust_credits = qsearch({ 'table' => $class->table,
525 'extra_sql' => 'WHERE reason IS NOT NULL',
528 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
529 warn "$me Found unmigrated reasons\n" if $DEBUG;
530 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
531 my $reason_type = qsearchs( 'reason_type', $hashref );
532 unless ($reason_type) {
533 $reason_type = new FS::reason_type( $hashref );
534 my $error = $reason_type->insert();
535 die "$class had error inserting FS::reason_type into database: $error\n"
539 $hashref = { 'reason_type' => $reason_type->typenum,
542 my $noreason = qsearchs( 'reason', $hashref );
544 $hashref->{'disabled'} = 'Y';
545 $noreason = new FS::reason( $hashref );
546 my $error = $noreason->insert();
547 die "can't insert legacy reason '(none)' into database: $error\n"
551 foreach my $cust_credit ( @cust_credits ) {
552 my $reason = $cust_credit->getfield('reason');
553 warn "Contemplating reason $reason\n" if $DEBUG > 1;
554 if ($reason =~ /\S/) {
555 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
556 or die "can't insert legacy reason $reason into database\n";
558 $cust_credit->reasonnum($noreason->reasonnum);
561 $cust_credit->setfield('reason', '');
562 my $error = $cust_credit->replace;
564 warn "*** WARNING: error replacing reason in $class ".
565 $cust_credit->crednum. ": $error ***\n"
570 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
572 foreach ( keys %reasontype_map ) {
573 unless ($conf->config($_)) { # hmmmm
574 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
575 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
576 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
577 my $reason_type = qsearchs( 'reason_type', $hashref );
578 unless ($reason_type) {
579 $reason_type = new FS::reason_type( $hashref );
580 my $error = $reason_type->insert();
581 die "$class had error inserting FS::reason_type into database: $error\n"
584 $conf->set($_, $reason_type->typenum);
588 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
590 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
591 my $reason_type = qsearchs( 'reason_type', $hashref );
592 unless ($reason_type) {
593 $reason_type = new FS::reason_type( $hashref );
594 my $error = $reason_type->insert();
595 die "$class had error inserting FS::reason_type into database: $error\n"
599 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
600 foreach my $plan ( @plans ) {
601 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
602 unless ($pkg->option('reason_type', 1) ) {
603 my $plandata = $pkg->plandata.
604 "reason_type=". $reason_type->typenum. "\n";
605 $pkg->plandata($plandata);
607 $pkg->replace( undef,
608 'pkg_svc' => { map { $_->svcpart => $_->quantity }
611 'primary_svc' => $pkg->svcpart,
613 die "failed setting reason_type option: $error"
620 local($otaker_upgrade_kludge) = 1;
621 local($ignore_empty_reasonnum) = 1;
622 $class->_upgrade_otaker(%opts);
624 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
625 and !$conf->exists('enable_taxproducts') ) {
626 # RT#25458: fix credit line item applications that should refer to a
627 # specific tax allocation
628 my @cust_credit_bill_pkg = qsearch({
629 table => 'cust_credit_bill_pkg',
630 select => 'cust_credit_bill_pkg.*',
631 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
633 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
634 'AND cust_bill_pkg.pkgnum = 0', # is a tax
638 foreach (@cust_credit_bill_pkg) {
639 my $billpkgnum = $_->billpkgnum;
640 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
641 $credits{$billpkgnum} ||= [];
642 push @{ $credits{$billpkgnum} }, $_;
644 TAX_ITEM: foreach my $tax_item (values %tax_items) {
645 my $billpkgnum = $tax_item->billpkgnum;
646 # get all pkg/location/taxrate allocations of this tax line item
647 my @allocations = sort {$b->amount <=> $a->amount}
648 qsearch('cust_bill_pkg_tax_location', {
649 billpkgnum => $billpkgnum
651 # and these are all credit applications to it
652 my @credits = sort {$b->amount <=> $a->amount}
653 @{ $credits{$billpkgnum} };
654 my $c = shift @credits;
655 my $a = shift @allocations; # we will NOT modify these
657 if ( abs($c->amount - $a->amount) < 0.005 ) {
658 # by far the most common case: the tax line item is for a single
659 # tax, so we just fill in the billpkgtaxlocationnum
660 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
661 my $error = $c->replace;
663 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
667 $a = shift @allocations;
668 } elsif ( $c->amount > $a->amount ) {
669 # fairly common: the tax line contains tax for multiple packages
670 # (or multiple taxes) but the credit isn't divided up
671 my $new_link = FS::cust_credit_bill_pkg->new({
672 creditbillnum => $c->creditbillnum,
673 billpkgnum => $c->billpkgnum,
674 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
675 amount => $a->amount,
676 setuprecur => 'setup',
678 my $error = $new_link->insert;
680 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
683 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
684 $a = shift @allocations;
685 } elsif ( $c->amount < 0.005 ) {
686 # also fairly common; we can delete these with no harm
687 my $error = $c->delete;
688 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
690 } elsif ( $c->amount < $a->amount ) {
691 # should never happen, but if it does, handle it gracefully
692 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
693 my $error = $c->replace;
695 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
698 $a->set(amount => $a->amount - $c->amount);
703 if ( $c->amount < 0.005 ) {
704 my $error = $c->delete;
705 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
706 } elsif ( $c->modified ) {
707 # then we've allocated part of it, so reduce the nonspecific
708 # application by that much
709 my $error = $c->replace;
710 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
712 # else there are probably no allocations, i.e. this is a pre-3.x
713 # record that was never migrated over, so leave it alone
715 } # foreach $tax_item
716 FS::upgrade_journal->set_done('cust_credit__tax_link');
728 Returns an SQL fragment to retreive the unapplied amount.
733 my ($class, $start, $end) = @_;
735 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
736 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
737 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
738 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
742 ( SELECT SUM(amount) FROM cust_credit_refund
743 WHERE cust_credit.crednum = cust_credit_refund.crednum
744 $refund_start $refund_end )
748 ( SELECT SUM(amount) FROM cust_credit_bill
749 WHERE cust_credit.crednum = cust_credit_bill.crednum
750 $bill_start $bill_end )
759 Deprecated name for the unapplied_sql method.
766 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
768 #$class->unapplied_sql(@_);
772 =item credit_lineitems
776 my $error = FS::cust_credit->credit_lineitems(
778 #the lineitems to credit
779 'billpkgnums' => \@billpkgnums,
780 'setuprecurs' => \@setuprecurs,
781 'amounts' => \@amounts,
782 'apply' => 1, #0 leaves the credit unapplied
785 'newreasonnum' => scalar($cgi->param('newreasonnum')),
786 'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
787 map { $_ => scalar($cgi->param($_)) }
788 #fields('cust_credit')
789 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
795 #maybe i should just be an insert with extra args instead of a class method
796 use FS::cust_bill_pkg;
797 sub credit_lineitems {
798 my( $class, %arg ) = @_;
799 my $curuser = $FS::CurrentUser::CurrentUser;
801 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
803 my $cust_main = qsearchs({
804 'table' => 'cust_main',
805 'hashref' => { 'custnum' => $arg{custnum} },
806 'extra_sql' => ' AND '. $curuser->agentnums_sql,
807 }) or return 'unknown customer';
810 local $SIG{HUP} = 'IGNORE';
811 local $SIG{INT} = 'IGNORE';
812 local $SIG{QUIT} = 'IGNORE';
813 local $SIG{TERM} = 'IGNORE';
814 local $SIG{TSTP} = 'IGNORE';
815 local $SIG{PIPE} = 'IGNORE';
817 my $oldAutoCommit = $FS::UID::AutoCommit;
818 local $FS::UID::AutoCommit = 0;
821 #my @cust_bill_pkg = qsearch({
822 # 'select' => 'cust_bill_pkg.*',
823 # 'table' => 'cust_bill_pkg',
824 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
825 # ' LEFT JOIN cust_main USING (custnum) ',
826 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
827 # join( ',', @{$arg{billpkgnums}} ). ')',
828 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
832 if ($arg{reasonnum} == -1) {
834 $error = 'Enter a new reason (or select an existing one)'
835 unless $arg{newreasonnum} !~ /^\s*$/;
836 my $reason = new FS::reason {
837 'reason' => $arg{newreasonnum},
838 'reason_type' => $arg{newreasonnum_type},
840 $error ||= $reason->insert;
842 $dbh->rollback if $oldAutoCommit;
843 return "Error inserting reason: $error";
845 $arg{reasonnum} = $reason->reasonnum;
848 my $cust_credit = new FS::cust_credit ( {
849 map { $_ => $arg{$_} }
850 #fields('cust_credit')
851 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
853 $error = $cust_credit->insert;
855 $dbh->rollback if $oldAutoCommit;
856 return "Error inserting credit: $error";
859 unless ( $arg{'apply'} ) {
860 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
865 # keys in all of these are invoice numbers
866 my %cust_credit_bill = ();
867 my %cust_bill_pkg = ();
868 my %cust_credit_bill_pkg = ();
869 my %taxlisthash = ();
870 my %unapplied_payments = (); #invoice numbers, and then billpaynums
871 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
872 my $setuprecur = shift @{$arg{setuprecurs}};
873 my $amount = shift @{$arg{amounts}};
875 my $cust_bill_pkg = qsearchs({
876 'table' => 'cust_bill_pkg',
877 'hashref' => { 'billpkgnum' => $billpkgnum },
878 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
879 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
880 }) or die "unknown billpkgnum $billpkgnum";
882 my $invnum = $cust_bill_pkg->invnum;
884 if ( $setuprecur eq 'setup' ) {
885 $cust_bill_pkg->setup($amount);
886 $cust_bill_pkg->recur(0);
887 $cust_bill_pkg->unitrecur(0);
888 $cust_bill_pkg->type('');
890 $setuprecur = 'recur'; #in case its a usage classnum?
891 $cust_bill_pkg->recur($amount);
892 $cust_bill_pkg->setup(0);
893 $cust_bill_pkg->unitsetup(0);
896 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
898 #unapply any payments applied to this line item (other credits too?)
899 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
900 $error = $cust_bill_pay_pkg->delete;
902 $dbh->rollback if $oldAutoCommit;
903 return "Error unapplying payment: $error";
905 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
906 += $cust_bill_pay_pkg->amount;
909 #$subtotal += $amount;
910 $cust_credit_bill{$invnum} += $amount;
911 push @{ $cust_credit_bill_pkg{$invnum} },
912 new FS::cust_credit_bill_pkg {
913 'billpkgnum' => $cust_bill_pkg->billpkgnum,
914 'amount' => sprintf('%.2f',$amount),
915 'setuprecur' => $setuprecur,
916 'sdate' => $cust_bill_pkg->sdate,
917 'edate' => $cust_bill_pkg->edate,
920 # recalculate taxes with new amounts
921 $taxlisthash{$invnum} ||= {};
922 my $part_pkg = $cust_bill_pkg->part_pkg;
923 $cust_main->_handle_taxes( $part_pkg,
924 $taxlisthash{$invnum},
926 $cust_bill_pkg->cust_pkg,
927 $cust_bill_pkg->cust_bill->_date, #invoice time
928 $cust_bill_pkg->cust_pkg->pkgpart,
933 # now loop through %cust_credit_bill and insert those
936 # (hack to prevent cust_credit_bill_pkg insertion)
937 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
939 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
941 my $arrayref_or_error =
942 $cust_main->calculate_taxes(
943 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
944 $taxlisthash{$invnum}, # list of tax-item bindings
945 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
948 unless ( ref( $arrayref_or_error ) ) {
949 $dbh->rollback if $oldAutoCommit;
950 return "Error calculating taxes: $arrayref_or_error";
953 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
956 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
957 my $billpkgnum = $cust_bill_pkg->billpkgnum;
958 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
959 # gather up existing tax links (we need their billpkgtaxlocationnums)
960 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
961 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
963 foreach ( @tax_links ) {
964 $tax_links{$_->billpkgnum} ||= {};
965 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
969 foreach my $taxline ( @$arrayref_or_error ) {
971 my $amount = $taxline->setup;
973 # find equivalent tax line item on the existing invoice
974 my $tax_item = qsearchs('cust_bill_pkg', {
977 'itemdesc' => $taxline->desc,
980 # or should we just exit if this happens?
981 $cust_credit->set('amount',
982 sprintf('%.2f', $cust_credit->get('amount') - $amount)
984 my $error = $cust_credit->replace;
986 $dbh->rollback if $oldAutoCommit;
987 return "error correcting credit for missing tax line: $error";
991 # but in the new era, we no longer have the problem of uniquely
992 # identifying the tax_Xlocation record. The billpkgnums of the
993 # tax and the taxed item are known.
995 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
996 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
998 # the existing tax_Xlocation object
1000 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
1002 next if !$old_loc; # apply the leftover amount nonspecifically
1004 #support partial credits: use $amount if smaller
1005 # (so just distribute to the first location? perhaps should
1007 my $loc_amount = min( $amount, $new_loc->amount);
1009 $amount -= $loc_amount;
1011 $cust_credit_bill{$invnum} += $loc_amount;
1012 push @{ $cust_credit_bill_pkg{$invnum} },
1013 new FS::cust_credit_bill_pkg {
1014 'billpkgnum' => $tax_item->billpkgnum,
1015 'amount' => $loc_amount,
1016 'setuprecur' => 'setup',
1017 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
1018 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
1021 } #foreach my $new_loc
1023 # we still have to deal with the possibility that the tax links don't
1024 # cover the whole amount of tax because of an incomplete upgrade...
1026 $cust_credit_bill{$invnum} += $amount;
1027 push @{ $cust_credit_bill_pkg{$invnum} },
1028 new FS::cust_credit_bill_pkg {
1029 'billpkgnum' => $tax_item->billpkgnum,
1030 'amount' => $amount,
1031 'setuprecur' => 'setup',
1036 #unapply any payments applied to the tax
1037 foreach my $cust_bill_pay_pkg
1038 ( $tax_item->cust_bill_pay_pkg('setup') )
1040 $error = $cust_bill_pay_pkg->delete;
1042 $dbh->rollback if $oldAutoCommit;
1043 return "Error unapplying payment: $error";
1045 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
1046 += $cust_bill_pay_pkg->amount;
1050 # if we unapplied any payments from line items, also unapply that
1051 # amount from the invoice
1052 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1053 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1054 or die "broken payment application $billpaynum";
1055 my @subapps = $cust_bill_pay->lineitem_applications;
1056 $error = $cust_bill_pay->delete; # can't replace
1058 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1059 $cust_bill_pay->hash,
1061 amount => sprintf('%.2f',
1062 $cust_bill_pay->amount
1063 - $unapplied_payments{$invnum}{$billpaynum}),
1066 if ( $new_cust_bill_pay->amount > 0 ) {
1067 $error ||= $new_cust_bill_pay->insert;
1068 # Also reapply it to everything it was applied to before.
1069 # Note that we've already deleted cust_bill_pay_pkg records for the
1070 # items we're crediting, so they aren't on this list.
1071 foreach my $cust_bill_pay_pkg (@subapps) {
1072 $cust_bill_pay_pkg->billpaypkgnum('');
1073 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1074 $error ||= $cust_bill_pay_pkg->insert;
1078 $dbh->rollback if $oldAutoCommit;
1079 return "Error unapplying payment: $error";
1082 #insert cust_credit_bill
1084 my $cust_credit_bill = new FS::cust_credit_bill {
1085 'crednum' => $cust_credit->crednum,
1086 'invnum' => $invnum,
1087 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1089 $error = $cust_credit_bill->insert;
1091 $dbh->rollback if $oldAutoCommit;
1092 return "Error applying credit of $cust_credit_bill{$invnum} ".
1093 " to invoice $invnum: $error";
1096 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1097 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1098 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1099 $error = $cust_credit_bill_pkg->insert;
1101 $dbh->rollback if $oldAutoCommit;
1102 return "Error applying credit to line item: $error";
1108 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1117 The delete method. The replace method.
1119 B<credited> and B<credited_sql> are now called B<unapplied> and
1120 B<unapplied_sql>. The old method names should start to give warnings.
1124 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1125 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base