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