communigate provisioning phase 2: Domain:Account Defaults:Settings: RulesAllowed...
[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 use Date::Format;
7 use FS::UID qw( dbh getotaker );
8 use FS::Misc qw(send_email);
9 use FS::Record qw( qsearch qsearchs dbdef );
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 use FS::cust_event;
18
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 usernum
80
81 Order taker (see L<FS::access_user>)
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_alphan('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     || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
305   ;
306   return $error if $error;
307
308   return "amount must be > 0 " if $self->amount <= 0;
309
310   return "amount must be greater or equal to amount applied"
311     if $self->unapplied < 0;
312
313   return "Unknown customer"
314     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
315
316   $self->_date(time) unless $self->_date;
317
318   $self->SUPER::check;
319 }
320
321 =item cust_credit_refund
322
323 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
324
325 =cut
326
327 sub cust_credit_refund {
328   my $self = shift;
329   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
330   sort { $a->_date <=> $b->_date }
331     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
332   ;
333 }
334
335 =item cust_credit_bill
336
337 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
338 credit.
339
340 =cut
341
342 sub cust_credit_bill {
343   my $self = shift;
344   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
345   sort { $a->_date <=> $b->_date }
346     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
347   ;
348 }
349
350 =item unapplied
351
352 Returns the amount of this credit that is still unapplied/outstanding; 
353 amount minus all refund applications (see L<FS::cust_credit_refund>) and
354 applications to invoices (see L<FS::cust_credit_bill>).
355
356 =cut
357
358 sub unapplied {
359   my $self = shift;
360   my $amount = $self->amount;
361   $amount -= $_->amount foreach ( $self->cust_credit_refund );
362   $amount -= $_->amount foreach ( $self->cust_credit_bill );
363   sprintf( "%.2f", $amount );
364 }
365
366 =item credited
367
368 Deprecated name for the unapplied method.
369
370 =cut
371
372 sub credited {
373   my $self = shift;
374   #carp "cust_credit->credited deprecated; use ->unapplied";
375   $self->unapplied(@_);
376 }
377
378 =item cust_main
379
380 Returns the customer (see L<FS::cust_main>) for this credit.
381
382 =cut
383
384 sub cust_main {
385   my $self = shift;
386   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
387 }
388
389
390 =item reason
391
392 Returns the text of the associated reason (see L<FS::reason>) for this credit.
393
394 =cut
395
396 sub reason {
397   my ($self, $value, %options) = @_;
398   my $dbh = dbh;
399   my $reason;
400   my $typenum = $options{'reason_type'};
401
402   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
403   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
404
405   if ( defined( $value ) ) {
406     my $hashref = { 'reason' => $value };
407     $hashref->{'reason_type'} = $typenum if $typenum;
408     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
409     my $extra_sql = " AND reason_type.class='R'"; 
410
411     $reason = qsearchs( { 'table'     => 'reason',
412                           'hashref'   => $hashref,
413                           'addl_from' => $addl_from,
414                           'extra_sql' => $extra_sql,
415                        } );
416
417     if (!$reason && $typenum) {
418       $reason = new FS::reason( { 'reason_type' => $typenum,
419                                   'reason' => $value,
420                                   'disabled' => 'Y', 
421                               } );
422       my $error = $reason->insert;
423       if ( $error ) {
424         warn "error inserting reason: $error\n";
425         $reason = undef;
426       }
427     }
428
429     $self->reasonnum($reason ? $reason->reasonnum : '') ;
430     warn "$me reason used in set mode with non-existant reason -- clearing"
431       unless $reason;
432   }
433   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
434
435   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
436
437   ( $reason ? $reason->reason : '' ).
438   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
439 }
440
441 # _upgrade_data
442 #
443 # Used by FS::Upgrade to migrate to a new database.
444
445 sub _upgrade_data {  # class method
446   my ($class, %opts) = @_;
447
448   warn "$me upgrading $class\n" if $DEBUG;
449
450   if (defined dbdef->table($class->table)->column('reason')) {
451
452     warn "$me Checking for unmigrated reasons\n" if $DEBUG;
453
454     my @cust_credits = qsearch({ 'table'     => $class->table,
455                                  'hashref'   => {},
456                                  'extra_sql' => 'WHERE reason IS NOT NULL',
457                               });
458
459     if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
460       warn "$me Found unmigrated reasons\n" if $DEBUG;
461       my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
462       my $reason_type = qsearchs( 'reason_type', $hashref );
463       unless ($reason_type) {
464         $reason_type  = new FS::reason_type( $hashref );
465         my $error   = $reason_type->insert();
466         die "$class had error inserting FS::reason_type into database: $error\n"
467           if $error;
468       }
469
470       $hashref = { 'reason_type' => $reason_type->typenum,
471                    'reason' => '(none)'
472                  };
473       my $noreason = qsearchs( 'reason', $hashref );
474       unless ($noreason) {
475         $hashref->{'disabled'} = 'Y';
476         $noreason = new FS::reason( $hashref );
477         my $error  = $noreason->insert();
478         die "can't insert legacy reason '(none)' into database: $error\n"
479           if $error;
480       }
481
482       foreach my $cust_credit ( @cust_credits ) {
483         my $reason = $cust_credit->getfield('reason');
484         warn "Contemplating reason $reason\n" if $DEBUG > 1;
485         if ($reason =~ /\S/) {
486           $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
487             or die "can't insert legacy reason $reason into database\n";
488         }else{
489           $cust_credit->reasonnum($noreason->reasonnum);
490         }
491
492         $cust_credit->setfield('reason', '');
493         my $error = $cust_credit->replace;
494
495         warn "*** WARNING: error replacing reason in $class ".
496              $cust_credit->crednum. ": $error ***\n"
497           if $error;
498       }
499     }
500
501     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
502
503     foreach ( keys %reasontype_map ) {
504       unless ($conf->config($_)) {       # hmmmm
505 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
506 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
507         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
508         my $reason_type = qsearchs( 'reason_type', $hashref );
509         unless ($reason_type) {
510           $reason_type  = new FS::reason_type( $hashref );
511           my $error   = $reason_type->insert();
512           die "$class had error inserting FS::reason_type into database: $error\n"
513             if $error;
514         }
515         $conf->set($_, $reason_type->typenum);
516       }
517     }
518
519     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
520
521     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
522     my $reason_type = qsearchs( 'reason_type', $hashref );
523     unless ($reason_type) {
524       $reason_type  = new FS::reason_type( $hashref );
525       my $error   = $reason_type->insert();
526       die "$class had error inserting FS::reason_type into database: $error\n"
527         if $error;
528     }
529
530     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
531     foreach my $plan ( @plans ) {
532       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
533         unless ($pkg->option('reason_type', 1) ) { 
534           my $plandata = $pkg->plandata.
535                         "reason_type=". $reason_type->typenum. "\n";
536           $pkg->plandata($plandata);
537           my $error =
538             $pkg->replace( undef,
539                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
540                                           $pkg->pkg_svc
541                                         },
542                            'primary_svc' => $pkg->svcpart,
543                          );
544             die "failed setting reason_type option: $error"
545               if $error;
546         }
547       }
548     }
549   }
550
551   $class->_upgrade_otaker(%opts);
552
553 }
554
555 =back
556
557 =head1 CLASS METHODS
558
559 =over 4
560
561 =item unapplied_sql
562
563 Returns an SQL fragment to retreive the unapplied amount.
564
565 =cut
566
567 sub unapplied_sql {
568   #my $class = shift;
569
570   "amount
571         - COALESCE(
572                     ( SELECT SUM(amount) FROM cust_credit_refund
573                         WHERE cust_credit.crednum = cust_credit_refund.crednum )
574                     ,0
575                   )
576         - COALESCE(
577                     ( SELECT SUM(amount) FROM cust_credit_bill
578                         WHERE cust_credit.crednum = cust_credit_bill.crednum )
579                     ,0
580                   )
581   ";
582
583 }
584
585 =item credited_sql
586
587 Deprecated name for the unapplied_sql method.
588
589 =cut
590
591 sub credited_sql {
592   #my $class = shift;
593
594   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
595
596   #$class->unapplied_sql(@_);
597   unapplied_sql();
598 }
599
600 =back
601
602 =head1 BUGS
603
604 The delete method.  The replace method.
605
606 B<credited> and B<credited_sql> are now called B<unapplied> and
607 B<unapplied_sql>.  The old method names should start to give warnings.
608
609 =head1 SEE ALSO
610
611 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
612 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
613 documentation.
614
615 =cut
616
617 1;
618