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