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 unless ( $cust_main ) {
158 $dbh->rollback if $oldAutoCommit;
159 return "Unknown custnum ". $self->custnum;
161 my $old_balance = $cust_main->balance;
163 if (!$self->reasonnum) {
164 my $reason_text = $self->get('reason')
165 or return "reason text or existing reason required";
166 my $reason_type = $options{'reason_type'}
167 or return "reason type required";
170 my $reason = FS::reason->new_or_existing(
171 reason => $reason_text,
172 type => $reason_type,
176 $dbh->rollback if $oldAutoCommit;
177 return "failed to set credit reason: $@";
179 $self->set('reasonnum', $reason->reasonnum);
182 $self->setfield('reason', '');
184 my $error = $self->SUPER::insert;
186 $dbh->rollback if $oldAutoCommit;
187 return "error inserting $self: $error";
190 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
192 # possibly trigger package unsuspend, doesn't abort transaction on failure
193 $self->unsuspend_balance if $old_balance;
195 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
203 Unless the closed flag is set, deletes this credit and all associated
204 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
205 the void method instead to leave a record of the deleted credit.
209 # very similar to FS::cust_pay::delete
214 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
216 local $SIG{HUP} = 'IGNORE';
217 local $SIG{INT} = 'IGNORE';
218 local $SIG{QUIT} = 'IGNORE';
219 local $SIG{TERM} = 'IGNORE';
220 local $SIG{TSTP} = 'IGNORE';
221 local $SIG{PIPE} = 'IGNORE';
223 my $oldAutoCommit = $FS::UID::AutoCommit;
224 local $FS::UID::AutoCommit = 0;
227 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
228 my $error = $cust_credit_bill->delete;
230 $dbh->rollback if $oldAutoCommit;
235 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
236 my $error = $cust_credit_refund->delete;
238 $dbh->rollback if $oldAutoCommit;
243 my $error = $self->SUPER::delete(@_);
245 $dbh->rollback if $oldAutoCommit;
249 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
251 my $cust_main = $self->cust_main;
253 my $error = send_email(
254 'from' => $conf->invoice_from_full($self->cust_main->agentnum),
255 #invoice_from??? well as good as any
256 'to' => $conf->config('deletecredits'),
257 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
259 "This is an automatic message from your Freeside installation\n",
260 "informing you that the following credit has been deleted:\n",
262 'crednum: '. $self->crednum. "\n",
263 'custnum: '. $self->custnum.
264 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
265 'amount: $'. sprintf("%.2f", $self->amount). "\n",
266 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
267 'reason: '. $self->reason. "\n",
272 $dbh->rollback if $oldAutoCommit;
273 return "can't send credit deletion notification: $error";
278 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
284 =item replace [ OLD_RECORD ]
286 You can, but probably shouldn't modify credits...
288 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
289 supplied, replaces this record. If there is an error, returns the error,
290 otherwise returns false.
296 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
297 $self->SUPER::replace(@_);
302 Checks all fields to make sure this is a valid credit. If there is an error,
303 returns the error, otherwise returns false. Called by the insert and replace
311 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
314 $self->ut_numbern('crednum')
315 || $self->ut_number('custnum')
316 || $self->ut_numbern('_date')
317 || $self->ut_money('amount')
318 || $self->ut_alphan('otaker')
319 || $self->ut_textn('reason')
320 || $self->ut_textn('addlinfo')
321 || $self->ut_enum('closed', [ '', 'Y' ])
322 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
323 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
324 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
325 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
326 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
328 return $error if $error;
330 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
331 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
332 return $error if $error;
334 return "amount must be > 0 " if $self->amount <= 0;
336 return "amount must be greater or equal to amount applied"
337 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
339 return "Unknown customer"
340 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
342 $self->_date(time) unless $self->_date;
347 =item void [ REASON ]
349 Voids this credit: deletes the credit and all associated applications and
350 adds a record of the voided credit to the cust_credit_void table.
358 unless (ref($reason) || !$reason) {
359 $reason = FS::reason->new_or_existing(
361 'type' => 'Void credit',
366 local $SIG{HUP} = 'IGNORE';
367 local $SIG{INT} = 'IGNORE';
368 local $SIG{QUIT} = 'IGNORE';
369 local $SIG{TERM} = 'IGNORE';
370 local $SIG{TSTP} = 'IGNORE';
371 local $SIG{PIPE} = 'IGNORE';
373 my $oldAutoCommit = $FS::UID::AutoCommit;
374 local $FS::UID::AutoCommit = 0;
377 my $cust_credit_void = new FS::cust_credit_void ( {
378 map { $_ => $self->get($_) } $self->fields
380 $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
381 my $error = $cust_credit_void->insert;
383 $dbh->rollback if $oldAutoCommit;
387 $error = $self->delete(void => 1); # suppress deletecredits warning
389 $dbh->rollback if $oldAutoCommit;
393 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
399 =item cust_credit_refund
401 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
405 sub cust_credit_refund {
407 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
408 sort { $a->_date <=> $b->_date }
409 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
413 =item cust_credit_bill
415 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
420 sub cust_credit_bill {
422 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
423 sort { $a->_date <=> $b->_date }
424 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
430 Returns the amount of this credit that is still unapplied/outstanding;
431 amount minus all refund applications (see L<FS::cust_credit_refund>) and
432 applications to invoices (see L<FS::cust_credit_bill>).
438 my $amount = $self->amount;
439 $amount -= $_->amount foreach ( $self->cust_credit_refund );
440 $amount -= $_->amount foreach ( $self->cust_credit_bill );
441 sprintf( "%.2f", $amount );
446 Deprecated name for the unapplied method.
452 #carp "cust_credit->credited deprecated; use ->unapplied";
453 $self->unapplied(@_);
458 Returns the customer (see L<FS::cust_main>) for this credit.
464 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
469 Returns the text of the associated reason (see L<FS::reason>) for this credit.
475 # Used by FS::Upgrade to migrate to a new database.
477 sub _upgrade_data { # class method
478 my ($class, %opts) = @_;
480 warn "$me upgrading $class\n" if $DEBUG;
482 $class->_upgrade_reasonnum(%opts);
484 if (defined dbdef->table($class->table)->column('reason')) {
486 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
488 foreach ( keys %reasontype_map ) {
489 unless ($conf->config($_)) { # hmmmm
490 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
491 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
492 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
493 my $reason_type = qsearchs( 'reason_type', $hashref );
494 unless ($reason_type) {
495 $reason_type = new FS::reason_type( $hashref );
496 my $error = $reason_type->insert();
497 die "$class had error inserting FS::reason_type into database: $error\n"
500 $conf->set($_, $reason_type->typenum);
504 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
506 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
507 my $reason_type = qsearchs( 'reason_type', $hashref );
508 unless ($reason_type) {
509 $reason_type = new FS::reason_type( $hashref );
510 my $error = $reason_type->insert();
511 die "$class had error inserting FS::reason_type into database: $error\n"
515 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
516 foreach my $plan ( @plans ) {
517 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
518 unless ($pkg->option('reason_type', 1) ) {
519 my $plandata = $pkg->plandata.
520 "reason_type=". $reason_type->typenum. "\n";
521 $pkg->plandata($plandata);
523 $pkg->replace( undef,
524 'pkg_svc' => { map { $_->svcpart => $_->quantity }
527 'primary_svc' => $pkg->svcpart,
529 die "failed setting reason_type option: $error"
536 local($otaker_upgrade_kludge) = 1;
537 local($ignore_empty_reasonnum) = 1;
538 $class->_upgrade_otaker(%opts);
540 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
541 and !$conf->exists('enable_taxproducts') ) {
542 # RT#25458: fix credit line item applications that should refer to a
543 # specific tax allocation
544 my @cust_credit_bill_pkg = qsearch({
545 table => 'cust_credit_bill_pkg',
546 select => 'cust_credit_bill_pkg.*',
547 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
549 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
550 'AND cust_bill_pkg.pkgnum = 0', # is a tax
554 foreach (@cust_credit_bill_pkg) {
555 my $billpkgnum = $_->billpkgnum;
556 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
557 $credits{$billpkgnum} ||= [];
558 push @{ $credits{$billpkgnum} }, $_;
560 TAX_ITEM: foreach my $tax_item (values %tax_items) {
561 my $billpkgnum = $tax_item->billpkgnum;
562 # get all pkg/location/taxrate allocations of this tax line item
563 my @allocations = sort {$b->amount <=> $a->amount}
564 qsearch('cust_bill_pkg_tax_location', {
565 billpkgnum => $billpkgnum
567 # and these are all credit applications to it
568 my @credits = sort {$b->amount <=> $a->amount}
569 @{ $credits{$billpkgnum} };
570 my $c = shift @credits;
571 my $a = shift @allocations; # we will NOT modify these
573 if ( abs($c->amount - $a->amount) < 0.005 ) {
574 # by far the most common case: the tax line item is for a single
575 # tax, so we just fill in the billpkgtaxlocationnum
576 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
577 my $error = $c->replace;
579 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
583 $a = shift @allocations;
584 } elsif ( $c->amount > $a->amount ) {
585 # fairly common: the tax line contains tax for multiple packages
586 # (or multiple taxes) but the credit isn't divided up
587 my $new_link = FS::cust_credit_bill_pkg->new({
588 creditbillnum => $c->creditbillnum,
589 billpkgnum => $c->billpkgnum,
590 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
591 amount => $a->amount,
592 setuprecur => 'setup',
594 my $error = $new_link->insert;
596 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
599 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
600 $a = shift @allocations;
601 } elsif ( $c->amount < 0.005 ) {
602 # also fairly common; we can delete these with no harm
603 my $error = $c->delete;
604 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
606 } elsif ( $c->amount < $a->amount ) {
607 # should never happen, but if it does, handle it gracefully
608 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
609 my $error = $c->replace;
611 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
614 $a->set(amount => $a->amount - $c->amount);
619 if ( $c->amount < 0.005 ) {
620 my $error = $c->delete;
621 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
622 } elsif ( $c->modified ) {
623 # then we've allocated part of it, so reduce the nonspecific
624 # application by that much
625 my $error = $c->replace;
626 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
628 # else there are probably no allocations, i.e. this is a pre-3.x
629 # record that was never migrated over, so leave it alone
631 } # foreach $tax_item
632 FS::upgrade_journal->set_done('cust_credit__tax_link');
644 Returns an SQL fragment to retreive the unapplied amount.
649 my ($class, $start, $end) = @_;
651 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
652 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
653 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
654 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
658 ( SELECT SUM(amount) FROM cust_credit_refund
659 WHERE cust_credit.crednum = cust_credit_refund.crednum
660 $refund_start $refund_end )
664 ( SELECT SUM(amount) FROM cust_credit_bill
665 WHERE cust_credit.crednum = cust_credit_bill.crednum
666 $bill_start $bill_end )
675 Deprecated name for the unapplied_sql method.
682 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
684 #$class->unapplied_sql(@_);
688 =item calculate_tax_adjustment PARAMS
690 Calculate the amount of tax that needs to be credited as part of a lineitem
695 - billpkgnums: arrayref identifying the line items to credit
696 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
697 the lineitem charge is being credited
698 - amounts: arrayref of the amounts to credit on each line item
699 - custnum: the customer all of these invoices belong to, for error checking
701 Returns a hash containing:
702 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
703 - taxtotal: the total tax amount to be credited
704 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
705 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
706 - num: the key within that table
707 - credit: the credit amount to apply to that line
711 sub calculate_tax_adjustment {
712 my ($class, %arg) = @_;
719 my (%cust_bill_pkg, %cust_bill);
721 for (my $i = 0; ; $i++) {
722 my $billpkgnum = $arg{billpkgnums}[$i]
724 my $setuprecur = $arg{setuprecurs}[$i];
725 my $amount = $arg{amounts}[$i];
726 next if $amount == 0;
727 $subtotal += $amount;
728 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
729 ||= FS::cust_bill_pkg->by_key($billpkgnum)
730 or die "lineitem #$billpkgnum not found\n";
732 my $invnum = $cust_bill_pkg->invnum;
733 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
734 $cust_bill{ $invnum}->custnum == $arg{custnum}
735 or die "lineitem #$billpkgnum not found\n";
737 # tax_Xlocation records don't distinguish setup and recur, so calculate
738 # the fraction of setup+recur (after deducting credits) that's setup. This
739 # will also be the fraction of tax (after deducting credits) that's tax on
742 $setup = $cust_bill_pkg->get('setup') || 0;
744 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
746 $recur = $cust_bill_pkg->get('recur') || 0;
748 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
750 # Skip line items that have been completely credited.
751 next if ($setup + $recur) == 0;
752 my $setup_ratio = $setup / ($setup + $recur);
754 # Calculate the fraction of tax to credit: it's the fraction of this
755 # charge (either setup or recur) that's being credited.
756 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
757 next if $charged == 0; # shouldn't happen, but still...
759 if ($charged < $amount) {
760 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
763 my $credit_ratio = $amount / $charged;
765 # gather taxes that apply to the selected item
767 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
769 foreach my $tax_link (
770 qsearch($table, { taxable_billpkgnum => $billpkgnum })
772 my $tax_amount = $tax_link->amount;
773 # deduct existing credits applied to the tax, for the same reason as
775 foreach ($tax_link->cust_credit_bill_pkg) {
776 $tax_amount -= $_->amount;
778 # split tax amount based on setuprecur
779 # (this method ensures that, if you credit both setup and recur tax,
780 # it always equals the entire tax despite any rounding)
781 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
782 if ( $setuprecur eq 'setup' ) {
783 $tax_amount = $setup_tax;
785 $tax_amount = $tax_amount - $setup_tax;
787 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
788 my $pkey = $tax_link->get($tax_link->primary_key);
792 credit => $tax_credit,
794 $taxtotal += $tax_credit;
796 } #foreach cust_bill_pkg_tax_(rate_)?location
798 } # foreach $billpkgnum
801 subtotal => sprintf('%.2f', $subtotal),
802 taxtotal => sprintf('%.2f', $taxtotal),
803 taxlines => \@taxlines,
807 =item credit_lineitems OPTIONS
809 Creates a credit to a group of line items, with a specified amount applied
810 to each. This will also calculate the tax adjustments for those amounts and
811 credit the appropriate tax line items.
815 my $error = FS::cust_credit->credit_lineitems(
817 #the lineitems to credit
818 'billpkgnums' => \@billpkgnums,
819 'setuprecurs' => \@setuprecurs,
820 'amounts' => \@amounts,
821 'apply' => 1, #0 leaves the credit unapplied
824 map { $_ => scalar($cgi->param($_)) }
825 #fields('cust_credit')
826 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
830 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
831 arrays. Each one indicates an amount of credit to be applied to either the
832 setup or recur portion of a (non-tax) line item.
834 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
835 credit before it's inserted.
837 C<amount> is the total amount. If unspecified, the credit will be the sum
838 of the per-line-item amounts and their tax adjustments.
842 #maybe i should just be an insert with extra args instead of a class method
843 sub credit_lineitems {
844 my( $class, %arg ) = @_;
845 my $curuser = $FS::CurrentUser::CurrentUser;
847 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
849 my $cust_main = qsearchs({
850 'table' => 'cust_main',
851 'hashref' => { 'custnum' => $arg{custnum} },
852 'extra_sql' => ' AND '. $curuser->agentnums_sql,
853 }) or return 'unknown customer';
856 local $SIG{HUP} = 'IGNORE';
857 local $SIG{INT} = 'IGNORE';
858 local $SIG{QUIT} = 'IGNORE';
859 local $SIG{TERM} = 'IGNORE';
860 local $SIG{TSTP} = 'IGNORE';
861 local $SIG{PIPE} = 'IGNORE';
863 my $oldAutoCommit = $FS::UID::AutoCommit;
864 local $FS::UID::AutoCommit = 0;
867 #my @cust_bill_pkg = qsearch({
868 # 'select' => 'cust_bill_pkg.*',
869 # 'table' => 'cust_bill_pkg',
870 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
871 # ' LEFT JOIN cust_main USING (custnum) ',
872 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
873 # join( ',', @{$arg{billpkgnums}} ). ')',
874 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
879 # first, determine the tax adjustments
880 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
881 # and determine the amount automatically if it wasn't specified
882 if ( !exists( $arg{amount} ) ) {
883 $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
887 my $cust_credit = new FS::cust_credit ( {
888 map { $_ => $arg{$_} }
889 #fields('cust_credit')
890 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
892 $error = $cust_credit->insert;
894 $dbh->rollback if $oldAutoCommit;
895 return "Error inserting credit: $error";
898 unless ( $arg{'apply'} ) {
899 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
904 # keys in all of these are invoice numbers
905 my %cust_credit_bill = ();
906 my %cust_bill_pkg = ();
907 my %cust_credit_bill_pkg = ();
908 my %unapplied_payments = (); #invoice numbers, and then billpaynums
910 # little private function to unapply payments from a cust_bill_pkg until
911 # there's a specified amount of unpaid balance on it.
912 # it's a separate sub because we do it for both tax and nontax items. it's
913 # private because it needs access to some local data structures.
914 my $unapply_sub = sub {
915 my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
917 my $invnum = $cust_bill_pkg->invnum;
919 $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
920 return if $need_to_unapply < 0.005;
923 # then unapply payments one at a time (partially if need be) until the
924 # unpaid balance = the credit amount.
925 foreach my $cust_bill_pay_pkg (
926 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
928 my $this_amount = $cust_bill_pay_pkg->amount;
929 if ( $this_amount > $need_to_unapply ) {
930 # unapply the needed amount
931 $cust_bill_pay_pkg->set('amount',
932 sprintf('%.2f', $this_amount - $need_to_unapply));
933 $error = $cust_bill_pay_pkg->replace;
934 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
935 last; # and we're done
939 $error = $cust_bill_pay_pkg->delete;
940 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
942 $need_to_unapply -= $this_amount;
945 } # foreach $cust_bill_pay_pkg
947 # return an error if we somehow still have leftover $need_to_unapply?
953 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
954 my $setuprecur = shift @{$arg{setuprecurs}};
955 my $amount = shift @{$arg{amounts}};
957 my $cust_bill_pkg = qsearchs({
958 'table' => 'cust_bill_pkg',
959 'hashref' => { 'billpkgnum' => $billpkgnum },
960 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
961 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
962 }) or die "unknown billpkgnum $billpkgnum";
964 my $invnum = $cust_bill_pkg->invnum;
966 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
968 $cust_credit_bill{$invnum} += $amount;
969 push @{ $cust_credit_bill_pkg{$invnum} },
970 new FS::cust_credit_bill_pkg {
971 'billpkgnum' => $billpkgnum,
972 'amount' => sprintf('%.2f',$amount),
973 'setuprecur' => $setuprecur,
974 'sdate' => $cust_bill_pkg->sdate,
975 'edate' => $cust_bill_pkg->edate,
978 # unapply payments if necessary
979 $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
982 $dbh->rollback if $oldAutoCommit;
983 return "Error unapplying payment: $error";
987 # do the same for taxes
988 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
989 my $table = $tax_credit->{table};
990 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
991 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
993 my $billpkgnum = $tax_link->billpkgnum;
994 my $cust_bill_pkg = qsearchs({
995 'table' => 'cust_bill_pkg',
996 'hashref' => { 'billpkgnum' => $billpkgnum },
997 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
998 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
999 }) or die "unknown billpkgnum $billpkgnum";
1001 my $invnum = $cust_bill_pkg->invnum;
1002 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
1004 my $amount = $tax_credit->{credit};
1005 $cust_credit_bill{$invnum} += $amount;
1007 # create a credit application record to the tax line item, earmarked
1008 # to the specific cust_bill_pkg_Xlocation
1009 push @{ $cust_credit_bill_pkg{$invnum} },
1010 new FS::cust_credit_bill_pkg {
1011 'billpkgnum' => $billpkgnum,
1012 'amount' => sprintf('%.2f', $amount),
1013 'setuprecur' => 'setup',
1014 $tax_link->primary_key, $tax_credit->{num}
1017 $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1019 $dbh->rollback if $oldAutoCommit;
1020 return "Error unapplying payment: $error";
1025 # now loop through %cust_credit_bill and insert those
1028 # (hack to prevent cust_credit_bill_pkg insertion)
1029 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1031 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1033 # if we unapplied any payments from line items, also unapply that
1034 # amount from the invoice
1035 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1036 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1037 or die "broken payment application $billpaynum";
1038 my @subapps = $cust_bill_pay->lineitem_applications;
1039 $error = $cust_bill_pay->delete; # can't replace
1041 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1042 $cust_bill_pay->hash,
1044 amount => sprintf('%.2f',
1045 $cust_bill_pay->amount
1046 - $unapplied_payments{$invnum}{$billpaynum}),
1049 if ( $new_cust_bill_pay->amount > 0 ) {
1050 $error ||= $new_cust_bill_pay->insert;
1051 # Also reapply it to everything it was applied to before.
1052 # Note that we've already deleted cust_bill_pay_pkg records for the
1053 # items we're crediting, so they aren't on this list.
1054 foreach my $cust_bill_pay_pkg (@subapps) {
1055 $cust_bill_pay_pkg->billpaypkgnum('');
1056 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1057 $error ||= $cust_bill_pay_pkg->insert;
1061 $dbh->rollback if $oldAutoCommit;
1062 return "Error unapplying payment: $error";
1065 #insert cust_credit_bill
1067 my $cust_credit_bill = new FS::cust_credit_bill {
1068 'crednum' => $cust_credit->crednum,
1069 'invnum' => $invnum,
1070 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1072 $error = $cust_credit_bill->insert;
1074 $dbh->rollback if $oldAutoCommit;
1075 return "Error applying credit of $cust_credit_bill{$invnum} ".
1076 " to invoice $invnum: $error";
1079 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1080 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1081 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1082 $error = $cust_credit_bill_pkg->insert;
1084 $dbh->rollback if $oldAutoCommit;
1085 return "Error applying credit to line item: $error";
1091 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1096 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1098 =item refund_to_unapply
1100 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1101 (all currently applied refunds that aren't closed.)
1102 Returns empty list if credit itself is closed.
1106 sub refund_to_unapply {
1108 return () if $self->closed;
1110 'table' => 'cust_credit_refund',
1111 'hashref' => { 'crednum' => $self->crednum },
1112 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1113 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1117 =item unapply_refund
1119 Deletes all objects returned by L</refund_to_unapply>.
1123 sub unapply_refund {
1126 local $SIG{HUP} = 'IGNORE';
1127 local $SIG{INT} = 'IGNORE';
1128 local $SIG{QUIT} = 'IGNORE';
1129 local $SIG{TERM} = 'IGNORE';
1130 local $SIG{TSTP} = 'IGNORE';
1131 local $SIG{PIPE} = 'IGNORE';
1133 my $oldAutoCommit = $FS::UID::AutoCommit;
1134 local $FS::UID::AutoCommit = 0;
1136 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1137 my $error = $cust_credit_refund->delete;
1139 dbh->rollback if $oldAutoCommit;
1144 dbh->commit or die dbh->errstr if $oldAutoCommit;
1154 =item process_batch_import
1158 use List::Util qw( min );
1160 use FS::cust_credit_bill;
1161 sub process_batch_import {
1164 # some false laziness with FS::cust_pay::process_batch_import
1167 my $custnum = $hash{'custnum'};
1168 my $agent_custid = $hash{'agent_custid'};
1169 # translate agent_custid into regular custnum
1170 if ($custnum && $agent_custid) {
1171 die "can't specify both custnum and agent_custid\n";
1172 } elsif ($agent_custid) {
1173 # here is the agent virtualization
1174 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1176 $search{'agent_custid'} = $agent_custid
1178 $search{'custnum'} = $custnum
1180 my $cust_main = qsearchs({
1181 'table' => 'cust_main',
1182 'hashref' => \%search,
1183 'extra_sql' => $extra_sql,
1185 die "can't find customer with" .
1186 ($custnum ? " custnum $custnum" : '') .
1187 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1189 die "mismatched customer number\n"
1190 if $custnum && ($custnum ne $cust_main->custnum);
1191 $custnum = $cust_main->custnum;
1193 $hash{'custnum'} = $custnum;
1194 delete($hash{'agent_custid'});
1198 my $opt = { 'table' => 'cust_credit',
1199 'params' => [ '_date', 'credbatch' ],
1200 'formats' => { 'simple' =>
1201 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1204 'format_hash_callbacks' => { 'simple' => $hashcb },
1205 'postinsert_callback' => sub {
1206 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1208 if ( $cust_credit->invnum ) {
1210 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1211 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1213 my $cust_credit_bill = new FS::cust_credit_bill ( {
1214 'crednum' => $cust_credit->crednum,
1215 'invnum' => $cust_bill->invnum,
1216 'amount' => $amount,
1218 my $error = $cust_credit_bill->insert;
1219 return '' unless $error;
1223 #apply_payments_and_credits ?
1224 $cust_credit->cust_main->apply_credits;
1231 FS::Record::process_batch_import( $job, $opt, @_ );
1239 The delete method. The replace method.
1241 B<credited> and B<credited_sql> are now called B<unapplied> and
1242 B<unapplied_sql>. The old method names should start to give warnings.
1246 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1247 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base