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