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