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