option to credit unused time on suspension as part of suspend reason, #31702
[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 $unsuspendauto $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::Misc qw(send_email);
13 use FS::Record qw( qsearch qsearchs dbdef );
14 use FS::CurrentUser;
15 use FS::cust_pkg;
16 use FS::cust_refund;
17 use FS::cust_credit_bill;
18 use FS::part_pkg;
19 use FS::reason_type;
20 use FS::reason;
21 use FS::cust_event;
22 use FS::agent;
23 use FS::sales;
24 use FS::cust_credit_void;
25 use FS::cust_bill_pkg;
26 use FS::upgrade_journal;
27
28 $me = '[ FS::cust_credit ]';
29 $DEBUG = 0;
30
31 $otaker_upgrade_kludge = 0;
32 $ignore_empty_reasonnum = 0;
33
34 #ask FS::UID to run this stuff for us later
35 $FS::UID::callback{'FS::cust_credit'} = sub { 
36
37   $conf = new FS::Conf;
38   $unsuspendauto = $conf->exists('unsuspendauto');
39
40 };
41
42 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
43                         'cancel_credit_type'   => 'Cancellation Credit',
44                         'signup_credit_type'   => 'Self-Service Credit',
45                       );
46
47 =head1 NAME
48
49 FS::cust_credit - Object methods for cust_credit records
50
51 =head1 SYNOPSIS
52
53   use FS::cust_credit;
54
55   $record = new FS::cust_credit \%hash;
56   $record = new FS::cust_credit { 'column' => 'value' };
57
58   $error = $record->insert;
59
60   $error = $new_record->replace($old_record);
61
62   $error = $record->delete;
63
64   $error = $record->check;
65
66 =head1 DESCRIPTION
67
68 An FS::cust_credit object represents a credit; the equivalent of a negative
69 B<cust_bill> record (see L<FS::cust_bill>).  FS::cust_credit inherits from
70 FS::Record.  The following fields are currently supported:
71
72 =over 4
73
74 =item crednum
75
76 Primary key (assigned automatically for new credits)
77
78 =item custnum
79
80 Customer (see L<FS::cust_main>)
81
82 =item amount
83
84 Amount of the credit
85
86 =item _date
87
88 Specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
89 L<Time::Local> and L<Date::Parse> for conversion functions.
90
91 =item usernum
92
93 Order taker (see L<FS::access_user>)
94
95 =item reason
96
97 Text ( deprecated )
98
99 =item reasonnum
100
101 Reason (see L<FS::reason>)
102
103 =item addlinfo
104
105 Text
106
107 =item closed
108
109 Books closed flag, empty or `Y'
110
111 =item pkgnum
112
113 Desired pkgnum when using experimental package balances.
114
115 =back
116
117 =head1 METHODS
118
119 =over 4
120
121 =item new HASHREF
122
123 Creates a new credit.  To add the credit to the database, see L<"insert">.
124
125 =cut
126
127 sub table { 'cust_credit'; }
128 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
129 sub cust_unlinked_msg {
130   my $self = shift;
131   "WARNING: can't find cust_main.custnum ". $self->custnum.
132   ' (cust_credit.crednum '. $self->crednum. ')';
133 }
134
135 =item insert
136
137 Adds this credit to the database ("Posts" the credit).  If there is an error,
138 returns the error, otherwise returns false.
139
140 =cut
141
142 sub insert {
143   my ($self, %options) = @_;
144
145   local $SIG{HUP} = 'IGNORE';
146   local $SIG{INT} = 'IGNORE';
147   local $SIG{QUIT} = 'IGNORE';
148   local $SIG{TERM} = 'IGNORE';
149   local $SIG{TSTP} = 'IGNORE';
150   local $SIG{PIPE} = 'IGNORE';
151
152   my $oldAutoCommit = $FS::UID::AutoCommit;
153   local $FS::UID::AutoCommit = 0;
154   my $dbh = dbh;
155
156   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
157   my $old_balance = $cust_main->balance;
158
159   unless ($self->reasonnum) {
160     my $result = $self->reason( $self->getfield('reason'),
161                                 exists($options{ 'reason_type' })
162                                   ? ('reason_type' => $options{ 'reason_type' })
163                                   : (),
164                               );
165     unless($result) {
166       $dbh->rollback if $oldAutoCommit;
167       return "failed to set reason for $me"; #: ". $dbh->errstr;
168     }
169   }
170
171   $self->setfield('reason', '');
172
173   my $error = $self->SUPER::insert;
174   if ( $error ) {
175     $dbh->rollback if $oldAutoCommit;
176     return "error inserting $self: $error";
177   }
178
179   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
180
181   #false laziness w/ cust_pay::insert
182   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
183     my @errors = $cust_main->unsuspend;
184     #return 
185     # side-fx with nested transactions?  upstack rolls back?
186     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
187          join(' / ', @errors)
188       if @errors;
189   }
190   #eslaf
191
192   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
193
194   '';
195
196 }
197
198 =item delete
199
200 Unless the closed flag is set, deletes this credit and all associated
201 applications (see L<FS::cust_credit_bill>).  In most cases, you want to use
202 the void method instead to leave a record of the deleted credit.
203
204 =cut
205
206 # very similar to FS::cust_pay::delete
207 sub delete {
208   my $self = shift;
209   my %opt = @_;
210
211   return "Can't delete closed credit" if $self->closed =~ /^Y/i;
212
213   local $SIG{HUP} = 'IGNORE';
214   local $SIG{INT} = 'IGNORE';
215   local $SIG{QUIT} = 'IGNORE';
216   local $SIG{TERM} = 'IGNORE';
217   local $SIG{TSTP} = 'IGNORE';
218   local $SIG{PIPE} = 'IGNORE';
219
220   my $oldAutoCommit = $FS::UID::AutoCommit;
221   local $FS::UID::AutoCommit = 0;
222   my $dbh = dbh;
223
224   foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
225     my $error = $cust_credit_bill->delete;
226     if ( $error ) {
227       $dbh->rollback if $oldAutoCommit;
228       return $error;
229     }
230   }
231
232   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
233     my $error = $cust_credit_refund->delete;
234     if ( $error ) {
235       $dbh->rollback if $oldAutoCommit;
236       return $error;
237     }
238   }
239
240   my $error = $self->SUPER::delete(@_);
241   if ( $error ) {
242     $dbh->rollback if $oldAutoCommit;
243     return $error;
244   }
245
246   if ( !$opt{void} and $conf->config('deletecredits') ne '' ) {
247
248     my $cust_main = $self->cust_main;
249
250     my $error = send_email(
251       'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
252                                  #invoice_from??? well as good as any
253       'to'      => $conf->config('deletecredits'),
254       'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
255       'body'    => [
256         "This is an automatic message from your Freeside installation\n",
257         "informing you that the following credit has been deleted:\n",
258         "\n",
259         'crednum: '. $self->crednum. "\n",
260         'custnum: '. $self->custnum.
261           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
262         'amount: $'. sprintf("%.2f", $self->amount). "\n",
263         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
264         'reason: '. $self->reason. "\n",
265       ],
266     );
267
268     if ( $error ) {
269       $dbh->rollback if $oldAutoCommit;
270       return "can't send credit deletion notification: $error";
271     }
272
273   }
274
275   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
276
277   '';
278
279 }
280
281 =item replace [ OLD_RECORD ]
282
283 You can, but probably shouldn't modify credits... 
284
285 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
286 supplied, replaces this record.  If there is an error, returns the error,
287 otherwise returns false.
288
289 =cut
290
291 sub replace {
292   my $self = shift;
293   return "Can't modify closed credit" if $self->closed =~ /^Y/i;
294   $self->SUPER::replace(@_);
295 }
296
297 =item check
298
299 Checks all fields to make sure this is a valid credit.  If there is an error,
300 returns the error, otherwise returns false.  Called by the insert and replace
301 methods.
302
303 =cut
304
305 sub check {
306   my $self = shift;
307
308   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
309
310   my $error =
311     $self->ut_numbern('crednum')
312     || $self->ut_number('custnum')
313     || $self->ut_numbern('_date')
314     || $self->ut_money('amount')
315     || $self->ut_alphan('otaker')
316     || $self->ut_textn('reason')
317     || $self->ut_textn('addlinfo')
318     || $self->ut_enum('closed', [ '', 'Y' ])
319     || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
320     || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
321     || $self->ut_foreign_keyn('commission_agentnum',  'agent', 'agentnum')
322     || $self->ut_foreign_keyn('commission_salesnum',  'sales', 'salesnum')
323     || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
324   ;
325   return $error if $error;
326
327   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
328   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
329   return $error if $error;
330
331   return "amount must be > 0 " if $self->amount <= 0;
332
333   return "amount must be greater or equal to amount applied"
334     if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
335
336   return "Unknown customer"
337     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
338
339   $self->_date(time) unless $self->_date;
340
341   $self->SUPER::check;
342 }
343
344 =item void [ REASON ]
345
346 Voids this credit: deletes the credit and all associated applications and 
347 adds a record of the voided credit to the cust_credit_void table.
348
349 =cut
350
351 # yes, false laziness with cust_pay and cust_bill
352 # but frankly I don't have time to fix it now
353
354 sub void {
355   my $self = shift;
356   my $reason = shift;
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_reason', $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(void => 1); # suppress deletecredits warning
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->exists('enable_taxproducts') ) {
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 credit_lineitems
670
671 Example:
672
673   my $error = FS::cust_credit->credit_lineitems(
674
675     #the lineitems to credit
676     'billpkgnums'       => \@billpkgnums,
677     'setuprecurs'       => \@setuprecurs,
678     'amounts'           => \@amounts,
679     'apply'             => 1, #0 leaves the credit unapplied
680
681     #the credit
682     map { $_ => scalar($cgi->param($_)) }
683       #fields('cust_credit')  
684       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
685
686   );
687
688 =cut
689
690 #maybe i should just be an insert with extra args instead of a class method
691 sub credit_lineitems {
692   my( $class, %arg ) = @_;
693   my $curuser = $FS::CurrentUser::CurrentUser;
694
695   #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
696
697   my $cust_main = qsearchs({
698     'table'     => 'cust_main',
699     'hashref'   => { 'custnum' => $arg{custnum} },
700     'extra_sql' => ' AND '. $curuser->agentnums_sql,
701   }) or return 'unknown customer';
702
703
704   local $SIG{HUP} = 'IGNORE';
705   local $SIG{INT} = 'IGNORE';
706   local $SIG{QUIT} = 'IGNORE';
707   local $SIG{TERM} = 'IGNORE';
708   local $SIG{TSTP} = 'IGNORE';
709   local $SIG{PIPE} = 'IGNORE';
710
711   my $oldAutoCommit = $FS::UID::AutoCommit;
712   local $FS::UID::AutoCommit = 0;
713   my $dbh = dbh;
714
715   #my @cust_bill_pkg = qsearch({
716   #  'select'    => 'cust_bill_pkg.*',
717   #  'table'     => 'cust_bill_pkg',
718   #  'addl_from' => ' LEFT JOIN cust_bill USING (invnum)  '.
719   #                 ' LEFT JOIN cust_main USING (custnum) ',
720   #  'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
721   #                     join( ',', @{$arg{billpkgnums}} ). ')',
722   #  'order_by'  => 'ORDER BY invnum ASC, billpkgnum ASC',
723   #});
724
725   my $error = '';
726
727   my $cust_credit = new FS::cust_credit ( {
728     map { $_ => $arg{$_} }
729       #fields('cust_credit')
730       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
731   } );
732   $error = $cust_credit->insert;
733   if ( $error ) {
734     $dbh->rollback if $oldAutoCommit;
735     return "Error inserting credit: $error";
736   }
737
738   unless ( $arg{'apply'} ) {
739     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
740     return '';
741   }
742
743   #my $subtotal = 0;
744   # keys in all of these are invoice numbers
745   my %cust_credit_bill = ();
746   my %cust_bill_pkg = ();
747   my %cust_credit_bill_pkg = ();
748   my %taxlisthash = ();
749   my %unapplied_payments = (); #invoice numbers, and then billpaynums
750   foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
751     my $setuprecur = shift @{$arg{setuprecurs}};
752     my $amount = shift @{$arg{amounts}};
753
754     my $cust_bill_pkg = qsearchs({
755       'table'     => 'cust_bill_pkg',
756       'hashref'   => { 'billpkgnum' => $billpkgnum },
757       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
758       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
759     }) or die "unknown billpkgnum $billpkgnum";
760   
761     my $invnum = $cust_bill_pkg->invnum;
762
763     if ( $setuprecur eq 'setup' ) {
764       $cust_bill_pkg->setup($amount);
765       $cust_bill_pkg->recur(0);
766       $cust_bill_pkg->unitrecur(0);
767       $cust_bill_pkg->type('');
768     } else {
769       $setuprecur = 'recur'; #in case its a usage classnum?
770       $cust_bill_pkg->recur($amount);
771       $cust_bill_pkg->setup(0);
772       $cust_bill_pkg->unitsetup(0);
773     }
774
775     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
776
777     #unapply any payments applied to this line item (other credits too?)
778     foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
779       $error = $cust_bill_pay_pkg->delete;
780       if ( $error ) {
781         $dbh->rollback if $oldAutoCommit;
782         return "Error unapplying payment: $error";
783       }
784       $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
785         += $cust_bill_pay_pkg->amount;
786     }
787
788     #$subtotal += $amount;
789     $cust_credit_bill{$invnum} += $amount;
790     push @{ $cust_credit_bill_pkg{$invnum} },
791       new FS::cust_credit_bill_pkg {
792         'billpkgnum' => $cust_bill_pkg->billpkgnum,
793         'amount'     => sprintf('%.2f',$amount),
794         'setuprecur' => $setuprecur,
795         'sdate'      => $cust_bill_pkg->sdate,
796         'edate'      => $cust_bill_pkg->edate,
797       };
798
799     # recalculate taxes with new amounts
800     $taxlisthash{$invnum} ||= {};
801     if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
802       $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
803     } # otherwise the item itself is a tax, and assume the caller knows
804       # what they're doing
805   }
806
807   ###
808   # now loop through %cust_credit_bill and insert those
809   ###
810
811   # (hack to prevent cust_credit_bill_pkg insertion)
812   local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
813
814   foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
815
816     my $arrayref_or_error =
817       $cust_main->calculate_taxes(
818         $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
819         $taxlisthash{$invnum},   # list of tax-item bindings
820         $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
821       );
822
823     unless ( ref( $arrayref_or_error ) ) {
824       $dbh->rollback if $oldAutoCommit;
825       return "Error calculating taxes: $arrayref_or_error";
826     }
827     
828     my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
829
830     #taxes
831     foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
832       my $billpkgnum = $cust_bill_pkg->billpkgnum;
833       my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
834       # gather up existing tax links (we need their billpkgtaxlocationnums)
835       my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
836                       qsearch('cust_bill_pkg_tax_rate_location', \%hash);
837
838       foreach ( @tax_links ) {
839         $tax_links{$_->billpkgnum} ||= {};
840         $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
841       }
842     }
843
844     foreach my $taxline ( @$arrayref_or_error ) {
845
846       my $amount = $taxline->setup;
847
848       # find equivalent tax line item on the existing invoice
849       my $tax_item = qsearchs('cust_bill_pkg', {
850           'invnum'    => $invnum,
851           'pkgnum'    => 0,
852           'itemdesc'  => $taxline->desc,
853       });
854       if (!$tax_item) {
855         # or should we just exit if this happens?
856         $cust_credit->set('amount', 
857           sprintf('%.2f', $cust_credit->get('amount') - $amount)
858         );
859         my $error = $cust_credit->replace;
860         if ( $error ) {
861           $dbh->rollback if $oldAutoCommit;
862           return "error correcting credit for missing tax line: $error";
863         }
864       }
865
866       # but in the new era, we no longer have the problem of uniquely
867       # identifying the tax_Xlocation record.  The billpkgnums of the 
868       # tax and the taxed item are known.
869       foreach my $new_loc
870         ( @{ $taxline->get('cust_bill_pkg_tax_location') },
871           @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
872       {
873         # the existing tax_Xlocation object
874         my $old_loc =
875           $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
876
877         next if !$old_loc; # apply the leftover amount nonspecifically
878
879         #support partial credits: use $amount if smaller
880         # (so just distribute to the first location?   perhaps should
881         #  do so evenly...)
882         my $loc_amount = min( $amount, $new_loc->amount);
883
884         $amount -= $loc_amount;
885
886         $cust_credit_bill{$invnum} += $loc_amount;
887         push @{ $cust_credit_bill_pkg{$invnum} },
888           new FS::cust_credit_bill_pkg {
889             'billpkgnum'                => $tax_item->billpkgnum,
890             'amount'                    => $loc_amount,
891             'setuprecur'                => 'setup',
892             'billpkgtaxlocationnum'     => $old_loc->billpkgtaxlocationnum,
893             'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
894           };
895
896       } #foreach my $new_loc
897
898       # we still have to deal with the possibility that the tax links don't
899       # cover the whole amount of tax because of an incomplete upgrade...
900       if ($amount > 0.005) {
901         $cust_credit_bill{$invnum} += $amount;
902         push @{ $cust_credit_bill_pkg{$invnum} },
903           new FS::cust_credit_bill_pkg {
904             'billpkgnum' => $tax_item->billpkgnum,
905             'amount'     => sprintf('%.2f', $amount),
906             'setuprecur' => 'setup',
907           };
908
909       } # if $amount > 0
910
911       #unapply any payments applied to the tax
912       foreach my $cust_bill_pay_pkg
913         ( $tax_item->cust_bill_pay_pkg('setup') )
914       {
915         $error = $cust_bill_pay_pkg->delete;
916         if ( $error ) {
917           $dbh->rollback if $oldAutoCommit;
918           return "Error unapplying payment: $error";
919         }
920         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
921           += $cust_bill_pay_pkg->amount;
922       }
923     } #foreach $taxline
924
925     # if we unapplied any payments from line items, also unapply that 
926     # amount from the invoice
927     foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
928       my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
929         or die "broken payment application $billpaynum";
930       my @subapps = $cust_bill_pay->lineitem_applications;
931       $error = $cust_bill_pay->delete; # can't replace
932
933       my $new_cust_bill_pay = FS::cust_bill_pay->new({
934           $cust_bill_pay->hash,
935           billpaynum => '',
936           amount => sprintf('%.2f', 
937               $cust_bill_pay->amount 
938               - $unapplied_payments{$invnum}{$billpaynum}),
939       });
940
941       if ( $new_cust_bill_pay->amount > 0 ) {
942         $error ||= $new_cust_bill_pay->insert;
943         # Also reapply it to everything it was applied to before.
944         # Note that we've already deleted cust_bill_pay_pkg records for the
945         # items we're crediting, so they aren't on this list.
946         foreach my $cust_bill_pay_pkg (@subapps) {
947           $cust_bill_pay_pkg->billpaypkgnum('');
948           $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
949           $error ||= $cust_bill_pay_pkg->insert;
950         }
951       }
952       if ( $error ) {
953         $dbh->rollback if $oldAutoCommit;
954         return "Error unapplying payment: $error";
955       }
956     }
957     #insert cust_credit_bill
958
959     my $cust_credit_bill = new FS::cust_credit_bill {
960       'crednum' => $cust_credit->crednum,
961       'invnum'  => $invnum,
962       'amount'  => sprintf('%.2f', $cust_credit_bill{$invnum}),
963     };
964     $error = $cust_credit_bill->insert;
965     if ( $error ) {
966       $dbh->rollback if $oldAutoCommit;
967       return "Error applying credit of $cust_credit_bill{$invnum} ".
968              " to invoice $invnum: $error";
969     }
970
971     #and then insert cust_credit_bill_pkg for each cust_bill_pkg
972     foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
973       $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
974       $error = $cust_credit_bill_pkg->insert;
975       if ( $error ) {
976         $dbh->rollback if $oldAutoCommit;
977         return "Error applying credit to line item: $error";
978       }
979     }
980
981   }
982
983   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
984   '';
985
986 }
987
988 =back
989
990 =head1 SUBROUTINES
991
992 =over 4
993
994 =item process_batch_import
995
996 =cut
997
998 use List::Util qw( min );
999 use FS::cust_bill;
1000 use FS::cust_credit_bill;
1001 sub process_batch_import {
1002   my $job = shift;
1003
1004   my $opt = { 'table'   => 'cust_credit',
1005               'params'  => [ '_date', 'credbatch' ],
1006               'formats' => { 'simple' =>
1007                                [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1008                            },
1009               'default_csv' => 1,
1010               'postinsert_callback' => sub {
1011                 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1012
1013                 if ( $cust_credit->invnum ) {
1014
1015                   my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1016                   my $amount = min( $cust_credit->credited, $cust_bill->owed );
1017     
1018                   my $cust_credit_bill = new FS::cust_credit_bill ( {
1019                     'crednum' => $cust_credit->crednum,
1020                     'invnum'  => $cust_bill->invnum,
1021                     'amount'  => $amount,
1022                   } );
1023                   my $error = $cust_credit_bill->insert;
1024                   return '' unless $error;
1025
1026                 }
1027
1028                 #apply_payments_and_credits ?
1029                 $cust_credit->cust_main->apply_credits;
1030
1031                 return '';
1032
1033               },
1034             };
1035
1036   FS::Record::process_batch_import( $job, $opt, @_ );
1037
1038 }
1039
1040 =back
1041
1042 =head1 BUGS
1043
1044 The delete method.  The replace method.
1045
1046 B<credited> and B<credited_sql> are now called B<unapplied> and
1047 B<unapplied_sql>.  The old method names should start to give warnings.
1048
1049 =head1 SEE ALSO
1050
1051 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1052 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
1053 documentation.
1054
1055 =cut
1056
1057 1;
1058