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> 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 unless ( $cust_main ) {
171 $dbh->rollback if $oldAutoCommit;
172 return "Unknown custnum ". $self->custnum;
174 my $old_balance = $cust_main->balance;
176 if (!$self->reasonnum) {
177 my $reason_text = $self->get('reason')
178 or return "reason text or existing reason required";
179 my $reason_type = $options{'reason_type'}
180 or return "reason type required";
183 my $reason = FS::reason->new_or_existing(
184 reason => $reason_text,
185 type => $reason_type,
189 $dbh->rollback if $oldAutoCommit;
190 return "failed to set credit reason: $@";
192 $self->set('reasonnum', $reason->reasonnum);
195 $self->setfield('reason', '');
197 my $error = $self->SUPER::insert;
199 $dbh->rollback if $oldAutoCommit;
200 return "error inserting $self: $error";
203 if ( $options{'cust_credit_source_bill_pkg'} ) {
204 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
205 $ccsbr->crednum( $self->crednum );
206 $error = $ccsbr->insert;
208 $dbh->rollback if $oldAutoCommit;
209 return "error inserting $ccsbr: $error";
214 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
216 # possibly trigger package unsuspend, doesn't abort transaction on failure
217 $self->unsuspend_balance if $old_balance;
219 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
227 Unless the closed flag is set, deletes this credit and all associated
228 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
229 the void method instead to leave a record of the deleted credit.
233 # very similar to FS::cust_pay::delete
238 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
240 local $SIG{HUP} = 'IGNORE';
241 local $SIG{INT} = 'IGNORE';
242 local $SIG{QUIT} = 'IGNORE';
243 local $SIG{TERM} = 'IGNORE';
244 local $SIG{TSTP} = 'IGNORE';
245 local $SIG{PIPE} = 'IGNORE';
247 my $oldAutoCommit = $FS::UID::AutoCommit;
248 local $FS::UID::AutoCommit = 0;
251 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
252 my $error = $cust_credit_bill->delete;
254 $dbh->rollback if $oldAutoCommit;
259 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
260 my $error = $cust_credit_refund->delete;
262 $dbh->rollback if $oldAutoCommit;
267 my $error = $self->SUPER::delete(@_);
269 $dbh->rollback if $oldAutoCommit;
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.
353 unless (ref($reason) || !$reason) {
354 $reason = FS::reason->new_or_existing(
356 'type' => 'Void credit',
361 local $SIG{HUP} = 'IGNORE';
362 local $SIG{INT} = 'IGNORE';
363 local $SIG{QUIT} = 'IGNORE';
364 local $SIG{TERM} = 'IGNORE';
365 local $SIG{TSTP} = 'IGNORE';
366 local $SIG{PIPE} = 'IGNORE';
368 my $oldAutoCommit = $FS::UID::AutoCommit;
369 local $FS::UID::AutoCommit = 0;
372 my $cust_credit_void = new FS::cust_credit_void ( {
373 map { $_ => $self->get($_) } $self->fields
375 $cust_credit_void->set('void_reasonnum', $reason->reasonnum) if $reason;
376 my $error = $cust_credit_void->insert;
378 $dbh->rollback if $oldAutoCommit;
382 $error = $self->delete();
384 $dbh->rollback if $oldAutoCommit;
388 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
394 =item cust_credit_refund
396 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
400 sub cust_credit_refund {
402 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
403 sort { $a->_date <=> $b->_date }
404 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
408 =item cust_credit_bill
410 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
415 sub cust_credit_bill {
417 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
418 sort { $a->_date <=> $b->_date }
419 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
425 Returns the amount of this credit that is still unapplied/outstanding;
426 amount minus all refund applications (see L<FS::cust_credit_refund>) and
427 applications to invoices (see L<FS::cust_credit_bill>).
433 my $amount = $self->amount;
434 $amount -= $_->amount foreach ( $self->cust_credit_refund );
435 $amount -= $_->amount foreach ( $self->cust_credit_bill );
436 sprintf( "%.2f", $amount );
441 Deprecated name for the unapplied method.
447 #carp "cust_credit->credited deprecated; use ->unapplied";
448 $self->unapplied(@_);
453 Returns the customer (see L<FS::cust_main>) for this credit.
459 # Used by FS::Upgrade to migrate to a new database.
461 sub _upgrade_data { # class method
462 my ($class, %opts) = @_;
464 warn "$me upgrading $class\n" if $DEBUG;
466 $class->_upgrade_reasonnum(%opts);
468 if (defined dbdef->table($class->table)->column('reason')) {
470 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
472 foreach ( keys %reasontype_map ) {
473 unless ($conf->config($_)) { # hmmmm
474 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
475 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
476 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
477 my $reason_type = qsearchs( 'reason_type', $hashref );
478 unless ($reason_type) {
479 $reason_type = new FS::reason_type( $hashref );
480 my $error = $reason_type->insert();
481 die "$class had error inserting FS::reason_type into database: $error\n"
484 $conf->set($_, $reason_type->typenum);
488 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
490 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
491 my $reason_type = qsearchs( 'reason_type', $hashref );
492 unless ($reason_type) {
493 $reason_type = new FS::reason_type( $hashref );
494 my $error = $reason_type->insert();
495 die "$class had error inserting FS::reason_type into database: $error\n"
499 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
500 foreach my $plan ( @plans ) {
501 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
502 unless ($pkg->option('reason_type', 1) ) {
503 my $plandata = $pkg->plandata.
504 "reason_type=". $reason_type->typenum. "\n";
505 $pkg->plandata($plandata);
507 $pkg->replace( undef,
508 'pkg_svc' => { map { $_->svcpart => $_->quantity }
511 'primary_svc' => $pkg->svcpart,
513 die "failed setting reason_type option: $error"
520 local($otaker_upgrade_kludge) = 1;
521 local($ignore_empty_reasonnum) = 1;
522 $class->_upgrade_otaker(%opts);
524 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
525 and !$conf->config('tax_data_vendor') ) {
526 # RT#25458: fix credit line item applications that should refer to a
527 # specific tax allocation
528 my @cust_credit_bill_pkg = qsearch({
529 table => 'cust_credit_bill_pkg',
530 select => 'cust_credit_bill_pkg.*',
531 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
533 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
534 'AND cust_bill_pkg.pkgnum = 0', # is a tax
538 foreach (@cust_credit_bill_pkg) {
539 my $billpkgnum = $_->billpkgnum;
540 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
541 $credits{$billpkgnum} ||= [];
542 push @{ $credits{$billpkgnum} }, $_;
544 TAX_ITEM: foreach my $tax_item (values %tax_items) {
545 my $billpkgnum = $tax_item->billpkgnum;
546 # get all pkg/location/taxrate allocations of this tax line item
547 my @allocations = sort {$b->amount <=> $a->amount}
548 qsearch('cust_bill_pkg_tax_location', {
549 billpkgnum => $billpkgnum
551 # and these are all credit applications to it
552 my @credits = sort {$b->amount <=> $a->amount}
553 @{ $credits{$billpkgnum} };
554 my $c = shift @credits;
555 my $a = shift @allocations; # we will NOT modify these
557 if ( abs($c->amount - $a->amount) < 0.005 ) {
558 # by far the most common case: the tax line item is for a single
559 # tax, so we just fill in the billpkgtaxlocationnum
560 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
561 my $error = $c->replace;
563 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
567 $a = shift @allocations;
568 } elsif ( $c->amount > $a->amount ) {
569 # fairly common: the tax line contains tax for multiple packages
570 # (or multiple taxes) but the credit isn't divided up
571 my $new_link = FS::cust_credit_bill_pkg->new({
572 creditbillnum => $c->creditbillnum,
573 billpkgnum => $c->billpkgnum,
574 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
575 amount => $a->amount,
576 setuprecur => 'setup',
578 my $error = $new_link->insert;
580 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
583 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
584 $a = shift @allocations;
585 } elsif ( $c->amount < 0.005 ) {
586 # also fairly common; we can delete these with no harm
587 my $error = $c->delete;
588 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
590 } elsif ( $c->amount < $a->amount ) {
591 # should never happen, but if it does, handle it gracefully
592 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
593 my $error = $c->replace;
595 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
598 $a->set(amount => $a->amount - $c->amount);
603 if ( $c->amount < 0.005 ) {
604 my $error = $c->delete;
605 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
606 } elsif ( $c->modified ) {
607 # then we've allocated part of it, so reduce the nonspecific
608 # application by that much
609 my $error = $c->replace;
610 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
612 # else there are probably no allocations, i.e. this is a pre-3.x
613 # record that was never migrated over, so leave it alone
615 } # foreach $tax_item
616 FS::upgrade_journal->set_done('cust_credit__tax_link');
628 Returns an SQL fragment to retreive the unapplied amount.
633 my ($class, $start, $end) = @_;
635 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
636 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
637 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
638 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
642 ( SELECT SUM(amount) FROM cust_credit_refund
643 WHERE cust_credit.crednum = cust_credit_refund.crednum
644 $refund_start $refund_end )
648 ( SELECT SUM(amount) FROM cust_credit_bill
649 WHERE cust_credit.crednum = cust_credit_bill.crednum
650 $bill_start $bill_end )
659 Deprecated name for the unapplied_sql method.
666 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
668 #$class->unapplied_sql(@_);
672 =item calculate_tax_adjustment PARAMS
674 Calculate the amount of tax that needs to be credited as part of a lineitem
679 - billpkgnums: arrayref identifying the line items to credit
680 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
681 the lineitem charge is being credited
682 - amounts: arrayref of the amounts to credit on each line item
683 - custnum: the customer all of these invoices belong to, for error checking
685 Returns a hash containing:
686 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
687 - taxtotal: the total tax amount to be credited
688 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
689 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
690 - num: the key within that table
691 - credit: the credit amount to apply to that line
695 sub calculate_tax_adjustment {
696 my ($class, %arg) = @_;
703 my (%cust_bill_pkg, %cust_bill);
705 for (my $i = 0; ; $i++) {
706 my $billpkgnum = $arg{billpkgnums}[$i]
708 my $setuprecur = $arg{setuprecurs}[$i];
709 my $amount = $arg{amounts}[$i];
710 next if $amount == 0;
711 $subtotal += $amount;
712 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
713 ||= FS::cust_bill_pkg->by_key($billpkgnum)
714 or die "lineitem #$billpkgnum not found\n";
716 my $invnum = $cust_bill_pkg->invnum;
717 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
718 $cust_bill{ $invnum}->custnum == $arg{custnum}
719 or die "lineitem #$billpkgnum not found\n";
721 # tax_Xlocation records don't distinguish setup and recur, so calculate
722 # the fraction of setup+recur (after deducting credits) that's setup. This
723 # will also be the fraction of tax (after deducting credits) that's tax on
726 $setup = $cust_bill_pkg->get('setup') || 0;
728 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
730 $recur = $cust_bill_pkg->get('recur') || 0;
732 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
734 # Skip line items that have been completely credited.
735 next if ($setup + $recur) == 0;
736 my $setup_ratio = $setup / ($setup + $recur);
738 # Calculate the fraction of tax to credit: it's the fraction of this
739 # charge (either setup or recur) that's being credited.
740 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
741 next if $charged == 0; # shouldn't happen, but still...
743 if ($charged < $amount) {
744 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
747 my $credit_ratio = $amount / $charged;
749 # gather taxes that apply to the selected item
751 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
753 foreach my $tax_link (
754 qsearch($table, { taxable_billpkgnum => $billpkgnum })
756 my $tax_amount = $tax_link->amount;
757 # deduct existing credits applied to the tax, for the same reason as
759 foreach ($tax_link->cust_credit_bill_pkg) {
760 $tax_amount -= $_->amount;
762 # split tax amount based on setuprecur
763 # (this method ensures that, if you credit both setup and recur tax,
764 # it always equals the entire tax despite any rounding)
765 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
766 if ( $setuprecur eq 'setup' ) {
767 $tax_amount = $setup_tax;
769 $tax_amount = $tax_amount - $setup_tax;
771 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
772 my $pkey = $tax_link->get($tax_link->primary_key);
776 credit => $tax_credit,
778 $taxtotal += $tax_credit;
780 } #foreach cust_bill_pkg_tax_(rate_)?location
782 } # foreach $billpkgnum
785 subtotal => sprintf('%.2f', $subtotal),
786 taxtotal => sprintf('%.2f', $taxtotal),
787 taxlines => \@taxlines,
791 =item credit_lineitems OPTIONS
793 Creates a credit to a group of line items, with a specified amount applied
794 to each. This will also calculate the tax adjustments for those amounts and
795 credit the appropriate tax line items.
799 my $error = FS::cust_credit->credit_lineitems(
801 #the lineitems to credit
802 'billpkgnums' => \@billpkgnums,
803 'setuprecurs' => \@setuprecurs,
804 'amounts' => \@amounts,
805 'apply' => 1, #0 leaves the credit unapplied
806 'set_source' => 1, #creates credit source records for the line items
809 map { $_ => scalar($cgi->param($_)) }
810 #fields('cust_credit')
811 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
815 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
816 arrays. Each one indicates an amount of credit to be applied to either the
817 setup or recur portion of a (non-tax) line item.
819 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
820 credit before it's inserted.
822 C<amount> is the total amount. If unspecified, the credit will be the sum
823 of the per-line-item amounts and their tax adjustments.
827 #maybe i should just be an insert with extra args instead of a class method
828 sub credit_lineitems {
829 my( $class, %arg ) = @_;
830 my $curuser = $FS::CurrentUser::CurrentUser;
832 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
834 my $cust_main = qsearchs({
835 'table' => 'cust_main',
836 'hashref' => { 'custnum' => $arg{custnum} },
837 'extra_sql' => ' AND '. $curuser->agentnums_sql,
838 }) or return 'unknown customer';
841 local $SIG{HUP} = 'IGNORE';
842 local $SIG{INT} = 'IGNORE';
843 local $SIG{QUIT} = 'IGNORE';
844 local $SIG{TERM} = 'IGNORE';
845 local $SIG{TSTP} = 'IGNORE';
846 local $SIG{PIPE} = 'IGNORE';
848 my $oldAutoCommit = $FS::UID::AutoCommit;
849 local $FS::UID::AutoCommit = 0;
852 #my @cust_bill_pkg = qsearch({
853 # 'select' => 'cust_bill_pkg.*',
854 # 'table' => 'cust_bill_pkg',
855 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
856 # ' LEFT JOIN cust_main USING (custnum) ',
857 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
858 # join( ',', @{$arg{billpkgnums}} ). ')',
859 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
864 # first, determine the tax adjustments
865 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
866 # and determine the amount automatically if it wasn't specified
867 if ( !exists( $arg{amount} ) ) {
868 $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
871 my $set_source = $arg{set_source};
874 my $cust_credit = new FS::cust_credit ( {
875 map { $_ => $arg{$_} }
876 #fields('cust_credit')
877 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
879 $error = $cust_credit->insert;
881 $dbh->rollback if $oldAutoCommit;
882 return "Error inserting credit: $error";
885 unless ( $arg{'apply'} ) {
886 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
891 # keys in all of these are invoice numbers
892 my %cust_credit_bill = ();
893 my %cust_bill_pkg = ();
894 my %cust_credit_bill_pkg = ();
895 my %unapplied_payments = (); #invoice numbers, and then billpaynums
898 # little private function to unapply payments from a cust_bill_pkg until
899 # there's a specified amount of unpaid balance on it.
900 # it's a separate sub because we do it for both tax and nontax items. it's
901 # private because it needs access to some local data structures.
902 my $unapply_sub = sub {
903 my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
905 my $invnum = $cust_bill_pkg->invnum;
907 $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
908 return if $need_to_unapply < 0.005;
911 # then unapply payments one at a time (partially if need be) until the
912 # unpaid balance = the credit amount.
913 foreach my $cust_bill_pay_pkg (
914 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
916 my $this_amount = $cust_bill_pay_pkg->amount;
917 if ( $this_amount > $need_to_unapply ) {
918 # unapply the needed amount
919 $cust_bill_pay_pkg->set('amount',
920 sprintf('%.2f', $this_amount - $need_to_unapply));
921 $error = $cust_bill_pay_pkg->replace;
922 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
923 last; # and we're done
927 $error = $cust_bill_pay_pkg->delete;
928 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
930 $need_to_unapply -= $this_amount;
933 } # foreach $cust_bill_pay_pkg
935 # return an error if we somehow still have leftover $need_to_unapply?
941 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
942 my $setuprecur = shift @{$arg{setuprecurs}};
943 my $amount = shift @{$arg{amounts}};
945 my $cust_bill_pkg = qsearchs({
946 'table' => 'cust_bill_pkg',
947 'hashref' => { 'billpkgnum' => $billpkgnum },
948 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
949 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
950 }) or die "unknown billpkgnum $billpkgnum";
952 my $invnum = $cust_bill_pkg->invnum;
954 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
956 $cust_credit_bill{$invnum} += $amount;
957 push @{ $cust_credit_bill_pkg{$invnum} },
958 new FS::cust_credit_bill_pkg {
959 'billpkgnum' => $billpkgnum,
960 'amount' => sprintf('%.2f',$amount),
961 'setuprecur' => $setuprecur,
962 'sdate' => $cust_bill_pkg->sdate,
963 'edate' => $cust_bill_pkg->edate,
966 # unapply payments if necessary
967 $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
970 $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
971 my $source = FS::cust_credit_source_bill_pkg->new({
972 'crednum' => $cust_credit->crednum,
973 'billpkgnum' => $billpkgnum,
975 'currency' => $currency{invnum},
977 $error ||= $source->insert;
981 $dbh->rollback if $oldAutoCommit;
982 return "Error unapplying payment: $error";
986 # do the same for taxes
987 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
988 my $table = $tax_credit->{table};
989 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
990 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
992 my $billpkgnum = $tax_link->billpkgnum;
993 my $cust_bill_pkg = qsearchs({
994 'table' => 'cust_bill_pkg',
995 'hashref' => { 'billpkgnum' => $billpkgnum },
996 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
997 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
998 }) or die "unknown billpkgnum $billpkgnum";
1000 my $invnum = $cust_bill_pkg->invnum;
1001 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
1003 my $amount = $tax_credit->{credit};
1004 $cust_credit_bill{$invnum} += $amount;
1006 # create a credit application record to the tax line item, earmarked
1007 # to the specific cust_bill_pkg_Xlocation
1008 push @{ $cust_credit_bill_pkg{$invnum} },
1009 new FS::cust_credit_bill_pkg {
1010 'billpkgnum' => $billpkgnum,
1011 'amount' => sprintf('%.2f', $amount),
1012 'setuprecur' => 'setup',
1013 $tax_link->primary_key, $tax_credit->{num}
1016 $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1018 # I guess it's correct to do this for taxes also?
1019 if ( $set_source ) {
1020 $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
1021 my $source = FS::cust_credit_source_bill_pkg->new({
1022 'crednum' => $cust_credit->crednum,
1023 'billpkgnum' => $billpkgnum,
1024 'amount' => $amount,
1025 'currency' => $currency{invnum},
1027 $error ||= $source->insert;
1031 $dbh->rollback if $oldAutoCommit;
1032 return "Error unapplying payment: $error";
1037 # now loop through %cust_credit_bill and insert those
1040 # (hack to prevent cust_credit_bill_pkg insertion)
1041 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1043 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1045 # if we unapplied any payments from line items, also unapply that
1046 # amount from the invoice
1047 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1048 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1049 or die "broken payment application $billpaynum";
1050 my @subapps = $cust_bill_pay->lineitem_applications;
1051 $error = $cust_bill_pay->delete; # can't replace
1053 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1054 $cust_bill_pay->hash,
1056 amount => sprintf('%.2f',
1057 $cust_bill_pay->amount
1058 - $unapplied_payments{$invnum}{$billpaynum}),
1061 if ( $new_cust_bill_pay->amount > 0 ) {
1062 $error ||= $new_cust_bill_pay->insert;
1063 # Also reapply it to everything it was applied to before.
1064 # Note that we've already deleted cust_bill_pay_pkg records for the
1065 # items we're crediting, so they aren't on this list.
1066 foreach my $cust_bill_pay_pkg (@subapps) {
1067 $cust_bill_pay_pkg->billpaypkgnum('');
1068 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1069 $error ||= $cust_bill_pay_pkg->insert;
1073 $dbh->rollback if $oldAutoCommit;
1074 return "Error unapplying payment: $error";
1077 #insert cust_credit_bill
1079 my $cust_credit_bill = new FS::cust_credit_bill {
1080 'crednum' => $cust_credit->crednum,
1081 'invnum' => $invnum,
1082 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1084 $error = $cust_credit_bill->insert;
1086 $dbh->rollback if $oldAutoCommit;
1087 return "Error applying credit of $cust_credit_bill{$invnum} ".
1088 " to invoice $invnum: $error";
1091 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1092 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1093 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1094 $error = $cust_credit_bill_pkg->insert;
1096 $dbh->rollback if $oldAutoCommit;
1097 return "Error applying credit to line item: $error";
1103 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1108 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1110 =item refund_to_unapply
1112 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1113 (all currently applied refunds that aren't closed.)
1114 Returns empty list if credit itself is closed.
1118 sub refund_to_unapply {
1120 return () if $self->closed;
1122 'table' => 'cust_credit_refund',
1123 'hashref' => { 'crednum' => $self->crednum },
1124 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1125 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1129 =item unapply_refund
1131 Deletes all objects returned by L</refund_to_unapply>.
1135 sub unapply_refund {
1138 local $SIG{HUP} = 'IGNORE';
1139 local $SIG{INT} = 'IGNORE';
1140 local $SIG{QUIT} = 'IGNORE';
1141 local $SIG{TERM} = 'IGNORE';
1142 local $SIG{TSTP} = 'IGNORE';
1143 local $SIG{PIPE} = 'IGNORE';
1145 my $oldAutoCommit = $FS::UID::AutoCommit;
1146 local $FS::UID::AutoCommit = 0;
1148 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1149 my $error = $cust_credit_refund->delete;
1151 dbh->rollback if $oldAutoCommit;
1156 dbh->commit or die dbh->errstr if $oldAutoCommit;
1166 =item process_batch_import
1170 use List::Util qw( min );
1172 use FS::cust_credit_bill;
1173 sub process_batch_import {
1176 # some false laziness with FS::cust_pay::process_batch_import
1179 my $custnum = $hash{'custnum'};
1180 my $agent_custid = $hash{'agent_custid'};
1181 # translate agent_custid into regular custnum
1182 if ($custnum && $agent_custid) {
1183 die "can't specify both custnum and agent_custid\n";
1184 } elsif ($agent_custid) {
1185 # here is the agent virtualization
1186 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1188 $search{'agent_custid'} = $agent_custid
1190 $search{'custnum'} = $custnum
1192 my $cust_main = qsearchs({
1193 'table' => 'cust_main',
1194 'hashref' => \%search,
1195 'extra_sql' => $extra_sql,
1197 die "can't find customer with" .
1198 ($custnum ? " custnum $custnum" : '') .
1199 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1201 die "mismatched customer number\n"
1202 if $custnum && ($custnum ne $cust_main->custnum);
1203 $custnum = $cust_main->custnum;
1205 $hash{'custnum'} = $custnum;
1206 delete($hash{'agent_custid'});
1210 my $opt = { 'table' => 'cust_credit',
1211 'params' => [ '_date', 'credbatch' ],
1212 'formats' => { 'simple' =>
1213 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1216 'format_hash_callbacks' => { 'simple' => $hashcb },
1217 'postinsert_callback' => sub {
1218 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1220 if ( $cust_credit->invnum ) {
1222 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1223 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1225 my $cust_credit_bill = new FS::cust_credit_bill ( {
1226 'crednum' => $cust_credit->crednum,
1227 'invnum' => $cust_bill->invnum,
1228 'amount' => $amount,
1230 my $error = $cust_credit_bill->insert;
1231 return '' unless $error;
1235 #apply_payments_and_credits ?
1236 $cust_credit->cust_main->apply_credits;
1243 FS::Record::process_batch_import( $job, $opt, @_ );
1251 The delete method. The replace method.
1253 B<credited> and B<credited_sql> are now called B<unapplied> and
1254 B<unapplied_sql>. The old method names should start to give warnings.
1258 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1259 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base