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',
48 FS::cust_credit - Object methods for cust_credit records
54 $record = new FS::cust_credit \%hash;
55 $record = new FS::cust_credit { 'column' => 'value' };
57 $error = $record->insert;
59 $error = $new_record->replace($old_record);
61 $error = $record->delete;
63 $error = $record->check;
67 An FS::cust_credit object represents a credit; the equivalent of a negative
68 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
69 FS::Record. The following fields are currently supported:
75 Primary key (assigned automatically for new credits)
79 Customer (see L<FS::cust_main>)
87 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
88 L<Time::Local> and L<Date::Parse> for conversion functions.
92 Order taker (see L<FS::access_user>)
100 Reason (see L<FS::reason>)
108 Books closed flag, empty or `Y'
112 Desired pkgnum when using experimental package balances.
122 Creates a new credit. To add the credit to the database, see L<"insert">.
126 sub table { 'cust_credit'; }
127 sub cust_linked { $_[0]->cust_main_custnum; }
128 sub cust_unlinked_msg {
130 "WARNING: can't find cust_main.custnum ". $self->custnum.
131 ' (cust_credit.crednum '. $self->crednum. ')';
136 Adds this credit to the database ("Posts" the credit). If there is an error,
137 returns the error, otherwise returns false.
142 my ($self, %options) = @_;
144 local $SIG{HUP} = 'IGNORE';
145 local $SIG{INT} = 'IGNORE';
146 local $SIG{QUIT} = 'IGNORE';
147 local $SIG{TERM} = 'IGNORE';
148 local $SIG{TSTP} = 'IGNORE';
149 local $SIG{PIPE} = 'IGNORE';
151 my $oldAutoCommit = $FS::UID::AutoCommit;
152 local $FS::UID::AutoCommit = 0;
155 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
156 my $old_balance = $cust_main->balance;
158 unless ($self->reasonnum) {
159 my $result = $self->reason( $self->getfield('reason'),
160 exists($options{ 'reason_type' })
161 ? ('reason_type' => $options{ 'reason_type' })
165 $dbh->rollback if $oldAutoCommit;
166 return "failed to set reason for $me"; #: ". $dbh->errstr;
170 $self->setfield('reason', '');
172 my $error = $self->SUPER::insert;
174 $dbh->rollback if $oldAutoCommit;
175 return "error inserting $self: $error";
178 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
180 #false laziness w/ cust_pay::insert
181 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
182 my @errors = $cust_main->unsuspend;
184 # side-fx with nested transactions? upstack rolls back?
185 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
191 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
199 Unless the closed flag is set, deletes this credit and all associated
200 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
201 the void method instead to leave a record of the deleted credit.
205 # very similar to FS::cust_pay::delete
210 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
212 local $SIG{HUP} = 'IGNORE';
213 local $SIG{INT} = 'IGNORE';
214 local $SIG{QUIT} = 'IGNORE';
215 local $SIG{TERM} = 'IGNORE';
216 local $SIG{TSTP} = 'IGNORE';
217 local $SIG{PIPE} = 'IGNORE';
219 my $oldAutoCommit = $FS::UID::AutoCommit;
220 local $FS::UID::AutoCommit = 0;
223 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
224 my $error = $cust_credit_bill->delete;
226 $dbh->rollback if $oldAutoCommit;
231 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
232 my $error = $cust_credit_refund->delete;
234 $dbh->rollback if $oldAutoCommit;
239 my $error = $self->SUPER::delete(@_);
241 $dbh->rollback if $oldAutoCommit;
245 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
247 my $cust_main = $self->cust_main;
249 my $error = send_email(
250 'from' => $conf->invoice_from_full($self->cust_main->agentnum),
251 #invoice_from??? well as good as any
252 'to' => $conf->config('deletecredits'),
253 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
255 "This is an automatic message from your Freeside installation\n",
256 "informing you that the following credit has been deleted:\n",
258 'crednum: '. $self->crednum. "\n",
259 'custnum: '. $self->custnum.
260 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
261 'amount: $'. sprintf("%.2f", $self->amount). "\n",
262 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
263 'reason: '. $self->reason. "\n",
268 $dbh->rollback if $oldAutoCommit;
269 return "can't send credit deletion notification: $error";
274 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280 =item replace [ OLD_RECORD ]
282 You can, but probably shouldn't modify credits...
284 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
285 supplied, replaces this record. If there is an error, returns the error,
286 otherwise returns false.
292 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
293 $self->SUPER::replace(@_);
298 Checks all fields to make sure this is a valid credit. If there is an error,
299 returns the error, otherwise returns false. Called by the insert and replace
307 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
310 $self->ut_numbern('crednum')
311 || $self->ut_number('custnum')
312 || $self->ut_numbern('_date')
313 || $self->ut_money('amount')
314 || $self->ut_alphan('otaker')
315 || $self->ut_textn('reason')
316 || $self->ut_textn('addlinfo')
317 || $self->ut_enum('closed', [ '', 'Y' ])
318 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
319 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
320 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
321 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
322 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
324 return $error if $error;
326 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
327 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
328 return $error if $error;
330 return "amount must be > 0 " if $self->amount <= 0;
332 return "amount must be greater or equal to amount applied"
333 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
335 return "Unknown customer"
336 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
338 $self->_date(time) unless $self->_date;
343 =item void [ REASON ]
345 Voids this credit: deletes the credit and all associated applications and
346 adds a record of the voided credit to the cust_credit_void table.
354 unless (ref($reason) || !$reason) {
355 $reason = FS::reason->new_or_existing(
357 'type' => 'Void credit',
362 local $SIG{HUP} = 'IGNORE';
363 local $SIG{INT} = 'IGNORE';
364 local $SIG{QUIT} = 'IGNORE';
365 local $SIG{TERM} = 'IGNORE';
366 local $SIG{TSTP} = 'IGNORE';
367 local $SIG{PIPE} = 'IGNORE';
369 my $oldAutoCommit = $FS::UID::AutoCommit;
370 local $FS::UID::AutoCommit = 0;
373 my $cust_credit_void = new FS::cust_credit_void ( {
374 map { $_ => $self->get($_) } $self->fields
376 $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
377 my $error = $cust_credit_void->insert;
379 $dbh->rollback if $oldAutoCommit;
383 $error = $self->delete(void => 1); # suppress deletecredits warning
385 $dbh->rollback if $oldAutoCommit;
389 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
395 =item cust_credit_refund
397 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
401 sub cust_credit_refund {
403 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
404 sort { $a->_date <=> $b->_date }
405 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
409 =item cust_credit_bill
411 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
416 sub cust_credit_bill {
418 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
419 sort { $a->_date <=> $b->_date }
420 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
426 Returns the amount of this credit that is still unapplied/outstanding;
427 amount minus all refund applications (see L<FS::cust_credit_refund>) and
428 applications to invoices (see L<FS::cust_credit_bill>).
434 my $amount = $self->amount;
435 $amount -= $_->amount foreach ( $self->cust_credit_refund );
436 $amount -= $_->amount foreach ( $self->cust_credit_bill );
437 sprintf( "%.2f", $amount );
442 Deprecated name for the unapplied method.
448 #carp "cust_credit->credited deprecated; use ->unapplied";
449 $self->unapplied(@_);
454 Returns the customer (see L<FS::cust_main>) for this credit.
460 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
466 Returns the text of the associated reason (see L<FS::reason>) for this credit.
471 my ($self, $value, %options) = @_;
474 my $typenum = $options{'reason_type'};
476 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
477 local $FS::UID::AutoCommit = 0; # a transaction if it matters
479 if ( defined( $value ) ) {
480 my $hashref = { 'reason' => $value };
481 $hashref->{'reason_type'} = $typenum if $typenum;
482 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
483 my $extra_sql = " AND reason_type.class='R'";
485 $reason = qsearchs( { 'table' => 'reason',
486 'hashref' => $hashref,
487 'addl_from' => $addl_from,
488 'extra_sql' => $extra_sql,
491 if (!$reason && $typenum) {
492 $reason = new FS::reason( { 'reason_type' => $typenum,
496 my $error = $reason->insert;
498 warn "error inserting reason: $error\n";
503 $self->reasonnum($reason ? $reason->reasonnum : '') ;
504 warn "$me reason used in set mode with non-existant reason -- clearing"
507 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
509 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
511 ( $reason ? $reason->reason : '' ).
512 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
517 # Used by FS::Upgrade to migrate to a new database.
519 sub _upgrade_data { # class method
520 my ($class, %opts) = @_;
522 warn "$me upgrading $class\n" if $DEBUG;
524 if (defined dbdef->table($class->table)->column('reason')) {
526 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
528 my @cust_credits = qsearch({ 'table' => $class->table,
530 'extra_sql' => 'WHERE reason IS NOT NULL',
533 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
534 warn "$me Found unmigrated reasons\n" if $DEBUG;
535 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
536 my $reason_type = qsearchs( 'reason_type', $hashref );
537 unless ($reason_type) {
538 $reason_type = new FS::reason_type( $hashref );
539 my $error = $reason_type->insert();
540 die "$class had error inserting FS::reason_type into database: $error\n"
544 $hashref = { 'reason_type' => $reason_type->typenum,
547 my $noreason = qsearchs( 'reason', $hashref );
549 $hashref->{'disabled'} = 'Y';
550 $noreason = new FS::reason( $hashref );
551 my $error = $noreason->insert();
552 die "can't insert legacy reason '(none)' into database: $error\n"
556 foreach my $cust_credit ( @cust_credits ) {
557 my $reason = $cust_credit->getfield('reason');
558 warn "Contemplating reason $reason\n" if $DEBUG > 1;
559 if ($reason =~ /\S/) {
560 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
561 or die "can't insert legacy reason $reason into database\n";
563 $cust_credit->reasonnum($noreason->reasonnum);
566 $cust_credit->setfield('reason', '');
567 my $error = $cust_credit->replace;
569 warn "*** WARNING: error replacing reason in $class ".
570 $cust_credit->crednum. ": $error ***\n"
575 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
577 foreach ( keys %reasontype_map ) {
578 unless ($conf->config($_)) { # hmmmm
579 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
580 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
581 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
582 my $reason_type = qsearchs( 'reason_type', $hashref );
583 unless ($reason_type) {
584 $reason_type = new FS::reason_type( $hashref );
585 my $error = $reason_type->insert();
586 die "$class had error inserting FS::reason_type into database: $error\n"
589 $conf->set($_, $reason_type->typenum);
593 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
595 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
596 my $reason_type = qsearchs( 'reason_type', $hashref );
597 unless ($reason_type) {
598 $reason_type = new FS::reason_type( $hashref );
599 my $error = $reason_type->insert();
600 die "$class had error inserting FS::reason_type into database: $error\n"
604 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
605 foreach my $plan ( @plans ) {
606 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
607 unless ($pkg->option('reason_type', 1) ) {
608 my $plandata = $pkg->plandata.
609 "reason_type=". $reason_type->typenum. "\n";
610 $pkg->plandata($plandata);
612 $pkg->replace( undef,
613 'pkg_svc' => { map { $_->svcpart => $_->quantity }
616 'primary_svc' => $pkg->svcpart,
618 die "failed setting reason_type option: $error"
625 local($otaker_upgrade_kludge) = 1;
626 local($ignore_empty_reasonnum) = 1;
627 $class->_upgrade_otaker(%opts);
629 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
630 and !$conf->exists('enable_taxproducts') ) {
631 # RT#25458: fix credit line item applications that should refer to a
632 # specific tax allocation
633 my @cust_credit_bill_pkg = qsearch({
634 table => 'cust_credit_bill_pkg',
635 select => 'cust_credit_bill_pkg.*',
636 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
638 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
639 'AND cust_bill_pkg.pkgnum = 0', # is a tax
643 foreach (@cust_credit_bill_pkg) {
644 my $billpkgnum = $_->billpkgnum;
645 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
646 $credits{$billpkgnum} ||= [];
647 push @{ $credits{$billpkgnum} }, $_;
649 TAX_ITEM: foreach my $tax_item (values %tax_items) {
650 my $billpkgnum = $tax_item->billpkgnum;
651 # get all pkg/location/taxrate allocations of this tax line item
652 my @allocations = sort {$b->amount <=> $a->amount}
653 qsearch('cust_bill_pkg_tax_location', {
654 billpkgnum => $billpkgnum
656 # and these are all credit applications to it
657 my @credits = sort {$b->amount <=> $a->amount}
658 @{ $credits{$billpkgnum} };
659 my $c = shift @credits;
660 my $a = shift @allocations; # we will NOT modify these
662 if ( abs($c->amount - $a->amount) < 0.005 ) {
663 # by far the most common case: the tax line item is for a single
664 # tax, so we just fill in the billpkgtaxlocationnum
665 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
666 my $error = $c->replace;
668 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
672 $a = shift @allocations;
673 } elsif ( $c->amount > $a->amount ) {
674 # fairly common: the tax line contains tax for multiple packages
675 # (or multiple taxes) but the credit isn't divided up
676 my $new_link = FS::cust_credit_bill_pkg->new({
677 creditbillnum => $c->creditbillnum,
678 billpkgnum => $c->billpkgnum,
679 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
680 amount => $a->amount,
681 setuprecur => 'setup',
683 my $error = $new_link->insert;
685 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
688 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
689 $a = shift @allocations;
690 } elsif ( $c->amount < 0.005 ) {
691 # also fairly common; we can delete these with no harm
692 my $error = $c->delete;
693 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
695 } elsif ( $c->amount < $a->amount ) {
696 # should never happen, but if it does, handle it gracefully
697 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
698 my $error = $c->replace;
700 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
703 $a->set(amount => $a->amount - $c->amount);
708 if ( $c->amount < 0.005 ) {
709 my $error = $c->delete;
710 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
711 } elsif ( $c->modified ) {
712 # then we've allocated part of it, so reduce the nonspecific
713 # application by that much
714 my $error = $c->replace;
715 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
717 # else there are probably no allocations, i.e. this is a pre-3.x
718 # record that was never migrated over, so leave it alone
720 } # foreach $tax_item
721 FS::upgrade_journal->set_done('cust_credit__tax_link');
733 Returns an SQL fragment to retreive the unapplied amount.
738 my ($class, $start, $end) = @_;
740 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
741 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
742 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
743 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
747 ( SELECT SUM(amount) FROM cust_credit_refund
748 WHERE cust_credit.crednum = cust_credit_refund.crednum
749 $refund_start $refund_end )
753 ( SELECT SUM(amount) FROM cust_credit_bill
754 WHERE cust_credit.crednum = cust_credit_bill.crednum
755 $bill_start $bill_end )
764 Deprecated name for the unapplied_sql method.
771 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
773 #$class->unapplied_sql(@_);
777 =item credit_lineitems
781 my $error = FS::cust_credit->credit_lineitems(
783 #the lineitems to credit
784 'billpkgnums' => \@billpkgnums,
785 'setuprecurs' => \@setuprecurs,
786 'amounts' => \@amounts,
787 'apply' => 1, #0 leaves the credit unapplied
790 map { $_ => scalar($cgi->param($_)) }
791 #fields('cust_credit')
792 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
798 #maybe i should just be an insert with extra args instead of a class method
799 sub credit_lineitems {
800 my( $class, %arg ) = @_;
801 my $curuser = $FS::CurrentUser::CurrentUser;
803 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
805 my $cust_main = qsearchs({
806 'table' => 'cust_main',
807 'hashref' => { 'custnum' => $arg{custnum} },
808 'extra_sql' => ' AND '. $curuser->agentnums_sql,
809 }) or return 'unknown customer';
812 local $SIG{HUP} = 'IGNORE';
813 local $SIG{INT} = 'IGNORE';
814 local $SIG{QUIT} = 'IGNORE';
815 local $SIG{TERM} = 'IGNORE';
816 local $SIG{TSTP} = 'IGNORE';
817 local $SIG{PIPE} = 'IGNORE';
819 my $oldAutoCommit = $FS::UID::AutoCommit;
820 local $FS::UID::AutoCommit = 0;
823 #my @cust_bill_pkg = qsearch({
824 # 'select' => 'cust_bill_pkg.*',
825 # 'table' => 'cust_bill_pkg',
826 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
827 # ' LEFT JOIN cust_main USING (custnum) ',
828 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
829 # join( ',', @{$arg{billpkgnums}} ). ')',
830 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
835 my $cust_credit = new FS::cust_credit ( {
836 map { $_ => $arg{$_} }
837 #fields('cust_credit')
838 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
840 $error = $cust_credit->insert;
842 $dbh->rollback if $oldAutoCommit;
843 return "Error inserting credit: $error";
846 unless ( $arg{'apply'} ) {
847 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
852 # keys in all of these are invoice numbers
853 my %cust_credit_bill = ();
854 my %cust_bill_pkg = ();
855 my %cust_credit_bill_pkg = ();
856 my %taxlisthash = ();
857 my %unapplied_payments = (); #invoice numbers, and then billpaynums
858 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
859 my $setuprecur = shift @{$arg{setuprecurs}};
860 my $amount = shift @{$arg{amounts}};
862 my $cust_bill_pkg = qsearchs({
863 'table' => 'cust_bill_pkg',
864 'hashref' => { 'billpkgnum' => $billpkgnum },
865 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
866 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
867 }) or die "unknown billpkgnum $billpkgnum";
869 my $invnum = $cust_bill_pkg->invnum;
871 if ( $setuprecur eq 'setup' ) {
872 $cust_bill_pkg->setup($amount);
873 $cust_bill_pkg->recur(0);
874 $cust_bill_pkg->unitrecur(0);
875 $cust_bill_pkg->type('');
877 $setuprecur = 'recur'; #in case its a usage classnum?
878 $cust_bill_pkg->recur($amount);
879 $cust_bill_pkg->setup(0);
880 $cust_bill_pkg->unitsetup(0);
883 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
885 #unapply any payments applied to this line item (other credits too?)
886 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
887 $error = $cust_bill_pay_pkg->delete;
889 $dbh->rollback if $oldAutoCommit;
890 return "Error unapplying payment: $error";
892 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
893 += $cust_bill_pay_pkg->amount;
896 #$subtotal += $amount;
897 $cust_credit_bill{$invnum} += $amount;
898 push @{ $cust_credit_bill_pkg{$invnum} },
899 new FS::cust_credit_bill_pkg {
900 'billpkgnum' => $cust_bill_pkg->billpkgnum,
901 'amount' => sprintf('%.2f',$amount),
902 'setuprecur' => $setuprecur,
903 'sdate' => $cust_bill_pkg->sdate,
904 'edate' => $cust_bill_pkg->edate,
907 # recalculate taxes with new amounts
908 $taxlisthash{$invnum} ||= {};
909 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
910 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
911 } # otherwise the item itself is a tax, and assume the caller knows
916 # now loop through %cust_credit_bill and insert those
919 # (hack to prevent cust_credit_bill_pkg insertion)
920 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
922 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
924 my $arrayref_or_error =
925 $cust_main->calculate_taxes(
926 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
927 $taxlisthash{$invnum}, # list of tax-item bindings
928 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
931 unless ( ref( $arrayref_or_error ) ) {
932 $dbh->rollback if $oldAutoCommit;
933 return "Error calculating taxes: $arrayref_or_error";
936 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
939 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
940 my $billpkgnum = $cust_bill_pkg->billpkgnum;
941 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
942 # gather up existing tax links (we need their billpkgtaxlocationnums)
943 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
944 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
946 foreach ( @tax_links ) {
947 $tax_links{$_->billpkgnum} ||= {};
948 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
952 foreach my $taxline ( @$arrayref_or_error ) {
954 my $amount = $taxline->setup;
956 # find equivalent tax line item on the existing invoice
957 my $tax_item = qsearchs('cust_bill_pkg', {
960 'itemdesc' => $taxline->desc,
963 # or should we just exit if this happens?
964 $cust_credit->set('amount',
965 sprintf('%.2f', $cust_credit->get('amount') - $amount)
967 my $error = $cust_credit->replace;
969 $dbh->rollback if $oldAutoCommit;
970 return "error correcting credit for missing tax line: $error";
974 # but in the new era, we no longer have the problem of uniquely
975 # identifying the tax_Xlocation record. The billpkgnums of the
976 # tax and the taxed item are known.
978 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
979 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
981 # the existing tax_Xlocation object
983 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
985 next if !$old_loc; # apply the leftover amount nonspecifically
987 #support partial credits: use $amount if smaller
988 # (so just distribute to the first location? perhaps should
990 my $loc_amount = min( $amount, $new_loc->amount);
992 $amount -= $loc_amount;
994 $cust_credit_bill{$invnum} += $loc_amount;
995 push @{ $cust_credit_bill_pkg{$invnum} },
996 new FS::cust_credit_bill_pkg {
997 'billpkgnum' => $tax_item->billpkgnum,
998 'amount' => $loc_amount,
999 'setuprecur' => 'setup',
1000 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
1001 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
1004 } #foreach my $new_loc
1006 # we still have to deal with the possibility that the tax links don't
1007 # cover the whole amount of tax because of an incomplete upgrade...
1008 if ($amount > 0.005) {
1009 $cust_credit_bill{$invnum} += $amount;
1010 push @{ $cust_credit_bill_pkg{$invnum} },
1011 new FS::cust_credit_bill_pkg {
1012 'billpkgnum' => $tax_item->billpkgnum,
1013 'amount' => sprintf('%.2f', $amount),
1014 'setuprecur' => 'setup',
1019 #unapply any payments applied to the tax
1020 foreach my $cust_bill_pay_pkg
1021 ( $tax_item->cust_bill_pay_pkg('setup') )
1023 $error = $cust_bill_pay_pkg->delete;
1025 $dbh->rollback if $oldAutoCommit;
1026 return "Error unapplying payment: $error";
1028 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
1029 += $cust_bill_pay_pkg->amount;
1033 # if we unapplied any payments from line items, also unapply that
1034 # amount from the invoice
1035 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1036 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1037 or die "broken payment application $billpaynum";
1038 my @subapps = $cust_bill_pay->lineitem_applications;
1039 $error = $cust_bill_pay->delete; # can't replace
1041 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1042 $cust_bill_pay->hash,
1044 amount => sprintf('%.2f',
1045 $cust_bill_pay->amount
1046 - $unapplied_payments{$invnum}{$billpaynum}),
1049 if ( $new_cust_bill_pay->amount > 0 ) {
1050 $error ||= $new_cust_bill_pay->insert;
1051 # Also reapply it to everything it was applied to before.
1052 # Note that we've already deleted cust_bill_pay_pkg records for the
1053 # items we're crediting, so they aren't on this list.
1054 foreach my $cust_bill_pay_pkg (@subapps) {
1055 $cust_bill_pay_pkg->billpaypkgnum('');
1056 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1057 $error ||= $cust_bill_pay_pkg->insert;
1061 $dbh->rollback if $oldAutoCommit;
1062 return "Error unapplying payment: $error";
1065 #insert cust_credit_bill
1067 my $cust_credit_bill = new FS::cust_credit_bill {
1068 'crednum' => $cust_credit->crednum,
1069 'invnum' => $invnum,
1070 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1072 $error = $cust_credit_bill->insert;
1074 $dbh->rollback if $oldAutoCommit;
1075 return "Error applying credit of $cust_credit_bill{$invnum} ".
1076 " to invoice $invnum: $error";
1079 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1080 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1081 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1082 $error = $cust_credit_bill_pkg->insert;
1084 $dbh->rollback if $oldAutoCommit;
1085 return "Error applying credit to line item: $error";
1091 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1102 =item process_batch_import
1106 use List::Util qw( min );
1108 use FS::cust_credit_bill;
1109 sub process_batch_import {
1112 my $opt = { 'table' => 'cust_credit',
1113 'params' => [ '_date', 'credbatch' ],
1114 'formats' => { 'simple' =>
1115 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1118 'postinsert_callback' => sub {
1119 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1121 if ( $cust_credit->invnum ) {
1123 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1124 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1126 my $cust_credit_bill = new FS::cust_credit_bill ( {
1127 'crednum' => $cust_credit->crednum,
1128 'invnum' => $cust_bill->invnum,
1129 'amount' => $amount,
1131 my $error = $cust_credit_bill->insert;
1132 return '' unless $error;
1136 #apply_payments_and_credits ?
1137 $cust_credit->cust_main->apply_credits;
1144 FS::Record::process_batch_import( $job, $opt, @_ );
1152 The delete method. The replace method.
1154 B<credited> and B<credited_sql> are now called B<unapplied> and
1155 B<unapplied_sql>. The old method names should start to give warnings.
1159 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1160 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base