1 package FS::cust_credit;
4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $conf $unsuspendauto $me $DEBUG
6 $otaker_upgrade_kludge $ignore_empty_reasonnum
8 use List::Util qw( min );
10 use FS::UID qw( dbh getotaker );
11 use FS::Misc qw(send_email);
12 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; }
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->invoice_from_full($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 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
462 Returns the text of the associated reason (see L<FS::reason>) for this credit.
467 my ($self, $value, %options) = @_;
470 my $typenum = $options{'reason_type'};
472 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
473 local $FS::UID::AutoCommit = 0; # a transaction if it matters
475 if ( defined( $value ) ) {
476 my $hashref = { 'reason' => $value };
477 $hashref->{'reason_type'} = $typenum if $typenum;
478 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
479 my $extra_sql = " AND reason_type.class='R'";
481 $reason = qsearchs( { 'table' => 'reason',
482 'hashref' => $hashref,
483 'addl_from' => $addl_from,
484 'extra_sql' => $extra_sql,
487 if (!$reason && $typenum) {
488 $reason = new FS::reason( { 'reason_type' => $typenum,
492 my $error = $reason->insert;
494 warn "error inserting reason: $error\n";
499 $self->reasonnum($reason ? $reason->reasonnum : '') ;
500 warn "$me reason used in set mode with non-existant reason -- clearing"
503 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
505 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
507 ( $reason ? $reason->reason : '' ).
508 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
513 # Used by FS::Upgrade to migrate to a new database.
515 sub _upgrade_data { # class method
516 my ($class, %opts) = @_;
518 warn "$me upgrading $class\n" if $DEBUG;
520 if (defined dbdef->table($class->table)->column('reason')) {
522 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
524 my @cust_credits = qsearch({ 'table' => $class->table,
526 'extra_sql' => 'WHERE reason IS NOT NULL',
529 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
530 warn "$me Found unmigrated reasons\n" if $DEBUG;
531 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
532 my $reason_type = qsearchs( 'reason_type', $hashref );
533 unless ($reason_type) {
534 $reason_type = new FS::reason_type( $hashref );
535 my $error = $reason_type->insert();
536 die "$class had error inserting FS::reason_type into database: $error\n"
540 $hashref = { 'reason_type' => $reason_type->typenum,
543 my $noreason = qsearchs( 'reason', $hashref );
545 $hashref->{'disabled'} = 'Y';
546 $noreason = new FS::reason( $hashref );
547 my $error = $noreason->insert();
548 die "can't insert legacy reason '(none)' into database: $error\n"
552 foreach my $cust_credit ( @cust_credits ) {
553 my $reason = $cust_credit->getfield('reason');
554 warn "Contemplating reason $reason\n" if $DEBUG > 1;
555 if ($reason =~ /\S/) {
556 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
557 or die "can't insert legacy reason $reason into database\n";
559 $cust_credit->reasonnum($noreason->reasonnum);
562 $cust_credit->setfield('reason', '');
563 my $error = $cust_credit->replace;
565 warn "*** WARNING: error replacing reason in $class ".
566 $cust_credit->crednum. ": $error ***\n"
571 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
573 foreach ( keys %reasontype_map ) {
574 unless ($conf->config($_)) { # hmmmm
575 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
576 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
577 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
578 my $reason_type = qsearchs( 'reason_type', $hashref );
579 unless ($reason_type) {
580 $reason_type = new FS::reason_type( $hashref );
581 my $error = $reason_type->insert();
582 die "$class had error inserting FS::reason_type into database: $error\n"
585 $conf->set($_, $reason_type->typenum);
589 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
591 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
592 my $reason_type = qsearchs( 'reason_type', $hashref );
593 unless ($reason_type) {
594 $reason_type = new FS::reason_type( $hashref );
595 my $error = $reason_type->insert();
596 die "$class had error inserting FS::reason_type into database: $error\n"
600 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
601 foreach my $plan ( @plans ) {
602 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
603 unless ($pkg->option('reason_type', 1) ) {
604 my $plandata = $pkg->plandata.
605 "reason_type=". $reason_type->typenum. "\n";
606 $pkg->plandata($plandata);
608 $pkg->replace( undef,
609 'pkg_svc' => { map { $_->svcpart => $_->quantity }
612 'primary_svc' => $pkg->svcpart,
614 die "failed setting reason_type option: $error"
621 local($otaker_upgrade_kludge) = 1;
622 local($ignore_empty_reasonnum) = 1;
623 $class->_upgrade_otaker(%opts);
625 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
626 and !$conf->exists('enable_taxproducts') ) {
627 # RT#25458: fix credit line item applications that should refer to a
628 # specific tax allocation
629 my @cust_credit_bill_pkg = qsearch({
630 table => 'cust_credit_bill_pkg',
631 select => 'cust_credit_bill_pkg.*',
632 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
634 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
635 'AND cust_bill_pkg.pkgnum = 0', # is a tax
639 foreach (@cust_credit_bill_pkg) {
640 my $billpkgnum = $_->billpkgnum;
641 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
642 $credits{$billpkgnum} ||= [];
643 push @{ $credits{$billpkgnum} }, $_;
645 TAX_ITEM: foreach my $tax_item (values %tax_items) {
646 my $billpkgnum = $tax_item->billpkgnum;
647 # get all pkg/location/taxrate allocations of this tax line item
648 my @allocations = sort {$b->amount <=> $a->amount}
649 qsearch('cust_bill_pkg_tax_location', {
650 billpkgnum => $billpkgnum
652 # and these are all credit applications to it
653 my @credits = sort {$b->amount <=> $a->amount}
654 @{ $credits{$billpkgnum} };
655 my $c = shift @credits;
656 my $a = shift @allocations; # we will NOT modify these
658 if ( abs($c->amount - $a->amount) < 0.005 ) {
659 # by far the most common case: the tax line item is for a single
660 # tax, so we just fill in the billpkgtaxlocationnum
661 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
662 my $error = $c->replace;
664 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
668 $a = shift @allocations;
669 } elsif ( $c->amount > $a->amount ) {
670 # fairly common: the tax line contains tax for multiple packages
671 # (or multiple taxes) but the credit isn't divided up
672 my $new_link = FS::cust_credit_bill_pkg->new({
673 creditbillnum => $c->creditbillnum,
674 billpkgnum => $c->billpkgnum,
675 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
676 amount => $a->amount,
677 setuprecur => 'setup',
679 my $error = $new_link->insert;
681 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
684 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
685 $a = shift @allocations;
686 } elsif ( $c->amount < 0.005 ) {
687 # also fairly common; we can delete these with no harm
688 my $error = $c->delete;
689 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
691 } elsif ( $c->amount < $a->amount ) {
692 # should never happen, but if it does, handle it gracefully
693 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
694 my $error = $c->replace;
696 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
699 $a->set(amount => $a->amount - $c->amount);
704 if ( $c->amount < 0.005 ) {
705 my $error = $c->delete;
706 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
707 } elsif ( $c->modified ) {
708 # then we've allocated part of it, so reduce the nonspecific
709 # application by that much
710 my $error = $c->replace;
711 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
713 # else there are probably no allocations, i.e. this is a pre-3.x
714 # record that was never migrated over, so leave it alone
716 } # foreach $tax_item
717 FS::upgrade_journal->set_done('cust_credit__tax_link');
729 Returns an SQL fragment to retreive the unapplied amount.
734 my ($class, $start, $end) = @_;
736 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
737 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
738 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
739 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
743 ( SELECT SUM(amount) FROM cust_credit_refund
744 WHERE cust_credit.crednum = cust_credit_refund.crednum
745 $refund_start $refund_end )
749 ( SELECT SUM(amount) FROM cust_credit_bill
750 WHERE cust_credit.crednum = cust_credit_bill.crednum
751 $bill_start $bill_end )
760 Deprecated name for the unapplied_sql method.
767 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
769 #$class->unapplied_sql(@_);
773 =item credit_lineitems
777 my $error = FS::cust_credit->credit_lineitems(
779 #the lineitems to credit
780 'billpkgnums' => \@billpkgnums,
781 'setuprecurs' => \@setuprecurs,
782 'amounts' => \@amounts,
783 'apply' => 1, #0 leaves the credit unapplied
786 map { $_ => scalar($cgi->param($_)) }
787 #fields('cust_credit')
788 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
794 #maybe i should just be an insert with extra args instead of a class method
795 sub credit_lineitems {
796 my( $class, %arg ) = @_;
797 my $curuser = $FS::CurrentUser::CurrentUser;
799 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
801 my $cust_main = qsearchs({
802 'table' => 'cust_main',
803 'hashref' => { 'custnum' => $arg{custnum} },
804 'extra_sql' => ' AND '. $curuser->agentnums_sql,
805 }) or return 'unknown customer';
808 local $SIG{HUP} = 'IGNORE';
809 local $SIG{INT} = 'IGNORE';
810 local $SIG{QUIT} = 'IGNORE';
811 local $SIG{TERM} = 'IGNORE';
812 local $SIG{TSTP} = 'IGNORE';
813 local $SIG{PIPE} = 'IGNORE';
815 my $oldAutoCommit = $FS::UID::AutoCommit;
816 local $FS::UID::AutoCommit = 0;
819 #my @cust_bill_pkg = qsearch({
820 # 'select' => 'cust_bill_pkg.*',
821 # 'table' => 'cust_bill_pkg',
822 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
823 # ' LEFT JOIN cust_main USING (custnum) ',
824 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
825 # join( ',', @{$arg{billpkgnums}} ). ')',
826 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
831 my $cust_credit = new FS::cust_credit ( {
832 map { $_ => $arg{$_} }
833 #fields('cust_credit')
834 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
836 $error = $cust_credit->insert;
838 $dbh->rollback if $oldAutoCommit;
839 return "Error inserting credit: $error";
842 unless ( $arg{'apply'} ) {
843 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
848 # keys in all of these are invoice numbers
849 my %cust_credit_bill = ();
850 my %cust_bill_pkg = ();
851 my %cust_credit_bill_pkg = ();
852 my %taxlisthash = ();
853 my %unapplied_payments = (); #invoice numbers, and then billpaynums
854 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
855 my $setuprecur = shift @{$arg{setuprecurs}};
856 my $amount = shift @{$arg{amounts}};
858 my $cust_bill_pkg = qsearchs({
859 'table' => 'cust_bill_pkg',
860 'hashref' => { 'billpkgnum' => $billpkgnum },
861 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
862 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
863 }) or die "unknown billpkgnum $billpkgnum";
865 my $invnum = $cust_bill_pkg->invnum;
867 if ( $setuprecur eq 'setup' ) {
868 $cust_bill_pkg->setup($amount);
869 $cust_bill_pkg->recur(0);
870 $cust_bill_pkg->unitrecur(0);
871 $cust_bill_pkg->type('');
873 $setuprecur = 'recur'; #in case its a usage classnum?
874 $cust_bill_pkg->recur($amount);
875 $cust_bill_pkg->setup(0);
876 $cust_bill_pkg->unitsetup(0);
879 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
881 #unapply any payments applied to this line item (other credits too?)
882 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
883 $error = $cust_bill_pay_pkg->delete;
885 $dbh->rollback if $oldAutoCommit;
886 return "Error unapplying payment: $error";
888 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
889 += $cust_bill_pay_pkg->amount;
892 #$subtotal += $amount;
893 $cust_credit_bill{$invnum} += $amount;
894 push @{ $cust_credit_bill_pkg{$invnum} },
895 new FS::cust_credit_bill_pkg {
896 'billpkgnum' => $cust_bill_pkg->billpkgnum,
897 'amount' => sprintf('%.2f',$amount),
898 'setuprecur' => $setuprecur,
899 'sdate' => $cust_bill_pkg->sdate,
900 'edate' => $cust_bill_pkg->edate,
903 # recalculate taxes with new amounts
904 $taxlisthash{$invnum} ||= {};
905 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
906 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
907 } # otherwise the item itself is a tax, and assume the caller knows
912 # now loop through %cust_credit_bill and insert those
915 # (hack to prevent cust_credit_bill_pkg insertion)
916 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
918 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
920 my $arrayref_or_error =
921 $cust_main->calculate_taxes(
922 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
923 $taxlisthash{$invnum}, # list of tax-item bindings
924 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
927 unless ( ref( $arrayref_or_error ) ) {
928 $dbh->rollback if $oldAutoCommit;
929 return "Error calculating taxes: $arrayref_or_error";
932 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
935 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
936 my $billpkgnum = $cust_bill_pkg->billpkgnum;
937 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
938 # gather up existing tax links (we need their billpkgtaxlocationnums)
939 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
940 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
942 foreach ( @tax_links ) {
943 $tax_links{$_->billpkgnum} ||= {};
944 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
948 foreach my $taxline ( @$arrayref_or_error ) {
950 my $amount = $taxline->setup;
952 # find equivalent tax line item on the existing invoice
953 my $tax_item = qsearchs('cust_bill_pkg', {
956 'itemdesc' => $taxline->desc,
959 # or should we just exit if this happens?
960 $cust_credit->set('amount',
961 sprintf('%.2f', $cust_credit->get('amount') - $amount)
963 my $error = $cust_credit->replace;
965 $dbh->rollback if $oldAutoCommit;
966 return "error correcting credit for missing tax line: $error";
970 # but in the new era, we no longer have the problem of uniquely
971 # identifying the tax_Xlocation record. The billpkgnums of the
972 # tax and the taxed item are known.
974 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
975 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
977 # the existing tax_Xlocation object
979 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
981 next if !$old_loc; # apply the leftover amount nonspecifically
983 #support partial credits: use $amount if smaller
984 # (so just distribute to the first location? perhaps should
986 my $loc_amount = min( $amount, $new_loc->amount);
988 $amount -= $loc_amount;
990 $cust_credit_bill{$invnum} += $loc_amount;
991 push @{ $cust_credit_bill_pkg{$invnum} },
992 new FS::cust_credit_bill_pkg {
993 'billpkgnum' => $tax_item->billpkgnum,
994 'amount' => $loc_amount,
995 'setuprecur' => 'setup',
996 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
997 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
1000 } #foreach my $new_loc
1002 # we still have to deal with the possibility that the tax links don't
1003 # cover the whole amount of tax because of an incomplete upgrade...
1004 if ($amount > 0.005) {
1005 $cust_credit_bill{$invnum} += $amount;
1006 push @{ $cust_credit_bill_pkg{$invnum} },
1007 new FS::cust_credit_bill_pkg {
1008 'billpkgnum' => $tax_item->billpkgnum,
1009 'amount' => sprintf('%.2f', $amount),
1010 'setuprecur' => 'setup',
1015 #unapply any payments applied to the tax
1016 foreach my $cust_bill_pay_pkg
1017 ( $tax_item->cust_bill_pay_pkg('setup') )
1019 $error = $cust_bill_pay_pkg->delete;
1021 $dbh->rollback if $oldAutoCommit;
1022 return "Error unapplying payment: $error";
1024 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
1025 += $cust_bill_pay_pkg->amount;
1029 # if we unapplied any payments from line items, also unapply that
1030 # amount from the invoice
1031 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1032 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1033 or die "broken payment application $billpaynum";
1034 my @subapps = $cust_bill_pay->lineitem_applications;
1035 $error = $cust_bill_pay->delete; # can't replace
1037 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1038 $cust_bill_pay->hash,
1040 amount => sprintf('%.2f',
1041 $cust_bill_pay->amount
1042 - $unapplied_payments{$invnum}{$billpaynum}),
1045 if ( $new_cust_bill_pay->amount > 0 ) {
1046 $error ||= $new_cust_bill_pay->insert;
1047 # Also reapply it to everything it was applied to before.
1048 # Note that we've already deleted cust_bill_pay_pkg records for the
1049 # items we're crediting, so they aren't on this list.
1050 foreach my $cust_bill_pay_pkg (@subapps) {
1051 $cust_bill_pay_pkg->billpaypkgnum('');
1052 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1053 $error ||= $cust_bill_pay_pkg->insert;
1057 $dbh->rollback if $oldAutoCommit;
1058 return "Error unapplying payment: $error";
1061 #insert cust_credit_bill
1063 my $cust_credit_bill = new FS::cust_credit_bill {
1064 'crednum' => $cust_credit->crednum,
1065 'invnum' => $invnum,
1066 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1068 $error = $cust_credit_bill->insert;
1070 $dbh->rollback if $oldAutoCommit;
1071 return "Error applying credit of $cust_credit_bill{$invnum} ".
1072 " to invoice $invnum: $error";
1075 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1076 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1077 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1078 $error = $cust_credit_bill_pkg->insert;
1080 $dbh->rollback if $oldAutoCommit;
1081 return "Error applying credit to line item: $error";
1087 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1098 =item process_batch_import
1102 use List::Util qw( min );
1104 use FS::cust_credit_bill;
1105 sub process_batch_import {
1108 my $opt = { 'table' => 'cust_credit',
1109 'params' => [ '_date', 'credbatch' ],
1110 'formats' => { 'simple' =>
1111 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1114 'postinsert_callback' => sub {
1115 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1117 if ( $cust_credit->invnum ) {
1119 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1120 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1122 my $cust_credit_bill = new FS::cust_credit_bill ( {
1123 'crednum' => $cust_credit->crednum,
1124 'invnum' => $cust_bill->invnum,
1125 'amount' => $amount,
1127 my $error = $cust_credit_bill->insert;
1128 return '' unless $error;
1132 #apply_payments_and_credits ?
1133 $cust_credit->cust_main->apply_credits;
1140 FS::Record::process_batch_import( $job, $opt, @_ );
1148 The delete method. The replace method.
1150 B<credited> and B<credited_sql> are now called B<unapplied> and
1151 B<unapplied_sql>. The old method names should start to give warnings.
1155 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1156 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base