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 );
10 use FS::cust_bill_pkg;
14 @ISA = qw( FS::Record );
17 $me = '[FS::cust_bill_ApplicationCommon]';
19 $skip_apply_to_lineitems_hack = 0;
23 FS::cust_bill_ApplicationCommon - Base class for bill application classes
27 use FS::cust_bill_ApplicationCommon;
29 @ISA = qw( FS::cust_bill_ApplicationCommon );
31 sub _app_source_name { 'payment'; }
32 sub _app_source_table { 'cust_pay'; }
33 sub _app_lineitem_breakdown_table { 'cust_bill_pay_pkg'; }
37 FS::cust_bill_ApplicationCommon is intended as a base class for classes which
38 represent application of things to invoices, currently payments
39 (see L<FS::cust_bill_pay>) or credits (see L<FS::cust_credit_bill>).
52 local $SIG{HUP} = 'IGNORE';
53 local $SIG{INT} = 'IGNORE';
54 local $SIG{QUIT} = 'IGNORE';
55 local $SIG{TERM} = 'IGNORE';
56 local $SIG{TSTP} = 'IGNORE';
57 local $SIG{PIPE} = 'IGNORE';
59 my $oldAutoCommit = $FS::UID::AutoCommit;
60 local $FS::UID::AutoCommit = 0;
63 my $error = $self->SUPER::insert(@_)
64 || $self->apply_to_lineitems(@_);
66 $dbh->rollback if $oldAutoCommit;
70 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
83 local $SIG{HUP} = 'IGNORE';
84 local $SIG{INT} = 'IGNORE';
85 local $SIG{QUIT} = 'IGNORE';
86 local $SIG{TERM} = 'IGNORE';
87 local $SIG{TSTP} = 'IGNORE';
88 local $SIG{PIPE} = 'IGNORE';
90 my $oldAutoCommit = $FS::UID::AutoCommit;
91 local $FS::UID::AutoCommit = 0;
94 foreach my $app ( $self->lineitem_applications ) {
95 my $error = $app->delete;
97 $dbh->rollback if $oldAutoCommit;
102 my $error = $self->SUPER::delete(@_);
104 $dbh->rollback if $oldAutoCommit;
108 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
114 =item apply_to_lineitems
116 Auto-applies this invoice application to specific line items, if possible.
120 sub calculate_applications {
121 my( $self, %options ) = @_;
123 return '' if $skip_apply_to_lineitems_hack;
127 my $conf = new FS::Conf;
129 my @open = $self->cust_bill->open_cust_bill_pkg; #FOR UPDATE...?
131 if ( exists($options{subitems}) ) {
134 $open{$_->billpkgnum} = $i++ foreach @open;
136 foreach my $listref ( @{$options{subitems}} ) {
137 my ($billpkgnum, $itemamount, $taxlocationnum) = @$listref;
138 return "Can't apply a ". $self->_app_source_name. ' of $'. $listref->[1].
139 " to line item $billpkgnum which is not open"
140 unless exists($open{$billpkgnum});
141 my $itemindex = $open{$billpkgnum};
143 if ($taxlocationnum) {
144 %taxhash = map { ($_->primary_key => $_->get($_->primary_key)) }
145 grep { $_->get($_->primary_key) == $taxlocationnum }
146 $open[$itemindex]->cust_bill_pkg_tax_Xlocation;
148 return "No tax line item with a key value of $taxlocationnum exists"
149 unless scalar(%taxhash);
151 push @apply, [ $open[$itemindex], $itemamount, { %taxhash } ];
156 @open = grep { $_->pkgnum == $self->pkgnum } @open
157 if $conf->exists('pkg-balances') && $self->pkgnum;
158 warn "$me ". scalar(@open). " open line items for invoice ".
159 $self->cust_bill->invnum. ": ". join(', ', @open). "\n"
163 $total += $_->owed_setup if $_->setup;
164 $total += $_->owed_recur if $_->recur;
166 $total = sprintf('%.2f', $total);
168 if ( $self->amount > $total ) {
169 return "Can't apply a ". $self->_app_source_name. ' of $'. $self->amount.
170 " greater than the remaining owed on line items (\$$total)";
174 # - one lineitem (a simple special case of:)
175 # - amount is for whole invoice (well, all of remaining lineitem links)
176 if ( $self->amount == $total ) {
178 warn "$me application amount covers remaining balance of invoice in full;".
179 "applying to those lineitems\n"
182 #@apply = map { [ $_, $_->amount ]; } @open;
183 #@apply = map { [ $_, $_->owed_setup + 0 || $_->owed_recur + 0 ]; } @open;
184 @apply = map { [ $_, $_->setup ? $_->owed_setup : $_->owed_recur ]; } @open;
188 #slightly magic case:
189 # - amount exactly and uniquely matches a single open lineitem
190 # (you must be trying to pay or credit that item, then)
192 my @same = grep { ( $_->setup && $_->owed_setup == $self->amount )
193 || ( $_->recur && $_->owed_recur == $self->amount )
196 if ( scalar(@same) == 1 ) {
197 warn "$me application amount exactly and uniquely matches one lineitem;".
198 " applying to that lineitem\n"
200 @apply = map { [ $_, $self->amount ]; } @same
207 warn "$me applying amount based on package weights\n"
211 # - apply based on weights...
213 my $weight_col = $self->_app_part_pkg_weight_column;
214 my @openweight = map {
216 my $cust_pkg = $open->cust_pkg;
219 ? ( $cust_pkg->part_pkg->$weight_col() || 0 )
220 : -1; #default or per-tax weight?
226 my @weights = sort { $b <=> $a } # highest weight first
227 grep { ! $saw{$_}++ } # want a list of unique weights
231 my $remaining_amount = $self->amount;
232 foreach my $weight ( @weights ) {
234 #i hate it when my schwartz gets tangled
235 my @items = map { $_->[0] } grep { $weight == $_->[1] } @openweight;
238 foreach my $item (@items) {
239 $itemtotal += $item->owed_setup if $item->setup;
240 $itemtotal += $item->owed_recur if $item->recur;
242 my $applytotal = min( $itemtotal, $remaining_amount );
243 $remaining_amount -= $applytotal;
245 warn "$me applying $applytotal ($remaining_amount remaining)".
246 " to ". scalar(@items). " lineitems with weight $weight\n"
249 #if some items are less than applytotal/num_items, then apply then in full
254 #no, not sprintf("%.2f",
255 # we want this rounded DOWN for purposes of checking for line items
256 # less than it, we don't want .66666 becoming .67 and causing this
257 # to trigger when it shouldn't
258 my $applyeach = int( 100 * $applytotal / scalar(@items) ) / 100;
261 foreach my $item ( @items ) {
262 my $itemamount = $item->setup ? $item->owed_setup : $item->owed_recur;
263 if ( $itemamount < $applyeach ) {
264 warn "$me applying full $itemamount".
265 " to small line item (cust_bill_pkg ". $item->billpkgnum. ")\n"
267 push @apply, [ $item, $itemamount ];
268 $applytotal -= $itemamount;
271 push @newitems, $item;
276 } while ( $lessflag );
278 #and now that we've fallen out of the loop, distribute the rest equally...
280 # should cust_bill_pay_pkg and cust_credit_bill_pkg amount columns
281 # become real instead of numeric(10,2) ??? no..
282 my $applyeach = sprintf("%.2f", $applytotal / scalar(@items) );
284 my @equi_apply = map { [ $_, $applyeach ] } @items;
286 # or should we futz with pennies instead? yes, bah!
288 sprintf('%.0f', 100 * ( $applytotal - $applyeach * scalar(@items) ) );
289 $diff = 0 if $diff eq '-0'; #yay ieee fp
290 if ( abs($diff) > scalar(@items) ) {
291 #we must have done something really wrong, the difference is more than
293 return 'Error distributing pennies applying '. $self->_app_source_name.
294 " - can't distribute difference of $diff pennies".
295 ' among '. scalar(@items). ' line items';
298 warn "$me futzing with $diff pennies difference\n"
302 while ( $diff != 0 && $futz < scalar(@equi_apply) ) {
304 $equi_apply[$futz++]->[1] += .01;
306 } elsif ( $diff < 0 ) {
307 $equi_apply[$futz++]->[1] -= .01;
310 die "guru exception #5 (in fortran tongue the answer)";
314 if ( sprintf('%.0f', $diff ) ) {
315 return "couldn't futz with pennies enough: still $diff left";
319 warn "$me applying ". $_->[1].
320 " to line item (cust_bill_pkg ". $_->[0]->billpkgnum. ")\n"
325 push @apply, @equi_apply;
327 #$remaining_amount -= $applytotal;
328 last unless $remaining_amount;
334 # break down lineitem amounts for tax lines
335 # could expand @open above, instead, for a slightly different magic effect
337 foreach my $apply ( @apply ) {
338 my @sub_lines = $apply->[0]->cust_bill_pkg_tax_Xlocation;
339 my $amount = $apply->[1];
340 warn "applying ". $apply->[1]. " to ". $apply->[0]->desc
343 foreach my $subline ( @sub_lines ) {
344 my $owed = $subline->owed;
345 push @result, [ $apply->[0],
346 sprintf('%.2f', min($amount, $owed) ),
347 { $subline->primary_key => $subline->get($subline->primary_key) },
350 $amount = 0 if $amount < 0;
354 push @result, [ $apply->[0], sprintf('%.2f', $amount), {} ];
362 sub apply_to_lineitems {
364 my( $self, %options ) = @_;
366 return '' if $skip_apply_to_lineitems_hack;
368 my $conf = new FS::Conf;
370 local $SIG{HUP} = 'IGNORE';
371 local $SIG{INT} = 'IGNORE';
372 local $SIG{QUIT} = 'IGNORE';
373 local $SIG{TERM} = 'IGNORE';
374 local $SIG{TSTP} = 'IGNORE';
375 local $SIG{PIPE} = 'IGNORE';
377 my $oldAutoCommit = $FS::UID::AutoCommit;
378 local $FS::UID::AutoCommit = 0;
381 my $listref_or_error = $self->calculate_applications(%options);
382 unless (ref($listref_or_error)) {
383 $dbh->rollback if $oldAutoCommit;
384 return $listref_or_error;
387 my @apply = @$listref_or_error;
389 # do the applicaiton(s)
390 my $table = $self->lineitem_breakdown_table;
391 my $source_key = dbdef->table($self->table)->primary_key;
393 foreach my $apply ( @apply ) {
394 my ( $cust_bill_pkg, $amount, $taxcreditref ) = @$apply;
396 my $application = "FS::$table"->new( {
397 $source_key => $self->$source_key(),
398 'billpkgnum' => $cust_bill_pkg->billpkgnum,
399 'amount' => sprintf('%.2f', $amount),
400 'setuprecur' => ( $cust_bill_pkg->setup > 0 ? 'setup' : 'recur' ),
401 'sdate' => $cust_bill_pkg->sdate,
402 'edate' => $cust_bill_pkg->edate,
405 my $error = $application->insert(%options);
407 $dbh->rollback if $oldAutoCommit;
411 # trigger export_insert_on_payment
412 if ( $conf->exists('trigger_export_insert_on_payment')
413 && $cust_bill_pkg->pkgnum > 0 )
415 if ( my $cust_pkg = $cust_bill_pkg->cust_pkg ) {
417 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
418 my $svc_x = $cust_svc->svc_x;
419 my @part_export = grep { $_->can('export_insert_on_payment') }
420 $cust_svc->part_svc->part_export;
422 foreach my $part_export ( $cust_svc->part_svc->part_export ) {
423 $error = $part_export->_export_insert_on_payment($svc_x);
425 $dbh->rollback if $oldAutoCommit;
432 # done trigger export_insert_on_payment
436 #everything should always be applied to line items in full now... sanity check
437 $applied = sprintf('%.2f', $applied);
438 unless ( $applied == $self->amount ) {
439 $dbh->rollback if $oldAutoCommit;
440 return 'Error applying '. $self->_app_source_name. ' of $'. $self->amount.
441 ' to line items - only $'. $applied. ' was applied.';
444 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
449 =item lineitem_applications
451 Returns all the specific line item applications for this invoice application.
455 sub lineitem_applications {
457 my $primary_key = dbdef->table($self->table)->primary_key;
459 'table' => $self->lineitem_breakdown_table,
460 'hashref' => { $primary_key => $self->$primary_key() },
467 Returns the invoice (see L<FS::cust_bill>)
473 qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
476 =item applied_to_invoice
478 Returns a string representing the invoice (see L<FS::cust_bill>), for example:
479 "applied to Invoice #54 (3/20/2008)"
483 sub applied_to_invoice {
485 'applied to '. $self->cust_bill->invnum_date_pretty;
488 =item lineitem_breakdown_table
492 sub lineitem_breakdown_table {
494 $self->_load_table($self->_app_lineitem_breakdown_table);
498 my( $self, $table ) = @_;
499 eval "use FS::$table";
510 L<FS::cust_bill_pay> and L<FS::cust_bill_pay_pkg>,
511 L<FS::cust_credit_bill> and L<FS::cust_credit_bill_pkg>