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