1 package FS::cust_credit;
4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
7 use vars qw( $conf $me $DEBUG
8 $otaker_upgrade_kludge $ignore_empty_reasonnum
10 use List::Util qw( min );
12 use FS::UID qw( dbh getotaker );
13 use FS::Misc qw(send_email);
14 use FS::Record qw( qsearch qsearchs dbdef );
19 use FS::cust_credit_bill;
26 use FS::cust_credit_void;
27 use FS::cust_bill_pkg;
28 use FS::upgrade_journal;
30 $me = '[ FS::cust_credit ]';
33 $otaker_upgrade_kludge = 0;
34 $ignore_empty_reasonnum = 0;
36 #ask FS::UID to run this stuff for us later
37 $FS::UID::callback{'FS::cust_credit'} = sub {
43 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
44 'cancel_credit_type' => 'Cancellation 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 if (!$self->reasonnum) {
160 my $reason_text = $self->get('reason')
161 or return "reason text or existing reason required";
162 my $reason_type = $options{'reason_type'}
163 or return "reason type required";
166 my $reason = FS::reason->new_or_existing(
167 reason => $reason_text,
168 type => $reason_type,
172 $dbh->rollback if $oldAutoCommit;
173 return "failed to set credit reason: $@";
175 $self->set('reasonnum', $reason->reasonnum);
178 $self->setfield('reason', '');
180 my $error = $self->SUPER::insert;
182 $dbh->rollback if $oldAutoCommit;
183 return "error inserting $self: $error";
186 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
188 # possibly trigger package unsuspend, doesn't abort transaction on failure
189 $self->unsuspend_balance if $old_balance;
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 } );
465 Returns the text of the associated reason (see L<FS::reason>) for this credit.
471 # Used by FS::Upgrade to migrate to a new database.
473 sub _upgrade_data { # class method
474 my ($class, %opts) = @_;
476 warn "$me upgrading $class\n" if $DEBUG;
478 $class->_upgrade_reasonnum(%opts);
480 if (defined dbdef->table($class->table)->column('reason')) {
482 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
484 foreach ( keys %reasontype_map ) {
485 unless ($conf->config($_)) { # hmmmm
486 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
487 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
488 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
489 my $reason_type = qsearchs( 'reason_type', $hashref );
490 unless ($reason_type) {
491 $reason_type = new FS::reason_type( $hashref );
492 my $error = $reason_type->insert();
493 die "$class had error inserting FS::reason_type into database: $error\n"
496 $conf->set($_, $reason_type->typenum);
500 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
502 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
503 my $reason_type = qsearchs( 'reason_type', $hashref );
504 unless ($reason_type) {
505 $reason_type = new FS::reason_type( $hashref );
506 my $error = $reason_type->insert();
507 die "$class had error inserting FS::reason_type into database: $error\n"
511 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
512 foreach my $plan ( @plans ) {
513 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
514 unless ($pkg->option('reason_type', 1) ) {
515 my $plandata = $pkg->plandata.
516 "reason_type=". $reason_type->typenum. "\n";
517 $pkg->plandata($plandata);
519 $pkg->replace( undef,
520 'pkg_svc' => { map { $_->svcpart => $_->quantity }
523 'primary_svc' => $pkg->svcpart,
525 die "failed setting reason_type option: $error"
532 local($otaker_upgrade_kludge) = 1;
533 local($ignore_empty_reasonnum) = 1;
534 $class->_upgrade_otaker(%opts);
536 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
537 and !$conf->exists('enable_taxproducts') ) {
538 # RT#25458: fix credit line item applications that should refer to a
539 # specific tax allocation
540 my @cust_credit_bill_pkg = qsearch({
541 table => 'cust_credit_bill_pkg',
542 select => 'cust_credit_bill_pkg.*',
543 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
545 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
546 'AND cust_bill_pkg.pkgnum = 0', # is a tax
550 foreach (@cust_credit_bill_pkg) {
551 my $billpkgnum = $_->billpkgnum;
552 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
553 $credits{$billpkgnum} ||= [];
554 push @{ $credits{$billpkgnum} }, $_;
556 TAX_ITEM: foreach my $tax_item (values %tax_items) {
557 my $billpkgnum = $tax_item->billpkgnum;
558 # get all pkg/location/taxrate allocations of this tax line item
559 my @allocations = sort {$b->amount <=> $a->amount}
560 qsearch('cust_bill_pkg_tax_location', {
561 billpkgnum => $billpkgnum
563 # and these are all credit applications to it
564 my @credits = sort {$b->amount <=> $a->amount}
565 @{ $credits{$billpkgnum} };
566 my $c = shift @credits;
567 my $a = shift @allocations; # we will NOT modify these
569 if ( abs($c->amount - $a->amount) < 0.005 ) {
570 # by far the most common case: the tax line item is for a single
571 # tax, so we just fill in the billpkgtaxlocationnum
572 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
573 my $error = $c->replace;
575 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
579 $a = shift @allocations;
580 } elsif ( $c->amount > $a->amount ) {
581 # fairly common: the tax line contains tax for multiple packages
582 # (or multiple taxes) but the credit isn't divided up
583 my $new_link = FS::cust_credit_bill_pkg->new({
584 creditbillnum => $c->creditbillnum,
585 billpkgnum => $c->billpkgnum,
586 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
587 amount => $a->amount,
588 setuprecur => 'setup',
590 my $error = $new_link->insert;
592 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
595 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
596 $a = shift @allocations;
597 } elsif ( $c->amount < 0.005 ) {
598 # also fairly common; we can delete these with no harm
599 my $error = $c->delete;
600 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
602 } elsif ( $c->amount < $a->amount ) {
603 # should never happen, but if it does, handle it gracefully
604 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
605 my $error = $c->replace;
607 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
610 $a->set(amount => $a->amount - $c->amount);
615 if ( $c->amount < 0.005 ) {
616 my $error = $c->delete;
617 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
618 } elsif ( $c->modified ) {
619 # then we've allocated part of it, so reduce the nonspecific
620 # application by that much
621 my $error = $c->replace;
622 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
624 # else there are probably no allocations, i.e. this is a pre-3.x
625 # record that was never migrated over, so leave it alone
627 } # foreach $tax_item
628 FS::upgrade_journal->set_done('cust_credit__tax_link');
640 Returns an SQL fragment to retreive the unapplied amount.
645 my ($class, $start, $end) = @_;
647 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
648 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
649 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
650 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
654 ( SELECT SUM(amount) FROM cust_credit_refund
655 WHERE cust_credit.crednum = cust_credit_refund.crednum
656 $refund_start $refund_end )
660 ( SELECT SUM(amount) FROM cust_credit_bill
661 WHERE cust_credit.crednum = cust_credit_bill.crednum
662 $bill_start $bill_end )
671 Deprecated name for the unapplied_sql method.
678 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
680 #$class->unapplied_sql(@_);
684 =item calculate_tax_adjustment PARAMS
686 Calculate the amount of tax that needs to be credited as part of a lineitem
691 - billpkgnums: arrayref identifying the line items to credit
692 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
693 the lineitem charge is being credited
694 - amounts: arrayref of the amounts to credit on each line item
695 - custnum: the customer all of these invoices belong to, for error checking
697 Returns a hash containing:
698 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
699 - taxtotal: the total tax amount to be credited
700 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
701 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
702 - num: the key within that table
703 - credit: the credit amount to apply to that line
707 sub calculate_tax_adjustment {
708 my ($class, %arg) = @_;
715 my (%cust_bill_pkg, %cust_bill);
717 for (my $i = 0; ; $i++) {
718 my $billpkgnum = $arg{billpkgnums}[$i]
720 my $setuprecur = $arg{setuprecurs}[$i];
721 my $amount = $arg{amounts}[$i];
722 next if $amount == 0;
723 $subtotal += $amount;
724 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
725 ||= FS::cust_bill_pkg->by_key($billpkgnum)
726 or die "lineitem #$billpkgnum not found\n";
728 my $invnum = $cust_bill_pkg->invnum;
729 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
730 $cust_bill{ $invnum}->custnum == $arg{custnum}
731 or die "lineitem #$billpkgnum not found\n";
733 # tax_Xlocation records don't distinguish setup and recur, so calculate
734 # the fraction of setup+recur (after deducting credits) that's setup. This
735 # will also be the fraction of tax (after deducting credits) that's tax on
738 $setup = $cust_bill_pkg->get('setup') || 0;
740 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
742 $recur = $cust_bill_pkg->get('recur') || 0;
744 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
746 my $setup_ratio = $setup / ($setup + $recur);
748 # Calculate the fraction of tax to credit: it's the fraction of this charge
749 # (either setup or recur) that's being credited.
750 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
751 next if $charged == 0; # shouldn't happen, but still...
753 if ($charged < $amount) {
754 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
757 my $credit_ratio = $amount / $charged;
759 # gather taxes that apply to the selected item
761 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
763 foreach my $tax_link (
764 qsearch($table, { taxable_billpkgnum => $billpkgnum })
766 my $tax_amount = $tax_link->amount;
767 # deduct existing credits applied to the tax, for the same reason as
769 foreach ($tax_link->cust_credit_bill_pkg) {
770 $tax_amount -= $_->amount;
772 # split tax amount based on setuprecur
773 # (this method ensures that, if you credit both setup and recur tax,
774 # it always equals the entire tax despite any rounding)
775 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
776 if ( $setuprecur eq 'setup' ) {
777 $tax_amount = $setup_tax;
779 $tax_amount = $tax_amount - $setup_tax;
781 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
782 my $pkey = $tax_link->get($tax_link->primary_key);
786 credit => $tax_credit,
788 $taxtotal += $tax_credit;
790 } #foreach cust_bill_pkg_tax_(rate_)?location
792 } # foreach $billpkgnum
795 subtotal => sprintf('%.2f', $subtotal),
796 taxtotal => sprintf('%.2f', $taxtotal),
797 taxlines => \@taxlines,
801 =item credit_lineitems
805 my $error = FS::cust_credit->credit_lineitems(
807 #the lineitems to credit
808 'billpkgnums' => \@billpkgnums,
809 'setuprecurs' => \@setuprecurs,
810 'amounts' => \@amounts,
811 'apply' => 1, #0 leaves the credit unapplied
814 map { $_ => scalar($cgi->param($_)) }
815 #fields('cust_credit')
816 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
822 #maybe i should just be an insert with extra args instead of a class method
823 sub credit_lineitems {
824 my( $class, %arg ) = @_;
825 my $curuser = $FS::CurrentUser::CurrentUser;
827 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
829 my $cust_main = qsearchs({
830 'table' => 'cust_main',
831 'hashref' => { 'custnum' => $arg{custnum} },
832 'extra_sql' => ' AND '. $curuser->agentnums_sql,
833 }) or return 'unknown customer';
836 local $SIG{HUP} = 'IGNORE';
837 local $SIG{INT} = 'IGNORE';
838 local $SIG{QUIT} = 'IGNORE';
839 local $SIG{TERM} = 'IGNORE';
840 local $SIG{TSTP} = 'IGNORE';
841 local $SIG{PIPE} = 'IGNORE';
843 my $oldAutoCommit = $FS::UID::AutoCommit;
844 local $FS::UID::AutoCommit = 0;
847 #my @cust_bill_pkg = qsearch({
848 # 'select' => 'cust_bill_pkg.*',
849 # 'table' => 'cust_bill_pkg',
850 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
851 # ' LEFT JOIN cust_main USING (custnum) ',
852 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
853 # join( ',', @{$arg{billpkgnums}} ). ')',
854 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
859 my $cust_credit = new FS::cust_credit ( {
860 map { $_ => $arg{$_} }
861 #fields('cust_credit')
862 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
864 $error = $cust_credit->insert;
866 $dbh->rollback if $oldAutoCommit;
867 return "Error inserting credit: $error";
870 unless ( $arg{'apply'} ) {
871 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
876 # keys in all of these are invoice numbers
877 my %cust_credit_bill = ();
878 my %cust_bill_pkg = ();
879 my %cust_credit_bill_pkg = ();
880 my %unapplied_payments = (); #invoice numbers, and then billpaynums
882 # determine the tax adjustments
883 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
885 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
886 my $setuprecur = shift @{$arg{setuprecurs}};
887 my $amount = shift @{$arg{amounts}};
889 my $cust_bill_pkg = qsearchs({
890 'table' => 'cust_bill_pkg',
891 'hashref' => { 'billpkgnum' => $billpkgnum },
892 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
893 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
894 }) or die "unknown billpkgnum $billpkgnum";
896 my $invnum = $cust_bill_pkg->invnum;
898 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
900 $cust_credit_bill{$invnum} += $amount;
901 push @{ $cust_credit_bill_pkg{$invnum} },
902 new FS::cust_credit_bill_pkg {
903 'billpkgnum' => $billpkgnum,
904 'amount' => sprintf('%.2f',$amount),
905 'setuprecur' => $setuprecur,
906 'sdate' => $cust_bill_pkg->sdate,
907 'edate' => $cust_bill_pkg->edate,
909 # unapply payments (but not other credits) from this line item
910 foreach my $cust_bill_pay_pkg (
911 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
913 $error = $cust_bill_pay_pkg->delete;
915 $dbh->rollback if $oldAutoCommit;
916 return "Error unapplying payment: $error";
918 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
919 += $cust_bill_pay_pkg->amount;
923 # do the same for taxes
924 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
925 my $table = $tax_credit->{table};
926 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
927 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
929 my $billpkgnum = $tax_link->billpkgnum;
930 my $cust_bill_pkg = qsearchs({
931 'table' => 'cust_bill_pkg',
932 'hashref' => { 'billpkgnum' => $billpkgnum },
933 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
934 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
935 }) or die "unknown billpkgnum $billpkgnum";
937 my $invnum = $cust_bill_pkg->invnum;
938 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
940 my $amount = $tax_credit->{credit};
941 $cust_credit_bill{$invnum} += $amount;
943 # create a credit application record to the tax line item, earmarked
944 # to the specific cust_bill_pkg_Xlocation
945 push @{ $cust_credit_bill_pkg{$invnum} },
946 new FS::cust_credit_bill_pkg {
947 'billpkgnum' => $billpkgnum,
948 'amount' => sprintf('%.2f', $amount),
949 'setuprecur' => 'setup',
950 $tax_link->primary_key, $tax_credit->{num}
952 # unapply any payments from the tax
953 foreach my $cust_bill_pay_pkg (
954 $cust_bill_pkg->cust_bill_pay_pkg('setup')
956 $error = $cust_bill_pay_pkg->delete;
958 $dbh->rollback if $oldAutoCommit;
959 return "Error unapplying payment: $error";
961 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
962 += $cust_bill_pay_pkg->amount;
967 # now loop through %cust_credit_bill and insert those
970 # (hack to prevent cust_credit_bill_pkg insertion)
971 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
973 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
975 # if we unapplied any payments from line items, also unapply that
976 # amount from the invoice
977 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
978 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
979 or die "broken payment application $billpaynum";
980 my @subapps = $cust_bill_pay->lineitem_applications;
981 $error = $cust_bill_pay->delete; # can't replace
983 my $new_cust_bill_pay = FS::cust_bill_pay->new({
984 $cust_bill_pay->hash,
986 amount => sprintf('%.2f',
987 $cust_bill_pay->amount
988 - $unapplied_payments{$invnum}{$billpaynum}),
991 if ( $new_cust_bill_pay->amount > 0 ) {
992 $error ||= $new_cust_bill_pay->insert;
993 # Also reapply it to everything it was applied to before.
994 # Note that we've already deleted cust_bill_pay_pkg records for the
995 # items we're crediting, so they aren't on this list.
996 foreach my $cust_bill_pay_pkg (@subapps) {
997 $cust_bill_pay_pkg->billpaypkgnum('');
998 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
999 $error ||= $cust_bill_pay_pkg->insert;
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Error unapplying payment: $error";
1007 #insert cust_credit_bill
1009 my $cust_credit_bill = new FS::cust_credit_bill {
1010 'crednum' => $cust_credit->crednum,
1011 'invnum' => $invnum,
1012 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1014 $error = $cust_credit_bill->insert;
1016 $dbh->rollback if $oldAutoCommit;
1017 return "Error applying credit of $cust_credit_bill{$invnum} ".
1018 " to invoice $invnum: $error";
1021 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1022 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1023 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1024 $error = $cust_credit_bill_pkg->insert;
1026 $dbh->rollback if $oldAutoCommit;
1027 return "Error applying credit to line item: $error";
1033 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1038 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1040 =item refund_to_unapply
1042 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1043 (all currently applied refunds that aren't closed.)
1044 Returns empty list if credit itself is closed.
1048 sub refund_to_unapply {
1050 return () if $self->closed;
1052 'table' => 'cust_credit_refund',
1053 'hashref' => { 'crednum' => $self->crednum },
1054 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1055 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1059 =item unapply_refund
1061 Deletes all objects returned by L</refund_to_unapply>.
1065 sub unapply_refund {
1068 local $SIG{HUP} = 'IGNORE';
1069 local $SIG{INT} = 'IGNORE';
1070 local $SIG{QUIT} = 'IGNORE';
1071 local $SIG{TERM} = 'IGNORE';
1072 local $SIG{TSTP} = 'IGNORE';
1073 local $SIG{PIPE} = 'IGNORE';
1075 my $oldAutoCommit = $FS::UID::AutoCommit;
1076 local $FS::UID::AutoCommit = 0;
1078 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1079 my $error = $cust_credit_refund->delete;
1081 dbh->rollback if $oldAutoCommit;
1086 dbh->commit or die dbh->errstr if $oldAutoCommit;
1096 =item process_batch_import
1100 use List::Util qw( min );
1102 use FS::cust_credit_bill;
1103 sub process_batch_import {
1106 # some false laziness with FS::cust_pay::process_batch_import
1109 my $custnum = $hash{'custnum'};
1110 my $agent_custid = $hash{'agent_custid'};
1111 # translate agent_custid into regular custnum
1112 if ($custnum && $agent_custid) {
1113 die "can't specify both custnum and agent_custid\n";
1114 } elsif ($agent_custid) {
1115 # here is the agent virtualization
1116 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1118 $search{'agent_custid'} = $agent_custid
1120 $search{'custnum'} = $custnum
1122 my $cust_main = qsearchs({
1123 'table' => 'cust_main',
1124 'hashref' => \%search,
1125 'extra_sql' => $extra_sql,
1127 die "can't find customer with" .
1128 ($custnum ? " custnum $custnum" : '') .
1129 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1131 die "mismatched customer number\n"
1132 if $custnum && ($custnum ne $cust_main->custnum);
1133 $custnum = $cust_main->custnum;
1135 $hash{'custnum'} = $custnum;
1136 delete($hash{'agent_custid'});
1140 my $opt = { 'table' => 'cust_credit',
1141 'params' => [ '_date', 'credbatch' ],
1142 'formats' => { 'simple' =>
1143 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1146 'format_hash_callbacks' => { 'simple' => $hashcb },
1147 'postinsert_callback' => sub {
1148 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1150 if ( $cust_credit->invnum ) {
1152 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1153 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1155 my $cust_credit_bill = new FS::cust_credit_bill ( {
1156 'crednum' => $cust_credit->crednum,
1157 'invnum' => $cust_bill->invnum,
1158 'amount' => $amount,
1160 my $error = $cust_credit_bill->insert;
1161 return '' unless $error;
1165 #apply_payments_and_credits ?
1166 $cust_credit->cust_main->apply_credits;
1173 FS::Record::process_batch_import( $job, $opt, @_ );
1181 The delete method. The replace method.
1183 B<credited> and B<credited_sql> are now called B<unapplied> and
1184 B<unapplied_sql>. The old method names should start to give warnings.
1188 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1189 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base