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