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