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.
355 unless (ref($reason) || !$reason) {
356 $reason = FS::reason->new_or_existing(
358 'type' => 'Void credit',
363 local $SIG{HUP} = 'IGNORE';
364 local $SIG{INT} = 'IGNORE';
365 local $SIG{QUIT} = 'IGNORE';
366 local $SIG{TERM} = 'IGNORE';
367 local $SIG{TSTP} = 'IGNORE';
368 local $SIG{PIPE} = 'IGNORE';
370 my $oldAutoCommit = $FS::UID::AutoCommit;
371 local $FS::UID::AutoCommit = 0;
374 my $cust_credit_void = new FS::cust_credit_void ( {
375 map { $_ => $self->get($_) } $self->fields
377 $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
378 my $error = $cust_credit_void->insert;
380 $dbh->rollback if $oldAutoCommit;
384 $error = $self->delete(void => 1); # suppress deletecredits warning
386 $dbh->rollback if $oldAutoCommit;
390 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
396 =item cust_credit_refund
398 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
402 sub cust_credit_refund {
404 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
405 sort { $a->_date <=> $b->_date }
406 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
410 =item cust_credit_bill
412 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
417 sub cust_credit_bill {
419 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
420 sort { $a->_date <=> $b->_date }
421 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
427 Returns the amount of this credit that is still unapplied/outstanding;
428 amount minus all refund applications (see L<FS::cust_credit_refund>) and
429 applications to invoices (see L<FS::cust_credit_bill>).
435 my $amount = $self->amount;
436 $amount -= $_->amount foreach ( $self->cust_credit_refund );
437 $amount -= $_->amount foreach ( $self->cust_credit_bill );
438 sprintf( "%.2f", $amount );
443 Deprecated name for the unapplied method.
449 #carp "cust_credit->credited deprecated; use ->unapplied";
450 $self->unapplied(@_);
455 Returns the customer (see L<FS::cust_main>) for this credit.
461 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
467 Returns the text of the associated reason (see L<FS::reason>) for this credit.
472 my ($self, $value, %options) = @_;
475 my $typenum = $options{'reason_type'};
477 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
478 local $FS::UID::AutoCommit = 0; # a transaction if it matters
480 if ( defined( $value ) ) {
481 my $hashref = { 'reason' => $value };
482 $hashref->{'reason_type'} = $typenum if $typenum;
483 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
484 my $extra_sql = " AND reason_type.class='R'";
486 $reason = qsearchs( { 'table' => 'reason',
487 'hashref' => $hashref,
488 'addl_from' => $addl_from,
489 'extra_sql' => $extra_sql,
492 if (!$reason && $typenum) {
493 $reason = new FS::reason( { 'reason_type' => $typenum,
497 my $error = $reason->insert;
499 warn "error inserting reason: $error\n";
504 $self->reasonnum($reason ? $reason->reasonnum : '') ;
505 warn "$me reason used in set mode with non-existant reason -- clearing"
508 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
510 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
512 ( $reason ? $reason->reason : '' ).
513 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
518 # Used by FS::Upgrade to migrate to a new database.
520 sub _upgrade_data { # class method
521 my ($class, %opts) = @_;
523 warn "$me upgrading $class\n" if $DEBUG;
525 if (defined dbdef->table($class->table)->column('reason')) {
527 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
529 my @cust_credits = qsearch({ 'table' => $class->table,
531 'extra_sql' => 'WHERE reason IS NOT NULL',
534 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
535 warn "$me Found unmigrated reasons\n" if $DEBUG;
536 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
537 my $reason_type = qsearchs( 'reason_type', $hashref );
538 unless ($reason_type) {
539 $reason_type = new FS::reason_type( $hashref );
540 my $error = $reason_type->insert();
541 die "$class had error inserting FS::reason_type into database: $error\n"
545 $hashref = { 'reason_type' => $reason_type->typenum,
548 my $noreason = qsearchs( 'reason', $hashref );
550 $hashref->{'disabled'} = 'Y';
551 $noreason = new FS::reason( $hashref );
552 my $error = $noreason->insert();
553 die "can't insert legacy reason '(none)' into database: $error\n"
557 foreach my $cust_credit ( @cust_credits ) {
558 my $reason = $cust_credit->getfield('reason');
559 warn "Contemplating reason $reason\n" if $DEBUG > 1;
560 if ($reason =~ /\S/) {
561 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
562 or die "can't insert legacy reason $reason into database\n";
564 $cust_credit->reasonnum($noreason->reasonnum);
567 $cust_credit->setfield('reason', '');
568 my $error = $cust_credit->replace;
570 warn "*** WARNING: error replacing reason in $class ".
571 $cust_credit->crednum. ": $error ***\n"
576 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
578 foreach ( keys %reasontype_map ) {
579 unless ($conf->config($_)) { # hmmmm
580 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
581 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
582 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
583 my $reason_type = qsearchs( 'reason_type', $hashref );
584 unless ($reason_type) {
585 $reason_type = new FS::reason_type( $hashref );
586 my $error = $reason_type->insert();
587 die "$class had error inserting FS::reason_type into database: $error\n"
590 $conf->set($_, $reason_type->typenum);
594 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
596 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
597 my $reason_type = qsearchs( 'reason_type', $hashref );
598 unless ($reason_type) {
599 $reason_type = new FS::reason_type( $hashref );
600 my $error = $reason_type->insert();
601 die "$class had error inserting FS::reason_type into database: $error\n"
605 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
606 foreach my $plan ( @plans ) {
607 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
608 unless ($pkg->option('reason_type', 1) ) {
609 my $plandata = $pkg->plandata.
610 "reason_type=". $reason_type->typenum. "\n";
611 $pkg->plandata($plandata);
613 $pkg->replace( undef,
614 'pkg_svc' => { map { $_->svcpart => $_->quantity }
617 'primary_svc' => $pkg->svcpart,
619 die "failed setting reason_type option: $error"
626 local($otaker_upgrade_kludge) = 1;
627 local($ignore_empty_reasonnum) = 1;
628 $class->_upgrade_otaker(%opts);
630 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
631 and !$conf->exists('enable_taxproducts') ) {
632 # RT#25458: fix credit line item applications that should refer to a
633 # specific tax allocation
634 my @cust_credit_bill_pkg = qsearch({
635 table => 'cust_credit_bill_pkg',
636 select => 'cust_credit_bill_pkg.*',
637 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
639 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
640 'AND cust_bill_pkg.pkgnum = 0', # is a tax
644 foreach (@cust_credit_bill_pkg) {
645 my $billpkgnum = $_->billpkgnum;
646 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
647 $credits{$billpkgnum} ||= [];
648 push @{ $credits{$billpkgnum} }, $_;
650 TAX_ITEM: foreach my $tax_item (values %tax_items) {
651 my $billpkgnum = $tax_item->billpkgnum;
652 # get all pkg/location/taxrate allocations of this tax line item
653 my @allocations = sort {$b->amount <=> $a->amount}
654 qsearch('cust_bill_pkg_tax_location', {
655 billpkgnum => $billpkgnum
657 # and these are all credit applications to it
658 my @credits = sort {$b->amount <=> $a->amount}
659 @{ $credits{$billpkgnum} };
660 my $c = shift @credits;
661 my $a = shift @allocations; # we will NOT modify these
663 if ( abs($c->amount - $a->amount) < 0.005 ) {
664 # by far the most common case: the tax line item is for a single
665 # tax, so we just fill in the billpkgtaxlocationnum
666 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
667 my $error = $c->replace;
669 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
673 $a = shift @allocations;
674 } elsif ( $c->amount > $a->amount ) {
675 # fairly common: the tax line contains tax for multiple packages
676 # (or multiple taxes) but the credit isn't divided up
677 my $new_link = FS::cust_credit_bill_pkg->new({
678 creditbillnum => $c->creditbillnum,
679 billpkgnum => $c->billpkgnum,
680 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
681 amount => $a->amount,
682 setuprecur => 'setup',
684 my $error = $new_link->insert;
686 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
689 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
690 $a = shift @allocations;
691 } elsif ( $c->amount < 0.005 ) {
692 # also fairly common; we can delete these with no harm
693 my $error = $c->delete;
694 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
696 } elsif ( $c->amount < $a->amount ) {
697 # should never happen, but if it does, handle it gracefully
698 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
699 my $error = $c->replace;
701 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
704 $a->set(amount => $a->amount - $c->amount);
709 if ( $c->amount < 0.005 ) {
710 my $error = $c->delete;
711 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
712 } elsif ( $c->modified ) {
713 # then we've allocated part of it, so reduce the nonspecific
714 # application by that much
715 my $error = $c->replace;
716 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
718 # else there are probably no allocations, i.e. this is a pre-3.x
719 # record that was never migrated over, so leave it alone
721 } # foreach $tax_item
722 FS::upgrade_journal->set_done('cust_credit__tax_link');
734 Returns an SQL fragment to retreive the unapplied amount.
739 my ($class, $start, $end) = @_;
741 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
742 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
743 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
744 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
748 ( SELECT SUM(amount) FROM cust_credit_refund
749 WHERE cust_credit.crednum = cust_credit_refund.crednum
750 $refund_start $refund_end )
754 ( SELECT SUM(amount) FROM cust_credit_bill
755 WHERE cust_credit.crednum = cust_credit_bill.crednum
756 $bill_start $bill_end )
765 Deprecated name for the unapplied_sql method.
772 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
774 #$class->unapplied_sql(@_);
778 =item credit_lineitems
782 my $error = FS::cust_credit->credit_lineitems(
784 #the lineitems to credit
785 'billpkgnums' => \@billpkgnums,
786 'setuprecurs' => \@setuprecurs,
787 'amounts' => \@amounts,
788 'apply' => 1, #0 leaves the credit unapplied
791 map { $_ => scalar($cgi->param($_)) }
792 #fields('cust_credit')
793 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
799 #maybe i should just be an insert with extra args instead of a class method
800 sub credit_lineitems {
801 my( $class, %arg ) = @_;
802 my $curuser = $FS::CurrentUser::CurrentUser;
804 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
806 my $cust_main = qsearchs({
807 'table' => 'cust_main',
808 'hashref' => { 'custnum' => $arg{custnum} },
809 'extra_sql' => ' AND '. $curuser->agentnums_sql,
810 }) or return 'unknown customer';
813 local $SIG{HUP} = 'IGNORE';
814 local $SIG{INT} = 'IGNORE';
815 local $SIG{QUIT} = 'IGNORE';
816 local $SIG{TERM} = 'IGNORE';
817 local $SIG{TSTP} = 'IGNORE';
818 local $SIG{PIPE} = 'IGNORE';
820 my $oldAutoCommit = $FS::UID::AutoCommit;
821 local $FS::UID::AutoCommit = 0;
824 #my @cust_bill_pkg = qsearch({
825 # 'select' => 'cust_bill_pkg.*',
826 # 'table' => 'cust_bill_pkg',
827 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
828 # ' LEFT JOIN cust_main USING (custnum) ',
829 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
830 # join( ',', @{$arg{billpkgnums}} ). ')',
831 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
836 my $cust_credit = new FS::cust_credit ( {
837 map { $_ => $arg{$_} }
838 #fields('cust_credit')
839 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
841 $error = $cust_credit->insert;
843 $dbh->rollback if $oldAutoCommit;
844 return "Error inserting credit: $error";
847 unless ( $arg{'apply'} ) {
848 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
853 # keys in all of these are invoice numbers
854 my %cust_credit_bill = ();
855 my %cust_bill_pkg = ();
856 my %cust_credit_bill_pkg = ();
857 my %taxlisthash = ();
858 my %unapplied_payments = (); #invoice numbers, and then billpaynums
859 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
860 my $setuprecur = shift @{$arg{setuprecurs}};
861 my $amount = shift @{$arg{amounts}};
863 my $cust_bill_pkg = qsearchs({
864 'table' => 'cust_bill_pkg',
865 'hashref' => { 'billpkgnum' => $billpkgnum },
866 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
867 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
868 }) or die "unknown billpkgnum $billpkgnum";
870 my $invnum = $cust_bill_pkg->invnum;
872 if ( $setuprecur eq 'setup' ) {
873 $cust_bill_pkg->setup($amount);
874 $cust_bill_pkg->recur(0);
875 $cust_bill_pkg->unitrecur(0);
876 $cust_bill_pkg->type('');
878 $setuprecur = 'recur'; #in case its a usage classnum?
879 $cust_bill_pkg->recur($amount);
880 $cust_bill_pkg->setup(0);
881 $cust_bill_pkg->unitsetup(0);
884 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
886 #unapply any payments applied to this line item (other credits too?)
887 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
888 $error = $cust_bill_pay_pkg->delete;
890 $dbh->rollback if $oldAutoCommit;
891 return "Error unapplying payment: $error";
893 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
894 += $cust_bill_pay_pkg->amount;
897 #$subtotal += $amount;
898 $cust_credit_bill{$invnum} += $amount;
899 push @{ $cust_credit_bill_pkg{$invnum} },
900 new FS::cust_credit_bill_pkg {
901 'billpkgnum' => $cust_bill_pkg->billpkgnum,
902 'amount' => sprintf('%.2f',$amount),
903 'setuprecur' => $setuprecur,
904 'sdate' => $cust_bill_pkg->sdate,
905 'edate' => $cust_bill_pkg->edate,
908 # recalculate taxes with new amounts
909 $taxlisthash{$invnum} ||= {};
910 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
911 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
912 } # otherwise the item itself is a tax, and assume the caller knows
917 # now loop through %cust_credit_bill and insert those
920 # (hack to prevent cust_credit_bill_pkg insertion)
921 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
923 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
925 my $arrayref_or_error =
926 $cust_main->calculate_taxes(
927 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
928 $taxlisthash{$invnum}, # list of tax-item bindings
929 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
932 unless ( ref( $arrayref_or_error ) ) {
933 $dbh->rollback if $oldAutoCommit;
934 return "Error calculating taxes: $arrayref_or_error";
937 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
940 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
941 my $billpkgnum = $cust_bill_pkg->billpkgnum;
942 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
943 # gather up existing tax links (we need their billpkgtaxlocationnums)
944 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
945 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
947 foreach ( @tax_links ) {
948 $tax_links{$_->billpkgnum} ||= {};
949 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
953 foreach my $taxline ( @$arrayref_or_error ) {
955 my $amount = $taxline->setup;
957 # find equivalent tax line item on the existing invoice
958 my $tax_item = qsearchs('cust_bill_pkg', {
961 'itemdesc' => $taxline->desc,
964 # or should we just exit if this happens?
965 $cust_credit->set('amount',
966 sprintf('%.2f', $cust_credit->get('amount') - $amount)
968 my $error = $cust_credit->replace;
970 $dbh->rollback if $oldAutoCommit;
971 return "error correcting credit for missing tax line: $error";
975 # but in the new era, we no longer have the problem of uniquely
976 # identifying the tax_Xlocation record. The billpkgnums of the
977 # tax and the taxed item are known.
979 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
980 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
982 # the existing tax_Xlocation object
984 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
986 next if !$old_loc; # apply the leftover amount nonspecifically
988 #support partial credits: use $amount if smaller
989 # (so just distribute to the first location? perhaps should
991 my $loc_amount = min( $amount, $new_loc->amount);
993 $amount -= $loc_amount;
995 $cust_credit_bill{$invnum} += $loc_amount;
996 push @{ $cust_credit_bill_pkg{$invnum} },
997 new FS::cust_credit_bill_pkg {
998 'billpkgnum' => $tax_item->billpkgnum,
999 'amount' => $loc_amount,
1000 'setuprecur' => 'setup',
1001 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
1002 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
1005 } #foreach my $new_loc
1007 # we still have to deal with the possibility that the tax links don't
1008 # cover the whole amount of tax because of an incomplete upgrade...
1009 if ($amount > 0.005) {
1010 $cust_credit_bill{$invnum} += $amount;
1011 push @{ $cust_credit_bill_pkg{$invnum} },
1012 new FS::cust_credit_bill_pkg {
1013 'billpkgnum' => $tax_item->billpkgnum,
1014 'amount' => sprintf('%.2f', $amount),
1015 'setuprecur' => 'setup',
1020 #unapply any payments applied to the tax
1021 foreach my $cust_bill_pay_pkg
1022 ( $tax_item->cust_bill_pay_pkg('setup') )
1024 $error = $cust_bill_pay_pkg->delete;
1026 $dbh->rollback if $oldAutoCommit;
1027 return "Error unapplying payment: $error";
1029 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
1030 += $cust_bill_pay_pkg->amount;
1034 # if we unapplied any payments from line items, also unapply that
1035 # amount from the invoice
1036 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1037 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1038 or die "broken payment application $billpaynum";
1039 my @subapps = $cust_bill_pay->lineitem_applications;
1040 $error = $cust_bill_pay->delete; # can't replace
1042 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1043 $cust_bill_pay->hash,
1045 amount => sprintf('%.2f',
1046 $cust_bill_pay->amount
1047 - $unapplied_payments{$invnum}{$billpaynum}),
1050 if ( $new_cust_bill_pay->amount > 0 ) {
1051 $error ||= $new_cust_bill_pay->insert;
1052 # Also reapply it to everything it was applied to before.
1053 # Note that we've already deleted cust_bill_pay_pkg records for the
1054 # items we're crediting, so they aren't on this list.
1055 foreach my $cust_bill_pay_pkg (@subapps) {
1056 $cust_bill_pay_pkg->billpaypkgnum('');
1057 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1058 $error ||= $cust_bill_pay_pkg->insert;
1062 $dbh->rollback if $oldAutoCommit;
1063 return "Error unapplying payment: $error";
1066 #insert cust_credit_bill
1068 my $cust_credit_bill = new FS::cust_credit_bill {
1069 'crednum' => $cust_credit->crednum,
1070 'invnum' => $invnum,
1071 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1073 $error = $cust_credit_bill->insert;
1075 $dbh->rollback if $oldAutoCommit;
1076 return "Error applying credit of $cust_credit_bill{$invnum} ".
1077 " to invoice $invnum: $error";
1080 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1081 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1082 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1083 $error = $cust_credit_bill_pkg->insert;
1085 $dbh->rollback if $oldAutoCommit;
1086 return "Error applying credit to line item: $error";
1092 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1103 =item process_batch_import
1107 use List::Util qw( min );
1109 use FS::cust_credit_bill;
1110 sub process_batch_import {
1113 my $opt = { 'table' => 'cust_credit',
1114 'params' => [ '_date', 'credbatch' ],
1115 'formats' => { 'simple' =>
1116 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1119 'postinsert_callback' => sub {
1120 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1122 if ( $cust_credit->invnum ) {
1124 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1125 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1127 my $cust_credit_bill = new FS::cust_credit_bill ( {
1128 'crednum' => $cust_credit->crednum,
1129 'invnum' => $cust_bill->invnum,
1130 'amount' => $amount,
1132 my $error = $cust_credit_bill->insert;
1133 return '' unless $error;
1137 #apply_payments_and_credits ?
1138 $cust_credit->cust_main->apply_credits;
1145 FS::Record::process_batch_import( $job, $opt, @_ );
1153 The delete method. The replace method.
1155 B<credited> and B<credited_sql> are now called B<unapplied> and
1156 B<unapplied_sql>. The old method names should start to give warnings.
1160 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1161 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base