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::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. ')';
136 Adds this credit to the database ("Posts" the credit). If there is an error,
137 returns the error, otherwise returns false.
142 my ($self, %options) = @_;
144 local $SIG{HUP} = 'IGNORE';
145 local $SIG{INT} = 'IGNORE';
146 local $SIG{QUIT} = 'IGNORE';
147 local $SIG{TERM} = 'IGNORE';
148 local $SIG{TSTP} = 'IGNORE';
149 local $SIG{PIPE} = 'IGNORE';
151 my $oldAutoCommit = $FS::UID::AutoCommit;
152 local $FS::UID::AutoCommit = 0;
155 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
156 my $old_balance = $cust_main->balance;
158 unless ($self->reasonnum) {
159 my $result = $self->reason( $self->getfield('reason'),
160 exists($options{ 'reason_type' })
161 ? ('reason_type' => $options{ 'reason_type' })
165 $dbh->rollback if $oldAutoCommit;
166 return "failed to set reason for $me"; #: ". $dbh->errstr;
170 $self->setfield('reason', '');
172 my $error = $self->SUPER::insert;
174 $dbh->rollback if $oldAutoCommit;
175 return "error inserting $self: $error";
178 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
180 #false laziness w/ cust_pay::insert
181 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
182 my @errors = $cust_main->unsuspend;
184 # side-fx with nested transactions? upstack rolls back?
185 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
191 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
199 Unless the closed flag is set, deletes this credit and all associated
200 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
201 the void method instead to leave a record of the deleted credit.
205 # very similar to FS::cust_pay::delete
210 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
212 local $SIG{HUP} = 'IGNORE';
213 local $SIG{INT} = 'IGNORE';
214 local $SIG{QUIT} = 'IGNORE';
215 local $SIG{TERM} = 'IGNORE';
216 local $SIG{TSTP} = 'IGNORE';
217 local $SIG{PIPE} = 'IGNORE';
219 my $oldAutoCommit = $FS::UID::AutoCommit;
220 local $FS::UID::AutoCommit = 0;
223 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
224 my $error = $cust_credit_bill->delete;
226 $dbh->rollback if $oldAutoCommit;
231 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
232 my $error = $cust_credit_refund->delete;
234 $dbh->rollback if $oldAutoCommit;
239 my $error = $self->SUPER::delete(@_);
241 $dbh->rollback if $oldAutoCommit;
245 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
247 my $cust_main = $self->cust_main;
249 my $error = send_email(
250 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
251 #invoice_from??? well as good as any
252 'to' => $conf->config('deletecredits'),
253 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
255 "This is an automatic message from your Freeside installation\n",
256 "informing you that the following credit has been deleted:\n",
258 'crednum: '. $self->crednum. "\n",
259 'custnum: '. $self->custnum.
260 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
261 'amount: $'. sprintf("%.2f", $self->amount). "\n",
262 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
263 'reason: '. $self->reason. "\n",
268 $dbh->rollback if $oldAutoCommit;
269 return "can't send credit deletion notification: $error";
274 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280 =item replace [ OLD_RECORD ]
282 You can, but probably shouldn't modify credits...
284 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
285 supplied, replaces this record. If there is an error, returns the error,
286 otherwise returns false.
292 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
293 $self->SUPER::replace(@_);
298 Checks all fields to make sure this is a valid credit. If there is an error,
299 returns the error, otherwise returns false. Called by the insert and replace
307 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
310 $self->ut_numbern('crednum')
311 || $self->ut_number('custnum')
312 || $self->ut_numbern('_date')
313 || $self->ut_money('amount')
314 || $self->ut_alphan('otaker')
315 || $self->ut_textn('reason')
316 || $self->ut_textn('addlinfo')
317 || $self->ut_enum('closed', [ '', 'Y' ])
318 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
319 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
320 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
321 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
322 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
324 return $error if $error;
326 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
327 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
328 return $error if $error;
330 return "amount must be > 0 " if $self->amount <= 0;
332 return "amount must be greater or equal to amount applied"
333 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
335 return "Unknown customer"
336 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
338 $self->_date(time) unless $self->_date;
343 =item void [ REASON ]
345 Voids this credit: deletes the credit and all associated applications and
346 adds a record of the voided credit to the cust_credit_void table.
350 # yes, false laziness with cust_pay and cust_bill
351 # but frankly I don't have time to fix it now
357 local $SIG{HUP} = 'IGNORE';
358 local $SIG{INT} = 'IGNORE';
359 local $SIG{QUIT} = 'IGNORE';
360 local $SIG{TERM} = 'IGNORE';
361 local $SIG{TSTP} = 'IGNORE';
362 local $SIG{PIPE} = 'IGNORE';
364 my $oldAutoCommit = $FS::UID::AutoCommit;
365 local $FS::UID::AutoCommit = 0;
368 my $cust_credit_void = new FS::cust_credit_void ( {
369 map { $_ => $self->get($_) } $self->fields
371 $cust_credit_void->set('void_reason', $reason);
372 my $error = $cust_credit_void->insert;
374 $dbh->rollback if $oldAutoCommit;
378 $error = $self->delete(void => 1); # suppress deletecredits warning
380 $dbh->rollback if $oldAutoCommit;
384 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
390 =item cust_credit_refund
392 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
396 sub cust_credit_refund {
398 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
399 sort { $a->_date <=> $b->_date }
400 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
404 =item cust_credit_bill
406 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
411 sub cust_credit_bill {
413 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
414 sort { $a->_date <=> $b->_date }
415 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
421 Returns the amount of this credit that is still unapplied/outstanding;
422 amount minus all refund applications (see L<FS::cust_credit_refund>) and
423 applications to invoices (see L<FS::cust_credit_bill>).
429 my $amount = $self->amount;
430 $amount -= $_->amount foreach ( $self->cust_credit_refund );
431 $amount -= $_->amount foreach ( $self->cust_credit_bill );
432 sprintf( "%.2f", $amount );
437 Deprecated name for the unapplied method.
443 #carp "cust_credit->credited deprecated; use ->unapplied";
444 $self->unapplied(@_);
449 Returns the customer (see L<FS::cust_main>) for this credit.
455 # Used by FS::Upgrade to migrate to a new database.
457 sub _upgrade_data { # class method
458 my ($class, %opts) = @_;
460 warn "$me upgrading $class\n" if $DEBUG;
462 $class->_upgrade_reasonnum(%opts);
464 if (defined dbdef->table($class->table)->column('reason')) {
466 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
468 foreach ( keys %reasontype_map ) {
469 unless ($conf->config($_)) { # hmmmm
470 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
471 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
472 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
473 my $reason_type = qsearchs( 'reason_type', $hashref );
474 unless ($reason_type) {
475 $reason_type = new FS::reason_type( $hashref );
476 my $error = $reason_type->insert();
477 die "$class had error inserting FS::reason_type into database: $error\n"
480 $conf->set($_, $reason_type->typenum);
484 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
486 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
487 my $reason_type = qsearchs( 'reason_type', $hashref );
488 unless ($reason_type) {
489 $reason_type = new FS::reason_type( $hashref );
490 my $error = $reason_type->insert();
491 die "$class had error inserting FS::reason_type into database: $error\n"
495 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
496 foreach my $plan ( @plans ) {
497 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
498 unless ($pkg->option('reason_type', 1) ) {
499 my $plandata = $pkg->plandata.
500 "reason_type=". $reason_type->typenum. "\n";
501 $pkg->plandata($plandata);
503 $pkg->replace( undef,
504 'pkg_svc' => { map { $_->svcpart => $_->quantity }
507 'primary_svc' => $pkg->svcpart,
509 die "failed setting reason_type option: $error"
516 local($otaker_upgrade_kludge) = 1;
517 local($ignore_empty_reasonnum) = 1;
518 $class->_upgrade_otaker(%opts);
520 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
521 and !$conf->exists('enable_taxproducts') ) {
522 # RT#25458: fix credit line item applications that should refer to a
523 # specific tax allocation
524 my @cust_credit_bill_pkg = qsearch({
525 table => 'cust_credit_bill_pkg',
526 select => 'cust_credit_bill_pkg.*',
527 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
529 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
530 'AND cust_bill_pkg.pkgnum = 0', # is a tax
534 foreach (@cust_credit_bill_pkg) {
535 my $billpkgnum = $_->billpkgnum;
536 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
537 $credits{$billpkgnum} ||= [];
538 push @{ $credits{$billpkgnum} }, $_;
540 TAX_ITEM: foreach my $tax_item (values %tax_items) {
541 my $billpkgnum = $tax_item->billpkgnum;
542 # get all pkg/location/taxrate allocations of this tax line item
543 my @allocations = sort {$b->amount <=> $a->amount}
544 qsearch('cust_bill_pkg_tax_location', {
545 billpkgnum => $billpkgnum
547 # and these are all credit applications to it
548 my @credits = sort {$b->amount <=> $a->amount}
549 @{ $credits{$billpkgnum} };
550 my $c = shift @credits;
551 my $a = shift @allocations; # we will NOT modify these
553 if ( abs($c->amount - $a->amount) < 0.005 ) {
554 # by far the most common case: the tax line item is for a single
555 # tax, so we just fill in the billpkgtaxlocationnum
556 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
557 my $error = $c->replace;
559 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
563 $a = shift @allocations;
564 } elsif ( $c->amount > $a->amount ) {
565 # fairly common: the tax line contains tax for multiple packages
566 # (or multiple taxes) but the credit isn't divided up
567 my $new_link = FS::cust_credit_bill_pkg->new({
568 creditbillnum => $c->creditbillnum,
569 billpkgnum => $c->billpkgnum,
570 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
571 amount => $a->amount,
572 setuprecur => 'setup',
574 my $error = $new_link->insert;
576 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
579 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
580 $a = shift @allocations;
581 } elsif ( $c->amount < 0.005 ) {
582 # also fairly common; we can delete these with no harm
583 my $error = $c->delete;
584 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
586 } elsif ( $c->amount < $a->amount ) {
587 # should never happen, but if it does, handle it gracefully
588 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
589 my $error = $c->replace;
591 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
594 $a->set(amount => $a->amount - $c->amount);
599 if ( $c->amount < 0.005 ) {
600 my $error = $c->delete;
601 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
602 } elsif ( $c->modified ) {
603 # then we've allocated part of it, so reduce the nonspecific
604 # application by that much
605 my $error = $c->replace;
606 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
608 # else there are probably no allocations, i.e. this is a pre-3.x
609 # record that was never migrated over, so leave it alone
611 } # foreach $tax_item
612 FS::upgrade_journal->set_done('cust_credit__tax_link');
624 Returns an SQL fragment to retreive the unapplied amount.
629 my ($class, $start, $end) = @_;
631 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
632 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
633 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
634 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
638 ( SELECT SUM(amount) FROM cust_credit_refund
639 WHERE cust_credit.crednum = cust_credit_refund.crednum
640 $refund_start $refund_end )
644 ( SELECT SUM(amount) FROM cust_credit_bill
645 WHERE cust_credit.crednum = cust_credit_bill.crednum
646 $bill_start $bill_end )
655 Deprecated name for the unapplied_sql method.
662 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
664 #$class->unapplied_sql(@_);
668 =item credit_lineitems
672 my $error = FS::cust_credit->credit_lineitems(
674 #the lineitems to credit
675 'billpkgnums' => \@billpkgnums,
676 'setuprecurs' => \@setuprecurs,
677 'amounts' => \@amounts,
678 'apply' => 1, #0 leaves the credit unapplied
681 'newreasonnum' => scalar($cgi->param('newreasonnum')),
682 'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
683 map { $_ => scalar($cgi->param($_)) }
684 #fields('cust_credit')
685 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
691 #maybe i should just be an insert with extra args instead of a class method
692 use FS::cust_bill_pkg;
693 sub credit_lineitems {
694 my( $class, %arg ) = @_;
695 my $curuser = $FS::CurrentUser::CurrentUser;
697 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
699 my $cust_main = qsearchs({
700 'table' => 'cust_main',
701 'hashref' => { 'custnum' => $arg{custnum} },
702 'extra_sql' => ' AND '. $curuser->agentnums_sql,
703 }) or return 'unknown customer';
706 local $SIG{HUP} = 'IGNORE';
707 local $SIG{INT} = 'IGNORE';
708 local $SIG{QUIT} = 'IGNORE';
709 local $SIG{TERM} = 'IGNORE';
710 local $SIG{TSTP} = 'IGNORE';
711 local $SIG{PIPE} = 'IGNORE';
713 my $oldAutoCommit = $FS::UID::AutoCommit;
714 local $FS::UID::AutoCommit = 0;
717 #my @cust_bill_pkg = qsearch({
718 # 'select' => 'cust_bill_pkg.*',
719 # 'table' => 'cust_bill_pkg',
720 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
721 # ' LEFT JOIN cust_main USING (custnum) ',
722 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
723 # join( ',', @{$arg{billpkgnums}} ). ')',
724 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
728 if ($arg{reasonnum} == -1) {
730 $error = 'Enter a new reason (or select an existing one)'
731 unless $arg{newreasonnum} !~ /^\s*$/;
732 my $reason = new FS::reason {
733 'reason' => $arg{newreasonnum},
734 'reason_type' => $arg{newreasonnum_type},
736 $error ||= $reason->insert;
738 $dbh->rollback if $oldAutoCommit;
739 return "Error inserting reason: $error";
741 $arg{reasonnum} = $reason->reasonnum;
744 my $cust_credit = new FS::cust_credit ( {
745 map { $_ => $arg{$_} }
746 #fields('cust_credit')
747 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
749 $error = $cust_credit->insert;
751 $dbh->rollback if $oldAutoCommit;
752 return "Error inserting credit: $error";
755 unless ( $arg{'apply'} ) {
756 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
761 # keys in all of these are invoice numbers
762 my %cust_credit_bill = ();
763 my %cust_bill_pkg = ();
764 my %cust_credit_bill_pkg = ();
765 my %taxlisthash = ();
766 my %unapplied_payments = (); #invoice numbers, and then billpaynums
767 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
768 my $setuprecur = shift @{$arg{setuprecurs}};
769 my $amount = shift @{$arg{amounts}};
771 my $cust_bill_pkg = qsearchs({
772 'table' => 'cust_bill_pkg',
773 'hashref' => { 'billpkgnum' => $billpkgnum },
774 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
775 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
776 }) or die "unknown billpkgnum $billpkgnum";
778 my $invnum = $cust_bill_pkg->invnum;
780 if ( $setuprecur eq 'setup' ) {
781 $cust_bill_pkg->setup($amount);
782 $cust_bill_pkg->recur(0);
783 $cust_bill_pkg->unitrecur(0);
784 $cust_bill_pkg->type('');
786 $setuprecur = 'recur'; #in case its a usage classnum?
787 $cust_bill_pkg->recur($amount);
788 $cust_bill_pkg->setup(0);
789 $cust_bill_pkg->unitsetup(0);
792 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
794 #unapply any payments applied to this line item (other credits too?)
795 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
796 $error = $cust_bill_pay_pkg->delete;
798 $dbh->rollback if $oldAutoCommit;
799 return "Error unapplying payment: $error";
801 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
802 += $cust_bill_pay_pkg->amount;
805 #$subtotal += $amount;
806 $cust_credit_bill{$invnum} += $amount;
807 push @{ $cust_credit_bill_pkg{$invnum} },
808 new FS::cust_credit_bill_pkg {
809 'billpkgnum' => $cust_bill_pkg->billpkgnum,
810 'amount' => sprintf('%.2f',$amount),
811 'setuprecur' => $setuprecur,
812 'sdate' => $cust_bill_pkg->sdate,
813 'edate' => $cust_bill_pkg->edate,
816 # recalculate taxes with new amounts
817 $taxlisthash{$invnum} ||= {};
818 my $part_pkg = $cust_bill_pkg->part_pkg;
819 $cust_main->_handle_taxes( $part_pkg,
820 $taxlisthash{$invnum},
822 $cust_bill_pkg->cust_pkg,
823 $cust_bill_pkg->cust_bill->_date, #invoice time
824 $cust_bill_pkg->cust_pkg->pkgpart,
829 # now loop through %cust_credit_bill and insert those
832 # (hack to prevent cust_credit_bill_pkg insertion)
833 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
835 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
837 my $arrayref_or_error =
838 $cust_main->calculate_taxes(
839 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
840 $taxlisthash{$invnum}, # list of tax-item bindings
841 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
844 unless ( ref( $arrayref_or_error ) ) {
845 $dbh->rollback if $oldAutoCommit;
846 return "Error calculating taxes: $arrayref_or_error";
849 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
852 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
853 my $billpkgnum = $cust_bill_pkg->billpkgnum;
854 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
855 # gather up existing tax links (we need their billpkgtaxlocationnums)
856 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
857 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
859 foreach ( @tax_links ) {
860 $tax_links{$_->billpkgnum} ||= {};
861 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
865 foreach my $taxline ( @$arrayref_or_error ) {
867 my $amount = $taxline->setup;
869 # find equivalent tax line item on the existing invoice
870 my $tax_item = qsearchs('cust_bill_pkg', {
873 'itemdesc' => $taxline->desc,
876 # or should we just exit if this happens?
877 $cust_credit->set('amount',
878 sprintf('%.2f', $cust_credit->get('amount') - $amount)
880 my $error = $cust_credit->replace;
882 $dbh->rollback if $oldAutoCommit;
883 return "error correcting credit for missing tax line: $error";
887 # but in the new era, we no longer have the problem of uniquely
888 # identifying the tax_Xlocation record. The billpkgnums of the
889 # tax and the taxed item are known.
891 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
892 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
894 # the existing tax_Xlocation object
896 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
898 next if !$old_loc; # apply the leftover amount nonspecifically
900 #support partial credits: use $amount if smaller
901 # (so just distribute to the first location? perhaps should
903 my $loc_amount = min( $amount, $new_loc->amount);
905 $amount -= $loc_amount;
907 $cust_credit_bill{$invnum} += $loc_amount;
908 push @{ $cust_credit_bill_pkg{$invnum} },
909 new FS::cust_credit_bill_pkg {
910 'billpkgnum' => $tax_item->billpkgnum,
911 'amount' => $loc_amount,
912 'setuprecur' => 'setup',
913 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
914 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
917 } #foreach my $new_loc
919 # we still have to deal with the possibility that the tax links don't
920 # cover the whole amount of tax because of an incomplete upgrade...
922 $cust_credit_bill{$invnum} += $amount;
923 push @{ $cust_credit_bill_pkg{$invnum} },
924 new FS::cust_credit_bill_pkg {
925 'billpkgnum' => $tax_item->billpkgnum,
927 'setuprecur' => 'setup',
932 #unapply any payments applied to the tax
933 foreach my $cust_bill_pay_pkg
934 ( $tax_item->cust_bill_pay_pkg('setup') )
936 $error = $cust_bill_pay_pkg->delete;
938 $dbh->rollback if $oldAutoCommit;
939 return "Error unapplying payment: $error";
941 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
942 += $cust_bill_pay_pkg->amount;
946 # if we unapplied any payments from line items, also unapply that
947 # amount from the invoice
948 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
949 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
950 or die "broken payment application $billpaynum";
951 my @subapps = $cust_bill_pay->lineitem_applications;
952 $error = $cust_bill_pay->delete; # can't replace
954 my $new_cust_bill_pay = FS::cust_bill_pay->new({
955 $cust_bill_pay->hash,
957 amount => sprintf('%.2f',
958 $cust_bill_pay->amount
959 - $unapplied_payments{$invnum}{$billpaynum}),
962 if ( $new_cust_bill_pay->amount > 0 ) {
963 $error ||= $new_cust_bill_pay->insert;
964 # Also reapply it to everything it was applied to before.
965 # Note that we've already deleted cust_bill_pay_pkg records for the
966 # items we're crediting, so they aren't on this list.
967 foreach my $cust_bill_pay_pkg (@subapps) {
968 $cust_bill_pay_pkg->billpaypkgnum('');
969 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
970 $error ||= $cust_bill_pay_pkg->insert;
974 $dbh->rollback if $oldAutoCommit;
975 return "Error unapplying payment: $error";
978 #insert cust_credit_bill
980 my $cust_credit_bill = new FS::cust_credit_bill {
981 'crednum' => $cust_credit->crednum,
983 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
985 $error = $cust_credit_bill->insert;
987 $dbh->rollback if $oldAutoCommit;
988 return "Error applying credit of $cust_credit_bill{$invnum} ".
989 " to invoice $invnum: $error";
992 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
993 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
994 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
995 $error = $cust_credit_bill_pkg->insert;
997 $dbh->rollback if $oldAutoCommit;
998 return "Error applying credit to line item: $error";
1004 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1015 =item process_batch_import
1019 use List::Util qw( min );
1021 use FS::cust_credit_bill;
1022 sub process_batch_import {
1025 my $opt = { 'table' => 'cust_credit',
1026 'params' => [ '_date', 'credbatch' ],
1027 'formats' => { 'simple' =>
1028 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1031 'postinsert_callback' => sub {
1032 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1034 if ( $cust_credit->invnum ) {
1036 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1037 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1039 my $cust_credit_bill = new FS::cust_credit_bill ( {
1040 'crednum' => $cust_credit->crednum,
1041 'invnum' => $cust_bill->invnum,
1042 'amount' => $amount,
1044 my $error = $cust_credit_bill->insert;
1045 return '' unless $error;
1049 #apply_payments_and_credits ?
1050 $cust_credit->cust_main->apply_credits;
1057 FS::Record::process_batch_import( $job, $opt, @_ );
1065 The delete method. The replace method.
1067 B<credited> and B<credited_sql> are now called B<unapplied> and
1068 B<unapplied_sql>. The old method names should start to give warnings.
1072 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1073 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base