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