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 apply_to_lineitems {
118 return '' if $skip_apply_to_lineitems_hack;
122 my $conf = new FS::Conf;
124 local $SIG{HUP} = 'IGNORE';
125 local $SIG{INT} = 'IGNORE';
126 local $SIG{QUIT} = 'IGNORE';
127 local $SIG{TERM} = 'IGNORE';
128 local $SIG{TSTP} = 'IGNORE';
129 local $SIG{PIPE} = 'IGNORE';
131 my $oldAutoCommit = $FS::UID::AutoCommit;
132 local $FS::UID::AutoCommit = 0;
135 my @open = $self->cust_bill->open_cust_bill_pkg; #FOR UPDATE...?
136 @open = grep { $_->pkgnum == $self->pkgnum } @open
137 if $conf->exists('pkg-balances') && $self->pkgnum;
138 warn "$me ". scalar(@open). " open line items for invoice ".
139 $self->cust_bill->invnum. ": ". join(', ', @open). "\n"
142 $total += $_->setup + $_->recur foreach @open;
143 $total = sprintf('%.2f', $total);
145 if ( $self->amount > $total ) {
146 $dbh->rollback if $oldAutoCommit;
147 return "Can't apply a ". $self->_app_source_name. ' of $'. $self->amount.
148 " greater than the remaining owed on line items (\$$total)";
152 # - one lineitem (a simple special case of:)
153 # - amount is for whole invoice (well, all of remaining lineitem links)
154 if ( $self->amount == $total ) {
156 warn "$me application amount covers remaining balance of invoice in full;".
157 "applying to those lineitems\n"
160 #@apply = map { [ $_, $_->amount ]; } @open;
161 @apply = map { [ $_, $_->setup || $_->recur ]; } @open;
165 #slightly magic case:
166 # - amount exactly and uniquely matches a single open lineitem
167 # (you must be trying to pay or credit that item, then)
169 my @same = grep { $_->setup == $self->amount
170 || $_->recur == $self->amount
173 if ( scalar(@same) == 1 ) {
174 warn "$me application amount exactly and uniquely matches one lineitem;".
175 " applying to that lineitem\n"
177 @apply = map { [ $_, $self->amount ]; } @same
184 warn "$me applying amount based on package weights\n"
188 # - apply based on weights...
190 my $weight_col = $self->_app_part_pkg_weight_column;
191 my @openweight = map {
193 my $cust_pkg = $open->cust_pkg;
196 ? ( $cust_pkg->part_pkg->$weight_col() || 0 )
197 : 0; #default or per-tax weight?
203 my @weights = sort { $b <=> $a } # highest weight first
204 grep { ! $saw{$_}++ } # want a list of unique weights
208 my $remaining_amount = $self->amount;
209 foreach my $weight ( @weights ) {
211 #i hate it when my schwartz gets tangled
212 my @items = map { $_->[0] } grep { $weight == $_->[1] } @openweight;
215 foreach my $item (@items) { $itemtotal += $item->setup || $item->recur; }
216 my $applytotal = min( $itemtotal, $remaining_amount );
217 $remaining_amount -= $applytotal;
219 warn "$me applying $applytotal ($remaining_amount remaining)".
220 " to ". scalar(@items). " lineitems with weight $weight\n"
223 #if some items are less than applytotal/num_items, then apply then in full
228 #no, not sprintf("%.2f",
229 # we want this rounded DOWN for purposes of checking for line items
230 # less than it, we don't want .66666 becoming .67 and causing this
231 # to trigger when it shouldn't
232 my $applyeach = int( 100 * $applytotal / scalar(@items) ) / 100;
235 foreach my $item ( @items ) {
236 my $itemamount = $item->setup || $item->recur;
237 if ( $itemamount < $applyeach ) {
238 warn "$me applying full $itemamount".
239 " to small line item (cust_bill_pkg ". $item->billpkgnum. ")\n"
241 push @apply, [ $item, $itemamount ];
242 $applytotal -= $itemamount;
245 push @newitems, $item;
250 } while ( $lessflag );
252 #and now that we've fallen out of the loop, distribute the rest equally...
254 # should cust_bill_pay_pkg and cust_credit_bill_pkg amount columns
255 # become real instead of numeric(10,2) ??? no..
256 my $applyeach = sprintf("%.2f", $applytotal / scalar(@items) );
258 my @equi_apply = map { [ $_, $applyeach ] } @items;
260 # or should we futz with pennies instead? yes, bah!
262 sprintf('%.0f', 100 * ( $applytotal - $applyeach * scalar(@items) ) );
263 $diff = 0 if $diff eq '-0'; #yay ieee fp
264 if ( abs($diff) > scalar(@items) ) {
265 #we must have done something really wrong, the difference is more than
267 $dbh->rollback if $oldAutoCommit;
268 return 'Error distributing pennies applying '. $self->_app_source_name.
269 " - can't distribute difference of $diff pennies".
270 ' among '. scalar(@items). ' line items';
273 warn "$me futzing with $diff pennies difference\n"
277 while ( $diff != 0 && $futz < scalar(@equi_apply) ) {
279 $equi_apply[$futz++]->[1] += .01;
281 } elsif ( $diff < 0 ) {
282 $equi_apply[$futz++]->[1] -= .01;
285 die "guru exception #5 (in fortran tongue the answer)";
289 if ( sprintf('%.0f', $diff ) ) {
290 $dbh->rollback if $oldAutoCommit;
291 return "couldn't futz with pennies enough: still $diff left";
295 warn "$me applying ". $_->[1].
296 " to line item (cust_bill_pkg ". $_->[0]->billpkgnum. ")\n"
301 push @apply, @equi_apply;
303 #$remaining_amount -= $applytotal;
304 last unless $remaining_amount;
310 # do the applicaiton(s)
311 my $table = $self->lineitem_breakdown_table;
312 my $source_key = dbdef->table($self->table)->primary_key;
314 foreach my $apply ( @apply ) {
315 my ( $cust_bill_pkg, $amount ) = @$apply;
317 my $application = "FS::$table"->new( {
318 $source_key => $self->$source_key(),
319 'billpkgnum' => $cust_bill_pkg->billpkgnum,
320 'amount' => sprintf('%.2f', $amount),
321 'setuprecur' => ( $cust_bill_pkg->setup > 0 ? 'setup' : 'recur' ),
322 'sdate' => $cust_bill_pkg->sdate,
323 'edate' => $cust_bill_pkg->edate,
325 my $error = $application->insert;
327 $dbh->rollback if $oldAutoCommit;
332 #everything should always be applied to line items in full now... sanity check
333 $applied = sprintf('%.2f', $applied);
334 unless ( $applied == $self->amount ) {
335 $dbh->rollback if $oldAutoCommit;
336 return 'Error applying '. $self->_app_source_name. ' of $'. $self->amount.
337 ' to line items - only $'. $applied. ' was applied.';
340 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
345 =item lineitem_applications
347 Returns all the specific line item applications for this invoice application.
351 sub lineitem_applications {
353 my $primary_key = dbdef->table($self->table)->primary_key;
355 'table' => $self->lineitem_breakdown_table,
356 'hashref' => { $primary_key => $self->$primary_key() },
363 Returns the invoice (see L<FS::cust_bill>)
369 qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
372 =item applied_to_invoice
374 Returns a string representing the invoice (see L<FS::cust_bill>), for example:
375 "applied to Invoice #54 (3/20/2008)"
379 sub applied_to_invoice {
381 'applied to '. $self->cust_bill->invnum_date_pretty;
384 =item lineitem_breakdown_table
388 sub lineitem_breakdown_table {
390 $self->_load_table($self->_app_lineitem_breakdown_table);
394 my( $self, $table ) = @_;
395 eval "use FS::$table";
406 L<FS::cust_bill_pay> and L<FS::cust_bill_pay_pkg>,
407 L<FS::cust_credit_bill> and L<FS::cust_credit_bill_pkg>