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