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 OPTIONS
803 Creates a credit to a group of line items, with a specified amount applied
804 to each. This will also calculate the tax adjustments for those amounts and
805 credit the appropriate tax line items.
809 my $error = FS::cust_credit->credit_lineitems(
811 #the lineitems to credit
812 'billpkgnums' => \@billpkgnums,
813 'setuprecurs' => \@setuprecurs,
814 'amounts' => \@amounts,
815 'apply' => 1, #0 leaves the credit unapplied
818 map { $_ => scalar($cgi->param($_)) }
819 #fields('cust_credit')
820 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
824 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
825 arrays. Each one indicates an amount of credit to be applied to either the
826 setup or recur portion of a (non-tax) line item.
828 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
829 credit before it's inserted.
831 C<amount> is the total amount. If unspecified, the credit will be the sum
832 of the per-line-item amounts and their tax adjustments.
836 #maybe i should just be an insert with extra args instead of a class method
837 sub credit_lineitems {
838 my( $class, %arg ) = @_;
839 my $curuser = $FS::CurrentUser::CurrentUser;
841 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
843 my $cust_main = qsearchs({
844 'table' => 'cust_main',
845 'hashref' => { 'custnum' => $arg{custnum} },
846 'extra_sql' => ' AND '. $curuser->agentnums_sql,
847 }) or return 'unknown customer';
850 local $SIG{HUP} = 'IGNORE';
851 local $SIG{INT} = 'IGNORE';
852 local $SIG{QUIT} = 'IGNORE';
853 local $SIG{TERM} = 'IGNORE';
854 local $SIG{TSTP} = 'IGNORE';
855 local $SIG{PIPE} = 'IGNORE';
857 my $oldAutoCommit = $FS::UID::AutoCommit;
858 local $FS::UID::AutoCommit = 0;
861 #my @cust_bill_pkg = qsearch({
862 # 'select' => 'cust_bill_pkg.*',
863 # 'table' => 'cust_bill_pkg',
864 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
865 # ' LEFT JOIN cust_main USING (custnum) ',
866 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
867 # join( ',', @{$arg{billpkgnums}} ). ')',
868 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
873 # first, determine the tax adjustments
874 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
875 # and determine the amount automatically if it wasn't specified
876 if ( !exists( $arg{amount} ) ) {
877 $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
881 my $cust_credit = new FS::cust_credit ( {
882 map { $_ => $arg{$_} }
883 #fields('cust_credit')
884 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
886 $error = $cust_credit->insert;
888 $dbh->rollback if $oldAutoCommit;
889 return "Error inserting credit: $error";
892 unless ( $arg{'apply'} ) {
893 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
898 # keys in all of these are invoice numbers
899 my %cust_credit_bill = ();
900 my %cust_bill_pkg = ();
901 my %cust_credit_bill_pkg = ();
902 my %unapplied_payments = (); #invoice numbers, and then billpaynums
904 # little private function to unapply payments from a cust_bill_pkg until
905 # there's a specified amount of unpaid balance on it.
906 # it's a separate sub because we do it for both tax and nontax items. it's
907 # private because it needs access to some local data structures.
908 my $unapply_sub = sub {
909 my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
911 my $invnum = $cust_bill_pkg->invnum;
913 $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
914 next if $need_to_unapply < 0.005;
917 # then unapply payments one at a time (partially if need be) until the
918 # unpaid balance = the credit amount.
919 foreach my $cust_bill_pay_pkg (
920 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
922 my $this_amount = $cust_bill_pay_pkg->amount;
923 if ( $this_amount > $need_to_unapply ) {
924 # unapply the needed amount
925 $cust_bill_pay_pkg->set('amount',
926 sprintf('%.2f', $this_amount - $need_to_unapply));
927 $error = $cust_bill_pay_pkg->replace;
928 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
929 last; # and we're done
933 $error = $cust_bill_pay_pkg->delete;
934 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
936 $need_to_unapply -= $this_amount;
939 } # foreach $cust_bill_pay_pkg
941 # return an error if we somehow still have leftover $need_to_unapply?
947 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
948 my $setuprecur = shift @{$arg{setuprecurs}};
949 my $amount = shift @{$arg{amounts}};
951 my $cust_bill_pkg = qsearchs({
952 'table' => 'cust_bill_pkg',
953 'hashref' => { 'billpkgnum' => $billpkgnum },
954 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
955 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
956 }) or die "unknown billpkgnum $billpkgnum";
958 my $invnum = $cust_bill_pkg->invnum;
960 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
962 $cust_credit_bill{$invnum} += $amount;
963 push @{ $cust_credit_bill_pkg{$invnum} },
964 new FS::cust_credit_bill_pkg {
965 'billpkgnum' => $billpkgnum,
966 'amount' => sprintf('%.2f',$amount),
967 'setuprecur' => $setuprecur,
968 'sdate' => $cust_bill_pkg->sdate,
969 'edate' => $cust_bill_pkg->edate,
972 # unapply payments if necessary
973 $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
976 $dbh->rollback if $oldAutoCommit;
977 return "Error unapplying payment: $error";
981 # do the same for taxes
982 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
983 my $table = $tax_credit->{table};
984 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
985 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
987 my $billpkgnum = $tax_link->billpkgnum;
988 my $cust_bill_pkg = qsearchs({
989 'table' => 'cust_bill_pkg',
990 'hashref' => { 'billpkgnum' => $billpkgnum },
991 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
992 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
993 }) or die "unknown billpkgnum $billpkgnum";
995 my $invnum = $cust_bill_pkg->invnum;
996 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
998 my $amount = $tax_credit->{credit};
999 $cust_credit_bill{$invnum} += $amount;
1001 # create a credit application record to the tax line item, earmarked
1002 # to the specific cust_bill_pkg_Xlocation
1003 push @{ $cust_credit_bill_pkg{$invnum} },
1004 new FS::cust_credit_bill_pkg {
1005 'billpkgnum' => $billpkgnum,
1006 'amount' => sprintf('%.2f', $amount),
1007 'setuprecur' => 'setup',
1008 $tax_link->primary_key, $tax_credit->{num}
1011 $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1013 $dbh->rollback if $oldAutoCommit;
1014 return "Error unapplying payment: $error";
1019 # now loop through %cust_credit_bill and insert those
1022 # (hack to prevent cust_credit_bill_pkg insertion)
1023 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1025 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1027 # if we unapplied any payments from line items, also unapply that
1028 # amount from the invoice
1029 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1030 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1031 or die "broken payment application $billpaynum";
1032 my @subapps = $cust_bill_pay->lineitem_applications;
1033 $error = $cust_bill_pay->delete; # can't replace
1035 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1036 $cust_bill_pay->hash,
1038 amount => sprintf('%.2f',
1039 $cust_bill_pay->amount
1040 - $unapplied_payments{$invnum}{$billpaynum}),
1043 if ( $new_cust_bill_pay->amount > 0 ) {
1044 $error ||= $new_cust_bill_pay->insert;
1045 # Also reapply it to everything it was applied to before.
1046 # Note that we've already deleted cust_bill_pay_pkg records for the
1047 # items we're crediting, so they aren't on this list.
1048 foreach my $cust_bill_pay_pkg (@subapps) {
1049 $cust_bill_pay_pkg->billpaypkgnum('');
1050 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1051 $error ||= $cust_bill_pay_pkg->insert;
1055 $dbh->rollback if $oldAutoCommit;
1056 return "Error unapplying payment: $error";
1059 #insert cust_credit_bill
1061 my $cust_credit_bill = new FS::cust_credit_bill {
1062 'crednum' => $cust_credit->crednum,
1063 'invnum' => $invnum,
1064 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1066 $error = $cust_credit_bill->insert;
1068 $dbh->rollback if $oldAutoCommit;
1069 return "Error applying credit of $cust_credit_bill{$invnum} ".
1070 " to invoice $invnum: $error";
1073 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1074 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1075 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1076 $error = $cust_credit_bill_pkg->insert;
1078 $dbh->rollback if $oldAutoCommit;
1079 return "Error applying credit to line item: $error";
1085 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1090 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1092 =item refund_to_unapply
1094 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1095 (all currently applied refunds that aren't closed.)
1096 Returns empty list if credit itself is closed.
1100 sub refund_to_unapply {
1102 return () if $self->closed;
1104 'table' => 'cust_credit_refund',
1105 'hashref' => { 'crednum' => $self->crednum },
1106 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1107 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1111 =item unapply_refund
1113 Deletes all objects returned by L</refund_to_unapply>.
1117 sub unapply_refund {
1120 local $SIG{HUP} = 'IGNORE';
1121 local $SIG{INT} = 'IGNORE';
1122 local $SIG{QUIT} = 'IGNORE';
1123 local $SIG{TERM} = 'IGNORE';
1124 local $SIG{TSTP} = 'IGNORE';
1125 local $SIG{PIPE} = 'IGNORE';
1127 my $oldAutoCommit = $FS::UID::AutoCommit;
1128 local $FS::UID::AutoCommit = 0;
1130 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1131 my $error = $cust_credit_refund->delete;
1133 dbh->rollback if $oldAutoCommit;
1138 dbh->commit or die dbh->errstr if $oldAutoCommit;
1148 =item process_batch_import
1152 use List::Util qw( min );
1154 use FS::cust_credit_bill;
1155 sub process_batch_import {
1158 # some false laziness with FS::cust_pay::process_batch_import
1161 my $custnum = $hash{'custnum'};
1162 my $agent_custid = $hash{'agent_custid'};
1163 # translate agent_custid into regular custnum
1164 if ($custnum && $agent_custid) {
1165 die "can't specify both custnum and agent_custid\n";
1166 } elsif ($agent_custid) {
1167 # here is the agent virtualization
1168 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1170 $search{'agent_custid'} = $agent_custid
1172 $search{'custnum'} = $custnum
1174 my $cust_main = qsearchs({
1175 'table' => 'cust_main',
1176 'hashref' => \%search,
1177 'extra_sql' => $extra_sql,
1179 die "can't find customer with" .
1180 ($custnum ? " custnum $custnum" : '') .
1181 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1183 die "mismatched customer number\n"
1184 if $custnum && ($custnum ne $cust_main->custnum);
1185 $custnum = $cust_main->custnum;
1187 $hash{'custnum'} = $custnum;
1188 delete($hash{'agent_custid'});
1192 my $opt = { 'table' => 'cust_credit',
1193 'params' => [ '_date', 'credbatch' ],
1194 'formats' => { 'simple' =>
1195 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1198 'format_hash_callbacks' => { 'simple' => $hashcb },
1199 'postinsert_callback' => sub {
1200 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1202 if ( $cust_credit->invnum ) {
1204 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1205 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1207 my $cust_credit_bill = new FS::cust_credit_bill ( {
1208 'crednum' => $cust_credit->crednum,
1209 'invnum' => $cust_bill->invnum,
1210 'amount' => $amount,
1212 my $error = $cust_credit_bill->insert;
1213 return '' unless $error;
1217 #apply_payments_and_credits ?
1218 $cust_credit->cust_main->apply_credits;
1225 FS::Record::process_batch_import( $job, $opt, @_ );
1233 The delete method. The replace method.
1235 B<credited> and B<credited_sql> are now called B<unapplied> and
1236 B<unapplied_sql>. The old method names should start to give warnings.
1240 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1241 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base