1 package FS::cust_credit;
2 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 );
11 use FS::Misc qw(send_email);
12 use FS::Record qw( qsearch qsearchs dbdef );
16 use FS::cust_credit_bill;
23 use FS::cust_credit_void;
24 use FS::upgrade_journal;
26 $me = '[ FS::cust_credit ]';
29 $otaker_upgrade_kludge = 0;
30 $ignore_empty_reasonnum = 0;
32 #ask FS::UID to run this stuff for us later
33 $FS::UID::callback{'FS::cust_credit'} = sub {
36 $unsuspendauto = $conf->exists('unsuspendauto');
40 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
41 'cancel_credit_type' => 'Cancellation Credit',
42 'signup_credit_type' => 'Self-Service Credit',
47 FS::cust_credit - Object methods for cust_credit records
53 $record = new FS::cust_credit \%hash;
54 $record = new FS::cust_credit { 'column' => 'value' };
56 $error = $record->insert;
58 $error = $new_record->replace($old_record);
60 $error = $record->delete;
62 $error = $record->check;
66 An FS::cust_credit object represents a credit; the equivalent of a negative
67 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
68 FS::Record. The following fields are currently supported:
74 Primary key (assigned automatically for new credits)
78 Customer (see L<FS::cust_main>)
86 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
87 L<Time::Local> and L<Date::Parse> for conversion functions.
91 Order taker (see L<FS::access_user>)
99 Reason (see L<FS::reason>)
107 Books closed flag, empty or `Y'
111 Desired pkgnum when using experimental package balances.
121 Creates a new credit. To add the credit to the database, see L<"insert">.
125 sub table { 'cust_credit'; }
126 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
127 sub cust_unlinked_msg {
129 "WARNING: can't find cust_main.custnum ". $self->custnum.
130 ' (cust_credit.crednum '. $self->crednum. ')';
135 Adds this credit to the database ("Posts" the credit). If there is an error,
136 returns the error, otherwise returns false.
141 my ($self, %options) = @_;
143 local $SIG{HUP} = 'IGNORE';
144 local $SIG{INT} = 'IGNORE';
145 local $SIG{QUIT} = 'IGNORE';
146 local $SIG{TERM} = 'IGNORE';
147 local $SIG{TSTP} = 'IGNORE';
148 local $SIG{PIPE} = 'IGNORE';
150 my $oldAutoCommit = $FS::UID::AutoCommit;
151 local $FS::UID::AutoCommit = 0;
154 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
155 my $old_balance = $cust_main->balance;
157 unless ($self->reasonnum) {
158 my $result = $self->reason( $self->getfield('reason'),
159 exists($options{ 'reason_type' })
160 ? ('reason_type' => $options{ 'reason_type' })
164 $dbh->rollback if $oldAutoCommit;
165 return "failed to set reason for $me"; #: ". $dbh->errstr;
169 $self->setfield('reason', '');
171 my $error = $self->SUPER::insert;
173 $dbh->rollback if $oldAutoCommit;
174 return "error inserting $self: $error";
177 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
179 #false laziness w/ cust_pay::insert
180 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
181 my @errors = $cust_main->unsuspend;
183 # side-fx with nested transactions? upstack rolls back?
184 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
190 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
198 Unless the closed flag is set, deletes this credit and all associated
199 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
200 the void method instead to leave a record of the deleted credit.
204 # very similar to FS::cust_pay::delete
209 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
211 local $SIG{HUP} = 'IGNORE';
212 local $SIG{INT} = 'IGNORE';
213 local $SIG{QUIT} = 'IGNORE';
214 local $SIG{TERM} = 'IGNORE';
215 local $SIG{TSTP} = 'IGNORE';
216 local $SIG{PIPE} = 'IGNORE';
218 my $oldAutoCommit = $FS::UID::AutoCommit;
219 local $FS::UID::AutoCommit = 0;
222 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
223 my $error = $cust_credit_bill->delete;
225 $dbh->rollback if $oldAutoCommit;
230 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
231 my $error = $cust_credit_refund->delete;
233 $dbh->rollback if $oldAutoCommit;
238 my $error = $self->SUPER::delete(@_);
240 $dbh->rollback if $oldAutoCommit;
244 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
246 my $cust_main = $self->cust_main;
248 my $error = send_email(
249 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
250 #invoice_from??? well as good as any
251 'to' => $conf->config('deletecredits'),
252 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
254 "This is an automatic message from your Freeside installation\n",
255 "informing you that the following credit has been deleted:\n",
257 'crednum: '. $self->crednum. "\n",
258 'custnum: '. $self->custnum.
259 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
260 'amount: $'. sprintf("%.2f", $self->amount). "\n",
261 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
262 'reason: '. $self->reason. "\n",
267 $dbh->rollback if $oldAutoCommit;
268 return "can't send credit deletion notification: $error";
273 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
279 =item replace [ OLD_RECORD ]
281 You can, but probably shouldn't modify credits...
283 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
284 supplied, replaces this record. If there is an error, returns the error,
285 otherwise returns false.
291 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
292 $self->SUPER::replace(@_);
297 Checks all fields to make sure this is a valid credit. If there is an error,
298 returns the error, otherwise returns false. Called by the insert and replace
306 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
309 $self->ut_numbern('crednum')
310 || $self->ut_number('custnum')
311 || $self->ut_numbern('_date')
312 || $self->ut_money('amount')
313 || $self->ut_alphan('otaker')
314 || $self->ut_textn('reason')
315 || $self->ut_textn('addlinfo')
316 || $self->ut_enum('closed', [ '', 'Y' ])
317 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
318 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
319 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
320 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
321 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
323 return $error if $error;
325 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
326 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
327 return $error if $error;
329 return "amount must be > 0 " if $self->amount <= 0;
331 return "amount must be greater or equal to amount applied"
332 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
334 return "Unknown customer"
335 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
337 $self->_date(time) unless $self->_date;
342 =item void [ REASON ]
344 Voids this credit: deletes the credit and all associated applications and
345 adds a record of the voided credit to the cust_credit_void table.
349 # yes, false laziness with cust_pay and cust_bill
350 # but frankly I don't have time to fix it now
356 local $SIG{HUP} = 'IGNORE';
357 local $SIG{INT} = 'IGNORE';
358 local $SIG{QUIT} = 'IGNORE';
359 local $SIG{TERM} = 'IGNORE';
360 local $SIG{TSTP} = 'IGNORE';
361 local $SIG{PIPE} = 'IGNORE';
363 my $oldAutoCommit = $FS::UID::AutoCommit;
364 local $FS::UID::AutoCommit = 0;
367 my $cust_credit_void = new FS::cust_credit_void ( {
368 map { $_ => $self->get($_) } $self->fields
370 $cust_credit_void->set('void_reason', $reason);
371 my $error = $cust_credit_void->insert;
373 $dbh->rollback if $oldAutoCommit;
377 $error = $self->delete(void => 1); # suppress deletecredits warning
379 $dbh->rollback if $oldAutoCommit;
383 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
389 =item cust_credit_refund
391 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
395 sub cust_credit_refund {
397 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
398 sort { $a->_date <=> $b->_date }
399 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
403 =item cust_credit_bill
405 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
410 sub cust_credit_bill {
412 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
413 sort { $a->_date <=> $b->_date }
414 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
420 Returns the amount of this credit that is still unapplied/outstanding;
421 amount minus all refund applications (see L<FS::cust_credit_refund>) and
422 applications to invoices (see L<FS::cust_credit_bill>).
428 my $amount = $self->amount;
429 $amount -= $_->amount foreach ( $self->cust_credit_refund );
430 $amount -= $_->amount foreach ( $self->cust_credit_bill );
431 sprintf( "%.2f", $amount );
436 Deprecated name for the unapplied method.
442 #carp "cust_credit->credited deprecated; use ->unapplied";
443 $self->unapplied(@_);
448 Returns the customer (see L<FS::cust_main>) for this credit.
452 Returns the text of the associated reason (see L<FS::reason>) for this credit.
457 my ($self, $value, %options) = @_;
460 my $typenum = $options{'reason_type'};
462 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
463 local $FS::UID::AutoCommit = 0; # a transaction if it matters
465 if ( defined( $value ) ) {
466 my $hashref = { 'reason' => $value };
467 $hashref->{'reason_type'} = $typenum if $typenum;
468 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
469 my $extra_sql = " AND reason_type.class='R'";
471 $reason = qsearchs( { 'table' => 'reason',
472 'hashref' => $hashref,
473 'addl_from' => $addl_from,
474 'extra_sql' => $extra_sql,
477 if (!$reason && $typenum) {
478 $reason = new FS::reason( { 'reason_type' => $typenum,
482 my $error = $reason->insert;
484 warn "error inserting reason: $error\n";
489 $self->reasonnum($reason ? $reason->reasonnum : '') ;
490 warn "$me reason used in set mode with non-existant reason -- clearing"
493 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
495 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
497 ( $reason ? $reason->reason : '' ).
498 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
503 # Used by FS::Upgrade to migrate to a new database.
505 sub _upgrade_data { # class method
506 my ($class, %opts) = @_;
508 warn "$me upgrading $class\n" if $DEBUG;
510 if (defined dbdef->table($class->table)->column('reason')) {
512 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
514 my @cust_credits = qsearch({ 'table' => $class->table,
516 'extra_sql' => 'WHERE reason IS NOT NULL',
519 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
520 warn "$me Found unmigrated reasons\n" if $DEBUG;
521 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
522 my $reason_type = qsearchs( 'reason_type', $hashref );
523 unless ($reason_type) {
524 $reason_type = new FS::reason_type( $hashref );
525 my $error = $reason_type->insert();
526 die "$class had error inserting FS::reason_type into database: $error\n"
530 $hashref = { 'reason_type' => $reason_type->typenum,
533 my $noreason = qsearchs( 'reason', $hashref );
535 $hashref->{'disabled'} = 'Y';
536 $noreason = new FS::reason( $hashref );
537 my $error = $noreason->insert();
538 die "can't insert legacy reason '(none)' into database: $error\n"
542 foreach my $cust_credit ( @cust_credits ) {
543 my $reason = $cust_credit->getfield('reason');
544 warn "Contemplating reason $reason\n" if $DEBUG > 1;
545 if ($reason =~ /\S/) {
546 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
547 or die "can't insert legacy reason $reason into database\n";
549 $cust_credit->reasonnum($noreason->reasonnum);
552 $cust_credit->setfield('reason', '');
553 my $error = $cust_credit->replace;
555 warn "*** WARNING: error replacing reason in $class ".
556 $cust_credit->crednum. ": $error ***\n"
561 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
563 foreach ( keys %reasontype_map ) {
564 unless ($conf->config($_)) { # hmmmm
565 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
566 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
567 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
568 my $reason_type = qsearchs( 'reason_type', $hashref );
569 unless ($reason_type) {
570 $reason_type = new FS::reason_type( $hashref );
571 my $error = $reason_type->insert();
572 die "$class had error inserting FS::reason_type into database: $error\n"
575 $conf->set($_, $reason_type->typenum);
579 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
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"
590 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
591 foreach my $plan ( @plans ) {
592 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
593 unless ($pkg->option('reason_type', 1) ) {
594 my $plandata = $pkg->plandata.
595 "reason_type=". $reason_type->typenum. "\n";
596 $pkg->plandata($plandata);
598 $pkg->replace( undef,
599 'pkg_svc' => { map { $_->svcpart => $_->quantity }
602 'primary_svc' => $pkg->svcpart,
604 die "failed setting reason_type option: $error"
611 local($otaker_upgrade_kludge) = 1;
612 local($ignore_empty_reasonnum) = 1;
613 $class->_upgrade_otaker(%opts);
615 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
616 and !$conf->exists('enable_taxproducts') ) {
617 # RT#25458: fix credit line item applications that should refer to a
618 # specific tax allocation
619 my @cust_credit_bill_pkg = qsearch({
620 table => 'cust_credit_bill_pkg',
621 select => 'cust_credit_bill_pkg.*',
622 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
624 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
625 'AND cust_bill_pkg.pkgnum = 0', # is a tax
629 foreach (@cust_credit_bill_pkg) {
630 my $billpkgnum = $_->billpkgnum;
631 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
632 $credits{$billpkgnum} ||= [];
633 push @{ $credits{$billpkgnum} }, $_;
635 TAX_ITEM: foreach my $tax_item (values %tax_items) {
636 my $billpkgnum = $tax_item->billpkgnum;
637 # get all pkg/location/taxrate allocations of this tax line item
638 my @allocations = sort {$b->amount <=> $a->amount}
639 qsearch('cust_bill_pkg_tax_location', {
640 billpkgnum => $billpkgnum
642 # and these are all credit applications to it
643 my @credits = sort {$b->amount <=> $a->amount}
644 @{ $credits{$billpkgnum} };
645 my $c = shift @credits;
646 my $a = shift @allocations; # we will NOT modify these
648 if ( abs($c->amount - $a->amount) < 0.005 ) {
649 # by far the most common case: the tax line item is for a single
650 # tax, so we just fill in the billpkgtaxlocationnum
651 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
652 my $error = $c->replace;
654 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
658 $a = shift @allocations;
659 } elsif ( $c->amount > $a->amount ) {
660 # fairly common: the tax line contains tax for multiple packages
661 # (or multiple taxes) but the credit isn't divided up
662 my $new_link = FS::cust_credit_bill_pkg->new({
663 creditbillnum => $c->creditbillnum,
664 billpkgnum => $c->billpkgnum,
665 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
666 amount => $a->amount,
667 setuprecur => 'setup',
669 my $error = $new_link->insert;
671 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
674 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
675 $a = shift @allocations;
676 } elsif ( $c->amount < 0.005 ) {
677 # also fairly common; we can delete these with no harm
678 my $error = $c->delete;
679 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
681 } elsif ( $c->amount < $a->amount ) {
682 # should never happen, but if it does, handle it gracefully
683 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
684 my $error = $c->replace;
686 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
689 $a->set(amount => $a->amount - $c->amount);
694 if ( $c->amount < 0.005 ) {
695 my $error = $c->delete;
696 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
697 } elsif ( $c->modified ) {
698 # then we've allocated part of it, so reduce the nonspecific
699 # application by that much
700 my $error = $c->replace;
701 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
703 # else there are probably no allocations, i.e. this is a pre-3.x
704 # record that was never migrated over, so leave it alone
706 } # foreach $tax_item
707 FS::upgrade_journal->set_done('cust_credit__tax_link');
719 Returns an SQL fragment to retreive the unapplied amount.
724 my ($class, $start, $end) = @_;
726 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
727 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
728 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
729 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
733 ( SELECT SUM(amount) FROM cust_credit_refund
734 WHERE cust_credit.crednum = cust_credit_refund.crednum
735 $refund_start $refund_end )
739 ( SELECT SUM(amount) FROM cust_credit_bill
740 WHERE cust_credit.crednum = cust_credit_bill.crednum
741 $bill_start $bill_end )
750 Deprecated name for the unapplied_sql method.
757 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
759 #$class->unapplied_sql(@_);
763 =item credit_lineitems
767 my $error = FS::cust_credit->credit_lineitems(
769 #the lineitems to credit
770 'billpkgnums' => \@billpkgnums,
771 'setuprecurs' => \@setuprecurs,
772 'amounts' => \@amounts,
773 'apply' => 1, #0 leaves the credit unapplied
776 'newreasonnum' => scalar($cgi->param('newreasonnum')),
777 'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
778 map { $_ => scalar($cgi->param($_)) }
779 #fields('cust_credit')
780 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
786 #maybe i should just be an insert with extra args instead of a class method
787 use FS::cust_bill_pkg;
788 sub credit_lineitems {
789 my( $class, %arg ) = @_;
790 my $curuser = $FS::CurrentUser::CurrentUser;
792 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
794 my $cust_main = qsearchs({
795 'table' => 'cust_main',
796 'hashref' => { 'custnum' => $arg{custnum} },
797 'extra_sql' => ' AND '. $curuser->agentnums_sql,
798 }) or return 'unknown customer';
801 local $SIG{HUP} = 'IGNORE';
802 local $SIG{INT} = 'IGNORE';
803 local $SIG{QUIT} = 'IGNORE';
804 local $SIG{TERM} = 'IGNORE';
805 local $SIG{TSTP} = 'IGNORE';
806 local $SIG{PIPE} = 'IGNORE';
808 my $oldAutoCommit = $FS::UID::AutoCommit;
809 local $FS::UID::AutoCommit = 0;
812 #my @cust_bill_pkg = qsearch({
813 # 'select' => 'cust_bill_pkg.*',
814 # 'table' => 'cust_bill_pkg',
815 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
816 # ' LEFT JOIN cust_main USING (custnum) ',
817 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
818 # join( ',', @{$arg{billpkgnums}} ). ')',
819 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
823 if ($arg{reasonnum} == -1) {
825 $error = 'Enter a new reason (or select an existing one)'
826 unless $arg{newreasonnum} !~ /^\s*$/;
827 my $reason = new FS::reason {
828 'reason' => $arg{newreasonnum},
829 'reason_type' => $arg{newreasonnum_type},
831 $error ||= $reason->insert;
833 $dbh->rollback if $oldAutoCommit;
834 return "Error inserting reason: $error";
836 $arg{reasonnum} = $reason->reasonnum;
839 my $cust_credit = new FS::cust_credit ( {
840 map { $_ => $arg{$_} }
841 #fields('cust_credit')
842 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
844 $error = $cust_credit->insert;
846 $dbh->rollback if $oldAutoCommit;
847 return "Error inserting credit: $error";
850 unless ( $arg{'apply'} ) {
851 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
856 # keys in all of these are invoice numbers
857 my %cust_credit_bill = ();
858 my %cust_bill_pkg = ();
859 my %cust_credit_bill_pkg = ();
860 my %taxlisthash = ();
861 my %unapplied_payments = (); #invoice numbers, and then billpaynums
862 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
863 my $setuprecur = shift @{$arg{setuprecurs}};
864 my $amount = shift @{$arg{amounts}};
866 my $cust_bill_pkg = qsearchs({
867 'table' => 'cust_bill_pkg',
868 'hashref' => { 'billpkgnum' => $billpkgnum },
869 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
870 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
871 }) or die "unknown billpkgnum $billpkgnum";
873 my $invnum = $cust_bill_pkg->invnum;
875 if ( $setuprecur eq 'setup' ) {
876 $cust_bill_pkg->setup($amount);
877 $cust_bill_pkg->recur(0);
878 $cust_bill_pkg->unitrecur(0);
879 $cust_bill_pkg->type('');
881 $setuprecur = 'recur'; #in case its a usage classnum?
882 $cust_bill_pkg->recur($amount);
883 $cust_bill_pkg->setup(0);
884 $cust_bill_pkg->unitsetup(0);
887 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
889 #unapply any payments applied to this line item (other credits too?)
890 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
891 $error = $cust_bill_pay_pkg->delete;
893 $dbh->rollback if $oldAutoCommit;
894 return "Error unapplying payment: $error";
896 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
897 += $cust_bill_pay_pkg->amount;
900 #$subtotal += $amount;
901 $cust_credit_bill{$invnum} += $amount;
902 push @{ $cust_credit_bill_pkg{$invnum} },
903 new FS::cust_credit_bill_pkg {
904 'billpkgnum' => $cust_bill_pkg->billpkgnum,
905 'amount' => sprintf('%.2f',$amount),
906 'setuprecur' => $setuprecur,
907 'sdate' => $cust_bill_pkg->sdate,
908 'edate' => $cust_bill_pkg->edate,
911 # recalculate taxes with new amounts
912 $taxlisthash{$invnum} ||= {};
913 my $part_pkg = $cust_bill_pkg->part_pkg;
914 $cust_main->_handle_taxes( $part_pkg,
915 $taxlisthash{$invnum},
917 $cust_bill_pkg->cust_pkg,
918 $cust_bill_pkg->cust_bill->_date, #invoice time
919 $cust_bill_pkg->cust_pkg->pkgpart,
924 # now loop through %cust_credit_bill and insert those
927 # (hack to prevent cust_credit_bill_pkg insertion)
928 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
930 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
932 my $arrayref_or_error =
933 $cust_main->calculate_taxes(
934 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
935 $taxlisthash{$invnum}, # list of tax-item bindings
936 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
939 unless ( ref( $arrayref_or_error ) ) {
940 $dbh->rollback if $oldAutoCommit;
941 return "Error calculating taxes: $arrayref_or_error";
944 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
947 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
948 my $billpkgnum = $cust_bill_pkg->billpkgnum;
949 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
950 # gather up existing tax links (we need their billpkgtaxlocationnums)
951 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
952 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
954 foreach ( @tax_links ) {
955 $tax_links{$_->billpkgnum} ||= {};
956 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
960 foreach my $taxline ( @$arrayref_or_error ) {
962 my $amount = $taxline->setup;
964 # find equivalent tax line item on the existing invoice
965 my $tax_item = qsearchs('cust_bill_pkg', {
968 'itemdesc' => $taxline->desc,
971 # or should we just exit if this happens?
972 $cust_credit->set('amount',
973 sprintf('%.2f', $cust_credit->get('amount') - $amount)
975 my $error = $cust_credit->replace;
977 $dbh->rollback if $oldAutoCommit;
978 return "error correcting credit for missing tax line: $error";
982 # but in the new era, we no longer have the problem of uniquely
983 # identifying the tax_Xlocation record. The billpkgnums of the
984 # tax and the taxed item are known.
986 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
987 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
989 # the existing tax_Xlocation object
991 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
993 next if !$old_loc; # apply the leftover amount nonspecifically
995 #support partial credits: use $amount if smaller
996 # (so just distribute to the first location? perhaps should
998 my $loc_amount = min( $amount, $new_loc->amount);
1000 $amount -= $loc_amount;
1002 $cust_credit_bill{$invnum} += $loc_amount;
1003 push @{ $cust_credit_bill_pkg{$invnum} },
1004 new FS::cust_credit_bill_pkg {
1005 'billpkgnum' => $tax_item->billpkgnum,
1006 'amount' => $loc_amount,
1007 'setuprecur' => 'setup',
1008 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
1009 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
1012 } #foreach my $new_loc
1014 # we still have to deal with the possibility that the tax links don't
1015 # cover the whole amount of tax because of an incomplete upgrade...
1017 $cust_credit_bill{$invnum} += $amount;
1018 push @{ $cust_credit_bill_pkg{$invnum} },
1019 new FS::cust_credit_bill_pkg {
1020 'billpkgnum' => $tax_item->billpkgnum,
1021 'amount' => $amount,
1022 'setuprecur' => 'setup',
1027 #unapply any payments applied to the tax
1028 foreach my $cust_bill_pay_pkg
1029 ( $tax_item->cust_bill_pay_pkg('setup') )
1031 $error = $cust_bill_pay_pkg->delete;
1033 $dbh->rollback if $oldAutoCommit;
1034 return "Error unapplying payment: $error";
1036 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
1037 += $cust_bill_pay_pkg->amount;
1041 # if we unapplied any payments from line items, also unapply that
1042 # amount from the invoice
1043 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1044 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1045 or die "broken payment application $billpaynum";
1046 my @subapps = $cust_bill_pay->lineitem_applications;
1047 $error = $cust_bill_pay->delete; # can't replace
1049 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1050 $cust_bill_pay->hash,
1052 amount => sprintf('%.2f',
1053 $cust_bill_pay->amount
1054 - $unapplied_payments{$invnum}{$billpaynum}),
1057 if ( $new_cust_bill_pay->amount > 0 ) {
1058 $error ||= $new_cust_bill_pay->insert;
1059 # Also reapply it to everything it was applied to before.
1060 # Note that we've already deleted cust_bill_pay_pkg records for the
1061 # items we're crediting, so they aren't on this list.
1062 foreach my $cust_bill_pay_pkg (@subapps) {
1063 $cust_bill_pay_pkg->billpaypkgnum('');
1064 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1065 $error ||= $cust_bill_pay_pkg->insert;
1069 $dbh->rollback if $oldAutoCommit;
1070 return "Error unapplying payment: $error";
1073 #insert cust_credit_bill
1075 my $cust_credit_bill = new FS::cust_credit_bill {
1076 'crednum' => $cust_credit->crednum,
1077 'invnum' => $invnum,
1078 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1080 $error = $cust_credit_bill->insert;
1082 $dbh->rollback if $oldAutoCommit;
1083 return "Error applying credit of $cust_credit_bill{$invnum} ".
1084 " to invoice $invnum: $error";
1087 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1088 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1089 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1090 $error = $cust_credit_bill_pkg->insert;
1092 $dbh->rollback if $oldAutoCommit;
1093 return "Error applying credit to line item: $error";
1099 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1110 =item process_batch_import
1114 use List::Util qw( min );
1116 use FS::cust_credit_bill;
1117 sub process_batch_import {
1120 my $opt = { 'table' => 'cust_credit',
1121 'params' => [ 'credbatch' ],
1122 'formats' => { 'simple' =>
1123 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1126 'postinsert_callback' => sub {
1127 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1129 if ( $cust_credit->invnum ) {
1131 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1132 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1134 my $cust_credit_bill = new FS::cust_credit_bill ( {
1135 'crednum' => $cust_credit->crednum,
1136 'invnum' => $cust_bill->invnum,
1137 'amount' => $amount,
1139 my $error = $cust_credit_bill->insert;
1140 return '' unless $error;
1144 #apply_payments_and_credits ?
1145 $cust_credit->cust_main->apply_credits;
1152 FS::Record::process_batch_import( $job, $opt, @_ );
1160 The delete method. The replace method.
1162 B<credited> and B<credited_sql> are now called B<unapplied> and
1163 B<unapplied_sql>. The old method names should start to give warnings.
1167 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1168 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base