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 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
181 #false laziness w/ cust_pay::insert
182 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
183 my @errors = $cust_main->unsuspend;
185 # side-fx with nested transactions? upstack rolls back?
186 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
192 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
200 Unless the closed flag is set, deletes this credit and all associated
201 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
202 the void method instead to leave a record of the deleted credit.
206 # very similar to FS::cust_pay::delete
211 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
213 local $SIG{HUP} = 'IGNORE';
214 local $SIG{INT} = 'IGNORE';
215 local $SIG{QUIT} = 'IGNORE';
216 local $SIG{TERM} = 'IGNORE';
217 local $SIG{TSTP} = 'IGNORE';
218 local $SIG{PIPE} = 'IGNORE';
220 my $oldAutoCommit = $FS::UID::AutoCommit;
221 local $FS::UID::AutoCommit = 0;
224 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
225 my $error = $cust_credit_bill->delete;
227 $dbh->rollback if $oldAutoCommit;
232 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
233 my $error = $cust_credit_refund->delete;
235 $dbh->rollback if $oldAutoCommit;
240 my $error = $self->SUPER::delete(@_);
242 $dbh->rollback if $oldAutoCommit;
246 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
248 my $cust_main = $self->cust_main;
250 my $error = send_email(
251 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
252 #invoice_from??? well as good as any
253 'to' => $conf->config('deletecredits'),
254 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
256 "This is an automatic message from your Freeside installation\n",
257 "informing you that the following credit has been deleted:\n",
259 'crednum: '. $self->crednum. "\n",
260 'custnum: '. $self->custnum.
261 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
262 'amount: $'. sprintf("%.2f", $self->amount). "\n",
263 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
264 'reason: '. $self->reason. "\n",
269 $dbh->rollback if $oldAutoCommit;
270 return "can't send credit deletion notification: $error";
275 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
281 =item replace [ OLD_RECORD ]
283 You can, but probably shouldn't modify credits...
285 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
286 supplied, replaces this record. If there is an error, returns the error,
287 otherwise returns false.
293 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
294 $self->SUPER::replace(@_);
299 Checks all fields to make sure this is a valid credit. If there is an error,
300 returns the error, otherwise returns false. Called by the insert and replace
308 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
311 $self->ut_numbern('crednum')
312 || $self->ut_number('custnum')
313 || $self->ut_numbern('_date')
314 || $self->ut_money('amount')
315 || $self->ut_alphan('otaker')
316 || $self->ut_textn('reason')
317 || $self->ut_textn('addlinfo')
318 || $self->ut_enum('closed', [ '', 'Y' ])
319 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
320 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
321 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
322 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
323 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
325 return $error if $error;
327 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
328 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
329 return $error if $error;
331 return "amount must be > 0 " if $self->amount <= 0;
333 return "amount must be greater or equal to amount applied"
334 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
336 return "Unknown customer"
337 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
339 $self->_date(time) unless $self->_date;
344 =item void [ REASON ]
346 Voids this credit: deletes the credit and all associated applications and
347 adds a record of the voided credit to the cust_credit_void table.
351 # yes, false laziness with cust_pay and cust_bill
352 # but frankly I don't have time to fix it now
358 local $SIG{HUP} = 'IGNORE';
359 local $SIG{INT} = 'IGNORE';
360 local $SIG{QUIT} = 'IGNORE';
361 local $SIG{TERM} = 'IGNORE';
362 local $SIG{TSTP} = 'IGNORE';
363 local $SIG{PIPE} = 'IGNORE';
365 my $oldAutoCommit = $FS::UID::AutoCommit;
366 local $FS::UID::AutoCommit = 0;
369 my $cust_credit_void = new FS::cust_credit_void ( {
370 map { $_ => $self->get($_) } $self->fields
372 $cust_credit_void->set('void_reason', $reason);
373 my $error = $cust_credit_void->insert;
375 $dbh->rollback if $oldAutoCommit;
379 $error = $self->delete(void => 1); # suppress deletecredits warning
381 $dbh->rollback if $oldAutoCommit;
385 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
391 =item cust_credit_refund
393 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
397 sub cust_credit_refund {
399 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
400 sort { $a->_date <=> $b->_date }
401 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
405 =item cust_credit_bill
407 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
412 sub cust_credit_bill {
414 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
415 sort { $a->_date <=> $b->_date }
416 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
422 Returns the amount of this credit that is still unapplied/outstanding;
423 amount minus all refund applications (see L<FS::cust_credit_refund>) and
424 applications to invoices (see L<FS::cust_credit_bill>).
430 my $amount = $self->amount;
431 $amount -= $_->amount foreach ( $self->cust_credit_refund );
432 $amount -= $_->amount foreach ( $self->cust_credit_bill );
433 sprintf( "%.2f", $amount );
438 Deprecated name for the unapplied method.
444 #carp "cust_credit->credited deprecated; use ->unapplied";
445 $self->unapplied(@_);
450 Returns the customer (see L<FS::cust_main>) for this credit.
456 # Used by FS::Upgrade to migrate to a new database.
458 sub _upgrade_data { # class method
459 my ($class, %opts) = @_;
461 warn "$me upgrading $class\n" if $DEBUG;
463 $class->_upgrade_reasonnum(%opts);
465 if (defined dbdef->table($class->table)->column('reason')) {
467 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
469 foreach ( keys %reasontype_map ) {
470 unless ($conf->config($_)) { # hmmmm
471 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
472 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
473 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
474 my $reason_type = qsearchs( 'reason_type', $hashref );
475 unless ($reason_type) {
476 $reason_type = new FS::reason_type( $hashref );
477 my $error = $reason_type->insert();
478 die "$class had error inserting FS::reason_type into database: $error\n"
481 $conf->set($_, $reason_type->typenum);
485 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
487 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
488 my $reason_type = qsearchs( 'reason_type', $hashref );
489 unless ($reason_type) {
490 $reason_type = new FS::reason_type( $hashref );
491 my $error = $reason_type->insert();
492 die "$class had error inserting FS::reason_type into database: $error\n"
496 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
497 foreach my $plan ( @plans ) {
498 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
499 unless ($pkg->option('reason_type', 1) ) {
500 my $plandata = $pkg->plandata.
501 "reason_type=". $reason_type->typenum. "\n";
502 $pkg->plandata($plandata);
504 $pkg->replace( undef,
505 'pkg_svc' => { map { $_->svcpart => $_->quantity }
508 'primary_svc' => $pkg->svcpart,
510 die "failed setting reason_type option: $error"
517 local($otaker_upgrade_kludge) = 1;
518 local($ignore_empty_reasonnum) = 1;
519 $class->_upgrade_otaker(%opts);
521 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
522 and !$conf->exists('enable_taxproducts') ) {
523 # RT#25458: fix credit line item applications that should refer to a
524 # specific tax allocation
525 my @cust_credit_bill_pkg = qsearch({
526 table => 'cust_credit_bill_pkg',
527 select => 'cust_credit_bill_pkg.*',
528 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
530 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
531 'AND cust_bill_pkg.pkgnum = 0', # is a tax
535 foreach (@cust_credit_bill_pkg) {
536 my $billpkgnum = $_->billpkgnum;
537 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
538 $credits{$billpkgnum} ||= [];
539 push @{ $credits{$billpkgnum} }, $_;
541 TAX_ITEM: foreach my $tax_item (values %tax_items) {
542 my $billpkgnum = $tax_item->billpkgnum;
543 # get all pkg/location/taxrate allocations of this tax line item
544 my @allocations = sort {$b->amount <=> $a->amount}
545 qsearch('cust_bill_pkg_tax_location', {
546 billpkgnum => $billpkgnum
548 # and these are all credit applications to it
549 my @credits = sort {$b->amount <=> $a->amount}
550 @{ $credits{$billpkgnum} };
551 my $c = shift @credits;
552 my $a = shift @allocations; # we will NOT modify these
554 if ( abs($c->amount - $a->amount) < 0.005 ) {
555 # by far the most common case: the tax line item is for a single
556 # tax, so we just fill in the billpkgtaxlocationnum
557 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
558 my $error = $c->replace;
560 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
564 $a = shift @allocations;
565 } elsif ( $c->amount > $a->amount ) {
566 # fairly common: the tax line contains tax for multiple packages
567 # (or multiple taxes) but the credit isn't divided up
568 my $new_link = FS::cust_credit_bill_pkg->new({
569 creditbillnum => $c->creditbillnum,
570 billpkgnum => $c->billpkgnum,
571 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
572 amount => $a->amount,
573 setuprecur => 'setup',
575 my $error = $new_link->insert;
577 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
580 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
581 $a = shift @allocations;
582 } elsif ( $c->amount < 0.005 ) {
583 # also fairly common; we can delete these with no harm
584 my $error = $c->delete;
585 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
587 } elsif ( $c->amount < $a->amount ) {
588 # should never happen, but if it does, handle it gracefully
589 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
590 my $error = $c->replace;
592 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
595 $a->set(amount => $a->amount - $c->amount);
600 if ( $c->amount < 0.005 ) {
601 my $error = $c->delete;
602 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
603 } elsif ( $c->modified ) {
604 # then we've allocated part of it, so reduce the nonspecific
605 # application by that much
606 my $error = $c->replace;
607 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
609 # else there are probably no allocations, i.e. this is a pre-3.x
610 # record that was never migrated over, so leave it alone
612 } # foreach $tax_item
613 FS::upgrade_journal->set_done('cust_credit__tax_link');
625 Returns an SQL fragment to retreive the unapplied amount.
630 my ($class, $start, $end) = @_;
632 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
633 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
634 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
635 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
639 ( SELECT SUM(amount) FROM cust_credit_refund
640 WHERE cust_credit.crednum = cust_credit_refund.crednum
641 $refund_start $refund_end )
645 ( SELECT SUM(amount) FROM cust_credit_bill
646 WHERE cust_credit.crednum = cust_credit_bill.crednum
647 $bill_start $bill_end )
656 Deprecated name for the unapplied_sql method.
663 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
665 #$class->unapplied_sql(@_);
669 =item credit_lineitems
673 my $error = FS::cust_credit->credit_lineitems(
675 #the lineitems to credit
676 'billpkgnums' => \@billpkgnums,
677 'setuprecurs' => \@setuprecurs,
678 'amounts' => \@amounts,
679 'apply' => 1, #0 leaves the credit unapplied
682 'newreasonnum' => scalar($cgi->param('newreasonnum')),
683 'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
684 map { $_ => scalar($cgi->param($_)) }
685 #fields('cust_credit')
686 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
692 #maybe i should just be an insert with extra args instead of a class method
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 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
819 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
820 } # otherwise the item itself is a tax, and assume the caller knows
825 # now loop through %cust_credit_bill and insert those
828 # (hack to prevent cust_credit_bill_pkg insertion)
829 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
831 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
833 my $arrayref_or_error =
834 $cust_main->calculate_taxes(
835 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
836 $taxlisthash{$invnum}, # list of tax-item bindings
837 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
840 unless ( ref( $arrayref_or_error ) ) {
841 $dbh->rollback if $oldAutoCommit;
842 return "Error calculating taxes: $arrayref_or_error";
845 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
848 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
849 my $billpkgnum = $cust_bill_pkg->billpkgnum;
850 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
851 # gather up existing tax links (we need their billpkgtaxlocationnums)
852 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
853 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
855 foreach ( @tax_links ) {
856 $tax_links{$_->billpkgnum} ||= {};
857 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
861 foreach my $taxline ( @$arrayref_or_error ) {
863 my $amount = $taxline->setup;
865 # find equivalent tax line item on the existing invoice
866 my $tax_item = qsearchs('cust_bill_pkg', {
869 'itemdesc' => $taxline->desc,
872 # or should we just exit if this happens?
873 $cust_credit->set('amount',
874 sprintf('%.2f', $cust_credit->get('amount') - $amount)
876 my $error = $cust_credit->replace;
878 $dbh->rollback if $oldAutoCommit;
879 return "error correcting credit for missing tax line: $error";
883 # but in the new era, we no longer have the problem of uniquely
884 # identifying the tax_Xlocation record. The billpkgnums of the
885 # tax and the taxed item are known.
887 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
888 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
890 # the existing tax_Xlocation object
892 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
894 next if !$old_loc; # apply the leftover amount nonspecifically
896 #support partial credits: use $amount if smaller
897 # (so just distribute to the first location? perhaps should
899 my $loc_amount = min( $amount, $new_loc->amount);
901 $amount -= $loc_amount;
903 $cust_credit_bill{$invnum} += $loc_amount;
904 push @{ $cust_credit_bill_pkg{$invnum} },
905 new FS::cust_credit_bill_pkg {
906 'billpkgnum' => $tax_item->billpkgnum,
907 'amount' => $loc_amount,
908 'setuprecur' => 'setup',
909 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
910 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
913 } #foreach my $new_loc
915 # we still have to deal with the possibility that the tax links don't
916 # cover the whole amount of tax because of an incomplete upgrade...
917 if ($amount > 0.005) {
918 $cust_credit_bill{$invnum} += $amount;
919 push @{ $cust_credit_bill_pkg{$invnum} },
920 new FS::cust_credit_bill_pkg {
921 'billpkgnum' => $tax_item->billpkgnum,
922 'amount' => sprintf('%.2f', $amount),
923 'setuprecur' => 'setup',
928 #unapply any payments applied to the tax
929 foreach my $cust_bill_pay_pkg
930 ( $tax_item->cust_bill_pay_pkg('setup') )
932 $error = $cust_bill_pay_pkg->delete;
934 $dbh->rollback if $oldAutoCommit;
935 return "Error unapplying payment: $error";
937 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
938 += $cust_bill_pay_pkg->amount;
942 # if we unapplied any payments from line items, also unapply that
943 # amount from the invoice
944 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
945 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
946 or die "broken payment application $billpaynum";
947 my @subapps = $cust_bill_pay->lineitem_applications;
948 $error = $cust_bill_pay->delete; # can't replace
950 my $new_cust_bill_pay = FS::cust_bill_pay->new({
951 $cust_bill_pay->hash,
953 amount => sprintf('%.2f',
954 $cust_bill_pay->amount
955 - $unapplied_payments{$invnum}{$billpaynum}),
958 if ( $new_cust_bill_pay->amount > 0 ) {
959 $error ||= $new_cust_bill_pay->insert;
960 # Also reapply it to everything it was applied to before.
961 # Note that we've already deleted cust_bill_pay_pkg records for the
962 # items we're crediting, so they aren't on this list.
963 foreach my $cust_bill_pay_pkg (@subapps) {
964 $cust_bill_pay_pkg->billpaypkgnum('');
965 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
966 $error ||= $cust_bill_pay_pkg->insert;
970 $dbh->rollback if $oldAutoCommit;
971 return "Error unapplying payment: $error";
974 #insert cust_credit_bill
976 my $cust_credit_bill = new FS::cust_credit_bill {
977 'crednum' => $cust_credit->crednum,
979 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
981 $error = $cust_credit_bill->insert;
983 $dbh->rollback if $oldAutoCommit;
984 return "Error applying credit of $cust_credit_bill{$invnum} ".
985 " to invoice $invnum: $error";
988 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
989 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
990 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
991 $error = $cust_credit_bill_pkg->insert;
993 $dbh->rollback if $oldAutoCommit;
994 return "Error applying credit to line item: $error";
1000 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1011 =item process_batch_import
1015 use List::Util qw( min );
1017 use FS::cust_credit_bill;
1018 sub process_batch_import {
1021 my $opt = { 'table' => 'cust_credit',
1022 'params' => [ '_date', 'credbatch' ],
1023 'formats' => { 'simple' =>
1024 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1027 'postinsert_callback' => sub {
1028 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1030 if ( $cust_credit->invnum ) {
1032 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1033 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1035 my $cust_credit_bill = new FS::cust_credit_bill ( {
1036 'crednum' => $cust_credit->crednum,
1037 'invnum' => $cust_bill->invnum,
1038 'amount' => $amount,
1040 my $error = $cust_credit_bill->insert;
1041 return '' unless $error;
1045 #apply_payments_and_credits ?
1046 $cust_credit->cust_main->apply_credits;
1053 FS::Record::process_batch_import( $job, $opt, @_ );
1061 The delete method. The replace method.
1063 B<credited> and B<credited_sql> are now called B<unapplied> and
1064 B<unapplied_sql>. The old method names should start to give warnings.
1068 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1069 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base