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. ')';
135 =item insert [ OPTION => VALUE ... ]
137 Adds this credit to the database ("Posts" the credit). If there is an error,
138 returns the error, otherwise returns false.
140 Ooptions are passed as a list of keys and values. Available options:
146 L<FS::reason_type|Reason> type for newly-inserted reason
148 =item cust_credit_source_bill_pkg
151 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
152 They will have their crednum set and will be inserted along with this credit.
159 my ($self, %options) = @_;
161 local $SIG{HUP} = 'IGNORE';
162 local $SIG{INT} = 'IGNORE';
163 local $SIG{QUIT} = 'IGNORE';
164 local $SIG{TERM} = 'IGNORE';
165 local $SIG{TSTP} = 'IGNORE';
166 local $SIG{PIPE} = 'IGNORE';
168 my $oldAutoCommit = $FS::UID::AutoCommit;
169 local $FS::UID::AutoCommit = 0;
172 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
173 my $old_balance = $cust_main->balance;
175 unless ($self->reasonnum) {
176 my $result = $self->reason( $self->getfield('reason'),
177 exists($options{ 'reason_type' })
178 ? ('reason_type' => $options{ 'reason_type' })
182 $dbh->rollback if $oldAutoCommit;
183 return "failed to set reason for $me"; #: ". $dbh->errstr;
187 $self->setfield('reason', '');
189 my $error = $self->SUPER::insert;
191 $dbh->rollback if $oldAutoCommit;
192 return "error inserting $self: $error";
195 if ( $options{'cust_credit_source_bill_pkg'} ) {
196 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
197 $ccsbr->crednum( $self->crednum );
198 $error = $ccsbr->insert;
200 $dbh->rollback if $oldAutoCommit;
201 return "error inserting $ccsbr: $error";
206 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
208 #false laziness w/ cust_pay::insert
209 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
210 my @errors = $cust_main->unsuspend;
212 # side-fx with nested transactions? upstack rolls back?
213 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
219 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
227 Unless the closed flag is set, deletes this credit and all associated
228 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
229 the void method instead to leave a record of the deleted credit.
233 # very similar to FS::cust_pay::delete
238 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
240 local $SIG{HUP} = 'IGNORE';
241 local $SIG{INT} = 'IGNORE';
242 local $SIG{QUIT} = 'IGNORE';
243 local $SIG{TERM} = 'IGNORE';
244 local $SIG{TSTP} = 'IGNORE';
245 local $SIG{PIPE} = 'IGNORE';
247 my $oldAutoCommit = $FS::UID::AutoCommit;
248 local $FS::UID::AutoCommit = 0;
251 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
252 my $error = $cust_credit_bill->delete;
254 $dbh->rollback if $oldAutoCommit;
259 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
260 my $error = $cust_credit_refund->delete;
262 $dbh->rollback if $oldAutoCommit;
267 my $error = $self->SUPER::delete(@_);
269 $dbh->rollback if $oldAutoCommit;
273 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
275 my $cust_main = $self->cust_main;
277 my $error = send_email(
278 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
279 #invoice_from??? well as good as any
280 'to' => $conf->config('deletecredits'),
281 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
283 "This is an automatic message from your Freeside installation\n",
284 "informing you that the following credit has been deleted:\n",
286 'crednum: '. $self->crednum. "\n",
287 'custnum: '. $self->custnum.
288 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
289 'amount: $'. sprintf("%.2f", $self->amount). "\n",
290 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
291 'reason: '. $self->reason. "\n",
296 $dbh->rollback if $oldAutoCommit;
297 return "can't send credit deletion notification: $error";
302 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
308 =item replace [ OLD_RECORD ]
310 You can, but probably shouldn't modify credits...
312 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
313 supplied, replaces this record. If there is an error, returns the error,
314 otherwise returns false.
320 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
321 $self->SUPER::replace(@_);
326 Checks all fields to make sure this is a valid credit. If there is an error,
327 returns the error, otherwise returns false. Called by the insert and replace
335 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
338 $self->ut_numbern('crednum')
339 || $self->ut_number('custnum')
340 || $self->ut_numbern('_date')
341 || $self->ut_money('amount')
342 || $self->ut_alphan('otaker')
343 || $self->ut_textn('reason')
344 || $self->ut_textn('addlinfo')
345 || $self->ut_enum('closed', [ '', 'Y' ])
346 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
347 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
348 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
349 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
350 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
352 return $error if $error;
354 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
355 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
356 return $error if $error;
358 return "amount must be > 0 " if $self->amount <= 0;
360 return "amount must be greater or equal to amount applied"
361 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
363 return "Unknown customer"
364 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
366 $self->_date(time) unless $self->_date;
371 =item void [ REASON ]
373 Voids this credit: deletes the credit and all associated applications and
374 adds a record of the voided credit to the cust_credit_void table.
378 # yes, false laziness with cust_pay and cust_bill
379 # but frankly I don't have time to fix it now
385 local $SIG{HUP} = 'IGNORE';
386 local $SIG{INT} = 'IGNORE';
387 local $SIG{QUIT} = 'IGNORE';
388 local $SIG{TERM} = 'IGNORE';
389 local $SIG{TSTP} = 'IGNORE';
390 local $SIG{PIPE} = 'IGNORE';
392 my $oldAutoCommit = $FS::UID::AutoCommit;
393 local $FS::UID::AutoCommit = 0;
396 my $cust_credit_void = new FS::cust_credit_void ( {
397 map { $_ => $self->get($_) } $self->fields
399 $cust_credit_void->set('void_reason', $reason);
400 my $error = $cust_credit_void->insert;
402 $dbh->rollback if $oldAutoCommit;
406 $error = $self->delete(void => 1); # suppress deletecredits warning
408 $dbh->rollback if $oldAutoCommit;
412 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
418 =item cust_credit_refund
420 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
424 sub cust_credit_refund {
426 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
427 sort { $a->_date <=> $b->_date }
428 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
432 =item cust_credit_bill
434 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
439 sub cust_credit_bill {
441 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
442 sort { $a->_date <=> $b->_date }
443 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
449 Returns the amount of this credit that is still unapplied/outstanding;
450 amount minus all refund applications (see L<FS::cust_credit_refund>) and
451 applications to invoices (see L<FS::cust_credit_bill>).
457 my $amount = $self->amount;
458 $amount -= $_->amount foreach ( $self->cust_credit_refund );
459 $amount -= $_->amount foreach ( $self->cust_credit_bill );
460 sprintf( "%.2f", $amount );
465 Deprecated name for the unapplied method.
471 #carp "cust_credit->credited deprecated; use ->unapplied";
472 $self->unapplied(@_);
477 Returns the customer (see L<FS::cust_main>) for this credit.
483 # Used by FS::Upgrade to migrate to a new database.
485 sub _upgrade_data { # class method
486 my ($class, %opts) = @_;
488 warn "$me upgrading $class\n" if $DEBUG;
490 $class->_upgrade_reasonnum(%opts);
492 if (defined dbdef->table($class->table)->column('reason')) {
494 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
496 foreach ( keys %reasontype_map ) {
497 unless ($conf->config($_)) { # hmmmm
498 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
499 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
500 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
501 my $reason_type = qsearchs( 'reason_type', $hashref );
502 unless ($reason_type) {
503 $reason_type = new FS::reason_type( $hashref );
504 my $error = $reason_type->insert();
505 die "$class had error inserting FS::reason_type into database: $error\n"
508 $conf->set($_, $reason_type->typenum);
512 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
514 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
515 my $reason_type = qsearchs( 'reason_type', $hashref );
516 unless ($reason_type) {
517 $reason_type = new FS::reason_type( $hashref );
518 my $error = $reason_type->insert();
519 die "$class had error inserting FS::reason_type into database: $error\n"
523 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
524 foreach my $plan ( @plans ) {
525 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
526 unless ($pkg->option('reason_type', 1) ) {
527 my $plandata = $pkg->plandata.
528 "reason_type=". $reason_type->typenum. "\n";
529 $pkg->plandata($plandata);
531 $pkg->replace( undef,
532 'pkg_svc' => { map { $_->svcpart => $_->quantity }
535 'primary_svc' => $pkg->svcpart,
537 die "failed setting reason_type option: $error"
544 local($otaker_upgrade_kludge) = 1;
545 local($ignore_empty_reasonnum) = 1;
546 $class->_upgrade_otaker(%opts);
548 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
549 and !$conf->exists('enable_taxproducts') ) {
550 # RT#25458: fix credit line item applications that should refer to a
551 # specific tax allocation
552 my @cust_credit_bill_pkg = qsearch({
553 table => 'cust_credit_bill_pkg',
554 select => 'cust_credit_bill_pkg.*',
555 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
557 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
558 'AND cust_bill_pkg.pkgnum = 0', # is a tax
562 foreach (@cust_credit_bill_pkg) {
563 my $billpkgnum = $_->billpkgnum;
564 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
565 $credits{$billpkgnum} ||= [];
566 push @{ $credits{$billpkgnum} }, $_;
568 TAX_ITEM: foreach my $tax_item (values %tax_items) {
569 my $billpkgnum = $tax_item->billpkgnum;
570 # get all pkg/location/taxrate allocations of this tax line item
571 my @allocations = sort {$b->amount <=> $a->amount}
572 qsearch('cust_bill_pkg_tax_location', {
573 billpkgnum => $billpkgnum
575 # and these are all credit applications to it
576 my @credits = sort {$b->amount <=> $a->amount}
577 @{ $credits{$billpkgnum} };
578 my $c = shift @credits;
579 my $a = shift @allocations; # we will NOT modify these
581 if ( abs($c->amount - $a->amount) < 0.005 ) {
582 # by far the most common case: the tax line item is for a single
583 # tax, so we just fill in the billpkgtaxlocationnum
584 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
585 my $error = $c->replace;
587 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
591 $a = shift @allocations;
592 } elsif ( $c->amount > $a->amount ) {
593 # fairly common: the tax line contains tax for multiple packages
594 # (or multiple taxes) but the credit isn't divided up
595 my $new_link = FS::cust_credit_bill_pkg->new({
596 creditbillnum => $c->creditbillnum,
597 billpkgnum => $c->billpkgnum,
598 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
599 amount => $a->amount,
600 setuprecur => 'setup',
602 my $error = $new_link->insert;
604 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
607 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
608 $a = shift @allocations;
609 } elsif ( $c->amount < 0.005 ) {
610 # also fairly common; we can delete these with no harm
611 my $error = $c->delete;
612 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
614 } elsif ( $c->amount < $a->amount ) {
615 # should never happen, but if it does, handle it gracefully
616 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
617 my $error = $c->replace;
619 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
622 $a->set(amount => $a->amount - $c->amount);
627 if ( $c->amount < 0.005 ) {
628 my $error = $c->delete;
629 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
630 } elsif ( $c->modified ) {
631 # then we've allocated part of it, so reduce the nonspecific
632 # application by that much
633 my $error = $c->replace;
634 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
636 # else there are probably no allocations, i.e. this is a pre-3.x
637 # record that was never migrated over, so leave it alone
639 } # foreach $tax_item
640 FS::upgrade_journal->set_done('cust_credit__tax_link');
652 Returns an SQL fragment to retreive the unapplied amount.
657 my ($class, $start, $end) = @_;
659 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
660 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
661 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
662 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
666 ( SELECT SUM(amount) FROM cust_credit_refund
667 WHERE cust_credit.crednum = cust_credit_refund.crednum
668 $refund_start $refund_end )
672 ( SELECT SUM(amount) FROM cust_credit_bill
673 WHERE cust_credit.crednum = cust_credit_bill.crednum
674 $bill_start $bill_end )
683 Deprecated name for the unapplied_sql method.
690 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
692 #$class->unapplied_sql(@_);
696 =item credit_lineitems
700 my $error = FS::cust_credit->credit_lineitems(
702 #the lineitems to credit
703 'billpkgnums' => \@billpkgnums,
704 'setuprecurs' => \@setuprecurs,
705 'amounts' => \@amounts,
706 'apply' => 1, #0 leaves the credit unapplied
709 map { $_ => scalar($cgi->param($_)) }
710 #fields('cust_credit')
711 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
717 #maybe i should just be an insert with extra args instead of a class method
718 sub credit_lineitems {
719 my( $class, %arg ) = @_;
720 my $curuser = $FS::CurrentUser::CurrentUser;
722 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
724 my $cust_main = qsearchs({
725 'table' => 'cust_main',
726 'hashref' => { 'custnum' => $arg{custnum} },
727 'extra_sql' => ' AND '. $curuser->agentnums_sql,
728 }) or return 'unknown customer';
731 local $SIG{HUP} = 'IGNORE';
732 local $SIG{INT} = 'IGNORE';
733 local $SIG{QUIT} = 'IGNORE';
734 local $SIG{TERM} = 'IGNORE';
735 local $SIG{TSTP} = 'IGNORE';
736 local $SIG{PIPE} = 'IGNORE';
738 my $oldAutoCommit = $FS::UID::AutoCommit;
739 local $FS::UID::AutoCommit = 0;
742 #my @cust_bill_pkg = qsearch({
743 # 'select' => 'cust_bill_pkg.*',
744 # 'table' => 'cust_bill_pkg',
745 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
746 # ' LEFT JOIN cust_main USING (custnum) ',
747 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
748 # join( ',', @{$arg{billpkgnums}} ). ')',
749 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
754 my $cust_credit = new FS::cust_credit ( {
755 map { $_ => $arg{$_} }
756 #fields('cust_credit')
757 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
759 $error = $cust_credit->insert;
761 $dbh->rollback if $oldAutoCommit;
762 return "Error inserting credit: $error";
765 unless ( $arg{'apply'} ) {
766 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
771 # keys in all of these are invoice numbers
772 my %cust_credit_bill = ();
773 my %cust_bill_pkg = ();
774 my %cust_credit_bill_pkg = ();
775 my %taxlisthash = ();
776 my %unapplied_payments = (); #invoice numbers, and then billpaynums
777 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
778 my $setuprecur = shift @{$arg{setuprecurs}};
779 my $amount = shift @{$arg{amounts}};
781 my $cust_bill_pkg = qsearchs({
782 'table' => 'cust_bill_pkg',
783 'hashref' => { 'billpkgnum' => $billpkgnum },
784 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
785 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
786 }) or die "unknown billpkgnum $billpkgnum";
788 my $invnum = $cust_bill_pkg->invnum;
790 if ( $setuprecur eq 'setup' ) {
791 $cust_bill_pkg->setup($amount);
792 $cust_bill_pkg->recur(0);
793 $cust_bill_pkg->unitrecur(0);
794 $cust_bill_pkg->type('');
796 $setuprecur = 'recur'; #in case its a usage classnum?
797 $cust_bill_pkg->recur($amount);
798 $cust_bill_pkg->setup(0);
799 $cust_bill_pkg->unitsetup(0);
802 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
804 #unapply any payments applied to this line item (other credits too?)
805 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
806 $error = $cust_bill_pay_pkg->delete;
808 $dbh->rollback if $oldAutoCommit;
809 return "Error unapplying payment: $error";
811 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
812 += $cust_bill_pay_pkg->amount;
815 #$subtotal += $amount;
816 $cust_credit_bill{$invnum} += $amount;
817 push @{ $cust_credit_bill_pkg{$invnum} },
818 new FS::cust_credit_bill_pkg {
819 'billpkgnum' => $cust_bill_pkg->billpkgnum,
820 'amount' => sprintf('%.2f',$amount),
821 'setuprecur' => $setuprecur,
822 'sdate' => $cust_bill_pkg->sdate,
823 'edate' => $cust_bill_pkg->edate,
826 # recalculate taxes with new amounts
827 $taxlisthash{$invnum} ||= {};
828 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
829 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
830 } # otherwise the item itself is a tax, and assume the caller knows
835 # now loop through %cust_credit_bill and insert those
838 # (hack to prevent cust_credit_bill_pkg insertion)
839 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
841 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
843 my $arrayref_or_error =
844 $cust_main->calculate_taxes(
845 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
846 $taxlisthash{$invnum}, # list of tax-item bindings
847 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
850 unless ( ref( $arrayref_or_error ) ) {
851 $dbh->rollback if $oldAutoCommit;
852 return "Error calculating taxes: $arrayref_or_error";
855 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
858 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
859 my $billpkgnum = $cust_bill_pkg->billpkgnum;
860 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
861 # gather up existing tax links (we need their billpkgtaxlocationnums)
862 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
863 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
865 foreach ( @tax_links ) {
866 $tax_links{$_->billpkgnum} ||= {};
867 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
871 foreach my $taxline ( @$arrayref_or_error ) {
873 my $amount = $taxline->setup;
875 # find equivalent tax line item on the existing invoice
876 my $tax_item = qsearchs('cust_bill_pkg', {
879 'itemdesc' => $taxline->desc,
882 # or should we just exit if this happens?
883 $cust_credit->set('amount',
884 sprintf('%.2f', $cust_credit->get('amount') - $amount)
886 my $error = $cust_credit->replace;
888 $dbh->rollback if $oldAutoCommit;
889 return "error correcting credit for missing tax line: $error";
893 # but in the new era, we no longer have the problem of uniquely
894 # identifying the tax_Xlocation record. The billpkgnums of the
895 # tax and the taxed item are known.
897 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
898 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
900 # the existing tax_Xlocation object
902 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
904 next if !$old_loc; # apply the leftover amount nonspecifically
906 #support partial credits: use $amount if smaller
907 # (so just distribute to the first location? perhaps should
909 my $loc_amount = min( $amount, $new_loc->amount);
911 $amount -= $loc_amount;
913 $cust_credit_bill{$invnum} += $loc_amount;
914 push @{ $cust_credit_bill_pkg{$invnum} },
915 new FS::cust_credit_bill_pkg {
916 'billpkgnum' => $tax_item->billpkgnum,
917 'amount' => $loc_amount,
918 'setuprecur' => 'setup',
919 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
920 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
923 } #foreach my $new_loc
925 # we still have to deal with the possibility that the tax links don't
926 # cover the whole amount of tax because of an incomplete upgrade...
927 if ($amount > 0.005) {
928 $cust_credit_bill{$invnum} += $amount;
929 push @{ $cust_credit_bill_pkg{$invnum} },
930 new FS::cust_credit_bill_pkg {
931 'billpkgnum' => $tax_item->billpkgnum,
932 'amount' => sprintf('%.2f', $amount),
933 'setuprecur' => 'setup',
938 #unapply any payments applied to the tax
939 foreach my $cust_bill_pay_pkg
940 ( $tax_item->cust_bill_pay_pkg('setup') )
942 $error = $cust_bill_pay_pkg->delete;
944 $dbh->rollback if $oldAutoCommit;
945 return "Error unapplying payment: $error";
947 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
948 += $cust_bill_pay_pkg->amount;
952 # if we unapplied any payments from line items, also unapply that
953 # amount from the invoice
954 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
955 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
956 or die "broken payment application $billpaynum";
957 my @subapps = $cust_bill_pay->lineitem_applications;
958 $error = $cust_bill_pay->delete; # can't replace
960 my $new_cust_bill_pay = FS::cust_bill_pay->new({
961 $cust_bill_pay->hash,
963 amount => sprintf('%.2f',
964 $cust_bill_pay->amount
965 - $unapplied_payments{$invnum}{$billpaynum}),
968 if ( $new_cust_bill_pay->amount > 0 ) {
969 $error ||= $new_cust_bill_pay->insert;
970 # Also reapply it to everything it was applied to before.
971 # Note that we've already deleted cust_bill_pay_pkg records for the
972 # items we're crediting, so they aren't on this list.
973 foreach my $cust_bill_pay_pkg (@subapps) {
974 $cust_bill_pay_pkg->billpaypkgnum('');
975 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
976 $error ||= $cust_bill_pay_pkg->insert;
980 $dbh->rollback if $oldAutoCommit;
981 return "Error unapplying payment: $error";
984 #insert cust_credit_bill
986 my $cust_credit_bill = new FS::cust_credit_bill {
987 'crednum' => $cust_credit->crednum,
989 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
991 $error = $cust_credit_bill->insert;
993 $dbh->rollback if $oldAutoCommit;
994 return "Error applying credit of $cust_credit_bill{$invnum} ".
995 " to invoice $invnum: $error";
998 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
999 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1000 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1001 $error = $cust_credit_bill_pkg->insert;
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Error applying credit to line item: $error";
1010 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1021 =item process_batch_import
1025 use List::Util qw( min );
1027 use FS::cust_credit_bill;
1028 sub process_batch_import {
1031 my $opt = { 'table' => 'cust_credit',
1032 'params' => [ '_date', 'credbatch' ],
1033 'formats' => { 'simple' =>
1034 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1037 'postinsert_callback' => sub {
1038 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1040 if ( $cust_credit->invnum ) {
1042 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1043 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1045 my $cust_credit_bill = new FS::cust_credit_bill ( {
1046 'crednum' => $cust_credit->crednum,
1047 'invnum' => $cust_bill->invnum,
1048 'amount' => $amount,
1050 my $error = $cust_credit_bill->insert;
1051 return '' unless $error;
1055 #apply_payments_and_credits ?
1056 $cust_credit->cust_main->apply_credits;
1063 FS::Record::process_batch_import( $job, $opt, @_ );
1071 The delete method. The replace method.
1073 B<credited> and B<credited_sql> are now called B<unapplied> and
1074 B<unapplied_sql>. The old method names should start to give warnings.
1078 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1079 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base