1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
6 use vars qw( $conf $unsuspendauto $me $DEBUG
7 $otaker_upgrade_kludge $ignore_empty_reasonnum
9 use List::Util qw( min );
11 use FS::UID qw( dbh );
12 use FS::Misc qw(send_email);
13 use FS::Record qw( qsearch qsearchs dbdef );
17 use FS::cust_credit_bill;
24 use FS::cust_credit_void;
25 use FS::cust_bill_pkg;
26 use FS::upgrade_journal;
28 $me = '[ FS::cust_credit ]';
31 $otaker_upgrade_kludge = 0;
32 $ignore_empty_reasonnum = 0;
34 #ask FS::UID to run this stuff for us later
35 $FS::UID::callback{'FS::cust_credit'} = sub {
38 $unsuspendauto = $conf->exists('unsuspendauto');
42 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
43 'cancel_credit_type' => 'Cancellation Credit',
44 'signup_credit_type' => 'Self-Service 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 || $_[0]->custnum }
129 sub cust_unlinked_msg {
131 "WARNING: can't find cust_main.custnum ". $self->custnum.
132 ' (cust_credit.crednum '. $self->crednum. ')';
135 =item insert [ OPTION => VALUE ... ]
137 Adds this credit to the database ("Posts" the credit). If there is an error,
138 returns the error, otherwise returns false.
140 Ooptions are passed as a list of keys and values. Available options:
146 L<FS::reason_type|Reason> type for newly-inserted reason
148 =item cust_credit_source_bill_pkg
151 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
152 They will have their crednum set and will be inserted along with this credit.
159 my ($self, %options) = @_;
161 local $SIG{HUP} = 'IGNORE';
162 local $SIG{INT} = 'IGNORE';
163 local $SIG{QUIT} = 'IGNORE';
164 local $SIG{TERM} = 'IGNORE';
165 local $SIG{TSTP} = 'IGNORE';
166 local $SIG{PIPE} = 'IGNORE';
168 my $oldAutoCommit = $FS::UID::AutoCommit;
169 local $FS::UID::AutoCommit = 0;
172 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
173 my $old_balance = $cust_main->balance;
175 if (!$self->reasonnum) {
176 my $reason_text = $self->get('reason')
177 or return "reason text or existing reason required";
178 my $reason_type = $options{'reason_type'}
179 or return "reason type required";
182 my $reason = FS::reason->new_or_existing(
183 reason => $reason_text,
184 type => $reason_type,
188 $dbh->rollback if $oldAutoCommit;
189 return "failed to set credit reason: $@";
191 $self->set('reasonnum', $reason->reasonnum);
194 $self->setfield('reason', '');
196 my $error = $self->SUPER::insert;
198 $dbh->rollback if $oldAutoCommit;
199 return "error inserting $self: $error";
202 if ( $options{'cust_credit_source_bill_pkg'} ) {
203 foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
204 $ccsbr->crednum( $self->crednum );
205 $error = $ccsbr->insert;
207 $dbh->rollback if $oldAutoCommit;
208 return "error inserting $ccsbr: $error";
213 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
215 #false laziness w/ cust_pay::insert
216 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
217 my @errors = $cust_main->unsuspend;
219 # side-fx with nested transactions? upstack rolls back?
220 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
226 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
234 Unless the closed flag is set, deletes this credit and all associated
235 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
236 the void method instead to leave a record of the deleted credit.
240 # very similar to FS::cust_pay::delete
245 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
247 local $SIG{HUP} = 'IGNORE';
248 local $SIG{INT} = 'IGNORE';
249 local $SIG{QUIT} = 'IGNORE';
250 local $SIG{TERM} = 'IGNORE';
251 local $SIG{TSTP} = 'IGNORE';
252 local $SIG{PIPE} = 'IGNORE';
254 my $oldAutoCommit = $FS::UID::AutoCommit;
255 local $FS::UID::AutoCommit = 0;
258 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
259 my $error = $cust_credit_bill->delete;
261 $dbh->rollback if $oldAutoCommit;
266 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
267 my $error = $cust_credit_refund->delete;
269 $dbh->rollback if $oldAutoCommit;
274 my $error = $self->SUPER::delete(@_);
276 $dbh->rollback if $oldAutoCommit;
280 if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
282 my $cust_main = $self->cust_main;
284 my $error = send_email(
285 'from' => $conf->invoice_from_full($self->cust_main->agentnum),
286 #invoice_from??? well as good as any
287 'to' => $conf->config('deletecredits'),
288 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
290 "This is an automatic message from your Freeside installation\n",
291 "informing you that the following credit has been deleted:\n",
293 'crednum: '. $self->crednum. "\n",
294 'custnum: '. $self->custnum.
295 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
296 'amount: $'. sprintf("%.2f", $self->amount). "\n",
297 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
298 'reason: '. $self->reason. "\n",
303 $dbh->rollback if $oldAutoCommit;
304 return "can't send credit deletion notification: $error";
309 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
315 =item replace [ OLD_RECORD ]
317 You can, but probably shouldn't modify credits...
319 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
320 supplied, replaces this record. If there is an error, returns the error,
321 otherwise returns false.
327 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
328 $self->SUPER::replace(@_);
333 Checks all fields to make sure this is a valid credit. If there is an error,
334 returns the error, otherwise returns false. Called by the insert and replace
342 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
345 $self->ut_numbern('crednum')
346 || $self->ut_number('custnum')
347 || $self->ut_numbern('_date')
348 || $self->ut_money('amount')
349 || $self->ut_alphan('otaker')
350 || $self->ut_textn('reason')
351 || $self->ut_textn('addlinfo')
352 || $self->ut_enum('closed', [ '', 'Y' ])
353 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
354 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
355 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
356 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
357 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
359 return $error if $error;
361 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
362 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
363 return $error if $error;
365 return "amount must be > 0 " if $self->amount <= 0;
367 return "amount must be greater or equal to amount applied"
368 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
370 return "Unknown customer"
371 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
373 $self->_date(time) unless $self->_date;
378 =item void [ REASON ]
380 Voids this credit: deletes the credit and all associated applications and
381 adds a record of the voided credit to the cust_credit_void table.
389 unless (ref($reason) || !$reason) {
390 $reason = FS::reason->new_or_existing(
392 'type' => 'Void credit',
397 local $SIG{HUP} = 'IGNORE';
398 local $SIG{INT} = 'IGNORE';
399 local $SIG{QUIT} = 'IGNORE';
400 local $SIG{TERM} = 'IGNORE';
401 local $SIG{TSTP} = 'IGNORE';
402 local $SIG{PIPE} = 'IGNORE';
404 my $oldAutoCommit = $FS::UID::AutoCommit;
405 local $FS::UID::AutoCommit = 0;
408 my $cust_credit_void = new FS::cust_credit_void ( {
409 map { $_ => $self->get($_) } $self->fields
411 $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
412 my $error = $cust_credit_void->insert;
414 $dbh->rollback if $oldAutoCommit;
418 $error = $self->delete(void => 1); # suppress deletecredits warning
420 $dbh->rollback if $oldAutoCommit;
424 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
430 =item cust_credit_refund
432 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
436 sub cust_credit_refund {
438 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
439 sort { $a->_date <=> $b->_date }
440 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
444 =item cust_credit_bill
446 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
451 sub cust_credit_bill {
453 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
454 sort { $a->_date <=> $b->_date }
455 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
461 Returns the amount of this credit that is still unapplied/outstanding;
462 amount minus all refund applications (see L<FS::cust_credit_refund>) and
463 applications to invoices (see L<FS::cust_credit_bill>).
469 my $amount = $self->amount;
470 $amount -= $_->amount foreach ( $self->cust_credit_refund );
471 $amount -= $_->amount foreach ( $self->cust_credit_bill );
472 sprintf( "%.2f", $amount );
477 Deprecated name for the unapplied method.
483 #carp "cust_credit->credited deprecated; use ->unapplied";
484 $self->unapplied(@_);
489 Returns the customer (see L<FS::cust_main>) for this credit.
495 # Used by FS::Upgrade to migrate to a new database.
497 sub _upgrade_data { # class method
498 my ($class, %opts) = @_;
500 warn "$me upgrading $class\n" if $DEBUG;
502 $class->_upgrade_reasonnum(%opts);
504 if (defined dbdef->table($class->table)->column('reason')) {
506 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
508 foreach ( keys %reasontype_map ) {
509 unless ($conf->config($_)) { # hmmmm
510 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
511 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
512 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
513 my $reason_type = qsearchs( 'reason_type', $hashref );
514 unless ($reason_type) {
515 $reason_type = new FS::reason_type( $hashref );
516 my $error = $reason_type->insert();
517 die "$class had error inserting FS::reason_type into database: $error\n"
520 $conf->set($_, $reason_type->typenum);
524 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
526 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
527 my $reason_type = qsearchs( 'reason_type', $hashref );
528 unless ($reason_type) {
529 $reason_type = new FS::reason_type( $hashref );
530 my $error = $reason_type->insert();
531 die "$class had error inserting FS::reason_type into database: $error\n"
535 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
536 foreach my $plan ( @plans ) {
537 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
538 unless ($pkg->option('reason_type', 1) ) {
539 my $plandata = $pkg->plandata.
540 "reason_type=". $reason_type->typenum. "\n";
541 $pkg->plandata($plandata);
543 $pkg->replace( undef,
544 'pkg_svc' => { map { $_->svcpart => $_->quantity }
547 'primary_svc' => $pkg->svcpart,
549 die "failed setting reason_type option: $error"
556 local($otaker_upgrade_kludge) = 1;
557 local($ignore_empty_reasonnum) = 1;
558 $class->_upgrade_otaker(%opts);
560 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
561 and !$conf->config('tax_data_vendor') ) {
562 # RT#25458: fix credit line item applications that should refer to a
563 # specific tax allocation
564 my @cust_credit_bill_pkg = qsearch({
565 table => 'cust_credit_bill_pkg',
566 select => 'cust_credit_bill_pkg.*',
567 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
569 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
570 'AND cust_bill_pkg.pkgnum = 0', # is a tax
574 foreach (@cust_credit_bill_pkg) {
575 my $billpkgnum = $_->billpkgnum;
576 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
577 $credits{$billpkgnum} ||= [];
578 push @{ $credits{$billpkgnum} }, $_;
580 TAX_ITEM: foreach my $tax_item (values %tax_items) {
581 my $billpkgnum = $tax_item->billpkgnum;
582 # get all pkg/location/taxrate allocations of this tax line item
583 my @allocations = sort {$b->amount <=> $a->amount}
584 qsearch('cust_bill_pkg_tax_location', {
585 billpkgnum => $billpkgnum
587 # and these are all credit applications to it
588 my @credits = sort {$b->amount <=> $a->amount}
589 @{ $credits{$billpkgnum} };
590 my $c = shift @credits;
591 my $a = shift @allocations; # we will NOT modify these
593 if ( abs($c->amount - $a->amount) < 0.005 ) {
594 # by far the most common case: the tax line item is for a single
595 # tax, so we just fill in the billpkgtaxlocationnum
596 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
597 my $error = $c->replace;
599 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
603 $a = shift @allocations;
604 } elsif ( $c->amount > $a->amount ) {
605 # fairly common: the tax line contains tax for multiple packages
606 # (or multiple taxes) but the credit isn't divided up
607 my $new_link = FS::cust_credit_bill_pkg->new({
608 creditbillnum => $c->creditbillnum,
609 billpkgnum => $c->billpkgnum,
610 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
611 amount => $a->amount,
612 setuprecur => 'setup',
614 my $error = $new_link->insert;
616 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
619 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
620 $a = shift @allocations;
621 } elsif ( $c->amount < 0.005 ) {
622 # also fairly common; we can delete these with no harm
623 my $error = $c->delete;
624 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
626 } elsif ( $c->amount < $a->amount ) {
627 # should never happen, but if it does, handle it gracefully
628 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
629 my $error = $c->replace;
631 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
634 $a->set(amount => $a->amount - $c->amount);
639 if ( $c->amount < 0.005 ) {
640 my $error = $c->delete;
641 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
642 } elsif ( $c->modified ) {
643 # then we've allocated part of it, so reduce the nonspecific
644 # application by that much
645 my $error = $c->replace;
646 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
648 # else there are probably no allocations, i.e. this is a pre-3.x
649 # record that was never migrated over, so leave it alone
651 } # foreach $tax_item
652 FS::upgrade_journal->set_done('cust_credit__tax_link');
664 Returns an SQL fragment to retreive the unapplied amount.
669 my ($class, $start, $end) = @_;
671 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
672 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
673 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
674 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
678 ( SELECT SUM(amount) FROM cust_credit_refund
679 WHERE cust_credit.crednum = cust_credit_refund.crednum
680 $refund_start $refund_end )
684 ( SELECT SUM(amount) FROM cust_credit_bill
685 WHERE cust_credit.crednum = cust_credit_bill.crednum
686 $bill_start $bill_end )
695 Deprecated name for the unapplied_sql method.
702 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
704 #$class->unapplied_sql(@_);
708 =item calculate_tax_adjustment PARAMS
710 Calculate the amount of tax that needs to be credited as part of a lineitem
715 - billpkgnums: arrayref identifying the line items to credit
716 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
717 the lineitem charge is being credited
718 - amounts: arrayref of the amounts to credit on each line item
719 - custnum: the customer all of these invoices belong to, for error checking
721 Returns a hash containing:
722 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
723 - taxtotal: the total tax amount to be credited
724 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
725 - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
726 - num: the key within that table
727 - credit: the credit amount to apply to that line
731 sub calculate_tax_adjustment {
732 my ($class, %arg) = @_;
739 my (%cust_bill_pkg, %cust_bill);
741 for (my $i = 0; ; $i++) {
742 my $billpkgnum = $arg{billpkgnums}[$i]
744 my $setuprecur = $arg{setuprecurs}[$i];
745 my $amount = $arg{amounts}[$i];
746 next if $amount == 0;
747 $subtotal += $amount;
748 my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
749 ||= FS::cust_bill_pkg->by_key($billpkgnum)
750 or die "lineitem #$billpkgnum not found\n";
752 my $invnum = $cust_bill_pkg->invnum;
753 $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
754 $cust_bill{ $invnum}->custnum == $arg{custnum}
755 or die "lineitem #$billpkgnum not found\n";
757 # calculate credit ratio.
758 # (First deduct any existing credits applied to this line item, to avoid
760 my $charged = $cust_bill_pkg->get($setuprecur);
761 my $previously_credited =
762 $cust_bill_pkg->credited( '', '', setuprecur => $setuprecur) || 0;
764 $charged -= $previously_credited;
765 if ($charged < $amount) {
766 $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
769 my $ratio = $amount / $charged;
771 # gather taxes that apply to the selected item
773 qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
775 foreach my $tax_link (
776 qsearch($table, { taxable_billpkgnum => $billpkgnum })
778 my $tax_amount = $tax_link->amount;
779 # deduct existing credits applied to the tax, for the same reason as
781 foreach ($tax_link->cust_credit_bill_pkg) {
782 $tax_amount -= $_->amount;
784 my $tax_credit = sprintf('%.2f', $tax_amount * $ratio);
785 my $pkey = $tax_link->get($tax_link->primary_key);
789 credit => $tax_credit,
791 $taxtotal += $tax_credit;
793 } #foreach cust_bill_pkg_tax_(rate_)?location
795 } # foreach $billpkgnum
798 subtotal => sprintf('%.2f', $subtotal),
799 taxtotal => sprintf('%.2f', $taxtotal),
800 taxlines => \@taxlines,
804 =item credit_lineitems
808 my $error = FS::cust_credit->credit_lineitems(
810 #the lineitems to credit
811 'billpkgnums' => \@billpkgnums,
812 'setuprecurs' => \@setuprecurs,
813 'amounts' => \@amounts,
814 'apply' => 1, #0 leaves the credit unapplied
817 map { $_ => scalar($cgi->param($_)) }
818 #fields('cust_credit')
819 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
825 #maybe i should just be an insert with extra args instead of a class method
826 sub credit_lineitems {
827 my( $class, %arg ) = @_;
828 my $curuser = $FS::CurrentUser::CurrentUser;
830 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
832 my $cust_main = qsearchs({
833 'table' => 'cust_main',
834 'hashref' => { 'custnum' => $arg{custnum} },
835 'extra_sql' => ' AND '. $curuser->agentnums_sql,
836 }) or return 'unknown customer';
839 local $SIG{HUP} = 'IGNORE';
840 local $SIG{INT} = 'IGNORE';
841 local $SIG{QUIT} = 'IGNORE';
842 local $SIG{TERM} = 'IGNORE';
843 local $SIG{TSTP} = 'IGNORE';
844 local $SIG{PIPE} = 'IGNORE';
846 my $oldAutoCommit = $FS::UID::AutoCommit;
847 local $FS::UID::AutoCommit = 0;
850 #my @cust_bill_pkg = qsearch({
851 # 'select' => 'cust_bill_pkg.*',
852 # 'table' => 'cust_bill_pkg',
853 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
854 # ' LEFT JOIN cust_main USING (custnum) ',
855 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
856 # join( ',', @{$arg{billpkgnums}} ). ')',
857 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
862 my $cust_credit = new FS::cust_credit ( {
863 map { $_ => $arg{$_} }
864 #fields('cust_credit')
865 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
867 $error = $cust_credit->insert;
869 $dbh->rollback if $oldAutoCommit;
870 return "Error inserting credit: $error";
873 unless ( $arg{'apply'} ) {
874 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
879 # keys in all of these are invoice numbers
880 my %cust_credit_bill = ();
881 my %cust_bill_pkg = ();
882 my %cust_credit_bill_pkg = ();
883 my %unapplied_payments = (); #invoice numbers, and then billpaynums
885 # determine the tax adjustments
886 my %tax_adjust = $class->calculate_tax_adjustment(%arg);
888 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
889 my $setuprecur = shift @{$arg{setuprecurs}};
890 my $amount = shift @{$arg{amounts}};
892 my $cust_bill_pkg = qsearchs({
893 'table' => 'cust_bill_pkg',
894 'hashref' => { 'billpkgnum' => $billpkgnum },
895 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
896 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
897 }) or die "unknown billpkgnum $billpkgnum";
899 my $invnum = $cust_bill_pkg->invnum;
901 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
903 $cust_credit_bill{$invnum} += $amount;
904 push @{ $cust_credit_bill_pkg{$invnum} },
905 new FS::cust_credit_bill_pkg {
906 'billpkgnum' => $billpkgnum,
907 'amount' => sprintf('%.2f',$amount),
908 'setuprecur' => $setuprecur,
909 'sdate' => $cust_bill_pkg->sdate,
910 'edate' => $cust_bill_pkg->edate,
912 # unapply payments (but not other credits) from this line item
913 foreach my $cust_bill_pay_pkg (
914 $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
916 $error = $cust_bill_pay_pkg->delete;
918 $dbh->rollback if $oldAutoCommit;
919 return "Error unapplying payment: $error";
921 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
922 += $cust_bill_pay_pkg->amount;
926 # do the same for taxes
927 foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
928 my $table = $tax_credit->{table};
929 my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
930 or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
932 my $billpkgnum = $tax_link->billpkgnum;
933 my $cust_bill_pkg = qsearchs({
934 'table' => 'cust_bill_pkg',
935 'hashref' => { 'billpkgnum' => $billpkgnum },
936 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
937 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
938 }) or die "unknown billpkgnum $billpkgnum";
940 my $invnum = $cust_bill_pkg->invnum;
941 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
943 my $amount = $tax_credit->{credit};
944 $cust_credit_bill{$invnum} += $amount;
946 # create a credit application record to the tax line item, earmarked
947 # to the specific cust_bill_pkg_Xlocation
948 push @{ $cust_credit_bill_pkg{$invnum} },
949 new FS::cust_credit_bill_pkg {
950 'billpkgnum' => $billpkgnum,
951 'amount' => sprintf('%.2f', $amount),
952 'setuprecur' => 'setup',
953 $tax_link->primary_key, $tax_credit->{num}
955 # unapply any payments from the tax
956 foreach my $cust_bill_pay_pkg (
957 $cust_bill_pkg->cust_bill_pay_pkg('setup')
959 $error = $cust_bill_pay_pkg->delete;
961 $dbh->rollback if $oldAutoCommit;
962 return "Error unapplying payment: $error";
964 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
965 += $cust_bill_pay_pkg->amount;
970 # now loop through %cust_credit_bill and insert those
973 # (hack to prevent cust_credit_bill_pkg insertion)
974 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
976 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
978 # if we unapplied any payments from line items, also unapply that
979 # amount from the invoice
980 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
981 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
982 or die "broken payment application $billpaynum";
983 my @subapps = $cust_bill_pay->lineitem_applications;
984 $error = $cust_bill_pay->delete; # can't replace
986 my $new_cust_bill_pay = FS::cust_bill_pay->new({
987 $cust_bill_pay->hash,
989 amount => sprintf('%.2f',
990 $cust_bill_pay->amount
991 - $unapplied_payments{$invnum}{$billpaynum}),
994 if ( $new_cust_bill_pay->amount > 0 ) {
995 $error ||= $new_cust_bill_pay->insert;
996 # Also reapply it to everything it was applied to before.
997 # Note that we've already deleted cust_bill_pay_pkg records for the
998 # items we're crediting, so they aren't on this list.
999 foreach my $cust_bill_pay_pkg (@subapps) {
1000 $cust_bill_pay_pkg->billpaypkgnum('');
1001 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1002 $error ||= $cust_bill_pay_pkg->insert;
1006 $dbh->rollback if $oldAutoCommit;
1007 return "Error unapplying payment: $error";
1010 #insert cust_credit_bill
1012 my $cust_credit_bill = new FS::cust_credit_bill {
1013 'crednum' => $cust_credit->crednum,
1014 'invnum' => $invnum,
1015 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1017 $error = $cust_credit_bill->insert;
1019 $dbh->rollback if $oldAutoCommit;
1020 return "Error applying credit of $cust_credit_bill{$invnum} ".
1021 " to invoice $invnum: $error";
1024 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1025 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1026 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1027 $error = $cust_credit_bill_pkg->insert;
1029 $dbh->rollback if $oldAutoCommit;
1030 return "Error applying credit to line item: $error";
1036 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1047 =item process_batch_import
1051 use List::Util qw( min );
1053 use FS::cust_credit_bill;
1054 sub process_batch_import {
1057 my $opt = { 'table' => 'cust_credit',
1058 'params' => [ '_date', 'credbatch' ],
1059 'formats' => { 'simple' =>
1060 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1063 'postinsert_callback' => sub {
1064 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1066 if ( $cust_credit->invnum ) {
1068 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1069 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1071 my $cust_credit_bill = new FS::cust_credit_bill ( {
1072 'crednum' => $cust_credit->crednum,
1073 'invnum' => $cust_bill->invnum,
1074 'amount' => $amount,
1076 my $error = $cust_credit_bill->insert;
1077 return '' unless $error;
1081 #apply_payments_and_credits ?
1082 $cust_credit->cust_main->apply_credits;
1089 FS::Record::process_batch_import( $job, $opt, @_ );
1097 The delete method. The replace method.
1099 B<credited> and B<credited_sql> are now called B<unapplied> and
1100 B<unapplied_sql>. The old method names should start to give warnings.
1104 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1105 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base