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->config('invoice_from_name', $self->cust_main->agentnum) ?
286 $conf->config('invoice_from_name', $self->cust_main->agentnum) . ' <' .
287 $conf->config('invoice_from', $self->cust_main->agentnum) . '>' :
288 $conf->config('invoice_from', $self->cust_main->agentnum),
289 #invoice_from??? well as good as any
290 'to' => $conf->config('deletecredits'),
291 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
293 "This is an automatic message from your Freeside installation\n",
294 "informing you that the following credit has been deleted:\n",
296 'crednum: '. $self->crednum. "\n",
297 'custnum: '. $self->custnum.
298 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
299 'amount: $'. sprintf("%.2f", $self->amount). "\n",
300 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
301 'reason: '. $self->reason. "\n",
306 $dbh->rollback if $oldAutoCommit;
307 return "can't send credit deletion notification: $error";
312 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
318 =item replace [ OLD_RECORD ]
320 You can, but probably shouldn't modify credits...
322 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
323 supplied, replaces this record. If there is an error, returns the error,
324 otherwise returns false.
330 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
331 $self->SUPER::replace(@_);
336 Checks all fields to make sure this is a valid credit. If there is an error,
337 returns the error, otherwise returns false. Called by the insert and replace
345 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
348 $self->ut_numbern('crednum')
349 || $self->ut_number('custnum')
350 || $self->ut_numbern('_date')
351 || $self->ut_money('amount')
352 || $self->ut_alphan('otaker')
353 || $self->ut_textn('reason')
354 || $self->ut_textn('addlinfo')
355 || $self->ut_enum('closed', [ '', 'Y' ])
356 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
357 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
358 || $self->ut_foreign_keyn('commission_agentnum', 'agent', 'agentnum')
359 || $self->ut_foreign_keyn('commission_salesnum', 'sales', 'salesnum')
360 || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
362 return $error if $error;
364 my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
365 $error = $self->$method('reasonnum', 'reason', 'reasonnum');
366 return $error if $error;
368 return "amount must be > 0 " if $self->amount <= 0;
370 return "amount must be greater or equal to amount applied"
371 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
373 return "Unknown customer"
374 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
376 $self->_date(time) unless $self->_date;
381 =item void [ REASON ]
383 Voids this credit: deletes the credit and all associated applications and
384 adds a record of the voided credit to the cust_credit_void table.
388 # yes, false laziness with cust_pay and cust_bill
389 # but frankly I don't have time to fix it now
395 local $SIG{HUP} = 'IGNORE';
396 local $SIG{INT} = 'IGNORE';
397 local $SIG{QUIT} = 'IGNORE';
398 local $SIG{TERM} = 'IGNORE';
399 local $SIG{TSTP} = 'IGNORE';
400 local $SIG{PIPE} = 'IGNORE';
402 my $oldAutoCommit = $FS::UID::AutoCommit;
403 local $FS::UID::AutoCommit = 0;
406 my $cust_credit_void = new FS::cust_credit_void ( {
407 map { $_ => $self->get($_) } $self->fields
409 $cust_credit_void->set('void_reason', $reason);
410 my $error = $cust_credit_void->insert;
412 $dbh->rollback if $oldAutoCommit;
416 $error = $self->delete(void => 1); # suppress deletecredits warning
418 $dbh->rollback if $oldAutoCommit;
422 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
428 =item cust_credit_refund
430 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
434 sub cust_credit_refund {
436 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
437 sort { $a->_date <=> $b->_date }
438 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
442 =item cust_credit_bill
444 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
449 sub cust_credit_bill {
451 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
452 sort { $a->_date <=> $b->_date }
453 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
459 Returns the amount of this credit that is still unapplied/outstanding;
460 amount minus all refund applications (see L<FS::cust_credit_refund>) and
461 applications to invoices (see L<FS::cust_credit_bill>).
467 my $amount = $self->amount;
468 $amount -= $_->amount foreach ( $self->cust_credit_refund );
469 $amount -= $_->amount foreach ( $self->cust_credit_bill );
470 sprintf( "%.2f", $amount );
475 Deprecated name for the unapplied method.
481 #carp "cust_credit->credited deprecated; use ->unapplied";
482 $self->unapplied(@_);
487 Returns the customer (see L<FS::cust_main>) for this credit.
493 # Used by FS::Upgrade to migrate to a new database.
495 sub _upgrade_data { # class method
496 my ($class, %opts) = @_;
498 warn "$me upgrading $class\n" if $DEBUG;
500 $class->_upgrade_reasonnum(%opts);
502 if (defined dbdef->table($class->table)->column('reason')) {
504 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
506 foreach ( keys %reasontype_map ) {
507 unless ($conf->config($_)) { # hmmmm
508 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
509 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
510 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
511 my $reason_type = qsearchs( 'reason_type', $hashref );
512 unless ($reason_type) {
513 $reason_type = new FS::reason_type( $hashref );
514 my $error = $reason_type->insert();
515 die "$class had error inserting FS::reason_type into database: $error\n"
518 $conf->set($_, $reason_type->typenum);
522 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
524 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
525 my $reason_type = qsearchs( 'reason_type', $hashref );
526 unless ($reason_type) {
527 $reason_type = new FS::reason_type( $hashref );
528 my $error = $reason_type->insert();
529 die "$class had error inserting FS::reason_type into database: $error\n"
533 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
534 foreach my $plan ( @plans ) {
535 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
536 unless ($pkg->option('reason_type', 1) ) {
537 my $plandata = $pkg->plandata.
538 "reason_type=". $reason_type->typenum. "\n";
539 $pkg->plandata($plandata);
541 $pkg->replace( undef,
542 'pkg_svc' => { map { $_->svcpart => $_->quantity }
545 'primary_svc' => $pkg->svcpart,
547 die "failed setting reason_type option: $error"
554 local($otaker_upgrade_kludge) = 1;
555 local($ignore_empty_reasonnum) = 1;
556 $class->_upgrade_otaker(%opts);
558 if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
559 and !$conf->exists('enable_taxproducts') ) {
560 # RT#25458: fix credit line item applications that should refer to a
561 # specific tax allocation
562 my @cust_credit_bill_pkg = qsearch({
563 table => 'cust_credit_bill_pkg',
564 select => 'cust_credit_bill_pkg.*',
565 addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
567 'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
568 'AND cust_bill_pkg.pkgnum = 0', # is a tax
572 foreach (@cust_credit_bill_pkg) {
573 my $billpkgnum = $_->billpkgnum;
574 $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
575 $credits{$billpkgnum} ||= [];
576 push @{ $credits{$billpkgnum} }, $_;
578 TAX_ITEM: foreach my $tax_item (values %tax_items) {
579 my $billpkgnum = $tax_item->billpkgnum;
580 # get all pkg/location/taxrate allocations of this tax line item
581 my @allocations = sort {$b->amount <=> $a->amount}
582 qsearch('cust_bill_pkg_tax_location', {
583 billpkgnum => $billpkgnum
585 # and these are all credit applications to it
586 my @credits = sort {$b->amount <=> $a->amount}
587 @{ $credits{$billpkgnum} };
588 my $c = shift @credits;
589 my $a = shift @allocations; # we will NOT modify these
591 if ( abs($c->amount - $a->amount) < 0.005 ) {
592 # by far the most common case: the tax line item is for a single
593 # tax, so we just fill in the billpkgtaxlocationnum
594 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
595 my $error = $c->replace;
597 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
601 $a = shift @allocations;
602 } elsif ( $c->amount > $a->amount ) {
603 # fairly common: the tax line contains tax for multiple packages
604 # (or multiple taxes) but the credit isn't divided up
605 my $new_link = FS::cust_credit_bill_pkg->new({
606 creditbillnum => $c->creditbillnum,
607 billpkgnum => $c->billpkgnum,
608 billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
609 amount => $a->amount,
610 setuprecur => 'setup',
612 my $error = $new_link->insert;
614 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
617 $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
618 $a = shift @allocations;
619 } elsif ( $c->amount < 0.005 ) {
620 # also fairly common; we can delete these with no harm
621 my $error = $c->delete;
622 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
624 } elsif ( $c->amount < $a->amount ) {
625 # should never happen, but if it does, handle it gracefully
626 $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
627 my $error = $c->replace;
629 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
632 $a->set(amount => $a->amount - $c->amount);
637 if ( $c->amount < 0.005 ) {
638 my $error = $c->delete;
639 warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
640 } elsif ( $c->modified ) {
641 # then we've allocated part of it, so reduce the nonspecific
642 # application by that much
643 my $error = $c->replace;
644 warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
646 # else there are probably no allocations, i.e. this is a pre-3.x
647 # record that was never migrated over, so leave it alone
649 } # foreach $tax_item
650 FS::upgrade_journal->set_done('cust_credit__tax_link');
662 Returns an SQL fragment to retreive the unapplied amount.
667 my ($class, $start, $end) = @_;
669 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
670 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
671 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
672 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
676 ( SELECT SUM(amount) FROM cust_credit_refund
677 WHERE cust_credit.crednum = cust_credit_refund.crednum
678 $refund_start $refund_end )
682 ( SELECT SUM(amount) FROM cust_credit_bill
683 WHERE cust_credit.crednum = cust_credit_bill.crednum
684 $bill_start $bill_end )
693 Deprecated name for the unapplied_sql method.
700 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
702 #$class->unapplied_sql(@_);
706 =item credit_lineitems
710 my $error = FS::cust_credit->credit_lineitems(
712 #the lineitems to credit
713 'billpkgnums' => \@billpkgnums,
714 'setuprecurs' => \@setuprecurs,
715 'amounts' => \@amounts,
716 'apply' => 1, #0 leaves the credit unapplied
719 map { $_ => scalar($cgi->param($_)) }
720 #fields('cust_credit')
721 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
727 #maybe i should just be an insert with extra args instead of a class method
728 sub credit_lineitems {
729 my( $class, %arg ) = @_;
730 my $curuser = $FS::CurrentUser::CurrentUser;
732 #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
734 my $cust_main = qsearchs({
735 'table' => 'cust_main',
736 'hashref' => { 'custnum' => $arg{custnum} },
737 'extra_sql' => ' AND '. $curuser->agentnums_sql,
738 }) or return 'unknown customer';
741 local $SIG{HUP} = 'IGNORE';
742 local $SIG{INT} = 'IGNORE';
743 local $SIG{QUIT} = 'IGNORE';
744 local $SIG{TERM} = 'IGNORE';
745 local $SIG{TSTP} = 'IGNORE';
746 local $SIG{PIPE} = 'IGNORE';
748 my $oldAutoCommit = $FS::UID::AutoCommit;
749 local $FS::UID::AutoCommit = 0;
752 #my @cust_bill_pkg = qsearch({
753 # 'select' => 'cust_bill_pkg.*',
754 # 'table' => 'cust_bill_pkg',
755 # 'addl_from' => ' LEFT JOIN cust_bill USING (invnum) '.
756 # ' LEFT JOIN cust_main USING (custnum) ',
757 # 'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
758 # join( ',', @{$arg{billpkgnums}} ). ')',
759 # 'order_by' => 'ORDER BY invnum ASC, billpkgnum ASC',
764 my $cust_credit = new FS::cust_credit ( {
765 map { $_ => $arg{$_} }
766 #fields('cust_credit')
767 qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
769 $error = $cust_credit->insert;
771 $dbh->rollback if $oldAutoCommit;
772 return "Error inserting credit: $error";
775 unless ( $arg{'apply'} ) {
776 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
781 # keys in all of these are invoice numbers
782 my %cust_credit_bill = ();
783 my %cust_bill_pkg = ();
784 my %cust_credit_bill_pkg = ();
785 my %taxlisthash = ();
786 my %unapplied_payments = (); #invoice numbers, and then billpaynums
787 foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
788 my $setuprecur = shift @{$arg{setuprecurs}};
789 my $amount = shift @{$arg{amounts}};
791 my $cust_bill_pkg = qsearchs({
792 'table' => 'cust_bill_pkg',
793 'hashref' => { 'billpkgnum' => $billpkgnum },
794 'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
795 'extra_sql' => 'AND custnum = '. $cust_main->custnum,
796 }) or die "unknown billpkgnum $billpkgnum";
798 my $invnum = $cust_bill_pkg->invnum;
800 if ( $setuprecur eq 'setup' ) {
801 $cust_bill_pkg->setup($amount);
802 $cust_bill_pkg->recur(0);
803 $cust_bill_pkg->unitrecur(0);
804 $cust_bill_pkg->type('');
806 $setuprecur = 'recur'; #in case its a usage classnum?
807 $cust_bill_pkg->recur($amount);
808 $cust_bill_pkg->setup(0);
809 $cust_bill_pkg->unitsetup(0);
812 push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
814 #unapply any payments applied to this line item (other credits too?)
815 foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
816 $error = $cust_bill_pay_pkg->delete;
818 $dbh->rollback if $oldAutoCommit;
819 return "Error unapplying payment: $error";
821 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
822 += $cust_bill_pay_pkg->amount;
825 #$subtotal += $amount;
826 $cust_credit_bill{$invnum} += $amount;
827 push @{ $cust_credit_bill_pkg{$invnum} },
828 new FS::cust_credit_bill_pkg {
829 'billpkgnum' => $cust_bill_pkg->billpkgnum,
830 'amount' => sprintf('%.2f',$amount),
831 'setuprecur' => $setuprecur,
832 'sdate' => $cust_bill_pkg->sdate,
833 'edate' => $cust_bill_pkg->edate,
836 # recalculate taxes with new amounts
837 $taxlisthash{$invnum} ||= {};
838 if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
839 $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
840 } # otherwise the item itself is a tax, and assume the caller knows
845 # now loop through %cust_credit_bill and insert those
848 # (hack to prevent cust_credit_bill_pkg insertion)
849 local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
851 foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
853 my $arrayref_or_error =
854 $cust_main->calculate_taxes(
855 $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
856 $taxlisthash{$invnum}, # list of tax-item bindings
857 $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
860 unless ( ref( $arrayref_or_error ) ) {
861 $dbh->rollback if $oldAutoCommit;
862 return "Error calculating taxes: $arrayref_or_error";
865 my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
868 foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
869 my $billpkgnum = $cust_bill_pkg->billpkgnum;
870 my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
871 # gather up existing tax links (we need their billpkgtaxlocationnums)
872 my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
873 qsearch('cust_bill_pkg_tax_rate_location', \%hash);
875 foreach ( @tax_links ) {
876 $tax_links{$_->billpkgnum} ||= {};
877 $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
881 foreach my $taxline ( @$arrayref_or_error ) {
883 my $amount = $taxline->setup;
885 # find equivalent tax line item on the existing invoice
886 my $tax_item = qsearchs('cust_bill_pkg', {
889 'itemdesc' => $taxline->desc,
892 # or should we just exit if this happens?
893 $cust_credit->set('amount',
894 sprintf('%.2f', $cust_credit->get('amount') - $amount)
896 my $error = $cust_credit->replace;
898 $dbh->rollback if $oldAutoCommit;
899 return "error correcting credit for missing tax line: $error";
903 # but in the new era, we no longer have the problem of uniquely
904 # identifying the tax_Xlocation record. The billpkgnums of the
905 # tax and the taxed item are known.
907 ( @{ $taxline->get('cust_bill_pkg_tax_location') },
908 @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
910 # the existing tax_Xlocation object
912 $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
914 next if !$old_loc; # apply the leftover amount nonspecifically
916 #support partial credits: use $amount if smaller
917 # (so just distribute to the first location? perhaps should
919 my $loc_amount = min( $amount, $new_loc->amount);
921 $amount -= $loc_amount;
923 $cust_credit_bill{$invnum} += $loc_amount;
924 push @{ $cust_credit_bill_pkg{$invnum} },
925 new FS::cust_credit_bill_pkg {
926 'billpkgnum' => $tax_item->billpkgnum,
927 'amount' => $loc_amount,
928 'setuprecur' => 'setup',
929 'billpkgtaxlocationnum' => $old_loc->billpkgtaxlocationnum,
930 'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
933 } #foreach my $new_loc
935 # we still have to deal with the possibility that the tax links don't
936 # cover the whole amount of tax because of an incomplete upgrade...
937 if ($amount > 0.005) {
938 $cust_credit_bill{$invnum} += $amount;
939 push @{ $cust_credit_bill_pkg{$invnum} },
940 new FS::cust_credit_bill_pkg {
941 'billpkgnum' => $tax_item->billpkgnum,
942 'amount' => sprintf('%.2f', $amount),
943 'setuprecur' => 'setup',
948 #unapply any payments applied to the tax
949 foreach my $cust_bill_pay_pkg
950 ( $tax_item->cust_bill_pay_pkg('setup') )
952 $error = $cust_bill_pay_pkg->delete;
954 $dbh->rollback if $oldAutoCommit;
955 return "Error unapplying payment: $error";
957 $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
958 += $cust_bill_pay_pkg->amount;
962 # if we unapplied any payments from line items, also unapply that
963 # amount from the invoice
964 foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
965 my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
966 or die "broken payment application $billpaynum";
967 my @subapps = $cust_bill_pay->lineitem_applications;
968 $error = $cust_bill_pay->delete; # can't replace
970 my $new_cust_bill_pay = FS::cust_bill_pay->new({
971 $cust_bill_pay->hash,
973 amount => sprintf('%.2f',
974 $cust_bill_pay->amount
975 - $unapplied_payments{$invnum}{$billpaynum}),
978 if ( $new_cust_bill_pay->amount > 0 ) {
979 $error ||= $new_cust_bill_pay->insert;
980 # Also reapply it to everything it was applied to before.
981 # Note that we've already deleted cust_bill_pay_pkg records for the
982 # items we're crediting, so they aren't on this list.
983 foreach my $cust_bill_pay_pkg (@subapps) {
984 $cust_bill_pay_pkg->billpaypkgnum('');
985 $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
986 $error ||= $cust_bill_pay_pkg->insert;
990 $dbh->rollback if $oldAutoCommit;
991 return "Error unapplying payment: $error";
994 #insert cust_credit_bill
996 my $cust_credit_bill = new FS::cust_credit_bill {
997 'crednum' => $cust_credit->crednum,
999 'amount' => sprintf('%.2f', $cust_credit_bill{$invnum}),
1001 $error = $cust_credit_bill->insert;
1003 $dbh->rollback if $oldAutoCommit;
1004 return "Error applying credit of $cust_credit_bill{$invnum} ".
1005 " to invoice $invnum: $error";
1008 #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1009 foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1010 $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1011 $error = $cust_credit_bill_pkg->insert;
1013 $dbh->rollback if $oldAutoCommit;
1014 return "Error applying credit to line item: $error";
1020 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1031 =item process_batch_import
1035 use List::Util qw( min );
1037 use FS::cust_credit_bill;
1038 sub process_batch_import {
1041 my $opt = { 'table' => 'cust_credit',
1042 'params' => [ '_date', 'credbatch' ],
1043 'formats' => { 'simple' =>
1044 [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1047 'postinsert_callback' => sub {
1048 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1050 if ( $cust_credit->invnum ) {
1052 my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1053 my $amount = min( $cust_credit->credited, $cust_bill->owed );
1055 my $cust_credit_bill = new FS::cust_credit_bill ( {
1056 'crednum' => $cust_credit->crednum,
1057 'invnum' => $cust_bill->invnum,
1058 'amount' => $amount,
1060 my $error = $cust_credit_bill->insert;
1061 return '' unless $error;
1065 #apply_payments_and_credits ?
1066 $cust_credit->cust_main->apply_credits;
1073 FS::Record::process_batch_import( $job, $opt, @_ );
1081 The delete method. The replace method.
1083 B<credited> and B<credited_sql> are now called B<unapplied> and
1084 B<unapplied_sql>. The old method names should start to give warnings.
1088 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1089 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base