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