RT#39586 Manual check refunds cannot be unapplied [v3 merge]
[freeside.git] / FS / FS / cust_refund.pm
1 package FS::cust_refund;
2
3 use strict;
4 use base qw( FS::otaker_Mixin FS::payinfo_transaction_Mixin FS::cust_main_Mixin
5              FS::reason_Mixin FS::Record );
6 use vars qw( @encrypted_fields $me $DEBUG $ignore_empty_reasonnum );
7 use Business::CreditCard;
8 use FS::UID qw(getotaker);
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::CurrentUser;
11 use FS::cust_credit;
12 use FS::cust_credit_refund;
13 use FS::cust_pay_refund;
14 use FS::cust_main;
15 use FS::reason_type;
16 use FS::reason;
17
18 $me = '[ FS::cust_refund ]';
19 $DEBUG = 0;
20
21 $ignore_empty_reasonnum = 0;
22
23 @encrypted_fields = ('payinfo');
24 sub nohistory_fields { ('payinfo'); }
25
26 =head1 NAME
27
28 FS::cust_refund - Object method for cust_refund objects
29
30 =head1 SYNOPSIS
31
32   use FS::cust_refund;
33
34   $record = new FS::cust_refund \%hash;
35   $record = new FS::cust_refund { 'column' => 'value' };
36
37   $error = $record->insert;
38
39   $error = $new_record->replace($old_record);
40
41   $error = $record->delete;
42
43   $error = $record->check;
44
45 =head1 DESCRIPTION
46
47 An FS::cust_refund represents a refund: the transfer of money to a customer;
48 equivalent to a negative payment (see L<FS::cust_pay>).  FS::cust_refund
49 inherits from FS::Record.  The following fields are currently supported:
50
51 =over 4
52
53 =item refundnum
54
55 primary key (assigned automatically for new refunds)
56
57 =item custnum
58
59 customer (see L<FS::cust_main>)
60
61 =item refund
62
63 Amount of the refund
64
65 =item reason
66
67 Text stating the reason for the refund ( deprecated )
68
69 =item reasonnum
70
71 Reason (see L<FS::reason>)
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 payby
79
80 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
81
82 =item payinfo
83
84 Payment Information (See L<FS::payinfo_Mixin> for data format)
85
86 =item paymask
87
88 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
89
90 =item paybatch
91
92 text field for tracking card processing
93
94 =item usernum
95
96 order taker (see L<FS::access_user>
97
98 =item closed
99
100 books closed flag, empty or `Y'
101
102 =item gatewaynum, processor, auth, order_number
103
104 Same as for L<FS::cust_pay>, but specifically the result of realtime 
105 authorization of the refund.
106
107 =back
108
109 =head1 METHODS
110
111 =over 4
112
113 =item new HASHREF
114
115 Creates a new refund.  To add the refund to the database, see L<"insert">.
116
117 =cut
118
119 sub table { 'cust_refund'; }
120
121 =item insert
122
123 Adds this refund to the database.
124
125 For backwards-compatibility and convenience, if the additional field crednum is
126 defined, an FS::cust_credit_refund record for the full amount of the refund
127 will be created.  Or (this time for convenience and consistancy), if the
128 additional field paynum is defined, an FS::cust_pay_refund record for the full
129 amount of the refund will be created.  In both cases, custnum is optional.
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   unless ($self->reasonnum) {
148     local $@;
149     if ( $self->get('reason') ) {
150       my $reason = FS::reason->new_or_existing(
151         reason  => $self->get('reason'),
152         class   => 'F',
153         type    => 'Refund reason',
154       );
155       if ($@) {
156         return "failed to add refund reason: $@";
157       }
158       $self->set('reasonnum', $reason->get('reasonnum'));
159       $self->set('reason', '');
160     }
161     $self->set('reasonnum', $reason->reasonnum);
162   }
163
164   if ( $self->crednum ) {
165     my $cust_credit = qsearchs('cust_credit', { 'crednum' => $self->crednum } )
166       or do {
167         $dbh->rollback if $oldAutoCommit;
168         return "Unknown cust_credit.crednum: ". $self->crednum;
169       };
170     $self->custnum($cust_credit->custnum);
171   } elsif ( $self->paynum ) {
172     my $cust_pay = qsearchs('cust_pay', { 'paynum' => $self->paynum } )
173       or do {
174         $dbh->rollback if $oldAutoCommit;
175         return "Unknown cust_pay.paynum: ". $self->paynum;
176       };
177     $self->custnum($cust_pay->custnum);
178   }
179
180   my $error = $self->check;
181   return $error if $error;
182
183   $error = $self->SUPER::insert;
184   if ( $error ) {
185     $dbh->rollback if $oldAutoCommit;
186     return $error;
187   }
188
189   if ( $self->crednum ) {
190     my $cust_credit_refund = new FS::cust_credit_refund {
191       'crednum'   => $self->crednum,
192       'refundnum' => $self->refundnum,
193       'amount'    => $self->refund,
194       '_date'     => $self->_date,
195     };
196     $error = $cust_credit_refund->insert;
197     if ( $error ) {
198       $dbh->rollback if $oldAutoCommit;
199       return $error;
200     }
201     #$self->custnum($cust_credit_refund->cust_credit->custnum);
202   } elsif ( $self->paynum ) {
203     my $cust_pay_refund = new FS::cust_pay_refund {
204       'paynum'    => $self->paynum,
205       'refundnum' => $self->refundnum,
206       'amount'    => $self->refund,
207       '_date'     => $self->_date,
208     };
209     $error = $cust_pay_refund->insert;
210     if ( $error ) {
211       $dbh->rollback if $oldAutoCommit;
212       return $error;
213     }
214   }
215
216
217   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
218
219   '';
220
221 }
222
223 =item delete
224
225 Unless the closed flag is set, deletes this refund and all associated
226 applications (see L<FS::cust_credit_refund> and L<FS::cust_pay_refund>).
227
228 =cut
229
230 sub delete {
231   my $self = shift;
232   return "Can't delete closed refund" if $self->closed =~ /^Y/i;
233
234   local $SIG{HUP} = 'IGNORE';
235   local $SIG{INT} = 'IGNORE';
236   local $SIG{QUIT} = 'IGNORE';
237   local $SIG{TERM} = 'IGNORE';
238   local $SIG{TSTP} = 'IGNORE';
239   local $SIG{PIPE} = 'IGNORE';
240
241   my $oldAutoCommit = $FS::UID::AutoCommit;
242   local $FS::UID::AutoCommit = 0;
243   my $dbh = dbh;
244
245   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
246     my $error = $cust_credit_refund->delete;
247     if ( $error ) {
248       $dbh->rollback if $oldAutoCommit;
249       return $error;
250     }
251   }
252
253   foreach my $cust_pay_refund ( $self->cust_pay_refund ) {
254     my $error = $cust_pay_refund->delete;
255     if ( $error ) {
256       $dbh->rollback if $oldAutoCommit;
257       return $error;
258     }
259   }
260
261   my $error = $self->SUPER::delete(@_);
262   if ( $error ) {
263     $dbh->rollback if $oldAutoCommit;
264     return $error;
265   }
266
267   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
268
269   '';
270
271 }
272
273 =item replace OLD_RECORD
274
275 You can, but probably shouldn't modify refunds... 
276
277 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
278 supplied, replaces this record.  If there is an error, returns the error,
279 otherwise returns false.
280
281 =cut
282
283 sub replace {
284   my $self = shift;
285   return "Can't modify closed refund" if $self->closed =~ /^Y/i;
286   $self->SUPER::replace(@_);
287 }
288
289 =item check
290
291 Checks all fields to make sure this is a valid refund.  If there is an error,
292 returns the error, otherwise returns false.  Called by the insert method.
293
294 =cut
295
296 sub check {
297   my $self = shift;
298
299   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
300
301   my $error =
302     $self->ut_numbern('refundnum')
303     || $self->ut_numbern('custnum')
304     || $self->ut_money('refund')
305     || $self->ut_alphan('otaker')
306     || $self->ut_textn('reason')
307     || $self->ut_numbern('_date')
308     || $self->ut_textn('paybatch')
309     || $self->ut_enum('closed', [ '', 'Y' ])
310     || $self->ut_foreign_keyn('source_paynum', 'cust_pay', 'paynum')
311   ;
312   return $error if $error;
313
314   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
315   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
316   return $error if $error;
317
318   return "refund must be > 0 " if $self->refund <= 0;
319
320   $self->_date(time) unless $self->_date;
321
322   return "unknown cust_main.custnum: ". $self->custnum
323     unless $self->crednum 
324            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
325
326   $error = $self->payinfo_check;
327   return $error if $error;
328
329   $self->SUPER::check;
330 }
331
332 =item cust_credit_refund
333
334 Returns all applications to credits (see L<FS::cust_credit_refund>) for this
335 refund.
336
337 =cut
338
339 sub cust_credit_refund {
340   my $self = shift;
341   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
342   sort { $a->_date <=> $b->_date }
343     qsearch( 'cust_credit_refund', { 'refundnum' => $self->refundnum } )
344   ;
345 }
346
347 =item cust_pay_refund
348
349 Returns all applications to payments (see L<FS::cust_pay_refund>) for this
350 refund.
351
352 =cut
353
354 sub cust_pay_refund {
355   my $self = shift;
356   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
357   sort { $a->_date <=> $b->_date }
358     qsearch( 'cust_pay_refund', { 'refundnum' => $self->refundnum } )
359   ;
360 }
361
362 =item unapplied
363
364 Returns the amount of this refund that is still unapplied; which is
365 amount minus all credit applications (see L<FS::cust_credit_refund>) and
366 payment applications (see L<FS::cust_pay_refund>).
367
368 =cut
369
370 sub unapplied {
371   my $self = shift;
372   my $amount = $self->refund;
373   $amount -= $_->amount foreach ( $self->cust_credit_refund );
374   $amount -= $_->amount foreach ( $self->cust_pay_refund );
375   sprintf("%.2f", $amount );
376 }
377
378 =item send_receipt HASHREF | OPTION => VALUE ...
379
380 Sends a payment receipt for this payment.
381
382 refund_receipt_msgnum must be configured.
383
384 Available options:
385
386 =over 4
387
388 =item cust_main
389
390 Customer (FS::cust_main) object (for efficiency).
391
392 =cut
393
394 =back
395
396 =cut
397
398 sub send_receipt {
399   my $self = shift;
400   my $opt = ref($_[0]) ? shift : { @_ };
401
402   my $cust_main = $opt->{'cust_main'} || $self->cust_main;
403
404   my $conf = new FS::Conf;
405   
406   my $msgnum = $conf->config('refund_receipt_msgnum', $cust_main->agentnum);
407   return "No refund_receipt_msgnum configured" unless $msgnum;
408
409   my $msg_template = qsearchs('msg_template',{ msgnum => $msgnum});
410   return "Could not load template"
411     unless $msg_template;
412
413   my $queue = new FS::queue {
414     'job'     => 'FS::Misc::process_send_email',
415     'custnum' => $cust_main->custnum,
416   };
417   my $error = $queue->insert(
418     FS::msg_template->by_key($msgnum)->prepare(
419       'cust_main'     => $cust_main,
420       'object'        => $self,
421     ),
422     'msgtype' => 'receipt', # override msg_template's default
423   );
424
425   return $error;
426 }
427
428 =back
429
430 =head1 CLASS METHODS
431
432 =over 4
433
434 =item unapplied_sql
435
436 Returns an SQL fragment to retreive the unapplied amount.
437
438 =cut 
439
440 sub unapplied_sql {
441   my ($class, $start, $end) = @_;
442   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
443   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
444   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
445   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
446
447   "refund
448     - COALESCE( 
449                 ( SELECT SUM(amount) FROM cust_credit_refund
450                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
451                     $credit_start $credit_end )
452                 ,0
453               )
454     - COALESCE(
455                 ( SELECT SUM(amount) FROM cust_pay_refund
456                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
457                     $pay_start $pay_end )
458                 ,0
459               )
460   ";
461
462 }
463
464 =item reason
465
466 Returns the text of the associated reason (see L<FS::reason>) for this credit.
467
468 =cut
469
470 sub reason {
471   my ($self, $value, %options) = @_;
472   my $dbh = dbh;
473   my $reason;
474   my $typenum = $options{'reason_type'};
475
476   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
477   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
478
479   if ( defined( $value ) ) {
480     my $hashref = { 'reason' => $value };
481     $hashref->{'reason_type'} = $typenum if $typenum;
482     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
483     my $extra_sql = " AND reason_type.class='F'";
484
485     $reason = qsearchs( { 'table'     => 'reason',
486                           'hashref'   => $hashref,
487                           'addl_from' => $addl_from,
488                           'extra_sql' => $extra_sql,
489                        } );
490
491     if (!$reason && $typenum) {
492       $reason = new FS::reason( { 'reason_type' => $typenum,
493                                   'reason' => $value,
494                                   'disabled' => 'Y',
495                               } );
496       my $error = $reason->insert;
497       if ( $error ) {
498         warn "error inserting reason: $error\n";
499         $reason = undef;
500       }
501     }
502
503     $self->reasonnum($reason ? $reason->reasonnum : '') ;
504     warn "$me reason used in set mode with non-existant reason -- clearing"
505       unless $reason;
506   }
507   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
508
509   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
510
511   ( $reason ? $reason->reason : '' ).
512   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
513 }
514
515 # Used by FS::Upgrade to migrate to a new database.
516 sub _upgrade_data {  # class method
517   my ($class, %opts) = @_;
518   $class->_upgrade_reasonnum(%opts);
519   $class->_upgrade_otaker(%opts);
520 }
521
522 =back
523
524 =head1 BUGS
525
526 Delete and replace methods.
527
528 =head1 SEE ALSO
529
530 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
531
532 =cut
533
534 1;
535