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->config('invoice_from_name', $self->cust_main->agentnum) ?
252 $conf->config('invoice_from_name', $self->cust_main->agentnum) . ' <' .
253 $conf->config('invoice_from', $self->cust_main->agentnum) . '>' :
254 $conf->config('invoice_from', $self->cust_main->agentnum),
255 #invoice_from??? well as good as any
256 'to' => $conf->config('deletecredits'),
257 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
259 "This is an automatic message from your Freeside installation\n",
260 "informing you that the following credit has been deleted:\n",
262 'crednum: '. $self->crednum. "\n",
263 'custnum: '. $self->custnum.
264 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
265 'amount: $'. sprintf("%.2f", $self->amount). "\n",
266 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
267 'reason: '. $self->reason. "\n",
272 $dbh->rollback if $oldAutoCommit;
273 return "can't send credit deletion notification: $error";
278 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
284 =item replace [ OLD_RECORD ]
286 You can, but probably shouldn't modify credits...
288 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
289 supplied, replaces this record. If there is an error, returns the error,
290 otherwise returns false.
296 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
297 $self->SUPER::replace(@_);
302 Checks all fields to make sure this is a valid credit. If there is an error,
303 returns the error, otherwise returns false. Called by the insert and replace
311 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
314 $self->ut_numbern('crednum')
315 || $self->ut_number('custnum')
316 || $self->ut_numbern('_date')
317 || $self->ut_money('amount')
318 || $self->ut_alphan('otaker')
319 || $self->ut_textn('reason')
320 || $self->ut_textn('addlinfo')
321 || $self->ut_enum('closed', [ '', 'Y' ])
322 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
323 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
324 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
325 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
326 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
328 return $error if $error;
330 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
331 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
332 return $error if $error;
334 return "amount must be > 0 " if $self->amount <= 0;
336 return "amount must be greater or equal to amount applied"
337 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
339 return "Unknown customer"
340 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
342 $self->_date(time) unless $self->_date;
347 =item void [ REASON ]
349 Voids this credit: deletes the credit and all associated applications and
350 adds a record of the voided credit to the cust_credit_void table.
354 # yes, false laziness with cust_pay and cust_bill
355 # but frankly I don't have time to fix it now
361 local $SIG{HUP} = 'IGNORE';
362 local $SIG{INT} = 'IGNORE';
363 local $SIG{QUIT} = 'IGNORE';
364 local $SIG{TERM} = 'IGNORE';
365 local $SIG{TSTP} = 'IGNORE';
366 local $SIG{PIPE} = 'IGNORE';
368 my $oldAutoCommit = $FS::UID::AutoCommit;
369 local $FS::UID::AutoCommit = 0;
372 my $cust_credit_void = new FS::cust_credit_void ( {
373 map { $_ => $self->get($_) } $self->fields
375 $cust_credit_void->set('void_reason', $reason);
376 my $error = $cust_credit_void->insert;
378 $dbh->rollback if $oldAutoCommit;
382 $error = $self->delete(void => 1); # suppress deletecredits warning
384 $dbh->rollback if $oldAutoCommit;
388 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
394 =item cust_credit_refund
396 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
400 sub cust_credit_refund {
402 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
403 sort { $a->_date <=> $b->_date }
404 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
408 =item cust_credit_bill
410 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
415 sub cust_credit_bill {
417 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
418 sort { $a->_date <=> $b->_date }
419 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
425 Returns the amount of this credit that is still unapplied/outstanding;
426 amount minus all refund applications (see L<FS::cust_credit_refund>) and
427 applications to invoices (see L<FS::cust_credit_bill>).
433 my $amount = $self->amount;
434 $amount -= $_->amount foreach ( $self->cust_credit_refund );
435 $amount -= $_->amount foreach ( $self->cust_credit_bill );
436 sprintf( "%.2f", $amount );
441 Deprecated name for the unapplied method.
447 #carp "cust_credit->credited deprecated; use ->unapplied";
448 $self->unapplied(@_);
453 Returns the customer (see L<FS::cust_main>) for this credit.
459 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
465 Returns the text of the associated reason (see L<FS::reason>) for this credit.
470 my ($self, $value, %options) = @_;
473 my $typenum = $options{'reason_type'};
475 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
476 local $FS::UID::AutoCommit = 0; # a transaction if it matters
478 if ( defined( $value ) ) {
479 my $hashref = { 'reason' => $value };
480 $hashref->{'reason_type'} = $typenum if $typenum;
481 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
482 my $extra_sql = " AND reason_type.class='R'";
484 $reason = qsearchs( { 'table' => 'reason',
485 'hashref' => $hashref,
486 'addl_from' => $addl_from,
487 'extra_sql' => $extra_sql,
490 if (!$reason && $typenum) {
491 $reason = new FS::reason( { 'reason_type' => $typenum,
495 my $error = $reason->insert;
497 warn "error inserting reason: $error\n";
502 $self->reasonnum($reason ? $reason->reasonnum : '') ;
503 warn "$me reason used in set mode with non-existant reason -- clearing"
506 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
508 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
510 ( $reason ? $reason->reason : '' ).
511 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
516 # Used by FS::Upgrade to migrate to a new database.
518 sub _upgrade_data { # class method
519 my ($class, %opts) = @_;
521 warn "$me upgrading $class\n" if $DEBUG;
523 if (defined dbdef->table($class->table)->column('reason')) {
525 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
527 my @cust_credits = qsearch({ 'table' => $class->table,
529 'extra_sql' => 'WHERE reason IS NOT NULL',
532 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
533 warn "$me Found unmigrated reasons\n" if $DEBUG;
534 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
535 my $reason_type = qsearchs( 'reason_type', $hashref );
536 unless ($reason_type) {
537 $reason_type = new FS::reason_type( $hashref );
538 my $error = $reason_type->insert();
539 die "$class had error inserting FS::reason_type into database: $error\n"
543 $hashref = { 'reason_type' => $reason_type->typenum,
546 my $noreason = qsearchs( 'reason', $hashref );
548 $hashref->{'disabled'} = 'Y';
549 $noreason = new FS::reason( $hashref );
550 my $error = $noreason->insert();
551 die "can't insert legacy reason '(none)' into database: $error\n"
555 foreach my $cust_credit ( @cust_credits ) {
556 my $reason = $cust_credit->getfield('reason');
557 warn "Contemplating reason $reason\n" if $DEBUG > 1;
558 if ($reason =~ /\S/) {
559 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
560 or die "can't insert legacy reason $reason into database\n";
562 $cust_credit->reasonnum($noreason->reasonnum);
565 $cust_credit->setfield('reason', '');
566 my $error = $cust_credit->replace;
568 warn "*** WARNING: error replacing reason in $class ".
569 $cust_credit->crednum. ": $error ***\n"
574 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
576 foreach ( keys %reasontype_map ) {
577 unless ($conf->config($_)) { # hmmmm
578 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
579 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
580 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
581 my $reason_type = qsearchs( 'reason_type', $hashref );
582 unless ($reason_type) {
583 $reason_type = new FS::reason_type( $hashref );
584 my $error = $reason_type->insert();
585 die "$class had error inserting FS::reason_type into database: $error\n"
588 $conf->set($_, $reason_type->typenum);
592 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
594 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
595 my $reason_type = qsearchs( 'reason_type', $hashref );
596 unless ($reason_type) {
597 $reason_type = new FS::reason_type( $hashref );
598 my $error = $reason_type->insert();
599 die "$class had error inserting FS::reason_type into database: $error\n"
603 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
604 foreach my $plan ( @plans ) {
605 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
606 unless ($pkg->option('reason_type', 1) ) {
607 my $plandata = $pkg->plandata.
608 "reason_type=". $reason_type->typenum. "\n";
609 $pkg->plandata($plandata);
611 $pkg->replace( undef,
612 'pkg_svc' => { map { $_->svcpart => $_->quantity }
615 'primary_svc' => $pkg->svcpart,
617 die "failed setting reason_type option: $error"
624 local($otaker_upgrade_kludge) = 1;
625 local($ignore_empty_reasonnum) = 1;
626 $class->_upgrade_otaker(%opts);
628 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
629 and !$conf->exists('enable_taxproducts') ) {
630 # RT#25458: fix credit line item applications that should refer to a
631 # specific tax allocation
632 my @cust_credit_bill_pkg = qsearch({
633 table => 'cust_credit_bill_pkg',
634 select => 'cust_credit_bill_pkg.*',
635 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
637 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
638 'AND cust_bill_pkg.pkgnum = 0', # is a tax
642 foreach (@cust_credit_bill_pkg) {
643 my $billpkgnum = $_->billpkgnum;
644 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
645 $credits{$billpkgnum} ||= [];
646 push @{ $credits{$billpkgnum} }, $_;
648 TAX_ITEM: foreach my $tax_item (values %tax_items) {
649 my $billpkgnum = $tax_item->billpkgnum;
650 # get all pkg/location/taxrate allocations of this tax line item
651 my @allocations = sort {$b->amount <=> $a->amount}
652 qsearch('cust_bill_pkg_tax_location', {
653 billpkgnum => $billpkgnum
655 # and these are all credit applications to it
656 my @credits = sort {$b->amount <=> $a->amount}
657 @{ $credits{$billpkgnum} };
658 my $c = shift @credits;
659 my $a = shift @allocations; # we will NOT modify these
661 if ( abs($c->amount - $a->amount) < 0.005 ) {
662 # by far the most common case: the tax line item is for a single
663 # tax, so we just fill in the billpkgtaxlocationnum
664 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
665 my $error = $c->replace;
667 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
671 $a = shift @allocations;
672 } elsif ( $c->amount > $a->amount ) {
673 # fairly common: the tax line contains tax for multiple packages
674 # (or multiple taxes) but the credit isn't divided up
675 my $new_link = FS::cust_credit_bill_pkg->new({
676 creditbillnum => $c->creditbillnum,
677 billpkgnum => $c->billpkgnum,
678 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
679 amount => $a->amount,
680 setuprecur => 'setup',
682 my $error = $new_link->insert;
684 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
687 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
688 $a = shift @allocations;
689 } elsif ( $c->amount < 0.005 ) {
690 # also fairly common; we can delete these with no harm
691 my $error = $c->delete;
692 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
694 } elsif ( $c->amount < $a->amount ) {
695 # should never happen, but if it does, handle it gracefully
696 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
697 my $error = $c->replace;
699 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
702 $a->set(amount => $a->amount - $c->amount);
707 if ( $c->amount < 0.005 ) {
708 my $error = $c->delete;
709 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
710 } elsif ( $c->modified ) {
711 # then we've allocated part of it, so reduce the nonspecific
712 # application by that much
713 my $error = $c->replace;
714 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
716 # else there are probably no allocations, i.e. this is a pre-3.x
717 # record that was never migrated over, so leave it alone
719 } # foreach $tax_item
720 FS::upgrade_journal->set_done('cust_credit__tax_link');
732 Returns an SQL fragment to retreive the unapplied amount.
737 my ($class, $start, $end) = @_;
739 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
740 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
741 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
742 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
746 ( SELECT SUM(amount) FROM cust_credit_refund
747 WHERE cust_credit.crednum = cust_credit_refund.crednum
748 $refund_start $refund_end )
752 ( SELECT SUM(amount) FROM cust_credit_bill
753 WHERE cust_credit.crednum = cust_credit_bill.crednum
754 $bill_start $bill_end )
763 Deprecated name for the unapplied_sql method.
770 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
772 #$class->unapplied_sql(@_);
776 =item credit_lineitems
780 my $error = FS::cust_credit->credit_lineitems(
782 #the lineitems to credit
783 'billpkgnums' => \@billpkgnums,
784 'setuprecurs' => \@setuprecurs,
785 'amounts' => \@amounts,
786 'apply' => 1, #0 leaves the credit unapplied
789 map { $_ => scalar($cgi->param($_)) }
790 #fields('cust_credit')
791 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
797 #maybe i should just be an insert with extra args instead of a class method
798 sub credit_lineitems {
799 my( $class, %arg ) = @_;
800 my $curuser = $FS::CurrentUser::CurrentUser;
802 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
804 my $cust_main = qsearchs({
805 'table' => 'cust_main',
806 'hashref' => { 'custnum' => $arg{custnum} },
807 'extra_sql' => ' AND '. $curuser->agentnums_sql,
808 }) or return 'unknown customer';
811 local $SIG{HUP} = 'IGNORE';
812 local $SIG{INT} = 'IGNORE';
813 local $SIG{QUIT} = 'IGNORE';
814 local $SIG{TERM} = 'IGNORE';
815 local $SIG{TSTP} = 'IGNORE';
816 local $SIG{PIPE} = 'IGNORE';
818 my $oldAutoCommit = $FS::UID::AutoCommit;
819 local $FS::UID::AutoCommit = 0;
822 #my @cust_bill_pkg = qsearch({
823 # 'select' => 'cust_bill_pkg.*',
824 # 'table' => 'cust_bill_pkg',
825 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
826 # ' LEFT JOIN cust_main USING (custnum) ',
827 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
828 # join( ',', @{$arg{billpkgnums}} ). ')',
829 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
834 my $cust_credit = new FS::cust_credit ( {
835 map { $_ => $arg{$_} }
836 #fields('cust_credit')
837 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
839 $error = $cust_credit->insert;
841 $dbh->rollback if $oldAutoCommit;
842 return "Error inserting credit: $error";
845 unless ( $arg{'apply'} ) {
846 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
851 # keys in all of these are invoice numbers
852 my %cust_credit_bill = ();
853 my %cust_bill_pkg = ();
854 my %cust_credit_bill_pkg = ();
855 my %taxlisthash = ();
856 my %unapplied_payments = (); #invoice numbers, and then billpaynums
857 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
858 my $setuprecur = shift @{$arg{setuprecurs}};
859 my $amount = shift @{$arg{amounts}};
861 my $cust_bill_pkg = qsearchs({
862 'table' => 'cust_bill_pkg',
863 'hashref' => { 'billpkgnum' => $billpkgnum },
864 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
865 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
866 }) or die "unknown billpkgnum $billpkgnum";
868 my $invnum = $cust_bill_pkg->invnum;
870 if ( $setuprecur eq 'setup' ) {
871 $cust_bill_pkg->setup($amount);
872 $cust_bill_pkg->recur(0);
873 $cust_bill_pkg->unitrecur(0);
874 $cust_bill_pkg->type('');
876 $setuprecur = 'recur'; #in case its a usage classnum?
877 $cust_bill_pkg->recur($amount);
878 $cust_bill_pkg->setup(0);
879 $cust_bill_pkg->unitsetup(0);
882 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
884 #unapply any payments applied to this line item (other credits too?)
885 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
886 $error = $cust_bill_pay_pkg->delete;
888 $dbh->rollback if $oldAutoCommit;
889 return "Error unapplying payment: $error";
891 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
892 += $cust_bill_pay_pkg->amount;
895 #$subtotal += $amount;
896 $cust_credit_bill{$invnum} += $amount;
897 push @{ $cust_credit_bill_pkg{$invnum} },
898 new FS::cust_credit_bill_pkg {
899 'billpkgnum' => $cust_bill_pkg->billpkgnum,
900 'amount' => sprintf('%.2f',$amount),
901 'setuprecur' => $setuprecur,
902 'sdate' => $cust_bill_pkg->sdate,
903 'edate' => $cust_bill_pkg->edate,
906 # recalculate taxes with new amounts
907 $taxlisthash{$invnum} ||= {};
908 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
909 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
910 } # otherwise the item itself is a tax, and assume the caller knows
915 # now loop through %cust_credit_bill and insert those
918 # (hack to prevent cust_credit_bill_pkg insertion)
919 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
921 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
923 my $arrayref_or_error =
924 $cust_main->calculate_taxes(
925 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
926 $taxlisthash{$invnum}, # list of tax-item bindings
927 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
930 unless ( ref( $arrayref_or_error ) ) {
931 $dbh->rollback if $oldAutoCommit;
932 return "Error calculating taxes: $arrayref_or_error";
935 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
938 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
939 my $billpkgnum = $cust_bill_pkg->billpkgnum;
940 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
941 # gather up existing tax links (we need their billpkgtaxlocationnums)
942 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
943 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
945 foreach ( @tax_links ) {
946 $tax_links{$_->billpkgnum} ||= {};
947 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
951 foreach my $taxline ( @$arrayref_or_error ) {
953 my $amount = $taxline->setup;
955 # find equivalent tax line item on the existing invoice
956 my $tax_item = qsearchs('cust_bill_pkg', {
959 'itemdesc' => $taxline->desc,
962 # or should we just exit if this happens?
963 $cust_credit->set('amount',
964 sprintf('%.2f', $cust_credit->get('amount') - $amount)
966 my $error = $cust_credit->replace;
968 $dbh->rollback if $oldAutoCommit;
969 return "error correcting credit for missing tax line: $error";
973 # but in the new era, we no longer have the problem of uniquely
974 # identifying the tax_Xlocation record. The billpkgnums of the
975 # tax and the taxed item are known.
977 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
978 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
980 # the existing tax_Xlocation object
982 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
984 next if !$old_loc; # apply the leftover amount nonspecifically
986 #support partial credits: use $amount if smaller
987 # (so just distribute to the first location? perhaps should
989 my $loc_amount = min( $amount, $new_loc->amount);
991 $amount -= $loc_amount;
993 $cust_credit_bill{$invnum} += $loc_amount;
994 push @{ $cust_credit_bill_pkg{$invnum} },
995 new FS::cust_credit_bill_pkg {
996 'billpkgnum' => $tax_item->billpkgnum,
997 'amount' => $loc_amount,
998 'setuprecur' => 'setup',
999 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
1000 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
1003 } #foreach my $new_loc
1005 # we still have to deal with the possibility that the tax links don't
1006 # cover the whole amount of tax because of an incomplete upgrade...
1007 if ($amount > 0.005) {
1008 $cust_credit_bill{$invnum} += $amount;
1009 push @{ $cust_credit_bill_pkg{$invnum} },
1010 new FS::cust_credit_bill_pkg {
1011 'billpkgnum' => $tax_item->billpkgnum,
1012 'amount' => sprintf('%.2f', $amount),
1013 'setuprecur' => 'setup',
1018 #unapply any payments applied to the tax
1019 foreach my $cust_bill_pay_pkg
1020 ( $tax_item->cust_bill_pay_pkg('setup') )
1022 $error = $cust_bill_pay_pkg->delete;
1024 $dbh->rollback if $oldAutoCommit;
1025 return "Error unapplying payment: $error";
1027 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
1028 += $cust_bill_pay_pkg->amount;
1032 # if we unapplied any payments from line items, also unapply that
1033 # amount from the invoice
1034 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1035 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1036 or die "broken payment application $billpaynum";
1037 my @subapps = $cust_bill_pay->lineitem_applications;
1038 $error = $cust_bill_pay->delete; # can't replace
1040 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1041 $cust_bill_pay->hash,
1043 amount => sprintf('%.2f',
1044 $cust_bill_pay->amount
1045 - $unapplied_payments{$invnum}{$billpaynum}),
1048 if ( $new_cust_bill_pay->amount > 0 ) {
1049 $error ||= $new_cust_bill_pay->insert;
1050 # Also reapply it to everything it was applied to before.
1051 # Note that we've already deleted cust_bill_pay_pkg records for the
1052 # items we're crediting, so they aren't on this list.
1053 foreach my $cust_bill_pay_pkg (@subapps) {
1054 $cust_bill_pay_pkg->billpaypkgnum('');
1055 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1056 $error ||= $cust_bill_pay_pkg->insert;
1060 $dbh->rollback if $oldAutoCommit;
1061 return "Error unapplying payment: $error";
1064 #insert cust_credit_bill
1066 my $cust_credit_bill = new FS::cust_credit_bill {
1067 'crednum' => $cust_credit->crednum,
1068 'invnum' => $invnum,
1069 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1071 $error = $cust_credit_bill->insert;
1073 $dbh->rollback if $oldAutoCommit;
1074 return "Error applying credit of $cust_credit_bill{$invnum} ".
1075 " to invoice $invnum: $error";
1078 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1079 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1080 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1081 $error = $cust_credit_bill_pkg->insert;
1083 $dbh->rollback if $oldAutoCommit;
1084 return "Error applying credit to line item: $error";
1090 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1101 =item process_batch_import
1105 use List::Util qw( min );
1107 use FS::cust_credit_bill;
1108 sub process_batch_import {
1111 my $opt = { 'table' => 'cust_credit',
1112 'params' => [ '_date', 'credbatch' ],
1113 'formats' => { 'simple' =>
1114 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1117 'postinsert_callback' => sub {
1118 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1120 if ( $cust_credit->invnum ) {
1122 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1123 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1125 my $cust_credit_bill = new FS::cust_credit_bill ( {
1126 'crednum' => $cust_credit->crednum,
1127 'invnum' => $cust_bill->invnum,
1128 'amount' => $amount,
1130 my $error = $cust_credit_bill->insert;
1131 return '' unless $error;
1135 #apply_payments_and_credits ?
1136 $cust_credit->cust_main->apply_credits;
1143 FS::Record::process_batch_import( $job, $opt, @_ );
1151 The delete method. The replace method.
1153 B<credited> and B<credited_sql> are now called B<unapplied> and
1154 B<unapplied_sql>. The old method names should start to give warnings.
1158 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1159 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base