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