if asked to credit a zero-amount line item, skip it rather than throwing an error...
[freeside.git] / FS / FS / cust_credit.pm
1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
3              FS::Record );
4
5 use strict;
6 use vars qw( $conf $me $DEBUG
7              $otaker_upgrade_kludge $ignore_empty_reasonnum
8            );
9 use List::Util qw( min );
10 use Date::Format;
11 use FS::UID qw( dbh );
12 use FS::Record qw( qsearch qsearchs dbdef );
13 use FS::CurrentUser;
14 use FS::cust_pkg;
15 use FS::cust_refund;
16 use FS::cust_credit_bill;
17 use FS::part_pkg;
18 use FS::reason_type;
19 use FS::reason;
20 use FS::cust_event;
21 use FS::agent;
22 use FS::sales;
23 use FS::cust_credit_void;
24 use FS::cust_bill_pkg;
25 use FS::upgrade_journal;
26
27 $me = '[ FS::cust_credit ]';
28 $DEBUG = 0;
29
30 $otaker_upgrade_kludge = 0;
31 $ignore_empty_reasonnum = 0;
32
33 #ask FS::UID to run this stuff for us later
34 $FS::UID::callback{'FS::cust_credit'} = sub { 
35
36   $conf = new FS::Conf;
37
38 };
39
40 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
41                         'cancel_credit_type'   => 'Cancellation Credit',
42                       );
43
44 =head1 NAME
45
46 FS::cust_credit - Object methods for cust_credit records
47
48 =head1 SYNOPSIS
49
50   use FS::cust_credit;
51
52   $record = new FS::cust_credit \%hash;
53   $record = new FS::cust_credit { 'column' => 'value' };
54
55   $error = $record->insert;
56
57   $error = $new_record->replace($old_record);
58
59   $error = $record->delete;
60
61   $error = $record->check;
62
63 =head1 DESCRIPTION
64
65 An FS::cust_credit object represents a credit; the equivalent of a negative
66 B<cust_bill> record (see L<FS::cust_bill>).  FS::cust_credit inherits from
67 FS::Record.  The following fields are currently supported:
68
69 =over 4
70
71 =item crednum
72
73 Primary key (assigned automatically for new credits)
74
75 =item custnum
76
77 Customer (see L<FS::cust_main>)
78
79 =item amount
80
81 Amount of the credit
82
83 =item _date
84
85 Specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
86 L<Time::Local> and L<Date::Parse> for conversion functions.
87
88 =item usernum
89
90 Order taker (see L<FS::access_user>)
91
92 =item reason
93
94 Text ( deprecated )
95
96 =item reasonnum
97
98 Reason (see L<FS::reason>)
99
100 =item addlinfo
101
102 Text
103
104 =item closed
105
106 Books closed flag, empty or `Y'
107
108 =item pkgnum
109
110 Desired pkgnum when using experimental package balances.
111
112 =back
113
114 =head1 METHODS
115
116 =over 4
117
118 =item new HASHREF
119
120 Creates a new credit.  To add the credit to the database, see L<"insert">.
121
122 =cut
123
124 sub table { 'cust_credit'; }
125 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
126 sub cust_unlinked_msg {
127   my $self = shift;
128   "WARNING: can't find cust_main.custnum ". $self->custnum.
129   ' (cust_credit.crednum '. $self->crednum. ')';
130 }
131
132 =item insert [ OPTION => VALUE ... ]
133
134 Adds this credit to the database ("Posts" the credit).  If there is an error,
135 returns the error, otherwise returns false.
136
137 Ooptions are passed as a list of keys and values.  Available options:
138
139 =over 4
140
141 =item reason_type
142
143 L<FS::reason_type|Reason> type for newly-inserted reason
144
145 =item cust_credit_source_bill_pkg
146
147 An arrayref of
148 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
149 They will have their crednum set and will be inserted along with this credit.
150
151 =back
152
153 =cut
154
155 sub insert {
156   my ($self, %options) = @_;
157
158   local $SIG{HUP} = 'IGNORE';
159   local $SIG{INT} = 'IGNORE';
160   local $SIG{QUIT} = 'IGNORE';
161   local $SIG{TERM} = 'IGNORE';
162   local $SIG{TSTP} = 'IGNORE';
163   local $SIG{PIPE} = 'IGNORE';
164
165   my $oldAutoCommit = $FS::UID::AutoCommit;
166   local $FS::UID::AutoCommit = 0;
167   my $dbh = dbh;
168
169   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
170   my $old_balance = $cust_main->balance;
171
172   if (!$self->reasonnum) {
173     my $reason_text = $self->get('reason')
174       or return "reason text or existing reason required";
175     my $reason_type = $options{'reason_type'}
176       or return "reason type required";
177
178     local $@;
179     my $reason = FS::reason->new_or_existing(
180       reason => $reason_text,
181       type   => $reason_type,
182       class  => 'R',
183     );
184     if ($@) {
185       $dbh->rollback if $oldAutoCommit;
186       return "failed to set credit reason: $@";
187     }
188     $self->set('reasonnum', $reason->reasonnum);
189   }
190
191   $self->setfield('reason', '');
192
193   my $error = $self->SUPER::insert;
194   if ( $error ) {
195     $dbh->rollback if $oldAutoCommit;
196     return "error inserting $self: $error";
197   }
198
199   if ( $options{'cust_credit_source_bill_pkg'} ) {
200     foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
201       $ccsbr->crednum( $self->crednum );
202       $error = $ccsbr->insert;
203       if ( $error ) {
204         $dbh->rollback if $oldAutoCommit;
205         return "error inserting $ccsbr: $error";
206       }
207     }
208   }
209
210   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
211
212   # possibly trigger package unsuspend, doesn't abort transaction on failure
213   $self->unsuspend_balance if $old_balance;
214
215   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
216
217   '';
218
219 }
220
221 =item delete
222
223 Unless the closed flag is set, deletes this credit and all associated
224 applications (see L<FS::cust_credit_bill>).  In most cases, you want to use
225 the void method instead to leave a record of the deleted credit.
226
227 =cut
228
229 # very similar to FS::cust_pay::delete
230 sub delete {
231   my $self = shift;
232   my %opt = @_;
233
234   return "Can't delete closed credit" if $self->closed =~ /^Y/i;
235
236   local $SIG{HUP} = 'IGNORE';
237   local $SIG{INT} = 'IGNORE';
238   local $SIG{QUIT} = 'IGNORE';
239   local $SIG{TERM} = 'IGNORE';
240   local $SIG{TSTP} = 'IGNORE';
241   local $SIG{PIPE} = 'IGNORE';
242
243   my $oldAutoCommit = $FS::UID::AutoCommit;
244   local $FS::UID::AutoCommit = 0;
245   my $dbh = dbh;
246
247   foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
248     my $error = $cust_credit_bill->delete;
249     if ( $error ) {
250       $dbh->rollback if $oldAutoCommit;
251       return $error;
252     }
253   }
254
255   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
256     my $error = $cust_credit_refund->delete;
257     if ( $error ) {
258       $dbh->rollback if $oldAutoCommit;
259       return $error;
260     }
261   }
262
263   my $error = $self->SUPER::delete(@_);
264   if ( $error ) {
265     $dbh->rollback if $oldAutoCommit;
266     return $error;
267   }
268
269   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
270
271   '';
272
273 }
274
275 =item replace [ OLD_RECORD ]
276
277 You can, but probably shouldn't modify credits... 
278
279 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
280 supplied, replaces this record.  If there is an error, returns the error,
281 otherwise returns false.
282
283 =cut
284
285 sub replace {
286   my $self = shift;
287   return "Can't modify closed credit" if $self->closed =~ /^Y/i;
288   $self->SUPER::replace(@_);
289 }
290
291 =item check
292
293 Checks all fields to make sure this is a valid credit.  If there is an error,
294 returns the error, otherwise returns false.  Called by the insert and replace
295 methods.
296
297 =cut
298
299 sub check {
300   my $self = shift;
301
302   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
303
304   my $error =
305     $self->ut_numbern('crednum')
306     || $self->ut_number('custnum')
307     || $self->ut_numbern('_date')
308     || $self->ut_money('amount')
309     || $self->ut_alphan('otaker')
310     || $self->ut_textn('reason')
311     || $self->ut_textn('addlinfo')
312     || $self->ut_enum('closed', [ '', 'Y' ])
313     || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
314     || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
315     || $self->ut_foreign_keyn('commission_agentnum',  'agent', 'agentnum')
316     || $self->ut_foreign_keyn('commission_salesnum',  'sales', 'salesnum')
317     || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
318   ;
319   return $error if $error;
320
321   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
322   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
323   return $error if $error;
324
325   return "amount must be > 0 " if $self->amount <= 0;
326
327   return "amount must be greater or equal to amount applied"
328     if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
329
330   return "Unknown customer"
331     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
332
333   $self->_date(time) unless $self->_date;
334
335   $self->SUPER::check;
336 }
337
338 =item void [ REASON ]
339
340 Voids this credit: deletes the credit and all associated applications and 
341 adds a record of the voided credit to the cust_credit_void table.
342
343 =cut
344
345 sub void {
346   my $self = shift;
347   my $reason = shift;
348
349   unless (ref($reason) || !$reason) {
350     $reason = FS::reason->new_or_existing(
351       'class'  => 'X',
352       'type'   => 'Void credit',
353       'reason' => $reason
354     );
355   }
356
357   local $SIG{HUP} = 'IGNORE';
358   local $SIG{INT} = 'IGNORE';
359   local $SIG{QUIT} = 'IGNORE';
360   local $SIG{TERM} = 'IGNORE';
361   local $SIG{TSTP} = 'IGNORE';
362   local $SIG{PIPE} = 'IGNORE';
363
364   my $oldAutoCommit = $FS::UID::AutoCommit;
365   local $FS::UID::AutoCommit = 0;
366   my $dbh = dbh;
367
368   my $cust_credit_void = new FS::cust_credit_void ( {
369       map { $_ => $self->get($_) } $self->fields
370     } );
371   $cust_credit_void->set('void_reasonnum', $reason->reasonnum) if $reason;
372   my $error = $cust_credit_void->insert;
373   if ( $error ) {
374     $dbh->rollback if $oldAutoCommit;
375     return $error;
376   }
377
378   $error = $self->delete();
379   if ( $error ) {
380     $dbh->rollback if $oldAutoCommit;
381     return $error;
382   }
383
384   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
385
386   '';
387
388 }
389
390 =item cust_credit_refund
391
392 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
393
394 =cut
395
396 sub cust_credit_refund {
397   my $self = shift;
398   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
399   sort { $a->_date <=> $b->_date }
400     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
401   ;
402 }
403
404 =item cust_credit_bill
405
406 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
407 credit.
408
409 =cut
410
411 sub cust_credit_bill {
412   my $self = shift;
413   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
414   sort { $a->_date <=> $b->_date }
415     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
416   ;
417 }
418
419 =item unapplied
420
421 Returns the amount of this credit that is still unapplied/outstanding; 
422 amount minus all refund applications (see L<FS::cust_credit_refund>) and
423 applications to invoices (see L<FS::cust_credit_bill>).
424
425 =cut
426
427 sub unapplied {
428   my $self = shift;
429   my $amount = $self->amount;
430   $amount -= $_->amount foreach ( $self->cust_credit_refund );
431   $amount -= $_->amount foreach ( $self->cust_credit_bill );
432   sprintf( "%.2f", $amount );
433 }
434
435 =item credited
436
437 Deprecated name for the unapplied method.
438
439 =cut
440
441 sub credited {
442   my $self = shift;
443   #carp "cust_credit->credited deprecated; use ->unapplied";
444   $self->unapplied(@_);
445 }
446
447 =item cust_main
448
449 Returns the customer (see L<FS::cust_main>) for this credit.
450
451 =cut
452
453 # _upgrade_data
454 #
455 # Used by FS::Upgrade to migrate to a new database.
456
457 sub _upgrade_data {  # class method
458   my ($class, %opts) = @_;
459
460   warn "$me upgrading $class\n" if $DEBUG;
461
462   $class->_upgrade_reasonnum(%opts);
463
464   if (defined dbdef->table($class->table)->column('reason')) {
465
466     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
467
468     foreach ( keys %reasontype_map ) {
469       unless ($conf->config($_)) {       # hmmmm
470 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
471 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
472         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
473         my $reason_type = qsearchs( 'reason_type', $hashref );
474         unless ($reason_type) {
475           $reason_type  = new FS::reason_type( $hashref );
476           my $error   = $reason_type->insert();
477           die "$class had error inserting FS::reason_type into database: $error\n"
478             if $error;
479         }
480         $conf->set($_, $reason_type->typenum);
481       }
482     }
483
484     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
485
486     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
487     my $reason_type = qsearchs( 'reason_type', $hashref );
488     unless ($reason_type) {
489       $reason_type  = new FS::reason_type( $hashref );
490       my $error   = $reason_type->insert();
491       die "$class had error inserting FS::reason_type into database: $error\n"
492         if $error;
493     }
494
495     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
496     foreach my $plan ( @plans ) {
497       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
498         unless ($pkg->option('reason_type', 1) ) { 
499           my $plandata = $pkg->plandata.
500                         "reason_type=". $reason_type->typenum. "\n";
501           $pkg->plandata($plandata);
502           my $error =
503             $pkg->replace( undef,
504                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
505                                           $pkg->pkg_svc
506                                         },
507                            'primary_svc' => $pkg->svcpart,
508                          );
509             die "failed setting reason_type option: $error"
510               if $error;
511         }
512       }
513     }
514   }
515
516   local($otaker_upgrade_kludge) = 1;
517   local($ignore_empty_reasonnum) = 1;
518   $class->_upgrade_otaker(%opts);
519
520   if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
521       and !$conf->config('tax_data_vendor') ) {
522     # RT#25458: fix credit line item applications that should refer to a 
523     # specific tax allocation
524     my @cust_credit_bill_pkg = qsearch({
525         table     => 'cust_credit_bill_pkg',
526         select    => 'cust_credit_bill_pkg.*',
527         addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
528         extra_sql =>
529           'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
530           'AND cust_bill_pkg.pkgnum = 0', # is a tax
531     });
532     my %tax_items;
533     my %credits;
534     foreach (@cust_credit_bill_pkg) {
535       my $billpkgnum = $_->billpkgnum;
536       $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
537       $credits{$billpkgnum} ||= [];
538       push @{ $credits{$billpkgnum} }, $_;
539     }
540     TAX_ITEM: foreach my $tax_item (values %tax_items) {
541       my $billpkgnum = $tax_item->billpkgnum;
542       # get all pkg/location/taxrate allocations of this tax line item
543       my @allocations = sort {$b->amount <=> $a->amount}
544                         qsearch('cust_bill_pkg_tax_location', {
545                             billpkgnum => $billpkgnum
546                         });
547       # and these are all credit applications to it
548       my @credits = sort {$b->amount <=> $a->amount}
549                     @{ $credits{$billpkgnum} };
550       my $c = shift @credits;
551       my $a = shift @allocations; # we will NOT modify these
552       while ($c and $a) {
553         if ( abs($c->amount - $a->amount) < 0.005 ) {
554           # by far the most common case: the tax line item is for a single
555           # tax, so we just fill in the billpkgtaxlocationnum
556           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
557           my $error = $c->replace;
558           if ($error) {
559             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
560             next TAX_ITEM;
561           }
562           $c = shift @credits;
563           $a = shift @allocations;
564         } elsif ( $c->amount > $a->amount ) {
565           # fairly common: the tax line contains tax for multiple packages
566           # (or multiple taxes) but the credit isn't divided up
567           my $new_link = FS::cust_credit_bill_pkg->new({
568               creditbillnum         => $c->creditbillnum,
569               billpkgnum            => $c->billpkgnum,
570               billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
571               amount                => $a->amount,
572               setuprecur            => 'setup',
573           });
574           my $error = $new_link->insert;
575           if ($error) {
576             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
577             next TAX_ITEM;
578           }
579           $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
580           $a = shift @allocations;
581         } elsif ( $c->amount < 0.005 ) {
582           # also fairly common; we can delete these with no harm
583           my $error = $c->delete;
584           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
585           $c = shift @credits;
586         } elsif ( $c->amount < $a->amount ) {
587           # should never happen, but if it does, handle it gracefully
588           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
589           my $error = $c->replace;
590           if ($error) {
591             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
592             next TAX_ITEM;
593           }
594           $a->set(amount => $a->amount - $c->amount);
595           $c = shift @credits;
596         }
597       } # while $c and $a
598       if ( $c ) {
599         if ( $c->amount < 0.005 ) {
600           my $error = $c->delete;
601           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
602         } elsif ( $c->modified ) {
603           # then we've allocated part of it, so reduce the nonspecific 
604           # application by that much
605           my $error = $c->replace;
606           warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
607         }
608         # else there are probably no allocations, i.e. this is a pre-3.x 
609         # record that was never migrated over, so leave it alone
610       } # if $c
611     } # foreach $tax_item
612     FS::upgrade_journal->set_done('cust_credit__tax_link');
613   }
614 }
615
616 =back
617
618 =head1 CLASS METHODS
619
620 =over 4
621
622 =item unapplied_sql
623
624 Returns an SQL fragment to retreive the unapplied amount.
625
626 =cut
627
628 sub unapplied_sql {
629   my ($class, $start, $end) = @_;
630
631   my $bill_start   = $start ? "AND cust_credit_bill._date <= $start"   : '';
632   my $bill_end     = $end   ? "AND cust_credit_bill._date > $end"     : '';
633   my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
634   my $refund_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
635
636   "amount
637         - COALESCE(
638                     ( SELECT SUM(amount) FROM cust_credit_refund
639                         WHERE cust_credit.crednum = cust_credit_refund.crednum
640                         $refund_start $refund_end )
641                     ,0
642                   )
643         - COALESCE(
644                     ( SELECT SUM(amount) FROM cust_credit_bill
645                         WHERE cust_credit.crednum = cust_credit_bill.crednum
646                         $bill_start $bill_end )
647                     ,0
648                   )
649   ";
650
651 }
652
653 =item credited_sql
654
655 Deprecated name for the unapplied_sql method.
656
657 =cut
658
659 sub credited_sql {
660   #my $class = shift;
661
662   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
663
664   #$class->unapplied_sql(@_);
665   unapplied_sql();
666 }
667
668 =item calculate_tax_adjustment PARAMS
669
670 Calculate the amount of tax that needs to be credited as part of a lineitem
671 credit.
672
673 PARAMS must include:
674
675 - billpkgnums: arrayref identifying the line items to credit
676 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
677   the lineitem charge is being credited
678 - amounts: arrayref of the amounts to credit on each line item
679 - custnum: the customer all of these invoices belong to, for error checking
680
681 Returns a hash containing:
682 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
683 - taxtotal: the total tax amount to be credited
684 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
685   - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
686   - num: the key within that table
687   - credit: the credit amount to apply to that line
688
689 =cut
690
691 sub calculate_tax_adjustment {
692   my ($class, %arg) = @_;
693
694   my $error;
695   my @taxlines;
696   my $subtotal = 0;
697   my $taxtotal = 0;
698
699   my (%cust_bill_pkg, %cust_bill);
700
701   for (my $i = 0; ; $i++) {
702     my $billpkgnum = $arg{billpkgnums}[$i]
703       or last;
704     my $setuprecur = $arg{setuprecurs}[$i];
705     my $amount = $arg{amounts}[$i];
706     next if $amount == 0;
707     $subtotal += $amount;
708     my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
709                     ||= FS::cust_bill_pkg->by_key($billpkgnum)
710       or die "lineitem #$billpkgnum not found\n";
711
712     my $invnum = $cust_bill_pkg->invnum;
713     $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
714     $cust_bill{ $invnum}->custnum == $arg{custnum}
715       or die "lineitem #$billpkgnum not found\n";
716
717     # tax_Xlocation records don't distinguish setup and recur, so calculate
718     # the fraction of setup+recur (after deducting credits) that's setup. This
719     # will also be the fraction of tax (after deducting credits) that's tax on
720     # setup.
721     my ($setup, $recur);
722     $setup = $cust_bill_pkg->get('setup') || 0;
723     if ($setup) {
724       $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
725     }
726     $recur = $cust_bill_pkg->get('recur') || 0;
727     if ($recur) {
728       $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
729     }
730     # Skip line items that have been completely credited.
731     next if ($setup + $recur) == 0;
732     my $setup_ratio = $setup / ($setup + $recur);
733
734     # Calculate the fraction of tax to credit: it's the fraction of this
735     # charge (either setup or recur) that's being credited.
736     my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
737     next if $charged == 0; # shouldn't happen, but still...
738
739     if ($charged < $amount) {
740       $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
741       last;
742     }
743     my $credit_ratio = $amount / $charged;
744
745     # gather taxes that apply to the selected item
746     foreach my $table (
747       qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
748     ) {
749       foreach my $tax_link (
750         qsearch($table, { taxable_billpkgnum => $billpkgnum })
751       ) {
752         my $tax_amount = $tax_link->amount;
753         # deduct existing credits applied to the tax, for the same reason as
754         # above
755         foreach ($tax_link->cust_credit_bill_pkg) {
756           $tax_amount -= $_->amount;
757         }
758         # split tax amount based on setuprecur
759         # (this method ensures that, if you credit both setup and recur tax,
760         # it always equals the entire tax despite any rounding)
761         my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
762         if ( $setuprecur eq 'setup' ) {
763           $tax_amount = $setup_tax;
764         } else {
765           $tax_amount = $tax_amount - $setup_tax;
766         }
767         my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
768         my $pkey = $tax_link->get($tax_link->primary_key);
769         push @taxlines, {
770           table   => $table,
771           num     => $pkey,
772           credit  => $tax_credit,
773         };
774         $taxtotal += $tax_credit;
775
776       } #foreach cust_bill_pkg_tax_(rate_)?location
777     }
778   } # foreach $billpkgnum
779
780   return (
781     subtotal => sprintf('%.2f', $subtotal),
782     taxtotal => sprintf('%.2f', $taxtotal),
783     taxlines => \@taxlines,
784   );
785 }
786
787 =item credit_lineitems OPTIONS
788
789 Creates a credit to a group of line items, with a specified amount applied
790 to each. This will also calculate the tax adjustments for those amounts and
791 credit the appropriate tax line items.
792
793 Example:
794
795   my $error = FS::cust_credit->credit_lineitems(
796
797     #the lineitems to credit
798     'billpkgnums'       => \@billpkgnums,
799     'setuprecurs'       => \@setuprecurs,
800     'amounts'           => \@amounts,
801     'apply'             => 1, #0 leaves the credit unapplied
802     'set_source'        => 1, #creates credit source records for the line items
803
804     #the credit
805     map { $_ => scalar($cgi->param($_)) }
806       #fields('cust_credit')  
807       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
808
809   );
810
811 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
812 arrays. Each one indicates an amount of credit to be applied to either the
813 setup or recur portion of a (non-tax) line item.
814
815 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
816 credit before it's inserted.
817
818 C<amount> is the total amount. If unspecified, the credit will be the sum
819 of the per-line-item amounts and their tax adjustments.
820
821 =cut
822
823 #maybe i should just be an insert with extra args instead of a class method
824 sub credit_lineitems {
825   my( $class, %arg ) = @_;
826   my $curuser = $FS::CurrentUser::CurrentUser;
827
828   #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
829
830   my $cust_main = qsearchs({
831     'table'     => 'cust_main',
832     'hashref'   => { 'custnum' => $arg{custnum} },
833     'extra_sql' => ' AND '. $curuser->agentnums_sql,
834   }) or return 'unknown customer';
835
836
837   local $SIG{HUP} = 'IGNORE';
838   local $SIG{INT} = 'IGNORE';
839   local $SIG{QUIT} = 'IGNORE';
840   local $SIG{TERM} = 'IGNORE';
841   local $SIG{TSTP} = 'IGNORE';
842   local $SIG{PIPE} = 'IGNORE';
843
844   my $oldAutoCommit = $FS::UID::AutoCommit;
845   local $FS::UID::AutoCommit = 0;
846   my $dbh = dbh;
847
848   #my @cust_bill_pkg = qsearch({
849   #  'select'    => 'cust_bill_pkg.*',
850   #  'table'     => 'cust_bill_pkg',
851   #  'addl_from' => ' LEFT JOIN cust_bill USING (invnum)  '.
852   #                 ' LEFT JOIN cust_main USING (custnum) ',
853   #  'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
854   #                     join( ',', @{$arg{billpkgnums}} ). ')',
855   #  'order_by'  => 'ORDER BY invnum ASC, billpkgnum ASC',
856   #});
857
858   my $error = '';
859
860   # first, determine the tax adjustments
861   my %tax_adjust = $class->calculate_tax_adjustment(%arg);
862   # and determine the amount automatically if it wasn't specified
863   if ( !exists( $arg{amount} ) ) {
864     $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
865   }
866
867   my $set_source = $arg{set_source};
868
869   # create the credit
870   my $cust_credit = new FS::cust_credit ( {
871     map { $_ => $arg{$_} }
872       #fields('cust_credit')
873       qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
874   } );
875   $error = $cust_credit->insert;
876   if ( $error ) {
877     $dbh->rollback if $oldAutoCommit;
878     return "Error inserting credit: $error";
879   }
880
881   unless ( $arg{'apply'} ) {
882     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
883     return '';
884   }
885
886   #my $subtotal = 0;
887   # keys in all of these are invoice numbers
888   my %cust_credit_bill = ();
889   my %cust_bill_pkg = ();
890   my %cust_credit_bill_pkg = ();
891   my %unapplied_payments = (); #invoice numbers, and then billpaynums
892   my %currency;
893
894   # little private function to unapply payments from a cust_bill_pkg until
895   # there's a specified amount of unpaid balance on it.
896   # it's a separate sub because we do it for both tax and nontax items. it's
897   # private because it needs access to some local data structures.
898   my $unapply_sub = sub {
899     my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
900
901     my $invnum = $cust_bill_pkg->invnum;
902
903     $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
904     return if $need_to_unapply < 0.005;
905
906     my $error;
907     # then unapply payments one at a time (partially if need be) until the
908     # unpaid balance = the credit amount.
909     foreach my $cust_bill_pay_pkg (
910       $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
911     ) {
912       my $this_amount = $cust_bill_pay_pkg->amount;
913       if ( $this_amount > $need_to_unapply ) {
914         # unapply the needed amount
915         $cust_bill_pay_pkg->set('amount',
916           sprintf('%.2f', $this_amount - $need_to_unapply));
917         $error = $cust_bill_pay_pkg->replace;
918         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
919         last; # and we're done
920
921       } else {
922         # unapply it all
923         $error = $cust_bill_pay_pkg->delete;
924         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
925
926         $need_to_unapply -= $this_amount;
927       }
928
929     } # foreach $cust_bill_pay_pkg
930
931     # return an error if we somehow still have leftover $need_to_unapply?
932
933     return $error;
934   };
935
936
937   foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
938     my $setuprecur = shift @{$arg{setuprecurs}};
939     my $amount = shift @{$arg{amounts}};
940
941     my $cust_bill_pkg = qsearchs({
942       'table'     => 'cust_bill_pkg',
943       'hashref'   => { 'billpkgnum' => $billpkgnum },
944       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
945       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
946     }) or die "unknown billpkgnum $billpkgnum";
947   
948     my $invnum = $cust_bill_pkg->invnum;
949
950     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
951
952     $cust_credit_bill{$invnum} += $amount;
953     push @{ $cust_credit_bill_pkg{$invnum} },
954       new FS::cust_credit_bill_pkg {
955         'billpkgnum' => $billpkgnum,
956         'amount'     => sprintf('%.2f',$amount),
957         'setuprecur' => $setuprecur,
958         'sdate'      => $cust_bill_pkg->sdate,
959         'edate'      => $cust_bill_pkg->edate,
960       };
961
962     # unapply payments if necessary
963     $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
964
965     if ( $set_source ) {
966       $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
967       my $source = FS::cust_credit_source_bill_pkg->new({
968         'crednum'     => $cust_credit->crednum,
969         'billpkgnum'  => $billpkgnum,
970         'amount'      => $amount,
971         'currency'    => $currency{invnum},
972       });
973       $error ||= $source->insert;
974     }
975
976     if ( $error ) {
977       $dbh->rollback if $oldAutoCommit;
978       return "Error unapplying payment: $error";
979     }
980   }
981
982   # do the same for taxes
983   foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
984     my $table = $tax_credit->{table};
985     my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
986       or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
987
988     my $billpkgnum = $tax_link->billpkgnum;
989     my $cust_bill_pkg = qsearchs({
990       'table'     => 'cust_bill_pkg',
991       'hashref'   => { 'billpkgnum' => $billpkgnum },
992       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
993       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
994     }) or die "unknown billpkgnum $billpkgnum";
995     
996     my $invnum = $cust_bill_pkg->invnum;
997     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
998
999     my $amount = $tax_credit->{credit};
1000     $cust_credit_bill{$invnum} += $amount;
1001
1002     # create a credit application record to the tax line item, earmarked
1003     # to the specific cust_bill_pkg_Xlocation
1004     push @{ $cust_credit_bill_pkg{$invnum} },
1005       new FS::cust_credit_bill_pkg {
1006         'billpkgnum' => $billpkgnum,
1007         'amount'     => sprintf('%.2f', $amount),
1008         'setuprecur' => 'setup',
1009         $tax_link->primary_key, $tax_credit->{num}
1010       };
1011
1012     $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1013
1014     # I guess it's correct to do this for taxes also?
1015     if ( $set_source ) {
1016       $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
1017       my $source = FS::cust_credit_source_bill_pkg->new({
1018         'crednum'     => $cust_credit->crednum,
1019         'billpkgnum'  => $billpkgnum,
1020         'amount'      => $amount,
1021         'currency'    => $currency{invnum},
1022       });
1023       $error ||= $source->insert;
1024     }
1025
1026     if ( $error ) {
1027       $dbh->rollback if $oldAutoCommit;
1028       return "Error unapplying payment: $error";
1029     }
1030   }
1031
1032   ###
1033   # now loop through %cust_credit_bill and insert those
1034   ###
1035
1036   # (hack to prevent cust_credit_bill_pkg insertion)
1037   local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1038
1039   foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1040
1041     # if we unapplied any payments from line items, also unapply that 
1042     # amount from the invoice
1043     foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1044       my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1045         or die "broken payment application $billpaynum";
1046       my @subapps = $cust_bill_pay->lineitem_applications;
1047       $error = $cust_bill_pay->delete; # can't replace
1048
1049       my $new_cust_bill_pay = FS::cust_bill_pay->new({
1050           $cust_bill_pay->hash,
1051           billpaynum => '',
1052           amount => sprintf('%.2f', 
1053               $cust_bill_pay->amount 
1054               - $unapplied_payments{$invnum}{$billpaynum}),
1055       });
1056
1057       if ( $new_cust_bill_pay->amount > 0 ) {
1058         $error ||= $new_cust_bill_pay->insert;
1059         # Also reapply it to everything it was applied to before.
1060         # Note that we've already deleted cust_bill_pay_pkg records for the
1061         # items we're crediting, so they aren't on this list.
1062         foreach my $cust_bill_pay_pkg (@subapps) {
1063           $cust_bill_pay_pkg->billpaypkgnum('');
1064           $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1065           $error ||= $cust_bill_pay_pkg->insert;
1066         }
1067       }
1068       if ( $error ) {
1069         $dbh->rollback if $oldAutoCommit;
1070         return "Error unapplying payment: $error";
1071       }
1072     }
1073     #insert cust_credit_bill
1074
1075     my $cust_credit_bill = new FS::cust_credit_bill {
1076       'crednum' => $cust_credit->crednum,
1077       'invnum'  => $invnum,
1078       'amount'  => sprintf('%.2f', $cust_credit_bill{$invnum}),
1079     };
1080     $error = $cust_credit_bill->insert;
1081     if ( $error ) {
1082       $dbh->rollback if $oldAutoCommit;
1083       return "Error applying credit of $cust_credit_bill{$invnum} ".
1084              " to invoice $invnum: $error";
1085     }
1086
1087     #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1088     foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1089       $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1090       $error = $cust_credit_bill_pkg->insert;
1091       if ( $error ) {
1092         $dbh->rollback if $oldAutoCommit;
1093         return "Error applying credit to line item: $error";
1094       }
1095     }
1096
1097   }
1098
1099   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1100   '';
1101
1102 }
1103
1104 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1105
1106 =item refund_to_unapply
1107
1108 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1109 (all currently applied refunds that aren't closed.)
1110 Returns empty list if credit itself is closed.
1111
1112 =cut
1113
1114 sub refund_to_unapply {
1115   my $self = shift;
1116   return () if $self->closed;
1117   qsearch({
1118     'table'   => 'cust_credit_refund',
1119     'hashref' => { 'crednum' => $self->crednum },
1120     'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1121     'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1122   });
1123 }
1124
1125 =item unapply_refund
1126
1127 Deletes all objects returned by L</refund_to_unapply>.
1128
1129 =cut
1130
1131 sub unapply_refund {
1132   my $self = shift;
1133
1134   local $SIG{HUP} = 'IGNORE';
1135   local $SIG{INT} = 'IGNORE';
1136   local $SIG{QUIT} = 'IGNORE';
1137   local $SIG{TERM} = 'IGNORE';
1138   local $SIG{TSTP} = 'IGNORE';
1139   local $SIG{PIPE} = 'IGNORE';
1140
1141   my $oldAutoCommit = $FS::UID::AutoCommit;
1142   local $FS::UID::AutoCommit = 0;
1143
1144   foreach my $cust_credit_refund ($self->refund_to_unapply) {
1145     my $error = $cust_credit_refund->delete;
1146     if ($error) {
1147       dbh->rollback if $oldAutoCommit;
1148       return $error;
1149     }
1150   }
1151
1152   dbh->commit or die dbh->errstr if $oldAutoCommit;
1153   return '';
1154 }
1155
1156 =back
1157
1158 =head1 SUBROUTINES
1159
1160 =over 4
1161
1162 =item process_batch_import
1163
1164 =cut
1165
1166 use List::Util qw( min );
1167 use FS::cust_bill;
1168 use FS::cust_credit_bill;
1169 sub process_batch_import {
1170   my $job = shift;
1171
1172   # some false laziness with FS::cust_pay::process_batch_import
1173   my $hashcb = sub {
1174     my %hash = @_;
1175     my $custnum = $hash{'custnum'};
1176     my $agent_custid = $hash{'agent_custid'};
1177     # translate agent_custid into regular custnum
1178     if ($custnum && $agent_custid) {
1179       die "can't specify both custnum and agent_custid\n";
1180     } elsif ($agent_custid) {
1181       # here is the agent virtualization
1182       my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1183       my %search;
1184       $search{'agent_custid'} = $agent_custid
1185         if $agent_custid;
1186       $search{'custnum'} = $custnum
1187         if $custnum;
1188       my $cust_main = qsearchs({
1189         'table'     => 'cust_main',
1190         'hashref'   => \%search,
1191         'extra_sql' => $extra_sql,
1192       });
1193       die "can't find customer with" .
1194         ($custnum  ? " custnum $custnum" : '') .
1195         ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1196         unless $cust_main;
1197       die "mismatched customer number\n"
1198         if $custnum && ($custnum ne $cust_main->custnum);
1199       $custnum = $cust_main->custnum;
1200     }
1201     $hash{'custnum'} = $custnum;
1202     delete($hash{'agent_custid'});
1203     return %hash;
1204   };
1205
1206   my $opt = { 'table'   => 'cust_credit',
1207               'params'  => [ '_date', 'credbatch' ],
1208               'formats' => { 'simple' =>
1209                                [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1210                            },
1211               'default_csv' => 1,
1212               'format_hash_callbacks' => { 'simple' => $hashcb },
1213               'postinsert_callback' => sub {
1214                 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1215
1216                 if ( $cust_credit->invnum ) {
1217
1218                   my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1219                   my $amount = min( $cust_credit->credited, $cust_bill->owed );
1220     
1221                   my $cust_credit_bill = new FS::cust_credit_bill ( {
1222                     'crednum' => $cust_credit->crednum,
1223                     'invnum'  => $cust_bill->invnum,
1224                     'amount'  => $amount,
1225                   } );
1226                   my $error = $cust_credit_bill->insert;
1227                   return '' unless $error;
1228
1229                 }
1230
1231                 #apply_payments_and_credits ?
1232                 $cust_credit->cust_main->apply_credits;
1233
1234                 return '';
1235
1236               },
1237             };
1238
1239   FS::Record::process_batch_import( $job, $opt, @_ );
1240
1241 }
1242
1243 =back
1244
1245 =head1 BUGS
1246
1247 The delete method.  The replace method.
1248
1249 B<credited> and B<credited_sql> are now called B<unapplied> and
1250 B<unapplied_sql>.  The old method names should start to give warnings.
1251
1252 =head1 SEE ALSO
1253
1254 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1255 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
1256 documentation.
1257
1258 =cut
1259
1260 1;
1261