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