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