1 package FS::cust_main::Billing;
4 use vars qw( $conf $DEBUG $me );
7 use List::Util qw( min );
9 use FS::Record qw( qsearch qsearchs dbdef );
10 use FS::Misc::DateTime qw( day_end );
12 use FS::cust_bill_pkg;
13 use FS::cust_bill_pkg_display;
14 use FS::cust_bill_pay;
15 use FS::cust_credit_bill;
16 use FS::cust_tax_adjustment;
18 use FS::tax_rate_location;
19 use FS::cust_bill_pkg_tax_location;
20 use FS::cust_bill_pkg_tax_rate_location;
22 use FS::part_event_condition;
25 # 1 is mostly method/subroutine entry and options
26 # 2 traces progress of some operations
27 # 3 is even more information including possibly sensitive data
29 $me = '[FS::cust_main::Billing]';
31 install_callback FS::UID sub {
33 #yes, need it for stuff below (prolly should be cached)
38 FS::cust_main::Billing - Billing mixin for cust_main
44 These methods are available on FS::cust_main objects.
50 =item bill_and_collect
52 Cancels and suspends any packages due, generates bills, applies payments and
53 credits, and applies collection events to run cards, send bills and notices,
56 By default, warns on errors and continues with the next operation (but see the
59 Options are passed as name-value pairs. Currently available options are:
65 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
69 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
73 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
77 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
81 If set true, re-charges setup fees.
85 If set any errors prevent subsequent operations from continusing. If set
86 specifically to "return", returns the error (or false, if there is no error).
87 Any other true value causes errors to die.
91 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
95 Optional FS::queue entry to receive status updates.
99 Options are passed to the B<bill> and B<collect> methods verbatim, so all
100 options of those methods are also available.
104 sub bill_and_collect {
105 my( $self, %options ) = @_;
109 #$options{actual_time} not $options{time} because freeside-daily -d is for
110 #pre-printing invoices
112 $options{'actual_time'} ||= time;
113 my $job = $options{'job'};
115 $job->update_statustext('0,cleaning expired packages') if $job;
116 $error = $self->cancel_expired_pkgs( day_end( $options{actual_time} ) );
118 $error = "Error expiring custnum ". $self->custnum. ": $error";
119 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
120 elsif ( $options{fatal} ) { die $error; }
121 else { warn $error; }
124 $error = $self->suspend_adjourned_pkgs( day_end( $options{actual_time} ) );
126 $error = "Error adjourning custnum ". $self->custnum. ": $error";
127 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
128 elsif ( $options{fatal} ) { die $error; }
129 else { warn $error; }
132 $error = $self->unsuspend_resumed_pkgs( day_end( $options{actual_time} ) );
134 $error = "Error resuming custnum ".$self->custnum. ": $error";
135 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
136 elsif ( $options{fatal} ) { die $error; }
137 else { warn $error; }
140 $job->update_statustext('20,billing packages') if $job;
141 $error = $self->bill( %options );
143 $error = "Error billing custnum ". $self->custnum. ": $error";
144 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
145 elsif ( $options{fatal} ) { die $error; }
146 else { warn $error; }
149 $job->update_statustext('50,applying payments and credits') if $job;
150 $error = $self->apply_payments_and_credits;
152 $error = "Error applying custnum ". $self->custnum. ": $error";
153 if ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
154 elsif ( $options{fatal} ) { die $error; }
155 else { warn $error; }
158 $job->update_statustext('70,running collection events') if $job;
159 unless ( $conf->exists('cancelled_cust-noevents')
160 && ! $self->num_ncancelled_pkgs
162 $error = $self->collect( %options );
164 $error = "Error collecting custnum ". $self->custnum. ": $error";
165 if ($options{fatal} && $options{fatal} eq 'return') { return $error; }
166 elsif ($options{fatal} ) { die $error; }
167 else { warn $error; }
170 $job->update_statustext('100,finished') if $job;
176 sub cancel_expired_pkgs {
177 my ( $self, $time, %options ) = @_;
179 my @cancel_pkgs = $self->ncancelled_pkgs( {
180 'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
185 foreach my $cust_pkg ( @cancel_pkgs ) {
186 my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
187 my $error = $cust_pkg->cancel($cpr ? ( 'reason' => $cpr->reasonnum,
188 'reason_otaker' => $cpr->otaker,
193 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
196 join(' / ', @errors);
200 sub suspend_adjourned_pkgs {
201 my ( $self, $time, %options ) = @_;
203 my @susp_pkgs = $self->ncancelled_pkgs( {
205 " AND ( susp IS NULL OR susp = 0 )
206 AND ( ( bill IS NOT NULL AND bill != 0 AND bill < $time )
207 OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
212 #only because there's no SQL test for is_prepaid :/
214 grep { ( $_->part_pkg->is_prepaid
219 && $_->adjourn <= $time
227 foreach my $cust_pkg ( @susp_pkgs ) {
228 my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
229 if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
230 my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
231 'reason_otaker' => $cpr->otaker
235 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
238 join(' / ', @errors);
242 sub unsuspend_resumed_pkgs {
243 my ( $self, $time, %options ) = @_;
245 my @unsusp_pkgs = $self->ncancelled_pkgs( {
246 'extra_sql' => " AND resume IS NOT NULL AND resume > 0 AND resume <= $time "
251 foreach my $cust_pkg ( @unsusp_pkgs ) {
252 my $error = $cust_pkg->unsuspend( 'time' => $time );
253 push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
256 join(' / ', @errors);
262 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
263 conjunction with the collect method by calling B<bill_and_collect>.
265 If there is an error, returns the error, otherwise returns false.
267 Options are passed as name-value pairs. Currently available options are:
273 If set true, re-charges setup fees.
277 If set true then only bill recurring charges, not setup, usage, one time
282 If set, then override the normal frequency and look for a part_pkg_discount
283 to take at that frequency. This is appropriate only when the normal
284 frequency for all packages is monthly, and is an error otherwise. Use
285 C<pkg_list> to limit the set of packages included in billing.
289 Bills the customer as if it were that time. Specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions. For example:
293 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
297 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
299 $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
303 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
307 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices. Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
311 This boolean value informs the us that the package is being cancelled. This
312 typically might mean not charging the normal recurring fee but only usage
313 fees since the last billing. Setup charges may be charged. Not all package
314 plans support this feature (they tend to charge 0).
318 Prevent the resetting of usage limits during this call.
322 Do not save the generated bill in the database. Useful with return_bill
326 A list reference on which the generated bill(s) will be returned.
330 Optional terms to be printed on this invoice. Otherwise, customer-specific
331 terms or the default terms are used.
338 my( $self, %options ) = @_;
340 return '' if $self->payby eq 'COMP';
342 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
344 warn "$me bill customer ". $self->custnum. "\n"
347 my $time = $options{'time'} || time;
348 my $invoice_time = $options{'invoice_time'} || $time;
350 $options{'not_pkgpart'} ||= {};
351 $options{'not_pkgpart'} = { map { $_ => 1 }
352 split(/\s*,\s*/, $options{'not_pkgpart'})
354 unless ref($options{'not_pkgpart'});
356 local $SIG{HUP} = 'IGNORE';
357 local $SIG{INT} = 'IGNORE';
358 local $SIG{QUIT} = 'IGNORE';
359 local $SIG{TERM} = 'IGNORE';
360 local $SIG{TSTP} = 'IGNORE';
361 local $SIG{PIPE} = 'IGNORE';
363 my $oldAutoCommit = $FS::UID::AutoCommit;
364 local $FS::UID::AutoCommit = 0;
367 warn "$me acquiring lock on customer ". $self->custnum. "\n"
370 $self->select_for_update; #mutex
372 warn "$me running pre-bill events for customer ". $self->custnum. "\n"
375 my $error = $self->do_cust_event(
376 'debug' => ( $options{'debug'} || 0 ),
377 'time' => $invoice_time,
378 'check_freq' => $options{'check_freq'},
379 'stage' => 'pre-bill',
381 unless $options{no_commit};
383 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
387 warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
390 #keep auto-charge and non-auto-charge line items separate
391 my @passes = ( '', 'no_auto' );
393 my %cust_bill_pkg = map { $_ => [] } @passes;
396 # find the packages which are due for billing, find out how much they are
397 # & generate invoice database.
400 my %total_setup = map { my $z = 0; $_ => \$z; } @passes;
401 my %total_recur = map { my $z = 0; $_ => \$z; } @passes;
403 my %taxlisthash = map { $_ => {} } @passes;
405 my @precommit_hooks = ();
407 $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ]; #param checks?
408 foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
410 next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
412 warn " bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG;
414 #? to avoid use of uninitialized value errors... ?
415 $cust_pkg->setfield('bill', '')
416 unless defined($cust_pkg->bill);
418 #my $part_pkg = $cust_pkg->part_pkg;
420 my $real_pkgpart = $cust_pkg->pkgpart;
421 my %hash = $cust_pkg->hash;
423 # we could implement this bit as FS::part_pkg::has_hidden, but we already
424 # suffer from performance issues
425 $options{has_hidden} = 0;
426 my @part_pkg = $cust_pkg->part_pkg->self_and_bill_linked;
427 $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
429 foreach my $part_pkg ( @part_pkg ) {
431 $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
433 my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
435 my $next_bill = $cust_pkg->getfield('bill') || 0;
437 # let this run once if this is the last bill upon cancellation
438 while ( $next_bill <= $time or $options{cancel} ) {
440 $self->_make_lines( 'part_pkg' => $part_pkg,
441 'cust_pkg' => $cust_pkg,
442 'precommit_hooks' => \@precommit_hooks,
443 'line_items' => $cust_bill_pkg{$pass},
444 'setup' => $total_setup{$pass},
445 'recur' => $total_recur{$pass},
446 'tax_matrix' => $taxlisthash{$pass},
448 'real_pkgpart' => $real_pkgpart,
449 'options' => \%options,
452 # Stop if anything goes wrong
455 # or if we're not incrementing the bill date.
456 last if ($cust_pkg->getfield('bill') || 0) == $next_bill;
458 # or if we're letting it run only once
459 last if $options{cancel};
461 $next_bill = $cust_pkg->getfield('bill') || 0;
463 #stop if -o was passed to freeside-daily
464 last if $options{'one_recur'};
467 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
471 } #foreach my $part_pkg
473 } #foreach my $cust_pkg
475 #if the customer isn't on an automatic payby, everything can go on a single
477 #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
478 #merge everything into one list
481 foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
483 my @cust_bill_pkg = _omit_zero_value_bundles(@{ $cust_bill_pkg{$pass} });
485 next unless @cust_bill_pkg; #don't create an invoice w/o line items
487 warn "$me billing pass $pass\n"
488 #.Dumper(\@cust_bill_pkg)."\n"
491 if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
492 !$conf->exists('postal_invoice-recurring_only')
496 my $postal_pkg = $self->charge_postal_fee();
497 if ( $postal_pkg && !ref( $postal_pkg ) ) {
499 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
500 return "can't charge postal invoice fee for customer ".
501 $self->custnum. ": $postal_pkg";
503 } elsif ( $postal_pkg ) {
505 my $real_pkgpart = $postal_pkg->pkgpart;
506 # we could implement this bit as FS::part_pkg::has_hidden, but we already
507 # suffer from performance issues
508 $options{has_hidden} = 0;
509 my @part_pkg = $postal_pkg->part_pkg->self_and_bill_linked;
510 $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
512 foreach my $part_pkg ( @part_pkg ) {
513 my %postal_options = %options;
514 delete $postal_options{cancel};
516 $self->_make_lines( 'part_pkg' => $part_pkg,
517 'cust_pkg' => $postal_pkg,
518 'precommit_hooks' => \@precommit_hooks,
519 'line_items' => \@cust_bill_pkg,
520 'setup' => $total_setup{$pass},
521 'recur' => $total_recur{$pass},
522 'tax_matrix' => $taxlisthash{$pass},
524 'real_pkgpart' => $real_pkgpart,
525 'options' => \%postal_options,
528 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
533 # it's silly to have a zero value postal_pkg, but....
534 @cust_bill_pkg = _omit_zero_value_bundles(@cust_bill_pkg);
540 my $listref_or_error =
541 $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
543 unless ( ref( $listref_or_error ) ) {
544 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
545 return $listref_or_error;
548 foreach my $taxline ( @$listref_or_error ) {
549 ${ $total_setup{$pass} } =
550 sprintf('%.2f', ${ $total_setup{$pass} } + $taxline->setup );
551 push @cust_bill_pkg, $taxline;
555 warn "adding tax adjustments...\n" if $DEBUG > 2;
556 foreach my $cust_tax_adjustment (
557 qsearch('cust_tax_adjustment', { 'custnum' => $self->custnum,
563 my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
565 my $itemdesc = $cust_tax_adjustment->taxname;
566 $itemdesc = '' if $itemdesc eq 'Tax';
568 push @cust_bill_pkg, new FS::cust_bill_pkg {
574 'itemdesc' => $itemdesc,
575 'itemcomment' => $cust_tax_adjustment->comment,
576 'cust_tax_adjustment' => $cust_tax_adjustment,
577 #'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
582 my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
584 my @cust_bill = $self->cust_bill;
585 my $balance = $self->balance;
586 my $previous_balance = scalar(@cust_bill)
587 ? ( $cust_bill[$#cust_bill]->billing_balance || 0 )
590 $previous_balance += $cust_bill[$#cust_bill]->charged
591 if scalar(@cust_bill);
592 #my $balance_adjustments =
593 # sprintf('%.2f', $balance - $prior_prior_balance - $prior_charged);
595 warn "creating the new invoice\n" if $DEBUG;
596 #create the new invoice
597 my $cust_bill = new FS::cust_bill ( {
598 'custnum' => $self->custnum,
599 '_date' => $invoice_time,
600 'charged' => $charged,
601 'billing_balance' => $balance,
602 'previous_balance' => $previous_balance,
603 'invoice_terms' => $options{'invoice_terms'},
604 'cust_bill_pkg' => \@cust_bill_pkg,
606 $error = $cust_bill->insert unless $options{no_commit};
608 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
609 return "can't create invoice for customer #". $self->custnum. ": $error";
611 push @{$options{return_bill}}, $cust_bill if $options{return_bill};
613 } #foreach my $pass ( keys %cust_bill_pkg )
615 foreach my $hook ( @precommit_hooks ) {
618 } unless $options{no_commit};
620 $dbh->rollback if $oldAutoCommit && !$options{no_commit};
621 return "$@ running precommit hook $hook\n";
625 $dbh->commit or die $dbh->errstr if $oldAutoCommit && !$options{no_commit};
630 #discard bundled packages of 0 value
631 sub _omit_zero_value_bundles {
634 my @cust_bill_pkg = ();
635 my @cust_bill_pkg_bundle = ();
637 my $discount_show_always = 0;
639 foreach my $cust_bill_pkg ( @in ) {
641 $discount_show_always = ($cust_bill_pkg->get('discounts')
642 && scalar(@{$cust_bill_pkg->get('discounts')})
643 && $conf->exists('discount-show-always'));
645 warn " pkgnum ". $cust_bill_pkg->pkgnum. " sum $sum, ".
646 "setup_show_zero ". $cust_bill_pkg->setup_show_zero.
647 "recur_show_zero ". $cust_bill_pkg->recur_show_zero. "\n"
650 if (scalar(@cust_bill_pkg_bundle) && !$cust_bill_pkg->pkgpart_override) {
651 push @cust_bill_pkg, @cust_bill_pkg_bundle
653 || ($sum == 0 && ( $discount_show_always
654 || grep {$_->recur_show_zero || $_->setup_show_zero}
655 @cust_bill_pkg_bundle
658 @cust_bill_pkg_bundle = ();
662 $sum += $cust_bill_pkg->setup + $cust_bill_pkg->recur;
663 push @cust_bill_pkg_bundle, $cust_bill_pkg;
667 push @cust_bill_pkg, @cust_bill_pkg_bundle
669 || ($sum == 0 && ( $discount_show_always
670 || grep {$_->recur_show_zero || $_->setup_show_zero}
671 @cust_bill_pkg_bundle
675 warn " _omit_zero_value_bundles: ". scalar(@in).
676 '->'. scalar(@cust_bill_pkg). "\n" #. Dumper(@cust_bill_pkg). "\n"
683 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
685 This is a weird one. Perhaps it should not even be exposed.
687 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
688 Usually used internally by bill method B<bill>.
690 If there is an error, returns the error, otherwise returns reference to a
691 list of line items suitable for insertion.
697 An array ref of the line items being billed.
701 A strange beast. The keys to this hash are internal identifiers consisting
702 of the name of the tax object type, a space, and its unique identifier ( e.g.
703 'cust_main_county 23' ). The values of the hash are listrefs. The first
704 item in the list is the tax object. The remaining items are either line
705 items or floating point values (currency amounts).
707 The taxes are calculated on this entity. Calculated exemption records are
708 transferred to the LINEITEMREF items on the assumption that they are related.
714 This specifies the date appearing on the associated invoice. Some
715 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
721 sub calculate_taxes {
722 my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
724 # $taxlisthash is a hashref
725 # keys are identifiers, values are arrayrefs
726 # each arrayref starts with a tax object (cust_main_county or tax_rate)
727 # then any cust_bill_pkg objects the tax applies to
729 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
731 warn "$me calculate_taxes\n"
732 #.Dumper($self, $cust_bill_pkg, $taxlisthash, $invoice_time). "\n"
735 my @tax_line_items = ();
737 # keys are tax names (as printed on invoices / itemdesc )
738 # values are listrefs of taxlisthash keys (internal identifiers)
741 # keys are taxlisthash keys (internal identifiers)
742 # values are (cumulative) amounts
745 # keys are taxlisthash keys (internal identifiers)
746 # values are listrefs of cust_bill_pkg_tax_location hashrefs
747 my %tax_location = ();
749 # keys are taxlisthash keys (internal identifiers)
750 # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
751 my %tax_rate_location = ();
753 foreach my $tax ( keys %$taxlisthash ) {
754 # $tax is a tax identifier
755 my $tax_object = shift @{ $taxlisthash->{$tax} };
756 # $tax_object is a cust_main_county or tax_rate
757 # (with pkgnum and locationnum set)
758 # the rest of @{ $taxlisthash->{$tax} } is cust_bill_pkg objects
759 warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
760 warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
761 # taxline calculates the tax on all cust_bill_pkgs in the
762 # first (arrayref) argument
763 my $hashref_or_error =
764 $tax_object->taxline( $taxlisthash->{$tax},
765 'custnum' => $self->custnum,
766 'invoice_time' => $invoice_time
768 return $hashref_or_error unless ref($hashref_or_error);
770 unshift @{ $taxlisthash->{$tax} }, $tax_object;
772 my $name = $hashref_or_error->{'name'};
773 my $amount = $hashref_or_error->{'amount'};
775 #warn "adding $amount as $name\n";
776 $taxname{ $name } ||= [];
777 push @{ $taxname{ $name } }, $tax;
779 $tax{ $tax } += $amount;
781 # link records between cust_main_county/tax_rate and cust_location
782 $tax_location{ $tax } ||= [];
783 $tax_rate_location{ $tax } ||= [];
784 if ( ref($tax_object) eq 'FS::cust_main_county' ) {
785 push @{ $tax_location{ $tax } },
787 'taxnum' => $tax_object->taxnum,
788 'taxtype' => ref($tax_object),
789 'pkgnum' => $tax_object->get('pkgnum'),
790 'locationnum' => $tax_object->get('locationnum'),
791 'amount' => sprintf('%.2f', $amount ),
794 elsif ( ref($tax_object) eq 'FS::tax_rate' ) {
795 my $taxratelocationnum =
796 $tax_object->tax_rate_location->taxratelocationnum;
797 push @{ $tax_rate_location{ $tax } },
799 'taxnum' => $tax_object->taxnum,
800 'taxtype' => ref($tax_object),
801 'amount' => sprintf('%.2f', $amount ),
802 'locationtaxid' => $tax_object->location,
803 'taxratelocationnum' => $taxratelocationnum,
809 #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
810 my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
811 foreach my $tax ( keys %$taxlisthash ) {
812 foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
813 next unless ref($_) eq 'FS::cust_bill_pkg';
815 my @cust_tax_exempt_pkg = splice( @{ $_->_cust_tax_exempt_pkg } );
817 next unless @cust_tax_exempt_pkg; #just avoiding the prob when irrelevant?
818 die "can't distribute tax exemptions: no line item for ". Dumper($_).
819 " in packagemap ". join(',', sort {$a<=>$b} keys %packagemap). "\n"
820 unless $packagemap{$_->pkgnum};
822 push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
823 @cust_tax_exempt_pkg;
827 #consolidate and create tax line items
828 warn "consolidating and generating...\n" if $DEBUG > 2;
829 foreach my $taxname ( keys %taxname ) {
832 my @cust_bill_pkg_tax_location = ();
833 my @cust_bill_pkg_tax_rate_location = ();
834 warn "adding $taxname\n" if $DEBUG > 1;
835 foreach my $taxitem ( @{ $taxname{$taxname} } ) {
836 next if $seen{$taxitem}++;
837 warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
838 $tax += $tax{$taxitem};
839 push @cust_bill_pkg_tax_location,
840 map { new FS::cust_bill_pkg_tax_location $_ }
841 @{ $tax_location{ $taxitem } };
842 push @cust_bill_pkg_tax_rate_location,
843 map { new FS::cust_bill_pkg_tax_rate_location $_ }
844 @{ $tax_rate_location{ $taxitem } };
848 $tax = sprintf('%.2f', $tax );
850 my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
856 if ( $pkg_category and
857 $conf->config('invoice_latexsummary') ||
858 $conf->config('invoice_htmlsummary')
862 my %hash = ( 'section' => $pkg_category->categoryname );
863 push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
867 push @tax_line_items, new FS::cust_bill_pkg {
873 'itemdesc' => $taxname,
874 'display' => \@display,
875 'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
876 'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
885 my ($self, %params) = @_;
887 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
889 my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
890 my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
891 my $precommit_hooks = $params{precommit_hooks} or die "no precommit_hooks specified";
892 my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
893 my $total_setup = $params{setup} or die "no setup accumulator specified";
894 my $total_recur = $params{recur} or die "no recur accumulator specified";
895 my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
896 my $time = $params{'time'} or die "no time specified";
897 my (%options) = %{$params{options}};
899 if ( $part_pkg->freq ne '1' and ($options{'freq_override'} || 0) > 0 ) {
900 # this should never happen
901 die 'freq_override billing attempted on non-monthly package '.
906 my $real_pkgpart = $params{real_pkgpart};
907 my %hash = $cust_pkg->hash;
908 my $old_cust_pkg = new FS::cust_pkg \%hash;
913 $cust_pkg->pkgpart($part_pkg->pkgpart);
921 my @setup_discounts = ();
922 my %setup_param = ( 'discounts' => \@setup_discounts );
923 if ( ! $options{recurring_only}
924 and ! $options{cancel}
925 and ( $options{'resetup'}
926 || ( ! $cust_pkg->setup
927 && ( ! $cust_pkg->start_date
928 || $cust_pkg->start_date <= day_end($time)
930 && ( ! $conf->exists('disable_setup_suspended_pkgs')
931 || ( $conf->exists('disable_setup_suspended_pkgs') &&
932 ! $cust_pkg->getfield('susp')
940 warn " bill setup\n" if $DEBUG > 1;
942 unless ( $cust_pkg->waive_setup ) {
945 $setup = eval { $cust_pkg->calc_setup( $time, \@details, \%setup_param ) };
946 return "$@ running calc_setup for $cust_pkg\n"
949 $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
952 $cust_pkg->setfield('setup', $time)
953 unless $cust_pkg->setup;
954 #do need it, but it won't get written to the db
955 #|| $cust_pkg->pkgpart != $real_pkgpart;
957 $cust_pkg->setfield('start_date', '')
958 if $cust_pkg->start_date;
968 my @recur_discounts = ();
970 if ( ! $cust_pkg->start_date
971 and ( ! $cust_pkg->susp || $cust_pkg->option('suspend_bill',1)
972 || ( $part_pkg->option('suspend_bill', 1) )
973 && ! $cust_pkg->option('no_suspend_bill',1)
976 ( $part_pkg->freq ne '0' && ( $cust_pkg->bill || 0 ) <= day_end($time) )
977 || ( $part_pkg->plan eq 'voip_cdr'
978 && $part_pkg->option('bill_every_call')
983 # XXX should this be a package event? probably. events are called
984 # at collection time at the moment, though...
985 $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
986 if $part_pkg->can('reset_usage') && !$options{'no_usage_reset'};
987 #don't want to reset usage just cause we want a line item??
988 #&& $part_pkg->pkgpart == $real_pkgpart;
990 warn " bill recur\n" if $DEBUG > 1;
993 # XXX shared with $recur_prog
994 $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
998 #over two params! lets at least switch to a hashref for the rest...
999 my $increment_next_bill = ( $part_pkg->freq ne '0'
1000 && ( $cust_pkg->getfield('bill') || 0 ) <= day_end($time)
1001 && !$options{cancel}
1003 my %param = ( %setup_param,
1004 'precommit_hooks' => $precommit_hooks,
1005 'increment_next_bill' => $increment_next_bill,
1006 'discounts' => \@recur_discounts,
1007 'real_pkgpart' => $real_pkgpart,
1008 'freq_override' => $options{freq_override} || '',
1012 my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
1014 # There may be some part_pkg for which this is wrong. Only those
1015 # which can_discount are supported.
1016 # (the UI should prevent adding discounts to these at the moment)
1018 warn "calling $method on cust_pkg ". $cust_pkg->pkgnum.
1019 " for pkgpart ". $cust_pkg->pkgpart.
1020 " with params ". join(' / ', map "$_=>$param{$_}", keys %param). "\n"
1023 $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
1024 return "$@ running $method for $cust_pkg\n"
1028 $unitrecur = $cust_pkg->part_pkg->base_recur || $recur; #XXX uuh
1030 if ( $increment_next_bill ) {
1032 my $next_bill = $part_pkg->add_freq($sdate, $options{freq_override} || 0);
1033 return "unparsable frequency: ". $part_pkg->freq
1034 if $next_bill == -1;
1036 #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
1037 # only for figuring next bill date, nothing else, so, reset $sdate again
1039 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1040 #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
1041 $cust_pkg->last_bill($sdate);
1043 $cust_pkg->setfield('bill', $next_bill );
1047 if ( $param{'setup_fee'} ) {
1048 # Add an additional setup fee at the billing stage.
1049 # Used for prorate_defer_bill.
1050 $setup += $param{'setup_fee'};
1051 $unitsetup += $param{'setup_fee'};
1055 if ( defined $param{'discount_left_setup'} ) {
1056 foreach my $discount_setup ( values %{$param{'discount_left_setup'}} ) {
1057 $setup -= $discount_setup;
1063 warn "\$setup is undefined" unless defined($setup);
1064 warn "\$recur is undefined" unless defined($recur);
1065 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1068 # If there's line items, create em cust_bill_pkg records
1069 # If $cust_pkg has been modified, update it (if we're a real pkgpart)
1074 if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
1075 # hmm.. and if just the options are modified in some weird price plan?
1077 warn " package ". $cust_pkg->pkgnum. " modified; updating\n"
1080 my $error = $cust_pkg->replace( $old_cust_pkg,
1081 'depend_jobnum'=>$options{depend_jobnum},
1082 'options' => { $cust_pkg->options },
1084 unless $options{no_commit};
1085 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
1086 if $error; #just in case
1089 $setup = sprintf( "%.2f", $setup );
1090 $recur = sprintf( "%.2f", $recur );
1091 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1092 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1094 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1095 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1098 my $discount_show_always = $conf->exists('discount-show-always')
1099 && ( ($setup == 0 && scalar(@setup_discounts))
1100 || ($recur == 0 && scalar(@recur_discounts))
1105 || (!$part_pkg->hidden && $options{has_hidden}) #include some $0 lines
1106 || $discount_show_always
1107 || ($setup == 0 && $cust_pkg->_X_show_zero('setup'))
1108 || ($recur == 0 && $cust_pkg->_X_show_zero('recur'))
1112 warn " charges (setup=$setup, recur=$recur); adding line items\n"
1115 my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
1117 warn " adding customer package invoice detail: $_\n"
1118 foreach @cust_pkg_detail;
1120 push @details, @cust_pkg_detail;
1122 my $cust_bill_pkg = new FS::cust_bill_pkg {
1123 'pkgnum' => $cust_pkg->pkgnum,
1125 'unitsetup' => $unitsetup,
1127 'unitrecur' => $unitrecur,
1128 'quantity' => $cust_pkg->quantity,
1129 'details' => \@details,
1130 'discounts' => [ @setup_discounts, @recur_discounts ],
1131 'hidden' => $part_pkg->hidden,
1132 'freq' => $part_pkg->freq,
1135 if ( $part_pkg->option('prorate_defer_bill',1)
1136 and !$hash{last_bill} ) {
1137 # both preceding and upcoming, technically
1138 $cust_bill_pkg->sdate( $cust_pkg->setup );
1139 $cust_bill_pkg->edate( $cust_pkg->bill );
1140 } elsif ( $part_pkg->recur_temporality eq 'preceding' ) {
1141 $cust_bill_pkg->sdate( $hash{last_bill} );
1142 $cust_bill_pkg->edate( $sdate - 86399 ); #60s*60m*24h-1
1143 $cust_bill_pkg->edate( $time ) if $options{cancel};
1144 } else { #if ( $part_pkg->recur_temporality eq 'upcoming' ) {
1145 $cust_bill_pkg->sdate( $sdate );
1146 $cust_bill_pkg->edate( $cust_pkg->bill );
1147 #$cust_bill_pkg->edate( $time ) if $options{cancel};
1150 $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
1151 unless $part_pkg->pkgpart == $real_pkgpart;
1153 $$total_setup += $setup;
1154 $$total_recur += $recur;
1160 unless ( $discount_show_always ) {
1162 $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
1163 return $error if $error;
1166 push @$cust_bill_pkgs, $cust_bill_pkg;
1168 } #if $setup != 0 || $recur != 0
1178 my $part_pkg = shift;
1179 my $taxlisthash = shift;
1180 my $cust_bill_pkg = shift;
1181 my $cust_pkg = shift;
1182 my $invoice_time = shift;
1183 my $real_pkgpart = shift;
1184 my $options = shift;
1186 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1188 my %cust_bill_pkg = ();
1192 #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
1193 push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
1194 push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
1195 push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
1197 my $exempt = $conf->exists('cust_class-tax_exempt')
1198 ? ( $self->cust_class ? $self->cust_class->tax : '' )
1201 if ( $exempt !~ /Y/i && $self->payby ne 'COMP' ) {
1203 if ( $conf->exists('enable_taxproducts')
1204 && ( scalar($part_pkg->part_pkg_taxoverride)
1205 || $part_pkg->has_taxproduct
1210 foreach my $class (@classes) {
1211 my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $cust_pkg );
1212 return $err_or_ref unless ref($err_or_ref);
1213 $taxes{$class} = $err_or_ref;
1216 unless (exists $taxes{''}) {
1217 my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $cust_pkg );
1218 return $err_or_ref unless ref($err_or_ref);
1219 $taxes{''} = $err_or_ref;
1224 my @loc_keys = qw( district city county state country );
1225 my $location = $cust_pkg->tax_location;
1226 my %taxhash = map { $_ => $location->$_ } @loc_keys;
1228 $taxhash{'taxclass'} = $part_pkg->taxclass;
1230 warn "taxhash:\n". Dumper(\%taxhash) if $DEBUG > 2;
1232 my @taxes = (); # entries are cust_main_county objects
1233 my %taxhash_elim = %taxhash;
1234 my @elim = qw( district city county state );
1237 #first try a match with taxclass
1238 @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
1240 if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
1241 #then try a match without taxclass
1242 my %no_taxclass = %taxhash_elim;
1243 $no_taxclass{ 'taxclass' } = '';
1244 @taxes = qsearch( 'cust_main_county', \%no_taxclass );
1247 $taxhash_elim{ shift(@elim) } = '';
1249 } while ( !scalar(@taxes) && scalar(@elim) );
1251 @taxes = grep { ! $_->taxname || ! $self->tax_exemption($_->taxname) }
1253 if $self->cust_main_exemption; #just to be safe
1255 warn "using taxes:\n". Dumper(@taxes) if $DEBUG > 2;
1257 # all packages now have a locationnum and should get a
1258 # cust_bill_pkg_tax_location record. The tax_locationnum
1259 # may be the package's locationnum, or the customer's bill
1260 # or service location.
1262 $_->set('pkgnum', $cust_pkg->pkgnum);
1263 $_->set('locationnum', $cust_pkg->tax_locationnum);
1266 $taxes{''} = [ @taxes ];
1267 $taxes{'setup'} = [ @taxes ];
1268 $taxes{'recur'} = [ @taxes ];
1269 $taxes{$_} = [ @taxes ] foreach (@classes);
1271 # # maybe eliminate this entirely, along with all the 0% records
1272 # unless ( @taxes ) {
1274 # "fatal: can't find tax rate for state/county/country/taxclass ".
1275 # join('/', map $taxhash{$_}, qw(state county country taxclass) );
1278 } #if $conf->exists('enable_taxproducts') ...
1282 #what's this doing in the middle of _handle_taxes? probably should split
1283 #this into three parts above in _make_lines
1284 $cust_bill_pkg->set_display( part_pkg => $part_pkg,
1285 real_pkgpart => $real_pkgpart,
1288 my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
1289 foreach my $key (keys %tax_cust_bill_pkg) {
1290 # $key is "setup", "recur", or a usage class name. ('' is a usage class.)
1291 # $tax_cust_bill_pkg{$key} is a cust_bill_pkg for that component of
1293 # $taxes{$key} is an arrayref of cust_main_county or tax_rate objects that
1294 # apply to $key-class charges.
1295 my @taxes = @{ $taxes{$key} || [] };
1296 my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
1298 my %localtaxlisthash = ();
1299 foreach my $tax ( @taxes ) {
1301 # this is the tax identifier, not the taxname
1302 my $taxname = ref( $tax ). ' '. $tax->taxnum;
1303 # $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
1304 # ' locationnum'. $cust_pkg->locationnum
1305 # if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
1307 # $taxlisthash: keys are "setup", "recur", and usage classes
1308 # values are arrayrefs, first the tax object (cust_main_county
1309 # or tax_rate) and then any cust_bill_pkg objects that the
1311 $taxlisthash->{ $taxname } ||= [ $tax ];
1312 push @{ $taxlisthash->{ $taxname } }, $tax_cust_bill_pkg;
1314 $localtaxlisthash{ $taxname } ||= [ $tax ];
1315 push @{ $localtaxlisthash{ $taxname } }, $tax_cust_bill_pkg;
1319 warn "finding taxed taxes...\n" if $DEBUG > 2;
1320 foreach my $tax ( keys %localtaxlisthash ) {
1321 my $tax_object = shift @{ $localtaxlisthash{$tax} };
1322 warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
1324 next unless $tax_object->can('tax_on_tax');
1326 foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
1327 my $totname = ref( $tot ). ' '. $tot->taxnum;
1329 warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
1331 next unless exists( $localtaxlisthash{ $totname } ); # only increase
1333 warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
1334 my $hashref_or_error =
1335 $tax_object->taxline( $localtaxlisthash{$tax},
1336 'custnum' => $self->custnum,
1337 'invoice_time' => $invoice_time,
1339 return $hashref_or_error
1340 unless ref($hashref_or_error);
1342 $taxlisthash->{ $totname } ||= [ $tot ];
1343 push @{ $taxlisthash->{ $totname } }, $hashref_or_error->{amount};
1355 my $part_pkg = shift;
1357 my $cust_pkg = shift;
1359 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1362 if ( $cust_pkg->locationnum && $conf->exists('tax-pkg_address') ) {
1363 $geocode = $cust_pkg->cust_location->geocode('cch');
1365 $geocode = $self->geocode('cch');
1370 my @taxclassnums = map { $_->taxclassnum }
1371 $part_pkg->part_pkg_taxoverride($class);
1373 unless (@taxclassnums) {
1374 @taxclassnums = map { $_->taxclassnum }
1375 grep { $_->taxable eq 'Y' }
1376 $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
1378 warn "Found taxclassnum values of ". join(',', @taxclassnums)
1383 join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
1385 @taxes = qsearch({ 'table' => 'tax_rate',
1386 'hashref' => { 'geocode' => $geocode, },
1387 'extra_sql' => $extra_sql,
1389 if scalar(@taxclassnums);
1391 warn "Found taxes ".
1392 join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n"
1399 =item collect [ HASHREF | OPTION => VALUE ... ]
1401 (Attempt to) collect money for this customer's outstanding invoices (see
1402 L<FS::cust_bill>). Usually used after the bill method.
1404 Actions are now triggered by billing events; see L<FS::part_event> and the
1405 billing events web interface. Old-style invoice events (see
1406 L<FS::part_bill_event>) have been deprecated.
1408 If there is an error, returns the error, otherwise returns false.
1410 Options are passed as name-value pairs.
1412 Currently available options are:
1418 Use this time when deciding when to print invoices and late notices on those invoices. The default is now. It is specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions.
1422 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1426 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1430 set true to surpress email card/ACH decline notices.
1434 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1440 # allows for one time override of normal customer billing method
1445 my( $self, %options ) = @_;
1447 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1449 my $invoice_time = $options{'invoice_time'} || time;
1452 local $SIG{HUP} = 'IGNORE';
1453 local $SIG{INT} = 'IGNORE';
1454 local $SIG{QUIT} = 'IGNORE';
1455 local $SIG{TERM} = 'IGNORE';
1456 local $SIG{TSTP} = 'IGNORE';
1457 local $SIG{PIPE} = 'IGNORE';
1459 my $oldAutoCommit = $FS::UID::AutoCommit;
1460 local $FS::UID::AutoCommit = 0;
1463 $self->select_for_update; #mutex
1466 my $balance = $self->balance;
1467 warn "$me collect customer ". $self->custnum. ": balance $balance\n"
1470 if ( exists($options{'retry_card'}) ) {
1471 carp 'retry_card option passed to collect is deprecated; use retry';
1472 $options{'retry'} ||= $options{'retry_card'};
1474 if ( exists($options{'retry'}) && $options{'retry'} ) {
1475 my $error = $self->retry_realtime;
1477 $dbh->rollback if $oldAutoCommit;
1482 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1484 #never want to roll back an event just because it returned an error
1485 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1487 $self->do_cust_event(
1488 'debug' => ( $options{'debug'} || 0 ),
1489 'time' => $invoice_time,
1490 'check_freq' => $options{'check_freq'},
1491 'stage' => 'collect',
1496 =item retry_realtime
1498 Schedules realtime / batch credit card / electronic check / LEC billing
1499 events for for retry. Useful if card information has changed or manual
1500 retry is desired. The 'collect' method must be called to actually retry
1503 Implementation details: For either this customer, or for each of this
1504 customer's open invoices, changes the status of the first "done" (with
1505 statustext error) realtime processing event to "failed".
1509 sub retry_realtime {
1512 local $SIG{HUP} = 'IGNORE';
1513 local $SIG{INT} = 'IGNORE';
1514 local $SIG{QUIT} = 'IGNORE';
1515 local $SIG{TERM} = 'IGNORE';
1516 local $SIG{TSTP} = 'IGNORE';
1517 local $SIG{PIPE} = 'IGNORE';
1519 my $oldAutoCommit = $FS::UID::AutoCommit;
1520 local $FS::UID::AutoCommit = 0;
1523 #a little false laziness w/due_cust_event (not too bad, really)
1525 my $join = FS::part_event_condition->join_conditions_sql;
1526 my $order = FS::part_event_condition->order_conditions_sql;
1529 . join ( ' OR ' , map {
1530 my $cust_join = FS::part_event->eventtables_cust_join->{$_} || '';
1531 my $custnum = FS::part_event->eventtables_custnum->{$_};
1532 "( part_event.eventtable = " . dbh->quote($_)
1533 . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key
1534 . " from $_ $cust_join"
1535 . " where $custnum = " . dbh->quote( $self->custnum ) . "))" ;
1536 } FS::part_event->eventtables)
1539 #here is the agent virtualization
1540 my $agent_virt = " ( part_event.agentnum IS NULL
1541 OR part_event.agentnum = ". $self->agentnum. ' )';
1543 #XXX this shouldn't be hardcoded, actions should declare it...
1544 my @realtime_events = qw(
1545 cust_bill_realtime_card
1546 cust_bill_realtime_check
1547 cust_bill_realtime_lec
1551 my $is_realtime_event =
1552 ' part_event.action IN ( '.
1553 join(',', map "'$_'", @realtime_events ).
1556 my $batch_or_statustext =
1557 "( part_event.action = 'cust_bill_batch'
1558 OR ( statustext IS NOT NULL AND statustext != '' )
1562 my @cust_event = qsearch({
1563 'table' => 'cust_event',
1564 'select' => 'cust_event.*',
1565 'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
1566 'hashref' => { 'status' => 'done' },
1567 'extra_sql' => " AND $batch_or_statustext ".
1568 " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
1571 my %seen_invnum = ();
1572 foreach my $cust_event (@cust_event) {
1574 #max one for the customer, one for each open invoice
1575 my $cust_X = $cust_event->cust_X;
1576 next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
1580 or $cust_event->part_event->eventtable eq 'cust_bill'
1583 my $error = $cust_event->retry;
1585 $dbh->rollback if $oldAutoCommit;
1586 return "error scheduling event for retry: $error";
1591 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1596 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
1598 Runs billing events; see L<FS::part_event> and the billing events web
1601 If there is an error, returns the error, otherwise returns false.
1603 Options are passed as name-value pairs.
1605 Currently available options are:
1611 Use this time when deciding when to print invoices and late notices on those invoices. The default is now. It is specified as a UNIX timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion functions.
1615 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1619 "collect" (the default) or "pre-bill"
1623 set true to surpress email card/ACH decline notices.
1627 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1634 # allows for one time override of normal customer billing method
1638 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1641 my( $self, %options ) = @_;
1643 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1645 my $time = $options{'time'} || time;
1648 local $SIG{HUP} = 'IGNORE';
1649 local $SIG{INT} = 'IGNORE';
1650 local $SIG{QUIT} = 'IGNORE';
1651 local $SIG{TERM} = 'IGNORE';
1652 local $SIG{TSTP} = 'IGNORE';
1653 local $SIG{PIPE} = 'IGNORE';
1655 my $oldAutoCommit = $FS::UID::AutoCommit;
1656 local $FS::UID::AutoCommit = 0;
1659 $self->select_for_update; #mutex
1662 my $balance = $self->balance;
1663 warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
1666 # if ( exists($options{'retry_card'}) ) {
1667 # carp 'retry_card option passed to collect is deprecated; use retry';
1668 # $options{'retry'} ||= $options{'retry_card'};
1670 # if ( exists($options{'retry'}) && $options{'retry'} ) {
1671 # my $error = $self->retry_realtime;
1673 # $dbh->rollback if $oldAutoCommit;
1678 # false laziness w/pay_batch::import_results
1680 my $due_cust_event = $self->due_cust_event(
1681 'debug' => ( $options{'debug'} || 0 ),
1683 'check_freq' => $options{'check_freq'},
1684 'stage' => ( $options{'stage'} || 'collect' ),
1686 unless( ref($due_cust_event) ) {
1687 $dbh->rollback if $oldAutoCommit;
1688 return $due_cust_event;
1691 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1692 #never want to roll back an event just because it or a different one
1694 local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1696 foreach my $cust_event ( @$due_cust_event ) {
1700 #re-eval event conditions (a previous event could have changed things)
1701 unless ( $cust_event->test_conditions ) {
1702 #don't leave stray "new/locked" records around
1703 my $error = $cust_event->delete;
1704 return $error if $error;
1709 local $FS::cust_main::Billing_Realtime::realtime_bop_decline_quiet = 1
1710 if $options{'quiet'};
1711 warn " running cust_event ". $cust_event->eventnum. "\n"
1714 #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
1715 if ( my $error = $cust_event->do_event( 'time' => $time ) ) {
1716 #XXX wtf is this? figure out a proper dealio with return value
1728 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
1730 Inserts database records for and returns an ordered listref of new events due
1731 for this customer, as FS::cust_event objects (see L<FS::cust_event>). If no
1732 events are due, an empty listref is returned. If there is an error, returns a
1733 scalar error message.
1735 To actually run the events, call each event's test_condition method, and if
1736 still true, call the event's do_event method.
1738 Options are passed as a hashref or as a list of name-value pairs. Available
1745 Search only for events of this check frequency (how often events of this type are checked); currently "1d" (daily, the default) and "1m" (monthly) are recognized.
1749 "collect" (the default) or "pre-bill"
1753 "Current time" for the events.
1757 Debugging level. Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1761 Only return events for the specified eventtable (by default, events of all eventtables are returned)
1765 Explicitly pass the objects to be tested (typically used with eventtable).
1769 Set to true to return the objects, but not actually insert them into the
1776 sub due_cust_event {
1778 my %opt = ref($_[0]) ? %{ $_[0] } : @_;
1781 #my $DEBUG = $opt{'debug'}
1782 local($DEBUG) = $opt{'debug'}
1783 if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
1784 $DEBUG = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1786 warn "$me due_cust_event called with options ".
1787 join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
1790 $opt{'time'} ||= time;
1792 local $SIG{HUP} = 'IGNORE';
1793 local $SIG{INT} = 'IGNORE';
1794 local $SIG{QUIT} = 'IGNORE';
1795 local $SIG{TERM} = 'IGNORE';
1796 local $SIG{TSTP} = 'IGNORE';
1797 local $SIG{PIPE} = 'IGNORE';
1799 my $oldAutoCommit = $FS::UID::AutoCommit;
1800 local $FS::UID::AutoCommit = 0;
1803 $self->select_for_update #mutex
1804 unless $opt{testonly};
1807 # find possible events (initial search)
1810 my @cust_event = ();
1812 my @eventtable = $opt{'eventtable'}
1813 ? ( $opt{'eventtable'} )
1814 : FS::part_event->eventtables_runorder;
1816 my $check_freq = $opt{'check_freq'} || '1d';
1818 foreach my $eventtable ( @eventtable ) {
1821 if ( $opt{'objects'} ) {
1823 @objects = @{ $opt{'objects'} };
1825 } elsif ( $eventtable eq 'cust_main' ) {
1827 @objects = ( $self );
1831 my $cm_join = " LEFT JOIN cust_main USING ( custnum )";
1832 # linkage not needed here because FS::cust_main->$eventtable will
1835 #some false laziness w/Cron::bill bill_where
1837 my $join = FS::part_event_condition->join_conditions_sql( $eventtable);
1838 my $where = FS::part_event_condition->where_conditions_sql($eventtable,
1839 'time'=>$opt{'time'},
1841 $where = $where ? "AND $where" : '';
1843 my $are_part_event =
1844 "EXISTS ( SELECT 1 FROM part_event $join
1845 WHERE check_freq = '$check_freq'
1846 AND eventtable = '$eventtable'
1847 AND ( disabled = '' OR disabled IS NULL )
1853 @objects = $self->$eventtable(
1854 'addl_from' => $cm_join,
1855 'extra_sql' => " AND $are_part_event",
1857 } # if ( !$opt{objects} and $eventtable ne 'cust_main' )
1859 my @e_cust_event = ();
1861 my $linkage = FS::part_event->eventtables_cust_join->{$eventtable} || '';
1863 my $cross = "CROSS JOIN $eventtable $linkage";
1864 $cross .= ' LEFT JOIN cust_main USING ( custnum )'
1865 unless $eventtable eq 'cust_main';
1867 foreach my $object ( @objects ) {
1869 #this first search uses the condition_sql magic for optimization.
1870 #the more possible events we can eliminate in this step the better
1872 my $cross_where = '';
1873 my $pkey = $object->primary_key;
1874 $cross_where = "$eventtable.$pkey = ". $object->$pkey();
1876 my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
1878 FS::part_event_condition->where_conditions_sql( $eventtable,
1879 'time'=>$opt{'time'}
1881 my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
1883 $extra_sql = "AND $extra_sql" if $extra_sql;
1885 #here is the agent virtualization
1886 $extra_sql .= " AND ( part_event.agentnum IS NULL
1887 OR part_event.agentnum = ". $self->agentnum. ' )';
1889 $extra_sql .= " $order";
1891 warn "searching for events for $eventtable ". $object->$pkey. "\n"
1892 if $opt{'debug'} > 2;
1893 my @part_event = qsearch( {
1894 'debug' => ( $opt{'debug'} > 3 ? 1 : 0 ),
1895 'select' => 'part_event.*',
1896 'table' => 'part_event',
1897 'addl_from' => "$cross $join",
1898 'hashref' => { 'check_freq' => $check_freq,
1899 'eventtable' => $eventtable,
1902 'extra_sql' => "AND $cross_where $extra_sql",
1906 my $pkey = $object->primary_key;
1907 warn " ". scalar(@part_event).
1908 " possible events found for $eventtable ". $object->$pkey(). "\n";
1911 push @e_cust_event, map {
1912 $_->new_cust_event($object, 'time' => $opt{'time'})
1917 warn " ". scalar(@e_cust_event).
1918 " subtotal possible cust events found for $eventtable\n"
1921 push @cust_event, @e_cust_event;
1925 warn " ". scalar(@cust_event).
1926 " total possible cust events found in initial search\n"
1934 $opt{stage} ||= 'collect';
1936 grep { my $stage = $_->part_event->event_stage;
1937 $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
1947 @cust_event = grep $_->test_conditions( 'stats_hashref' => \%unsat ),
1950 warn " ". scalar(@cust_event). " cust events left satisfying conditions\n"
1953 warn " invalid conditions not eliminated with condition_sql:\n".
1954 join('', map " $_: ".$unsat{$_}."\n", keys %unsat )
1955 if keys %unsat && $DEBUG; # > 1;
1961 unless( $opt{testonly} ) {
1962 foreach my $cust_event ( @cust_event ) {
1964 my $error = $cust_event->insert();
1966 $dbh->rollback if $oldAutoCommit;
1973 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1979 warn " returning events: ". Dumper(@cust_event). "\n"
1986 =item apply_payments_and_credits [ OPTION => VALUE ... ]
1988 Applies unapplied payments and credits.
1990 In most cases, this new method should be used in place of sequential
1991 apply_payments and apply_credits methods.
1993 A hash of optional arguments may be passed. Currently "manual" is supported.
1994 If true, a payment receipt is sent instead of a statement when
1995 'payment_receipt_email' configuration option is set.
1997 If there is an error, returns the error, otherwise returns false.
2001 sub apply_payments_and_credits {
2002 my( $self, %options ) = @_;
2004 local $SIG{HUP} = 'IGNORE';
2005 local $SIG{INT} = 'IGNORE';
2006 local $SIG{QUIT} = 'IGNORE';
2007 local $SIG{TERM} = 'IGNORE';
2008 local $SIG{TSTP} = 'IGNORE';
2009 local $SIG{PIPE} = 'IGNORE';
2011 my $oldAutoCommit = $FS::UID::AutoCommit;
2012 local $FS::UID::AutoCommit = 0;
2015 $self->select_for_update; #mutex
2017 foreach my $cust_bill ( $self->open_cust_bill ) {
2018 my $error = $cust_bill->apply_payments_and_credits(%options);
2020 $dbh->rollback if $oldAutoCommit;
2021 return "Error applying: $error";
2025 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2030 =item apply_credits OPTION => VALUE ...
2032 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2033 to outstanding invoice balances in chronological order (or reverse
2034 chronological order if the I<order> option is set to B<newest>) and returns the
2035 value of any remaining unapplied credits available for refund (see
2036 L<FS::cust_refund>).
2038 Dies if there is an error.
2046 local $SIG{HUP} = 'IGNORE';
2047 local $SIG{INT} = 'IGNORE';
2048 local $SIG{QUIT} = 'IGNORE';
2049 local $SIG{TERM} = 'IGNORE';
2050 local $SIG{TSTP} = 'IGNORE';
2051 local $SIG{PIPE} = 'IGNORE';
2053 my $oldAutoCommit = $FS::UID::AutoCommit;
2054 local $FS::UID::AutoCommit = 0;
2057 $self->select_for_update; #mutex
2059 unless ( $self->total_unapplied_credits ) {
2060 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2064 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2065 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2067 my @invoices = $self->open_cust_bill;
2068 @invoices = sort { $b->_date <=> $a->_date } @invoices
2069 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2071 if ( $conf->exists('pkg-balances') ) {
2072 # limit @credits to those w/ a pkgnum grepped from $self
2074 foreach my $i (@invoices) {
2075 foreach my $li ( $i->cust_bill_pkg ) {
2076 $pkgnums{$li->pkgnum} = 1;
2079 @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
2084 foreach my $cust_bill ( @invoices ) {
2086 if ( !defined($credit) || $credit->credited == 0) {
2087 $credit = pop @credits or last;
2091 if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
2092 $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
2094 $owed = $cust_bill->owed;
2096 unless ( $owed > 0 ) {
2097 push @credits, $credit;
2101 my $amount = min( $credit->credited, $owed );
2103 my $cust_credit_bill = new FS::cust_credit_bill ( {
2104 'crednum' => $credit->crednum,
2105 'invnum' => $cust_bill->invnum,
2106 'amount' => $amount,
2108 $cust_credit_bill->pkgnum( $credit->pkgnum )
2109 if $conf->exists('pkg-balances') && $credit->pkgnum;
2110 my $error = $cust_credit_bill->insert;
2112 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2116 redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2120 my $total_unapplied_credits = $self->total_unapplied_credits;
2122 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2124 return $total_unapplied_credits;
2127 =item apply_payments [ OPTION => VALUE ... ]
2129 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2130 to outstanding invoice balances in chronological order.
2132 #and returns the value of any remaining unapplied payments.
2134 A hash of optional arguments may be passed. Currently "manual" is supported.
2135 If true, a payment receipt is sent instead of a statement when
2136 'payment_receipt_email' configuration option is set.
2138 Dies if there is an error.
2142 sub apply_payments {
2143 my( $self, %options ) = @_;
2145 local $SIG{HUP} = 'IGNORE';
2146 local $SIG{INT} = 'IGNORE';
2147 local $SIG{QUIT} = 'IGNORE';
2148 local $SIG{TERM} = 'IGNORE';
2149 local $SIG{TSTP} = 'IGNORE';
2150 local $SIG{PIPE} = 'IGNORE';
2152 my $oldAutoCommit = $FS::UID::AutoCommit;
2153 local $FS::UID::AutoCommit = 0;
2156 $self->select_for_update; #mutex
2160 my @payments = sort { $b->_date <=> $a->_date }
2161 grep { $_->unapplied > 0 }
2164 my @invoices = sort { $a->_date <=> $b->_date}
2165 grep { $_->owed > 0 }
2168 if ( $conf->exists('pkg-balances') ) {
2169 # limit @payments to those w/ a pkgnum grepped from $self
2171 foreach my $i (@invoices) {
2172 foreach my $li ( $i->cust_bill_pkg ) {
2173 $pkgnums{$li->pkgnum} = 1;
2176 @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
2181 foreach my $cust_bill ( @invoices ) {
2183 if ( !defined($payment) || $payment->unapplied == 0 ) {
2184 $payment = pop @payments or last;
2188 if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
2189 $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
2191 $owed = $cust_bill->owed;
2193 unless ( $owed > 0 ) {
2194 push @payments, $payment;
2198 my $amount = min( $payment->unapplied, $owed );
2201 'paynum' => $payment->paynum,
2202 'invnum' => $cust_bill->invnum,
2203 'amount' => $amount,
2205 $cbp->{_date} = $payment->_date
2206 if $options{'manual'} && $options{'backdate_application'};
2207 my $cust_bill_pay = new FS::cust_bill_pay($cbp);
2208 $cust_bill_pay->pkgnum( $payment->pkgnum )
2209 if $conf->exists('pkg-balances') && $payment->pkgnum;
2210 my $error = $cust_bill_pay->insert(%options);
2212 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2216 redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2220 my $total_unapplied_payments = $self->total_unapplied_payments;
2222 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2224 return $total_unapplied_payments;
2234 suspend_adjourned_pkgs
2235 unsuspend_resumed_pkgs
2238 (do_cust_event pre-bill)
2241 (vendor-only) _gather_taxes
2242 _omit_zero_value_bundles
2245 apply_payments_and_credits
2254 L<FS::cust_main>, L<FS::cust_main::Billing_Realtime>