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