show prorate details on invoice, #16010
[freeside.git] / FS / FS / cust_main / Billing.pm
1 package FS::cust_main::Billing;
2
3 use strict;
4 use vars qw( $conf $DEBUG $me );
5 use Carp;
6 use Data::Dumper;
7 use List::Util qw( min );
8 use FS::UID qw( dbh );
9 use FS::Record qw( qsearch qsearchs dbdef );
10 use FS::Misc::DateTime qw( day_end );
11 use FS::cust_bill;
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;
17 use FS::tax_rate;
18 use FS::tax_rate_location;
19 use FS::cust_bill_pkg_tax_location;
20 use FS::cust_bill_pkg_tax_rate_location;
21 use FS::part_event;
22 use FS::part_event_condition;
23 use FS::pkg_category;
24
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
28 $DEBUG = 0;
29 $me = '[FS::cust_main::Billing]';
30
31 install_callback FS::UID sub { 
32   $conf = new FS::Conf;
33   #yes, need it for stuff below (prolly should be cached)
34 };
35
36 =head1 NAME
37
38 FS::cust_main::Billing - Billing mixin for cust_main
39
40 =head1 SYNOPSIS
41
42 =head1 DESCRIPTION
43
44 These methods are available on FS::cust_main objects.
45
46 =head1 METHODS
47
48 =over 4
49
50 =item bill_and_collect 
51
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,
54 etc.
55
56 By default, warns on errors and continues with the next operation (but see the
57 "fatal" flag below).
58
59 Options are passed as name-value pairs.  Currently available options are:
60
61 =over 4
62
63 =item time
64
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:
66
67  use Date::Parse;
68  ...
69  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
70
71 =item invoice_time
72
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.
74
75 =item check_freq
76
77 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
78
79 =item resetup
80
81 If set true, re-charges setup fees.
82
83 =item fatal
84
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.
88
89 =item debug
90
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)
92
93 =item job
94
95 Optional FS::queue entry to receive status updates.
96
97 =back
98
99 Options are passed to the B<bill> and B<collect> methods verbatim, so all
100 options of those methods are also available.
101
102 =cut
103
104 sub bill_and_collect {
105   my( $self, %options ) = @_;
106
107   my $error;
108
109   #$options{actual_time} not $options{time} because freeside-daily -d is for
110   #pre-printing invoices
111
112   $options{'actual_time'} ||= time;
113   my $job = $options{'job'};
114
115   $job->update_statustext('0,cleaning expired packages') if $job;
116   $error = $self->cancel_expired_pkgs( day_end( $options{actual_time} ) );
117   if ( $error ) {
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; }
122   }
123
124   $error = $self->suspend_adjourned_pkgs( day_end( $options{actual_time} ) );
125   if ( $error ) {
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; }
130   }
131
132   $error = $self->unsuspend_resumed_pkgs( day_end( $options{actual_time} ) );
133   if ( $error ) {
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; }
138   }
139
140   $job->update_statustext('20,billing packages') if $job;
141   $error = $self->bill( %options );
142   if ( $error ) {
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; }
147   }
148
149   $job->update_statustext('50,applying payments and credits') if $job;
150   $error = $self->apply_payments_and_credits;
151   if ( $error ) {
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; }
156   }
157
158   $job->update_statustext('70,running collection events') if $job;
159   unless ( $conf->exists('cancelled_cust-noevents')
160            && ! $self->num_ncancelled_pkgs
161   ) {
162     $error = $self->collect( %options );
163     if ( $error ) {
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; }
168     }
169   }
170   $job->update_statustext('100,finished') if $job;
171
172   '';
173
174 }
175
176 sub cancel_expired_pkgs {
177   my ( $self, $time, %options ) = @_;
178   
179   my @cancel_pkgs = $self->ncancelled_pkgs( { 
180     'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
181   } );
182
183   my @errors = ();
184
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,
189                                            'time'          => $time,
190                                          )
191                                        : ()
192                                  );
193     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
194   }
195
196   join(' / ', @errors);
197
198 }
199
200 sub suspend_adjourned_pkgs {
201   my ( $self, $time, %options ) = @_;
202   
203   my @susp_pkgs = $self->ncancelled_pkgs( {
204     'extra_sql' =>
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 )
208             )
209       ",
210   } );
211
212   #only because there's no SQL test for is_prepaid :/
213   @susp_pkgs = 
214     grep {     (    $_->part_pkg->is_prepaid
215                  && $_->bill
216                  && $_->bill < $time
217                )
218             || (    $_->adjourn
219                  && $_->adjourn <= $time
220                )
221            
222          }
223          @susp_pkgs;
224
225   my @errors = ();
226
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
232                                           )
233                                         : ()
234                                   );
235     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
236   }
237
238   join(' / ', @errors);
239
240 }
241
242 sub unsuspend_resumed_pkgs {
243   my ( $self, $time, %options ) = @_;
244   
245   my @unsusp_pkgs = $self->ncancelled_pkgs( { 
246     'extra_sql' => " AND resume IS NOT NULL AND resume > 0 AND resume <= $time "
247   } );
248
249   my @errors = ();
250
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;
254   }
255
256   join(' / ', @errors);
257
258 }
259
260 =item bill OPTIONS
261
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>.
264
265 If there is an error, returns the error, otherwise returns false.
266
267 Options are passed as name-value pairs.  Currently available options are:
268
269 =over 4
270
271 =item resetup
272
273 If set true, re-charges setup fees.
274
275 =item recurring_only
276
277 If set true then only bill recurring charges, not setup, usage, one time
278 charges, etc.
279
280 =item freq_override
281
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.
286
287 =item time
288
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:
290
291  use Date::Parse;
292  ...
293  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
294
295 =item pkg_list
296
297 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
298
299  $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
300
301 =item not_pkgpart
302
303 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
304
305 =item invoice_time
306
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.
308
309 =item cancel
310
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).
315
316 =item no_usage_reset
317
318 Prevent the resetting of usage limits during this call.
319
320 =item no_commit
321
322 Do not save the generated bill in the database.  Useful with return_bill
323
324 =item return_bill
325
326 A list reference on which the generated bill(s) will be returned.
327
328 =item invoice_terms
329
330 Optional terms to be printed on this invoice.  Otherwise, customer-specific
331 terms or the default terms are used.
332
333 =back
334
335 =cut
336
337 sub bill {
338   my( $self, %options ) = @_;
339
340   return '' if $self->payby eq 'COMP';
341
342   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
343
344   warn "$me bill customer ". $self->custnum. "\n"
345     if $DEBUG;
346
347   my $time = $options{'time'} || time;
348   my $invoice_time = $options{'invoice_time'} || $time;
349
350   $options{'not_pkgpart'} ||= {};
351   $options{'not_pkgpart'} = { map { $_ => 1 }
352                                   split(/\s*,\s*/, $options{'not_pkgpart'})
353                             }
354     unless ref($options{'not_pkgpart'});
355
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';
362
363   my $oldAutoCommit = $FS::UID::AutoCommit;
364   local $FS::UID::AutoCommit = 0;
365   my $dbh = dbh;
366
367   warn "$me acquiring lock on customer ". $self->custnum. "\n"
368     if $DEBUG;
369
370   $self->select_for_update; #mutex
371
372   warn "$me running pre-bill events for customer ". $self->custnum. "\n"
373     if $DEBUG;
374
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',
380   )
381     unless $options{no_commit};
382   if ( $error ) {
383     $dbh->rollback if $oldAutoCommit && !$options{no_commit};
384     return $error;
385   }
386
387   warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
388     if $DEBUG;
389
390   #keep auto-charge and non-auto-charge line items separate
391   my @passes = ( '', 'no_auto' );
392
393   my %cust_bill_pkg = map { $_ => [] } @passes;
394
395   ###
396   # find the packages which are due for billing, find out how much they are
397   # & generate invoice database.
398   ###
399
400   my %total_setup   = map { my $z = 0; $_ => \$z; } @passes;
401   my %total_recur   = map { my $z = 0; $_ => \$z; } @passes;
402
403   my %taxlisthash = map { $_ => {} } @passes;
404
405   my @precommit_hooks = ();
406
407   $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ];  #param checks?
408   foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
409
410     next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
411
412     warn "  bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG;
413
414     #? to avoid use of uninitialized value errors... ?
415     $cust_pkg->setfield('bill', '')
416       unless defined($cust_pkg->bill);
417  
418     #my $part_pkg = $cust_pkg->part_pkg;
419
420     my $real_pkgpart = $cust_pkg->pkgpart;
421     my %hash = $cust_pkg->hash;
422
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);
428  
429     foreach my $part_pkg ( @part_pkg ) {
430
431       $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
432
433       my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
434
435       my $next_bill = $cust_pkg->getfield('bill') || 0;
436       my $error;
437       # let this run once if this is the last bill upon cancellation
438       while ( $next_bill <= $time or $options{cancel} ) {
439         $error =
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},
447                               'time'                => $time,
448                               'real_pkgpart'        => $real_pkgpart,
449                               'options'             => \%options,
450                             );
451
452         # Stop if anything goes wrong
453         last if $error;
454
455         # or if we're not incrementing the bill date.
456         last if ($cust_pkg->getfield('bill') || 0) == $next_bill;
457
458         # or if we're letting it run only once
459         last if $options{cancel};
460
461         $next_bill = $cust_pkg->getfield('bill') || 0;
462
463         #stop if -o was passed to freeside-daily
464         last if $options{'one_recur'};
465       }
466       if ($error) {
467         $dbh->rollback if $oldAutoCommit && !$options{no_commit};
468         return $error;
469       }
470
471     } #foreach my $part_pkg
472
473   } #foreach my $cust_pkg
474
475   #if the customer isn't on an automatic payby, everything can go on a single
476   #invoice anyway?
477   #if ( $cust_main->payby !~ /^(CARD|CHEK)$/ ) {
478     #merge everything into one list
479   #}
480
481   foreach my $pass (@passes) { # keys %cust_bill_pkg ) {
482
483     my @cust_bill_pkg = _omit_zero_value_bundles(@{ $cust_bill_pkg{$pass} });
484
485     next unless @cust_bill_pkg; #don't create an invoice w/o line items
486
487     warn "$me billing pass $pass\n"
488            #.Dumper(\@cust_bill_pkg)."\n"
489       if $DEBUG > 2;
490
491     if ( scalar( grep { $_->recur && $_->recur > 0 } @cust_bill_pkg) ||
492            !$conf->exists('postal_invoice-recurring_only')
493        )
494     {
495
496       my $postal_pkg = $self->charge_postal_fee();
497       if ( $postal_pkg && !ref( $postal_pkg ) ) {
498
499         $dbh->rollback if $oldAutoCommit && !$options{no_commit};
500         return "can't charge postal invoice fee for customer ".
501           $self->custnum. ": $postal_pkg";
502
503       } elsif ( $postal_pkg ) {
504
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);
511
512         foreach my $part_pkg ( @part_pkg ) {
513           my %postal_options = %options;
514           delete $postal_options{cancel};
515           my $error =
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},
523                                 'time'                => $time,
524                                 'real_pkgpart'        => $real_pkgpart,
525                                 'options'             => \%postal_options,
526                               );
527           if ($error) {
528             $dbh->rollback if $oldAutoCommit && !$options{no_commit};
529             return $error;
530           }
531         }
532
533         # it's silly to have a zero value postal_pkg, but....
534         @cust_bill_pkg = _omit_zero_value_bundles(@cust_bill_pkg);
535
536       }
537
538     }
539
540     my $listref_or_error =
541       $self->calculate_taxes( \@cust_bill_pkg, $taxlisthash{$pass}, $invoice_time);
542
543     unless ( ref( $listref_or_error ) ) {
544       $dbh->rollback if $oldAutoCommit && !$options{no_commit};
545       return $listref_or_error;
546     }
547
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;
552     }
553
554     #add tax adjustments
555     warn "adding tax adjustments...\n" if $DEBUG > 2;
556     foreach my $cust_tax_adjustment (
557       qsearch('cust_tax_adjustment', { 'custnum'    => $self->custnum,
558                                        'billpkgnum' => '',
559                                      }
560              )
561     ) {
562
563       my $tax = sprintf('%.2f', $cust_tax_adjustment->amount );
564
565       my $itemdesc = $cust_tax_adjustment->taxname;
566       $itemdesc = '' if $itemdesc eq 'Tax';
567
568       push @cust_bill_pkg, new FS::cust_bill_pkg {
569         'pkgnum'      => 0,
570         'setup'       => $tax,
571         'recur'       => 0,
572         'sdate'       => '',
573         'edate'       => '',
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,
578       };
579
580     }
581
582     my $charged = sprintf('%.2f', ${ $total_setup{$pass} } + ${ $total_recur{$pass} } );
583
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 )
588                              : 0;
589
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);
594
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,
605     } );
606     $error = $cust_bill->insert unless $options{no_commit};
607     if ( $error ) {
608       $dbh->rollback if $oldAutoCommit && !$options{no_commit};
609       return "can't create invoice for customer #". $self->custnum. ": $error";
610     }
611     push @{$options{return_bill}}, $cust_bill if $options{return_bill};
612
613   } #foreach my $pass ( keys %cust_bill_pkg )
614
615   foreach my $hook ( @precommit_hooks ) { 
616     eval {
617       &{$hook}; #($self) ?
618     } unless $options{no_commit};
619     if ( $@ ) {
620       $dbh->rollback if $oldAutoCommit && !$options{no_commit};
621       return "$@ running precommit hook $hook\n";
622     }
623   }
624   
625   $dbh->commit or die $dbh->errstr if $oldAutoCommit && !$options{no_commit};
626
627   ''; #no error
628 }
629
630 #discard bundled packages of 0 value
631 sub _omit_zero_value_bundles {
632   my @in = @_;
633
634   my @cust_bill_pkg = ();
635   my @cust_bill_pkg_bundle = ();
636   my $sum = 0;
637   my $discount_show_always = 0;
638
639   foreach my $cust_bill_pkg ( @in ) {
640
641     $discount_show_always = ($cust_bill_pkg->get('discounts')
642                                 && scalar(@{$cust_bill_pkg->get('discounts')})
643                                 && $conf->exists('discount-show-always'));
644
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"
648       if $DEBUG > 0;
649
650     if (scalar(@cust_bill_pkg_bundle) && !$cust_bill_pkg->pkgpart_override) {
651       push @cust_bill_pkg, @cust_bill_pkg_bundle 
652         if $sum > 0
653         || ($sum == 0 && (    $discount_show_always
654                            || grep {$_->recur_show_zero || $_->setup_show_zero}
655                                    @cust_bill_pkg_bundle
656                          )
657            );
658       @cust_bill_pkg_bundle = ();
659       $sum = 0;
660     }
661
662     $sum += $cust_bill_pkg->setup + $cust_bill_pkg->recur;
663     push @cust_bill_pkg_bundle, $cust_bill_pkg;
664
665   }
666
667   push @cust_bill_pkg, @cust_bill_pkg_bundle
668     if $sum > 0
669     || ($sum == 0 && (    $discount_show_always
670                        || grep {$_->recur_show_zero || $_->setup_show_zero}
671                                @cust_bill_pkg_bundle
672                      )
673        );
674
675   warn "  _omit_zero_value_bundles: ". scalar(@in).
676        '->'. scalar(@cust_bill_pkg). "\n" #. Dumper(@cust_bill_pkg). "\n"
677     if $DEBUG > 2;
678
679   (@cust_bill_pkg);
680
681 }
682
683 =item calculate_taxes LINEITEMREF TAXHASHREF INVOICE_TIME
684
685 This is a weird one.  Perhaps it should not even be exposed.
686
687 Generates tax line items (see L<FS::cust_bill_pkg>) for this customer.
688 Usually used internally by bill method B<bill>.
689
690 If there is an error, returns the error, otherwise returns reference to a
691 list of line items suitable for insertion.
692
693 =over 4
694
695 =item LINEITEMREF
696
697 An array ref of the line items being billed.
698
699 =item TAXHASHREF
700
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).
706
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.
709
710 Read the source.
711
712 =item INVOICE_TIME
713
714 This specifies the date appearing on the associated invoice.  Some
715 jurisdictions (i.e. Texas) have tax exemptions which are date sensitive.
716
717 =back
718
719 =cut
720
721 sub calculate_taxes {
722   my ($self, $cust_bill_pkg, $taxlisthash, $invoice_time) = @_;
723
724   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
725
726   warn "$me calculate_taxes\n"
727        #.Dumper($self, $cust_bill_pkg, $taxlisthash, $invoice_time). "\n"
728     if $DEBUG > 2;
729
730   my @tax_line_items = ();
731
732   # keys are tax names (as printed on invoices / itemdesc )
733   # values are listrefs of taxlisthash keys (internal identifiers)
734   my %taxname = ();
735
736   # keys are taxlisthash keys (internal identifiers)
737   # values are (cumulative) amounts
738   my %tax = ();
739
740   # keys are taxlisthash keys (internal identifiers)
741   # values are listrefs of cust_bill_pkg_tax_location hashrefs
742   my %tax_location = ();
743
744   # keys are taxlisthash keys (internal identifiers)
745   # values are listrefs of cust_bill_pkg_tax_rate_location hashrefs
746   my %tax_rate_location = ();
747
748   foreach my $tax ( keys %$taxlisthash ) {
749     my $tax_object = shift @{ $taxlisthash->{$tax} };
750     warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
751     warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
752     my $hashref_or_error =
753       $tax_object->taxline( $taxlisthash->{$tax},
754                             'custnum'      => $self->custnum,
755                             'invoice_time' => $invoice_time
756                           );
757     return $hashref_or_error unless ref($hashref_or_error);
758
759     unshift @{ $taxlisthash->{$tax} }, $tax_object;
760
761     my $name   = $hashref_or_error->{'name'};
762     my $amount = $hashref_or_error->{'amount'};
763
764     #warn "adding $amount as $name\n";
765     $taxname{ $name } ||= [];
766     push @{ $taxname{ $name } }, $tax;
767
768     $tax{ $tax } += $amount;
769
770     $tax_location{ $tax } ||= [];
771     if ( $tax_object->get('pkgnum') || $tax_object->get('locationnum') ) {
772       push @{ $tax_location{ $tax }  },
773         {
774           'taxnum'      => $tax_object->taxnum, 
775           'taxtype'     => ref($tax_object),
776           'pkgnum'      => $tax_object->get('pkgnum'),
777           'locationnum' => $tax_object->get('locationnum'),
778           'amount'      => sprintf('%.2f', $amount ),
779         };
780     }
781
782     $tax_rate_location{ $tax } ||= [];
783     if ( ref($tax_object) eq 'FS::tax_rate' ) {
784       my $taxratelocationnum =
785         $tax_object->tax_rate_location->taxratelocationnum;
786       push @{ $tax_rate_location{ $tax }  },
787         {
788           'taxnum'             => $tax_object->taxnum, 
789           'taxtype'            => ref($tax_object),
790           'amount'             => sprintf('%.2f', $amount ),
791           'locationtaxid'      => $tax_object->location,
792           'taxratelocationnum' => $taxratelocationnum,
793         };
794     }
795
796   }
797
798   #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
799   my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
800   foreach my $tax ( keys %$taxlisthash ) {
801     foreach ( @{ $taxlisthash->{$tax} }[1 ... scalar(@{ $taxlisthash->{$tax} })] ) {
802       next unless ref($_) eq 'FS::cust_bill_pkg';
803      
804       my @cust_tax_exempt_pkg = splice( @{ $_->_cust_tax_exempt_pkg } );
805
806       next unless @cust_tax_exempt_pkg; #just avoiding the prob when irrelevant?
807       die "can't distribute tax exemptions: no line item for ".  Dumper($_).
808           " in packagemap ". join(',', sort {$a<=>$b} keys %packagemap). "\n"
809         unless $packagemap{$_->pkgnum};
810
811       push @{ $packagemap{$_->pkgnum}->_cust_tax_exempt_pkg },
812            @cust_tax_exempt_pkg;
813     }
814   }
815
816   #consolidate and create tax line items
817   warn "consolidating and generating...\n" if $DEBUG > 2;
818   foreach my $taxname ( keys %taxname ) {
819     my $tax = 0;
820     my %seen = ();
821     my @cust_bill_pkg_tax_location = ();
822     my @cust_bill_pkg_tax_rate_location = ();
823     warn "adding $taxname\n" if $DEBUG > 1;
824     foreach my $taxitem ( @{ $taxname{$taxname} } ) {
825       next if $seen{$taxitem}++;
826       warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
827       $tax += $tax{$taxitem};
828       push @cust_bill_pkg_tax_location,
829         map { new FS::cust_bill_pkg_tax_location $_ }
830             @{ $tax_location{ $taxitem } };
831       push @cust_bill_pkg_tax_rate_location,
832         map { new FS::cust_bill_pkg_tax_rate_location $_ }
833             @{ $tax_rate_location{ $taxitem } };
834     }
835     next unless $tax;
836
837     $tax = sprintf('%.2f', $tax );
838   
839     my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
840                                                    'disabled'     => '',
841                                                  },
842                                );
843
844     my @display = ();
845     if ( $pkg_category and
846          $conf->config('invoice_latexsummary') ||
847          $conf->config('invoice_htmlsummary')
848        )
849     {
850
851       my %hash = (  'section' => $pkg_category->categoryname );
852       push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
853
854     }
855
856     push @tax_line_items, new FS::cust_bill_pkg {
857       'pkgnum'   => 0,
858       'setup'    => $tax,
859       'recur'    => 0,
860       'sdate'    => '',
861       'edate'    => '',
862       'itemdesc' => $taxname,
863       'display'  => \@display,
864       'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
865       'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
866     };
867
868   }
869
870   \@tax_line_items;
871 }
872
873 sub _make_lines {
874   my ($self, %params) = @_;
875
876   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
877
878   my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
879   my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
880   my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
881   my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
882   my $total_setup = $params{setup} or die "no setup accumulator specified";
883   my $total_recur = $params{recur} or die "no recur accumulator specified";
884   my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
885   my $time = $params{'time'} or die "no time specified";
886   my (%options) = %{$params{options}};
887
888   if ( $part_pkg->freq ne '1' and ($options{'freq_override'} || 0) > 0 ) {
889     # this should never happen
890     die 'freq_override billing attempted on non-monthly package '.
891       $cust_pkg->pkgnum;
892   }
893
894   my $dbh = dbh;
895   my $real_pkgpart = $params{real_pkgpart};
896   my %hash = $cust_pkg->hash;
897   my $old_cust_pkg = new FS::cust_pkg \%hash;
898
899   my @details = ();
900   my $lineitems = 0;
901
902   $cust_pkg->pkgpart($part_pkg->pkgpart);
903
904   ###
905   # bill setup
906   ###
907
908   my $setup = 0;
909   my $unitsetup = 0;
910   my @setup_discounts = ();
911   my %setup_param = ( 'discounts' => \@setup_discounts );
912   if (     ! $options{recurring_only}
913        and ! $options{cancel}
914        and ( $options{'resetup'}
915              || ( ! $cust_pkg->setup
916                   && ( ! $cust_pkg->start_date
917                        || $cust_pkg->start_date <= day_end($time)
918                      )
919                   && ( ! $conf->exists('disable_setup_suspended_pkgs')
920                        || ( $conf->exists('disable_setup_suspended_pkgs') &&
921                             ! $cust_pkg->getfield('susp')
922                           )
923                      )
924                 )
925            )
926      )
927   {
928     
929     warn "    bill setup\n" if $DEBUG > 1;
930
931     unless ( $cust_pkg->waive_setup ) {
932         $lineitems++;
933
934         $setup = eval { $cust_pkg->calc_setup( $time, \@details, \%setup_param ) };
935         return "$@ running calc_setup for $cust_pkg\n"
936           if $@;
937
938         $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
939     }
940
941     $cust_pkg->setfield('setup', $time)
942       unless $cust_pkg->setup;
943           #do need it, but it won't get written to the db
944           #|| $cust_pkg->pkgpart != $real_pkgpart;
945
946     $cust_pkg->setfield('start_date', '')
947       if $cust_pkg->start_date;
948
949   }
950
951   ###
952   # bill recurring fee
953   ### 
954
955   #XXX unit stuff here too
956   my $recur = 0;
957   my $unitrecur = 0;
958   my @recur_discounts = ();
959   my $sdate;
960   if (     ! $cust_pkg->start_date
961        and ( ! $cust_pkg->susp || $part_pkg->option('suspend_bill', 1) )
962        and
963             ( $part_pkg->freq ne '0' && ( $cust_pkg->bill || 0 ) <= day_end($time) )
964          || ( $part_pkg->plan eq 'voip_cdr'
965                && $part_pkg->option('bill_every_call')
966             )
967          || $options{cancel}
968   ) {
969
970     # XXX should this be a package event?  probably.  events are called
971     # at collection time at the moment, though...
972     $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
973       if $part_pkg->can('reset_usage') && !$options{'no_usage_reset'};
974       #don't want to reset usage just cause we want a line item??
975       #&& $part_pkg->pkgpart == $real_pkgpart;
976
977     warn "    bill recur\n" if $DEBUG > 1;
978     $lineitems++;
979
980     # XXX shared with $recur_prog
981     $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
982              || $cust_pkg->setup
983              || $time;
984
985     #over two params!  lets at least switch to a hashref for the rest...
986     my $increment_next_bill = ( $part_pkg->freq ne '0'
987                                 && ( $cust_pkg->getfield('bill') || 0 ) <= day_end($time)
988                                 && !$options{cancel}
989                               );
990     my %param = ( %setup_param,
991                   'precommit_hooks'     => $precommit_hooks,
992                   'increment_next_bill' => $increment_next_bill,
993                   'discounts'           => \@recur_discounts,
994                   'real_pkgpart'        => $real_pkgpart,
995                   'freq_override'       => $options{freq_override} || '',
996                   'setup_fee'           => 0,
997                 );
998
999     my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
1000
1001     # There may be some part_pkg for which this is wrong.  Only those
1002     # which can_discount are supported.
1003     # (the UI should prevent adding discounts to these at the moment)
1004
1005     warn "calling $method on cust_pkg ". $cust_pkg->pkgnum.
1006          " for pkgpart ". $cust_pkg->pkgpart.
1007          " with params ". join(' / ', map "$_=>$param{$_}", keys %param). "\n"
1008       if $DEBUG > 2;
1009            
1010     $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
1011     return "$@ running $method for $cust_pkg\n"
1012       if ( $@ );
1013
1014     if ( $increment_next_bill ) {
1015
1016       my $next_bill = $part_pkg->add_freq($sdate, $options{freq_override} || 0);
1017       return "unparsable frequency: ". $part_pkg->freq
1018         if $next_bill == -1;
1019   
1020       #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
1021       # only for figuring next bill date, nothing else, so, reset $sdate again
1022       # here
1023       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1024       #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
1025       $cust_pkg->last_bill($sdate);
1026
1027       $cust_pkg->setfield('bill', $next_bill );
1028
1029     }
1030
1031     if ( $param{'setup_fee'} ) {
1032       # Add an additional setup fee at the billing stage.
1033       # Used for prorate_defer_bill.
1034       $setup += $param{'setup_fee'};
1035       $unitsetup += $param{'setup_fee'};
1036       $lineitems++;
1037     }
1038
1039     if ( defined $param{'discount_left_setup'} ) {
1040         foreach my $discount_setup ( values %{$param{'discount_left_setup'}} ) {
1041             $setup -= $discount_setup;
1042         }
1043     }
1044
1045   }
1046
1047   warn "\$setup is undefined" unless defined($setup);
1048   warn "\$recur is undefined" unless defined($recur);
1049   warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1050   
1051   ###
1052   # If there's line items, create em cust_bill_pkg records
1053   # If $cust_pkg has been modified, update it (if we're a real pkgpart)
1054   ###
1055
1056   if ( $lineitems ) {
1057
1058     if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
1059       # hmm.. and if just the options are modified in some weird price plan?
1060   
1061       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
1062         if $DEBUG >1;
1063   
1064       my $error = $cust_pkg->replace( $old_cust_pkg,
1065                                       'depend_jobnum'=>$options{depend_jobnum},
1066                                       'options' => { $cust_pkg->options },
1067                                     )
1068         unless $options{no_commit};
1069       return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
1070         if $error; #just in case
1071     }
1072   
1073     $setup = sprintf( "%.2f", $setup );
1074     $recur = sprintf( "%.2f", $recur );
1075     if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1076       return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1077     }
1078     if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1079       return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1080     }
1081
1082     my $discount_show_always = $conf->exists('discount-show-always')
1083                                && (    ($setup == 0 && scalar(@setup_discounts))
1084                                     || ($recur == 0 && scalar(@recur_discounts))
1085                                   );
1086
1087     if (    $setup != 0
1088          || $recur != 0
1089          || (!$part_pkg->hidden && $options{has_hidden}) #include some $0 lines
1090          || $discount_show_always
1091          || ($setup == 0 && $cust_pkg->_X_show_zero('setup'))
1092          || ($recur == 0 && $cust_pkg->_X_show_zero('recur'))
1093        ) 
1094     {
1095
1096       warn "    charges (setup=$setup, recur=$recur); adding line items\n"
1097         if $DEBUG > 1;
1098
1099       my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
1100       if ( $DEBUG > 1 ) {
1101         warn "      adding customer package invoice detail: $_\n"
1102           foreach @cust_pkg_detail;
1103       }
1104       push @details, @cust_pkg_detail;
1105
1106       my $cust_bill_pkg = new FS::cust_bill_pkg {
1107         'pkgnum'    => $cust_pkg->pkgnum,
1108         'setup'     => $setup,
1109         'unitsetup' => $unitsetup,
1110         'recur'     => $recur,
1111         'unitrecur' => $unitrecur,
1112         'quantity'  => $cust_pkg->quantity,
1113         'details'   => \@details,
1114         'discounts' => [ @setup_discounts, @recur_discounts ],
1115         'hidden'    => $part_pkg->hidden,
1116         'freq'      => $part_pkg->freq,
1117       };
1118
1119       if ( $part_pkg->option('prorate_defer_bill',1) 
1120            and !$hash{last_bill} ) {
1121         # both preceding and upcoming, technically
1122         $cust_bill_pkg->sdate( $cust_pkg->setup );
1123         $cust_bill_pkg->edate( $cust_pkg->bill );
1124       } elsif ( $part_pkg->recur_temporality eq 'preceding' ) {
1125         $cust_bill_pkg->sdate( $hash{last_bill} );
1126         $cust_bill_pkg->edate( $sdate - 86399   ); #60s*60m*24h-1
1127         $cust_bill_pkg->edate( $time ) if $options{cancel};
1128       } else { #if ( $part_pkg->recur_temporality eq 'upcoming' ) {
1129         $cust_bill_pkg->sdate( $sdate );
1130         $cust_bill_pkg->edate( $cust_pkg->bill );
1131         #$cust_bill_pkg->edate( $time ) if $options{cancel};
1132       }
1133
1134       $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
1135         unless $part_pkg->pkgpart == $real_pkgpart;
1136
1137       $$total_setup += $setup;
1138       $$total_recur += $recur;
1139
1140       ###
1141       # handle taxes
1142       ###
1143
1144       unless ( $discount_show_always ) {
1145           my $error = 
1146             $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
1147           return $error if $error;
1148       }
1149
1150       push @$cust_bill_pkgs, $cust_bill_pkg;
1151
1152     } #if $setup != 0 || $recur != 0
1153       
1154   } #if $line_items
1155
1156   '';
1157
1158 }
1159
1160 sub _handle_taxes {
1161   my $self = shift;
1162   my $part_pkg = shift;
1163   my $taxlisthash = shift;
1164   my $cust_bill_pkg = shift;
1165   my $cust_pkg = shift;
1166   my $invoice_time = shift;
1167   my $real_pkgpart = shift;
1168   my $options = shift;
1169
1170   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1171
1172   my %cust_bill_pkg = ();
1173   my %taxes = ();
1174     
1175   my @classes;
1176   #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
1177   push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
1178   push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
1179   push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
1180
1181   if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
1182
1183     if ( $conf->exists('enable_taxproducts')
1184          && ( scalar($part_pkg->part_pkg_taxoverride)
1185               || $part_pkg->has_taxproduct
1186             )
1187        )
1188     {
1189
1190       foreach my $class (@classes) {
1191         my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $cust_pkg );
1192         return $err_or_ref unless ref($err_or_ref);
1193         $taxes{$class} = $err_or_ref;
1194       }
1195
1196       unless (exists $taxes{''}) {
1197         my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $cust_pkg );
1198         return $err_or_ref unless ref($err_or_ref);
1199         $taxes{''} = $err_or_ref;
1200       }
1201
1202     } else {
1203
1204       my @loc_keys = qw( district city county state country );
1205       my %taxhash;
1206       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
1207         my $cust_location = $cust_pkg->cust_location;
1208         %taxhash = map { $_ => $cust_location->$_()    } @loc_keys;
1209       } else {
1210         my $prefix = 
1211           ( $conf->exists('tax-ship_address') && length($self->ship_last) )
1212           ? 'ship_'
1213           : '';
1214         %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
1215       }
1216
1217       $taxhash{'taxclass'} = $part_pkg->taxclass;
1218
1219       my @taxes = ();
1220       my %taxhash_elim = %taxhash;
1221       my @elim = qw( district city county state );
1222       do { 
1223
1224         #first try a match with taxclass
1225         @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
1226
1227         if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
1228           #then try a match without taxclass
1229           my %no_taxclass = %taxhash_elim;
1230           $no_taxclass{ 'taxclass' } = '';
1231           @taxes = qsearch( 'cust_main_county', \%no_taxclass );
1232         }
1233
1234         $taxhash_elim{ shift(@elim) } = '';
1235
1236       } while ( !scalar(@taxes) && scalar(@elim) );
1237
1238       @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
1239                     @taxes
1240         if $self->cust_main_exemption; #just to be safe
1241
1242       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
1243         foreach (@taxes) {
1244           $_->set('pkgnum',      $cust_pkg->pkgnum );
1245           $_->set('locationnum', $cust_pkg->locationnum );
1246         }
1247       }
1248
1249       $taxes{''} = [ @taxes ];
1250       $taxes{'setup'} = [ @taxes ];
1251       $taxes{'recur'} = [ @taxes ];
1252       $taxes{$_} = [ @taxes ] foreach (@classes);
1253
1254       # # maybe eliminate this entirely, along with all the 0% records
1255       # unless ( @taxes ) {
1256       #   return
1257       #     "fatal: can't find tax rate for state/county/country/taxclass ".
1258       #     join('/', map $taxhash{$_}, qw(state county country taxclass) );
1259       # }
1260
1261     } #if $conf->exists('enable_taxproducts') ...
1262
1263   }
1264
1265   #what's this doing in the middle of _handle_taxes?  probably should split
1266   #this into three parts above in _make_lines
1267   $cust_bill_pkg->set_display(   part_pkg     => $part_pkg,
1268                                  real_pkgpart => $real_pkgpart,
1269                              );
1270
1271   my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
1272   foreach my $key (keys %tax_cust_bill_pkg) {
1273     my @taxes = @{ $taxes{$key} || [] };
1274     my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
1275
1276     my %localtaxlisthash = ();
1277     foreach my $tax ( @taxes ) {
1278
1279       my $taxname = ref( $tax ). ' '. $tax->taxnum;
1280 #      $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
1281 #                  ' locationnum'. $cust_pkg->locationnum
1282 #        if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
1283
1284       $taxlisthash->{ $taxname } ||= [ $tax ];
1285       push @{ $taxlisthash->{ $taxname  } }, $tax_cust_bill_pkg;
1286
1287       $localtaxlisthash{ $taxname } ||= [ $tax ];
1288       push @{ $localtaxlisthash{ $taxname  } }, $tax_cust_bill_pkg;
1289
1290     }
1291
1292     warn "finding taxed taxes...\n" if $DEBUG > 2;
1293     foreach my $tax ( keys %localtaxlisthash ) {
1294       my $tax_object = shift @{ $localtaxlisthash{$tax} };
1295       warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
1296         if $DEBUG > 2;
1297       next unless $tax_object->can('tax_on_tax');
1298
1299       foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
1300         my $totname = ref( $tot ). ' '. $tot->taxnum;
1301
1302         warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
1303           if $DEBUG > 2;
1304         next unless exists( $localtaxlisthash{ $totname } ); # only increase
1305                                                              # existing taxes
1306         warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
1307         my $hashref_or_error = 
1308           $tax_object->taxline( $localtaxlisthash{$tax},
1309                                 'custnum'      => $self->custnum,
1310                                 'invoice_time' => $invoice_time,
1311                               );
1312         return $hashref_or_error
1313           unless ref($hashref_or_error);
1314         
1315         $taxlisthash->{ $totname } ||= [ $tot ];
1316         push @{ $taxlisthash->{ $totname  } }, $hashref_or_error->{amount};
1317
1318       }
1319     }
1320
1321   }
1322
1323   '';
1324 }
1325
1326 sub _gather_taxes {
1327   my $self = shift;
1328   my $part_pkg = shift;
1329   my $class = shift;
1330   my $cust_pkg = shift;
1331
1332   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1333
1334   my $geocode;
1335   if ( $cust_pkg->locationnum && $conf->exists('tax-pkg_address') ) {
1336     $geocode = $cust_pkg->cust_location->geocode('cch');
1337   } else {
1338     $geocode = $self->geocode('cch');
1339   }
1340
1341   my @taxes = ();
1342
1343   my @taxclassnums = map { $_->taxclassnum }
1344                      $part_pkg->part_pkg_taxoverride($class);
1345
1346   unless (@taxclassnums) {
1347     @taxclassnums = map { $_->taxclassnum }
1348                     grep { $_->taxable eq 'Y' }
1349                     $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
1350   }
1351   warn "Found taxclassnum values of ". join(',', @taxclassnums)
1352     if $DEBUG;
1353
1354   my $extra_sql =
1355     "AND (".
1356     join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
1357
1358   @taxes = qsearch({ 'table' => 'tax_rate',
1359                      'hashref' => { 'geocode' => $geocode, },
1360                      'extra_sql' => $extra_sql,
1361                   })
1362     if scalar(@taxclassnums);
1363
1364   warn "Found taxes ".
1365        join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n" 
1366    if $DEBUG;
1367
1368   [ @taxes ];
1369
1370 }
1371
1372 =item collect [ HASHREF | OPTION => VALUE ... ]
1373
1374 (Attempt to) collect money for this customer's outstanding invoices (see
1375 L<FS::cust_bill>).  Usually used after the bill method.
1376
1377 Actions are now triggered by billing events; see L<FS::part_event> and the
1378 billing events web interface.  Old-style invoice events (see
1379 L<FS::part_bill_event>) have been deprecated.
1380
1381 If there is an error, returns the error, otherwise returns false.
1382
1383 Options are passed as name-value pairs.
1384
1385 Currently available options are:
1386
1387 =over 4
1388
1389 =item invoice_time
1390
1391 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.
1392
1393 =item retry
1394
1395 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1396
1397 =item check_freq
1398
1399 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1400
1401 =item quiet
1402
1403 set true to surpress email card/ACH decline notices.
1404
1405 =item debug
1406
1407 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)
1408
1409 =back
1410
1411 # =item payby
1412 #
1413 # allows for one time override of normal customer billing method
1414
1415 =cut
1416
1417 sub collect {
1418   my( $self, %options ) = @_;
1419
1420   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1421
1422   my $invoice_time = $options{'invoice_time'} || time;
1423
1424   #put below somehow?
1425   local $SIG{HUP} = 'IGNORE';
1426   local $SIG{INT} = 'IGNORE';
1427   local $SIG{QUIT} = 'IGNORE';
1428   local $SIG{TERM} = 'IGNORE';
1429   local $SIG{TSTP} = 'IGNORE';
1430   local $SIG{PIPE} = 'IGNORE';
1431
1432   my $oldAutoCommit = $FS::UID::AutoCommit;
1433   local $FS::UID::AutoCommit = 0;
1434   my $dbh = dbh;
1435
1436   $self->select_for_update; #mutex
1437
1438   if ( $DEBUG ) {
1439     my $balance = $self->balance;
1440     warn "$me collect customer ". $self->custnum. ": balance $balance\n"
1441   }
1442
1443   if ( exists($options{'retry_card'}) ) {
1444     carp 'retry_card option passed to collect is deprecated; use retry';
1445     $options{'retry'} ||= $options{'retry_card'};
1446   }
1447   if ( exists($options{'retry'}) && $options{'retry'} ) {
1448     my $error = $self->retry_realtime;
1449     if ( $error ) {
1450       $dbh->rollback if $oldAutoCommit;
1451       return $error;
1452     }
1453   }
1454
1455   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1456
1457   #never want to roll back an event just because it returned an error
1458   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1459
1460   $self->do_cust_event(
1461     'debug'      => ( $options{'debug'} || 0 ),
1462     'time'       => $invoice_time,
1463     'check_freq' => $options{'check_freq'},
1464     'stage'      => 'collect',
1465   );
1466
1467 }
1468
1469 =item retry_realtime
1470
1471 Schedules realtime / batch  credit card / electronic check / LEC billing
1472 events for for retry.  Useful if card information has changed or manual
1473 retry is desired.  The 'collect' method must be called to actually retry
1474 the transaction.
1475
1476 Implementation details: For either this customer, or for each of this
1477 customer's open invoices, changes the status of the first "done" (with
1478 statustext error) realtime processing event to "failed".
1479
1480 =cut
1481
1482 sub retry_realtime {
1483   my $self = shift;
1484
1485   local $SIG{HUP} = 'IGNORE';
1486   local $SIG{INT} = 'IGNORE';
1487   local $SIG{QUIT} = 'IGNORE';
1488   local $SIG{TERM} = 'IGNORE';
1489   local $SIG{TSTP} = 'IGNORE';
1490   local $SIG{PIPE} = 'IGNORE';
1491
1492   my $oldAutoCommit = $FS::UID::AutoCommit;
1493   local $FS::UID::AutoCommit = 0;
1494   my $dbh = dbh;
1495
1496   #a little false laziness w/due_cust_event (not too bad, really)
1497
1498   my $join = FS::part_event_condition->join_conditions_sql;
1499   my $order = FS::part_event_condition->order_conditions_sql;
1500   my $mine = 
1501   '( '
1502    . join ( ' OR ' , map { 
1503     my $cust_join = FS::part_event->eventtables_cust_join->{$_} || '';
1504     my $custnum = FS::part_event->eventtables_custnum->{$_};
1505     "( part_event.eventtable = " . dbh->quote($_) 
1506     . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key 
1507     . " from $_ $cust_join"
1508     . " where $custnum = " . dbh->quote( $self->custnum ) . "))" ;
1509    } FS::part_event->eventtables)
1510    . ') ';
1511
1512   #here is the agent virtualization
1513   my $agent_virt = " (    part_event.agentnum IS NULL
1514                        OR part_event.agentnum = ". $self->agentnum. ' )';
1515
1516   #XXX this shouldn't be hardcoded, actions should declare it...
1517   my @realtime_events = qw(
1518     cust_bill_realtime_card
1519     cust_bill_realtime_check
1520     cust_bill_realtime_lec
1521     cust_bill_batch
1522   );
1523
1524   my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
1525                                                   @realtime_events
1526                                      ).
1527                           ' ) ';
1528
1529   my @cust_event = qsearch({
1530     'table'     => 'cust_event',
1531     'select'    => 'cust_event.*',
1532     'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
1533     'hashref'   => { 'status' => 'done' },
1534     'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
1535                    " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
1536   });
1537
1538   my %seen_invnum = ();
1539   foreach my $cust_event (@cust_event) {
1540
1541     #max one for the customer, one for each open invoice
1542     my $cust_X = $cust_event->cust_X;
1543     next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
1544                           ? $cust_X->invnum
1545                           : 0
1546                         }++
1547          or $cust_event->part_event->eventtable eq 'cust_bill'
1548             && ! $cust_X->owed;
1549
1550     my $error = $cust_event->retry;
1551     if ( $error ) {
1552       $dbh->rollback if $oldAutoCommit;
1553       return "error scheduling event for retry: $error";
1554     }
1555
1556   }
1557
1558   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1559   '';
1560
1561 }
1562
1563 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
1564
1565 Runs billing events; see L<FS::part_event> and the billing events web
1566 interface.
1567
1568 If there is an error, returns the error, otherwise returns false.
1569
1570 Options are passed as name-value pairs.
1571
1572 Currently available options are:
1573
1574 =over 4
1575
1576 =item time
1577
1578 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.
1579
1580 =item check_freq
1581
1582 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1583
1584 =item stage
1585
1586 "collect" (the default) or "pre-bill"
1587
1588 =item quiet
1589  
1590 set true to surpress email card/ACH decline notices.
1591
1592 =item debug
1593
1594 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)
1595
1596 =back
1597 =cut
1598
1599 # =item payby
1600 #
1601 # allows for one time override of normal customer billing method
1602
1603 # =item retry
1604 #
1605 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1606
1607 sub do_cust_event {
1608   my( $self, %options ) = @_;
1609
1610   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1611
1612   my $time = $options{'time'} || time;
1613
1614   #put below somehow?
1615   local $SIG{HUP} = 'IGNORE';
1616   local $SIG{INT} = 'IGNORE';
1617   local $SIG{QUIT} = 'IGNORE';
1618   local $SIG{TERM} = 'IGNORE';
1619   local $SIG{TSTP} = 'IGNORE';
1620   local $SIG{PIPE} = 'IGNORE';
1621
1622   my $oldAutoCommit = $FS::UID::AutoCommit;
1623   local $FS::UID::AutoCommit = 0;
1624   my $dbh = dbh;
1625
1626   $self->select_for_update; #mutex
1627
1628   if ( $DEBUG ) {
1629     my $balance = $self->balance;
1630     warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
1631   }
1632
1633 #  if ( exists($options{'retry_card'}) ) {
1634 #    carp 'retry_card option passed to collect is deprecated; use retry';
1635 #    $options{'retry'} ||= $options{'retry_card'};
1636 #  }
1637 #  if ( exists($options{'retry'}) && $options{'retry'} ) {
1638 #    my $error = $self->retry_realtime;
1639 #    if ( $error ) {
1640 #      $dbh->rollback if $oldAutoCommit;
1641 #      return $error;
1642 #    }
1643 #  }
1644
1645   # false laziness w/pay_batch::import_results
1646
1647   my $due_cust_event = $self->due_cust_event(
1648     'debug'      => ( $options{'debug'} || 0 ),
1649     'time'       => $time,
1650     'check_freq' => $options{'check_freq'},
1651     'stage'      => ( $options{'stage'} || 'collect' ),
1652   );
1653   unless( ref($due_cust_event) ) {
1654     $dbh->rollback if $oldAutoCommit;
1655     return $due_cust_event;
1656   }
1657
1658   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1659   #never want to roll back an event just because it or a different one
1660   # returned an error
1661   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1662
1663   foreach my $cust_event ( @$due_cust_event ) {
1664
1665     #XXX lock event
1666     
1667     #re-eval event conditions (a previous event could have changed things)
1668     unless ( $cust_event->test_conditions ) {
1669       #don't leave stray "new/locked" records around
1670       my $error = $cust_event->delete;
1671       return $error if $error;
1672       next;
1673     }
1674
1675     {
1676       local $FS::cust_main::Billing_Realtime::realtime_bop_decline_quiet = 1
1677         if $options{'quiet'};
1678       warn "  running cust_event ". $cust_event->eventnum. "\n"
1679         if $DEBUG > 1;
1680
1681       #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
1682       if ( my $error = $cust_event->do_event( 'time' => $time ) ) {
1683         #XXX wtf is this?  figure out a proper dealio with return value
1684         #from do_event
1685         return $error;
1686       }
1687     }
1688
1689   }
1690
1691   '';
1692
1693 }
1694
1695 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
1696
1697 Inserts database records for and returns an ordered listref of new events due
1698 for this customer, as FS::cust_event objects (see L<FS::cust_event>).  If no
1699 events are due, an empty listref is returned.  If there is an error, returns a
1700 scalar error message.
1701
1702 To actually run the events, call each event's test_condition method, and if
1703 still true, call the event's do_event method.
1704
1705 Options are passed as a hashref or as a list of name-value pairs.  Available
1706 options are:
1707
1708 =over 4
1709
1710 =item check_freq
1711
1712 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.
1713
1714 =item stage
1715
1716 "collect" (the default) or "pre-bill"
1717
1718 =item time
1719
1720 "Current time" for the events.
1721
1722 =item debug
1723
1724 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)
1725
1726 =item eventtable
1727
1728 Only return events for the specified eventtable (by default, events of all eventtables are returned)
1729
1730 =item objects
1731
1732 Explicitly pass the objects to be tested (typically used with eventtable).
1733
1734 =item testonly
1735
1736 Set to true to return the objects, but not actually insert them into the
1737 database.
1738
1739 =back
1740
1741 =cut
1742
1743 sub due_cust_event {
1744   my $self = shift;
1745   my %opt = ref($_[0]) ? %{ $_[0] } : @_;
1746
1747   #???
1748   #my $DEBUG = $opt{'debug'}
1749   local($DEBUG) = $opt{'debug'}
1750     if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
1751   $DEBUG = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1752
1753   warn "$me due_cust_event called with options ".
1754        join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
1755     if $DEBUG;
1756
1757   $opt{'time'} ||= time;
1758
1759   local $SIG{HUP} = 'IGNORE';
1760   local $SIG{INT} = 'IGNORE';
1761   local $SIG{QUIT} = 'IGNORE';
1762   local $SIG{TERM} = 'IGNORE';
1763   local $SIG{TSTP} = 'IGNORE';
1764   local $SIG{PIPE} = 'IGNORE';
1765
1766   my $oldAutoCommit = $FS::UID::AutoCommit;
1767   local $FS::UID::AutoCommit = 0;
1768   my $dbh = dbh;
1769
1770   $self->select_for_update #mutex
1771     unless $opt{testonly};
1772
1773   ###
1774   # find possible events (initial search)
1775   ###
1776   
1777   my @cust_event = ();
1778
1779   my @eventtable = $opt{'eventtable'}
1780                      ? ( $opt{'eventtable'} )
1781                      : FS::part_event->eventtables_runorder;
1782
1783   my $check_freq = $opt{'check_freq'} || '1d';
1784
1785   foreach my $eventtable ( @eventtable ) {
1786
1787     my @objects;
1788     if ( $opt{'objects'} ) {
1789
1790       @objects = @{ $opt{'objects'} };
1791
1792     } elsif ( $eventtable eq 'cust_main' ) {
1793
1794       @objects = ( $self );
1795
1796     } else {
1797
1798       my $cm_join = " LEFT JOIN cust_main USING ( custnum )";
1799       # linkage not needed here because FS::cust_main->$eventtable will 
1800       # already supply it
1801
1802       #some false laziness w/Cron::bill bill_where
1803
1804       my $join  = FS::part_event_condition->join_conditions_sql( $eventtable);
1805       my $where = FS::part_event_condition->where_conditions_sql($eventtable,
1806         'time'=>$opt{'time'},
1807       );
1808       $where = $where ? "AND $where" : '';
1809
1810       my $are_part_event = 
1811       "EXISTS ( SELECT 1 FROM part_event $join
1812         WHERE check_freq = '$check_freq'
1813         AND eventtable = '$eventtable'
1814         AND ( disabled = '' OR disabled IS NULL )
1815         $where
1816         )
1817       ";
1818       #eofalse
1819
1820       @objects = $self->$eventtable(
1821         'addl_from' => $cm_join,
1822         'extra_sql' => " AND $are_part_event",
1823       );
1824     } # if ( !$opt{objects} and $eventtable ne 'cust_main' )
1825
1826     my @e_cust_event = ();
1827
1828     my $linkage = FS::part_event->eventtables_cust_join->{$eventtable} || '';
1829
1830     my $cross = "CROSS JOIN $eventtable $linkage";
1831     $cross .= ' LEFT JOIN cust_main USING ( custnum )'
1832       unless $eventtable eq 'cust_main';
1833
1834     foreach my $object ( @objects ) {
1835
1836       #this first search uses the condition_sql magic for optimization.
1837       #the more possible events we can eliminate in this step the better
1838
1839       my $cross_where = '';
1840       my $pkey = $object->primary_key;
1841       $cross_where = "$eventtable.$pkey = ". $object->$pkey();
1842
1843       my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
1844       my $extra_sql =
1845         FS::part_event_condition->where_conditions_sql( $eventtable,
1846                                                         'time'=>$opt{'time'}
1847                                                       );
1848       my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
1849
1850       $extra_sql = "AND $extra_sql" if $extra_sql;
1851
1852       #here is the agent virtualization
1853       $extra_sql .= " AND (    part_event.agentnum IS NULL
1854                             OR part_event.agentnum = ". $self->agentnum. ' )';
1855
1856       $extra_sql .= " $order";
1857
1858       warn "searching for events for $eventtable ". $object->$pkey. "\n"
1859         if $opt{'debug'} > 2;
1860       my @part_event = qsearch( {
1861         'debug'     => ( $opt{'debug'} > 3 ? 1 : 0 ),
1862         'select'    => 'part_event.*',
1863         'table'     => 'part_event',
1864         'addl_from' => "$cross $join",
1865         'hashref'   => { 'check_freq' => $check_freq,
1866                          'eventtable' => $eventtable,
1867                          'disabled'   => '',
1868                        },
1869         'extra_sql' => "AND $cross_where $extra_sql",
1870       } );
1871
1872       if ( $DEBUG > 2 ) {
1873         my $pkey = $object->primary_key;
1874         warn "      ". scalar(@part_event).
1875              " possible events found for $eventtable ". $object->$pkey(). "\n";
1876       }
1877
1878       push @e_cust_event, map { 
1879         $_->new_cust_event($object, 'time' => $opt{'time'}) 
1880       } @part_event;
1881
1882     }
1883
1884     warn "    ". scalar(@e_cust_event).
1885          " subtotal possible cust events found for $eventtable\n"
1886       if $DEBUG > 1;
1887
1888     push @cust_event, @e_cust_event;
1889
1890   }
1891
1892   warn "  ". scalar(@cust_event).
1893        " total possible cust events found in initial search\n"
1894     if $DEBUG; # > 1;
1895
1896
1897   ##
1898   # test stage
1899   ##
1900
1901   $opt{stage} ||= 'collect';
1902   @cust_event =
1903     grep { my $stage = $_->part_event->event_stage;
1904            $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
1905          }
1906          @cust_event;
1907
1908   ##
1909   # test conditions
1910   ##
1911   
1912   my %unsat = ();
1913
1914   @cust_event = grep $_->test_conditions( 'stats_hashref' => \%unsat ),
1915                      @cust_event;
1916
1917   warn "  ". scalar(@cust_event). " cust events left satisfying conditions\n"
1918     if $DEBUG; # > 1;
1919
1920   warn "    invalid conditions not eliminated with condition_sql:\n".
1921        join('', map "      $_: ".$unsat{$_}."\n", keys %unsat )
1922     if keys %unsat && $DEBUG; # > 1;
1923
1924   ##
1925   # insert
1926   ##
1927
1928   unless( $opt{testonly} ) {
1929     foreach my $cust_event ( @cust_event ) {
1930
1931       my $error = $cust_event->insert();
1932       if ( $error ) {
1933         $dbh->rollback if $oldAutoCommit;
1934         return $error;
1935       }
1936                                        
1937     }
1938   }
1939
1940   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1941
1942   ##
1943   # return
1944   ##
1945
1946   warn "  returning events: ". Dumper(@cust_event). "\n"
1947     if $DEBUG > 2;
1948
1949   \@cust_event;
1950
1951 }
1952
1953 =item apply_payments_and_credits [ OPTION => VALUE ... ]
1954
1955 Applies unapplied payments and credits.
1956
1957 In most cases, this new method should be used in place of sequential
1958 apply_payments and apply_credits methods.
1959
1960 A hash of optional arguments may be passed.  Currently "manual" is supported.
1961 If true, a payment receipt is sent instead of a statement when
1962 'payment_receipt_email' configuration option is set.
1963
1964 If there is an error, returns the error, otherwise returns false.
1965
1966 =cut
1967
1968 sub apply_payments_and_credits {
1969   my( $self, %options ) = @_;
1970
1971   local $SIG{HUP} = 'IGNORE';
1972   local $SIG{INT} = 'IGNORE';
1973   local $SIG{QUIT} = 'IGNORE';
1974   local $SIG{TERM} = 'IGNORE';
1975   local $SIG{TSTP} = 'IGNORE';
1976   local $SIG{PIPE} = 'IGNORE';
1977
1978   my $oldAutoCommit = $FS::UID::AutoCommit;
1979   local $FS::UID::AutoCommit = 0;
1980   my $dbh = dbh;
1981
1982   $self->select_for_update; #mutex
1983
1984   foreach my $cust_bill ( $self->open_cust_bill ) {
1985     my $error = $cust_bill->apply_payments_and_credits(%options);
1986     if ( $error ) {
1987       $dbh->rollback if $oldAutoCommit;
1988       return "Error applying: $error";
1989     }
1990   }
1991
1992   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1993   ''; #no error
1994
1995 }
1996
1997 =item apply_credits OPTION => VALUE ...
1998
1999 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2000 to outstanding invoice balances in chronological order (or reverse
2001 chronological order if the I<order> option is set to B<newest>) and returns the
2002 value of any remaining unapplied credits available for refund (see
2003 L<FS::cust_refund>).
2004
2005 Dies if there is an error.
2006
2007 =cut
2008
2009 sub apply_credits {
2010   my $self = shift;
2011   my %opt = @_;
2012
2013   local $SIG{HUP} = 'IGNORE';
2014   local $SIG{INT} = 'IGNORE';
2015   local $SIG{QUIT} = 'IGNORE';
2016   local $SIG{TERM} = 'IGNORE';
2017   local $SIG{TSTP} = 'IGNORE';
2018   local $SIG{PIPE} = 'IGNORE';
2019
2020   my $oldAutoCommit = $FS::UID::AutoCommit;
2021   local $FS::UID::AutoCommit = 0;
2022   my $dbh = dbh;
2023
2024   $self->select_for_update; #mutex
2025
2026   unless ( $self->total_unapplied_credits ) {
2027     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2028     return 0;
2029   }
2030
2031   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2032       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2033
2034   my @invoices = $self->open_cust_bill;
2035   @invoices = sort { $b->_date <=> $a->_date } @invoices
2036     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2037
2038   if ( $conf->exists('pkg-balances') ) {
2039     # limit @credits to those w/ a pkgnum grepped from $self
2040     my %pkgnums = ();
2041     foreach my $i (@invoices) {
2042       foreach my $li ( $i->cust_bill_pkg ) {
2043         $pkgnums{$li->pkgnum} = 1;
2044       }
2045     }
2046     @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
2047   }
2048
2049   my $credit;
2050
2051   foreach my $cust_bill ( @invoices ) {
2052
2053     if ( !defined($credit) || $credit->credited == 0) {
2054       $credit = pop @credits or last;
2055     }
2056
2057     my $owed;
2058     if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
2059       $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
2060     } else {
2061       $owed = $cust_bill->owed;
2062     }
2063     unless ( $owed > 0 ) {
2064       push @credits, $credit;
2065       next;
2066     }
2067
2068     my $amount = min( $credit->credited, $owed );
2069     
2070     my $cust_credit_bill = new FS::cust_credit_bill ( {
2071       'crednum' => $credit->crednum,
2072       'invnum'  => $cust_bill->invnum,
2073       'amount'  => $amount,
2074     } );
2075     $cust_credit_bill->pkgnum( $credit->pkgnum )
2076       if $conf->exists('pkg-balances') && $credit->pkgnum;
2077     my $error = $cust_credit_bill->insert;
2078     if ( $error ) {
2079       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2080       die $error;
2081     }
2082     
2083     redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2084
2085   }
2086
2087   my $total_unapplied_credits = $self->total_unapplied_credits;
2088
2089   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2090
2091   return $total_unapplied_credits;
2092 }
2093
2094 =item apply_payments  [ OPTION => VALUE ... ]
2095
2096 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2097 to outstanding invoice balances in chronological order.
2098
2099  #and returns the value of any remaining unapplied payments.
2100
2101 A hash of optional arguments may be passed.  Currently "manual" is supported.
2102 If true, a payment receipt is sent instead of a statement when
2103 'payment_receipt_email' configuration option is set.
2104
2105 Dies if there is an error.
2106
2107 =cut
2108
2109 sub apply_payments {
2110   my( $self, %options ) = @_;
2111
2112   local $SIG{HUP} = 'IGNORE';
2113   local $SIG{INT} = 'IGNORE';
2114   local $SIG{QUIT} = 'IGNORE';
2115   local $SIG{TERM} = 'IGNORE';
2116   local $SIG{TSTP} = 'IGNORE';
2117   local $SIG{PIPE} = 'IGNORE';
2118
2119   my $oldAutoCommit = $FS::UID::AutoCommit;
2120   local $FS::UID::AutoCommit = 0;
2121   my $dbh = dbh;
2122
2123   $self->select_for_update; #mutex
2124
2125   #return 0 unless
2126
2127   my @payments = sort { $b->_date <=> $a->_date }
2128                  grep { $_->unapplied > 0 }
2129                  $self->cust_pay;
2130
2131   my @invoices = sort { $a->_date <=> $b->_date}
2132                  grep { $_->owed > 0 }
2133                  $self->cust_bill;
2134
2135   if ( $conf->exists('pkg-balances') ) {
2136     # limit @payments to those w/ a pkgnum grepped from $self
2137     my %pkgnums = ();
2138     foreach my $i (@invoices) {
2139       foreach my $li ( $i->cust_bill_pkg ) {
2140         $pkgnums{$li->pkgnum} = 1;
2141       }
2142     }
2143     @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
2144   }
2145
2146   my $payment;
2147
2148   foreach my $cust_bill ( @invoices ) {
2149
2150     if ( !defined($payment) || $payment->unapplied == 0 ) {
2151       $payment = pop @payments or last;
2152     }
2153
2154     my $owed;
2155     if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
2156       $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
2157     } else {
2158       $owed = $cust_bill->owed;
2159     }
2160     unless ( $owed > 0 ) {
2161       push @payments, $payment;
2162       next;
2163     }
2164
2165     my $amount = min( $payment->unapplied, $owed );
2166
2167     my $cbp = {
2168       'paynum' => $payment->paynum,
2169       'invnum' => $cust_bill->invnum,
2170       'amount' => $amount,
2171     };
2172     $cbp->{_date} = $payment->_date 
2173         if $options{'manual'} && $options{'backdate_application'};
2174     my $cust_bill_pay = new FS::cust_bill_pay($cbp);
2175     $cust_bill_pay->pkgnum( $payment->pkgnum )
2176       if $conf->exists('pkg-balances') && $payment->pkgnum;
2177     my $error = $cust_bill_pay->insert(%options);
2178     if ( $error ) {
2179       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2180       die $error;
2181     }
2182
2183     redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2184
2185   }
2186
2187   my $total_unapplied_payments = $self->total_unapplied_payments;
2188
2189   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2190
2191   return $total_unapplied_payments;
2192 }
2193
2194 =back
2195
2196 =head1 FLOW
2197
2198   bill_and_collect
2199
2200     cancel_expired_pkgs
2201     suspend_adjourned_pkgs
2202     unsuspend_resumed_pkgs
2203
2204     bill
2205       (do_cust_event pre-bill)
2206       _make_lines
2207         _handle_taxes
2208           (vendor-only) _gather_taxes
2209       _omit_zero_value_bundles
2210       calculate_taxes
2211
2212     apply_payments_and_credits
2213     collect
2214       do_cust_event
2215         due_cust_event
2216
2217 =head1 BUGS
2218
2219 =head1 SEE ALSO
2220
2221 L<FS::cust_main>, L<FS::cust_main::Billing_Realtime>
2222
2223 =cut
2224
2225 1;