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