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