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 # Skip line items that have been completely credited.
747 next if ($setup + $recur) == 0;
748 my $setup_ratio = $setup / ($setup + $recur);
750 # Calculate the fraction of tax to credit: it's the fraction of this
751 # charge (either setup or recur) that's being credited.
752 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
753 next if $charged == 0; # shouldn't happen, but still...
755 if ($charged < $amount) {
756 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
759 my $credit_ratio = $amount / $charged;
761 # gather taxes that apply to the selected item
763 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
765 foreach my $tax_link (
766 qsearch($table, { taxable_billpkgnum => $billpkgnum })
768 my $tax_amount = $tax_link->amount;
769 # deduct existing credits applied to the tax, for the same reason as
771 foreach ($tax_link->cust_credit_bill_pkg) {
772 $tax_amount -= $_->amount;
774 # split tax amount based on setuprecur
775 # (this method ensures that, if you credit both setup and recur tax,
776 # it always equals the entire tax despite any rounding)
777 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
778 if ( $setuprecur eq 'setup' ) {
779 $tax_amount = $setup_tax;
781 $tax_amount = $tax_amount - $setup_tax;
783 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
784 my $pkey = $tax_link->get($tax_link->primary_key);
788 credit => $tax_credit,
790 $taxtotal += $tax_credit;
792 } #foreach cust_bill_pkg_tax_(rate_)?location
794 } # foreach $billpkgnum
797 subtotal => sprintf('%.2f', $subtotal),
798 taxtotal => sprintf('%.2f', $taxtotal),
799 taxlines => \@taxlines,
803 =item credit_lineitems OPTIONS
805 Creates a credit to a group of line items, with a specified amount applied
806 to each. This will also calculate the tax adjustments for those amounts and
807 credit the appropriate tax line items.
811 my $error = FS::cust_credit->credit_lineitems(
813 #the lineitems to credit
814 'billpkgnums' => \@billpkgnums,
815 'setuprecurs' => \@setuprecurs,
816 'amounts' => \@amounts,
817 'apply' => 1, #0 leaves the credit unapplied
820 map { $_ => scalar($cgi->param($_)) }
821 #fields('cust_credit')
822 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
826 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
827 arrays. Each one indicates an amount of credit to be applied to either the
828 setup or recur portion of a (non-tax) line item.
830 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
831 credit before it's inserted.
833 C<amount> is the total amount. If unspecified, the credit will be the sum
834 of the per-line-item amounts and their tax adjustments.
838 #maybe i should just be an insert with extra args instead of a class method
839 sub credit_lineitems {
840 my( $class, %arg ) = @_;
841 my $curuser = $FS::CurrentUser::CurrentUser;
843 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
845 my $cust_main = qsearchs({
846 'table' => 'cust_main',
847 'hashref' => { 'custnum' => $arg{custnum} },
848 'extra_sql' => ' AND '. $curuser->agentnums_sql,
849 }) or return 'unknown customer';
852 local $SIG{HUP} = 'IGNORE';
853 local $SIG{INT} = 'IGNORE';
854 local $SIG{QUIT} = 'IGNORE';
855 local $SIG{TERM} = 'IGNORE';
856 local $SIG{TSTP} = 'IGNORE';
857 local $SIG{PIPE} = 'IGNORE';
859 my $oldAutoCommit = $FS::UID::AutoCommit;
860 local $FS::UID::AutoCommit = 0;
863 #my @cust_bill_pkg = qsearch({
864 # 'select' => 'cust_bill_pkg.*',
865 # 'table' => 'cust_bill_pkg',
866 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
867 # ' LEFT JOIN cust_main USING (custnum) ',
868 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
869 # join( ',', @{$arg{billpkgnums}} ). ')',
870 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
875 # first, determine the tax adjustments
876 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
877 # and determine the amount automatically if it wasn't specified
878 if ( !exists( $arg{amount} ) ) {
879 $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
883 my $cust_credit = new FS::cust_credit ( {
884 map { $_ => $arg{$_} }
885 #fields('cust_credit')
886 qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
888 $error = $cust_credit->insert;
890 $dbh->rollback if $oldAutoCommit;
891 return "Error inserting credit: $error";
894 unless ( $arg{'apply'} ) {
895 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
900 # keys in all of these are invoice numbers
901 my %cust_credit_bill = ();
902 my %cust_bill_pkg = ();
903 my %cust_credit_bill_pkg = ();
904 my %unapplied_payments = (); #invoice numbers, and then billpaynums
906 # little private function to unapply payments from a cust_bill_pkg until
907 # there's a specified amount of unpaid balance on it.
908 # it's a separate sub because we do it for both tax and nontax items. it's
909 # private because it needs access to some local data structures.
910 my $unapply_sub = sub {
911 my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
913 my $invnum = $cust_bill_pkg->invnum;
915 $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
916 return if $need_to_unapply < 0.005;
919 # then unapply payments one at a time (partially if need be) until the
920 # unpaid balance = the credit amount.
921 foreach my $cust_bill_pay_pkg (
922 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
924 my $this_amount = $cust_bill_pay_pkg->amount;
925 if ( $this_amount > $need_to_unapply ) {
926 # unapply the needed amount
927 $cust_bill_pay_pkg->set('amount',
928 sprintf('%.2f', $this_amount - $need_to_unapply));
929 $error = $cust_bill_pay_pkg->replace;
930 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
931 last; # and we're done
935 $error = $cust_bill_pay_pkg->delete;
936 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
938 $need_to_unapply -= $this_amount;
941 } # foreach $cust_bill_pay_pkg
943 # return an error if we somehow still have leftover $need_to_unapply?
949 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
950 my $setuprecur = shift @{$arg{setuprecurs}};
951 my $amount = shift @{$arg{amounts}};
953 my $cust_bill_pkg = qsearchs({
954 'table' => 'cust_bill_pkg',
955 'hashref' => { 'billpkgnum' => $billpkgnum },
956 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
957 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
958 }) or die "unknown billpkgnum $billpkgnum";
960 my $invnum = $cust_bill_pkg->invnum;
962 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
964 $cust_credit_bill{$invnum} += $amount;
965 push @{ $cust_credit_bill_pkg{$invnum} },
966 new FS::cust_credit_bill_pkg {
967 'billpkgnum' => $billpkgnum,
968 'amount' => sprintf('%.2f',$amount),
969 'setuprecur' => $setuprecur,
970 'sdate' => $cust_bill_pkg->sdate,
971 'edate' => $cust_bill_pkg->edate,
974 # unapply payments if necessary
975 $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
978 $dbh->rollback if $oldAutoCommit;
979 return "Error unapplying payment: $error";
983 # do the same for taxes
984 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
985 my $table = $tax_credit->{table};
986 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
987 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
989 my $billpkgnum = $tax_link->billpkgnum;
990 my $cust_bill_pkg = qsearchs({
991 'table' => 'cust_bill_pkg',
992 'hashref' => { 'billpkgnum' => $billpkgnum },
993 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
994 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
995 }) or die "unknown billpkgnum $billpkgnum";
997 my $invnum = $cust_bill_pkg->invnum;
998 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
1000 my $amount = $tax_credit->{credit};
1001 $cust_credit_bill{$invnum} += $amount;
1003 # create a credit application record to the tax line item, earmarked
1004 # to the specific cust_bill_pkg_Xlocation
1005 push @{ $cust_credit_bill_pkg{$invnum} },
1006 new FS::cust_credit_bill_pkg {
1007 'billpkgnum' => $billpkgnum,
1008 'amount' => sprintf('%.2f', $amount),
1009 'setuprecur' => 'setup',
1010 $tax_link->primary_key, $tax_credit->{num}
1013 $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1015 $dbh->rollback if $oldAutoCommit;
1016 return "Error unapplying payment: $error";
1021 # now loop through %cust_credit_bill and insert those
1024 # (hack to prevent cust_credit_bill_pkg insertion)
1025 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1027 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1029 # if we unapplied any payments from line items, also unapply that
1030 # amount from the invoice
1031 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1032 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1033 or die "broken payment application $billpaynum";
1034 my @subapps = $cust_bill_pay->lineitem_applications;
1035 $error = $cust_bill_pay->delete; # can't replace
1037 my $new_cust_bill_pay = FS::cust_bill_pay->new({
1038 $cust_bill_pay->hash,
1040 amount => sprintf('%.2f',
1041 $cust_bill_pay->amount
1042 - $unapplied_payments{$invnum}{$billpaynum}),
1045 if ( $new_cust_bill_pay->amount > 0 ) {
1046 $error ||= $new_cust_bill_pay->insert;
1047 # Also reapply it to everything it was applied to before.
1048 # Note that we've already deleted cust_bill_pay_pkg records for the
1049 # items we're crediting, so they aren't on this list.
1050 foreach my $cust_bill_pay_pkg (@subapps) {
1051 $cust_bill_pay_pkg->billpaypkgnum('');
1052 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1053 $error ||= $cust_bill_pay_pkg->insert;
1057 $dbh->rollback if $oldAutoCommit;
1058 return "Error unapplying payment: $error";
1061 #insert cust_credit_bill
1063 my $cust_credit_bill = new FS::cust_credit_bill {
1064 'crednum' => $cust_credit->crednum,
1065 'invnum' => $invnum,
1066 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1068 $error = $cust_credit_bill->insert;
1070 $dbh->rollback if $oldAutoCommit;
1071 return "Error applying credit of $cust_credit_bill{$invnum} ".
1072 " to invoice $invnum: $error";
1075 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1076 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1077 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1078 $error = $cust_credit_bill_pkg->insert;
1080 $dbh->rollback if $oldAutoCommit;
1081 return "Error applying credit to line item: $error";
1087 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1092 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1094 =item refund_to_unapply
1096 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1097 (all currently applied refunds that aren't closed.)
1098 Returns empty list if credit itself is closed.
1102 sub refund_to_unapply {
1104 return () if $self->closed;
1106 'table' => 'cust_credit_refund',
1107 'hashref' => { 'crednum' => $self->crednum },
1108 'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1109 'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1113 =item unapply_refund
1115 Deletes all objects returned by L</refund_to_unapply>.
1119 sub unapply_refund {
1122 local $SIG{HUP} = 'IGNORE';
1123 local $SIG{INT} = 'IGNORE';
1124 local $SIG{QUIT} = 'IGNORE';
1125 local $SIG{TERM} = 'IGNORE';
1126 local $SIG{TSTP} = 'IGNORE';
1127 local $SIG{PIPE} = 'IGNORE';
1129 my $oldAutoCommit = $FS::UID::AutoCommit;
1130 local $FS::UID::AutoCommit = 0;
1132 foreach my $cust_credit_refund ($self->refund_to_unapply) {
1133 my $error = $cust_credit_refund->delete;
1135 dbh->rollback if $oldAutoCommit;
1140 dbh->commit or die dbh->errstr if $oldAutoCommit;
1150 =item process_batch_import
1154 use List::Util qw( min );
1156 use FS::cust_credit_bill;
1157 sub process_batch_import {
1160 # some false laziness with FS::cust_pay::process_batch_import
1163 my $custnum = $hash{'custnum'};
1164 my $agent_custid = $hash{'agent_custid'};
1165 # translate agent_custid into regular custnum
1166 if ($custnum && $agent_custid) {
1167 die "can't specify both custnum and agent_custid\n";
1168 } elsif ($agent_custid) {
1169 # here is the agent virtualization
1170 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1172 $search{'agent_custid'} = $agent_custid
1174 $search{'custnum'} = $custnum
1176 my $cust_main = qsearchs({
1177 'table' => 'cust_main',
1178 'hashref' => \%search,
1179 'extra_sql' => $extra_sql,
1181 die "can't find customer with" .
1182 ($custnum ? " custnum $custnum" : '') .
1183 ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1185 die "mismatched customer number\n"
1186 if $custnum && ($custnum ne $cust_main->custnum);
1187 $custnum = $cust_main->custnum;
1189 $hash{'custnum'} = $custnum;
1190 delete($hash{'agent_custid'});
1194 my $opt = { 'table' => 'cust_credit',
1195 'params' => [ '_date', 'credbatch' ],
1196 'formats' => { 'simple' =>
1197 [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1200 'format_hash_callbacks' => { 'simple' => $hashcb },
1201 'postinsert_callback' => sub {
1202 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1204 if ( $cust_credit->invnum ) {
1206 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1207 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1209 my $cust_credit_bill = new FS::cust_credit_bill ( {
1210 'crednum' => $cust_credit->crednum,
1211 'invnum' => $cust_bill->invnum,
1212 'amount' => $amount,
1214 my $error = $cust_credit_bill->insert;
1215 return '' unless $error;
1219 #apply_payments_and_credits ?
1220 $cust_credit->cust_main->apply_credits;
1227 FS::Record::process_batch_import( $job, $opt, @_ );
1235 The delete method. The replace method.
1237 B<credited> and B<credited_sql> are now called B<unapplied> and
1238 B<unapplied_sql>. The old method names should start to give warnings.
1242 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1243 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base