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