1 package FS::cust_bill_ApplicationCommon;
4 use vars qw( @ISA $DEBUG $me $skip_apply_to_lineitems_hack );
5 use List::Util qw(min);
6 use FS::Schema qw( dbdef );
7 use FS::Record qw( qsearch qsearchs dbh );
9 @ISA = qw( FS::Record );
12 $me = '[FS::cust_bill_ApplicationCommon]';
14 $skip_apply_to_lineitems_hack = 0;
18 FS::cust_bill_ApplicationCommon - Base class for bill application classes
22 use FS::cust_bill_ApplicationCommon;
24 @ISA = qw( FS::cust_bill_ApplicationCommon );
26 sub _app_source_name { 'payment'; }
27 sub _app_source_table { 'cust_pay'; }
28 sub _app_lineitem_breakdown_table { 'cust_bill_pay_pkg'; }
32 FS::cust_bill_ApplicationCommon is intended as a base class for classes which
33 represent application of things to invoices, currently payments
34 (see L<FS::cust_bill_pay>) or credits (see L<FS::cust_credit_bill>).
47 local $SIG{HUP} = 'IGNORE';
48 local $SIG{INT} = 'IGNORE';
49 local $SIG{QUIT} = 'IGNORE';
50 local $SIG{TERM} = 'IGNORE';
51 local $SIG{TSTP} = 'IGNORE';
52 local $SIG{PIPE} = 'IGNORE';
54 my $oldAutoCommit = $FS::UID::AutoCommit;
55 local $FS::UID::AutoCommit = 0;
58 my $error = $self->SUPER::insert(@_)
59 || $self->apply_to_lineitems(@_);
61 $dbh->rollback if $oldAutoCommit;
65 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
78 local $SIG{HUP} = 'IGNORE';
79 local $SIG{INT} = 'IGNORE';
80 local $SIG{QUIT} = 'IGNORE';
81 local $SIG{TERM} = 'IGNORE';
82 local $SIG{TSTP} = 'IGNORE';
83 local $SIG{PIPE} = 'IGNORE';
85 my $oldAutoCommit = $FS::UID::AutoCommit;
86 local $FS::UID::AutoCommit = 0;
89 foreach my $app ( $self->lineitem_applications ) {
90 my $error = $app->delete;
92 $dbh->rollback if $oldAutoCommit;
97 my $error = $self->SUPER::delete(@_);
99 $dbh->rollback if $oldAutoCommit;
103 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
109 =item apply_to_lineitems
111 Auto-applies this invoice application to specific line items, if possible.
115 sub calculate_applications {
116 my( $self, %options ) = @_;
118 return '' if $skip_apply_to_lineitems_hack;
122 my $conf = new FS::Conf;
124 my @open = $self->cust_bill->open_cust_bill_pkg; #FOR UPDATE...?
126 if ( exists($options{subitems}) ) {
129 $open{$_->billpkgnum} = $i++ foreach @open;
131 foreach my $listref ( @{$options{subitems}} ) {
132 my ($billpkgnum, $itemamount, $taxlocationnum) = @$listref;
133 return "Can't apply a ". $self->_app_source_name. ' of $'. $listref->[1].
134 " to line item $billpkgnum which is not open"
135 unless exists($open{$billpkgnum});
136 my $itemindex = $open{$billpkgnum};
138 if ($taxlocationnum) {
139 %taxhash = map { ($_->primary_key => $_->get($_->primary_key)) }
140 grep { $_->get($_->primary_key) == $taxlocationnum }
141 $open[$itemindex]->cust_bill_pkg_tax_Xlocation;
143 return "No tax line item with a key value of $taxlocationnum exists"
144 unless scalar(%taxhash);
146 push @apply, [ $open[$itemindex], $itemamount, { %taxhash } ];
151 @open = grep { $_->pkgnum == $self->pkgnum } @open
152 if $conf->exists('pkg-balances') && $self->pkgnum;
153 warn "$me ". scalar(@open). " open line items for invoice ".
154 $self->cust_bill->invnum. ": ". join(', ', @open). "\n"
157 $total += $_->owed_setup + $_->owed_recur foreach @open;
158 $total = sprintf('%.2f', $total);
160 if ( $self->amount > $total ) {
161 return "Can't apply a ". $self->_app_source_name. ' of $'. $self->amount.
162 " greater than the remaining owed on line items (\$$total)";
166 # - one lineitem (a simple special case of:)
167 # - amount is for whole invoice (well, all of remaining lineitem links)
168 if ( $self->amount == $total ) {
170 warn "$me application amount covers remaining balance of invoice in full;".
171 "applying to those lineitems\n"
174 #@apply = map { [ $_, $_->amount ]; } @open;
175 @apply = map { [ $_, $_->owed_setup + 0 || $_->owed_recur + 0 ]; } @open;
179 #slightly magic case:
180 # - amount exactly and uniquely matches a single open lineitem
181 # (you must be trying to pay or credit that item, then)
183 my @same = grep { $_->owed_setup == $self->amount
184 || $_->owed_recur == $self->amount
187 if ( scalar(@same) == 1 ) {
188 warn "$me application amount exactly and uniquely matches one lineitem;".
189 " applying to that lineitem\n"
191 @apply = map { [ $_, $self->amount ]; } @same
198 warn "$me applying amount based on package weights\n"
202 # - apply based on weights...
204 my $weight_col = $self->_app_part_pkg_weight_column;
205 my @openweight = map {
207 my $cust_pkg = $open->cust_pkg;
210 ? ( $cust_pkg->part_pkg->$weight_col() || 0 )
211 : 0; #default or per-tax weight?
217 my @weights = sort { $b <=> $a } # highest weight first
218 grep { ! $saw{$_}++ } # want a list of unique weights
222 my $remaining_amount = $self->amount;
223 foreach my $weight ( @weights ) {
225 #i hate it when my schwartz gets tangled
226 my @items = map { $_->[0] } grep { $weight == $_->[1] } @openweight;
229 foreach my $item (@items) { $itemtotal += $item->owed_setup + 0 || $item->owed_recur + 0; }
230 my $applytotal = min( $itemtotal, $remaining_amount );
231 $remaining_amount -= $applytotal;
233 warn "$me applying $applytotal ($remaining_amount remaining)".
234 " to ". scalar(@items). " lineitems with weight $weight\n"
237 #if some items are less than applytotal/num_items, then apply then in full
242 #no, not sprintf("%.2f",
243 # we want this rounded DOWN for purposes of checking for line items
244 # less than it, we don't want .66666 becoming .67 and causing this
245 # to trigger when it shouldn't
246 my $applyeach = int( 100 * $applytotal / scalar(@items) ) / 100;
249 foreach my $item ( @items ) {
250 my $itemamount = $item->owed_setup + 0 || $item->owed_recur + 0;
251 if ( $itemamount < $applyeach ) {
252 warn "$me applying full $itemamount".
253 " to small line item (cust_bill_pkg ". $item->billpkgnum. ")\n"
255 push @apply, [ $item, $itemamount ];
256 $applytotal -= $itemamount;
259 push @newitems, $item;
264 } while ( $lessflag );
266 #and now that we've fallen out of the loop, distribute the rest equally...
268 # should cust_bill_pay_pkg and cust_credit_bill_pkg amount columns
269 # become real instead of numeric(10,2) ??? no..
270 my $applyeach = sprintf("%.2f", $applytotal / scalar(@items) );
272 my @equi_apply = map { [ $_, $applyeach ] } @items;
274 # or should we futz with pennies instead? yes, bah!
276 sprintf('%.0f', 100 * ( $applytotal - $applyeach * scalar(@items) ) );
277 $diff = 0 if $diff eq '-0'; #yay ieee fp
278 if ( abs($diff) > scalar(@items) ) {
279 #we must have done something really wrong, the difference is more than
281 return 'Error distributing pennies applying '. $self->_app_source_name.
282 " - can't distribute difference of $diff pennies".
283 ' among '. scalar(@items). ' line items';
286 warn "$me futzing with $diff pennies difference\n"
290 while ( $diff != 0 && $futz < scalar(@equi_apply) ) {
292 $equi_apply[$futz++]->[1] += .01;
294 } elsif ( $diff < 0 ) {
295 $equi_apply[$futz++]->[1] -= .01;
298 die "guru exception #5 (in fortran tongue the answer)";
302 if ( sprintf('%.0f', $diff ) ) {
303 return "couldn't futz with pennies enough: still $diff left";
307 warn "$me applying ". $_->[1].
308 " to line item (cust_bill_pkg ". $_->[0]->billpkgnum. ")\n"
313 push @apply, @equi_apply;
315 #$remaining_amount -= $applytotal;
316 last unless $remaining_amount;
322 # break down lineitem amounts for tax lines
323 # could expand @open above, instead, for a slightly different magic effect
325 foreach my $apply ( @apply ) {
326 my @sub_lines = $apply->[0]->cust_bill_pkg_tax_Xlocation;
327 my $amount = $apply->[1];
328 warn "applying ". $apply->[1]. " to ". $apply->[0]->desc
331 foreach my $subline ( @sub_lines ) {
332 my $owed = $subline->owed;
333 push @result, [ $apply->[0],
334 sprintf('%.2f', min($amount, $owed) ),
335 { $subline->primary_key => $subline->get($subline->primary_key) },
338 $amount = 0 if $amount < 0;
342 push @result, [ $apply->[0], sprintf('%.2f', $amount), {} ];
350 sub apply_to_lineitems {
352 my( $self, %options ) = @_;
354 return '' if $skip_apply_to_lineitems_hack;
358 my $conf = new FS::Conf;
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';
367 my $oldAutoCommit = $FS::UID::AutoCommit;
368 local $FS::UID::AutoCommit = 0;
371 my $listref_or_error = $self->calculate_applications(%options);
372 unless (ref($listref_or_error)) {
373 $dbh->rollback if $oldAutoCommit;
374 return $listref_or_error;
377 my @apply = @$listref_or_error;
379 # do the applicaiton(s)
380 my $table = $self->lineitem_breakdown_table;
381 my $source_key = dbdef->table($self->table)->primary_key;
383 foreach my $apply ( @apply ) {
384 my ( $cust_bill_pkg, $amount, $taxcreditref ) = @$apply;
386 my $application = "FS::$table"->new( {
387 $source_key => $self->$source_key(),
388 'billpkgnum' => $cust_bill_pkg->billpkgnum,
389 'amount' => sprintf('%.2f', $amount),
390 'setuprecur' => ( $cust_bill_pkg->setup > 0 ? 'setup' : 'recur' ),
391 'sdate' => $cust_bill_pkg->sdate,
392 'edate' => $cust_bill_pkg->edate,
395 my $error = $application->insert(%options);
397 $dbh->rollback if $oldAutoCommit;
402 #everything should always be applied to line items in full now... sanity check
403 $applied = sprintf('%.2f', $applied);
404 unless ( $applied == $self->amount ) {
405 $dbh->rollback if $oldAutoCommit;
406 return 'Error applying '. $self->_app_source_name. ' of $'. $self->amount.
407 ' to line items - only $'. $applied. ' was applied.';
410 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
415 =item lineitem_applications
417 Returns all the specific line item applications for this invoice application.
421 sub lineitem_applications {
423 my $primary_key = dbdef->table($self->table)->primary_key;
425 'table' => $self->lineitem_breakdown_table,
426 'hashref' => { $primary_key => $self->$primary_key() },
433 Returns the invoice (see L<FS::cust_bill>)
439 qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
442 =item applied_to_invoice
444 Returns a string representing the invoice (see L<FS::cust_bill>), for example:
445 "applied to Invoice #54 (3/20/2008)"
449 sub applied_to_invoice {
451 'applied to '. $self->cust_bill->invnum_date_pretty;
454 =item lineitem_breakdown_table
458 sub lineitem_breakdown_table {
460 $self->_load_table($self->_app_lineitem_breakdown_table);
464 my( $self, $table ) = @_;
465 eval "use FS::$table";
476 L<FS::cust_bill_pay> and L<FS::cust_bill_pay_pkg>,
477 L<FS::cust_credit_bill> and L<FS::cust_credit_bill_pkg>