1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
6 use vars qw( $conf $unsuspendauto $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 {
37 $unsuspendauto = $conf->exists('unsuspendauto');
41 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
42 'cancel_credit_type' => 'Cancellation 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 || $_[0]->custnum }
127 sub cust_unlinked_msg {
129 "WARNING: can't find cust_main.custnum ". $self->custnum.
130 ' (cust_credit.crednum '. $self->crednum. ')';
133 =item insert [ OPTION => VALUE ... ]
135 Adds this credit to the database ("Posts" the credit). If there is an error,
136 returns the error, otherwise returns false.
138 Ooptions are passed as a list of keys and values. Available options:
144 L<FS::reason_type|Reason> type for newly-inserted reason
146 =item cust_credit_source_bill_pkg
149 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
150 They will have their crednum set and will be inserted along with this credit.
157 my ($self, %options) = @_;
159 local $SIG{HUP} = 'IGNORE';
160 local $SIG{INT} = 'IGNORE';
161 local $SIG{QUIT} = 'IGNORE';
162 local $SIG{TERM} = 'IGNORE';
163 local $SIG{TSTP} = 'IGNORE';
164 local $SIG{PIPE} = 'IGNORE';
166 my $oldAutoCommit = $FS::UID::AutoCommit;
167 local $FS::UID::AutoCommit = 0;
170 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
171 my $old_balance = $cust_main->balance;
173 if (!$self->reasonnum) {
174 my $reason_text = $self->get('reason')
175 or return "reason text or existing reason required";
176 my $reason_type = $options{'reason_type'}
177 or return "reason type required";
180 my $reason = FS::reason->new_or_existing(
181 reason => $reason_text,
182 type => $reason_type,
186 $dbh->rollback if $oldAutoCommit;
187 return "failed to set credit reason: $@";
189 $self->set('reasonnum', $reason->reasonnum);
192 $self->setfield('reason', '');
194 my $error = $self->SUPER::insert;
196 $dbh->rollback if $oldAutoCommit;
197 return "error inserting $self: $error";
200 if ( $options{'cust_credit_source_bill_pkg'} ) {
201 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
202 $ccsbr->crednum( $self->crednum );
203 $error = $ccsbr->insert;
205 $dbh->rollback if $oldAutoCommit;
206 return "error inserting $ccsbr: $error";
211 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
213 #false laziness w/ cust_pay::insert
214 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
215 my @errors = $cust_main->unsuspend;
217 # side-fx with nested transactions? upstack rolls back?
218 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
224 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
232 Unless the closed flag is set, deletes this credit and all associated
233 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
234 the void method instead to leave a record of the deleted credit.
238 # very similar to FS::cust_pay::delete
243 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
245 local $SIG{HUP} = 'IGNORE';
246 local $SIG{INT} = 'IGNORE';
247 local $SIG{QUIT} = 'IGNORE';
248 local $SIG{TERM} = 'IGNORE';
249 local $SIG{TSTP} = 'IGNORE';
250 local $SIG{PIPE} = 'IGNORE';
252 my $oldAutoCommit = $FS::UID::AutoCommit;
253 local $FS::UID::AutoCommit = 0;
256 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
257 my $error = $cust_credit_bill->delete;
259 $dbh->rollback if $oldAutoCommit;
264 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
265 my $error = $cust_credit_refund->delete;
267 $dbh->rollback if $oldAutoCommit;
272 my $error = $self->SUPER::delete(@_);
274 $dbh->rollback if $oldAutoCommit;
278 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
284 =item replace [ OLD_RECORD ]
286 You can, but probably shouldn't modify credits...
288 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
289 supplied, replaces this record. If there is an error, returns the error,
290 otherwise returns false.
296 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
297 $self->SUPER::replace(@_);
302 Checks all fields to make sure this is a valid credit. If there is an error,
303 returns the error, otherwise returns false. Called by the insert and replace
311 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
314 $self->ut_numbern('crednum')
315 || $self->ut_number('custnum')
316 || $self->ut_numbern('_date')
317 || $self->ut_money('amount')
318 || $self->ut_alphan('otaker')
319 || $self->ut_textn('reason')
320 || $self->ut_textn('addlinfo')
321 || $self->ut_enum('closed', [ '', 'Y' ])
322 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
323 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
324 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
325 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
326 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
328 return $error if $error;
330 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
331 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
332 return $error if $error;
334 return "amount must be > 0 " if $self->amount <= 0;
336 return "amount must be greater or equal to amount applied"
337 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
339 return "Unknown customer"
340 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
342 $self->_date(time) unless $self->_date;
347 =item void [ REASON ]
349 Voids this credit: deletes the credit and all associated applications and
350 adds a record of the voided credit to the cust_credit_void table.
358 unless (ref($reason) || !$reason) {
359 $reason = FS::reason->new_or_existing(
361 'type' => 'Void credit',
366 local $SIG{HUP} = 'IGNORE';
367 local $SIG{INT} = 'IGNORE';
368 local $SIG{QUIT} = 'IGNORE';
369 local $SIG{TERM} = 'IGNORE';
370 local $SIG{TSTP} = 'IGNORE';
371 local $SIG{PIPE} = 'IGNORE';
373 my $oldAutoCommit = $FS::UID::AutoCommit;
374 local $FS::UID::AutoCommit = 0;
377 my $cust_credit_void = new FS::cust_credit_void ( {
378 map { $_ => $self->get($_) } $self->fields
380 $cust_credit_void->set('void_reasonnum', $reason->reasonnum) if $reason;
381 my $error = $cust_credit_void->insert;
383 $dbh->rollback if $oldAutoCommit;
387 $error = $self->delete();
389 $dbh->rollback if $oldAutoCommit;
393 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
399 =item cust_credit_refund
401 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
405 sub cust_credit_refund {
407 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
408 sort { $a->_date <=> $b->_date }
409 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
413 =item cust_credit_bill
415 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
420 sub cust_credit_bill {
422 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
423 sort { $a->_date <=> $b->_date }
424 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
430 Returns the amount of this credit that is still unapplied/outstanding;
431 amount minus all refund applications (see L<FS::cust_credit_refund>) and
432 applications to invoices (see L<FS::cust_credit_bill>).
438 my $amount = $self->amount;
439 $amount -= $_->amount foreach ( $self->cust_credit_refund );
440 $amount -= $_->amount foreach ( $self->cust_credit_bill );
441 sprintf( "%.2f", $amount );
446 Deprecated name for the unapplied method.
452 #carp "cust_credit->credited deprecated; use ->unapplied";
453 $self->unapplied(@_);
458 Returns the customer (see L<FS::cust_main>) for this credit.
464 # Used by FS::Upgrade to migrate to a new database.
466 sub _upgrade_data { # class method
467 my ($class, %opts) = @_;
469 warn "$me upgrading $class\n" if $DEBUG;
471 $class->_upgrade_reasonnum(%opts);
473 if (defined dbdef->table($class->table)->column('reason')) {
475 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
477 foreach ( keys %reasontype_map ) {
478 unless ($conf->config($_)) { # hmmmm
479 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
480 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
481 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
482 my $reason_type = qsearchs( 'reason_type', $hashref );
483 unless ($reason_type) {
484 $reason_type = new FS::reason_type( $hashref );
485 my $error = $reason_type->insert();
486 die "$class had error inserting FS::reason_type into database: $error\n"
489 $conf->set($_, $reason_type->typenum);
493 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
495 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
496 my $reason_type = qsearchs( 'reason_type', $hashref );
497 unless ($reason_type) {
498 $reason_type = new FS::reason_type( $hashref );
499 my $error = $reason_type->insert();
500 die "$class had error inserting FS::reason_type into database: $error\n"
504 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
505 foreach my $plan ( @plans ) {
506 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
507 unless ($pkg->option('reason_type', 1) ) {
508 my $plandata = $pkg->plandata.
509 "reason_type=". $reason_type->typenum. "\n";
510 $pkg->plandata($plandata);
512 $pkg->replace( undef,
513 'pkg_svc' => { map { $_->svcpart => $_->quantity }
516 'primary_svc' => $pkg->svcpart,
518 die "failed setting reason_type option: $error"
525 local($otaker_upgrade_kludge) = 1;
526 local($ignore_empty_reasonnum) = 1;
527 $class->_upgrade_otaker(%opts);
529 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
530 and !$conf->config('tax_data_vendor') ) {
531 # RT#25458: fix credit line item applications that should refer to a
532 # specific tax allocation
533 my @cust_credit_bill_pkg = qsearch({
534 table => 'cust_credit_bill_pkg',
535 select => 'cust_credit_bill_pkg.*',
536 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
538 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
539 'AND cust_bill_pkg.pkgnum = 0', # is a tax
543 foreach (@cust_credit_bill_pkg) {
544 my $billpkgnum = $_->billpkgnum;
545 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
546 $credits{$billpkgnum} ||= [];
547 push @{ $credits{$billpkgnum} }, $_;
549 TAX_ITEM: foreach my $tax_item (values %tax_items) {
550 my $billpkgnum = $tax_item->billpkgnum;
551 # get all pkg/location/taxrate allocations of this tax line item
552 my @allocations = sort {$b->amount <=> $a->amount}
553 qsearch('cust_bill_pkg_tax_location', {
554 billpkgnum => $billpkgnum
556 # and these are all credit applications to it
557 my @credits = sort {$b->amount <=> $a->amount}
558 @{ $credits{$billpkgnum} };
559 my $c = shift @credits;
560 my $a = shift @allocations; # we will NOT modify these
562 if ( abs($c->amount - $a->amount) < 0.005 ) {
563 # by far the most common case: the tax line item is for a single
564 # tax, so we just fill in the billpkgtaxlocationnum
565 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
566 my $error = $c->replace;
568 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
572 $a = shift @allocations;
573 } elsif ( $c->amount > $a->amount ) {
574 # fairly common: the tax line contains tax for multiple packages
575 # (or multiple taxes) but the credit isn't divided up
576 my $new_link = FS::cust_credit_bill_pkg->new({
577 creditbillnum => $c->creditbillnum,
578 billpkgnum => $c->billpkgnum,
579 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
580 amount => $a->amount,
581 setuprecur => 'setup',
583 my $error = $new_link->insert;
585 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
588 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
589 $a = shift @allocations;
590 } elsif ( $c->amount < 0.005 ) {
591 # also fairly common; we can delete these with no harm
592 my $error = $c->delete;
593 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
595 } elsif ( $c->amount < $a->amount ) {
596 # should never happen, but if it does, handle it gracefully
597 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
598 my $error = $c->replace;
600 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
603 $a->set(amount => $a->amount - $c->amount);
608 if ( $c->amount < 0.005 ) {
609 my $error = $c->delete;
610 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
611 } elsif ( $c->modified ) {
612 # then we've allocated part of it, so reduce the nonspecific
613 # application by that much
614 my $error = $c->replace;
615 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
617 # else there are probably no allocations, i.e. this is a pre-3.x
618 # record that was never migrated over, so leave it alone
620 } # foreach $tax_item
621 FS::upgrade_journal->set_done('cust_credit__tax_link');
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 calculate_tax_adjustment PARAMS
679 Calculate the amount of tax that needs to be credited as part of a lineitem
684 - billpkgnums: arrayref identifying the line items to credit
685 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
686 the lineitem charge is being credited
687 - amounts: arrayref of the amounts to credit on each line item
688 - custnum: the customer all of these invoices belong to, for error checking
690 Returns a hash containing:
691 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
692 - taxtotal: the total tax amount to be credited
693 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
694 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
695 - num: the key within that table
696 - credit: the credit amount to apply to that line
700 sub calculate_tax_adjustment {
701 my ($class, %arg) = @_;
708 my (%cust_bill_pkg, %cust_bill);
710 for (my $i = 0; ; $i++) {
711 my $billpkgnum = $arg{billpkgnums}[$i]
713 my $setuprecur = $arg{setuprecurs}[$i];
714 my $amount = $arg{amounts}[$i];
715 next if $amount == 0;
716 $subtotal += $amount;
717 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
718 ||= FS::cust_bill_pkg->by_key($billpkgnum)
719 or die "lineitem #$billpkgnum not found\n";
721 my $invnum = $cust_bill_pkg->invnum;
722 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
723 $cust_bill{ $invnum}->custnum == $arg{custnum}
724 or die "lineitem #$billpkgnum not found\n";
726 # tax_Xlocation records don't distinguish setup and recur, so calculate
727 # the fraction of setup+recur (after deducting credits) that's setup. This
728 # will also be the fraction of tax (after deducting credits) that's tax on
731 $setup = $cust_bill_pkg->get('setup') || 0;
733 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
735 $recur = $cust_bill_pkg->get('recur') || 0;
737 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
739 my $setup_ratio = $setup / ($setup + $recur);
741 # Calculate the fraction of tax to credit: it's the fraction of this charge
742 # (either setup or recur) that's being credited.
743 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
744 next if $charged == 0; # shouldn't happen, but still...
746 if ($charged < $amount) {
747 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
750 my $credit_ratio = $amount / $charged;
752 # gather taxes that apply to the selected item
754 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
756 foreach my $tax_link (
757 qsearch($table, { taxable_billpkgnum => $billpkgnum })
759 my $tax_amount = $tax_link->amount;
760 # deduct existing credits applied to the tax, for the same reason as
762 foreach ($tax_link->cust_credit_bill_pkg) {
763 $tax_amount -= $_->amount;
765 # split tax amount based on setuprecur
766 # (this method ensures that, if you credit both setup and recur tax,
767 # it always equals the entire tax despite any rounding)
768 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
769 if ( $setuprecur eq 'setup' ) {
770 $tax_amount = $setup_tax;
772 $tax_amount = $tax_amount - $setup_tax;
774 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
775 my $pkey = $tax_link->get($tax_link->primary_key);
779 credit => $tax_credit,
781 $taxtotal += $tax_credit;
783 } #foreach cust_bill_pkg_tax_(rate_)?location
785 } # foreach $billpkgnum
788 subtotal => sprintf('%.2f', $subtotal),
789 taxtotal => sprintf('%.2f', $taxtotal),
790 taxlines => \@taxlines,
794 =item credit_lineitems
798 my $error = FS::cust_credit->credit_lineitems(
800 #the lineitems to credit
801 'billpkgnums' => \@billpkgnums,
802 'setuprecurs' => \@setuprecurs,
803 'amounts' => \@amounts,
804 'apply' => 1, #0 leaves the credit unapplied
807 map { $_ => scalar($cgi->param($_)) }
808 #fields('cust_credit')
809 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
815 #maybe i should just be an insert with extra args instead of a class method
816 sub credit_lineitems {
817 my( $class, %arg ) = @_;
818 my $curuser = $FS::CurrentUser::CurrentUser;
820 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
822 my $cust_main = qsearchs({
823 'table' => 'cust_main',
824 'hashref' => { 'custnum' => $arg{custnum} },
825 'extra_sql' => ' AND '. $curuser->agentnums_sql,
826 }) or return 'unknown customer';
829 local $SIG{HUP} = 'IGNORE';
830 local $SIG{INT} = 'IGNORE';
831 local $SIG{QUIT} = 'IGNORE';
832 local $SIG{TERM} = 'IGNORE';
833 local $SIG{TSTP} = 'IGNORE';
834 local $SIG{PIPE} = 'IGNORE';
836 my $oldAutoCommit = $FS::UID::AutoCommit;
837 local $FS::UID::AutoCommit = 0;
840 #my @cust_bill_pkg = qsearch({
841 # 'select' => 'cust_bill_pkg.*',
842 # 'table' => 'cust_bill_pkg',
843 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
844 # ' LEFT JOIN cust_main USING (custnum) ',
845 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
846 # join( ',', @{$arg{billpkgnums}} ). ')',
847 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
852 my $cust_credit = new FS::cust_credit ( {
853 map { $_ => $arg{$_} }
854 #fields('cust_credit')
855 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
857 $error = $cust_credit->insert;
859 $dbh->rollback if $oldAutoCommit;
860 return "Error inserting credit: $error";
863 unless ( $arg{'apply'} ) {
864 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
869 # keys in all of these are invoice numbers
870 my %cust_credit_bill = ();
871 my %cust_bill_pkg = ();
872 my %cust_credit_bill_pkg = ();
873 my %unapplied_payments = (); #invoice numbers, and then billpaynums
875 # determine the tax adjustments
876 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
878 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
879 my $setuprecur = shift @{$arg{setuprecurs}};
880 my $amount = shift @{$arg{amounts}};
882 my $cust_bill_pkg = qsearchs({
883 'table' => 'cust_bill_pkg',
884 'hashref' => { 'billpkgnum' => $billpkgnum },
885 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
886 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
887 }) or die "unknown billpkgnum $billpkgnum";
889 my $invnum = $cust_bill_pkg->invnum;
891 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
893 $cust_credit_bill{$invnum} += $amount;
894 push @{ $cust_credit_bill_pkg{$invnum} },
895 new FS::cust_credit_bill_pkg {
896 'billpkgnum' => $billpkgnum,
897 'amount' => sprintf('%.2f',$amount),
898 'setuprecur' => $setuprecur,
899 'sdate' => $cust_bill_pkg->sdate,
900 'edate' => $cust_bill_pkg->edate,
902 # unapply payments (but not other credits) from this line item
903 foreach my $cust_bill_pay_pkg (
904 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
906 $error = $cust_bill_pay_pkg->delete;
908 $dbh->rollback if $oldAutoCommit;
909 return "Error unapplying payment: $error";
911 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
912 += $cust_bill_pay_pkg->amount;
916 # do the same for taxes
917 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
918 my $table = $tax_credit->{table};
919 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
920 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
922 my $billpkgnum = $tax_link->billpkgnum;
923 my $cust_bill_pkg = qsearchs({
924 'table' => 'cust_bill_pkg',
925 'hashref' => { 'billpkgnum' => $billpkgnum },
926 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
927 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
928 }) or die "unknown billpkgnum $billpkgnum";
930 my $invnum = $cust_bill_pkg->invnum;
931 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
933 my $amount = $tax_credit->{credit};
934 $cust_credit_bill{$invnum} += $amount;
936 # create a credit application record to the tax line item, earmarked
937 # to the specific cust_bill_pkg_Xlocation
938 push @{ $cust_credit_bill_pkg{$invnum} },
939 new FS::cust_credit_bill_pkg {
940 'billpkgnum' => $billpkgnum,
941 'amount' => sprintf('%.2f', $amount),
942 'setuprecur' => 'setup',
943 $tax_link->primary_key, $tax_credit->{num}
945 # unapply any payments from the tax
946 foreach my $cust_bill_pay_pkg (
947 $cust_bill_pkg->cust_bill_pay_pkg('setup')
949 $error = $cust_bill_pay_pkg->delete;
951 $dbh->rollback if $oldAutoCommit;
952 return "Error unapplying payment: $error";
954 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
955 += $cust_bill_pay_pkg->amount;
960 # now loop through %cust_credit_bill and insert those
963 # (hack to prevent cust_credit_bill_pkg insertion)
964 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
966 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
968 # if we unapplied any payments from line items, also unapply that
969 # amount from the invoice
970 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
971 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
972 or die "broken payment application $billpaynum";
973 my @subapps = $cust_bill_pay->lineitem_applications;
974 $error = $cust_bill_pay->delete; # can't replace
976 my $new_cust_bill_pay = FS::cust_bill_pay->new({
977 $cust_bill_pay->hash,
979 amount => sprintf('%.2f',
980 $cust_bill_pay->amount
981 - $unapplied_payments{$invnum}{$billpaynum}),
984 if ( $new_cust_bill_pay->amount > 0 ) {
985 $error ||= $new_cust_bill_pay->insert;
986 # Also reapply it to everything it was applied to before.
987 # Note that we've already deleted cust_bill_pay_pkg records for the
988 # items we're crediting, so they aren't on this list.
989 foreach my $cust_bill_pay_pkg (@subapps) {
990 $cust_bill_pay_pkg->billpaypkgnum('');
991 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
992 $error ||= $cust_bill_pay_pkg->insert;
996 $dbh->rollback if $oldAutoCommit;
997 return "Error unapplying payment: $error";
1000 #insert cust_credit_bill
1002 my $cust_credit_bill = new FS::cust_credit_bill {
1003 'crednum' => $cust_credit->crednum,
1004 'invnum' => $invnum,
1005 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1007 $error = $cust_credit_bill->insert;
1009 $dbh->rollback if $oldAutoCommit;
1010 return "Error applying credit of $cust_credit_bill{$invnum} ".
1011 " to invoice $invnum: $error";
1014 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1015 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1016 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1017 $error = $cust_credit_bill_pkg->insert;
1019 $dbh->rollback if $oldAutoCommit;
1020 return "Error applying credit to line item: $error";
1026 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1031 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1033 =item refund_to_unapply
1035 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1036 (all currently applied refunds that aren't closed.)
1037 Returns empty list if credit itself is closed.
1041 sub refund_to_unapply {
1043 return () if $self->closed;
1045 'table' => 'cust_credit_refund',
1046 'hashref' => { 'crednum' => $self->crednum },
1047 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1048 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1052 =item unapply_refund
1054 Deletes all objects returned by L</refund_to_unapply>.
1058 sub unapply_refund {
1061 local $SIG{HUP} = 'IGNORE';
1062 local $SIG{INT} = 'IGNORE';
1063 local $SIG{QUIT} = 'IGNORE';
1064 local $SIG{TERM} = 'IGNORE';
1065 local $SIG{TSTP} = 'IGNORE';
1066 local $SIG{PIPE} = 'IGNORE';
1068 my $oldAutoCommit = $FS::UID::AutoCommit;
1069 local $FS::UID::AutoCommit = 0;
1071 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1072 my $error = $cust_credit_refund->delete;
1074 dbh->rollback if $oldAutoCommit;
1079 dbh->commit or die dbh->errstr if $oldAutoCommit;
1089 =item process_batch_import
1093 use List::Util qw( min );
1095 use FS::cust_credit_bill;
1096 sub process_batch_import {
1099 my $opt = { 'table' => 'cust_credit',
1100 'params' => [ '_date', 'credbatch' ],
1101 'formats' => { 'simple' =>
1102 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1105 'postinsert_callback' => sub {
1106 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1108 if ( $cust_credit->invnum ) {
1110 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1111 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1113 my $cust_credit_bill = new FS::cust_credit_bill ( {
1114 'crednum' => $cust_credit->crednum,
1115 'invnum' => $cust_bill->invnum,
1116 'amount' => $amount,
1118 my $error = $cust_credit_bill->insert;
1119 return '' unless $error;
1123 #apply_payments_and_credits ?
1124 $cust_credit->cust_main->apply_credits;
1131 FS::Record::process_batch_import( $job, $opt, @_ );
1139 The delete method. The replace method.
1141 B<credited> and B<credited_sql> are now called B<unapplied> and
1142 B<unapplied_sql>. The old method names should start to give warnings.
1146 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1147 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base