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