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     || $self->ut_foreign_keyn('commission_invnum', 'cust_bill', 'invnum')
319   ;
320   return $error if $error;
321
322   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
323   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
324   return $error if $error;
325
326   return "amount must be > 0 " if $self->amount <= 0;
327
328   return "amount must be greater or equal to amount applied"
329     if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
330
331   return "Unknown customer"
332     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
333
334   $self->_date(time) unless $self->_date;
335
336   $self->SUPER::check;
337 }
338
339 =item void [ REASON ]
340
341 Voids this credit: deletes the credit and all associated applications and 
342 adds a record of the voided credit to the cust_credit_void table.
343
344 =cut
345
346 sub void {
347   my $self = shift;
348   my $reason = shift;
349
350   unless (ref($reason) || !$reason) {
351     $reason = FS::reason->new_or_existing(
352       'class'  => 'X',
353       'type'   => 'Void credit',
354       'reason' => $reason
355     );
356   }
357
358   local $SIG{HUP} = 'IGNORE';
359   local $SIG{INT} = 'IGNORE';
360   local $SIG{QUIT} = 'IGNORE';
361   local $SIG{TERM} = 'IGNORE';
362   local $SIG{TSTP} = 'IGNORE';
363   local $SIG{PIPE} = 'IGNORE';
364
365   my $oldAutoCommit = $FS::UID::AutoCommit;
366   local $FS::UID::AutoCommit = 0;
367   my $dbh = dbh;
368
369   my $cust_credit_void = new FS::cust_credit_void ( {
370       map { $_ => $self->get($_) } $self->fields
371     } );
372   $cust_credit_void->set('void_reasonnum', $reason->reasonnum) if $reason;
373   my $error = $cust_credit_void->insert;
374   if ( $error ) {
375     $dbh->rollback if $oldAutoCommit;
376     return $error;
377   }
378
379   $error = $self->delete();
380   if ( $error ) {
381     $dbh->rollback if $oldAutoCommit;
382     return $error;
383   }
384
385   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
386
387   '';
388
389 }
390
391 =item cust_credit_refund
392
393 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
394
395 =cut
396
397 sub cust_credit_refund {
398   my $self = shift;
399   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
400   sort { $a->_date <=> $b->_date }
401     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
402   ;
403 }
404
405 =item cust_credit_bill
406
407 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
408 credit.
409
410 =cut
411
412 sub cust_credit_bill {
413   my $self = shift;
414   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
415   sort { $a->_date <=> $b->_date }
416     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
417   ;
418 }
419
420 =item unapplied
421
422 Returns the amount of this credit that is still unapplied/outstanding; 
423 amount minus all refund applications (see L<FS::cust_credit_refund>) and
424 applications to invoices (see L<FS::cust_credit_bill>).
425
426 =cut
427
428 sub unapplied {
429   my $self = shift;
430   my $amount = $self->amount;
431   $amount -= $_->amount foreach ( $self->cust_credit_refund );
432   $amount -= $_->amount foreach ( $self->cust_credit_bill );
433   sprintf( "%.2f", $amount );
434 }
435
436 =item credited
437
438 Deprecated name for the unapplied method.
439
440 =cut
441
442 sub credited {
443   my $self = shift;
444   #carp "cust_credit->credited deprecated; use ->unapplied";
445   $self->unapplied(@_);
446 }
447
448 =item cust_main
449
450 Returns the customer (see L<FS::cust_main>) for this credit.
451
452 =cut
453
454 # _upgrade_data
455 #
456 # Used by FS::Upgrade to migrate to a new database.
457
458 sub _upgrade_data {  # class method
459   my ($class, %opts) = @_;
460
461   warn "$me upgrading $class\n" if $DEBUG;
462
463   $class->_upgrade_reasonnum(%opts);
464
465   if (defined dbdef->table($class->table)->column('reason')) {
466
467     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
468
469     foreach ( keys %reasontype_map ) {
470       unless ($conf->config($_)) {       # hmmmm
471 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
472 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
473         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
474         my $reason_type = qsearchs( 'reason_type', $hashref );
475         unless ($reason_type) {
476           $reason_type  = new FS::reason_type( $hashref );
477           my $error   = $reason_type->insert();
478           die "$class had error inserting FS::reason_type into database: $error\n"
479             if $error;
480         }
481         $conf->set($_, $reason_type->typenum);
482       }
483     }
484
485     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
486
487     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
488     my $reason_type = qsearchs( 'reason_type', $hashref );
489     unless ($reason_type) {
490       $reason_type  = new FS::reason_type( $hashref );
491       my $error   = $reason_type->insert();
492       die "$class had error inserting FS::reason_type into database: $error\n"
493         if $error;
494     }
495
496     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
497     foreach my $plan ( @plans ) {
498       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
499         unless ($pkg->option('reason_type', 1) ) { 
500           my $plandata = $pkg->plandata.
501                         "reason_type=". $reason_type->typenum. "\n";
502           $pkg->plandata($plandata);
503           my $error =
504             $pkg->replace( undef,
505                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
506                                           $pkg->pkg_svc
507                                         },
508                            'primary_svc' => $pkg->svcpart,
509                          );
510             die "failed setting reason_type option: $error"
511               if $error;
512         }
513       }
514     }
515   }
516
517   local($otaker_upgrade_kludge) = 1;
518   local($ignore_empty_reasonnum) = 1;
519   $class->_upgrade_otaker(%opts);
520
521   if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
522       and !$conf->config('tax_data_vendor') ) {
523     # RT#25458: fix credit line item applications that should refer to a 
524     # specific tax allocation
525     my @cust_credit_bill_pkg = qsearch({
526         table     => 'cust_credit_bill_pkg',
527         select    => 'cust_credit_bill_pkg.*',
528         addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
529         extra_sql =>
530           'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
531           'AND cust_bill_pkg.pkgnum = 0', # is a tax
532     });
533     my %tax_items;
534     my %credits;
535     foreach (@cust_credit_bill_pkg) {
536       my $billpkgnum = $_->billpkgnum;
537       $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
538       $credits{$billpkgnum} ||= [];
539       push @{ $credits{$billpkgnum} }, $_;
540     }
541     TAX_ITEM: foreach my $tax_item (values %tax_items) {
542       my $billpkgnum = $tax_item->billpkgnum;
543       # get all pkg/location/taxrate allocations of this tax line item
544       my @allocations = sort {$b->amount <=> $a->amount}
545                         qsearch('cust_bill_pkg_tax_location', {
546                             billpkgnum => $billpkgnum
547                         });
548       # and these are all credit applications to it
549       my @credits = sort {$b->amount <=> $a->amount}
550                     @{ $credits{$billpkgnum} };
551       my $c = shift @credits;
552       my $a = shift @allocations; # we will NOT modify these
553       while ($c and $a) {
554         if ( abs($c->amount - $a->amount) < 0.005 ) {
555           # by far the most common case: the tax line item is for a single
556           # tax, so we just fill in the billpkgtaxlocationnum
557           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
558           my $error = $c->replace;
559           if ($error) {
560             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
561             next TAX_ITEM;
562           }
563           $c = shift @credits;
564           $a = shift @allocations;
565         } elsif ( $c->amount > $a->amount ) {
566           # fairly common: the tax line contains tax for multiple packages
567           # (or multiple taxes) but the credit isn't divided up
568           my $new_link = FS::cust_credit_bill_pkg->new({
569               creditbillnum         => $c->creditbillnum,
570               billpkgnum            => $c->billpkgnum,
571               billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
572               amount                => $a->amount,
573               setuprecur            => 'setup',
574           });
575           my $error = $new_link->insert;
576           if ($error) {
577             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
578             next TAX_ITEM;
579           }
580           $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
581           $a = shift @allocations;
582         } elsif ( $c->amount < 0.005 ) {
583           # also fairly common; we can delete these with no harm
584           my $error = $c->delete;
585           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
586           $c = shift @credits;
587         } elsif ( $c->amount < $a->amount ) {
588           # should never happen, but if it does, handle it gracefully
589           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
590           my $error = $c->replace;
591           if ($error) {
592             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
593             next TAX_ITEM;
594           }
595           $a->set(amount => $a->amount - $c->amount);
596           $c = shift @credits;
597         }
598       } # while $c and $a
599       if ( $c ) {
600         if ( $c->amount < 0.005 ) {
601           my $error = $c->delete;
602           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
603         } elsif ( $c->modified ) {
604           # then we've allocated part of it, so reduce the nonspecific 
605           # application by that much
606           my $error = $c->replace;
607           warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
608         }
609         # else there are probably no allocations, i.e. this is a pre-3.x 
610         # record that was never migrated over, so leave it alone
611       } # if $c
612     } # foreach $tax_item
613     FS::upgrade_journal->set_done('cust_credit__tax_link');
614   }
615 }
616
617 =back
618
619 =head1 CLASS METHODS
620
621 =over 4
622
623 =item unapplied_sql
624
625 Returns an SQL fragment to retreive the unapplied amount.
626
627 =cut
628
629 sub unapplied_sql {
630   my ($class, $start, $end) = @_;
631
632   my $bill_start   = $start ? "AND cust_credit_bill._date <= $start"   : '';
633   my $bill_end     = $end   ? "AND cust_credit_bill._date > $end"     : '';
634   my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
635   my $refund_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
636
637   "amount
638         - COALESCE(
639                     ( SELECT SUM(amount) FROM cust_credit_refund
640                         WHERE cust_credit.crednum = cust_credit_refund.crednum
641                         $refund_start $refund_end )
642                     ,0
643                   )
644         - COALESCE(
645                     ( SELECT SUM(amount) FROM cust_credit_bill
646                         WHERE cust_credit.crednum = cust_credit_bill.crednum
647                         $bill_start $bill_end )
648                     ,0
649                   )
650   ";
651
652 }
653
654 =item credited_sql
655
656 Deprecated name for the unapplied_sql method.
657
658 =cut
659
660 sub credited_sql {
661   #my $class = shift;
662
663   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
664
665   #$class->unapplied_sql(@_);
666   unapplied_sql();
667 }
668
669 =item calculate_tax_adjustment PARAMS
670
671 Calculate the amount of tax that needs to be credited as part of a lineitem
672 credit.
673
674 PARAMS must include:
675
676 - billpkgnums: arrayref identifying the line items to credit
677 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
678   the lineitem charge is being credited
679 - amounts: arrayref of the amounts to credit on each line item
680 - custnum: the customer all of these invoices belong to, for error checking
681
682 Returns a hash containing:
683 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
684 - taxtotal: the total tax amount to be credited
685 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
686   - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
687   - num: the key within that table
688   - credit: the credit amount to apply to that line
689
690 =cut
691
692 sub calculate_tax_adjustment {
693   my ($class, %arg) = @_;
694
695   my $error;
696   my @taxlines;
697   my $subtotal = 0;
698   my $taxtotal = 0;
699
700   my (%cust_bill_pkg, %cust_bill);
701
702   for (my $i = 0; ; $i++) {
703     my $billpkgnum = $arg{billpkgnums}[$i]
704       or last;
705     my $setuprecur = $arg{setuprecurs}[$i];
706     my $amount = $arg{amounts}[$i];
707     next if $amount == 0;
708     $subtotal += $amount;
709     my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
710                     ||= FS::cust_bill_pkg->by_key($billpkgnum)
711       or die "lineitem #$billpkgnum not found\n";
712
713     my $invnum = $cust_bill_pkg->invnum;
714     $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
715     $cust_bill{ $invnum}->custnum == $arg{custnum}
716       or die "lineitem #$billpkgnum not found\n";
717
718     # tax_Xlocation records don't distinguish setup and recur, so calculate
719     # the fraction of setup+recur (after deducting credits) that's setup. This
720     # will also be the fraction of tax (after deducting credits) that's tax on
721     # setup.
722     my ($setup, $recur);
723     $setup = $cust_bill_pkg->get('setup') || 0;
724     if ($setup) {
725       $setup -= $cust_bill_pkg->credited('', '', setuprecur => 'setup') || 0;
726     }
727     $recur = $cust_bill_pkg->get('recur') || 0;
728     if ($recur) {
729       $recur -= $cust_bill_pkg->credited('', '', setuprecur => 'recur') || 0;
730     }
731     # Skip line items that have been completely credited.
732     next if ($setup + $recur) == 0;
733     my $setup_ratio = $setup / ($setup + $recur);
734
735     # Calculate the fraction of tax to credit: it's the fraction of this
736     # charge (either setup or recur) that's being credited.
737     my $charged = ($setuprecur eq 'setup') ? $setup : $recur;
738     next if $charged == 0; # shouldn't happen, but still...
739
740     if ($charged < $amount) {
741       $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
742       last;
743     }
744     my $credit_ratio = $amount / $charged;
745
746     # gather taxes that apply to the selected item
747     foreach my $table (
748       qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
749     ) {
750       foreach my $tax_link (
751         qsearch($table, { taxable_billpkgnum => $billpkgnum })
752       ) {
753         my $tax_amount = $tax_link->amount;
754         # deduct existing credits applied to the tax, for the same reason as
755         # above
756         foreach ($tax_link->cust_credit_bill_pkg) {
757           $tax_amount -= $_->amount;
758         }
759         # split tax amount based on setuprecur
760         # (this method ensures that, if you credit both setup and recur tax,
761         # it always equals the entire tax despite any rounding)
762         my $setup_tax = sprintf('%.2f', $tax_amount * $setup_ratio);
763         if ( $setuprecur eq 'setup' ) {
764           $tax_amount = $setup_tax;
765         } else {
766           $tax_amount = $tax_amount - $setup_tax;
767         }
768         my $tax_credit = sprintf('%.2f', $tax_amount * $credit_ratio);
769         my $pkey = $tax_link->get($tax_link->primary_key);
770         push @taxlines, {
771           table   => $table,
772           num     => $pkey,
773           credit  => $tax_credit,
774         };
775         $taxtotal += $tax_credit;
776
777       } #foreach cust_bill_pkg_tax_(rate_)?location
778     }
779   } # foreach $billpkgnum
780
781   return (
782     subtotal => sprintf('%.2f', $subtotal),
783     taxtotal => sprintf('%.2f', $taxtotal),
784     taxlines => \@taxlines,
785   );
786 }
787
788 =item credit_lineitems OPTIONS
789
790 Creates a credit to a group of line items, with a specified amount applied
791 to each. This will also calculate the tax adjustments for those amounts and
792 credit the appropriate tax line items.
793
794 Example:
795
796   my $error = FS::cust_credit->credit_lineitems(
797
798     #the lineitems to credit
799     'billpkgnums'       => \@billpkgnums,
800     'setuprecurs'       => \@setuprecurs,
801     'amounts'           => \@amounts,
802     'apply'             => 1, #0 leaves the credit unapplied
803     'set_source'        => 1, #creates credit source records for the line items
804
805     #the credit
806     map { $_ => scalar($cgi->param($_)) }
807       #fields('cust_credit')  
808       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
809
810   );
811
812 C<billpkgnums>, C<setuprecurs>, C<amounts> are required and are parallel
813 arrays. Each one indicates an amount of credit to be applied to either the
814 setup or recur portion of a (non-tax) line item.
815
816 C<custnum>, C<_date>, C<reasonnum>, and C<addlinfo> will be set on the
817 credit before it's inserted.
818
819 C<amount> is the total amount. If unspecified, the credit will be the sum
820 of the per-line-item amounts and their tax adjustments.
821
822 =cut
823
824 #maybe i should just be an insert with extra args instead of a class method
825 sub credit_lineitems {
826   my( $class, %arg ) = @_;
827   my $curuser = $FS::CurrentUser::CurrentUser;
828
829   #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
830
831   my $cust_main = qsearchs({
832     'table'     => 'cust_main',
833     'hashref'   => { 'custnum' => $arg{custnum} },
834     'extra_sql' => ' AND '. $curuser->agentnums_sql,
835   }) or return 'unknown customer';
836
837
838   local $SIG{HUP} = 'IGNORE';
839   local $SIG{INT} = 'IGNORE';
840   local $SIG{QUIT} = 'IGNORE';
841   local $SIG{TERM} = 'IGNORE';
842   local $SIG{TSTP} = 'IGNORE';
843   local $SIG{PIPE} = 'IGNORE';
844
845   my $oldAutoCommit = $FS::UID::AutoCommit;
846   local $FS::UID::AutoCommit = 0;
847   my $dbh = dbh;
848
849   #my @cust_bill_pkg = qsearch({
850   #  'select'    => 'cust_bill_pkg.*',
851   #  'table'     => 'cust_bill_pkg',
852   #  'addl_from' => ' LEFT JOIN cust_bill USING (invnum)  '.
853   #                 ' LEFT JOIN cust_main USING (custnum) ',
854   #  'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
855   #                     join( ',', @{$arg{billpkgnums}} ). ')',
856   #  'order_by'  => 'ORDER BY invnum ASC, billpkgnum ASC',
857   #});
858
859   my $error = '';
860
861   # first, determine the tax adjustments
862   my %tax_adjust = $class->calculate_tax_adjustment(%arg);
863   # and determine the amount automatically if it wasn't specified
864   if ( !exists( $arg{amount} ) ) {
865     $arg{amount} = sprintf('%.2f', $tax_adjust{subtotal} + $tax_adjust{taxtotal});
866   }
867
868   my $set_source = $arg{set_source};
869
870   # create the credit
871   my $cust_credit = new FS::cust_credit ( {
872     map { $_ => $arg{$_} }
873       #fields('cust_credit')
874       qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
875   } );
876   $error = $cust_credit->insert;
877   if ( $error ) {
878     $dbh->rollback if $oldAutoCommit;
879     return "Error inserting credit: $error";
880   }
881
882   unless ( $arg{'apply'} ) {
883     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
884     return '';
885   }
886
887   #my $subtotal = 0;
888   # keys in all of these are invoice numbers
889   my %cust_credit_bill = ();
890   my %cust_bill_pkg = ();
891   my %cust_credit_bill_pkg = ();
892   my %unapplied_payments = (); #invoice numbers, and then billpaynums
893   my %currency;
894
895   # little private function to unapply payments from a cust_bill_pkg until
896   # there's a specified amount of unpaid balance on it.
897   # it's a separate sub because we do it for both tax and nontax items. it's
898   # private because it needs access to some local data structures.
899   my $unapply_sub = sub {
900     my ($cust_bill_pkg, $setuprecur, $need_to_unapply) = @_;
901
902     my $invnum = $cust_bill_pkg->invnum;
903
904     $need_to_unapply -= $cust_bill_pkg->owed($setuprecur);
905     return if $need_to_unapply < 0.005;
906
907     my $error;
908     # then unapply payments one at a time (partially if need be) until the
909     # unpaid balance = the credit amount.
910     foreach my $cust_bill_pay_pkg (
911       $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
912     ) {
913       my $this_amount = $cust_bill_pay_pkg->amount;
914       if ( $this_amount > $need_to_unapply ) {
915         # unapply the needed amount
916         $cust_bill_pay_pkg->set('amount',
917           sprintf('%.2f', $this_amount - $need_to_unapply));
918         $error = $cust_bill_pay_pkg->replace;
919         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $need_to_unapply;
920         last; # and we're done
921
922       } else {
923         # unapply it all
924         $error = $cust_bill_pay_pkg->delete;
925         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum} += $this_amount;
926
927         $need_to_unapply -= $this_amount;
928       }
929
930     } # foreach $cust_bill_pay_pkg
931
932     # return an error if we somehow still have leftover $need_to_unapply?
933
934     return $error;
935   };
936
937
938   foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
939     my $setuprecur = shift @{$arg{setuprecurs}};
940     my $amount = shift @{$arg{amounts}};
941
942     my $cust_bill_pkg = qsearchs({
943       'table'     => 'cust_bill_pkg',
944       'hashref'   => { 'billpkgnum' => $billpkgnum },
945       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
946       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
947     }) or die "unknown billpkgnum $billpkgnum";
948   
949     my $invnum = $cust_bill_pkg->invnum;
950
951     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
952
953     $cust_credit_bill{$invnum} += $amount;
954     push @{ $cust_credit_bill_pkg{$invnum} },
955       new FS::cust_credit_bill_pkg {
956         'billpkgnum' => $billpkgnum,
957         'amount'     => sprintf('%.2f',$amount),
958         'setuprecur' => $setuprecur,
959         'sdate'      => $cust_bill_pkg->sdate,
960         'edate'      => $cust_bill_pkg->edate,
961       };
962
963     # unapply payments if necessary
964     $error = &{$unapply_sub}($cust_bill_pkg, $setuprecur, $amount);
965
966     if ( $set_source ) {
967       $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
968       my $source = FS::cust_credit_source_bill_pkg->new({
969         'crednum'     => $cust_credit->crednum,
970         'billpkgnum'  => $billpkgnum,
971         'amount'      => $amount,
972         'currency'    => $currency{invnum},
973       });
974       $error ||= $source->insert;
975     }
976
977     if ( $error ) {
978       $dbh->rollback if $oldAutoCommit;
979       return "Error unapplying payment: $error";
980     }
981   }
982
983   # do the same for taxes
984   foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
985     my $table = $tax_credit->{table};
986     my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
987       or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
988
989     my $billpkgnum = $tax_link->billpkgnum;
990     my $cust_bill_pkg = qsearchs({
991       'table'     => 'cust_bill_pkg',
992       'hashref'   => { 'billpkgnum' => $billpkgnum },
993       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
994       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
995     }) or die "unknown billpkgnum $billpkgnum";
996     
997     my $invnum = $cust_bill_pkg->invnum;
998     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
999
1000     my $amount = $tax_credit->{credit};
1001     $cust_credit_bill{$invnum} += $amount;
1002
1003     # create a credit application record to the tax line item, earmarked
1004     # to the specific cust_bill_pkg_Xlocation
1005     push @{ $cust_credit_bill_pkg{$invnum} },
1006       new FS::cust_credit_bill_pkg {
1007         'billpkgnum' => $billpkgnum,
1008         'amount'     => sprintf('%.2f', $amount),
1009         'setuprecur' => 'setup',
1010         $tax_link->primary_key, $tax_credit->{num}
1011       };
1012
1013     $error = &{$unapply_sub}($cust_bill_pkg, 'setup', $amount);
1014
1015     # I guess it's correct to do this for taxes also?
1016     if ( $set_source ) {
1017       $currency{$invnum} ||= $cust_bill_pkg->cust_bill->currency;
1018       my $source = FS::cust_credit_source_bill_pkg->new({
1019         'crednum'     => $cust_credit->crednum,
1020         'billpkgnum'  => $billpkgnum,
1021         'amount'      => $amount,
1022         'currency'    => $currency{invnum},
1023       });
1024       $error ||= $source->insert;
1025     }
1026
1027     if ( $error ) {
1028       $dbh->rollback if $oldAutoCommit;
1029       return "Error unapplying payment: $error";
1030     }
1031   }
1032
1033   ###
1034   # now loop through %cust_credit_bill and insert those
1035   ###
1036
1037   # (hack to prevent cust_credit_bill_pkg insertion)
1038   local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
1039
1040   foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
1041
1042     # if we unapplied any payments from line items, also unapply that 
1043     # amount from the invoice
1044     foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
1045       my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
1046         or die "broken payment application $billpaynum";
1047       my @subapps = $cust_bill_pay->lineitem_applications;
1048       $error = $cust_bill_pay->delete; # can't replace
1049
1050       my $new_cust_bill_pay = FS::cust_bill_pay->new({
1051           $cust_bill_pay->hash,
1052           billpaynum => '',
1053           amount => sprintf('%.2f', 
1054               $cust_bill_pay->amount 
1055               - $unapplied_payments{$invnum}{$billpaynum}),
1056       });
1057
1058       if ( $new_cust_bill_pay->amount > 0 ) {
1059         $error ||= $new_cust_bill_pay->insert;
1060         # Also reapply it to everything it was applied to before.
1061         # Note that we've already deleted cust_bill_pay_pkg records for the
1062         # items we're crediting, so they aren't on this list.
1063         foreach my $cust_bill_pay_pkg (@subapps) {
1064           $cust_bill_pay_pkg->billpaypkgnum('');
1065           $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
1066           $error ||= $cust_bill_pay_pkg->insert;
1067         }
1068       }
1069       if ( $error ) {
1070         $dbh->rollback if $oldAutoCommit;
1071         return "Error unapplying payment: $error";
1072       }
1073     }
1074     #insert cust_credit_bill
1075
1076     my $cust_credit_bill = new FS::cust_credit_bill {
1077       'crednum' => $cust_credit->crednum,
1078       'invnum'  => $invnum,
1079       'amount'  => sprintf('%.2f', $cust_credit_bill{$invnum}),
1080     };
1081     $error = $cust_credit_bill->insert;
1082     if ( $error ) {
1083       $dbh->rollback if $oldAutoCommit;
1084       return "Error applying credit of $cust_credit_bill{$invnum} ".
1085              " to invoice $invnum: $error";
1086     }
1087
1088     #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1089     foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1090       $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1091       $error = $cust_credit_bill_pkg->insert;
1092       if ( $error ) {
1093         $dbh->rollback if $oldAutoCommit;
1094         return "Error applying credit to line item: $error";
1095       }
1096     }
1097
1098   }
1099
1100   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1101   '';
1102
1103 }
1104
1105 ### refund_to_unapply/unapply_refund false laziness with FS::cust_pay
1106
1107 =item refund_to_unapply
1108
1109 Returns L<FS::cust_credit_refund> objects that will be deleted by L</unapply_refund>
1110 (all currently applied refunds that aren't closed.)
1111 Returns empty list if credit itself is closed.
1112
1113 =cut
1114
1115 sub refund_to_unapply {
1116   my $self = shift;
1117   return () if $self->closed;
1118   qsearch({
1119     'table'   => 'cust_credit_refund',
1120     'hashref' => { 'crednum' => $self->crednum },
1121     'addl_from' => 'LEFT JOIN cust_refund USING (refundnum)',
1122     'extra_sql' => "AND cust_refund.closed IS NULL AND cust_refund.source_paynum IS NULL",
1123   });
1124 }
1125
1126 =item unapply_refund
1127
1128 Deletes all objects returned by L</refund_to_unapply>.
1129
1130 =cut
1131
1132 sub unapply_refund {
1133   my $self = shift;
1134
1135   local $SIG{HUP} = 'IGNORE';
1136   local $SIG{INT} = 'IGNORE';
1137   local $SIG{QUIT} = 'IGNORE';
1138   local $SIG{TERM} = 'IGNORE';
1139   local $SIG{TSTP} = 'IGNORE';
1140   local $SIG{PIPE} = 'IGNORE';
1141
1142   my $oldAutoCommit = $FS::UID::AutoCommit;
1143   local $FS::UID::AutoCommit = 0;
1144
1145   foreach my $cust_credit_refund ($self->refund_to_unapply) {
1146     my $error = $cust_credit_refund->delete;
1147     if ($error) {
1148       dbh->rollback if $oldAutoCommit;
1149       return $error;
1150     }
1151   }
1152
1153   dbh->commit or die dbh->errstr if $oldAutoCommit;
1154   return '';
1155 }
1156
1157 =back
1158
1159 =head1 SUBROUTINES
1160
1161 =over 4
1162
1163 =item process_batch_import
1164
1165 =cut
1166
1167 use List::Util qw( min );
1168 use FS::cust_bill;
1169 use FS::cust_credit_bill;
1170 sub process_batch_import {
1171   my $job = shift;
1172
1173   # some false laziness with FS::cust_pay::process_batch_import
1174   my $hashcb = sub {
1175     my %hash = @_;
1176     my $custnum = $hash{'custnum'};
1177     my $agent_custid = $hash{'agent_custid'};
1178     # translate agent_custid into regular custnum
1179     if ($custnum && $agent_custid) {
1180       die "can't specify both custnum and agent_custid\n";
1181     } elsif ($agent_custid) {
1182       # here is the agent virtualization
1183       my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
1184       my %search;
1185       $search{'agent_custid'} = $agent_custid
1186         if $agent_custid;
1187       $search{'custnum'} = $custnum
1188         if $custnum;
1189       my $cust_main = qsearchs({
1190         'table'     => 'cust_main',
1191         'hashref'   => \%search,
1192         'extra_sql' => $extra_sql,
1193       });
1194       die "can't find customer with" .
1195         ($custnum  ? " custnum $custnum" : '') .
1196         ($agent_custid ? " agent_custid $agent_custid" : '') . "\n"
1197         unless $cust_main;
1198       die "mismatched customer number\n"
1199         if $custnum && ($custnum ne $cust_main->custnum);
1200       $custnum = $cust_main->custnum;
1201     }
1202     $hash{'custnum'} = $custnum;
1203     delete($hash{'agent_custid'});
1204     return %hash;
1205   };
1206
1207   my $opt = { 'table'   => 'cust_credit',
1208               'params'  => [ '_date', 'credbatch' ],
1209               'formats' => { 'simple' =>
1210                                [ 'custnum', 'amount', 'reasonnum', 'invnum', 'agent_custid' ],
1211                            },
1212               'default_csv' => 1,
1213               'format_hash_callbacks' => { 'simple' => $hashcb },
1214               'postinsert_callback' => sub {
1215                 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1216
1217                 if ( $cust_credit->invnum ) {
1218
1219                   my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1220                   my $amount = min( $cust_credit->credited, $cust_bill->owed );
1221     
1222                   my $cust_credit_bill = new FS::cust_credit_bill ( {
1223                     'crednum' => $cust_credit->crednum,
1224                     'invnum'  => $cust_bill->invnum,
1225                     'amount'  => $amount,
1226                   } );
1227                   my $error = $cust_credit_bill->insert;
1228                   return '' unless $error;
1229
1230                 }
1231
1232                 #apply_payments_and_credits ?
1233                 $cust_credit->cust_main->apply_credits;
1234
1235                 return '';
1236
1237               },
1238             };
1239
1240   FS::Record::process_batch_import( $job, $opt, @_ );
1241
1242 }
1243
1244 =back
1245
1246 =head1 BUGS
1247
1248 The delete method.  The replace method.
1249
1250 B<credited> and B<credited_sql> are now called B<unapplied> and
1251 B<unapplied_sql>.  The old method names should start to give warnings.
1252
1253 =head1 SEE ALSO
1254
1255 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1256 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
1257 documentation.
1258
1259 =cut
1260
1261 1;
1262