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