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',
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 || $_[0]->custnum }
128 sub cust_unlinked_msg {
130 "WARNING: can't find cust_main.custnum ". $self->custnum.
131 ' (cust_credit.crednum '. $self->crednum. ')';
134 =item insert [ OPTION => VALUE ... ]
136 Adds this credit to the database ("Posts" the credit). If there is an error,
137 returns the error, otherwise returns false.
139 Ooptions are passed as a list of keys and values. Available options:
145 L<FS::reason_type|Reason> type for newly-inserted reason
147 =item cust_credit_source_bill_pkg
150 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
151 They will have their crednum set and will be inserted along with this credit.
158 my ($self, %options) = @_;
160 local $SIG{HUP} = 'IGNORE';
161 local $SIG{INT} = 'IGNORE';
162 local $SIG{QUIT} = 'IGNORE';
163 local $SIG{TERM} = 'IGNORE';
164 local $SIG{TSTP} = 'IGNORE';
165 local $SIG{PIPE} = 'IGNORE';
167 my $oldAutoCommit = $FS::UID::AutoCommit;
168 local $FS::UID::AutoCommit = 0;
171 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
172 my $old_balance = $cust_main->balance;
174 if (!$self->reasonnum) {
175 my $reason_text = $self->get('reason')
176 or return "reason text or existing reason required";
177 my $reason_type = $options{'reason_type'}
178 or return "reason type required";
181 my $reason = FS::reason->new_or_existing(
182 reason => $reason_text,
183 type => $reason_type,
187 $dbh->rollback if $oldAutoCommit;
188 return "failed to set credit reason: $@";
190 $self->set('reasonnum', $reason->reasonnum);
193 $self->setfield('reason', '');
195 my $error = $self->SUPER::insert;
197 $dbh->rollback if $oldAutoCommit;
198 return "error inserting $self: $error";
201 if ( $options{'cust_credit_source_bill_pkg'} ) {
202 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
203 $ccsbr->crednum( $self->crednum );
204 $error = $ccsbr->insert;
206 $dbh->rollback if $oldAutoCommit;
207 return "error inserting $ccsbr: $error";
212 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
214 #false laziness w/ cust_pay::insert
215 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
216 my @errors = $cust_main->unsuspend;
218 # side-fx with nested transactions? upstack rolls back?
219 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
225 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
233 Unless the closed flag is set, deletes this credit and all associated
234 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
235 the void method instead to leave a record of the deleted credit.
239 # very similar to FS::cust_pay::delete
244 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
246 local $SIG{HUP} = 'IGNORE';
247 local $SIG{INT} = 'IGNORE';
248 local $SIG{QUIT} = 'IGNORE';
249 local $SIG{TERM} = 'IGNORE';
250 local $SIG{TSTP} = 'IGNORE';
251 local $SIG{PIPE} = 'IGNORE';
253 my $oldAutoCommit = $FS::UID::AutoCommit;
254 local $FS::UID::AutoCommit = 0;
257 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
258 my $error = $cust_credit_bill->delete;
260 $dbh->rollback if $oldAutoCommit;
265 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
266 my $error = $cust_credit_refund->delete;
268 $dbh->rollback if $oldAutoCommit;
273 my $error = $self->SUPER::delete(@_);
275 $dbh->rollback if $oldAutoCommit;
279 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
285 =item replace [ OLD_RECORD ]
287 You can, but probably shouldn't modify credits...
289 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
290 supplied, replaces this record. If there is an error, returns the error,
291 otherwise returns false.
297 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
298 $self->SUPER::replace(@_);
303 Checks all fields to make sure this is a valid credit. If there is an error,
304 returns the error, otherwise returns false. Called by the insert and replace
312 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
315 $self->ut_numbern('crednum')
316 || $self->ut_number('custnum')
317 || $self->ut_numbern('_date')
318 || $self->ut_money('amount')
319 || $self->ut_alphan('otaker')
320 || $self->ut_textn('reason')
321 || $self->ut_textn('addlinfo')
322 || $self->ut_enum('closed', [ '', 'Y' ])
323 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
324 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
325 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
326 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
327 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
329 return $error if $error;
331 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
332 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
333 return $error if $error;
335 return "amount must be > 0 " if $self->amount <= 0;
337 return "amount must be greater or equal to amount applied"
338 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
340 return "Unknown customer"
341 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
343 $self->_date(time) unless $self->_date;
348 =item void [ REASON ]
350 Voids this credit: deletes the credit and all associated applications and
351 adds a record of the voided credit to the cust_credit_void table.
359 unless (ref($reason) || !$reason) {
360 $reason = FS::reason->new_or_existing(
362 'type' => 'Void credit',
367 local $SIG{HUP} = 'IGNORE';
368 local $SIG{INT} = 'IGNORE';
369 local $SIG{QUIT} = 'IGNORE';
370 local $SIG{TERM} = 'IGNORE';
371 local $SIG{TSTP} = 'IGNORE';
372 local $SIG{PIPE} = 'IGNORE';
374 my $oldAutoCommit = $FS::UID::AutoCommit;
375 local $FS::UID::AutoCommit = 0;
378 my $cust_credit_void = new FS::cust_credit_void ( {
379 map { $_ => $self->get($_) } $self->fields
381 $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
382 my $error = $cust_credit_void->insert;
384 $dbh->rollback if $oldAutoCommit;
388 $error = $self->delete();
390 $dbh->rollback if $oldAutoCommit;
394 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
400 =item cust_credit_refund
402 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
406 sub cust_credit_refund {
408 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
409 sort { $a->_date <=> $b->_date }
410 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
414 =item cust_credit_bill
416 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
421 sub cust_credit_bill {
423 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
424 sort { $a->_date <=> $b->_date }
425 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
431 Returns the amount of this credit that is still unapplied/outstanding;
432 amount minus all refund applications (see L<FS::cust_credit_refund>) and
433 applications to invoices (see L<FS::cust_credit_bill>).
439 my $amount = $self->amount;
440 $amount -= $_->amount foreach ( $self->cust_credit_refund );
441 $amount -= $_->amount foreach ( $self->cust_credit_bill );
442 sprintf( "%.2f", $amount );
447 Deprecated name for the unapplied method.
453 #carp "cust_credit->credited deprecated; use ->unapplied";
454 $self->unapplied(@_);
459 Returns the customer (see L<FS::cust_main>) for this credit.
465 # Used by FS::Upgrade to migrate to a new database.
467 sub _upgrade_data { # class method
468 my ($class, %opts) = @_;
470 warn "$me upgrading $class\n" if $DEBUG;
472 $class->_upgrade_reasonnum(%opts);
474 if (defined dbdef->table($class->table)->column('reason')) {
476 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
478 foreach ( keys %reasontype_map ) {
479 unless ($conf->config($_)) { # hmmmm
480 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
481 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
482 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
483 my $reason_type = qsearchs( 'reason_type', $hashref );
484 unless ($reason_type) {
485 $reason_type = new FS::reason_type( $hashref );
486 my $error = $reason_type->insert();
487 die "$class had error inserting FS::reason_type into database: $error\n"
490 $conf->set($_, $reason_type->typenum);
494 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
496 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
497 my $reason_type = qsearchs( 'reason_type', $hashref );
498 unless ($reason_type) {
499 $reason_type = new FS::reason_type( $hashref );
500 my $error = $reason_type->insert();
501 die "$class had error inserting FS::reason_type into database: $error\n"
505 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
506 foreach my $plan ( @plans ) {
507 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
508 unless ($pkg->option('reason_type', 1) ) {
509 my $plandata = $pkg->plandata.
510 "reason_type=". $reason_type->typenum. "\n";
511 $pkg->plandata($plandata);
513 $pkg->replace( undef,
514 'pkg_svc' => { map { $_->svcpart => $_->quantity }
517 'primary_svc' => $pkg->svcpart,
519 die "failed setting reason_type option: $error"
526 local($otaker_upgrade_kludge) = 1;
527 local($ignore_empty_reasonnum) = 1;
528 $class->_upgrade_otaker(%opts);
530 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
531 and !$conf->config('tax_data_vendor') ) {
532 # RT#25458: fix credit line item applications that should refer to a
533 # specific tax allocation
534 my @cust_credit_bill_pkg = qsearch({
535 table => 'cust_credit_bill_pkg',
536 select => 'cust_credit_bill_pkg.*',
537 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
539 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
540 'AND cust_bill_pkg.pkgnum = 0', # is a tax
544 foreach (@cust_credit_bill_pkg) {
545 my $billpkgnum = $_->billpkgnum;
546 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
547 $credits{$billpkgnum} ||= [];
548 push @{ $credits{$billpkgnum} }, $_;
550 TAX_ITEM: foreach my $tax_item (values %tax_items) {
551 my $billpkgnum = $tax_item->billpkgnum;
552 # get all pkg/location/taxrate allocations of this tax line item
553 my @allocations = sort {$b->amount <=> $a->amount}
554 qsearch('cust_bill_pkg_tax_location', {
555 billpkgnum => $billpkgnum
557 # and these are all credit applications to it
558 my @credits = sort {$b->amount <=> $a->amount}
559 @{ $credits{$billpkgnum} };
560 my $c = shift @credits;
561 my $a = shift @allocations; # we will NOT modify these
563 if ( abs($c->amount - $a->amount) < 0.005 ) {
564 # by far the most common case: the tax line item is for a single
565 # tax, so we just fill in the billpkgtaxlocationnum
566 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
567 my $error = $c->replace;
569 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
573 $a = shift @allocations;
574 } elsif ( $c->amount > $a->amount ) {
575 # fairly common: the tax line contains tax for multiple packages
576 # (or multiple taxes) but the credit isn't divided up
577 my $new_link = FS::cust_credit_bill_pkg->new({
578 creditbillnum => $c->creditbillnum,
579 billpkgnum => $c->billpkgnum,
580 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
581 amount => $a->amount,
582 setuprecur => 'setup',
584 my $error = $new_link->insert;
586 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
589 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
590 $a = shift @allocations;
591 } elsif ( $c->amount < 0.005 ) {
592 # also fairly common; we can delete these with no harm
593 my $error = $c->delete;
594 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
596 } elsif ( $c->amount < $a->amount ) {
597 # should never happen, but if it does, handle it gracefully
598 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
599 my $error = $c->replace;
601 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
604 $a->set(amount => $a->amount - $c->amount);
609 if ( $c->amount < 0.005 ) {
610 my $error = $c->delete;
611 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
612 } elsif ( $c->modified ) {
613 # then we've allocated part of it, so reduce the nonspecific
614 # application by that much
615 my $error = $c->replace;
616 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
618 # else there are probably no allocations, i.e. this is a pre-3.x
619 # record that was never migrated over, so leave it alone
621 } # foreach $tax_item
622 FS::upgrade_journal->set_done('cust_credit__tax_link');
634 Returns an SQL fragment to retreive the unapplied amount.
639 my ($class, $start, $end) = @_;
641 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
642 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
643 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
644 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
648 ( SELECT SUM(amount) FROM cust_credit_refund
649 WHERE cust_credit.crednum = cust_credit_refund.crednum
650 $refund_start $refund_end )
654 ( SELECT SUM(amount) FROM cust_credit_bill
655 WHERE cust_credit.crednum = cust_credit_bill.crednum
656 $bill_start $bill_end )
665 Deprecated name for the unapplied_sql method.
672 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
674 #$class->unapplied_sql(@_);
678 =item calculate_tax_adjustment PARAMS
680 Calculate the amount of tax that needs to be credited as part of a lineitem
685 - billpkgnums: arrayref identifying the line items to credit
686 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
687 the lineitem charge is being credited
688 - amounts: arrayref of the amounts to credit on each line item
689 - custnum: the customer all of these invoices belong to, for error checking
691 Returns a hash containing:
692 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
693 - taxtotal: the total tax amount to be credited
694 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
695 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
696 - num: the key within that table
697 - credit: the credit amount to apply to that line
701 sub calculate_tax_adjustment {
702 my ($class, %arg) = @_;
709 my (%cust_bill_pkg, %cust_bill);
711 for (my $i = 0; ; $i++) {
712 my $billpkgnum = $arg{billpkgnums}[$i]
714 my $setuprecur = $arg{setuprecurs}[$i];
715 my $amount = $arg{amounts}[$i];
716 next if $amount == 0;
717 $subtotal += $amount;
718 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
719 ||= FS::cust_bill_pkg->by_key($billpkgnum)
720 or die "lineitem #$billpkgnum not found\n";
722 my $invnum = $cust_bill_pkg->invnum;
723 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
724 $cust_bill{ $invnum}->custnum == $arg{custnum}
725 or die "lineitem #$billpkgnum not found\n";
727 # calculate credit ratio.
728 # (First deduct any existing credits applied to this line item, to avoid
730 my $charged = $cust_bill_pkg->get($setuprecur);
731 my $previously_credited =
732 $cust_bill_pkg->credited( '', '', setuprecur => $setuprecur) || 0;
734 $charged -= $previously_credited;
735 if ($charged < $amount) {
736 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
739 my $ratio = $amount / $charged;
741 # gather taxes that apply to the selected item
743 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
745 foreach my $tax_link (
746 qsearch($table, { taxable_billpkgnum => $billpkgnum })
748 my $tax_amount = $tax_link->amount;
749 # deduct existing credits applied to the tax, for the same reason as
751 foreach ($tax_link->cust_credit_bill_pkg) {
752 $tax_amount -= $_->amount;
754 my $tax_credit = sprintf('%.2f', $tax_amount * $ratio);
755 my $pkey = $tax_link->get($tax_link->primary_key);
759 credit => $tax_credit,
761 $taxtotal += $tax_credit;
763 } #foreach cust_bill_pkg_tax_(rate_)?location
765 } # foreach $billpkgnum
768 subtotal => sprintf('%.2f', $subtotal),
769 taxtotal => sprintf('%.2f', $taxtotal),
770 taxlines => \@taxlines,
774 =item credit_lineitems
778 my $error = FS::cust_credit->credit_lineitems(
780 #the lineitems to credit
781 'billpkgnums' => \@billpkgnums,
782 'setuprecurs' => \@setuprecurs,
783 'amounts' => \@amounts,
784 'apply' => 1, #0 leaves the credit unapplied
787 map { $_ => scalar($cgi->param($_)) }
788 #fields('cust_credit')
789 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
795 #maybe i should just be an insert with extra args instead of a class method
796 sub credit_lineitems {
797 my( $class, %arg ) = @_;
798 my $curuser = $FS::CurrentUser::CurrentUser;
800 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
802 my $cust_main = qsearchs({
803 'table' => 'cust_main',
804 'hashref' => { 'custnum' => $arg{custnum} },
805 'extra_sql' => ' AND '. $curuser->agentnums_sql,
806 }) or return 'unknown customer';
809 local $SIG{HUP} = 'IGNORE';
810 local $SIG{INT} = 'IGNORE';
811 local $SIG{QUIT} = 'IGNORE';
812 local $SIG{TERM} = 'IGNORE';
813 local $SIG{TSTP} = 'IGNORE';
814 local $SIG{PIPE} = 'IGNORE';
816 my $oldAutoCommit = $FS::UID::AutoCommit;
817 local $FS::UID::AutoCommit = 0;
820 #my @cust_bill_pkg = qsearch({
821 # 'select' => 'cust_bill_pkg.*',
822 # 'table' => 'cust_bill_pkg',
823 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
824 # ' LEFT JOIN cust_main USING (custnum) ',
825 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
826 # join( ',', @{$arg{billpkgnums}} ). ')',
827 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
832 my $cust_credit = new FS::cust_credit ( {
833 map { $_ => $arg{$_} }
834 #fields('cust_credit')
835 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
837 $error = $cust_credit->insert;
839 $dbh->rollback if $oldAutoCommit;
840 return "Error inserting credit: $error";
843 unless ( $arg{'apply'} ) {
844 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
849 # keys in all of these are invoice numbers
850 my %cust_credit_bill = ();
851 my %cust_bill_pkg = ();
852 my %cust_credit_bill_pkg = ();
853 my %unapplied_payments = (); #invoice numbers, and then billpaynums
855 # determine the tax adjustments
856 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
858 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
859 my $setuprecur = shift @{$arg{setuprecurs}};
860 my $amount = shift @{$arg{amounts}};
862 my $cust_bill_pkg = qsearchs({
863 'table' => 'cust_bill_pkg',
864 'hashref' => { 'billpkgnum' => $billpkgnum },
865 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
866 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
867 }) or die "unknown billpkgnum $billpkgnum";
869 my $invnum = $cust_bill_pkg->invnum;
871 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
873 $cust_credit_bill{$invnum} += $amount;
874 push @{ $cust_credit_bill_pkg{$invnum} },
875 new FS::cust_credit_bill_pkg {
876 'billpkgnum' => $billpkgnum,
877 'amount' => sprintf('%.2f',$amount),
878 'setuprecur' => $setuprecur,
879 'sdate' => $cust_bill_pkg->sdate,
880 'edate' => $cust_bill_pkg->edate,
882 # unapply payments (but not other credits) from this line item
883 foreach my $cust_bill_pay_pkg (
884 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
886 $error = $cust_bill_pay_pkg->delete;
888 $dbh->rollback if $oldAutoCommit;
889 return "Error unapplying payment: $error";
891 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
892 += $cust_bill_pay_pkg->amount;
896 # do the same for taxes
897 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
898 my $table = $tax_credit->{table};
899 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
900 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
902 my $billpkgnum = $tax_link->billpkgnum;
903 my $cust_bill_pkg = qsearchs({
904 'table' => 'cust_bill_pkg',
905 'hashref' => { 'billpkgnum' => $billpkgnum },
906 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
907 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
908 }) or die "unknown billpkgnum $billpkgnum";
910 my $invnum = $cust_bill_pkg->invnum;
911 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
913 my $amount = $tax_credit->{credit};
914 $cust_credit_bill{$invnum} += $amount;
916 # create a credit application record to the tax line item, earmarked
917 # to the specific cust_bill_pkg_Xlocation
918 push @{ $cust_credit_bill_pkg{$invnum} },
919 new FS::cust_credit_bill_pkg {
920 'billpkgnum' => $billpkgnum,
921 'amount' => sprintf('%.2f', $amount),
922 'setuprecur' => 'setup',
923 $tax_link->primary_key, $tax_credit->{num}
925 # unapply any payments from the tax
926 foreach my $cust_bill_pay_pkg (
927 $cust_bill_pkg->cust_bill_pay_pkg('setup')
929 $error = $cust_bill_pay_pkg->delete;
931 $dbh->rollback if $oldAutoCommit;
932 return "Error unapplying payment: $error";
934 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
935 += $cust_bill_pay_pkg->amount;
940 # now loop through %cust_credit_bill and insert those
943 # (hack to prevent cust_credit_bill_pkg insertion)
944 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
946 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
948 # if we unapplied any payments from line items, also unapply that
949 # amount from the invoice
950 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
951 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
952 or die "broken payment application $billpaynum";
953 my @subapps = $cust_bill_pay->lineitem_applications;
954 $error = $cust_bill_pay->delete; # can't replace
956 my $new_cust_bill_pay = FS::cust_bill_pay->new({
957 $cust_bill_pay->hash,
959 amount => sprintf('%.2f',
960 $cust_bill_pay->amount
961 - $unapplied_payments{$invnum}{$billpaynum}),
964 if ( $new_cust_bill_pay->amount > 0 ) {
965 $error ||= $new_cust_bill_pay->insert;
966 # Also reapply it to everything it was applied to before.
967 # Note that we've already deleted cust_bill_pay_pkg records for the
968 # items we're crediting, so they aren't on this list.
969 foreach my $cust_bill_pay_pkg (@subapps) {
970 $cust_bill_pay_pkg->billpaypkgnum('');
971 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
972 $error ||= $cust_bill_pay_pkg->insert;
976 $dbh->rollback if $oldAutoCommit;
977 return "Error unapplying payment: $error";
980 #insert cust_credit_bill
982 my $cust_credit_bill = new FS::cust_credit_bill {
983 'crednum' => $cust_credit->crednum,
985 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
987 $error = $cust_credit_bill->insert;
989 $dbh->rollback if $oldAutoCommit;
990 return "Error applying credit of $cust_credit_bill{$invnum} ".
991 " to invoice $invnum: $error";
994 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
995 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
996 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
997 $error = $cust_credit_bill_pkg->insert;
999 $dbh->rollback if $oldAutoCommit;
1000 return "Error applying credit to line item: $error";
1006 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1017 =item process_batch_import
1021 use List::Util qw( min );
1023 use FS::cust_credit_bill;
1024 sub process_batch_import {
1027 my $opt = { 'table' => 'cust_credit',
1028 'params' => [ '_date', 'credbatch' ],
1029 'formats' => { 'simple' =>
1030 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1033 'postinsert_callback' => sub {
1034 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1036 if ( $cust_credit->invnum ) {
1038 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1039 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1041 my $cust_credit_bill = new FS::cust_credit_bill ( {
1042 'crednum' => $cust_credit->crednum,
1043 'invnum' => $cust_bill->invnum,
1044 'amount' => $amount,
1046 my $error = $cust_credit_bill->insert;
1047 return '' unless $error;
1051 #apply_payments_and_credits ?
1052 $cust_credit->cust_main->apply_credits;
1059 FS::Record::process_batch_import( $job, $opt, @_ );
1067 The delete method. The replace method.
1069 B<credited> and B<credited_sql> are now called B<unapplied> and
1070 B<unapplied_sql>. The old method names should start to give warnings.
1074 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1075 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base