1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
6 use vars qw( $conf $me $DEBUG
7 $otaker_upgrade_kludge $ignore_empty_reasonnum
9 use List::Util qw( min );
11 use FS::UID qw( dbh );
12 use FS::Record qw( qsearch qsearchs dbdef );
16 use FS::cust_credit_bill;
23 use FS::cust_credit_void;
24 use FS::cust_bill_pkg;
25 use FS::upgrade_journal;
27 $me = '[ FS::cust_credit ]';
30 $otaker_upgrade_kludge = 0;
31 $ignore_empty_reasonnum = 0;
33 #ask FS::UID to run this stuff for us later
34 $FS::UID::callback{'FS::cust_credit'} = sub {
40 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
41 'cancel_credit_type' => 'Cancellation Credit',
46 FS::cust_credit - Object methods for cust_credit records
52 $record = new FS::cust_credit \%hash;
53 $record = new FS::cust_credit { 'column' => 'value' };
55 $error = $record->insert;
57 $error = $new_record->replace($old_record);
59 $error = $record->delete;
61 $error = $record->check;
65 An FS::cust_credit object represents a credit; the equivalent of a negative
66 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
67 FS::Record. The following fields are currently supported:
73 Primary key (assigned automatically for new credits)
77 Customer (see L<FS::cust_main>)
85 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
86 L<Time::Local> and L<Date::Parse> for conversion functions.
90 Order taker (see L<FS::access_user>)
98 Reason (see L<FS::reason>)
106 Books closed flag, empty or `Y'
110 Desired pkgnum when using experimental package balances.
120 Creates a new credit. To add the credit to the database, see L<"insert">.
124 sub table { 'cust_credit'; }
125 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum }
126 sub cust_unlinked_msg {
128 "WARNING: can't find cust_main.custnum ". $self->custnum.
129 ' (cust_credit.crednum '. $self->crednum. ')';
132 =item insert [ OPTION => VALUE ... ]
134 Adds this credit to the database ("Posts" the credit). If there is an error,
135 returns the error, otherwise returns false.
137 Ooptions are passed as a list of keys and values. Available options:
143 L<FS::reason_type|Reason> type for newly-inserted reason
145 =item cust_credit_source_bill_pkg
148 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
149 They will have their crednum set and will be inserted along with this credit.
156 my ($self, %options) = @_;
158 local $SIG{HUP} = 'IGNORE';
159 local $SIG{INT} = 'IGNORE';
160 local $SIG{QUIT} = 'IGNORE';
161 local $SIG{TERM} = 'IGNORE';
162 local $SIG{TSTP} = 'IGNORE';
163 local $SIG{PIPE} = 'IGNORE';
165 my $oldAutoCommit = $FS::UID::AutoCommit;
166 local $FS::UID::AutoCommit = 0;
169 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
170 my $old_balance = $cust_main->balance;
172 if (!$self->reasonnum) {
173 my $reason_text = $self->get('reason')
174 or return "reason text or existing reason required";
175 my $reason_type = $options{'reason_type'}
176 or return "reason type required";
179 my $reason = FS::reason->new_or_existing(
180 reason => $reason_text,
181 type => $reason_type,
185 $dbh->rollback if $oldAutoCommit;
186 return "failed to set credit reason: $@";
188 $self->set('reasonnum', $reason->reasonnum);
191 $self->setfield('reason', '');
193 my $error = $self->SUPER::insert;
195 $dbh->rollback if $oldAutoCommit;
196 return "error inserting $self: $error";
199 if ( $options{'cust_credit_source_bill_pkg'} ) {
200 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
201 $ccsbr->crednum( $self->crednum );
202 $error = $ccsbr->insert;
204 $dbh->rollback if $oldAutoCommit;
205 return "error inserting $ccsbr: $error";
210 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
212 # possibly trigger package unsuspend, doesn't abort transaction on failure
213 $self->unsuspend_balance if $old_balance;
215 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
223 Unless the closed flag is set, deletes this credit and all associated
224 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
225 the void method instead to leave a record of the deleted credit.
229 # very similar to FS::cust_pay::delete
234 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
236 local $SIG{HUP} = 'IGNORE';
237 local $SIG{INT} = 'IGNORE';
238 local $SIG{QUIT} = 'IGNORE';
239 local $SIG{TERM} = 'IGNORE';
240 local $SIG{TSTP} = 'IGNORE';
241 local $SIG{PIPE} = 'IGNORE';
243 my $oldAutoCommit = $FS::UID::AutoCommit;
244 local $FS::UID::AutoCommit = 0;
247 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
248 my $error = $cust_credit_bill->delete;
250 $dbh->rollback if $oldAutoCommit;
255 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
256 my $error = $cust_credit_refund->delete;
258 $dbh->rollback if $oldAutoCommit;
263 my $error = $self->SUPER::delete(@_);
265 $dbh->rollback if $oldAutoCommit;
269 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
275 =item replace [ OLD_RECORD ]
277 You can, but probably shouldn't modify credits...
279 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
280 supplied, replaces this record. If there is an error, returns the error,
281 otherwise returns false.
287 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
288 $self->SUPER::replace(@_);
293 Checks all fields to make sure this is a valid credit. If there is an error,
294 returns the error, otherwise returns false. Called by the insert and replace
302 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
305 $self->ut_numbern('crednum')
306 || $self->ut_number('custnum')
307 || $self->ut_numbern('_date')
308 || $self->ut_money('amount')
309 || $self->ut_alphan('otaker')
310 || $self->ut_textn('reason')
311 || $self->ut_textn('addlinfo')
312 || $self->ut_enum('closed', [ '', 'Y' ])
313 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
314 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
315 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
316 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
317 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
319 return $error if $error;
321 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
322 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
323 return $error if $error;
325 return "amount must be > 0 " if $self->amount <= 0;
327 return "amount must be greater or equal to amount applied"
328 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
330 return "Unknown customer"
331 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
333 $self->_date(time) unless $self->_date;
338 =item void [ REASON ]
340 Voids this credit: deletes the credit and all associated applications and
341 adds a record of the voided credit to the cust_credit_void table.
349 unless (ref($reason) || !$reason) {
350 $reason = FS::reason->new_or_existing(
352 'type' => 'Void credit',
357 local $SIG{HUP} = 'IGNORE';
358 local $SIG{INT} = 'IGNORE';
359 local $SIG{QUIT} = 'IGNORE';
360 local $SIG{TERM} = 'IGNORE';
361 local $SIG{TSTP} = 'IGNORE';
362 local $SIG{PIPE} = 'IGNORE';
364 my $oldAutoCommit = $FS::UID::AutoCommit;
365 local $FS::UID::AutoCommit = 0;
368 my $cust_credit_void = new FS::cust_credit_void ( {
369 map { $_ => $self->get($_) } $self->fields
371 $cust_credit_void->set('void_reasonnum', $reason->reasonnum) if $reason;
372 my $error = $cust_credit_void->insert;
374 $dbh->rollback if $oldAutoCommit;
378 $error = $self->delete();
380 $dbh->rollback if $oldAutoCommit;
384 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
390 =item cust_credit_refund
392 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
396 sub cust_credit_refund {
398 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
399 sort { $a->_date <=> $b->_date }
400 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
404 =item cust_credit_bill
406 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
411 sub cust_credit_bill {
413 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
414 sort { $a->_date <=> $b->_date }
415 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
421 Returns the amount of this credit that is still unapplied/outstanding;
422 amount minus all refund applications (see L<FS::cust_credit_refund>) and
423 applications to invoices (see L<FS::cust_credit_bill>).
429 my $amount = $self->amount;
430 $amount -= $_->amount foreach ( $self->cust_credit_refund );
431 $amount -= $_->amount foreach ( $self->cust_credit_bill );
432 sprintf( "%.2f", $amount );
437 Deprecated name for the unapplied method.
443 #carp "cust_credit->credited deprecated; use ->unapplied";
444 $self->unapplied(@_);
449 Returns the customer (see L<FS::cust_main>) for this credit.
455 # Used by FS::Upgrade to migrate to a new database.
457 sub _upgrade_data { # class method
458 my ($class, %opts) = @_;
460 warn "$me upgrading $class\n" if $DEBUG;
462 $class->_upgrade_reasonnum(%opts);
464 if (defined dbdef->table($class->table)->column('reason')) {
466 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
468 foreach ( keys %reasontype_map ) {
469 unless ($conf->config($_)) { # hmmmm
470 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
471 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
472 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
473 my $reason_type = qsearchs( 'reason_type', $hashref );
474 unless ($reason_type) {
475 $reason_type = new FS::reason_type( $hashref );
476 my $error = $reason_type->insert();
477 die "$class had error inserting FS::reason_type into database: $error\n"
480 $conf->set($_, $reason_type->typenum);
484 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
486 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
487 my $reason_type = qsearchs( 'reason_type', $hashref );
488 unless ($reason_type) {
489 $reason_type = new FS::reason_type( $hashref );
490 my $error = $reason_type->insert();
491 die "$class had error inserting FS::reason_type into database: $error\n"
495 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
496 foreach my $plan ( @plans ) {
497 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
498 unless ($pkg->option('reason_type', 1) ) {
499 my $plandata = $pkg->plandata.
500 "reason_type=". $reason_type->typenum. "\n";
501 $pkg->plandata($plandata);
503 $pkg->replace( undef,
504 'pkg_svc' => { map { $_->svcpart => $_->quantity }
507 'primary_svc' => $pkg->svcpart,
509 die "failed setting reason_type option: $error"
516 local($otaker_upgrade_kludge) = 1;
517 local($ignore_empty_reasonnum) = 1;
518 $class->_upgrade_otaker(%opts);
520 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
521 and !$conf->config('tax_data_vendor') ) {
522 # RT#25458: fix credit line item applications that should refer to a
523 # specific tax allocation
524 my @cust_credit_bill_pkg = qsearch({
525 table => 'cust_credit_bill_pkg',
526 select => 'cust_credit_bill_pkg.*',
527 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
529 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
530 'AND cust_bill_pkg.pkgnum = 0', # is a tax
534 foreach (@cust_credit_bill_pkg) {
535 my $billpkgnum = $_->billpkgnum;
536 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
537 $credits{$billpkgnum} ||= [];
538 push @{ $credits{$billpkgnum} }, $_;
540 TAX_ITEM: foreach my $tax_item (values %tax_items) {
541 my $billpkgnum = $tax_item->billpkgnum;
542 # get all pkg/location/taxrate allocations of this tax line item
543 my @allocations = sort {$b->amount <=> $a->amount}
544 qsearch('cust_bill_pkg_tax_location', {
545 billpkgnum => $billpkgnum
547 # and these are all credit applications to it
548 my @credits = sort {$b->amount <=> $a->amount}
549 @{ $credits{$billpkgnum} };
550 my $c = shift @credits;
551 my $a = shift @allocations; # we will NOT modify these
553 if ( abs($c->amount - $a->amount) < 0.005 ) {
554 # by far the most common case: the tax line item is for a single
555 # tax, so we just fill in the billpkgtaxlocationnum
556 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
557 my $error = $c->replace;
559 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
563 $a = shift @allocations;
564 } elsif ( $c->amount > $a->amount ) {
565 # fairly common: the tax line contains tax for multiple packages
566 # (or multiple taxes) but the credit isn't divided up
567 my $new_link = FS::cust_credit_bill_pkg->new({
568 creditbillnum => $c->creditbillnum,
569 billpkgnum => $c->billpkgnum,
570 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
571 amount => $a->amount,
572 setuprecur => 'setup',
574 my $error = $new_link->insert;
576 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
579 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
580 $a = shift @allocations;
581 } elsif ( $c->amount < 0.005 ) {
582 # also fairly common; we can delete these with no harm
583 my $error = $c->delete;
584 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
586 } elsif ( $c->amount < $a->amount ) {
587 # should never happen, but if it does, handle it gracefully
588 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
589 my $error = $c->replace;
591 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
594 $a->set(amount => $a->amount - $c->amount);
599 if ( $c->amount < 0.005 ) {
600 my $error = $c->delete;
601 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
602 } elsif ( $c->modified ) {
603 # then we've allocated part of it, so reduce the nonspecific
604 # application by that much
605 my $error = $c->replace;
606 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
608 # else there are probably no allocations, i.e. this is a pre-3.x
609 # record that was never migrated over, so leave it alone
611 } # foreach $tax_item
612 FS::upgrade_journal->set_done('cust_credit__tax_link');
624 Returns an SQL fragment to retreive the unapplied amount.
629 my ($class, $start, $end) = @_;
631 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
632 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
633 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
634 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
638 ( SELECT SUM(amount) FROM cust_credit_refund
639 WHERE cust_credit.crednum = cust_credit_refund.crednum
640 $refund_start $refund_end )
644 ( SELECT SUM(amount) FROM cust_credit_bill
645 WHERE cust_credit.crednum = cust_credit_bill.crednum
646 $bill_start $bill_end )
655 Deprecated name for the unapplied_sql method.
662 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
664 #$class->unapplied_sql(@_);
668 =item calculate_tax_adjustment PARAMS
670 Calculate the amount of tax that needs to be credited as part of a lineitem
675 - billpkgnums: arrayref identifying the line items to credit
676 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
677 the lineitem charge is being credited
678 - amounts: arrayref of the amounts to credit on each line item
679 - custnum: the customer all of these invoices belong to, for error checking
681 Returns a hash containing:
682 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
683 - taxtotal: the total tax amount to be credited
684 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
685 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
686 - num: the key within that table
687 - credit: the credit amount to apply to that line
691 sub calculate_tax_adjustment {
692 my ($class, %arg) = @_;
699 my (%cust_bill_pkg, %cust_bill);
701 for (my $i = 0; ; $i++) {
702 my $billpkgnum = $arg{billpkgnums}[$i]
704 my $setuprecur = $arg{setuprecurs}[$i];
705 my $amount = $arg{amounts}[$i];
706 next if $amount == 0;
707 $subtotal += $amount;
708 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
709 ||= FS::cust_bill_pkg->by_key($billpkgnum)
710 or die "lineitem #$billpkgnum not found\n";
712 my $invnum = $cust_bill_pkg->invnum;
713 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
714 $cust_bill{ $invnum}->custnum == $arg{custnum}
715 or die "lineitem #$billpkgnum not found\n";
717 # tax_Xlocation records don't distinguish setup and recur, so calculate
718 # the fraction of setup+recur (after deducting credits) that's setup. This
719 # will also be the fraction of tax (after deducting credits) that's tax on
722 $setup = $cust_bill_pkg->get('setup') || 0;
724 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
726 $recur = $cust_bill_pkg->get('recur') || 0;
728 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
730 my $setup_ratio = $setup / ($setup + $recur);
732 # Calculate the fraction of tax to credit: it's the fraction of this charge
733 # (either setup or recur) that's being credited.
734 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
735 next if $charged == 0; # shouldn't happen, but still...
737 if ($charged < $amount) {
738 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
741 my $credit_ratio = $amount / $charged;
743 # gather taxes that apply to the selected item
745 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
747 foreach my $tax_link (
748 qsearch($table, { taxable_billpkgnum => $billpkgnum })
750 my $tax_amount = $tax_link->amount;
751 # deduct existing credits applied to the tax, for the same reason as
753 foreach ($tax_link->cust_credit_bill_pkg) {
754 $tax_amount -= $_->amount;
756 # split tax amount based on setuprecur
757 # (this method ensures that, if you credit both setup and recur tax,
758 # it always equals the entire tax despite any rounding)
759 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
760 if ( $setuprecur eq 'setup' ) {
761 $tax_amount = $setup_tax;
763 $tax_amount = $tax_amount - $setup_tax;
765 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
766 my $pkey = $tax_link->get($tax_link->primary_key);
770 credit => $tax_credit,
772 $taxtotal += $tax_credit;
774 } #foreach cust_bill_pkg_tax_(rate_)?location
776 } # foreach $billpkgnum
779 subtotal => sprintf('%.2f', $subtotal),
780 taxtotal => sprintf('%.2f', $taxtotal),
781 taxlines => \@taxlines,
785 =item credit_lineitems
789 my $error = FS::cust_credit->credit_lineitems(
791 #the lineitems to credit
792 'billpkgnums' => \@billpkgnums,
793 'setuprecurs' => \@setuprecurs,
794 'amounts' => \@amounts,
795 'apply' => 1, #0 leaves the credit unapplied
798 map { $_ => scalar($cgi->param($_)) }
799 #fields('cust_credit')
800 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
806 #maybe i should just be an insert with extra args instead of a class method
807 sub credit_lineitems {
808 my( $class, %arg ) = @_;
809 my $curuser = $FS::CurrentUser::CurrentUser;
811 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
813 my $cust_main = qsearchs({
814 'table' => 'cust_main',
815 'hashref' => { 'custnum' => $arg{custnum} },
816 'extra_sql' => ' AND '. $curuser->agentnums_sql,
817 }) or return 'unknown customer';
820 local $SIG{HUP} = 'IGNORE';
821 local $SIG{INT} = 'IGNORE';
822 local $SIG{QUIT} = 'IGNORE';
823 local $SIG{TERM} = 'IGNORE';
824 local $SIG{TSTP} = 'IGNORE';
825 local $SIG{PIPE} = 'IGNORE';
827 my $oldAutoCommit = $FS::UID::AutoCommit;
828 local $FS::UID::AutoCommit = 0;
831 #my @cust_bill_pkg = qsearch({
832 # 'select' => 'cust_bill_pkg.*',
833 # 'table' => 'cust_bill_pkg',
834 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
835 # ' LEFT JOIN cust_main USING (custnum) ',
836 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
837 # join( ',', @{$arg{billpkgnums}} ). ')',
838 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
843 my $cust_credit = new FS::cust_credit ( {
844 map { $_ => $arg{$_} }
845 #fields('cust_credit')
846 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
848 $error = $cust_credit->insert;
850 $dbh->rollback if $oldAutoCommit;
851 return "Error inserting credit: $error";
854 unless ( $arg{'apply'} ) {
855 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
860 # keys in all of these are invoice numbers
861 my %cust_credit_bill = ();
862 my %cust_bill_pkg = ();
863 my %cust_credit_bill_pkg = ();
864 my %unapplied_payments = (); #invoice numbers, and then billpaynums
866 # determine the tax adjustments
867 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
869 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
870 my $setuprecur = shift @{$arg{setuprecurs}};
871 my $amount = shift @{$arg{amounts}};
873 my $cust_bill_pkg = qsearchs({
874 'table' => 'cust_bill_pkg',
875 'hashref' => { 'billpkgnum' => $billpkgnum },
876 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
877 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
878 }) or die "unknown billpkgnum $billpkgnum";
880 my $invnum = $cust_bill_pkg->invnum;
882 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
884 $cust_credit_bill{$invnum} += $amount;
885 push @{ $cust_credit_bill_pkg{$invnum} },
886 new FS::cust_credit_bill_pkg {
887 'billpkgnum' => $billpkgnum,
888 'amount' => sprintf('%.2f',$amount),
889 'setuprecur' => $setuprecur,
890 'sdate' => $cust_bill_pkg->sdate,
891 'edate' => $cust_bill_pkg->edate,
893 # unapply payments (but not other credits) from this line item
894 foreach my $cust_bill_pay_pkg (
895 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
897 $error = $cust_bill_pay_pkg->delete;
899 $dbh->rollback if $oldAutoCommit;
900 return "Error unapplying payment: $error";
902 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
903 += $cust_bill_pay_pkg->amount;
907 # do the same for taxes
908 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
909 my $table = $tax_credit->{table};
910 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
911 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
913 my $billpkgnum = $tax_link->billpkgnum;
914 my $cust_bill_pkg = qsearchs({
915 'table' => 'cust_bill_pkg',
916 'hashref' => { 'billpkgnum' => $billpkgnum },
917 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
918 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
919 }) or die "unknown billpkgnum $billpkgnum";
921 my $invnum = $cust_bill_pkg->invnum;
922 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
924 my $amount = $tax_credit->{credit};
925 $cust_credit_bill{$invnum} += $amount;
927 # create a credit application record to the tax line item, earmarked
928 # to the specific cust_bill_pkg_Xlocation
929 push @{ $cust_credit_bill_pkg{$invnum} },
930 new FS::cust_credit_bill_pkg {
931 'billpkgnum' => $billpkgnum,
932 'amount' => sprintf('%.2f', $amount),
933 'setuprecur' => 'setup',
934 $tax_link->primary_key, $tax_credit->{num}
936 # unapply any payments from the tax
937 foreach my $cust_bill_pay_pkg (
938 $cust_bill_pkg->cust_bill_pay_pkg('setup')
940 $error = $cust_bill_pay_pkg->delete;
942 $dbh->rollback if $oldAutoCommit;
943 return "Error unapplying payment: $error";
945 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
946 += $cust_bill_pay_pkg->amount;
951 # now loop through %cust_credit_bill and insert those
954 # (hack to prevent cust_credit_bill_pkg insertion)
955 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
957 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
959 # if we unapplied any payments from line items, also unapply that
960 # amount from the invoice
961 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
962 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
963 or die "broken payment application $billpaynum";
964 my @subapps = $cust_bill_pay->lineitem_applications;
965 $error = $cust_bill_pay->delete; # can't replace
967 my $new_cust_bill_pay = FS::cust_bill_pay->new({
968 $cust_bill_pay->hash,
970 amount => sprintf('%.2f',
971 $cust_bill_pay->amount
972 - $unapplied_payments{$invnum}{$billpaynum}),
975 if ( $new_cust_bill_pay->amount > 0 ) {
976 $error ||= $new_cust_bill_pay->insert;
977 # Also reapply it to everything it was applied to before.
978 # Note that we've already deleted cust_bill_pay_pkg records for the
979 # items we're crediting, so they aren't on this list.
980 foreach my $cust_bill_pay_pkg (@subapps) {
981 $cust_bill_pay_pkg->billpaypkgnum('');
982 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
983 $error ||= $cust_bill_pay_pkg->insert;
987 $dbh->rollback if $oldAutoCommit;
988 return "Error unapplying payment: $error";
991 #insert cust_credit_bill
993 my $cust_credit_bill = new FS::cust_credit_bill {
994 'crednum' => $cust_credit->crednum,
996 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
998 $error = $cust_credit_bill->insert;
1000 $dbh->rollback if $oldAutoCommit;
1001 return "Error applying credit of $cust_credit_bill{$invnum} ".
1002 " to invoice $invnum: $error";
1005 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1006 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1007 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1008 $error = $cust_credit_bill_pkg->insert;
1010 $dbh->rollback if $oldAutoCommit;
1011 return "Error applying credit to line item: $error";
1017 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1022 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1024 =item refund_to_unapply
1026 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1027 (all currently applied refunds that aren't closed.)
1028 Returns empty list if credit itself is closed.
1032 sub refund_to_unapply {
1034 return () if $self->closed;
1036 'table' => 'cust_credit_refund',
1037 'hashref' => { 'crednum' => $self->crednum },
1038 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1039 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1043 =item unapply_refund
1045 Deletes all objects returned by L</refund_to_unapply>.
1049 sub unapply_refund {
1052 local $SIG{HUP} = 'IGNORE';
1053 local $SIG{INT} = 'IGNORE';
1054 local $SIG{QUIT} = 'IGNORE';
1055 local $SIG{TERM} = 'IGNORE';
1056 local $SIG{TSTP} = 'IGNORE';
1057 local $SIG{PIPE} = 'IGNORE';
1059 my $oldAutoCommit = $FS::UID::AutoCommit;
1060 local $FS::UID::AutoCommit = 0;
1062 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1063 my $error = $cust_credit_refund->delete;
1065 dbh->rollback if $oldAutoCommit;
1070 dbh->commit or die dbh->errstr if $oldAutoCommit;
1080 =item process_batch_import
1084 use List::Util qw( min );
1086 use FS::cust_credit_bill;
1087 sub process_batch_import {
1090 # some false laziness with FS::cust_pay::process_batch_import
1093 my $custnum = $hash{'custnum'};
1094 my $agent_custid = $hash{'agent_custid'};
1095 # translate agent_custid into regular custnum
1096 if ($custnum && $agent_custid) {
1097 die "can't specify both custnum and agent_custid\n";
1098 } elsif ($agent_custid) {
1099 # here is the agent virtualization
1100 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1102 $search{'agent_custid'} = $agent_custid
1104 $search{'custnum'} = $custnum
1106 my $cust_main = qsearchs({
1107 'table' => 'cust_main',
1108 'hashref' => \%search,
1109 'extra_sql' => $extra_sql,
1111 die "can't find customer with" .
1112 ($custnum ? " custnum $custnum" : '') .
1113 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1115 die "mismatched customer number\n"
1116 if $custnum && ($custnum ne $cust_main->custnum);
1117 $custnum = $cust_main->custnum;
1119 $hash{'custnum'} = $custnum;
1120 delete($hash{'agent_custid'});
1124 my $opt = { 'table' => 'cust_credit',
1125 'params' => [ '_date', 'credbatch' ],
1126 'formats' => { 'simple' =>
1127 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1130 'format_hash_callbacks' => { 'simple' => $hashcb },
1131 'postinsert_callback' => sub {
1132 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1134 if ( $cust_credit->invnum ) {
1136 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1137 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1139 my $cust_credit_bill = new FS::cust_credit_bill ( {
1140 'crednum' => $cust_credit->crednum,
1141 'invnum' => $cust_bill->invnum,
1142 'amount' => $amount,
1144 my $error = $cust_credit_bill->insert;
1145 return '' unless $error;
1149 #apply_payments_and_credits ?
1150 $cust_credit->cust_main->apply_credits;
1157 FS::Record::process_batch_import( $job, $opt, @_ );
1165 The delete method. The replace method.
1167 B<credited> and B<credited_sql> are now called B<unapplied> and
1168 B<unapplied_sql>. The old method names should start to give warnings.
1172 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1173 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base