fix warning
[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 use FS::Log;
25
26 # 1 is mostly method/subroutine entry and options
27 # 2 traces progress of some operations
28 # 3 is even more information including possibly sensitive data
29 $DEBUG = 0;
30 $me = '[FS::cust_main::Billing]';
31
32 install_callback FS::UID sub { 
33   $conf = new FS::Conf;
34   #yes, need it for stuff below (prolly should be cached)
35 };
36
37 =head1 NAME
38
39 FS::cust_main::Billing - Billing mixin for cust_main
40
41 =head1 SYNOPSIS
42
43 =head1 DESCRIPTION
44
45 These methods are available on FS::cust_main objects.
46
47 =head1 METHODS
48
49 =over 4
50
51 =item bill_and_collect 
52
53 Cancels and suspends any packages due, generates bills, applies payments and
54 credits, and applies collection events to run cards, send bills and notices,
55 etc.
56
57 By default, warns on errors and continues with the next operation (but see the
58 "fatal" flag below).
59
60 Options are passed as name-value pairs.  Currently available options are:
61
62 =over 4
63
64 =item time
65
66 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:
67
68  use Date::Parse;
69  ...
70  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
71
72 =item invoice_time
73
74 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.
75
76 =item check_freq
77
78 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
79
80 =item resetup
81
82 If set true, re-charges setup fees.
83
84 =item fatal
85
86 If set any errors prevent subsequent operations from continusing.  If set
87 specifically to "return", returns the error (or false, if there is no error).
88 Any other true value causes errors to die.
89
90 =item debug
91
92 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)
93
94 =item job
95
96 Optional FS::queue entry to receive status updates.
97
98 =back
99
100 Options are passed to the B<bill> and B<collect> methods verbatim, so all
101 options of those methods are also available.
102
103 =cut
104
105 sub bill_and_collect {
106   my( $self, %options ) = @_;
107
108   my $log = FS::Log->new('bill_and_collect');
109   $log->debug('start', object => $self, agentnum => $self->agentnum);
110
111   my $error;
112
113   #$options{actual_time} not $options{time} because freeside-daily -d is for
114   #pre-printing invoices
115
116   $options{'actual_time'} ||= time;
117   my $job = $options{'job'};
118
119   $job->update_statustext('0,cleaning expired packages') if $job;
120   $error = $self->cancel_expired_pkgs( day_end( $options{actual_time} ) );
121   if ( $error ) {
122     $error = "Error expiring custnum ". $self->custnum. ": $error";
123     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
124     elsif ( $options{fatal}                                ) { die    $error; }
125     else                                                     { warn   $error; }
126   }
127
128   $error = $self->suspend_adjourned_pkgs( day_end( $options{actual_time} ) );
129   if ( $error ) {
130     $error = "Error adjourning custnum ". $self->custnum. ": $error";
131     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
132     elsif ( $options{fatal}                                ) { die    $error; }
133     else                                                     { warn   $error; }
134   }
135
136   $error = $self->unsuspend_resumed_pkgs( day_end( $options{actual_time} ) );
137   if ( $error ) {
138     $error = "Error resuming custnum ".$self->custnum. ": $error";
139     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
140     elsif ( $options{fatal}                                ) { die    $error; }
141     else                                                     { warn   $error; }
142   }
143
144   $job->update_statustext('20,billing packages') if $job;
145   $error = $self->bill( %options );
146   if ( $error ) {
147     $error = "Error billing custnum ". $self->custnum. ": $error";
148     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
149     elsif ( $options{fatal}                                ) { die    $error; }
150     else                                                     { warn   $error; }
151   }
152
153   $job->update_statustext('50,applying payments and credits') if $job;
154   $error = $self->apply_payments_and_credits;
155   if ( $error ) {
156     $error = "Error applying custnum ". $self->custnum. ": $error";
157     if    ( $options{fatal} && $options{fatal} eq 'return' ) { return $error; }
158     elsif ( $options{fatal}                                ) { die    $error; }
159     else                                                     { warn   $error; }
160   }
161
162   $job->update_statustext('70,running collection events') if $job;
163   unless ( $conf->exists('cancelled_cust-noevents')
164            && ! $self->num_ncancelled_pkgs
165   ) {
166     $error = $self->collect( %options );
167     if ( $error ) {
168       $error = "Error collecting custnum ". $self->custnum. ": $error";
169       if    ($options{fatal} && $options{fatal} eq 'return') { return $error; }
170       elsif ($options{fatal}                               ) { die    $error; }
171       else                                                   { warn   $error; }
172     }
173   }
174   $job->update_statustext('100,finished') if $job;
175   $log->debug('finish', object => $self, agentnum => $self->agentnum);
176
177   '';
178
179 }
180
181 sub cancel_expired_pkgs {
182   my ( $self, $time, %options ) = @_;
183   
184   my @cancel_pkgs = $self->ncancelled_pkgs( { 
185     'extra_sql' => " AND expire IS NOT NULL AND expire > 0 AND expire <= $time "
186   } );
187
188   my @errors = ();
189
190   foreach my $cust_pkg ( @cancel_pkgs ) {
191     my $cpr = $cust_pkg->last_cust_pkg_reason('expire');
192     my $error = $cust_pkg->cancel($cpr ? ( 'reason'        => $cpr->reasonnum,
193                                            'reason_otaker' => $cpr->otaker
194                                          )
195                                        : ()
196                                  );
197     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
198   }
199
200   join(' / ', @errors);
201
202 }
203
204 sub suspend_adjourned_pkgs {
205   my ( $self, $time, %options ) = @_;
206   
207   my @susp_pkgs = $self->ncancelled_pkgs( {
208     'extra_sql' =>
209       " AND ( susp IS NULL OR susp = 0 )
210         AND (    ( bill    IS NOT NULL AND bill    != 0 AND bill    <  $time )
211               OR ( adjourn IS NOT NULL AND adjourn != 0 AND adjourn <= $time )
212             )
213       ",
214   } );
215
216   #only because there's no SQL test for is_prepaid :/
217   @susp_pkgs = 
218     grep {     (    $_->part_pkg->is_prepaid
219                  && $_->bill
220                  && $_->bill < $time
221                )
222             || (    $_->adjourn
223                  && $_->adjourn <= $time
224                )
225            
226          }
227          @susp_pkgs;
228
229   my @errors = ();
230
231   foreach my $cust_pkg ( @susp_pkgs ) {
232     my $cpr = $cust_pkg->last_cust_pkg_reason('adjourn')
233       if ($cust_pkg->adjourn && $cust_pkg->adjourn < $^T);
234     my $error = $cust_pkg->suspend($cpr ? ( 'reason' => $cpr->reasonnum,
235                                             'reason_otaker' => $cpr->otaker
236                                           )
237                                         : ()
238                                   );
239     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
240   }
241
242   join(' / ', @errors);
243
244 }
245
246 sub unsuspend_resumed_pkgs {
247   my ( $self, $time, %options ) = @_;
248   
249   my @unsusp_pkgs = $self->ncancelled_pkgs( { 
250     'extra_sql' => " AND resume IS NOT NULL AND resume > 0 AND resume <= $time "
251   } );
252
253   my @errors = ();
254
255   foreach my $cust_pkg ( @unsusp_pkgs ) {
256     my $error = $cust_pkg->unsuspend( 'time' => $time );
257     push @errors, 'pkgnum '.$cust_pkg->pkgnum.": $error" if $error;
258   }
259
260   join(' / ', @errors);
261
262 }
263
264 =item bill OPTIONS
265
266 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
267 conjunction with the collect method by calling B<bill_and_collect>.
268
269 If there is an error, returns the error, otherwise returns false.
270
271 Options are passed as name-value pairs.  Currently available options are:
272
273 =over 4
274
275 =item resetup
276
277 If set true, re-charges setup fees.
278
279 =item recurring_only
280
281 If set true then only bill recurring charges, not setup, usage, one time
282 charges, etc.
283
284 =item freq_override
285
286 If set, then override the normal frequency and look for a part_pkg_discount
287 to take at that frequency.  This is appropriate only when the normal 
288 frequency for all packages is monthly, and is an error otherwise.  Use
289 C<pkg_list> to limit the set of packages included in billing.
290
291 =item time
292
293 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:
294
295  use Date::Parse;
296  ...
297  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
298
299 =item pkg_list
300
301 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
302
303  $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
304
305 =item not_pkgpart
306
307 A hashref of pkgparts to exclude from this billing run (can also be specified as a comma-separated scalar).
308
309 =item invoice_time
310
311 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.
312
313 =item cancel
314
315 This boolean value informs the us that the package is being cancelled.  This
316 typically might mean not charging the normal recurring fee but only usage
317 fees since the last billing. Setup charges may be charged.  Not all package
318 plans support this feature (they tend to charge 0).
319
320 =item no_usage_reset
321
322 Prevent the resetting of usage limits during this call.
323
324 =item no_commit
325
326 Do not save the generated bill in the database.  Useful with return_bill
327
328 =item return_bill
329
330 A list reference on which the generated bill(s) will be returned.
331
332 =item invoice_terms
333
334 Optional terms to be printed on this invoice.  Otherwise, customer-specific
335 terms or the default terms are used.
336
337 =back
338
339 =cut
340
341 sub bill {
342   my( $self, %options ) = @_;
343
344   return '' if $self->payby eq 'COMP';
345
346   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
347
348   warn "$me bill customer ". $self->custnum. "\n"
349     if $DEBUG;
350
351   my $time = $options{'time'} || time;
352   my $invoice_time = $options{'invoice_time'} || $time;
353
354   $options{'not_pkgpart'} ||= {};
355   $options{'not_pkgpart'} = { map { $_ => 1 }
356                                   split(/\s*,\s*/, $options{'not_pkgpart'})
357                             }
358     unless ref($options{'not_pkgpart'});
359
360   local $SIG{HUP} = 'IGNORE';
361   local $SIG{INT} = 'IGNORE';
362   local $SIG{QUIT} = 'IGNORE';
363   local $SIG{TERM} = 'IGNORE';
364   local $SIG{TSTP} = 'IGNORE';
365   local $SIG{PIPE} = 'IGNORE';
366
367   my $oldAutoCommit = $FS::UID::AutoCommit;
368   local $FS::UID::AutoCommit = 0;
369   my $dbh = dbh;
370
371   warn "$me acquiring lock on customer ". $self->custnum. "\n"
372     if $DEBUG;
373
374   $self->select_for_update; #mutex
375
376   warn "$me running pre-bill events for customer ". $self->custnum. "\n"
377     if $DEBUG;
378
379   my $error = $self->do_cust_event(
380     'debug'      => ( $options{'debug'} || 0 ),
381     'time'       => $invoice_time,
382     'check_freq' => $options{'check_freq'},
383     'stage'      => 'pre-bill',
384   )
385     unless $options{no_commit};
386   if ( $error ) {
387     $dbh->rollback if $oldAutoCommit && !$options{no_commit};
388     return $error;
389   }
390
391   warn "$me done running pre-bill events for customer ". $self->custnum. "\n"
392     if $DEBUG;
393
394   #keep auto-charge and non-auto-charge line items separate
395   my @passes = ( '', 'no_auto' );
396
397   my %cust_bill_pkg = map { $_ => [] } @passes;
398
399   ###
400   # find the packages which are due for billing, find out how much they are
401   # & generate invoice database.
402   ###
403
404   my %total_setup   = map { my $z = 0; $_ => \$z; } @passes;
405   my %total_recur   = map { my $z = 0; $_ => \$z; } @passes;
406
407   my %taxlisthash = map { $_ => {} } @passes;
408
409   my @precommit_hooks = ();
410
411   $options{'pkg_list'} ||= [ $self->ncancelled_pkgs ];  #param checks?
412   foreach my $cust_pkg ( @{ $options{'pkg_list'} } ) {
413
414     next if $options{'not_pkgpart'}->{$cust_pkg->pkgpart};
415
416     warn "  bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG;
417
418     #? to avoid use of uninitialized value errors... ?
419     $cust_pkg->setfield('bill', '')
420       unless defined($cust_pkg->bill);
421  
422     #my $part_pkg = $cust_pkg->part_pkg;
423
424     my $real_pkgpart = $cust_pkg->pkgpart;
425     my %hash = $cust_pkg->hash;
426
427     # we could implement this bit as FS::part_pkg::has_hidden, but we already
428     # suffer from performance issues
429     $options{has_hidden} = 0;
430     my @part_pkg = $cust_pkg->part_pkg->self_and_bill_linked;
431     $options{has_hidden} = 1 if ($part_pkg[1] && $part_pkg[1]->hidden);
432  
433     foreach my $part_pkg ( @part_pkg ) {
434
435       $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
436
437       my $pass = ($cust_pkg->no_auto || $part_pkg->no_auto) ? 'no_auto' : '';
438
439       my $next_bill = $cust_pkg->getfield('bill') || 0;
440       my $error;
441       while ( $next_bill <= $time ) {
442         $error =
443           $self->_make_lines( 'part_pkg'            => $part_pkg,
444                               'cust_pkg'            => $cust_pkg,
445                               'precommit_hooks'     => \@precommit_hooks,
446                               'line_items'          => $cust_bill_pkg{$pass},
447                               'setup'               => $total_setup{$pass},
448                               'recur'               => $total_recur{$pass},
449                               'tax_matrix'          => $taxlisthash{$pass},
450                               'time'                => $time,
451                               'real_pkgpart'        => $real_pkgpart,
452                               'options'             => \%options,
453                             );
454
455         # Stop if anything goes wrong
456         last if $error;
457
458         # or if we're not incrementing the bill date.
459         last if ($cust_pkg->getfield('bill') || 0) == $next_bill;
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}}) - 1] ) {
802       next unless ref($_) eq 'FS::cust_bill_pkg'; #IS needed for CCH tax-on-tax
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 || $cust_pkg->option('suspend_bill',1)
962                                || ( $part_pkg->option('suspend_bill', 1) )
963                                      && ! $cust_pkg->option('no_suspend_bill',1)
964                                   )
965        and
966             ( $part_pkg->freq ne '0' && ( $cust_pkg->bill || 0 ) <= day_end($time) )
967          || ( $part_pkg->plan eq 'voip_cdr'
968                && $part_pkg->option('bill_every_call')
969             )
970          || $options{cancel}
971   ) {
972
973     # XXX should this be a package event?  probably.  events are called
974     # at collection time at the moment, though...
975     $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
976       if $part_pkg->can('reset_usage') && !$options{'no_usage_reset'};
977       #don't want to reset usage just cause we want a line item??
978       #&& $part_pkg->pkgpart == $real_pkgpart;
979
980     warn "    bill recur\n" if $DEBUG > 1;
981     $lineitems++;
982
983     # XXX shared with $recur_prog
984     $sdate = ( $options{cancel} ? $cust_pkg->last_bill : $cust_pkg->bill )
985              || $cust_pkg->setup
986              || $time;
987
988     #over two params!  lets at least switch to a hashref for the rest...
989     my $increment_next_bill = ( $part_pkg->freq ne '0'
990                                 && ( $cust_pkg->getfield('bill') || 0 ) <= day_end($time)
991                                 && !$options{cancel}
992                               );
993     my %param = ( %setup_param,
994                   'precommit_hooks'     => $precommit_hooks,
995                   'increment_next_bill' => $increment_next_bill,
996                   'discounts'           => \@recur_discounts,
997                   'real_pkgpart'        => $real_pkgpart,
998                   'freq_override'       => $options{freq_override} || '',
999                   'setup_fee'           => 0,
1000                 );
1001
1002     my $method = $options{cancel} ? 'calc_cancel' : 'calc_recur';
1003
1004     # There may be some part_pkg for which this is wrong.  Only those
1005     # which can_discount are supported.
1006     # (the UI should prevent adding discounts to these at the moment)
1007
1008     warn "calling $method on cust_pkg ". $cust_pkg->pkgnum.
1009          " for pkgpart ". $cust_pkg->pkgpart.
1010          " with params ". join(' / ', map "$_=>$param{$_}", keys %param). "\n"
1011       if $DEBUG > 2;
1012            
1013     $recur = eval { $cust_pkg->$method( \$sdate, \@details, \%param ) };
1014     return "$@ running $method for $cust_pkg\n"
1015       if ( $@ );
1016
1017     if ( $increment_next_bill ) {
1018
1019       my $next_bill = $part_pkg->add_freq($sdate, $options{freq_override} || 0);
1020       return "unparsable frequency: ". $part_pkg->freq
1021         if $next_bill == -1;
1022   
1023       #pro-rating magic - if $recur_prog fiddled $sdate, want to use that
1024       # only for figuring next bill date, nothing else, so, reset $sdate again
1025       # here
1026       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1027       #no need, its in $hash{last_bill}# my $last_bill = $cust_pkg->last_bill;
1028       $cust_pkg->last_bill($sdate);
1029
1030       $cust_pkg->setfield('bill', $next_bill );
1031
1032     }
1033
1034     if ( $param{'setup_fee'} ) {
1035       # Add an additional setup fee at the billing stage.
1036       # Used for prorate_defer_bill.
1037       $setup += $param{'setup_fee'};
1038       $unitsetup += $param{'setup_fee'};
1039       $lineitems++;
1040     }
1041
1042     if ( defined $param{'discount_left_setup'} ) {
1043         foreach my $discount_setup ( values %{$param{'discount_left_setup'}} ) {
1044             $setup -= $discount_setup;
1045         }
1046     }
1047
1048   }
1049
1050   warn "\$setup is undefined" unless defined($setup);
1051   warn "\$recur is undefined" unless defined($recur);
1052   warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1053   
1054   ###
1055   # If there's line items, create em cust_bill_pkg records
1056   # If $cust_pkg has been modified, update it (if we're a real pkgpart)
1057   ###
1058
1059   if ( $lineitems ) {
1060
1061     if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
1062       # hmm.. and if just the options are modified in some weird price plan?
1063   
1064       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
1065         if $DEBUG >1;
1066   
1067       my $error = $cust_pkg->replace( $old_cust_pkg,
1068                                       'depend_jobnum'=>$options{depend_jobnum},
1069                                       'options' => { $cust_pkg->options },
1070                                     )
1071         unless $options{no_commit};
1072       return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
1073         if $error; #just in case
1074     }
1075   
1076     $setup = sprintf( "%.2f", $setup );
1077     $recur = sprintf( "%.2f", $recur );
1078     if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1079       return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1080     }
1081     if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1082       return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1083     }
1084
1085     my $discount_show_always = $conf->exists('discount-show-always')
1086                                && (    ($setup == 0 && scalar(@setup_discounts))
1087                                     || ($recur == 0 && scalar(@recur_discounts))
1088                                   );
1089
1090     if (    $setup != 0
1091          || $recur != 0
1092          || (!$part_pkg->hidden && $options{has_hidden}) #include some $0 lines
1093          || $discount_show_always
1094          || ($setup == 0 && $cust_pkg->_X_show_zero('setup'))
1095          || ($recur == 0 && $cust_pkg->_X_show_zero('recur'))
1096        ) 
1097     {
1098
1099       warn "    charges (setup=$setup, recur=$recur); adding line items\n"
1100         if $DEBUG > 1;
1101
1102       my @cust_pkg_detail = map { $_->detail } $cust_pkg->cust_pkg_detail('I');
1103       if ( $DEBUG > 1 ) {
1104         warn "      adding customer package invoice detail: $_\n"
1105           foreach @cust_pkg_detail;
1106       }
1107       push @details, @cust_pkg_detail;
1108
1109       my $cust_bill_pkg = new FS::cust_bill_pkg {
1110         'pkgnum'    => $cust_pkg->pkgnum,
1111         'setup'     => $setup,
1112         'unitsetup' => $unitsetup,
1113         'recur'     => $recur,
1114         'unitrecur' => $unitrecur,
1115         'quantity'  => $cust_pkg->quantity,
1116         'details'   => \@details,
1117         'discounts' => [ @setup_discounts, @recur_discounts ],
1118         'hidden'    => $part_pkg->hidden,
1119         'freq'      => $part_pkg->freq,
1120       };
1121
1122       if ( $part_pkg->option('prorate_defer_bill',1) 
1123            and !$hash{last_bill} ) {
1124         # both preceding and upcoming, technically
1125         $cust_bill_pkg->sdate( $cust_pkg->setup );
1126         $cust_bill_pkg->edate( $cust_pkg->bill );
1127       } elsif ( $part_pkg->recur_temporality eq 'preceding' ) {
1128         $cust_bill_pkg->sdate( $hash{last_bill} );
1129         $cust_bill_pkg->edate( $sdate - 86399   ); #60s*60m*24h-1
1130         $cust_bill_pkg->edate( $time ) if $options{cancel};
1131       } else { #if ( $part_pkg->recur_temporality eq 'upcoming' ) {
1132         $cust_bill_pkg->sdate( $sdate );
1133         $cust_bill_pkg->edate( $cust_pkg->bill );
1134         #$cust_bill_pkg->edate( $time ) if $options{cancel};
1135       }
1136
1137       $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
1138         unless $part_pkg->pkgpart == $real_pkgpart;
1139
1140       $$total_setup += $setup;
1141       $$total_recur += $recur;
1142
1143       ###
1144       # handle taxes
1145       ###
1146
1147       unless ( $discount_show_always ) {
1148           my $error = 
1149             $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg, $cust_pkg, $options{invoice_time}, $real_pkgpart, \%options);
1150           return $error if $error;
1151       }
1152
1153       push @$cust_bill_pkgs, $cust_bill_pkg;
1154
1155     } #if $setup != 0 || $recur != 0
1156       
1157   } #if $line_items
1158
1159   '';
1160
1161 }
1162
1163 sub _handle_taxes {
1164   my $self = shift;
1165   my $part_pkg = shift;
1166   my $taxlisthash = shift;
1167   my $cust_bill_pkg = shift;
1168   my $cust_pkg = shift;
1169   my $invoice_time = shift;
1170   my $real_pkgpart = shift;
1171   my $options = shift;
1172
1173   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1174
1175   my %cust_bill_pkg = ();
1176   my %taxes = ();
1177     
1178   my @classes;
1179   #push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->type eq 'U';
1180   push @classes, $cust_bill_pkg->usage_classes if $cust_bill_pkg->usage;
1181   push @classes, 'setup' if ($cust_bill_pkg->setup && !$options->{cancel});
1182   push @classes, 'recur' if ($cust_bill_pkg->recur && !$options->{cancel});
1183
1184   if ( $self->tax !~ /Y/i && $self->payby ne 'COMP' ) {
1185
1186     if ( $conf->exists('enable_taxproducts')
1187          && ( scalar($part_pkg->part_pkg_taxoverride)
1188               || $part_pkg->has_taxproduct
1189             )
1190        )
1191     {
1192
1193       foreach my $class (@classes) {
1194         my $err_or_ref = $self->_gather_taxes( $part_pkg, $class, $cust_pkg );
1195         return $err_or_ref unless ref($err_or_ref);
1196         $taxes{$class} = $err_or_ref;
1197       }
1198
1199       unless (exists $taxes{''}) {
1200         my $err_or_ref = $self->_gather_taxes( $part_pkg, '', $cust_pkg );
1201         return $err_or_ref unless ref($err_or_ref);
1202         $taxes{''} = $err_or_ref;
1203       }
1204
1205     } else {
1206
1207       my @loc_keys = qw( district city county state country );
1208       my %taxhash;
1209       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
1210         my $cust_location = $cust_pkg->cust_location;
1211         %taxhash = map { $_ => $cust_location->$_()    } @loc_keys;
1212       } else {
1213         my $prefix = 
1214           ( $conf->exists('tax-ship_address') && length($self->ship_last) )
1215           ? 'ship_'
1216           : '';
1217         %taxhash = map { $_ => $self->get("$prefix$_") } @loc_keys;
1218       }
1219
1220       $taxhash{'taxclass'} = $part_pkg->taxclass;
1221
1222       my @taxes = ();
1223       my %taxhash_elim = %taxhash;
1224       my @elim = qw( district city county state );
1225       do { 
1226
1227         #first try a match with taxclass
1228         @taxes = qsearch( 'cust_main_county', \%taxhash_elim );
1229
1230         if ( !scalar(@taxes) && $taxhash_elim{'taxclass'} ) {
1231           #then try a match without taxclass
1232           my %no_taxclass = %taxhash_elim;
1233           $no_taxclass{ 'taxclass' } = '';
1234           @taxes = qsearch( 'cust_main_county', \%no_taxclass );
1235         }
1236
1237         $taxhash_elim{ shift(@elim) } = '';
1238
1239       } while ( !scalar(@taxes) && scalar(@elim) );
1240
1241       @taxes = grep { ! $_->taxname or ! $self->tax_exemption($_->taxname) }
1242                     @taxes
1243         if $self->cust_main_exemption; #just to be safe
1244
1245       if ( $conf->exists('tax-pkg_address') && $cust_pkg->locationnum ) {
1246         foreach (@taxes) {
1247           $_->set('pkgnum',      $cust_pkg->pkgnum );
1248           $_->set('locationnum', $cust_pkg->locationnum );
1249         }
1250       }
1251
1252       $taxes{''} = [ @taxes ];
1253       $taxes{'setup'} = [ @taxes ];
1254       $taxes{'recur'} = [ @taxes ];
1255       $taxes{$_} = [ @taxes ] foreach (@classes);
1256
1257       # # maybe eliminate this entirely, along with all the 0% records
1258       # unless ( @taxes ) {
1259       #   return
1260       #     "fatal: can't find tax rate for state/county/country/taxclass ".
1261       #     join('/', map $taxhash{$_}, qw(state county country taxclass) );
1262       # }
1263
1264     } #if $conf->exists('enable_taxproducts') ...
1265
1266   }
1267
1268   #what's this doing in the middle of _handle_taxes?  probably should split
1269   #this into three parts above in _make_lines
1270   $cust_bill_pkg->set_display(   part_pkg     => $part_pkg,
1271                                  real_pkgpart => $real_pkgpart,
1272                              );
1273
1274   my %tax_cust_bill_pkg = $cust_bill_pkg->disintegrate;
1275   foreach my $key (keys %tax_cust_bill_pkg) {
1276     my @taxes = @{ $taxes{$key} || [] };
1277     my $tax_cust_bill_pkg = $tax_cust_bill_pkg{$key};
1278
1279     my %localtaxlisthash = ();
1280     foreach my $tax ( @taxes ) {
1281
1282       my $taxname = ref( $tax ). ' '. $tax->taxnum;
1283 #      $taxname .= ' pkgnum'. $cust_pkg->pkgnum.
1284 #                  ' locationnum'. $cust_pkg->locationnum
1285 #        if $conf->exists('tax-pkg_address') && $cust_pkg->locationnum;
1286
1287       $taxlisthash->{ $taxname } ||= [ $tax ];
1288       push @{ $taxlisthash->{ $taxname  } }, $tax_cust_bill_pkg;
1289
1290       $localtaxlisthash{ $taxname } ||= [ $tax ];
1291       push @{ $localtaxlisthash{ $taxname  } }, $tax_cust_bill_pkg;
1292
1293     }
1294
1295     warn "finding taxed taxes...\n" if $DEBUG > 2;
1296     foreach my $tax ( keys %localtaxlisthash ) {
1297       my $tax_object = shift @{ $localtaxlisthash{$tax} };
1298       warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
1299         if $DEBUG > 2;
1300       next unless $tax_object->can('tax_on_tax');
1301
1302       foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
1303         my $totname = ref( $tot ). ' '. $tot->taxnum;
1304
1305         warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
1306           if $DEBUG > 2;
1307         next unless exists( $localtaxlisthash{ $totname } ); # only increase
1308                                                              # existing taxes
1309         warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
1310         my $hashref_or_error = 
1311           $tax_object->taxline( $localtaxlisthash{$tax},
1312                                 'custnum'      => $self->custnum,
1313                                 'invoice_time' => $invoice_time,
1314                               );
1315         return $hashref_or_error
1316           unless ref($hashref_or_error);
1317         
1318         $taxlisthash->{ $totname } ||= [ $tot ];
1319         push @{ $taxlisthash->{ $totname  } }, $hashref_or_error->{amount};
1320
1321       }
1322     }
1323
1324   }
1325
1326   '';
1327 }
1328
1329 sub _gather_taxes {
1330   my $self = shift;
1331   my $part_pkg = shift;
1332   my $class = shift;
1333   my $cust_pkg = shift;
1334
1335   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1336
1337   my $geocode;
1338   if ( $cust_pkg->locationnum && $conf->exists('tax-pkg_address') ) {
1339     $geocode = $cust_pkg->cust_location->geocode('cch');
1340   } else {
1341     $geocode = $self->geocode('cch');
1342   }
1343
1344   my @taxes = ();
1345
1346   my @taxclassnums = map { $_->taxclassnum }
1347                      $part_pkg->part_pkg_taxoverride($class);
1348
1349   unless (@taxclassnums) {
1350     @taxclassnums = map { $_->taxclassnum }
1351                     grep { $_->taxable eq 'Y' }
1352                     $part_pkg->part_pkg_taxrate('cch', $geocode, $class);
1353   }
1354   warn "Found taxclassnum values of ". join(',', @taxclassnums)
1355     if $DEBUG;
1356
1357   my $extra_sql =
1358     "AND (".
1359     join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
1360
1361   @taxes = qsearch({ 'table' => 'tax_rate',
1362                      'hashref' => { 'geocode' => $geocode, },
1363                      'extra_sql' => $extra_sql,
1364                   })
1365     if scalar(@taxclassnums);
1366
1367   warn "Found taxes ".
1368        join(',', map{ ref($_). " ". $_->get($_->primary_key) } @taxes). "\n" 
1369    if $DEBUG;
1370
1371   [ @taxes ];
1372
1373 }
1374
1375 =item collect [ HASHREF | OPTION => VALUE ... ]
1376
1377 (Attempt to) collect money for this customer's outstanding invoices (see
1378 L<FS::cust_bill>).  Usually used after the bill method.
1379
1380 Actions are now triggered by billing events; see L<FS::part_event> and the
1381 billing events web interface.  Old-style invoice events (see
1382 L<FS::part_bill_event>) have been deprecated.
1383
1384 If there is an error, returns the error, otherwise returns false.
1385
1386 Options are passed as name-value pairs.
1387
1388 Currently available options are:
1389
1390 =over 4
1391
1392 =item invoice_time
1393
1394 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.
1395
1396 =item retry
1397
1398 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1399
1400 =item check_freq
1401
1402 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1403
1404 =item quiet
1405
1406 set true to surpress email card/ACH decline notices.
1407
1408 =item debug
1409
1410 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)
1411
1412 =back
1413
1414 # =item payby
1415 #
1416 # allows for one time override of normal customer billing method
1417
1418 =cut
1419
1420 sub collect {
1421   my( $self, %options ) = @_;
1422
1423   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1424
1425   my $invoice_time = $options{'invoice_time'} || time;
1426
1427   #put below somehow?
1428   local $SIG{HUP} = 'IGNORE';
1429   local $SIG{INT} = 'IGNORE';
1430   local $SIG{QUIT} = 'IGNORE';
1431   local $SIG{TERM} = 'IGNORE';
1432   local $SIG{TSTP} = 'IGNORE';
1433   local $SIG{PIPE} = 'IGNORE';
1434
1435   my $oldAutoCommit = $FS::UID::AutoCommit;
1436   local $FS::UID::AutoCommit = 0;
1437   my $dbh = dbh;
1438
1439   $self->select_for_update; #mutex
1440
1441   if ( $DEBUG ) {
1442     my $balance = $self->balance;
1443     warn "$me collect customer ". $self->custnum. ": balance $balance\n"
1444   }
1445
1446   if ( exists($options{'retry_card'}) ) {
1447     carp 'retry_card option passed to collect is deprecated; use retry';
1448     $options{'retry'} ||= $options{'retry_card'};
1449   }
1450   if ( exists($options{'retry'}) && $options{'retry'} ) {
1451     my $error = $self->retry_realtime;
1452     if ( $error ) {
1453       $dbh->rollback if $oldAutoCommit;
1454       return $error;
1455     }
1456   }
1457
1458   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1459
1460   #never want to roll back an event just because it returned an error
1461   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1462
1463   $self->do_cust_event(
1464     'debug'      => ( $options{'debug'} || 0 ),
1465     'time'       => $invoice_time,
1466     'check_freq' => $options{'check_freq'},
1467     'stage'      => 'collect',
1468   );
1469
1470 }
1471
1472 =item retry_realtime
1473
1474 Schedules realtime / batch  credit card / electronic check / LEC billing
1475 events for for retry.  Useful if card information has changed or manual
1476 retry is desired.  The 'collect' method must be called to actually retry
1477 the transaction.
1478
1479 Implementation details: For either this customer, or for each of this
1480 customer's open invoices, changes the status of the first "done" (with
1481 statustext error) realtime processing event to "failed".
1482
1483 =cut
1484
1485 sub retry_realtime {
1486   my $self = shift;
1487
1488   local $SIG{HUP} = 'IGNORE';
1489   local $SIG{INT} = 'IGNORE';
1490   local $SIG{QUIT} = 'IGNORE';
1491   local $SIG{TERM} = 'IGNORE';
1492   local $SIG{TSTP} = 'IGNORE';
1493   local $SIG{PIPE} = 'IGNORE';
1494
1495   my $oldAutoCommit = $FS::UID::AutoCommit;
1496   local $FS::UID::AutoCommit = 0;
1497   my $dbh = dbh;
1498
1499   #a little false laziness w/due_cust_event (not too bad, really)
1500
1501   my $join = FS::part_event_condition->join_conditions_sql;
1502   my $order = FS::part_event_condition->order_conditions_sql;
1503   my $mine = 
1504   '( '
1505    . join ( ' OR ' , map { 
1506     "( part_event.eventtable = " . dbh->quote($_) 
1507     . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
1508    } FS::part_event->eventtables)
1509    . ') ';
1510
1511   #here is the agent virtualization
1512   my $agent_virt = " (    part_event.agentnum IS NULL
1513                        OR part_event.agentnum = ". $self->agentnum. ' )';
1514
1515   #XXX this shouldn't be hardcoded, actions should declare it...
1516   my @realtime_events = qw(
1517     cust_bill_realtime_card
1518     cust_bill_realtime_check
1519     cust_bill_realtime_lec
1520     cust_bill_batch
1521   );
1522
1523   my $is_realtime_event =
1524     ' part_event.action IN ( '.
1525         join(',', map "'$_'", @realtime_events ).
1526     ' ) ';
1527
1528   my $batch_or_statustext =
1529     "( part_event.action = 'cust_bill_batch'
1530        OR ( statustext IS NOT NULL AND statustext != '' )
1531      )";
1532
1533
1534   my @cust_event = qsearch({
1535     'table'     => 'cust_event',
1536     'select'    => 'cust_event.*',
1537     'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
1538     'hashref'   => { 'status' => 'done' },
1539     'extra_sql' => " AND $batch_or_statustext ".
1540                    " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
1541   });
1542
1543   my %seen_invnum = ();
1544   foreach my $cust_event (@cust_event) {
1545
1546     #max one for the customer, one for each open invoice
1547     my $cust_X = $cust_event->cust_X;
1548     next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
1549                           ? $cust_X->invnum
1550                           : 0
1551                         }++
1552          or $cust_event->part_event->eventtable eq 'cust_bill'
1553             && ! $cust_X->owed;
1554
1555     my $error = $cust_event->retry;
1556     if ( $error ) {
1557       $dbh->rollback if $oldAutoCommit;
1558       return "error scheduling event for retry: $error";
1559     }
1560
1561   }
1562
1563   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1564   '';
1565
1566 }
1567
1568 =item do_cust_event [ HASHREF | OPTION => VALUE ... ]
1569
1570 Runs billing events; see L<FS::part_event> and the billing events web
1571 interface.
1572
1573 If there is an error, returns the error, otherwise returns false.
1574
1575 Options are passed as name-value pairs.
1576
1577 Currently available options are:
1578
1579 =over 4
1580
1581 =item time
1582
1583 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.
1584
1585 =item check_freq
1586
1587 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1588
1589 =item stage
1590
1591 "collect" (the default) or "pre-bill"
1592
1593 =item quiet
1594  
1595 set true to surpress email card/ACH decline notices.
1596
1597 =item debug
1598
1599 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)
1600
1601 =back
1602 =cut
1603
1604 # =item payby
1605 #
1606 # allows for one time override of normal customer billing method
1607
1608 # =item retry
1609 #
1610 # Retry card/echeck/LEC transactions even when not scheduled by invoice events.
1611
1612 sub do_cust_event {
1613   my( $self, %options ) = @_;
1614
1615   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1616
1617   my $time = $options{'time'} || time;
1618
1619   #put below somehow?
1620   local $SIG{HUP} = 'IGNORE';
1621   local $SIG{INT} = 'IGNORE';
1622   local $SIG{QUIT} = 'IGNORE';
1623   local $SIG{TERM} = 'IGNORE';
1624   local $SIG{TSTP} = 'IGNORE';
1625   local $SIG{PIPE} = 'IGNORE';
1626
1627   my $oldAutoCommit = $FS::UID::AutoCommit;
1628   local $FS::UID::AutoCommit = 0;
1629   my $dbh = dbh;
1630
1631   $self->select_for_update; #mutex
1632
1633   if ( $DEBUG ) {
1634     my $balance = $self->balance;
1635     warn "$me do_cust_event customer ". $self->custnum. ": balance $balance\n"
1636   }
1637
1638 #  if ( exists($options{'retry_card'}) ) {
1639 #    carp 'retry_card option passed to collect is deprecated; use retry';
1640 #    $options{'retry'} ||= $options{'retry_card'};
1641 #  }
1642 #  if ( exists($options{'retry'}) && $options{'retry'} ) {
1643 #    my $error = $self->retry_realtime;
1644 #    if ( $error ) {
1645 #      $dbh->rollback if $oldAutoCommit;
1646 #      return $error;
1647 #    }
1648 #  }
1649
1650   # false laziness w/pay_batch::import_results
1651
1652   my $due_cust_event = $self->due_cust_event(
1653     'debug'      => ( $options{'debug'} || 0 ),
1654     'time'       => $time,
1655     'check_freq' => $options{'check_freq'},
1656     'stage'      => ( $options{'stage'} || 'collect' ),
1657   );
1658   unless( ref($due_cust_event) ) {
1659     $dbh->rollback if $oldAutoCommit;
1660     return $due_cust_event;
1661   }
1662
1663   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1664   #never want to roll back an event just because it or a different one
1665   # returned an error
1666   local $FS::UID::AutoCommit = 1; #$oldAutoCommit;
1667
1668   foreach my $cust_event ( @$due_cust_event ) {
1669
1670     #XXX lock event
1671     
1672     #re-eval event conditions (a previous event could have changed things)
1673     unless ( $cust_event->test_conditions( 'time' => $time ) ) {
1674       #don't leave stray "new/locked" records around
1675       my $error = $cust_event->delete;
1676       return $error if $error;
1677       next;
1678     }
1679
1680     {
1681       local $FS::cust_main::Billing_Realtime::realtime_bop_decline_quiet = 1
1682         if $options{'quiet'};
1683       warn "  running cust_event ". $cust_event->eventnum. "\n"
1684         if $DEBUG > 1;
1685
1686       #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
1687       if ( my $error = $cust_event->do_event( 'time' => $time ) ) {
1688         #XXX wtf is this?  figure out a proper dealio with return value
1689         #from do_event
1690         return $error;
1691       }
1692     }
1693
1694   }
1695
1696   '';
1697
1698 }
1699
1700 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
1701
1702 Inserts database records for and returns an ordered listref of new events due
1703 for this customer, as FS::cust_event objects (see L<FS::cust_event>).  If no
1704 events are due, an empty listref is returned.  If there is an error, returns a
1705 scalar error message.
1706
1707 To actually run the events, call each event's test_condition method, and if
1708 still true, call the event's do_event method.
1709
1710 Options are passed as a hashref or as a list of name-value pairs.  Available
1711 options are:
1712
1713 =over 4
1714
1715 =item check_freq
1716
1717 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.
1718
1719 =item stage
1720
1721 "collect" (the default) or "pre-bill"
1722
1723 =item time
1724
1725 "Current time" for the events.
1726
1727 =item debug
1728
1729 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)
1730
1731 =item eventtable
1732
1733 Only return events for the specified eventtable (by default, events of all eventtables are returned)
1734
1735 =item objects
1736
1737 Explicitly pass the objects to be tested (typically used with eventtable).
1738
1739 =item testonly
1740
1741 Set to true to return the objects, but not actually insert them into the
1742 database.
1743
1744 =back
1745
1746 =cut
1747
1748 sub due_cust_event {
1749   my $self = shift;
1750   my %opt = ref($_[0]) ? %{ $_[0] } : @_;
1751
1752   #???
1753   #my $DEBUG = $opt{'debug'}
1754   $opt{'debug'} ||= 0; # silence some warnings
1755   local($DEBUG) = $opt{'debug'}
1756     if $opt{'debug'} > $DEBUG;
1757   $DEBUG = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1758
1759   warn "$me due_cust_event called with options ".
1760        join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
1761     if $DEBUG;
1762
1763   $opt{'time'} ||= time;
1764
1765   local $SIG{HUP} = 'IGNORE';
1766   local $SIG{INT} = 'IGNORE';
1767   local $SIG{QUIT} = 'IGNORE';
1768   local $SIG{TERM} = 'IGNORE';
1769   local $SIG{TSTP} = 'IGNORE';
1770   local $SIG{PIPE} = 'IGNORE';
1771
1772   my $oldAutoCommit = $FS::UID::AutoCommit;
1773   local $FS::UID::AutoCommit = 0;
1774   my $dbh = dbh;
1775
1776   $self->select_for_update #mutex
1777     unless $opt{testonly};
1778
1779   ###
1780   # find possible events (initial search)
1781   ###
1782   
1783   my @cust_event = ();
1784
1785   my @eventtable = $opt{'eventtable'}
1786                      ? ( $opt{'eventtable'} )
1787                      : FS::part_event->eventtables_runorder;
1788
1789   my $check_freq = $opt{'check_freq'} || '1d';
1790
1791   foreach my $eventtable ( @eventtable ) {
1792
1793     my @objects;
1794     if ( $opt{'objects'} ) {
1795
1796       @objects = @{ $opt{'objects'} };
1797
1798     } else {
1799
1800       #my @objects = $self->$eventtable(); # sub cust_main { @{ [ $self ] }; }
1801       if ( $eventtable eq 'cust_main' ) {
1802         @objects = ( $self );
1803       } else {
1804
1805         my $cm_join =
1806           "LEFT JOIN cust_main USING ( custnum )";
1807
1808         #some false laziness w/Cron::bill bill_where
1809
1810         my $join  = FS::part_event_condition->join_conditions_sql( $eventtable);
1811         my $where = FS::part_event_condition->where_conditions_sql($eventtable,
1812                                                            'time'=>$opt{'time'},
1813                                                                   );
1814         $where = $where ? "AND $where" : '';
1815
1816         my $are_part_event = 
1817           "EXISTS ( SELECT 1 FROM part_event $join
1818                       WHERE check_freq = '$check_freq'
1819                         AND eventtable = '$eventtable'
1820                         AND ( disabled = '' OR disabled IS NULL )
1821                         $where
1822                   )
1823           ";
1824         #eofalse
1825
1826         @objects = $self->$eventtable(
1827                      'addl_from' => $cm_join,
1828                      'extra_sql' => " AND $are_part_event",
1829                    );
1830       }
1831
1832     }
1833
1834     my @e_cust_event = ();
1835
1836     my $cross = "CROSS JOIN $eventtable";
1837     $cross .= ' LEFT JOIN cust_main USING ( custnum )'
1838       unless $eventtable eq 'cust_main';
1839
1840     foreach my $object ( @objects ) {
1841
1842       #this first search uses the condition_sql magic for optimization.
1843       #the more possible events we can eliminate in this step the better
1844
1845       my $cross_where = '';
1846       my $pkey = $object->primary_key;
1847       $cross_where = "$eventtable.$pkey = ". $object->$pkey();
1848
1849       my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
1850       my $extra_sql =
1851         FS::part_event_condition->where_conditions_sql( $eventtable,
1852                                                         'time'=>$opt{'time'}
1853                                                       );
1854       my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
1855
1856       $extra_sql = "AND $extra_sql" if $extra_sql;
1857
1858       #here is the agent virtualization
1859       $extra_sql .= " AND (    part_event.agentnum IS NULL
1860                             OR part_event.agentnum = ". $self->agentnum. ' )';
1861
1862       $extra_sql .= " $order";
1863
1864       warn "searching for events for $eventtable ". $object->$pkey. "\n"
1865         if $opt{'debug'} > 2;
1866       my @part_event = qsearch( {
1867         'debug'     => ( $opt{'debug'} > 3 ? 1 : 0 ),
1868         'select'    => 'part_event.*',
1869         'table'     => 'part_event',
1870         'addl_from' => "$cross $join",
1871         'hashref'   => { 'check_freq' => $check_freq,
1872                          'eventtable' => $eventtable,
1873                          'disabled'   => '',
1874                        },
1875         'extra_sql' => "AND $cross_where $extra_sql",
1876       } );
1877
1878       if ( $DEBUG > 2 ) {
1879         my $pkey = $object->primary_key;
1880         warn "      ". scalar(@part_event).
1881              " possible events found for $eventtable ". $object->$pkey(). "\n";
1882       }
1883
1884       push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
1885
1886     }
1887
1888     warn "    ". scalar(@e_cust_event).
1889          " subtotal possible cust events found for $eventtable\n"
1890       if $DEBUG > 1;
1891
1892     push @cust_event, @e_cust_event;
1893
1894   }
1895
1896   warn "  ". scalar(@cust_event).
1897        " total possible cust events found in initial search\n"
1898     if $DEBUG; # > 1;
1899
1900
1901   ##
1902   # test stage
1903   ##
1904
1905   $opt{stage} ||= 'collect';
1906   @cust_event =
1907     grep { my $stage = $_->part_event->event_stage;
1908            $opt{stage} eq $stage or ( ! $stage && $opt{stage} eq 'collect' )
1909          }
1910          @cust_event;
1911
1912   ##
1913   # test conditions
1914   ##
1915   
1916   my %unsat = ();
1917
1918   @cust_event = grep $_->test_conditions( 'time'          => $opt{'time'},
1919                                           'stats_hashref' => \%unsat ),
1920                      @cust_event;
1921
1922   warn "  ". scalar(@cust_event). " cust events left satisfying conditions\n"
1923     if $DEBUG; # > 1;
1924
1925   warn "    invalid conditions not eliminated with condition_sql:\n".
1926        join('', map "      $_: ".$unsat{$_}."\n", keys %unsat )
1927     if keys %unsat && $DEBUG; # > 1;
1928
1929   ##
1930   # insert
1931   ##
1932
1933   unless( $opt{testonly} ) {
1934     foreach my $cust_event ( @cust_event ) {
1935
1936       my $error = $cust_event->insert();
1937       if ( $error ) {
1938         $dbh->rollback if $oldAutoCommit;
1939         return $error;
1940       }
1941                                        
1942     }
1943   }
1944
1945   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1946
1947   ##
1948   # return
1949   ##
1950
1951   warn "  returning events: ". Dumper(@cust_event). "\n"
1952     if $DEBUG > 2;
1953
1954   \@cust_event;
1955
1956 }
1957
1958 =item apply_payments_and_credits [ OPTION => VALUE ... ]
1959
1960 Applies unapplied payments and credits.
1961
1962 In most cases, this new method should be used in place of sequential
1963 apply_payments and apply_credits methods.
1964
1965 A hash of optional arguments may be passed.  Currently "manual" is supported.
1966 If true, a payment receipt is sent instead of a statement when
1967 'payment_receipt_email' configuration option is set.
1968
1969 If there is an error, returns the error, otherwise returns false.
1970
1971 =cut
1972
1973 sub apply_payments_and_credits {
1974   my( $self, %options ) = @_;
1975
1976   local $SIG{HUP} = 'IGNORE';
1977   local $SIG{INT} = 'IGNORE';
1978   local $SIG{QUIT} = 'IGNORE';
1979   local $SIG{TERM} = 'IGNORE';
1980   local $SIG{TSTP} = 'IGNORE';
1981   local $SIG{PIPE} = 'IGNORE';
1982
1983   my $oldAutoCommit = $FS::UID::AutoCommit;
1984   local $FS::UID::AutoCommit = 0;
1985   my $dbh = dbh;
1986
1987   $self->select_for_update; #mutex
1988
1989   foreach my $cust_bill ( $self->open_cust_bill ) {
1990     my $error = $cust_bill->apply_payments_and_credits(%options);
1991     if ( $error ) {
1992       $dbh->rollback if $oldAutoCommit;
1993       return "Error applying: $error";
1994     }
1995   }
1996
1997   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1998   ''; #no error
1999
2000 }
2001
2002 =item apply_credits OPTION => VALUE ...
2003
2004 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2005 to outstanding invoice balances in chronological order (or reverse
2006 chronological order if the I<order> option is set to B<newest>) and returns the
2007 value of any remaining unapplied credits available for refund (see
2008 L<FS::cust_refund>).
2009
2010 Dies if there is an error.
2011
2012 =cut
2013
2014 sub apply_credits {
2015   my $self = shift;
2016   my %opt = @_;
2017
2018   local $SIG{HUP} = 'IGNORE';
2019   local $SIG{INT} = 'IGNORE';
2020   local $SIG{QUIT} = 'IGNORE';
2021   local $SIG{TERM} = 'IGNORE';
2022   local $SIG{TSTP} = 'IGNORE';
2023   local $SIG{PIPE} = 'IGNORE';
2024
2025   my $oldAutoCommit = $FS::UID::AutoCommit;
2026   local $FS::UID::AutoCommit = 0;
2027   my $dbh = dbh;
2028
2029   $self->select_for_update; #mutex
2030
2031   unless ( $self->total_unapplied_credits ) {
2032     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2033     return 0;
2034   }
2035
2036   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2037       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2038
2039   my @invoices = $self->open_cust_bill;
2040   @invoices = sort { $b->_date <=> $a->_date } @invoices
2041     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2042
2043   if ( $conf->exists('pkg-balances') ) {
2044     # limit @credits to those w/ a pkgnum grepped from $self
2045     my %pkgnums = ();
2046     foreach my $i (@invoices) {
2047       foreach my $li ( $i->cust_bill_pkg ) {
2048         $pkgnums{$li->pkgnum} = 1;
2049       }
2050     }
2051     @credits = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
2052   }
2053
2054   my $credit;
2055
2056   foreach my $cust_bill ( @invoices ) {
2057
2058     if ( !defined($credit) || $credit->credited == 0) {
2059       $credit = pop @credits or last;
2060     }
2061
2062     my $owed;
2063     if ( $conf->exists('pkg-balances') && $credit->pkgnum ) {
2064       $owed = $cust_bill->owed_pkgnum($credit->pkgnum);
2065     } else {
2066       $owed = $cust_bill->owed;
2067     }
2068     unless ( $owed > 0 ) {
2069       push @credits, $credit;
2070       next;
2071     }
2072
2073     my $amount = min( $credit->credited, $owed );
2074     
2075     my $cust_credit_bill = new FS::cust_credit_bill ( {
2076       'crednum' => $credit->crednum,
2077       'invnum'  => $cust_bill->invnum,
2078       'amount'  => $amount,
2079     } );
2080     $cust_credit_bill->pkgnum( $credit->pkgnum )
2081       if $conf->exists('pkg-balances') && $credit->pkgnum;
2082     my $error = $cust_credit_bill->insert;
2083     if ( $error ) {
2084       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2085       die $error;
2086     }
2087     
2088     redo if ($cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2089
2090   }
2091
2092   my $total_unapplied_credits = $self->total_unapplied_credits;
2093
2094   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2095
2096   return $total_unapplied_credits;
2097 }
2098
2099 =item apply_payments  [ OPTION => VALUE ... ]
2100
2101 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2102 to outstanding invoice balances in chronological order.
2103
2104  #and returns the value of any remaining unapplied payments.
2105
2106 A hash of optional arguments may be passed.  Currently "manual" is supported.
2107 If true, a payment receipt is sent instead of a statement when
2108 'payment_receipt_email' configuration option is set.
2109
2110 Dies if there is an error.
2111
2112 =cut
2113
2114 sub apply_payments {
2115   my( $self, %options ) = @_;
2116
2117   local $SIG{HUP} = 'IGNORE';
2118   local $SIG{INT} = 'IGNORE';
2119   local $SIG{QUIT} = 'IGNORE';
2120   local $SIG{TERM} = 'IGNORE';
2121   local $SIG{TSTP} = 'IGNORE';
2122   local $SIG{PIPE} = 'IGNORE';
2123
2124   my $oldAutoCommit = $FS::UID::AutoCommit;
2125   local $FS::UID::AutoCommit = 0;
2126   my $dbh = dbh;
2127
2128   $self->select_for_update; #mutex
2129
2130   #return 0 unless
2131
2132   my @payments = sort { $b->_date <=> $a->_date }
2133                  grep { $_->unapplied > 0 }
2134                  $self->cust_pay;
2135
2136   my @invoices = sort { $a->_date <=> $b->_date}
2137                  grep { $_->owed > 0 }
2138                  $self->cust_bill;
2139
2140   if ( $conf->exists('pkg-balances') ) {
2141     # limit @payments to those w/ a pkgnum grepped from $self
2142     my %pkgnums = ();
2143     foreach my $i (@invoices) {
2144       foreach my $li ( $i->cust_bill_pkg ) {
2145         $pkgnums{$li->pkgnum} = 1;
2146       }
2147     }
2148     @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
2149   }
2150
2151   my $payment;
2152
2153   foreach my $cust_bill ( @invoices ) {
2154
2155     if ( !defined($payment) || $payment->unapplied == 0 ) {
2156       $payment = pop @payments or last;
2157     }
2158
2159     my $owed;
2160     if ( $conf->exists('pkg-balances') && $payment->pkgnum ) {
2161       $owed = $cust_bill->owed_pkgnum($payment->pkgnum);
2162     } else {
2163       $owed = $cust_bill->owed;
2164     }
2165     unless ( $owed > 0 ) {
2166       push @payments, $payment;
2167       next;
2168     }
2169
2170     my $amount = min( $payment->unapplied, $owed );
2171
2172     my $cbp = {
2173       'paynum' => $payment->paynum,
2174       'invnum' => $cust_bill->invnum,
2175       'amount' => $amount,
2176     };
2177     $cbp->{_date} = $payment->_date 
2178         if $options{'manual'} && $options{'backdate_application'};
2179     my $cust_bill_pay = new FS::cust_bill_pay($cbp);
2180     $cust_bill_pay->pkgnum( $payment->pkgnum )
2181       if $conf->exists('pkg-balances') && $payment->pkgnum;
2182     my $error = $cust_bill_pay->insert(%options);
2183     if ( $error ) {
2184       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2185       die $error;
2186     }
2187
2188     redo if ( $cust_bill->owed > 0) && ! $conf->exists('pkg-balances');
2189
2190   }
2191
2192   my $total_unapplied_payments = $self->total_unapplied_payments;
2193
2194   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2195
2196   return $total_unapplied_payments;
2197 }
2198
2199 =back
2200
2201 =head1 FLOW
2202
2203   bill_and_collect
2204
2205     cancel_expired_pkgs
2206     suspend_adjourned_pkgs
2207     unsuspend_resumed_pkgs
2208
2209     bill
2210       (do_cust_event pre-bill)
2211       _make_lines
2212         _handle_taxes
2213           (vendor-only) _gather_taxes
2214       _omit_zero_value_bundles
2215       calculate_taxes
2216
2217     apply_payments_and_credits
2218     collect
2219       do_cust_event
2220         due_cust_event
2221
2222 =head1 BUGS
2223
2224 =head1 SEE ALSO
2225
2226 L<FS::cust_main>, L<FS::cust_main::Billing_Realtime>
2227
2228 =cut
2229
2230 1;