ignore misapplied credits when just trying upgrade the otaker, RT#8580
[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 $otaker_upgrade_kludge );
6 use Date::Format;
7 use FS::UID qw( dbh getotaker );
8 use FS::Misc qw(send_email);
9 use FS::Record qw( qsearch qsearchs dbdef );
10 use FS::cust_main;
11 use FS::cust_pkg;
12 use FS::cust_refund;
13 use FS::cust_credit_bill;
14 use FS::part_pkg;
15 use FS::reason_type;
16 use FS::reason;
17 use FS::cust_event;
18
19 $me = '[ FS::cust_credit ]';
20 $DEBUG = 0;
21
22 $otaker_upgrade_kludge = 0;
23
24 #ask FS::UID to run this stuff for us later
25 $FS::UID::callback{'FS::cust_credit'} = sub { 
26
27   $conf = new FS::Conf;
28   $unsuspendauto = $conf->exists('unsuspendauto');
29
30 };
31
32 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
33                         'cancel_credit_type'   => 'Cancellation Credit',
34                         'signup_credit_type'   => 'Self-Service Credit',
35                       );
36
37 =head1 NAME
38
39 FS::cust_credit - Object methods for cust_credit records
40
41 =head1 SYNOPSIS
42
43   use FS::cust_credit;
44
45   $record = new FS::cust_credit \%hash;
46   $record = new FS::cust_credit { 'column' => 'value' };
47
48   $error = $record->insert;
49
50   $error = $new_record->replace($old_record);
51
52   $error = $record->delete;
53
54   $error = $record->check;
55
56 =head1 DESCRIPTION
57
58 An FS::cust_credit object represents a credit; the equivalent of a negative
59 B<cust_bill> record (see L<FS::cust_bill>).  FS::cust_credit inherits from
60 FS::Record.  The following fields are currently supported:
61
62 =over 4
63
64 =item crednum
65
66 Primary key (assigned automatically for new credits)
67
68 =item custnum
69
70 Customer (see L<FS::cust_main>)
71
72 =item amount
73
74 Amount of the credit
75
76 =item _date
77
78 Specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
79 L<Time::Local> and L<Date::Parse> for conversion functions.
80
81 =item usernum
82
83 Order taker (see L<FS::access_user>)
84
85 =item reason
86
87 Text ( deprecated )
88
89 =item reasonnum
90
91 Reason (see L<FS::reason>)
92
93 =item addlinfo
94
95 Text
96
97 =item closed
98
99 Books closed flag, empty or `Y'
100
101 =item pkgnum
102
103 Desired pkgnum when using experimental package balances.
104
105 =back
106
107 =head1 METHODS
108
109 =over 4
110
111 =item new HASHREF
112
113 Creates a new credit.  To add the credit to the database, see L<"insert">.
114
115 =cut
116
117 sub table { 'cust_credit'; }
118 sub cust_linked { $_[0]->cust_main_custnum; } 
119 sub cust_unlinked_msg {
120   my $self = shift;
121   "WARNING: can't find cust_main.custnum ". $self->custnum.
122   ' (cust_credit.crednum '. $self->crednum. ')';
123 }
124
125 =item insert
126
127 Adds this credit to the database ("Posts" the credit).  If there is an error,
128 returns the error, otherwise returns false.
129
130 =cut
131
132 sub insert {
133   my ($self, %options) = @_;
134
135   local $SIG{HUP} = 'IGNORE';
136   local $SIG{INT} = 'IGNORE';
137   local $SIG{QUIT} = 'IGNORE';
138   local $SIG{TERM} = 'IGNORE';
139   local $SIG{TSTP} = 'IGNORE';
140   local $SIG{PIPE} = 'IGNORE';
141
142   my $oldAutoCommit = $FS::UID::AutoCommit;
143   local $FS::UID::AutoCommit = 0;
144   my $dbh = dbh;
145
146   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
147   my $old_balance = $cust_main->balance;
148
149   unless ($self->reasonnum) {
150     my $result = $self->reason( $self->getfield('reason'),
151                                 exists($options{ 'reason_type' })
152                                   ? ('reason_type' => $options{ 'reason_type' })
153                                   : (),
154                               );
155     unless($result) {
156       $dbh->rollback if $oldAutoCommit;
157       return "failed to set reason for $me"; #: ". $dbh->errstr;
158     }
159   }
160
161   $self->setfield('reason', '');
162
163   my $error = $self->SUPER::insert;
164   if ( $error ) {
165     $dbh->rollback if $oldAutoCommit;
166     return "error inserting $self: $error";
167   }
168
169   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
170
171   #false laziness w/ cust_credit::insert
172   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
173     my @errors = $cust_main->unsuspend;
174     #return 
175     # side-fx with nested transactions?  upstack rolls back?
176     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
177          join(' / ', @errors)
178       if @errors;
179   }
180   #eslaf
181
182   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
183
184   '';
185
186 }
187
188 =item delete
189
190 Unless the closed flag is set, deletes this credit and all associated
191 applications (see L<FS::cust_credit_bill>).  In most cases, you want to use
192 the void method instead to leave a record of the deleted credit.
193
194 =cut
195
196 # very similar to FS::cust_pay::delete
197 sub delete {
198   my $self = shift;
199   return "Can't delete closed credit" if $self->closed =~ /^Y/i;
200
201   local $SIG{HUP} = 'IGNORE';
202   local $SIG{INT} = 'IGNORE';
203   local $SIG{QUIT} = 'IGNORE';
204   local $SIG{TERM} = 'IGNORE';
205   local $SIG{TSTP} = 'IGNORE';
206   local $SIG{PIPE} = 'IGNORE';
207
208   my $oldAutoCommit = $FS::UID::AutoCommit;
209   local $FS::UID::AutoCommit = 0;
210   my $dbh = dbh;
211
212   foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
213     my $error = $cust_credit_bill->delete;
214     if ( $error ) {
215       $dbh->rollback if $oldAutoCommit;
216       return $error;
217     }
218   }
219
220   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
221     my $error = $cust_credit_refund->delete;
222     if ( $error ) {
223       $dbh->rollback if $oldAutoCommit;
224       return $error;
225     }
226   }
227
228   my $error = $self->SUPER::delete(@_);
229   if ( $error ) {
230     $dbh->rollback if $oldAutoCommit;
231     return $error;
232   }
233
234   if ( $conf->config('deletecredits') ne '' ) {
235
236     my $cust_main = $self->cust_main;
237
238     my $error = send_email(
239       'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
240                                  #invoice_from??? well as good as any
241       'to'      => $conf->config('deletecredits'),
242       'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
243       'body'    => [
244         "This is an automatic message from your Freeside installation\n",
245         "informing you that the following credit has been deleted:\n",
246         "\n",
247         'crednum: '. $self->crednum. "\n",
248         'custnum: '. $self->custnum.
249           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
250         'amount: $'. sprintf("%.2f", $self->amount). "\n",
251         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
252         'reason: '. $self->reason. "\n",
253       ],
254     );
255
256     if ( $error ) {
257       $dbh->rollback if $oldAutoCommit;
258       return "can't send credit deletion notification: $error";
259     }
260
261   }
262
263   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
264
265   '';
266
267 }
268
269 =item replace OLD_RECORD
270
271 You can, but probably shouldn't modify credits... 
272
273 =cut
274
275 sub replace {
276   #return "Can't modify credit!"
277   my $self = shift;
278   return "Can't modify closed credit" if $self->closed =~ /^Y/i;
279   $self->SUPER::replace(@_);
280 }
281
282 =item check
283
284 Checks all fields to make sure this is a valid credit.  If there is an error,
285 returns the error, otherwise returns false.  Called by the insert and replace
286 methods.
287
288 =cut
289
290 sub check {
291   my $self = shift;
292
293   $self->otaker(getotaker) unless ($self->otaker);
294
295   my $error =
296     $self->ut_numbern('crednum')
297     || $self->ut_number('custnum')
298     || $self->ut_numbern('_date')
299     || $self->ut_money('amount')
300     || $self->ut_alphan('otaker')
301     || $self->ut_textn('reason')
302     || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
303     || $self->ut_textn('addlinfo')
304     || $self->ut_enum('closed', [ '', 'Y' ])
305     || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
306     || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
307   ;
308   return $error if $error;
309
310   return "amount must be > 0 " if $self->amount <= 0;
311
312   return "amount must be greater or equal to amount applied"
313     if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
314
315   return "Unknown customer"
316     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
317
318   $self->_date(time) unless $self->_date;
319
320   $self->SUPER::check;
321 }
322
323 =item cust_credit_refund
324
325 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
326
327 =cut
328
329 sub cust_credit_refund {
330   my $self = shift;
331   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
332   sort { $a->_date <=> $b->_date }
333     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
334   ;
335 }
336
337 =item cust_credit_bill
338
339 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
340 credit.
341
342 =cut
343
344 sub cust_credit_bill {
345   my $self = shift;
346   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
347   sort { $a->_date <=> $b->_date }
348     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
349   ;
350 }
351
352 =item unapplied
353
354 Returns the amount of this credit that is still unapplied/outstanding; 
355 amount minus all refund applications (see L<FS::cust_credit_refund>) and
356 applications to invoices (see L<FS::cust_credit_bill>).
357
358 =cut
359
360 sub unapplied {
361   my $self = shift;
362   my $amount = $self->amount;
363   $amount -= $_->amount foreach ( $self->cust_credit_refund );
364   $amount -= $_->amount foreach ( $self->cust_credit_bill );
365   sprintf( "%.2f", $amount );
366 }
367
368 =item credited
369
370 Deprecated name for the unapplied method.
371
372 =cut
373
374 sub credited {
375   my $self = shift;
376   #carp "cust_credit->credited deprecated; use ->unapplied";
377   $self->unapplied(@_);
378 }
379
380 =item cust_main
381
382 Returns the customer (see L<FS::cust_main>) for this credit.
383
384 =cut
385
386 sub cust_main {
387   my $self = shift;
388   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
389 }
390
391
392 =item reason
393
394 Returns the text of the associated reason (see L<FS::reason>) for this credit.
395
396 =cut
397
398 sub reason {
399   my ($self, $value, %options) = @_;
400   my $dbh = dbh;
401   my $reason;
402   my $typenum = $options{'reason_type'};
403
404   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
405   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
406
407   if ( defined( $value ) ) {
408     my $hashref = { 'reason' => $value };
409     $hashref->{'reason_type'} = $typenum if $typenum;
410     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
411     my $extra_sql = " AND reason_type.class='R'"; 
412
413     $reason = qsearchs( { 'table'     => 'reason',
414                           'hashref'   => $hashref,
415                           'addl_from' => $addl_from,
416                           'extra_sql' => $extra_sql,
417                        } );
418
419     if (!$reason && $typenum) {
420       $reason = new FS::reason( { 'reason_type' => $typenum,
421                                   'reason' => $value,
422                                   'disabled' => 'Y', 
423                               } );
424       my $error = $reason->insert;
425       if ( $error ) {
426         warn "error inserting reason: $error\n";
427         $reason = undef;
428       }
429     }
430
431     $self->reasonnum($reason ? $reason->reasonnum : '') ;
432     warn "$me reason used in set mode with non-existant reason -- clearing"
433       unless $reason;
434   }
435   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
436
437   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
438
439   ( $reason ? $reason->reason : '' ).
440   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
441 }
442
443 # _upgrade_data
444 #
445 # Used by FS::Upgrade to migrate to a new database.
446
447 sub _upgrade_data {  # class method
448   my ($class, %opts) = @_;
449
450   warn "$me upgrading $class\n" if $DEBUG;
451
452   if (defined dbdef->table($class->table)->column('reason')) {
453
454     warn "$me Checking for unmigrated reasons\n" if $DEBUG;
455
456     my @cust_credits = qsearch({ 'table'     => $class->table,
457                                  'hashref'   => {},
458                                  'extra_sql' => 'WHERE reason IS NOT NULL',
459                               });
460
461     if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
462       warn "$me Found unmigrated reasons\n" if $DEBUG;
463       my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
464       my $reason_type = qsearchs( 'reason_type', $hashref );
465       unless ($reason_type) {
466         $reason_type  = new FS::reason_type( $hashref );
467         my $error   = $reason_type->insert();
468         die "$class had error inserting FS::reason_type into database: $error\n"
469           if $error;
470       }
471
472       $hashref = { 'reason_type' => $reason_type->typenum,
473                    'reason' => '(none)'
474                  };
475       my $noreason = qsearchs( 'reason', $hashref );
476       unless ($noreason) {
477         $hashref->{'disabled'} = 'Y';
478         $noreason = new FS::reason( $hashref );
479         my $error  = $noreason->insert();
480         die "can't insert legacy reason '(none)' into database: $error\n"
481           if $error;
482       }
483
484       foreach my $cust_credit ( @cust_credits ) {
485         my $reason = $cust_credit->getfield('reason');
486         warn "Contemplating reason $reason\n" if $DEBUG > 1;
487         if ($reason =~ /\S/) {
488           $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
489             or die "can't insert legacy reason $reason into database\n";
490         }else{
491           $cust_credit->reasonnum($noreason->reasonnum);
492         }
493
494         $cust_credit->setfield('reason', '');
495         my $error = $cust_credit->replace;
496
497         warn "*** WARNING: error replacing reason in $class ".
498              $cust_credit->crednum. ": $error ***\n"
499           if $error;
500       }
501     }
502
503     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
504
505     foreach ( keys %reasontype_map ) {
506       unless ($conf->config($_)) {       # hmmmm
507 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
508 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
509         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
510         my $reason_type = qsearchs( 'reason_type', $hashref );
511         unless ($reason_type) {
512           $reason_type  = new FS::reason_type( $hashref );
513           my $error   = $reason_type->insert();
514           die "$class had error inserting FS::reason_type into database: $error\n"
515             if $error;
516         }
517         $conf->set($_, $reason_type->typenum);
518       }
519     }
520
521     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
522
523     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
524     my $reason_type = qsearchs( 'reason_type', $hashref );
525     unless ($reason_type) {
526       $reason_type  = new FS::reason_type( $hashref );
527       my $error   = $reason_type->insert();
528       die "$class had error inserting FS::reason_type into database: $error\n"
529         if $error;
530     }
531
532     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
533     foreach my $plan ( @plans ) {
534       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
535         unless ($pkg->option('reason_type', 1) ) { 
536           my $plandata = $pkg->plandata.
537                         "reason_type=". $reason_type->typenum. "\n";
538           $pkg->plandata($plandata);
539           my $error =
540             $pkg->replace( undef,
541                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
542                                           $pkg->pkg_svc
543                                         },
544                            'primary_svc' => $pkg->svcpart,
545                          );
546             die "failed setting reason_type option: $error"
547               if $error;
548         }
549       }
550     }
551   }
552
553   local($otaker_upgrade_kludge) = 1;
554   $class->_upgrade_otaker(%opts);
555
556 }
557
558 =back
559
560 =head1 CLASS METHODS
561
562 =over 4
563
564 =item unapplied_sql
565
566 Returns an SQL fragment to retreive the unapplied amount.
567
568 =cut
569
570 sub unapplied_sql {
571   my ($class, $start, $end) = @_;
572
573   my $bill_start   = $start ? "AND cust_credit_bill._date <= $start"   : '';
574   my $bill_end     = $end   ? "AND cust_credit_bill._date > $end"     : '';
575   my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
576   my $refund_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
577
578   "amount
579         - COALESCE(
580                     ( SELECT SUM(amount) FROM cust_credit_refund
581                         WHERE cust_credit.crednum = cust_credit_refund.crednum
582                         $refund_start $refund_end )
583                     ,0
584                   )
585         - COALESCE(
586                     ( SELECT SUM(amount) FROM cust_credit_bill
587                         WHERE cust_credit.crednum = cust_credit_bill.crednum
588                         $bill_start $bill_end )
589                     ,0
590                   )
591   ";
592
593 }
594
595 =item credited_sql
596
597 Deprecated name for the unapplied_sql method.
598
599 =cut
600
601 sub credited_sql {
602   #my $class = shift;
603
604   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
605
606   #$class->unapplied_sql(@_);
607   unapplied_sql();
608 }
609
610 =back
611
612 =head1 BUGS
613
614 The delete method.  The replace method.
615
616 B<credited> and B<credited_sql> are now called B<unapplied> and
617 B<unapplied_sql>.  The old method names should start to give warnings.
618
619 =head1 SEE ALSO
620
621 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
622 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
623 documentation.
624
625 =cut
626
627 1;
628