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