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 # calculate credit ratio.
727 # (First deduct any existing credits applied to this line item, to avoid
729 my $charged = $cust_bill_pkg->get($setuprecur);
730 my $previously_credited =
731 $cust_bill_pkg->credited( '', '', setuprecur => $setuprecur) || 0;
733 $charged -= $previously_credited;
734 if ($charged < $amount) {
735 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
738 my $ratio = $amount / $charged;
740 # gather taxes that apply to the selected item
742 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
744 foreach my $tax_link (
745 qsearch($table, { taxable_billpkgnum => $billpkgnum })
747 my $tax_amount = $tax_link->amount;
748 # deduct existing credits applied to the tax, for the same reason as
750 foreach ($tax_link->cust_credit_bill_pkg) {
751 $tax_amount -= $_->amount;
753 my $tax_credit = sprintf('%.2f', $tax_amount * $ratio);
754 my $pkey = $tax_link->get($tax_link->primary_key);
758 credit => $tax_credit,
760 $taxtotal += $tax_credit;
762 } #foreach cust_bill_pkg_tax_(rate_)?location
764 } # foreach $billpkgnum
767 subtotal => sprintf('%.2f', $subtotal),
768 taxtotal => sprintf('%.2f', $taxtotal),
769 taxlines => \@taxlines,
773 =item credit_lineitems
777 my $error = FS::cust_credit->credit_lineitems(
779 #the lineitems to credit
780 'billpkgnums' => \@billpkgnums,
781 'setuprecurs' => \@setuprecurs,
782 'amounts' => \@amounts,
783 'apply' => 1, #0 leaves the credit unapplied
786 map { $_ => scalar($cgi->param($_)) }
787 #fields('cust_credit')
788 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
794 #maybe i should just be an insert with extra args instead of a class method
795 sub credit_lineitems {
796 my( $class, %arg ) = @_;
797 my $curuser = $FS::CurrentUser::CurrentUser;
799 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
801 my $cust_main = qsearchs({
802 'table' => 'cust_main',
803 'hashref' => { 'custnum' => $arg{custnum} },
804 'extra_sql' => ' AND '. $curuser->agentnums_sql,
805 }) or return 'unknown customer';
808 local $SIG{HUP} = 'IGNORE';
809 local $SIG{INT} = 'IGNORE';
810 local $SIG{QUIT} = 'IGNORE';
811 local $SIG{TERM} = 'IGNORE';
812 local $SIG{TSTP} = 'IGNORE';
813 local $SIG{PIPE} = 'IGNORE';
815 my $oldAutoCommit = $FS::UID::AutoCommit;
816 local $FS::UID::AutoCommit = 0;
819 #my @cust_bill_pkg = qsearch({
820 # 'select' => 'cust_bill_pkg.*',
821 # 'table' => 'cust_bill_pkg',
822 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
823 # ' LEFT JOIN cust_main USING (custnum) ',
824 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
825 # join( ',', @{$arg{billpkgnums}} ). ')',
826 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
831 my $cust_credit = new FS::cust_credit ( {
832 map { $_ => $arg{$_} }
833 #fields('cust_credit')
834 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
836 $error = $cust_credit->insert;
838 $dbh->rollback if $oldAutoCommit;
839 return "Error inserting credit: $error";
842 unless ( $arg{'apply'} ) {
843 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
848 # keys in all of these are invoice numbers
849 my %cust_credit_bill = ();
850 my %cust_bill_pkg = ();
851 my %cust_credit_bill_pkg = ();
852 my %unapplied_payments = (); #invoice numbers, and then billpaynums
854 # determine the tax adjustments
855 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
857 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
858 my $setuprecur = shift @{$arg{setuprecurs}};
859 my $amount = shift @{$arg{amounts}};
861 my $cust_bill_pkg = qsearchs({
862 'table' => 'cust_bill_pkg',
863 'hashref' => { 'billpkgnum' => $billpkgnum },
864 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
865 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
866 }) or die "unknown billpkgnum $billpkgnum";
868 my $invnum = $cust_bill_pkg->invnum;
870 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
872 $cust_credit_bill{$invnum} += $amount;
873 push @{ $cust_credit_bill_pkg{$invnum} },
874 new FS::cust_credit_bill_pkg {
875 'billpkgnum' => $billpkgnum,
876 'amount' => sprintf('%.2f',$amount),
877 'setuprecur' => $setuprecur,
878 'sdate' => $cust_bill_pkg->sdate,
879 'edate' => $cust_bill_pkg->edate,
881 # unapply payments (but not other credits) from this line item
882 foreach my $cust_bill_pay_pkg (
883 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
885 $error = $cust_bill_pay_pkg->delete;
887 $dbh->rollback if $oldAutoCommit;
888 return "Error unapplying payment: $error";
890 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
891 += $cust_bill_pay_pkg->amount;
895 # do the same for taxes
896 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
897 my $table = $tax_credit->{table};
898 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
899 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
901 my $billpkgnum = $tax_link->billpkgnum;
902 my $cust_bill_pkg = qsearchs({
903 'table' => 'cust_bill_pkg',
904 'hashref' => { 'billpkgnum' => $billpkgnum },
905 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
906 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
907 }) or die "unknown billpkgnum $billpkgnum";
909 my $invnum = $cust_bill_pkg->invnum;
910 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
912 my $amount = $tax_credit->{credit};
913 $cust_credit_bill{$invnum} += $amount;
915 # create a credit application record to the tax line item, earmarked
916 # to the specific cust_bill_pkg_Xlocation
917 push @{ $cust_credit_bill_pkg{$invnum} },
918 new FS::cust_credit_bill_pkg {
919 'billpkgnum' => $billpkgnum,
920 'amount' => sprintf('%.2f', $amount),
921 'setuprecur' => 'setup',
922 $tax_link->primary_key, $tax_credit->{num}
924 # unapply any payments from the tax
925 foreach my $cust_bill_pay_pkg (
926 $cust_bill_pkg->cust_bill_pay_pkg('setup')
928 $error = $cust_bill_pay_pkg->delete;
930 $dbh->rollback if $oldAutoCommit;
931 return "Error unapplying payment: $error";
933 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
934 += $cust_bill_pay_pkg->amount;
939 # now loop through %cust_credit_bill and insert those
942 # (hack to prevent cust_credit_bill_pkg insertion)
943 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
945 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
947 # if we unapplied any payments from line items, also unapply that
948 # amount from the invoice
949 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
950 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
951 or die "broken payment application $billpaynum";
952 my @subapps = $cust_bill_pay->lineitem_applications;
953 $error = $cust_bill_pay->delete; # can't replace
955 my $new_cust_bill_pay = FS::cust_bill_pay->new({
956 $cust_bill_pay->hash,
958 amount => sprintf('%.2f',
959 $cust_bill_pay->amount
960 - $unapplied_payments{$invnum}{$billpaynum}),
963 if ( $new_cust_bill_pay->amount > 0 ) {
964 $error ||= $new_cust_bill_pay->insert;
965 # Also reapply it to everything it was applied to before.
966 # Note that we've already deleted cust_bill_pay_pkg records for the
967 # items we're crediting, so they aren't on this list.
968 foreach my $cust_bill_pay_pkg (@subapps) {
969 $cust_bill_pay_pkg->billpaypkgnum('');
970 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
971 $error ||= $cust_bill_pay_pkg->insert;
975 $dbh->rollback if $oldAutoCommit;
976 return "Error unapplying payment: $error";
979 #insert cust_credit_bill
981 my $cust_credit_bill = new FS::cust_credit_bill {
982 'crednum' => $cust_credit->crednum,
984 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
986 $error = $cust_credit_bill->insert;
988 $dbh->rollback if $oldAutoCommit;
989 return "Error applying credit of $cust_credit_bill{$invnum} ".
990 " to invoice $invnum: $error";
993 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
994 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
995 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
996 $error = $cust_credit_bill_pkg->insert;
998 $dbh->rollback if $oldAutoCommit;
999 return "Error applying credit to line item: $error";
1005 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1016 =item process_batch_import
1020 use List::Util qw( min );
1022 use FS::cust_credit_bill;
1023 sub process_batch_import {
1026 my $opt = { 'table' => 'cust_credit',
1027 'params' => [ '_date', 'credbatch' ],
1028 'formats' => { 'simple' =>
1029 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1032 'postinsert_callback' => sub {
1033 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1035 if ( $cust_credit->invnum ) {
1037 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1038 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1040 my $cust_credit_bill = new FS::cust_credit_bill ( {
1041 'crednum' => $cust_credit->crednum,
1042 'invnum' => $cust_bill->invnum,
1043 'amount' => $amount,
1045 my $error = $cust_credit_bill->insert;
1046 return '' unless $error;
1050 #apply_payments_and_credits ?
1051 $cust_credit->cust_main->apply_credits;
1058 FS::Record::process_batch_import( $job, $opt, @_ );
1066 The delete method. The replace method.
1068 B<credited> and B<credited_sql> are now called B<unapplied> and
1069 B<unapplied_sql>. The old method names should start to give warnings.
1073 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1074 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base