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::Misc qw(send_email);
13 use FS::Record qw( qsearch qsearchs dbdef );
17 use FS::cust_credit_bill;
24 use FS::cust_credit_void;
25 use FS::cust_bill_pkg;
26 use FS::upgrade_journal;
28 $me = '[ FS::cust_credit ]';
31 $otaker_upgrade_kludge = 0;
32 $ignore_empty_reasonnum = 0;
34 #ask FS::UID to run this stuff for us later
35 $FS::UID::callback{'FS::cust_credit'} = sub {
38 $unsuspendauto = $conf->exists('unsuspendauto');
42 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
43 'cancel_credit_type' => 'Cancellation Credit',
44 'signup_credit_type' => 'Self-Service Credit',
49 FS::cust_credit - Object methods for cust_credit records
55 $record = new FS::cust_credit \%hash;
56 $record = new FS::cust_credit { 'column' => 'value' };
58 $error = $record->insert;
60 $error = $new_record->replace($old_record);
62 $error = $record->delete;
64 $error = $record->check;
68 An FS::cust_credit object represents a credit; the equivalent of a negative
69 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
70 FS::Record. The following fields are currently supported:
76 Primary key (assigned automatically for new credits)
80 Customer (see L<FS::cust_main>)
88 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
89 L<Time::Local> and L<Date::Parse> for conversion functions.
93 Order taker (see L<FS::access_user>)
101 Reason (see L<FS::reason>)
109 Books closed flag, empty or `Y'
113 Desired pkgnum when using experimental package balances.
123 Creates a new credit. To add the credit to the database, see L<"insert">.
127 sub table { 'cust_credit'; }
128 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
129 sub cust_unlinked_msg {
131 "WARNING: can't find cust_main.custnum ". $self->custnum.
132 ' (cust_credit.crednum '. $self->crednum. ')';
137 Adds this credit to the database ("Posts" the credit). If there is an error,
138 returns the error, otherwise returns false.
143 my ($self, %options) = @_;
145 local $SIG{HUP} = 'IGNORE';
146 local $SIG{INT} = 'IGNORE';
147 local $SIG{QUIT} = 'IGNORE';
148 local $SIG{TERM} = 'IGNORE';
149 local $SIG{TSTP} = 'IGNORE';
150 local $SIG{PIPE} = 'IGNORE';
152 my $oldAutoCommit = $FS::UID::AutoCommit;
153 local $FS::UID::AutoCommit = 0;
156 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
157 my $old_balance = $cust_main->balance;
159 unless ($self->reasonnum) {
160 my $result = $self->reason( $self->getfield('reason'),
161 exists($options{ 'reason_type' })
162 ? ('reason_type' => $options{ 'reason_type' })
166 $dbh->rollback if $oldAutoCommit;
167 return "failed to set reason for $me"; #: ". $dbh->errstr;
171 $self->setfield('reason', '');
173 my $error = $self->SUPER::insert;
175 $dbh->rollback if $oldAutoCommit;
176 return "error inserting $self: $error";
179 if ( $options{'cust_credit_source_bill_pkg'} ) {
180 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
181 $ccsbr->crednum( $self->crednum );
182 $error = $ccsbr->insert;
184 $dbh->rollback if $oldAutoCommit;
185 return "error inserting $ccsbr: $error";
190 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
192 #false laziness w/ cust_pay::insert
193 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
194 my @errors = $cust_main->unsuspend;
196 # side-fx with nested transactions? upstack rolls back?
197 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
203 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
211 Unless the closed flag is set, deletes this credit and all associated
212 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
213 the void method instead to leave a record of the deleted credit.
217 # very similar to FS::cust_pay::delete
222 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
224 local $SIG{HUP} = 'IGNORE';
225 local $SIG{INT} = 'IGNORE';
226 local $SIG{QUIT} = 'IGNORE';
227 local $SIG{TERM} = 'IGNORE';
228 local $SIG{TSTP} = 'IGNORE';
229 local $SIG{PIPE} = 'IGNORE';
231 my $oldAutoCommit = $FS::UID::AutoCommit;
232 local $FS::UID::AutoCommit = 0;
235 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
236 my $error = $cust_credit_bill->delete;
238 $dbh->rollback if $oldAutoCommit;
243 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
244 my $error = $cust_credit_refund->delete;
246 $dbh->rollback if $oldAutoCommit;
251 my $error = $self->SUPER::delete(@_);
253 $dbh->rollback if $oldAutoCommit;
257 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
259 my $cust_main = $self->cust_main;
261 my $error = send_email(
262 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
263 #invoice_from??? well as good as any
264 'to' => $conf->config('deletecredits'),
265 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
267 "This is an automatic message from your Freeside installation\n",
268 "informing you that the following credit has been deleted:\n",
270 'crednum: '. $self->crednum. "\n",
271 'custnum: '. $self->custnum.
272 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
273 'amount: $'. sprintf("%.2f", $self->amount). "\n",
274 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
275 'reason: '. $self->reason. "\n",
280 $dbh->rollback if $oldAutoCommit;
281 return "can't send credit deletion notification: $error";
286 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
292 =item replace [ OLD_RECORD ]
294 You can, but probably shouldn't modify credits...
296 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
297 supplied, replaces this record. If there is an error, returns the error,
298 otherwise returns false.
304 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
305 $self->SUPER::replace(@_);
310 Checks all fields to make sure this is a valid credit. If there is an error,
311 returns the error, otherwise returns false. Called by the insert and replace
319 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
322 $self->ut_numbern('crednum')
323 || $self->ut_number('custnum')
324 || $self->ut_numbern('_date')
325 || $self->ut_money('amount')
326 || $self->ut_alphan('otaker')
327 || $self->ut_textn('reason')
328 || $self->ut_textn('addlinfo')
329 || $self->ut_enum('closed', [ '', 'Y' ])
330 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
331 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
332 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
333 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
334 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
336 return $error if $error;
338 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
339 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
340 return $error if $error;
342 return "amount must be > 0 " if $self->amount <= 0;
344 return "amount must be greater or equal to amount applied"
345 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
347 return "Unknown customer"
348 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
350 $self->_date(time) unless $self->_date;
355 =item void [ REASON ]
357 Voids this credit: deletes the credit and all associated applications and
358 adds a record of the voided credit to the cust_credit_void table.
362 # yes, false laziness with cust_pay and cust_bill
363 # but frankly I don't have time to fix it now
369 local $SIG{HUP} = 'IGNORE';
370 local $SIG{INT} = 'IGNORE';
371 local $SIG{QUIT} = 'IGNORE';
372 local $SIG{TERM} = 'IGNORE';
373 local $SIG{TSTP} = 'IGNORE';
374 local $SIG{PIPE} = 'IGNORE';
376 my $oldAutoCommit = $FS::UID::AutoCommit;
377 local $FS::UID::AutoCommit = 0;
380 my $cust_credit_void = new FS::cust_credit_void ( {
381 map { $_ => $self->get($_) } $self->fields
383 $cust_credit_void->set('void_reason', $reason);
384 my $error = $cust_credit_void->insert;
386 $dbh->rollback if $oldAutoCommit;
390 $error = $self->delete(void => 1); # suppress deletecredits warning
392 $dbh->rollback if $oldAutoCommit;
396 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
402 =item cust_credit_refund
404 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
408 sub cust_credit_refund {
410 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
411 sort { $a->_date <=> $b->_date }
412 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
416 =item cust_credit_bill
418 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
423 sub cust_credit_bill {
425 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
426 sort { $a->_date <=> $b->_date }
427 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
433 Returns the amount of this credit that is still unapplied/outstanding;
434 amount minus all refund applications (see L<FS::cust_credit_refund>) and
435 applications to invoices (see L<FS::cust_credit_bill>).
441 my $amount = $self->amount;
442 $amount -= $_->amount foreach ( $self->cust_credit_refund );
443 $amount -= $_->amount foreach ( $self->cust_credit_bill );
444 sprintf( "%.2f", $amount );
449 Deprecated name for the unapplied method.
455 #carp "cust_credit->credited deprecated; use ->unapplied";
456 $self->unapplied(@_);
461 Returns the customer (see L<FS::cust_main>) for this credit.
467 # Used by FS::Upgrade to migrate to a new database.
469 sub _upgrade_data { # class method
470 my ($class, %opts) = @_;
472 warn "$me upgrading $class\n" if $DEBUG;
474 $class->_upgrade_reasonnum(%opts);
476 if (defined dbdef->table($class->table)->column('reason')) {
478 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
480 foreach ( keys %reasontype_map ) {
481 unless ($conf->config($_)) { # hmmmm
482 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
483 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
484 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
485 my $reason_type = qsearchs( 'reason_type', $hashref );
486 unless ($reason_type) {
487 $reason_type = new FS::reason_type( $hashref );
488 my $error = $reason_type->insert();
489 die "$class had error inserting FS::reason_type into database: $error\n"
492 $conf->set($_, $reason_type->typenum);
496 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
498 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
499 my $reason_type = qsearchs( 'reason_type', $hashref );
500 unless ($reason_type) {
501 $reason_type = new FS::reason_type( $hashref );
502 my $error = $reason_type->insert();
503 die "$class had error inserting FS::reason_type into database: $error\n"
507 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
508 foreach my $plan ( @plans ) {
509 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
510 unless ($pkg->option('reason_type', 1) ) {
511 my $plandata = $pkg->plandata.
512 "reason_type=". $reason_type->typenum. "\n";
513 $pkg->plandata($plandata);
515 $pkg->replace( undef,
516 'pkg_svc' => { map { $_->svcpart => $_->quantity }
519 'primary_svc' => $pkg->svcpart,
521 die "failed setting reason_type option: $error"
528 local($otaker_upgrade_kludge) = 1;
529 local($ignore_empty_reasonnum) = 1;
530 $class->_upgrade_otaker(%opts);
532 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
533 and !$conf->exists('enable_taxproducts') ) {
534 # RT#25458: fix credit line item applications that should refer to a
535 # specific tax allocation
536 my @cust_credit_bill_pkg = qsearch({
537 table => 'cust_credit_bill_pkg',
538 select => 'cust_credit_bill_pkg.*',
539 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
541 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
542 'AND cust_bill_pkg.pkgnum = 0', # is a tax
546 foreach (@cust_credit_bill_pkg) {
547 my $billpkgnum = $_->billpkgnum;
548 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
549 $credits{$billpkgnum} ||= [];
550 push @{ $credits{$billpkgnum} }, $_;
552 TAX_ITEM: foreach my $tax_item (values %tax_items) {
553 my $billpkgnum = $tax_item->billpkgnum;
554 # get all pkg/location/taxrate allocations of this tax line item
555 my @allocations = sort {$b->amount <=> $a->amount}
556 qsearch('cust_bill_pkg_tax_location', {
557 billpkgnum => $billpkgnum
559 # and these are all credit applications to it
560 my @credits = sort {$b->amount <=> $a->amount}
561 @{ $credits{$billpkgnum} };
562 my $c = shift @credits;
563 my $a = shift @allocations; # we will NOT modify these
565 if ( abs($c->amount - $a->amount) < 0.005 ) {
566 # by far the most common case: the tax line item is for a single
567 # tax, so we just fill in the billpkgtaxlocationnum
568 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
569 my $error = $c->replace;
571 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
575 $a = shift @allocations;
576 } elsif ( $c->amount > $a->amount ) {
577 # fairly common: the tax line contains tax for multiple packages
578 # (or multiple taxes) but the credit isn't divided up
579 my $new_link = FS::cust_credit_bill_pkg->new({
580 creditbillnum => $c->creditbillnum,
581 billpkgnum => $c->billpkgnum,
582 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
583 amount => $a->amount,
584 setuprecur => 'setup',
586 my $error = $new_link->insert;
588 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
591 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
592 $a = shift @allocations;
593 } elsif ( $c->amount < 0.005 ) {
594 # also fairly common; we can delete these with no harm
595 my $error = $c->delete;
596 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
598 } elsif ( $c->amount < $a->amount ) {
599 # should never happen, but if it does, handle it gracefully
600 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
601 my $error = $c->replace;
603 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
606 $a->set(amount => $a->amount - $c->amount);
611 if ( $c->amount < 0.005 ) {
612 my $error = $c->delete;
613 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
614 } elsif ( $c->modified ) {
615 # then we've allocated part of it, so reduce the nonspecific
616 # application by that much
617 my $error = $c->replace;
618 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
620 # else there are probably no allocations, i.e. this is a pre-3.x
621 # record that was never migrated over, so leave it alone
623 } # foreach $tax_item
624 FS::upgrade_journal->set_done('cust_credit__tax_link');
636 Returns an SQL fragment to retreive the unapplied amount.
641 my ($class, $start, $end) = @_;
643 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
644 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
645 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
646 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
650 ( SELECT SUM(amount) FROM cust_credit_refund
651 WHERE cust_credit.crednum = cust_credit_refund.crednum
652 $refund_start $refund_end )
656 ( SELECT SUM(amount) FROM cust_credit_bill
657 WHERE cust_credit.crednum = cust_credit_bill.crednum
658 $bill_start $bill_end )
667 Deprecated name for the unapplied_sql method.
674 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
676 #$class->unapplied_sql(@_);
680 =item credit_lineitems
684 my $error = FS::cust_credit->credit_lineitems(
686 #the lineitems to credit
687 'billpkgnums' => \@billpkgnums,
688 'setuprecurs' => \@setuprecurs,
689 'amounts' => \@amounts,
690 'apply' => 1, #0 leaves the credit unapplied
693 map { $_ => scalar($cgi->param($_)) }
694 #fields('cust_credit')
695 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
701 #maybe i should just be an insert with extra args instead of a class method
702 sub credit_lineitems {
703 my( $class, %arg ) = @_;
704 my $curuser = $FS::CurrentUser::CurrentUser;
706 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
708 my $cust_main = qsearchs({
709 'table' => 'cust_main',
710 'hashref' => { 'custnum' => $arg{custnum} },
711 'extra_sql' => ' AND '. $curuser->agentnums_sql,
712 }) or return 'unknown customer';
715 local $SIG{HUP} = 'IGNORE';
716 local $SIG{INT} = 'IGNORE';
717 local $SIG{QUIT} = 'IGNORE';
718 local $SIG{TERM} = 'IGNORE';
719 local $SIG{TSTP} = 'IGNORE';
720 local $SIG{PIPE} = 'IGNORE';
722 my $oldAutoCommit = $FS::UID::AutoCommit;
723 local $FS::UID::AutoCommit = 0;
726 #my @cust_bill_pkg = qsearch({
727 # 'select' => 'cust_bill_pkg.*',
728 # 'table' => 'cust_bill_pkg',
729 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
730 # ' LEFT JOIN cust_main USING (custnum) ',
731 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
732 # join( ',', @{$arg{billpkgnums}} ). ')',
733 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
738 my $cust_credit = new FS::cust_credit ( {
739 map { $_ => $arg{$_} }
740 #fields('cust_credit')
741 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
743 $error = $cust_credit->insert;
745 $dbh->rollback if $oldAutoCommit;
746 return "Error inserting credit: $error";
749 unless ( $arg{'apply'} ) {
750 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
755 # keys in all of these are invoice numbers
756 my %cust_credit_bill = ();
757 my %cust_bill_pkg = ();
758 my %cust_credit_bill_pkg = ();
759 my %taxlisthash = ();
760 my %unapplied_payments = (); #invoice numbers, and then billpaynums
761 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
762 my $setuprecur = shift @{$arg{setuprecurs}};
763 my $amount = shift @{$arg{amounts}};
765 my $cust_bill_pkg = qsearchs({
766 'table' => 'cust_bill_pkg',
767 'hashref' => { 'billpkgnum' => $billpkgnum },
768 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
769 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
770 }) or die "unknown billpkgnum $billpkgnum";
772 my $invnum = $cust_bill_pkg->invnum;
774 if ( $setuprecur eq 'setup' ) {
775 $cust_bill_pkg->setup($amount);
776 $cust_bill_pkg->recur(0);
777 $cust_bill_pkg->unitrecur(0);
778 $cust_bill_pkg->type('');
780 $setuprecur = 'recur'; #in case its a usage classnum?
781 $cust_bill_pkg->recur($amount);
782 $cust_bill_pkg->setup(0);
783 $cust_bill_pkg->unitsetup(0);
786 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
788 #unapply any payments applied to this line item (other credits too?)
789 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
790 $error = $cust_bill_pay_pkg->delete;
792 $dbh->rollback if $oldAutoCommit;
793 return "Error unapplying payment: $error";
795 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
796 += $cust_bill_pay_pkg->amount;
799 #$subtotal += $amount;
800 $cust_credit_bill{$invnum} += $amount;
801 push @{ $cust_credit_bill_pkg{$invnum} },
802 new FS::cust_credit_bill_pkg {
803 'billpkgnum' => $cust_bill_pkg->billpkgnum,
804 'amount' => sprintf('%.2f',$amount),
805 'setuprecur' => $setuprecur,
806 'sdate' => $cust_bill_pkg->sdate,
807 'edate' => $cust_bill_pkg->edate,
810 # recalculate taxes with new amounts
811 $taxlisthash{$invnum} ||= {};
812 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
813 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
814 } # otherwise the item itself is a tax, and assume the caller knows
819 # now loop through %cust_credit_bill and insert those
822 # (hack to prevent cust_credit_bill_pkg insertion)
823 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
825 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
827 my $arrayref_or_error =
828 $cust_main->calculate_taxes(
829 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
830 $taxlisthash{$invnum}, # list of tax-item bindings
831 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
834 unless ( ref( $arrayref_or_error ) ) {
835 $dbh->rollback if $oldAutoCommit;
836 return "Error calculating taxes: $arrayref_or_error";
839 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
842 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
843 my $billpkgnum = $cust_bill_pkg->billpkgnum;
844 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
845 # gather up existing tax links (we need their billpkgtaxlocationnums)
846 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
847 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
849 foreach ( @tax_links ) {
850 $tax_links{$_->billpkgnum} ||= {};
851 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
855 foreach my $taxline ( @$arrayref_or_error ) {
857 my $amount = $taxline->setup;
859 # find equivalent tax line item on the existing invoice
860 my $tax_item = qsearchs('cust_bill_pkg', {
863 'itemdesc' => $taxline->desc,
866 # or should we just exit if this happens?
867 $cust_credit->set('amount',
868 sprintf('%.2f', $cust_credit->get('amount') - $amount)
870 my $error = $cust_credit->replace;
872 $dbh->rollback if $oldAutoCommit;
873 return "error correcting credit for missing tax line: $error";
877 # but in the new era, we no longer have the problem of uniquely
878 # identifying the tax_Xlocation record. The billpkgnums of the
879 # tax and the taxed item are known.
881 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
882 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
884 # the existing tax_Xlocation object
886 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
888 next if !$old_loc; # apply the leftover amount nonspecifically
890 #support partial credits: use $amount if smaller
891 # (so just distribute to the first location? perhaps should
893 my $loc_amount = min( $amount, $new_loc->amount);
895 $amount -= $loc_amount;
897 $cust_credit_bill{$invnum} += $loc_amount;
898 push @{ $cust_credit_bill_pkg{$invnum} },
899 new FS::cust_credit_bill_pkg {
900 'billpkgnum' => $tax_item->billpkgnum,
901 'amount' => $loc_amount,
902 'setuprecur' => 'setup',
903 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
904 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
907 } #foreach my $new_loc
909 # we still have to deal with the possibility that the tax links don't
910 # cover the whole amount of tax because of an incomplete upgrade...
911 if ($amount > 0.005) {
912 $cust_credit_bill{$invnum} += $amount;
913 push @{ $cust_credit_bill_pkg{$invnum} },
914 new FS::cust_credit_bill_pkg {
915 'billpkgnum' => $tax_item->billpkgnum,
916 'amount' => sprintf('%.2f', $amount),
917 'setuprecur' => 'setup',
922 #unapply any payments applied to the tax
923 foreach my $cust_bill_pay_pkg
924 ( $tax_item->cust_bill_pay_pkg('setup') )
926 $error = $cust_bill_pay_pkg->delete;
928 $dbh->rollback if $oldAutoCommit;
929 return "Error unapplying payment: $error";
931 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
932 += $cust_bill_pay_pkg->amount;
936 # if we unapplied any payments from line items, also unapply that
937 # amount from the invoice
938 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
939 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
940 or die "broken payment application $billpaynum";
941 my @subapps = $cust_bill_pay->lineitem_applications;
942 $error = $cust_bill_pay->delete; # can't replace
944 my $new_cust_bill_pay = FS::cust_bill_pay->new({
945 $cust_bill_pay->hash,
947 amount => sprintf('%.2f',
948 $cust_bill_pay->amount
949 - $unapplied_payments{$invnum}{$billpaynum}),
952 if ( $new_cust_bill_pay->amount > 0 ) {
953 $error ||= $new_cust_bill_pay->insert;
954 # Also reapply it to everything it was applied to before.
955 # Note that we've already deleted cust_bill_pay_pkg records for the
956 # items we're crediting, so they aren't on this list.
957 foreach my $cust_bill_pay_pkg (@subapps) {
958 $cust_bill_pay_pkg->billpaypkgnum('');
959 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
960 $error ||= $cust_bill_pay_pkg->insert;
964 $dbh->rollback if $oldAutoCommit;
965 return "Error unapplying payment: $error";
968 #insert cust_credit_bill
970 my $cust_credit_bill = new FS::cust_credit_bill {
971 'crednum' => $cust_credit->crednum,
973 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
975 $error = $cust_credit_bill->insert;
977 $dbh->rollback if $oldAutoCommit;
978 return "Error applying credit of $cust_credit_bill{$invnum} ".
979 " to invoice $invnum: $error";
982 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
983 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
984 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
985 $error = $cust_credit_bill_pkg->insert;
987 $dbh->rollback if $oldAutoCommit;
988 return "Error applying credit to line item: $error";
994 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1005 =item process_batch_import
1009 use List::Util qw( min );
1011 use FS::cust_credit_bill;
1012 sub process_batch_import {
1015 my $opt = { 'table' => 'cust_credit',
1016 'params' => [ '_date', 'credbatch' ],
1017 'formats' => { 'simple' =>
1018 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1021 'postinsert_callback' => sub {
1022 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1024 if ( $cust_credit->invnum ) {
1026 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1027 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1029 my $cust_credit_bill = new FS::cust_credit_bill ( {
1030 'crednum' => $cust_credit->crednum,
1031 'invnum' => $cust_bill->invnum,
1032 'amount' => $amount,
1034 my $error = $cust_credit_bill->insert;
1035 return '' unless $error;
1039 #apply_payments_and_credits ?
1040 $cust_credit->cust_main->apply_credits;
1047 FS::Record::process_batch_import( $job, $opt, @_ );
1055 The delete method. The replace method.
1057 B<credited> and B<credited_sql> are now called B<unapplied> and
1058 B<unapplied_sql>. The old method names should start to give warnings.
1062 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1063 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base