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