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