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