svc_cable.providernum is optional, RT#22009
[freeside.git] / FS / FS / cust_bill_ApplicationCommon.pm
1 package FS::cust_bill_ApplicationCommon;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $me $skip_apply_to_lineitems_hack $date_format );
5 use List::Util qw(min);
6 use Date::Format;
7 use FS::Schema qw( dbdef );
8 use FS::UID;
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::cust_pkg;
11 use FS::cust_svc;
12 use FS::cust_bill_pkg;
13 use FS::part_svc;
14 use FS::part_export;
15
16 @ISA = qw( FS::Record );
17
18 $DEBUG = 0;
19 $me = '[FS::cust_bill_ApplicationCommon]';
20
21 $skip_apply_to_lineitems_hack = 0;
22
23 FS::UID->install_callback( sub { 
24   my $conf = new FS::Conf;
25   $date_format = $conf->config('date_format') || '%x'; #/YY
26 } );
27
28 =head1 NAME
29
30 FS::cust_bill_ApplicationCommon - Base class for bill application classes
31
32 =head1 SYNOPSIS
33
34 use FS::cust_bill_ApplicationCommon;
35
36 @ISA = qw( FS::cust_bill_ApplicationCommon );
37
38 sub _app_source_name  { 'payment'; }
39 sub _app_source_table { 'cust_pay'; }
40 sub _app_lineitem_breakdown_table { 'cust_bill_pay_pkg'; }
41
42 =head1 DESCRIPTION
43
44 FS::cust_bill_ApplicationCommon is intended as a base class for classes which
45 represent application of things to invoices, currently payments
46 (see L<FS::cust_bill_pay>) or credits (see L<FS::cust_credit_bill>).
47
48 =head1 METHODS
49
50 =over 4
51
52 =item insert
53
54 =cut
55
56 sub insert {
57   my $self = shift;
58
59   local $SIG{HUP} = 'IGNORE';
60   local $SIG{INT} = 'IGNORE';
61   local $SIG{QUIT} = 'IGNORE';
62   local $SIG{TERM} = 'IGNORE';
63   local $SIG{TSTP} = 'IGNORE';
64   local $SIG{PIPE} = 'IGNORE';
65
66   my $oldAutoCommit = $FS::UID::AutoCommit;
67   local $FS::UID::AutoCommit = 0;
68   my $dbh = dbh;
69
70   my $error =    $self->SUPER::insert(@_)
71               || $self->apply_to_lineitems(@_);
72   if ( $error ) {
73     $dbh->rollback if $oldAutoCommit;
74     return $error;
75   }
76
77   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
78
79   '';
80
81 }
82
83 =item delete
84
85 =cut
86
87 sub delete {
88   my $self = shift;
89
90   local $SIG{HUP} = 'IGNORE';
91   local $SIG{INT} = 'IGNORE';
92   local $SIG{QUIT} = 'IGNORE';
93   local $SIG{TERM} = 'IGNORE';
94   local $SIG{TSTP} = 'IGNORE';
95   local $SIG{PIPE} = 'IGNORE';
96
97   my $oldAutoCommit = $FS::UID::AutoCommit;
98   local $FS::UID::AutoCommit = 0;
99   my $dbh = dbh;
100
101   foreach my $app ( $self->lineitem_applications ) {
102     my $error = $app->delete;
103     if ( $error ) {
104       $dbh->rollback if $oldAutoCommit;
105       return $error;
106     }
107   }
108
109   my $error = $self->SUPER::delete(@_);
110   if ( $error ) {
111     $dbh->rollback if $oldAutoCommit;
112     return $error;
113   }
114
115   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
116
117   '';
118
119 }
120
121 =item apply_to_lineitems
122
123 Auto-applies this invoice application to specific line items, if possible.
124
125 =cut
126
127 sub calculate_applications {
128   my( $self, %options ) = @_;
129
130   return '' if $skip_apply_to_lineitems_hack;
131
132   my @apply = ();
133
134   my $conf = new FS::Conf;
135
136   my @open = $self->cust_bill->open_cust_bill_pkg; #FOR UPDATE...?
137
138   if ( exists($options{subitems}) ) {
139     my $i = 0;
140     my %open = ();
141     $open{$_->billpkgnum} = $i++ foreach @open;
142
143     foreach my $listref ( @{$options{subitems}} ) {
144       my ($billpkgnum, $itemamount, $taxlocationnum) = @$listref;
145       return "Can't apply a ". $self->_app_source_name. ' of $'. $listref->[1].
146              " to line item $billpkgnum which is not open"
147         unless exists($open{$billpkgnum});
148       my $itemindex = $open{$billpkgnum};
149       my %taxhash = ();
150       if ($taxlocationnum) {
151         %taxhash = map { ($_->primary_key => $_->get($_->primary_key)) }
152                    grep { $_->get($_->primary_key) == $taxlocationnum }
153                    $open[$itemindex]->cust_bill_pkg_tax_Xlocation;
154
155         return "No tax line item with a key value of $taxlocationnum exists"
156           unless scalar(%taxhash);
157       }
158       push @apply, [ $open[$itemindex], $itemamount, { %taxhash } ];
159     }
160     return \@apply;
161   }
162
163   @open = grep { $_->pkgnum == $self->pkgnum } @open
164     if $conf->exists('pkg-balances') && $self->pkgnum;
165   warn "$me ". scalar(@open). " open line items for invoice ".
166        $self->cust_bill->invnum. ": ". join(', ', @open). "\n"
167     if $DEBUG;
168   my $total = 0;
169   foreach (@open) {
170     $total += $_->owed_setup if $_->setup;
171     $total += $_->owed_recur if $_->recur;
172   }
173   $total = sprintf('%.2f', $total);
174
175   if ( $self->amount > $total ) {
176     return "Can't apply a ". $self->_app_source_name. ' of $'. $self->amount.
177            " greater than the remaining owed on line items (\$$total)";
178   }
179
180   #easy cases:
181   # - one lineitem (a simple special case of:)
182   # - amount is for whole invoice (well, all of remaining lineitem links)
183   if ( $self->amount == $total ) {
184
185     warn "$me application amount covers remaining balance of invoice in full;".
186          "applying to those lineitems\n"
187       if $DEBUG;
188
189     #@apply = map { [ $_, $_->amount ]; } @open;
190     #@apply = map { [ $_, $_->owed_setup + 0 || $_->owed_recur + 0 ]; } @open;
191     @apply = map { [ $_, $_->setup ? $_->owed_setup : $_->owed_recur ]; } @open;
192
193   } else {
194
195     #slightly magic case:
196     # - amount exactly and uniquely matches a single open lineitem
197     #   (you must be trying to pay or credit that item, then)
198
199     my @same = grep {    ( $_->setup && $_->owed_setup == $self->amount )
200                       || ( $_->recur && $_->owed_recur == $self->amount )
201                     }
202                     @open;
203     if ( scalar(@same) == 1 ) {
204       warn "$me application amount exactly and uniquely matches one lineitem;".
205            " applying to that lineitem\n"
206         if $DEBUG;
207       @apply = map { [ $_, $self->amount ]; } @same
208     }
209
210   }
211
212   unless ( @apply ) {
213
214     warn "$me applying amount based on package weights\n"
215       if $DEBUG;
216
217     #and the rest:
218     # - apply based on weights...
219
220     my $weight_col = $self->_app_part_pkg_weight_column;
221     my @openweight = map { 
222                            my $open = $_;
223                            my $cust_pkg = $open->cust_pkg;
224                            my $weight =
225                              $cust_pkg
226                                ? ( $cust_pkg->part_pkg->$weight_col() || 0 )
227                                : -1; #default or per-tax weight?
228                            [ $open, $weight ]
229                          }
230                          @open;
231
232     my %saw = ();
233     my @weights = sort { $b <=> $a }     # highest weight first
234                   grep { ! $saw{$_}++ }  # want a list of unique weights
235                   map  { $_->[1] }
236                        @openweight;
237   
238     my $remaining_amount = $self->amount;
239     foreach my $weight ( @weights ) {
240
241       #i hate it when my schwartz gets tangled
242       my @items = map { $_->[0] } grep { $weight == $_->[1] } @openweight;
243
244       my $itemtotal = 0;
245       foreach my $item (@items) {
246         $itemtotal += $item->owed_setup if $item->setup;
247         $itemtotal += $item->owed_recur if $item->recur;
248       }
249       my $applytotal = min( $itemtotal, $remaining_amount );
250       $remaining_amount -= $applytotal;
251
252       warn "$me applying $applytotal ($remaining_amount remaining)".
253            " to ". scalar(@items). " lineitems with weight $weight\n"
254         if $DEBUG;
255
256       #if some items are less than applytotal/num_items, then apply then in full
257       my $lessflag;
258       do {
259         $lessflag = 0;
260
261         #no, not sprintf("%.2f",
262         # we want this rounded DOWN for purposes of checking for line items
263         # less than it, we don't want .66666 becoming .67 and causing this
264         # to trigger when it shouldn't
265         my $applyeach = int( 100 * $applytotal / scalar(@items) ) / 100;
266
267         my @newitems = ();
268         foreach my $item ( @items ) {
269           my $itemamount = $item->setup ? $item->owed_setup : $item->owed_recur;
270           if ( $itemamount < $applyeach ) {
271             warn "$me applying full $itemamount".
272                  " to small line item (cust_bill_pkg ". $item->billpkgnum. ")\n"
273               if $DEBUG;
274             push @apply, [ $item, $itemamount ];
275             $applytotal -= $itemamount;
276             $lessflag=1;
277           } else {
278             push @newitems, $item;
279           }
280         }
281         @items = @newitems;
282
283       } while ( $lessflag && @items );
284
285       if ( @items ) {
286
287         #and now that we've fallen out of the loop, distribute the rest equally
288
289         # should cust_bill_pay_pkg and cust_credit_bill_pkg amount columns
290         # become real instead of numeric(10,2) ???  no..
291         my $applyeach = sprintf("%.2f", $applytotal / scalar(@items) );
292
293         my @equi_apply = map { [ $_, $applyeach ] } @items;
294
295         # or should we futz with pennies instead?  yes, bah!
296         my $diff =
297           sprintf('%.0f', 100 * ( $applytotal - $applyeach * scalar(@items) ) );
298         $diff = 0 if $diff eq '-0'; #yay ieee fp
299         if ( abs($diff) > scalar(@items) ) {
300           #we must have done something really wrong, the difference is more than
301           #a penny an item
302           return 'Error distributing pennies applying '.$self->_app_source_name.
303                  " - can't distribute difference of $diff pennies".
304                  ' among '. scalar(@items). ' line items';
305         }
306
307         warn "$me futzing with $diff pennies difference\n"
308           if $DEBUG && $diff;
309
310         my $futz = 0;
311         while ( $diff != 0 && $futz < scalar(@equi_apply) ) {
312           if ( $diff > 0 ) { 
313             $equi_apply[$futz++]->[1] += .01;
314             $diff -= 1;
315           } elsif ( $diff < 0 ) {
316             $equi_apply[$futz++]->[1] -= .01;
317             $diff += 1;
318           } else {
319             die "guru exception #5 (in fortran tongue the answer)";
320           }
321         }
322
323         if ( sprintf('%.0f', $diff ) ) {
324           return "couldn't futz with pennies enough: still $diff left";
325         }
326
327         if ( $DEBUG ) {
328           warn "$me applying ". $_->[1].
329                " to line item (cust_bill_pkg ". $_->[0]->billpkgnum. ")\n"
330             foreach @equi_apply;
331         }
332         push @apply, @equi_apply;
333
334       }
335
336       #$remaining_amount -= $applytotal;
337       last unless $remaining_amount;
338
339     }
340
341   }
342
343   # break down lineitem amounts for tax lines
344   # could expand @open above, instead, for a slightly different magic effect
345   my @result = ();
346   foreach my $apply ( @apply ) {
347     my @sub_lines = $apply->[0]->cust_bill_pkg_tax_Xlocation;
348     my $amount = $apply->[1];
349     warn "applying ". $apply->[1]. " to ". $apply->[0]->desc
350       if $DEBUG;
351     
352     foreach my $subline ( @sub_lines ) {
353       my $owed = $subline->owed;
354       push @result, [ $apply->[0],
355                       sprintf('%.2f', min($amount, $owed) ),
356                       { $subline->primary_key => $subline->get($subline->primary_key) },
357                     ];
358       $amount -= $owed;
359       $amount = 0 if $amount < 0;
360       last unless $amount;
361     }
362     if ( $amount > 0 ) {
363       push @result, [ $apply->[0], sprintf('%.2f', $amount), {} ];
364     }
365   }
366
367   \@result;
368
369 }
370
371 sub apply_to_lineitems {
372   #my $self = shift;
373   my( $self, %options ) = @_;
374
375   return '' if $skip_apply_to_lineitems_hack;
376
377   my $conf = new FS::Conf;
378
379   local $SIG{HUP} = 'IGNORE';
380   local $SIG{INT} = 'IGNORE';
381   local $SIG{QUIT} = 'IGNORE';
382   local $SIG{TERM} = 'IGNORE';
383   local $SIG{TSTP} = 'IGNORE';
384   local $SIG{PIPE} = 'IGNORE';
385
386   my $oldAutoCommit = $FS::UID::AutoCommit;
387   local $FS::UID::AutoCommit = 0;
388   my $dbh = dbh;
389
390   my $listref_or_error = $self->calculate_applications(%options);
391   unless (ref($listref_or_error)) {
392     $dbh->rollback if $oldAutoCommit;
393     return $listref_or_error;
394   }
395
396   my @apply = @$listref_or_error;
397
398   # do the applicaiton(s)
399   my $table = $self->lineitem_breakdown_table;
400   my $source_key = dbdef->table($self->table)->primary_key;
401   my $applied = 0;
402   foreach my $apply ( @apply ) {
403     my ( $cust_bill_pkg, $amount, $taxcreditref ) = @$apply;
404     $applied += $amount;
405     my $application = "FS::$table"->new( {
406       $source_key  => $self->$source_key(),
407       'billpkgnum' => $cust_bill_pkg->billpkgnum,
408       'amount'     => sprintf('%.2f', $amount),
409       'setuprecur' => ( $cust_bill_pkg->setup > 0 ? 'setup' : 'recur' ),
410       'sdate'      => $cust_bill_pkg->sdate,
411       'edate'      => $cust_bill_pkg->edate,
412       %$taxcreditref,
413     });
414     my $error = $application->insert(%options);
415     if ( $error ) {
416       $dbh->rollback if $oldAutoCommit;
417       return $error;
418     }
419
420     # trigger export_insert_on_payment
421     if ( $conf->exists('trigger_export_insert_on_payment')
422       && $cust_bill_pkg->pkgnum > 0 )
423     {
424       if ( my $cust_pkg = $cust_bill_pkg->cust_pkg ) {
425
426         foreach my $cust_svc ( $cust_pkg->cust_svc ) {
427           my $svc_x = $cust_svc->svc_x;
428           my @part_export = grep { $_->can('_export_insert_on_payment') }
429                                  $cust_svc->part_svc->part_export;
430       
431           foreach my $part_export ( @part_export ) {
432             $error = $part_export->_export_insert_on_payment($svc_x);
433             if ( $error ) {
434               $dbh->rollback if $oldAutoCommit;
435               return $error;
436             }
437           }
438         }
439       }
440     }
441     # done trigger export_insert_on_payment
442
443   }
444
445   # unset promised payment date if there is one
446   my $cust_bill = $self->cust_bill;
447   if ( $cust_bill->promised_date and $cust_bill->owed <= 0 ) {
448     $cust_bill->set('promised_date', '');
449     my $error = $cust_bill->replace;
450     if ( $error ) {
451       $dbh->rollback if $oldAutoCommit;
452       return $error;
453     }
454   }
455   
456   #everything should always be applied to line items in full now... sanity check
457   $applied = sprintf('%.2f', $applied);
458   unless ( $applied == $self->amount ) {
459     $dbh->rollback if $oldAutoCommit;
460     return 'Error applying '. $self->_app_source_name. ' of $'. $self->amount.
461            ' to line items - only $'. $applied. ' was applied.';
462   }
463
464   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
465   '';
466
467 }
468
469 =item lineitem_applications
470
471 Returns all the specific line item applications for this invoice application.
472
473 =cut
474
475 sub lineitem_applications {
476   my $self = shift;
477   my $primary_key = dbdef->table($self->table)->primary_key;
478   qsearch({
479     'table'   => $self->lineitem_breakdown_table, 
480     'hashref' => { $primary_key => $self->$primary_key() },
481   });
482
483 }
484
485 =item cust_bill 
486
487 Returns the invoice (see L<FS::cust_bill>)
488
489 =cut
490
491 sub cust_bill {
492   my $self = shift;
493   qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
494 }
495
496 =item applied_to_invoice
497
498 Returns a string representing the invoice (see L<FS::cust_bill>), for example:
499 "applied to Invoice #54 (3/20/2008)"
500
501 =cut
502
503 sub applied_to_invoice {
504   my $self = shift;
505   my $string = 'applied to '. $self->cust_bill->invnum_date_pretty;
506
507   #show application date if over 24 hours after (or before) payment/credit date
508   $string .= ' on '. $self->_date_pretty
509     if abs( $self->_date - $self->_app_source_object->_date ) > 86400;
510
511   $string;
512 }
513
514 =item _app_source_object 
515
516 =cut
517
518 sub _app_source_object {
519   my $self = shift;
520   my $source_table = $self->_app_source_table;
521   $self->$source_table();
522 }
523
524 =item _date_pretty
525
526 Returns a string with the application date, for example: "3/20/2008"
527
528 =cut
529
530 sub _date_pretty {
531   my $self = shift;
532   time2str($date_format, $self->_date);
533 }
534
535 =item lineitem_breakdown_table 
536
537 =cut
538
539 sub lineitem_breakdown_table {
540   my $self = shift;
541   $self->_load_table($self->_app_lineitem_breakdown_table);
542 }
543
544 sub _load_table {
545   my( $self, $table ) = @_;
546   eval "use FS::$table";
547   die $@ if $@;
548   $table;
549 }
550
551 =back
552
553 =head1 BUGS
554
555 =head1 SEE ALSO
556
557 L<FS::cust_bill_pay> and L<FS::cust_bill_pay_pkg>,
558 L<FS::cust_credit_bill> and L<FS::cust_credit_bill_pkg>
559
560 =cut
561
562 1;
563