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