experimental package balances, RT#4339
[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 );
5 use List::Util qw(min);
6 use FS::Schema qw( dbdef );
7 use FS::Record qw( qsearch qsearchs dbh );
8
9 @ISA = qw( FS::Record );
10
11 $DEBUG = 0;
12 $me = '[FS::cust_bill_ApplicationCommon]';
13
14 =head1 NAME
15
16 FS::cust_bill_ApplicationCommon - Base class for bill application classes
17
18 =head1 SYNOPSIS
19
20 use FS::cust_bill_ApplicationCommon;
21
22 @ISA = qw( FS::cust_bill_ApplicationCommon );
23
24 sub _app_source_name  { 'payment'; }
25 sub _app_source_table { 'cust_pay'; }
26 sub _app_lineitem_breakdown_table { 'cust_bill_pay_pkg'; }
27
28 =head1 DESCRIPTION
29
30 FS::cust_bill_ApplicationCommon is intended as a base class for classes which
31 represent application of things to invoices, currently payments
32 (see L<FS::cust_bill_pay>) or credits (see L<FS::cust_credit_bill>).
33
34 =head1 METHODS
35
36 =over 4
37
38 =item insert
39
40 =cut
41
42 sub insert {
43   my $self = shift;
44
45   local $SIG{HUP} = 'IGNORE';
46   local $SIG{INT} = 'IGNORE';
47   local $SIG{QUIT} = 'IGNORE';
48   local $SIG{TERM} = 'IGNORE';
49   local $SIG{TSTP} = 'IGNORE';
50   local $SIG{PIPE} = 'IGNORE';
51
52   my $oldAutoCommit = $FS::UID::AutoCommit;
53   local $FS::UID::AutoCommit = 0;
54   my $dbh = dbh;
55
56   my $error =    $self->SUPER::insert(@_)
57               || $self->apply_to_lineitems;
58   if ( $error ) {
59     $dbh->rollback if $oldAutoCommit;
60     return $error;
61   }
62
63   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
64
65   '';
66
67 }
68
69 =item delete
70
71 =cut
72
73 sub delete {
74   my $self = shift;
75
76   local $SIG{HUP} = 'IGNORE';
77   local $SIG{INT} = 'IGNORE';
78   local $SIG{QUIT} = 'IGNORE';
79   local $SIG{TERM} = 'IGNORE';
80   local $SIG{TSTP} = 'IGNORE';
81   local $SIG{PIPE} = 'IGNORE';
82
83   my $oldAutoCommit = $FS::UID::AutoCommit;
84   local $FS::UID::AutoCommit = 0;
85   my $dbh = dbh;
86
87   foreach my $app ( $self->lineitem_applications ) {
88     my $error = $app->delete;
89     if ( $error ) {
90       $dbh->rollback if $oldAutoCommit;
91       return $error;
92     }
93   }
94
95   my $error = $self->SUPER::delete(@_);
96   if ( $error ) {
97     $dbh->rollback if $oldAutoCommit;
98     return $error;
99   }
100
101   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
102
103   '';
104
105 }
106
107 =item apply_to_lineitems
108
109 Auto-applies this invoice application to specific line items, if possible.
110
111 =cut
112
113 sub apply_to_lineitems {
114   my $self = shift;
115
116   my @apply = ();
117
118   my $conf = new FS::Conf;
119
120   local $SIG{HUP} = 'IGNORE';
121   local $SIG{INT} = 'IGNORE';
122   local $SIG{QUIT} = 'IGNORE';
123   local $SIG{TERM} = 'IGNORE';
124   local $SIG{TSTP} = 'IGNORE';
125   local $SIG{PIPE} = 'IGNORE';
126
127   my $oldAutoCommit = $FS::UID::AutoCommit;
128   local $FS::UID::AutoCommit = 0;
129   my $dbh = dbh;
130
131   my @open = $self->cust_bill->open_cust_bill_pkg; #FOR UPDATE...?
132   @open = grep { $_->pkgnum == $self->pkgnum } @open
133     if $conf->exists('pkg-balances') && $self->pkgnum;
134   warn "$me ". scalar(@open). " open line items for invoice ".
135        $self->cust_bill->invnum. ": ". join(', ', @open). "\n"
136     if $DEBUG;
137   my $total = 0;
138   $total += $_->setup + $_->recur foreach @open;
139   $total = sprintf('%.2f', $total);
140
141   if ( $self->amount > $total ) {
142     $dbh->rollback if $oldAutoCommit;
143     return "Can't apply a ". $self->_app_source_name. ' of $'. $self->amount.
144            " greater than the remaining owed on line items (\$$total)";
145   }
146
147   #easy cases:
148   # - one lineitem (a simple special case of:)
149   # - amount is for whole invoice (well, all of remaining lineitem links)
150   if ( $self->amount == $total ) {
151
152     warn "$me application amount covers remaining balance of invoice in full;".
153          "applying to those lineitems\n"
154       if $DEBUG;
155
156     #@apply = map { [ $_, $_->amount ]; } @open;
157     @apply = map { [ $_, $_->setup || $_->recur ]; } @open;
158
159   } else {
160
161     #slightly magic case:
162     # - amount exactly and uniquely matches a single open lineitem
163     #   (you must be trying to pay or credit that item, then)
164
165     my @same = grep {    $_->setup == $self->amount
166                       || $_->recur == $self->amount
167                     }
168                     @open;
169     if ( scalar(@same) == 1 ) {
170       warn "$me application amount exactly and uniquely matches one lineitem;".
171            " applying to that lineitem\n"
172         if $DEBUG;
173       @apply = map { [ $_, $self->amount ]; } @same
174     }
175
176   }
177
178   unless ( @apply ) {
179
180     warn "$me applying amount based on package weights\n"
181       if $DEBUG;
182
183     #and the rest:
184     # - apply based on weights...
185
186     my $weight_col = $self->_app_part_pkg_weight_column;
187     my @openweight = map { 
188                            my $open = $_;
189                            my $cust_pkg = $open->cust_pkg;
190                            my $weight =
191                              $cust_pkg
192                                ? ( $cust_pkg->part_pkg->$weight_col() || 0 )
193                                : 0; #default or per-tax weight?
194                            [ $open, $weight ]
195                          }
196                          @open;
197
198     my %saw = ();
199     my @weights = sort { $b <=> $a }     # highest weight first
200                   grep { ! $saw{$_}++ }  # want a list of unique weights
201                   map  { $_->[1] }
202                        @openweight;
203   
204     my $remaining_amount = $self->amount;
205     foreach my $weight ( @weights ) {
206
207       #i hate it when my schwartz gets tangled
208       my @items = map { $_->[0] } grep { $weight == $_->[1] } @openweight;
209
210       my $itemtotal = 0;
211       foreach my $item (@items) { $itemtotal += $item->setup || $item->recur; }
212       my $applytotal = min( $itemtotal, $remaining_amount );
213       $remaining_amount -= $applytotal;
214
215       warn "$me applying $applytotal ($remaining_amount remaining)".
216            " to ". scalar(@items). " lineitems with weight $weight\n"
217         if $DEBUG;
218
219       #if some items are less than applytotal/num_items, then apply then in full
220       my $lessflag;
221       do {
222         $lessflag = 0;
223
224         #no, not sprintf("%.2f",
225         # we want this rounded DOWN for purposes of checking for line items
226         # less than it, we don't want .66666 becoming .67 and causing this
227         # to trigger when it shouldn't
228         my $applyeach = int( 100 * $applytotal / scalar(@items) ) / 100;
229
230         my @newitems = ();
231         foreach my $item ( @items ) {
232           my $itemamount = $item->setup || $item->recur;
233           if ( $itemamount < $applyeach ) {
234             warn "$me applying full $itemamount".
235                  " to small line item (cust_bill_pkg ". $item->billpkgnum. ")\n"
236               if $DEBUG;
237             push @apply, [ $item, $itemamount ];
238             $applytotal -= $itemamount;
239             $lessflag=1;
240           } else {
241             push @newitems, $item;
242           }
243         }
244         @items = @newitems;
245
246       } while ( $lessflag );
247
248       #and now that we've fallen out of the loop, distribute the rest equally...
249
250       # should cust_bill_pay_pkg and cust_credit_bill_pkg amount columns
251       # become real instead of numeric(10,2) ???  no..
252       my $applyeach = sprintf("%.2f", $applytotal / scalar(@items) );
253
254       my @equi_apply = map { [ $_, $applyeach ] } @items;
255
256       # or should we futz with pennies instead?  yes, bah!
257       my $diff =
258         sprintf('%.0f', 100 * ( $applytotal - $applyeach * scalar(@items) ) );
259       $diff = 0 if $diff eq '-0'; #yay ieee fp
260       if ( abs($diff) > scalar(@items) ) {
261         #we must have done something really wrong, the difference is more than
262         #a penny an item
263         $dbh->rollback if $oldAutoCommit;
264         return 'Error distributing pennies applying '. $self->_app_source_name.
265                " - can't distribute difference of $diff pennies".
266                ' among '. scalar(@items). ' line items';
267       }
268
269       warn "$me futzing with $diff pennies difference\n"
270         if $DEBUG && $diff;
271
272       my $futz = 0;
273       while ( $diff != 0 && $futz < scalar(@equi_apply) ) {
274         if ( $diff > 0 ) { 
275           $equi_apply[$futz++]->[1] += .01;
276           $diff -= 1;
277         } elsif ( $diff < 0 ) {
278           $equi_apply[$futz++]->[1] -= .01;
279           $diff += 1;
280         } else {
281           die "guru exception #5 (in fortran tongue the answer)";
282         }
283       }
284
285       if ( sprintf('%.0f', $diff ) ) {
286         $dbh->rollback if $oldAutoCommit;
287         return "couldn't futz with pennies enough: still $diff left";
288       }
289
290       if ( $DEBUG ) {
291         warn "$me applying ". $_->[1].
292              " to line item (cust_bill_pkg ". $_->[0]->billpkgnum. ")\n"
293           foreach @equi_apply;
294       }
295
296
297       push @apply, @equi_apply;
298
299       #$remaining_amount -= $applytotal;
300       last unless $remaining_amount;
301
302     }
303
304   }
305
306   # do the applicaiton(s)
307   my $table = $self->lineitem_breakdown_table;
308   my $source_key = dbdef->table($self->table)->primary_key;
309   my $applied = 0;
310   foreach my $apply ( @apply ) {
311     my ( $cust_bill_pkg, $amount ) = @$apply;
312     $applied += $amount;
313     my $application = "FS::$table"->new( {
314       $source_key  => $self->$source_key(),
315       'billpkgnum' => $cust_bill_pkg->billpkgnum,
316       'amount'     => sprintf('%.2f', $amount),
317       'setuprecur' => ( $cust_bill_pkg->setup > 0 ? 'setup' : 'recur' ),
318       'sdate'      => $cust_bill_pkg->sdate,
319       'edate'      => $cust_bill_pkg->edate,
320     });
321     my $error = $application->insert;
322     if ( $error ) {
323       $dbh->rollback if $oldAutoCommit;
324       return $error;
325     }
326   }
327
328   #everything should always be applied to line items in full now... sanity check
329   $applied = sprintf('%.2f', $applied);
330   unless ( $applied == $self->amount ) {
331     $dbh->rollback if $oldAutoCommit;
332     return 'Error applying '. $self->_app_source_name. ' of $'. $self->amount.
333            ' to line items - only $'. $applied. ' was applied.';
334   }
335
336   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
337   '';
338
339 }
340
341 =item lineitem_applications
342
343 Returns all the specific line item applications for this invoice application.
344
345 =cut
346
347 sub lineitem_applications {
348   my $self = shift;
349   my $primary_key = dbdef->table($self->table)->primary_key;
350   qsearch({
351     'table'   => $self->lineitem_breakdown_table, 
352     'hashref' => { $primary_key => $self->$primary_key() },
353   });
354
355 }
356
357 =item cust_bill 
358
359 Returns the invoice (see L<FS::cust_bill>)
360
361 =cut
362
363 sub cust_bill {
364   my $self = shift;
365   qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
366 }
367
368 =item applied_to_invoice
369
370 Returns a string representing the invoice (see L<FS::cust_bill>), for example:
371 "applied to Invoice #54 (3/20/2008)"
372
373 =cut
374
375 sub applied_to_invoice {
376   my $self = shift;
377   'applied to '. $self->cust_bill->invnum_date_pretty;
378 }
379
380 =item lineitem_breakdown_table 
381
382 =cut
383
384 sub lineitem_breakdown_table {
385   my $self = shift;
386   $self->_load_table($self->_app_lineitem_breakdown_table);
387 }
388
389 sub _load_table {
390   my( $self, $table ) = @_;
391   eval "use FS::$table";
392   die $@ if $@;
393   $table;
394 }
395
396 =back
397
398 =head1 BUGS
399
400 =head1 SEE ALSO
401
402 L<FS::cust_bill_pay> and L<FS::cust_bill_pay_pkg>,
403 L<FS::cust_credit_bill> and L<FS::cust_credit_bill_pkg>
404
405 =cut
406
407 1;
408