1 package FS::cust_credit;
4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
7 use vars qw( $conf $unsuspendauto $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 {
40 $unsuspendauto = $conf->exists('unsuspendauto');
44 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
45 'cancel_credit_type' => 'Cancellation Credit',
50 FS::cust_credit - Object methods for cust_credit records
56 $record = new FS::cust_credit \%hash;
57 $record = new FS::cust_credit { 'column' => 'value' };
59 $error = $record->insert;
61 $error = $new_record->replace($old_record);
63 $error = $record->delete;
65 $error = $record->check;
69 An FS::cust_credit object represents a credit; the equivalent of a negative
70 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
71 FS::Record. The following fields are currently supported:
77 Primary key (assigned automatically for new credits)
81 Customer (see L<FS::cust_main>)
89 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
90 L<Time::Local> and L<Date::Parse> for conversion functions.
94 Order taker (see L<FS::access_user>)
102 Reason (see L<FS::reason>)
110 Books closed flag, empty or `Y'
114 Desired pkgnum when using experimental package balances.
124 Creates a new credit. To add the credit to the database, see L<"insert">.
128 sub table { 'cust_credit'; }
129 sub cust_linked { $_[0]->cust_main_custnum; }
130 sub cust_unlinked_msg {
132 "WARNING: can't find cust_main.custnum ". $self->custnum.
133 ' (cust_credit.crednum '. $self->crednum. ')';
138 Adds this credit to the database ("Posts" the credit). If there is an error,
139 returns the error, otherwise returns false.
144 my ($self, %options) = @_;
146 local $SIG{HUP} = 'IGNORE';
147 local $SIG{INT} = 'IGNORE';
148 local $SIG{QUIT} = 'IGNORE';
149 local $SIG{TERM} = 'IGNORE';
150 local $SIG{TSTP} = 'IGNORE';
151 local $SIG{PIPE} = 'IGNORE';
153 my $oldAutoCommit = $FS::UID::AutoCommit;
154 local $FS::UID::AutoCommit = 0;
157 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
158 my $old_balance = $cust_main->balance;
160 if (!$self->reasonnum) {
161 my $reason_text = $self->get('reason')
162 or return "reason text or existing reason required";
163 my $reason_type = $options{'reason_type'}
164 or return "reason type required";
167 my $reason = FS::reason->new_or_existing(
168 reason => $reason_text,
169 type => $reason_type,
173 $dbh->rollback if $oldAutoCommit;
174 return "failed to set credit reason: $@";
176 $self->set('reasonnum', $reason->reasonnum);
179 $self->setfield('reason', '');
181 my $error = $self->SUPER::insert;
183 $dbh->rollback if $oldAutoCommit;
184 return "error inserting $self: $error";
187 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
189 #false laziness w/ cust_pay::insert
190 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
191 my @errors = $cust_main->unsuspend;
193 # side-fx with nested transactions? upstack rolls back?
194 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
200 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
208 Unless the closed flag is set, deletes this credit and all associated
209 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
210 the void method instead to leave a record of the deleted credit.
214 # very similar to FS::cust_pay::delete
219 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
221 local $SIG{HUP} = 'IGNORE';
222 local $SIG{INT} = 'IGNORE';
223 local $SIG{QUIT} = 'IGNORE';
224 local $SIG{TERM} = 'IGNORE';
225 local $SIG{TSTP} = 'IGNORE';
226 local $SIG{PIPE} = 'IGNORE';
228 my $oldAutoCommit = $FS::UID::AutoCommit;
229 local $FS::UID::AutoCommit = 0;
232 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
233 my $error = $cust_credit_bill->delete;
235 $dbh->rollback if $oldAutoCommit;
240 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
241 my $error = $cust_credit_refund->delete;
243 $dbh->rollback if $oldAutoCommit;
248 my $error = $self->SUPER::delete(@_);
250 $dbh->rollback if $oldAutoCommit;
254 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
256 my $cust_main = $self->cust_main;
258 my $error = send_email(
259 'from' => $conf->invoice_from_full($self->cust_main->agentnum),
260 #invoice_from??? well as good as any
261 'to' => $conf->config('deletecredits'),
262 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
264 "This is an automatic message from your Freeside installation\n",
265 "informing you that the following credit has been deleted:\n",
267 'crednum: '. $self->crednum. "\n",
268 'custnum: '. $self->custnum.
269 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
270 'amount: $'. sprintf("%.2f", $self->amount). "\n",
271 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
272 'reason: '. $self->reason. "\n",
277 $dbh->rollback if $oldAutoCommit;
278 return "can't send credit deletion notification: $error";
283 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
289 =item replace [ OLD_RECORD ]
291 You can, but probably shouldn't modify credits...
293 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
294 supplied, replaces this record. If there is an error, returns the error,
295 otherwise returns false.
301 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
302 $self->SUPER::replace(@_);
307 Checks all fields to make sure this is a valid credit. If there is an error,
308 returns the error, otherwise returns false. Called by the insert and replace
316 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
319 $self->ut_numbern('crednum')
320 || $self->ut_number('custnum')
321 || $self->ut_numbern('_date')
322 || $self->ut_money('amount')
323 || $self->ut_alphan('otaker')
324 || $self->ut_textn('reason')
325 || $self->ut_textn('addlinfo')
326 || $self->ut_enum('closed', [ '', 'Y' ])
327 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
328 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
329 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
330 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
331 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
333 return $error if $error;
335 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
336 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
337 return $error if $error;
339 return "amount must be > 0 " if $self->amount <= 0;
341 return "amount must be greater or equal to amount applied"
342 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
344 return "Unknown customer"
345 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
347 $self->_date(time) unless $self->_date;
352 =item void [ REASON ]
354 Voids this credit: deletes the credit and all associated applications and
355 adds a record of the voided credit to the cust_credit_void table.
363 unless (ref($reason) || !$reason) {
364 $reason = FS::reason->new_or_existing(
366 'type' => 'Void credit',
371 local $SIG{HUP} = 'IGNORE';
372 local $SIG{INT} = 'IGNORE';
373 local $SIG{QUIT} = 'IGNORE';
374 local $SIG{TERM} = 'IGNORE';
375 local $SIG{TSTP} = 'IGNORE';
376 local $SIG{PIPE} = 'IGNORE';
378 my $oldAutoCommit = $FS::UID::AutoCommit;
379 local $FS::UID::AutoCommit = 0;
382 my $cust_credit_void = new FS::cust_credit_void ( {
383 map { $_ => $self->get($_) } $self->fields
385 $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
386 my $error = $cust_credit_void->insert;
388 $dbh->rollback if $oldAutoCommit;
392 $error = $self->delete(void => 1); # suppress deletecredits warning
394 $dbh->rollback if $oldAutoCommit;
398 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
404 =item cust_credit_refund
406 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
410 sub cust_credit_refund {
412 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
413 sort { $a->_date <=> $b->_date }
414 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
418 =item cust_credit_bill
420 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
425 sub cust_credit_bill {
427 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
428 sort { $a->_date <=> $b->_date }
429 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
435 Returns the amount of this credit that is still unapplied/outstanding;
436 amount minus all refund applications (see L<FS::cust_credit_refund>) and
437 applications to invoices (see L<FS::cust_credit_bill>).
443 my $amount = $self->amount;
444 $amount -= $_->amount foreach ( $self->cust_credit_refund );
445 $amount -= $_->amount foreach ( $self->cust_credit_bill );
446 sprintf( "%.2f", $amount );
451 Deprecated name for the unapplied method.
457 #carp "cust_credit->credited deprecated; use ->unapplied";
458 $self->unapplied(@_);
463 Returns the customer (see L<FS::cust_main>) for this credit.
469 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
474 Returns the text of the associated reason (see L<FS::reason>) for this credit.
480 # Used by FS::Upgrade to migrate to a new database.
482 sub _upgrade_data { # class method
483 my ($class, %opts) = @_;
485 warn "$me upgrading $class\n" if $DEBUG;
487 $class->_upgrade_reasonnum(%opts);
489 if (defined dbdef->table($class->table)->column('reason')) {
491 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
493 foreach ( keys %reasontype_map ) {
494 unless ($conf->config($_)) { # hmmmm
495 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
496 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
497 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
498 my $reason_type = qsearchs( 'reason_type', $hashref );
499 unless ($reason_type) {
500 $reason_type = new FS::reason_type( $hashref );
501 my $error = $reason_type->insert();
502 die "$class had error inserting FS::reason_type into database: $error\n"
505 $conf->set($_, $reason_type->typenum);
509 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
511 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
512 my $reason_type = qsearchs( 'reason_type', $hashref );
513 unless ($reason_type) {
514 $reason_type = new FS::reason_type( $hashref );
515 my $error = $reason_type->insert();
516 die "$class had error inserting FS::reason_type into database: $error\n"
520 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
521 foreach my $plan ( @plans ) {
522 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
523 unless ($pkg->option('reason_type', 1) ) {
524 my $plandata = $pkg->plandata.
525 "reason_type=". $reason_type->typenum. "\n";
526 $pkg->plandata($plandata);
528 $pkg->replace( undef,
529 'pkg_svc' => { map { $_->svcpart => $_->quantity }
532 'primary_svc' => $pkg->svcpart,
534 die "failed setting reason_type option: $error"
541 local($otaker_upgrade_kludge) = 1;
542 local($ignore_empty_reasonnum) = 1;
543 $class->_upgrade_otaker(%opts);
545 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
546 and !$conf->exists('enable_taxproducts') ) {
547 # RT#25458: fix credit line item applications that should refer to a
548 # specific tax allocation
549 my @cust_credit_bill_pkg = qsearch({
550 table => 'cust_credit_bill_pkg',
551 select => 'cust_credit_bill_pkg.*',
552 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
554 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
555 'AND cust_bill_pkg.pkgnum = 0', # is a tax
559 foreach (@cust_credit_bill_pkg) {
560 my $billpkgnum = $_->billpkgnum;
561 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
562 $credits{$billpkgnum} ||= [];
563 push @{ $credits{$billpkgnum} }, $_;
565 TAX_ITEM: foreach my $tax_item (values %tax_items) {
566 my $billpkgnum = $tax_item->billpkgnum;
567 # get all pkg/location/taxrate allocations of this tax line item
568 my @allocations = sort {$b->amount <=> $a->amount}
569 qsearch('cust_bill_pkg_tax_location', {
570 billpkgnum => $billpkgnum
572 # and these are all credit applications to it
573 my @credits = sort {$b->amount <=> $a->amount}
574 @{ $credits{$billpkgnum} };
575 my $c = shift @credits;
576 my $a = shift @allocations; # we will NOT modify these
578 if ( abs($c->amount - $a->amount) < 0.005 ) {
579 # by far the most common case: the tax line item is for a single
580 # tax, so we just fill in the billpkgtaxlocationnum
581 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
582 my $error = $c->replace;
584 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
588 $a = shift @allocations;
589 } elsif ( $c->amount > $a->amount ) {
590 # fairly common: the tax line contains tax for multiple packages
591 # (or multiple taxes) but the credit isn't divided up
592 my $new_link = FS::cust_credit_bill_pkg->new({
593 creditbillnum => $c->creditbillnum,
594 billpkgnum => $c->billpkgnum,
595 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
596 amount => $a->amount,
597 setuprecur => 'setup',
599 my $error = $new_link->insert;
601 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
604 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
605 $a = shift @allocations;
606 } elsif ( $c->amount < 0.005 ) {
607 # also fairly common; we can delete these with no harm
608 my $error = $c->delete;
609 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
611 } elsif ( $c->amount < $a->amount ) {
612 # should never happen, but if it does, handle it gracefully
613 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
614 my $error = $c->replace;
616 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
619 $a->set(amount => $a->amount - $c->amount);
624 if ( $c->amount < 0.005 ) {
625 my $error = $c->delete;
626 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
627 } elsif ( $c->modified ) {
628 # then we've allocated part of it, so reduce the nonspecific
629 # application by that much
630 my $error = $c->replace;
631 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
633 # else there are probably no allocations, i.e. this is a pre-3.x
634 # record that was never migrated over, so leave it alone
636 } # foreach $tax_item
637 FS::upgrade_journal->set_done('cust_credit__tax_link');
649 Returns an SQL fragment to retreive the unapplied amount.
654 my ($class, $start, $end) = @_;
656 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
657 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
658 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
659 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
663 ( SELECT SUM(amount) FROM cust_credit_refund
664 WHERE cust_credit.crednum = cust_credit_refund.crednum
665 $refund_start $refund_end )
669 ( SELECT SUM(amount) FROM cust_credit_bill
670 WHERE cust_credit.crednum = cust_credit_bill.crednum
671 $bill_start $bill_end )
680 Deprecated name for the unapplied_sql method.
687 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
689 #$class->unapplied_sql(@_);
693 =item calculate_tax_adjustment PARAMS
695 Calculate the amount of tax that needs to be credited as part of a lineitem
700 - billpkgnums: arrayref identifying the line items to credit
701 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
702 the lineitem charge is being credited
703 - amounts: arrayref of the amounts to credit on each line item
704 - custnum: the customer all of these invoices belong to, for error checking
706 Returns a hash containing:
707 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
708 - taxtotal: the total tax amount to be credited
709 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
710 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
711 - num: the key within that table
712 - credit: the credit amount to apply to that line
716 sub calculate_tax_adjustment {
717 my ($class, %arg) = @_;
724 my (%cust_bill_pkg, %cust_bill);
726 for (my $i = 0; ; $i++) {
727 my $billpkgnum = $arg{billpkgnums}[$i]
729 my $setuprecur = $arg{setuprecurs}[$i];
730 my $amount = $arg{amounts}[$i];
731 next if $amount == 0;
732 $subtotal += $amount;
733 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
734 ||= FS::cust_bill_pkg->by_key($billpkgnum)
735 or die "lineitem #$billpkgnum not found\n";
737 my $invnum = $cust_bill_pkg->invnum;
738 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
739 $cust_bill{ $invnum}->custnum == $arg{custnum}
740 or die "lineitem #$billpkgnum not found\n";
742 # tax_Xlocation records don't distinguish setup and recur, so calculate
743 # the fraction of setup+recur (after deducting credits) that's setup. This
744 # will also be the fraction of tax (after deducting credits) that's tax on
747 $setup = $cust_bill_pkg->get('setup') || 0;
749 $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
751 $recur = $cust_bill_pkg->get('recur') || 0;
753 $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
755 my $setup_ratio = $setup / ($setup + $recur);
757 # Calculate the fraction of tax to credit: it's the fraction of this charge
758 # (either setup or recur) that's being credited.
759 my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
760 next if $charged == 0; # shouldn't happen, but still...
762 if ($charged < $amount) {
763 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
766 my $credit_ratio = $amount / $charged;
768 # gather taxes that apply to the selected item
770 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
772 foreach my $tax_link (
773 qsearch($table, { taxable_billpkgnum => $billpkgnum })
775 my $tax_amount = $tax_link->amount;
776 # deduct existing credits applied to the tax, for the same reason as
778 foreach ($tax_link->cust_credit_bill_pkg) {
779 $tax_amount -= $_->amount;
781 # split tax amount based on setuprecur
782 # (this method ensures that, if you credit both setup and recur tax,
783 # it always equals the entire tax despite any rounding)
784 my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
785 if ( $setuprecur eq 'setup' ) {
786 $tax_amount = $setup_tax;
788 $tax_amount = $tax_amount - $setup_tax;
790 my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
791 my $pkey = $tax_link->get($tax_link->primary_key);
795 credit => $tax_credit,
797 $taxtotal += $tax_credit;
799 } #foreach cust_bill_pkg_tax_(rate_)?location
801 } # foreach $billpkgnum
804 subtotal => sprintf('%.2f', $subtotal),
805 taxtotal => sprintf('%.2f', $taxtotal),
806 taxlines => \@taxlines,
810 =item credit_lineitems
814 my $error = FS::cust_credit->credit_lineitems(
816 #the lineitems to credit
817 'billpkgnums' => \@billpkgnums,
818 'setuprecurs' => \@setuprecurs,
819 'amounts' => \@amounts,
820 'apply' => 1, #0 leaves the credit unapplied
823 map { $_ => scalar($cgi->param($_)) }
824 #fields('cust_credit')
825 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
831 #maybe i should just be an insert with extra args instead of a class method
832 sub credit_lineitems {
833 my( $class, %arg ) = @_;
834 my $curuser = $FS::CurrentUser::CurrentUser;
836 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
838 my $cust_main = qsearchs({
839 'table' => 'cust_main',
840 'hashref' => { 'custnum' => $arg{custnum} },
841 'extra_sql' => ' AND '. $curuser->agentnums_sql,
842 }) or return 'unknown customer';
845 local $SIG{HUP} = 'IGNORE';
846 local $SIG{INT} = 'IGNORE';
847 local $SIG{QUIT} = 'IGNORE';
848 local $SIG{TERM} = 'IGNORE';
849 local $SIG{TSTP} = 'IGNORE';
850 local $SIG{PIPE} = 'IGNORE';
852 my $oldAutoCommit = $FS::UID::AutoCommit;
853 local $FS::UID::AutoCommit = 0;
856 #my @cust_bill_pkg = qsearch({
857 # 'select' => 'cust_bill_pkg.*',
858 # 'table' => 'cust_bill_pkg',
859 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
860 # ' LEFT JOIN cust_main USING (custnum) ',
861 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
862 # join( ',', @{$arg{billpkgnums}} ). ')',
863 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
868 my $cust_credit = new FS::cust_credit ( {
869 map { $_ => $arg{$_} }
870 #fields('cust_credit')
871 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
873 $error = $cust_credit->insert;
875 $dbh->rollback if $oldAutoCommit;
876 return "Error inserting credit: $error";
879 unless ( $arg{'apply'} ) {
880 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
885 # keys in all of these are invoice numbers
886 my %cust_credit_bill = ();
887 my %cust_bill_pkg = ();
888 my %cust_credit_bill_pkg = ();
889 my %unapplied_payments = (); #invoice numbers, and then billpaynums
891 # determine the tax adjustments
892 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
894 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
895 my $setuprecur = shift @{$arg{setuprecurs}};
896 my $amount = shift @{$arg{amounts}};
898 my $cust_bill_pkg = qsearchs({
899 'table' => 'cust_bill_pkg',
900 'hashref' => { 'billpkgnum' => $billpkgnum },
901 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
902 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
903 }) or die "unknown billpkgnum $billpkgnum";
905 my $invnum = $cust_bill_pkg->invnum;
907 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
909 $cust_credit_bill{$invnum} += $amount;
910 push @{ $cust_credit_bill_pkg{$invnum} },
911 new FS::cust_credit_bill_pkg {
912 'billpkgnum' => $billpkgnum,
913 'amount' => sprintf('%.2f',$amount),
914 'setuprecur' => $setuprecur,
915 'sdate' => $cust_bill_pkg->sdate,
916 'edate' => $cust_bill_pkg->edate,
918 # unapply payments (but not other credits) from this line item
919 foreach my $cust_bill_pay_pkg (
920 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
922 $error = $cust_bill_pay_pkg->delete;
924 $dbh->rollback if $oldAutoCommit;
925 return "Error unapplying payment: $error";
927 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
928 += $cust_bill_pay_pkg->amount;
932 # do the same for taxes
933 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
934 my $table = $tax_credit->{table};
935 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
936 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
938 my $billpkgnum = $tax_link->billpkgnum;
939 my $cust_bill_pkg = qsearchs({
940 'table' => 'cust_bill_pkg',
941 'hashref' => { 'billpkgnum' => $billpkgnum },
942 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
943 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
944 }) or die "unknown billpkgnum $billpkgnum";
946 my $invnum = $cust_bill_pkg->invnum;
947 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
949 my $amount = $tax_credit->{credit};
950 $cust_credit_bill{$invnum} += $amount;
952 # create a credit application record to the tax line item, earmarked
953 # to the specific cust_bill_pkg_Xlocation
954 push @{ $cust_credit_bill_pkg{$invnum} },
955 new FS::cust_credit_bill_pkg {
956 'billpkgnum' => $billpkgnum,
957 'amount' => sprintf('%.2f', $amount),
958 'setuprecur' => 'setup',
959 $tax_link->primary_key, $tax_credit->{num}
961 # unapply any payments from the tax
962 foreach my $cust_bill_pay_pkg (
963 $cust_bill_pkg->cust_bill_pay_pkg('setup')
965 $error = $cust_bill_pay_pkg->delete;
967 $dbh->rollback if $oldAutoCommit;
968 return "Error unapplying payment: $error";
970 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
971 += $cust_bill_pay_pkg->amount;
976 # now loop through %cust_credit_bill and insert those
979 # (hack to prevent cust_credit_bill_pkg insertion)
980 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
982 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
984 # if we unapplied any payments from line items, also unapply that
985 # amount from the invoice
986 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
987 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
988 or die "broken payment application $billpaynum";
989 my @subapps = $cust_bill_pay->lineitem_applications;
990 $error = $cust_bill_pay->delete; # can't replace
992 my $new_cust_bill_pay = FS::cust_bill_pay->new({
993 $cust_bill_pay->hash,
995 amount => sprintf('%.2f',
996 $cust_bill_pay->amount
997 - $unapplied_payments{$invnum}{$billpaynum}),
1000 if ( $new_cust_bill_pay->amount > 0 ) {
1001 $error ||= $new_cust_bill_pay->insert;
1002 # Also reapply it to everything it was applied to before.
1003 # Note that we've already deleted cust_bill_pay_pkg records for the
1004 # items we're crediting, so they aren't on this list.
1005 foreach my $cust_bill_pay_pkg (@subapps) {
1006 $cust_bill_pay_pkg->billpaypkgnum('');
1007 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1008 $error ||= $cust_bill_pay_pkg->insert;
1012 $dbh->rollback if $oldAutoCommit;
1013 return "Error unapplying payment: $error";
1016 #insert cust_credit_bill
1018 my $cust_credit_bill = new FS::cust_credit_bill {
1019 'crednum' => $cust_credit->crednum,
1020 'invnum' => $invnum,
1021 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1023 $error = $cust_credit_bill->insert;
1025 $dbh->rollback if $oldAutoCommit;
1026 return "Error applying credit of $cust_credit_bill{$invnum} ".
1027 " to invoice $invnum: $error";
1030 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1031 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1032 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1033 $error = $cust_credit_bill_pkg->insert;
1035 $dbh->rollback if $oldAutoCommit;
1036 return "Error applying credit to line item: $error";
1042 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1053 =item process_batch_import
1057 use List::Util qw( min );
1059 use FS::cust_credit_bill;
1060 sub process_batch_import {
1063 my $opt = { 'table' => 'cust_credit',
1064 'params' => [ '_date', 'credbatch' ],
1065 'formats' => { 'simple' =>
1066 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1069 'postinsert_callback' => sub {
1070 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1072 if ( $cust_credit->invnum ) {
1074 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1075 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1077 my $cust_credit_bill = new FS::cust_credit_bill ( {
1078 'crednum' => $cust_credit->crednum,
1079 'invnum' => $cust_bill->invnum,
1080 'amount' => $amount,
1082 my $error = $cust_credit_bill->insert;
1083 return '' unless $error;
1087 #apply_payments_and_credits ?
1088 $cust_credit->cust_main->apply_credits;
1095 FS::Record::process_batch_import( $job, $opt, @_ );
1103 The delete method. The replace method.
1105 B<credited> and B<credited_sql> are now called B<unapplied> and
1106 B<unapplied_sql>. The old method names should start to give warnings.
1110 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1111 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base