tax calculation and reporting for new customer locations, #940
[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   # $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
728
729   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
730
731   warn "$me calculate_taxes\n"
732        #.Dumper($self, $cust_bill_pkg, $taxlisthash, $invoice_time). "\n"
733     if $DEBUG > 2;
734
735   my @tax_line_items = ();
736
737   # keys are tax names (as printed on invoices / itemdesc )
738   # values are arrayrefs of taxlisthash keys (internal identifiers)
739   my %taxname = ();
740
741   # keys are taxlisthash keys (internal identifiers)
742   # values are (cumulative) amounts
743   my %tax_amount = ();
744
745   # keys are taxlisthash keys (internal identifiers)
746   # values are arrayrefs of cust_bill_pkg_tax_location hashrefs
747   my %tax_location = ();
748
749   # keys are taxlisthash keys (internal identifiers)
750   # values are arrayrefs of cust_bill_pkg_tax_rate_location hashrefs
751   my %tax_rate_location = ();
752
753   # keys are taxnums (not internal identifiers!)
754   # values are arrayrefs of cust_tax_exempt_pkg objects
755   my %tax_exemption;
756
757   foreach my $tax ( keys %$taxlisthash ) {
758     # $tax is a tax identifier
759     my $tax_object = shift @{ $taxlisthash->{$tax} };
760     # $tax_object is a cust_main_county or tax_rate 
761     # (with pkgnum and locationnum set)
762     # the rest of @{ $taxlisthash->{$tax} } is cust_bill_pkg objects
763     warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
764     warn " ". join('/', @{ $taxlisthash->{$tax} } ). "\n" if $DEBUG > 2;
765     # taxline calculates the tax on all cust_bill_pkgs in the 
766     # first (arrayref) argument, and returns a hashref of 'name' 
767     # (the line item description) and 'amount'.
768     # It also calculates exemptions and attaches them to the cust_bill_pkgs
769     # in the argument.
770     my $taxables = $taxlisthash->{$tax};
771     my $exemptions = $tax_exemption{$tax_object->taxnum} ||= [];
772     my $hashref_or_error =
773       $tax_object->taxline( $taxables,
774                             'custnum'      => $self->custnum,
775                             'invoice_time' => $invoice_time,
776                             'exemptions'   => $exemptions,
777                           );
778     return $hashref_or_error unless ref($hashref_or_error);
779
780     # then collect any new exemptions generated for this tax
781     push @$exemptions, @{ $_->cust_tax_exempt_pkg }
782       foreach @$taxables;
783
784     unshift @{ $taxlisthash->{$tax} }, $tax_object;
785
786     my $name   = $hashref_or_error->{'name'};
787     my $amount = $hashref_or_error->{'amount'};
788
789     #warn "adding $amount as $name\n";
790     $taxname{ $name } ||= [];
791     push @{ $taxname{ $name } }, $tax;
792
793     $tax_amount{ $tax } += $amount;
794
795     # link records between cust_main_county/tax_rate and cust_location
796     $tax_location{ $tax } ||= [];
797     $tax_rate_location{ $tax } ||= [];
798     if ( ref($tax_object) eq 'FS::cust_main_county' ) {
799       push @{ $tax_location{ $tax }  },
800         {
801           'taxnum'      => $tax_object->taxnum, 
802           'taxtype'     => ref($tax_object),
803           'pkgnum'      => $tax_object->get('pkgnum'),
804           'locationnum' => $tax_object->get('locationnum'),
805           'amount'      => sprintf('%.2f', $amount ),
806         };
807     }
808     elsif ( ref($tax_object) eq 'FS::tax_rate' ) {
809       my $taxratelocationnum =
810         $tax_object->tax_rate_location->taxratelocationnum;
811       push @{ $tax_rate_location{ $tax }  },
812         {
813           'taxnum'             => $tax_object->taxnum, 
814           'taxtype'            => ref($tax_object),
815           'amount'             => sprintf('%.2f', $amount ),
816           'locationtaxid'      => $tax_object->location,
817           'taxratelocationnum' => $taxratelocationnum,
818         };
819     }
820
821   }
822
823   #move the cust_tax_exempt_pkg records to the cust_bill_pkgs we will commit
824   my %packagemap = map { $_->pkgnum => $_ } @$cust_bill_pkg;
825   foreach my $tax ( keys %$taxlisthash ) {
826     my $taxables = $taxlisthash->{$tax};
827     my $tax_object = shift @$taxables; # the rest are line items
828     foreach my $cust_bill_pkg ( @$taxables ) {
829       next unless ref($cust_bill_pkg) eq 'FS::cust_bill_pkg';
830
831       my @cust_tax_exempt_pkg = splice @{ $cust_bill_pkg->cust_tax_exempt_pkg };
832
833       next unless @cust_tax_exempt_pkg;
834       # get the non-disintegrated version
835       my $real_cust_bill_pkg = $packagemap{$cust_bill_pkg->pkgnum}
836         or die "can't distribute tax exemptions: no line item for ".
837           Dumper($_). " in packagemap ". 
838           join(',', sort {$a<=>$b} keys %packagemap). "\n";
839
840       push @{ $real_cust_bill_pkg->cust_tax_exempt_pkg },
841            @cust_tax_exempt_pkg;
842     }
843   }
844
845   #consolidate and create tax line items
846   warn "consolidating and generating...\n" if $DEBUG > 2;
847   foreach my $taxname ( keys %taxname ) {
848     my $tax_total = 0;
849     my %seen = ();
850     my @cust_bill_pkg_tax_location = ();
851     my @cust_bill_pkg_tax_rate_location = ();
852     warn "adding $taxname\n" if $DEBUG > 1;
853     foreach my $taxitem ( @{ $taxname{$taxname} } ) {
854       next if $seen{$taxitem}++;
855       warn "adding $tax_amount{$taxitem}\n" if $DEBUG > 1;
856       $tax_total += $tax_amount{$taxitem};
857       push @cust_bill_pkg_tax_location,
858         map { new FS::cust_bill_pkg_tax_location $_ }
859             @{ $tax_location{ $taxitem } };
860       push @cust_bill_pkg_tax_rate_location,
861         map { new FS::cust_bill_pkg_tax_rate_location $_ }
862             @{ $tax_rate_location{ $taxitem } };
863     }
864     next unless $tax_total;
865
866     $tax_total = sprintf('%.2f', $tax_total );
867   
868     my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
869                                                    'disabled'     => '',
870                                                  },
871                                );
872
873     my @display = ();
874     if ( $pkg_category and
875          $conf->config('invoice_latexsummary') ||
876          $conf->config('invoice_htmlsummary')
877        )
878     {
879
880       my %hash = (  'section' => $pkg_category->categoryname );
881       push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
882
883     }
884
885     push @tax_line_items, new FS::cust_bill_pkg {
886       'pkgnum'   => 0,
887       'setup'    => $tax_total,
888       'recur'    => 0,
889       'sdate'    => '',
890       'edate'    => '',
891       'itemdesc' => $taxname,
892       'display'  => \@display,
893       'cust_bill_pkg_tax_location' => \@cust_bill_pkg_tax_location,
894       'cust_bill_pkg_tax_rate_location' => \@cust_bill_pkg_tax_rate_location,
895     };
896
897   }
898
899   \@tax_line_items;
900 }
901
902 sub _make_lines {
903   my ($self, %params) = @_;
904
905   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
906
907   my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
908   my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
909   my $precommit_hooks = $params{precommit_hooks} or die "no precommit_hooks specified";
910   my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
911   my $total_setup = $params{setup} or die "no setup accumulator specified";
912   my $total_recur = $params{recur} or die "no recur accumulator specified";
913   my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
914   my $time = $params{'time'} or die "no time specified";
915   my (%options) = %{$params{options}};
916
917   if ( $part_pkg->freq ne '1' and ($options{'freq_override'} || 0) > 0 ) {
918     # this should never happen
919     die 'freq_override billing attempted on non-monthly package '.
920       $cust_pkg->pkgnum;
921   }
922
923   my $dbh = dbh;
924   my $real_pkgpart = $params{real_pkgpart};
925   my %hash = $cust_pkg->hash;
926   my $old_cust_pkg = new FS::cust_pkg \%hash;
927
928   my @details = ();
929   my $lineitems = 0;
930
931   $cust_pkg->pkgpart($part_pkg->pkgpart);
932
933   ###
934   # bill setup
935   ###
936
937   my $setup = 0;
938   my $unitsetup = 0;
939   my @setup_discounts = ();
940   my %setup_param = ( 'discounts' => \@setup_discounts );
941   if (     ! $options{recurring_only}
942        and ! $options{cancel}
943        and ( $options{'resetup'}
944              || ( ! $cust_pkg->setup
945                   && ( ! $cust_pkg->start_date
946                        || $cust_pkg->start_date <= day_end($time)
947                      )
948                   && ( ! $conf->exists('disable_setup_suspended_pkgs')
949                        || ( $conf->exists('disable_setup_suspended_pkgs') &&
950                             ! $cust_pkg->getfield('susp')
951                           )
952                      )
953                 )
954            )
955      )
956   {
957     
958     warn "    bill setup\n" if $DEBUG > 1;
959
960     unless ( $cust_pkg->waive_setup ) {
961         $lineitems++;
962
963         $setup = eval { $cust_pkg->calc_setup( $time, \@details, \%setup_param ) };
964         return "$@ running calc_setup for $cust_pkg\n"
965           if $@;
966
967         $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
968     }
969
970     $cust_pkg->setfield('setup', $time)
971       unless $cust_pkg->setup;
972           #do need it, but it won't get written to the db
973           #|| $cust_pkg->pkgpart != $real_pkgpart;
974
975     $cust_pkg->setfield('start_date', '')
976       if $cust_pkg->start_date;
977
978   }
979
980   ###
981   # bill recurring fee
982   ### 
983
984   my $recur = 0;
985   my $unitrecur = 0;
986   my @recur_discounts = ();
987   my $sdate;
988   if (     ! $cust_pkg->start_date
989        and ( ! $cust_pkg->susp || $cust_pkg->option('suspend_bill',1)
990                                || ( $part_pkg->option('suspend_bill', 1) )
991                                      && ! $cust_pkg->option('no_suspend_bill',1)
992                                   )
993        and
994             ( $part_pkg->freq ne '0' && ( $cust_pkg->bill || 0 ) <= day_end($time) )
995          || ( $part_pkg->plan eq 'voip_cdr'
996                && $part_pkg->option('bill_every_call')
997             )
998          || $options{cancel}
999   ) {
1000
1001     # XXX should this be a package event?  probably.  events are called
1002     # at collection time at the moment, though...
1003     $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
1004       if $part_pkg->can('reset_usage') && !$options{'no_usage_reset'};
1005       #don't want to reset usage just cause we want a line item??
1006       #&& $part_pkg->pkgpart == $real_pkgpart;
1007
1008     warn "    bill recur\n" if $DEBUG > 1;
1009     $lineitems++;
1010
1011     # XXX shared with $recur_prog
1012     $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
1013              || $cust_pkg->setup
1014              || $time;
1015
1016     #over two params!  lets at least switch to a hashref for the rest...
1017     my $increment_next_bill = ( $part_pkg->freq ne '0'
1018                                 && ( $cust_pkg->getfield('bill') || 0 ) <= day_end($time)
1019                                 && !$options{cancel}
1020                               );
1021     my %param = ( %setup_param,
1022                   'precommit_hooks'     => $precommit_hooks,
1023                   'increment_next_bill' => $increment_next_bill,
1024                   'discounts'           => \@recur_discounts,
1025                   'real_pkgpart'        => $real_pkgpart,
1026                   'freq_override'       => $options{freq_override} || '',
1027                   'setup_fee'           => 0,
1028                 );
1029
1030     my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
1031
1032     # There may be some part_pkg for which this is wrong.  Only those
1033     # which can_discount are supported.
1034     # (the UI should prevent adding discounts to these at the moment)
1035
1036     warn "calling $method on cust_pkg ". $cust_pkg->pkgnum.
1037          " for pkgpart ". $cust_pkg->pkgpart.
1038          " with params ". join(' / ', map "$_=>$param{$_}", keys %param). "\n"
1039       if $DEBUG > 2;
1040            
1041     $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
1042     return "$@ running $method for $cust_pkg\n"
1043       if ( $@ );
1044
1045     #base_cancel???
1046     $unitrecur = $cust_pkg->part_pkg->base_recur || $recur; #XXX uuh
1047
1048     if ( $increment_next_bill ) {
1049
1050       my $next_bill = $part_pkg->add_freq($sdate, $options{freq_override} || 0);
1051       return "unparsable frequency: ". $part_pkg->freq
1052         if $next_bill == -1;
1053   
1054       #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
1055       # only for figuring next bill date, nothing else, so, reset $sdate again
1056       # here
1057       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1058       #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
1059       $cust_pkg->last_bill($sdate);
1060
1061       $cust_pkg->setfield('bill', $next_bill );
1062
1063     }
1064
1065     if ( $param{'setup_fee'} ) {
1066       # Add an additional setup fee at the billing stage.
1067       # Used for prorate_defer_bill.
1068       $setup += $param{'setup_fee'};
1069       $unitsetup += $param{'setup_fee'};
1070       $lineitems++;
1071     }
1072
1073     if ( defined $param{'discount_left_setup'} ) {
1074         foreach my $discount_setup ( values %{$param{'discount_left_setup'}} ) {
1075             $setup -= $discount_setup;
1076         }
1077     }
1078
1079   }
1080
1081   warn "\$setup is undefined" unless defined($setup);
1082   warn "\$recur is undefined" unless defined($recur);
1083   warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1084   
1085   ###
1086   # If there's line items, create em cust_bill_pkg records
1087   # If $cust_pkg has been modified, update it (if we're a real pkgpart)
1088   ###
1089
1090   if ( $lineitems ) {
1091
1092     if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
1093       # hmm.. and if just the options are modified in some weird price plan?
1094   
1095       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
1096         if $DEBUG >1;
1097   
1098       my $error = $cust_pkg->replace( $old_cust_pkg,
1099                                       'depend_jobnum'=>$options{depend_jobnum},
1100                                       'options' => { $cust_pkg->options },
1101                                     )
1102         unless $options{no_commit};
1103       return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
1104         if $error; #just in case
1105     }
1106   
1107     $setup = sprintf( "%.2f", $setup );
1108     $recur = sprintf( "%.2f", $recur );
1109     if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1110       return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1111     }
1112     if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1113       return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1114     }
1115
1116     my $discount_show_always = $conf->exists('discount-show-always')
1117                                && (    ($setup == 0 && scalar(@setup_discounts))
1118                                     || ($recur == 0 && scalar(@recur_discounts))
1119                                   );
1120
1121     if (    $setup != 0
1122          || $recur != 0
1123          || (!$part_pkg->hidden && $options{has_hidden}) #include some $0 lines
1124          || $discount_show_always
1125          || ($setup == 0 && $cust_pkg->_X_show_zero('setup'))
1126          || ($recur == 0 && $cust_pkg->_X_show_zero('recur'))
1127        ) 
1128     {
1129
1130       warn "    charges (setup=$setup, recur=$recur); adding line items\n"
1131         if $DEBUG > 1;
1132
1133       my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
1134       if ( $DEBUG > 1 ) {
1135         warn "      adding customer package invoice detail: $_\n"
1136           foreach @cust_pkg_detail;
1137       }
1138       push @details, @cust_pkg_detail;
1139
1140       my $cust_bill_pkg = new FS::cust_bill_pkg {
1141         'pkgnum'    => $cust_pkg->pkgnum,
1142         'setup'     => $setup,
1143         'unitsetup' => $unitsetup,
1144         'recur'     => $recur,
1145         'unitrecur' => $unitrecur,
1146         'quantity'  => $cust_pkg->quantity,
1147         'details'   => \@details,
1148         'discounts' => [ @setup_discounts, @recur_discounts ],
1149         'hidden'    => $part_pkg->hidden,
1150         'freq'      => $part_pkg->freq,
1151       };
1152
1153       if ( $part_pkg->option('prorate_defer_bill',1) 
1154            and !$hash{last_bill} ) {
1155         # both preceding and upcoming, technically
1156         $cust_bill_pkg->sdate( $cust_pkg->setup );
1157         $cust_bill_pkg->edate( $cust_pkg->bill );
1158       } elsif ( $part_pkg->recur_temporality eq 'preceding' ) {
1159         $cust_bill_pkg->sdate( $hash{last_bill} );
1160         $cust_bill_pkg->edate( $sdate - 86399   ); #60s*60m*24h-1
1161         $cust_bill_pkg->edate( $time ) if $options{cancel};
1162       } else { #if ( $part_pkg->recur_temporality eq 'upcoming' ) {
1163         $cust_bill_pkg->sdate( $sdate );
1164         $cust_bill_pkg->edate( $cust_pkg->bill );
1165         #$cust_bill_pkg->edate( $time ) if $options{cancel};
1166       }
1167
1168       $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
1169         unless $part_pkg->pkgpart == $real_pkgpart;
1170
1171       $$total_setup += $setup;
1172       $$total_recur += $recur;
1173
1174       ###
1175       # handle taxes
1176       ###
1177
1178       unless ( $discount_show_always ) {
1179           my $error = 
1180             $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
1181           return $error if $error;
1182       }
1183
1184       push @$cust_bill_pkgs, $cust_bill_pkg;
1185
1186     } #if $setup != 0 || $recur != 0
1187       
1188   } #if $line_items
1189
1190   '';
1191
1192 }
1193
1194 sub _handle_taxes {
1195   my $self = shift;
1196   my $part_pkg = shift;
1197   my $taxlisthash = shift;
1198   my $cust_bill_pkg = shift;
1199   my $cust_pkg = shift;
1200   my $invoice_time = shift;
1201   my $real_pkgpart = shift;
1202   my $options = shift;
1203
1204   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1205
1206   my %cust_bill_pkg = ();
1207   my %taxes = ();
1208     
1209   my @classes;
1210   #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
1211   push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
1212   push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
1213   push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
1214
1215   my $exempt = $conf->exists('cust_class-tax_exempt')
1216                  ? ( $self->cust_class ? $self->cust_class->tax : '' )
1217                  : $self->tax;
1218   # standardize this just to be sure
1219   $exempt = ($exempt eq 'Y') ? 'Y' : '';
1220
1221   #if ( $exempt !~ /Y/i && $self->payby ne 'COMP' ) {
1222   if ( $self->payby ne 'COMP' ) {
1223
1224     if ( $conf->exists('enable_taxproducts')
1225          && ( scalar($part_pkg->part_pkg_taxoverride)
1226               || $part_pkg->has_taxproduct
1227             )
1228        )
1229     {
1230
1231       if ( !$exempt ) {
1232
1233         foreach my $class (@classes) {
1234           my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $cust_pkg );
1235           return $err_or_ref unless ref($err_or_ref);
1236           $taxes{$class} = $err_or_ref;
1237         }
1238
1239         unless (exists $taxes{''}) {
1240           my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $cust_pkg );
1241           return $err_or_ref unless ref($err_or_ref);
1242           $taxes{''} = $err_or_ref;
1243         }
1244
1245       }
1246
1247     } else { # cust_main_county tax system
1248
1249       # We fetch taxes even if the customer is completely exempt,
1250       # because we need to record that fact.
1251
1252       my @loc_keys = qw( district city county state country );
1253       my $location = $cust_pkg->tax_location;
1254       my %taxhash = map { $_ => $location->$_ } @loc_keys;
1255
1256       $taxhash{'taxclass'} = $part_pkg->taxclass;
1257
1258       my @taxes = (); # entries are cust_main_county objects
1259       my %taxhash_elim = %taxhash;
1260       my @elim = qw( district city county state );
1261       do { 
1262
1263         #first try a match with taxclass
1264         @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
1265
1266         if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
1267           #then try a match without taxclass
1268           my %no_taxclass = %taxhash_elim;
1269           $no_taxclass{ 'taxclass' } = '';
1270           @taxes = qsearch( 'cust_main_county', \%no_taxclass );
1271         }
1272
1273         $taxhash_elim{ shift(@elim) } = '';
1274
1275       } while ( !scalar(@taxes) && scalar(@elim) );
1276
1277       foreach (@taxes) {
1278         # These could become cust_bill_pkg_tax_location records,
1279         # or cust_tax_exempt_pkg.  We'll decide later.
1280         $_->set('pkgnum',       $cust_pkg->pkgnum);
1281         $_->set('locationnum',  $cust_pkg->tax_locationnum);
1282       }
1283
1284       $taxes{''} = [ @taxes ];
1285       $taxes{'setup'} = [ @taxes ];
1286       $taxes{'recur'} = [ @taxes ];
1287       $taxes{$_} = [ @taxes ] foreach (@classes);
1288
1289       # # maybe eliminate this entirely, along with all the 0% records
1290       # unless ( @taxes ) {
1291       #   return
1292       #     "fatal: can't find tax rate for state/county/country/taxclass ".
1293       #     join('/', map $taxhash{$_}, qw(state county country taxclass) );
1294       # }
1295
1296     } #if $conf->exists('enable_taxproducts') ...
1297
1298   } # if $self->payby eq 'COMP'
1299
1300   #what's this doing in the middle of _handle_taxes?  probably should split
1301   #this into three parts above in _make_lines
1302   $cust_bill_pkg->set_display(   part_pkg     => $part_pkg,
1303                                  real_pkgpart => $real_pkgpart,
1304                              );
1305
1306   my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
1307   foreach my $key (keys %tax_cust_bill_pkg) {
1308     # $key is "setup", "recur", or a usage class name. ('' is a usage class.)
1309     # $tax_cust_bill_pkg{$key} is a cust_bill_pkg for that component of 
1310     # the line item.
1311     # $taxes{$key} is an arrayref of cust_main_county or tax_rate objects that
1312     # apply to $key-class charges.
1313     my @taxes = @{ $taxes{$key} || [] };
1314     my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
1315
1316     my %localtaxlisthash = ();
1317     foreach my $tax ( @taxes ) {
1318
1319       # this is the tax identifier, not the taxname
1320       my $taxname = ref( $tax ). ' '. $tax->taxnum;
1321       $taxname .= ' pkgnum'. $cust_pkg->pkgnum;
1322       # We need to create a separate $taxlisthash entry for each pkgnum
1323       # on the invoice, so that cust_bill_pkg_tax_location records will
1324       # be linked correctly.
1325
1326       # $taxlisthash: keys are "setup", "recur", and usage classes.
1327       # Values are arrayrefs, first the tax object (cust_main_county
1328       # or tax_rate) and then any cust_bill_pkg objects that the 
1329       # tax applies to.
1330       $taxlisthash->{ $taxname } ||= [ $tax ];
1331       push @{ $taxlisthash->{ $taxname  } }, $tax_cust_bill_pkg;
1332
1333       $localtaxlisthash{ $taxname } ||= [ $tax ];
1334       push @{ $localtaxlisthash{ $taxname  } }, $tax_cust_bill_pkg;
1335
1336     }
1337
1338     warn "finding taxed taxes...\n" if $DEBUG > 2;
1339     foreach my $tax ( keys %localtaxlisthash ) {
1340       my $tax_object = shift @{ $localtaxlisthash{$tax} };
1341       warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
1342         if $DEBUG > 2;
1343       next unless $tax_object->can('tax_on_tax');
1344
1345       foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
1346         my $totname = ref( $tot ). ' '. $tot->taxnum;
1347
1348         warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
1349           if $DEBUG > 2;
1350         next unless exists( $localtaxlisthash{ $totname } ); # only increase
1351                                                              # existing taxes
1352         warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
1353         my $hashref_or_error = 
1354           $tax_object->taxline( $localtaxlisthash{$tax},
1355                                 'custnum'      => $self->custnum,
1356                                 'invoice_time' => $invoice_time,
1357                               );
1358         return $hashref_or_error
1359           unless ref($hashref_or_error);
1360         
1361         $taxlisthash->{ $totname } ||= [ $tot ];
1362         push @{ $taxlisthash->{ $totname  } }, $hashref_or_error->{amount};
1363
1364       }
1365     }
1366
1367   }
1368
1369   '';
1370 }
1371
1372 sub _gather_taxes {
1373   my $self = shift;
1374   my $part_pkg = shift;
1375   my $class = shift;
1376   my $cust_pkg = shift;
1377
1378   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1379
1380   my $geocode;
1381   if ( $cust_pkg->locationnum && $conf->exists('tax-pkg_address') ) {
1382     $geocode = $cust_pkg->cust_location->geocode('cch');
1383   } else {
1384     $geocode = $self->geocode('cch');
1385   }
1386
1387   my @taxes = ();
1388
1389   my @taxclassnums = map { $_->taxclassnum }
1390                      $part_pkg->part_pkg_taxoverride($class);
1391
1392   unless (@taxclassnums) {
1393     @taxclassnums = map { $_->taxclassnum }
1394                     grep { $_->taxable eq 'Y' }
1395                     $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
1396   }
1397   warn "Found taxclassnum values of ". join(',', @taxclassnums)
1398     if $DEBUG;
1399
1400   my $extra_sql =
1401     "AND (".
1402     join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
1403
1404   @taxes = qsearch({ 'table' => 'tax_rate',
1405                      'hashref' => { 'geocode' => $geocode, },
1406                      'extra_sql' => $extra_sql,
1407                   })
1408     if scalar(@taxclassnums);
1409
1410   warn "Found taxes ".
1411        join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n" 
1412    if $DEBUG;
1413
1414   [ @taxes ];
1415
1416 }
1417
1418 =item collect [ HASHREF | OPTION => VALUE ... ]
1419
1420 (Attempt to) collect money for this customer's outstanding invoices (see
1421 L<FS::cust_bill>).  Usually used after the bill method.
1422
1423 Actions are now triggered by billing events; see L<FS::part_event> and the
1424 billing events web interface.  Old-style invoice events (see
1425 L<FS::part_bill_event>) have been deprecated.
1426
1427 If there is an error, returns the error, otherwise returns false.
1428
1429 Options are passed as name-value pairs.
1430
1431 Currently available options are:
1432
1433 =over 4
1434
1435 =item invoice_time
1436
1437 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.
1438
1439 =item retry
1440
1441 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1442
1443 =item check_freq
1444
1445 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1446
1447 =item quiet
1448
1449 set true to surpress email card/ACH decline notices.
1450
1451 =item debug
1452
1453 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)
1454
1455 =back
1456
1457 # =item payby
1458 #
1459 # allows for one time override of normal customer billing method
1460
1461 =cut
1462
1463 sub collect {
1464   my( $self, %options ) = @_;
1465
1466   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1467
1468   my $invoice_time = $options{'invoice_time'} || time;
1469
1470   #put below somehow?
1471   local $SIG{HUP} = 'IGNORE';
1472   local $SIG{INT} = 'IGNORE';
1473   local $SIG{QUIT} = 'IGNORE';
1474   local $SIG{TERM} = 'IGNORE';
1475   local $SIG{TSTP} = 'IGNORE';
1476   local $SIG{PIPE} = 'IGNORE';
1477
1478   my $oldAutoCommit = $FS::UID::AutoCommit;
1479   local $FS::UID::AutoCommit = 0;
1480   my $dbh = dbh;
1481
1482   $self->select_for_update; #mutex
1483
1484   if ( $DEBUG ) {
1485     my $balance = $self->balance;
1486     warn "$me collect customer ". $self->custnum. ": balance $balance\n"
1487   }
1488
1489   if ( exists($options{'retry_card'}) ) {
1490     carp 'retry_card option passed to collect is deprecated; use retry';
1491     $options{'retry'} ||= $options{'retry_card'};
1492   }
1493   if ( exists($options{'retry'}) && $options{'retry'} ) {
1494     my $error = $self->retry_realtime;
1495     if ( $error ) {
1496       $dbh->rollback if $oldAutoCommit;
1497       return $error;
1498     }
1499   }
1500
1501   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1502
1503   #never want to roll back an event just because it returned an error
1504   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1505
1506   $self->do_cust_event(
1507     'debug'      => ( $options{'debug'} || 0 ),
1508     'time'       => $invoice_time,
1509     'check_freq' => $options{'check_freq'},
1510     'stage'      => 'collect',
1511   );
1512
1513 }
1514
1515 =item retry_realtime
1516
1517 Schedules realtime / batch  credit card / electronic check / LEC billing
1518 events for for retry.  Useful if card information has changed or manual
1519 retry is desired.  The 'collect' method must be called to actually retry
1520 the transaction.
1521
1522 Implementation details: For either this customer, or for each of this
1523 customer's open invoices, changes the status of the first "done" (with
1524 statustext error) realtime processing event to "failed".
1525
1526 =cut
1527
1528 sub retry_realtime {
1529   my $self = shift;
1530
1531   local $SIG{HUP} = 'IGNORE';
1532   local $SIG{INT} = 'IGNORE';
1533   local $SIG{QUIT} = 'IGNORE';
1534   local $SIG{TERM} = 'IGNORE';
1535   local $SIG{TSTP} = 'IGNORE';
1536   local $SIG{PIPE} = 'IGNORE';
1537
1538   my $oldAutoCommit = $FS::UID::AutoCommit;
1539   local $FS::UID::AutoCommit = 0;
1540   my $dbh = dbh;
1541
1542   #a little false laziness w/due_cust_event (not too bad, really)
1543
1544   my $join = FS::part_event_condition->join_conditions_sql;
1545   my $order = FS::part_event_condition->order_conditions_sql;
1546   my $mine = 
1547   '( '
1548    . join ( ' OR ' , map { 
1549     my $cust_join = FS::part_event->eventtables_cust_join->{$_} || '';
1550     my $custnum = FS::part_event->eventtables_custnum->{$_};
1551     "( part_event.eventtable = " . dbh->quote($_) 
1552     . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key 
1553     . " from $_ $cust_join"
1554     . " where $custnum = " . dbh->quote( $self->custnum ) . "))" ;
1555    } FS::part_event->eventtables)
1556    . ') ';
1557
1558   #here is the agent virtualization
1559   my $agent_virt = " (    part_event.agentnum IS NULL
1560                        OR part_event.agentnum = ". $self->agentnum. ' )';
1561
1562   #XXX this shouldn't be hardcoded, actions should declare it...
1563   my @realtime_events = qw(
1564     cust_bill_realtime_card
1565     cust_bill_realtime_check
1566     cust_bill_realtime_lec
1567     cust_bill_batch
1568   );
1569
1570   my $is_realtime_event =
1571     ' part_event.action IN ( '.
1572         join(',', map "'$_'", @realtime_events ).
1573     ' ) ';
1574
1575   my $batch_or_statustext =
1576     "( part_event.action = 'cust_bill_batch'
1577        OR ( statustext IS NOT NULL AND statustext != '' )
1578      )";
1579
1580
1581   my @cust_event = qsearch({
1582     'table'     => 'cust_event',
1583     'select'    => 'cust_event.*',
1584     'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
1585     'hashref'   => { 'status' => 'done' },
1586     'extra_sql' => " AND $batch_or_statustext ".
1587                    " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
1588   });
1589
1590   my %seen_invnum = ();
1591   foreach my $cust_event (@cust_event) {
1592
1593     #max one for the customer, one for each open invoice
1594     my $cust_X = $cust_event->cust_X;
1595     next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
1596                           ? $cust_X->invnum
1597                           : 0
1598                         }++
1599          or $cust_event->part_event->eventtable eq 'cust_bill'
1600             && ! $cust_X->owed;
1601
1602     my $error = $cust_event->retry;
1603     if ( $error ) {
1604       $dbh->rollback if $oldAutoCommit;
1605       return "error scheduling event for retry: $error";
1606     }
1607
1608   }
1609
1610   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1611   '';
1612
1613 }
1614
1615 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
1616
1617 Runs billing events; see L<FS::part_event> and the billing events web
1618 interface.
1619
1620 If there is an error, returns the error, otherwise returns false.
1621
1622 Options are passed as name-value pairs.
1623
1624 Currently available options are:
1625
1626 =over 4
1627
1628 =item time
1629
1630 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.
1631
1632 =item check_freq
1633
1634 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1635
1636 =item stage
1637
1638 "collect" (the default) or "pre-bill"
1639
1640 =item quiet
1641  
1642 set true to surpress email card/ACH decline notices.
1643
1644 =item debug
1645
1646 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)
1647
1648 =back
1649 =cut
1650
1651 # =item payby
1652 #
1653 # allows for one time override of normal customer billing method
1654
1655 # =item retry
1656 #
1657 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1658
1659 sub do_cust_event {
1660   my( $self, %options ) = @_;
1661
1662   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1663
1664   my $time = $options{'time'} || time;
1665
1666   #put below somehow?
1667   local $SIG{HUP} = 'IGNORE';
1668   local $SIG{INT} = 'IGNORE';
1669   local $SIG{QUIT} = 'IGNORE';
1670   local $SIG{TERM} = 'IGNORE';
1671   local $SIG{TSTP} = 'IGNORE';
1672   local $SIG{PIPE} = 'IGNORE';
1673
1674   my $oldAutoCommit = $FS::UID::AutoCommit;
1675   local $FS::UID::AutoCommit = 0;
1676   my $dbh = dbh;
1677
1678   $self->select_for_update; #mutex
1679
1680   if ( $DEBUG ) {
1681     my $balance = $self->balance;
1682     warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
1683   }
1684
1685 #  if ( exists($options{'retry_card'}) ) {
1686 #    carp 'retry_card option passed to collect is deprecated; use retry';
1687 #    $options{'retry'} ||= $options{'retry_card'};
1688 #  }
1689 #  if ( exists($options{'retry'}) && $options{'retry'} ) {
1690 #    my $error = $self->retry_realtime;
1691 #    if ( $error ) {
1692 #      $dbh->rollback if $oldAutoCommit;
1693 #      return $error;
1694 #    }
1695 #  }
1696
1697   # false laziness w/pay_batch::import_results
1698
1699   my $due_cust_event = $self->due_cust_event(
1700     'debug'      => ( $options{'debug'} || 0 ),
1701     'time'       => $time,
1702     'check_freq' => $options{'check_freq'},
1703     'stage'      => ( $options{'stage'} || 'collect' ),
1704   );
1705   unless( ref($due_cust_event) ) {
1706     $dbh->rollback if $oldAutoCommit;
1707     return $due_cust_event;
1708   }
1709
1710   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1711   #never want to roll back an event just because it or a different one
1712   # returned an error
1713   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1714
1715   foreach my $cust_event ( @$due_cust_event ) {
1716
1717     #XXX lock event
1718     
1719     #re-eval event conditions (a previous event could have changed things)
1720     unless ( $cust_event->test_conditions ) {
1721       #don't leave stray "new/locked" records around
1722       my $error = $cust_event->delete;
1723       return $error if $error;
1724       next;
1725     }
1726
1727     {
1728       local $FS::cust_main::Billing_Realtime::realtime_bop_decline_quiet = 1
1729         if $options{'quiet'};
1730       warn "  running cust_event ". $cust_event->eventnum. "\n"
1731         if $DEBUG > 1;
1732
1733       #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
1734       if ( my $error = $cust_event->do_event( 'time' => $time ) ) {
1735         #XXX wtf is this?  figure out a proper dealio with return value
1736         #from do_event
1737         return $error;
1738       }
1739     }
1740
1741   }
1742
1743   '';
1744
1745 }
1746
1747 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
1748
1749 Inserts database records for and returns an ordered listref of new events due
1750 for this customer, as FS::cust_event objects (see L<FS::cust_event>).  If no
1751 events are due, an empty listref is returned.  If there is an error, returns a
1752 scalar error message.
1753
1754 To actually run the events, call each event's test_condition method, and if
1755 still true, call the event's do_event method.
1756
1757 Options are passed as a hashref or as a list of name-value pairs.  Available
1758 options are:
1759
1760 =over 4
1761
1762 =item check_freq
1763
1764 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.
1765
1766 =item stage
1767
1768 "collect" (the default) or "pre-bill"
1769
1770 =item time
1771
1772 "Current time" for the events.
1773
1774 =item debug
1775
1776 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)
1777
1778 =item eventtable
1779
1780 Only return events for the specified eventtable (by default, events of all eventtables are returned)
1781
1782 =item objects
1783
1784 Explicitly pass the objects to be tested (typically used with eventtable).
1785
1786 =item testonly
1787
1788 Set to true to return the objects, but not actually insert them into the
1789 database.
1790
1791 =back
1792
1793 =cut
1794
1795 sub due_cust_event {
1796   my $self = shift;
1797   my %opt = ref($_[0]) ? %{ $_[0] } : @_;
1798
1799   #???
1800   #my $DEBUG = $opt{'debug'}
1801   local($DEBUG) = $opt{'debug'}
1802     if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
1803   $DEBUG = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1804
1805   warn "$me due_cust_event called with options ".
1806        join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
1807     if $DEBUG;
1808
1809   $opt{'time'} ||= time;
1810
1811   local $SIG{HUP} = 'IGNORE';
1812   local $SIG{INT} = 'IGNORE';
1813   local $SIG{QUIT} = 'IGNORE';
1814   local $SIG{TERM} = 'IGNORE';
1815   local $SIG{TSTP} = 'IGNORE';
1816   local $SIG{PIPE} = 'IGNORE';
1817
1818   my $oldAutoCommit = $FS::UID::AutoCommit;
1819   local $FS::UID::AutoCommit = 0;
1820   my $dbh = dbh;
1821
1822   $self->select_for_update #mutex
1823     unless $opt{testonly};
1824
1825   ###
1826   # find possible events (initial search)
1827   ###
1828   
1829   my @cust_event = ();
1830
1831   my @eventtable = $opt{'eventtable'}
1832                      ? ( $opt{'eventtable'} )
1833                      : FS::part_event->eventtables_runorder;
1834
1835   my $check_freq = $opt{'check_freq'} || '1d';
1836
1837   foreach my $eventtable ( @eventtable ) {
1838
1839     my @objects;
1840     if ( $opt{'objects'} ) {
1841
1842       @objects = @{ $opt{'objects'} };
1843
1844     } elsif ( $eventtable eq 'cust_main' ) {
1845
1846       @objects = ( $self );
1847
1848     } else {
1849
1850       my $cm_join = " LEFT JOIN cust_main USING ( custnum )";
1851       # linkage not needed here because FS::cust_main->$eventtable will 
1852       # already supply it
1853
1854       #some false laziness w/Cron::bill bill_where
1855
1856       my $join  = FS::part_event_condition->join_conditions_sql( $eventtable);
1857       my $where = FS::part_event_condition->where_conditions_sql($eventtable,
1858         'time'=>$opt{'time'},
1859       );
1860       $where = $where ? "AND $where" : '';
1861
1862       my $are_part_event = 
1863       "EXISTS ( SELECT 1 FROM part_event $join
1864         WHERE check_freq = '$check_freq'
1865         AND eventtable = '$eventtable'
1866         AND ( disabled = '' OR disabled IS NULL )
1867         $where
1868         )
1869       ";
1870       #eofalse
1871
1872       @objects = $self->$eventtable(
1873         'addl_from' => $cm_join,
1874         'extra_sql' => " AND $are_part_event",
1875       );
1876     } # if ( !$opt{objects} and $eventtable ne 'cust_main' )
1877
1878     my @e_cust_event = ();
1879
1880     my $linkage = FS::part_event->eventtables_cust_join->{$eventtable} || '';
1881
1882     my $cross = "CROSS JOIN $eventtable $linkage";
1883     $cross .= ' LEFT JOIN cust_main USING ( custnum )'
1884       unless $eventtable eq 'cust_main';
1885
1886     foreach my $object ( @objects ) {
1887
1888       #this first search uses the condition_sql magic for optimization.
1889       #the more possible events we can eliminate in this step the better
1890
1891       my $cross_where = '';
1892       my $pkey = $object->primary_key;
1893       $cross_where = "$eventtable.$pkey = ". $object->$pkey();
1894
1895       my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
1896       my $extra_sql =
1897         FS::part_event_condition->where_conditions_sql( $eventtable,
1898                                                         'time'=>$opt{'time'}
1899                                                       );
1900       my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
1901
1902       $extra_sql = "AND $extra_sql" if $extra_sql;
1903
1904       #here is the agent virtualization
1905       $extra_sql .= " AND (    part_event.agentnum IS NULL
1906                             OR part_event.agentnum = ". $self->agentnum. ' )';
1907
1908       $extra_sql .= " $order";
1909
1910       warn "searching for events for $eventtable ". $object->$pkey. "\n"
1911         if $opt{'debug'} > 2;
1912       my @part_event = qsearch( {
1913         'debug'     => ( $opt{'debug'} > 3 ? 1 : 0 ),
1914         'select'    => 'part_event.*',
1915         'table'     => 'part_event',
1916         'addl_from' => "$cross $join",
1917         'hashref'   => { 'check_freq' => $check_freq,
1918                          'eventtable' => $eventtable,
1919                          'disabled'   => '',
1920                        },
1921         'extra_sql' => "AND $cross_where $extra_sql",
1922       } );
1923
1924       if ( $DEBUG > 2 ) {
1925         my $pkey = $object->primary_key;
1926         warn "      ". scalar(@part_event).
1927              " possible events found for $eventtable ". $object->$pkey(). "\n";
1928       }
1929
1930       push @e_cust_event, map { 
1931         $_->new_cust_event($object, 'time' => $opt{'time'}) 
1932       } @part_event;
1933
1934     }
1935
1936     warn "    ". scalar(@e_cust_event).
1937          " subtotal possible cust events found for $eventtable\n"
1938       if $DEBUG > 1;
1939
1940     push @cust_event, @e_cust_event;
1941
1942   }
1943
1944   warn "  ". scalar(@cust_event).
1945        " total possible cust events found in initial search\n"
1946     if $DEBUG; # > 1;
1947
1948
1949   ##
1950   # test stage
1951   ##
1952
1953   $opt{stage} ||= 'collect';
1954   @cust_event =
1955     grep { my $stage = $_->part_event->event_stage;
1956            $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
1957          }
1958          @cust_event;
1959
1960   ##
1961   # test conditions
1962   ##
1963   
1964   my %unsat = ();
1965
1966   @cust_event = grep $_->test_conditions( 'stats_hashref' => \%unsat ),
1967                      @cust_event;
1968
1969   warn "  ". scalar(@cust_event). " cust events left satisfying conditions\n"
1970     if $DEBUG; # > 1;
1971
1972   warn "    invalid conditions not eliminated with condition_sql:\n".
1973        join('', map "      $_: ".$unsat{$_}."\n", keys %unsat )
1974     if keys %unsat && $DEBUG; # > 1;
1975
1976   ##
1977   # insert
1978   ##
1979
1980   unless( $opt{testonly} ) {
1981     foreach my $cust_event ( @cust_event ) {
1982
1983       my $error = $cust_event->insert();
1984       if ( $error ) {
1985         $dbh->rollback if $oldAutoCommit;
1986         return $error;
1987       }
1988                                        
1989     }
1990   }
1991
1992   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1993
1994   ##
1995   # return
1996   ##
1997
1998   warn "  returning events: ". Dumper(@cust_event). "\n"
1999     if $DEBUG > 2;
2000
2001   \@cust_event;
2002
2003 }
2004
2005 =item apply_payments_and_credits [ OPTION => VALUE ... ]
2006
2007 Applies unapplied payments and credits.
2008
2009 In most cases, this new method should be used in place of sequential
2010 apply_payments and apply_credits methods.
2011
2012 A hash of optional arguments may be passed.  Currently "manual" is supported.
2013 If true, a payment receipt is sent instead of a statement when
2014 'payment_receipt_email' configuration option is set.
2015
2016 If there is an error, returns the error, otherwise returns false.
2017
2018 =cut
2019
2020 sub apply_payments_and_credits {
2021   my( $self, %options ) = @_;
2022
2023   local $SIG{HUP} = 'IGNORE';
2024   local $SIG{INT} = 'IGNORE';
2025   local $SIG{QUIT} = 'IGNORE';
2026   local $SIG{TERM} = 'IGNORE';
2027   local $SIG{TSTP} = 'IGNORE';
2028   local $SIG{PIPE} = 'IGNORE';
2029
2030   my $oldAutoCommit = $FS::UID::AutoCommit;
2031   local $FS::UID::AutoCommit = 0;
2032   my $dbh = dbh;
2033
2034   $self->select_for_update; #mutex
2035
2036   foreach my $cust_bill ( $self->open_cust_bill ) {
2037     my $error = $cust_bill->apply_payments_and_credits(%options);
2038     if ( $error ) {
2039       $dbh->rollback if $oldAutoCommit;
2040       return "Error applying: $error";
2041     }
2042   }
2043
2044   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2045   ''; #no error
2046
2047 }
2048
2049 =item apply_credits OPTION => VALUE ...
2050
2051 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2052 to outstanding invoice balances in chronological order (or reverse
2053 chronological order if the I<order> option is set to B<newest>) and returns the
2054 value of any remaining unapplied credits available for refund (see
2055 L<FS::cust_refund>).
2056
2057 Dies if there is an error.
2058
2059 =cut
2060
2061 sub apply_credits {
2062   my $self = shift;
2063   my %opt = @_;
2064
2065   local $SIG{HUP} = 'IGNORE';
2066   local $SIG{INT} = 'IGNORE';
2067   local $SIG{QUIT} = 'IGNORE';
2068   local $SIG{TERM} = 'IGNORE';
2069   local $SIG{TSTP} = 'IGNORE';
2070   local $SIG{PIPE} = 'IGNORE';
2071
2072   my $oldAutoCommit = $FS::UID::AutoCommit;
2073   local $FS::UID::AutoCommit = 0;
2074   my $dbh = dbh;
2075
2076   $self->select_for_update; #mutex
2077
2078   unless ( $self->total_unapplied_credits ) {
2079     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2080     return 0;
2081   }
2082
2083   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2084       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2085
2086   my @invoices = $self->open_cust_bill;
2087   @invoices = sort { $b->_date <=> $a->_date } @invoices
2088     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2089
2090   if ( $conf->exists('pkg-balances') ) {
2091     # limit @credits to those w/ a pkgnum grepped from $self
2092     my %pkgnums = ();
2093     foreach my $i (@invoices) {
2094       foreach my $li ( $i->cust_bill_pkg ) {
2095         $pkgnums{$li->pkgnum} = 1;
2096       }
2097     }
2098     @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
2099   }
2100
2101   my $credit;
2102
2103   foreach my $cust_bill ( @invoices ) {
2104
2105     if ( !defined($credit) || $credit->credited == 0) {
2106       $credit = pop @credits or last;
2107     }
2108
2109     my $owed;
2110     if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
2111       $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
2112     } else {
2113       $owed = $cust_bill->owed;
2114     }
2115     unless ( $owed > 0 ) {
2116       push @credits, $credit;
2117       next;
2118     }
2119
2120     my $amount = min( $credit->credited, $owed );
2121     
2122     my $cust_credit_bill = new FS::cust_credit_bill ( {
2123       'crednum' => $credit->crednum,
2124       'invnum'  => $cust_bill->invnum,
2125       'amount'  => $amount,
2126     } );
2127     $cust_credit_bill->pkgnum( $credit->pkgnum )
2128       if $conf->exists('pkg-balances') && $credit->pkgnum;
2129     my $error = $cust_credit_bill->insert;
2130     if ( $error ) {
2131       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2132       die $error;
2133     }
2134     
2135     redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2136
2137   }
2138
2139   my $total_unapplied_credits = $self->total_unapplied_credits;
2140
2141   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2142
2143   return $total_unapplied_credits;
2144 }
2145
2146 =item apply_payments  [ OPTION => VALUE ... ]
2147
2148 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2149 to outstanding invoice balances in chronological order.
2150
2151  #and returns the value of any remaining unapplied payments.
2152
2153 A hash of optional arguments may be passed.  Currently "manual" is supported.
2154 If true, a payment receipt is sent instead of a statement when
2155 'payment_receipt_email' configuration option is set.
2156
2157 Dies if there is an error.
2158
2159 =cut
2160
2161 sub apply_payments {
2162   my( $self, %options ) = @_;
2163
2164   local $SIG{HUP} = 'IGNORE';
2165   local $SIG{INT} = 'IGNORE';
2166   local $SIG{QUIT} = 'IGNORE';
2167   local $SIG{TERM} = 'IGNORE';
2168   local $SIG{TSTP} = 'IGNORE';
2169   local $SIG{PIPE} = 'IGNORE';
2170
2171   my $oldAutoCommit = $FS::UID::AutoCommit;
2172   local $FS::UID::AutoCommit = 0;
2173   my $dbh = dbh;
2174
2175   $self->select_for_update; #mutex
2176
2177   #return 0 unless
2178
2179   my @payments = sort { $b->_date <=> $a->_date }
2180                  grep { $_->unapplied > 0 }
2181                  $self->cust_pay;
2182
2183   my @invoices = sort { $a->_date <=> $b->_date}
2184                  grep { $_->owed > 0 }
2185                  $self->cust_bill;
2186
2187   if ( $conf->exists('pkg-balances') ) {
2188     # limit @payments to those w/ a pkgnum grepped from $self
2189     my %pkgnums = ();
2190     foreach my $i (@invoices) {
2191       foreach my $li ( $i->cust_bill_pkg ) {
2192         $pkgnums{$li->pkgnum} = 1;
2193       }
2194     }
2195     @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
2196   }
2197
2198   my $payment;
2199
2200   foreach my $cust_bill ( @invoices ) {
2201
2202     if ( !defined($payment) || $payment->unapplied == 0 ) {
2203       $payment = pop @payments or last;
2204     }
2205
2206     my $owed;
2207     if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
2208       $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
2209     } else {
2210       $owed = $cust_bill->owed;
2211     }
2212     unless ( $owed > 0 ) {
2213       push @payments, $payment;
2214       next;
2215     }
2216
2217     my $amount = min( $payment->unapplied, $owed );
2218
2219     my $cbp = {
2220       'paynum' => $payment->paynum,
2221       'invnum' => $cust_bill->invnum,
2222       'amount' => $amount,
2223     };
2224     $cbp->{_date} = $payment->_date 
2225         if $options{'manual'} && $options{'backdate_application'};
2226     my $cust_bill_pay = new FS::cust_bill_pay($cbp);
2227     $cust_bill_pay->pkgnum( $payment->pkgnum )
2228       if $conf->exists('pkg-balances') && $payment->pkgnum;
2229     my $error = $cust_bill_pay->insert(%options);
2230     if ( $error ) {
2231       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2232       die $error;
2233     }
2234
2235     redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2236
2237   }
2238
2239   my $total_unapplied_payments = $self->total_unapplied_payments;
2240
2241   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2242
2243   return $total_unapplied_payments;
2244 }
2245
2246 =back
2247
2248 =head1 FLOW
2249
2250   bill_and_collect
2251
2252     cancel_expired_pkgs
2253     suspend_adjourned_pkgs
2254     unsuspend_resumed_pkgs
2255
2256     bill
2257       (do_cust_event pre-bill)
2258       _make_lines
2259         _handle_taxes
2260           (vendor-only) _gather_taxes
2261       _omit_zero_value_bundles
2262       calculate_taxes
2263
2264     apply_payments_and_credits
2265     collect
2266       do_cust_event
2267         due_cust_event
2268
2269 =head1 BUGS
2270
2271 =head1 SEE ALSO
2272
2273 L<FS::cust_main>, L<FS::cust_main::Billing_Realtime>
2274
2275 =cut
2276
2277 1;