71513: Card tokenization [v3 backport]
[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 paycardtype
87
88 Detected credit card type, if appropriate; autodetected.
89
90 =item paymask
91
92 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
93
94 =item paybatch
95
96 text field for tracking card processing
97
98 =item usernum
99
100 order taker (see L<FS::access_user>
101
102 =item closed
103
104 books closed flag, empty or `Y'
105
106 =item gatewaynum, processor, auth, order_number
107
108 Same as for L<FS::cust_pay>, but specifically the result of realtime 
109 authorization of the refund.
110
111 =back
112
113 =head1 METHODS
114
115 =over 4
116
117 =item new HASHREF
118
119 Creates a new refund.  To add the refund to the database, see L<"insert">.
120
121 =cut
122
123 sub table { 'cust_refund'; }
124
125 =item insert
126
127 Adds this refund to the database.
128
129 For backwards-compatibility and convenience, if the additional field crednum is
130 defined, an FS::cust_credit_refund record for the full amount of the refund
131 will be created.  Or (this time for convenience and consistancy), if the
132 additional field paynum is defined, an FS::cust_pay_refund record for the full
133 amount of the refund will be created.  In both cases, custnum is optional.
134
135 =cut
136
137 sub insert {
138   my ($self, %options) = @_;
139
140   local $SIG{HUP} = 'IGNORE';
141   local $SIG{INT} = 'IGNORE';
142   local $SIG{QUIT} = 'IGNORE';
143   local $SIG{TERM} = 'IGNORE';
144   local $SIG{TSTP} = 'IGNORE';
145   local $SIG{PIPE} = 'IGNORE';
146
147   my $oldAutoCommit = $FS::UID::AutoCommit;
148   local $FS::UID::AutoCommit = 0;
149   my $dbh = dbh;
150
151   unless ($self->reasonnum) {
152     local $@;
153     if ( $self->get('reason') ) {
154       my $reason = FS::reason->new_or_existing(
155         reason  => $self->get('reason'),
156         class   => 'F',
157         type    => 'Refund reason',
158       );
159       if ($@) {
160         return "failed to add refund reason: $@";
161       }
162       $self->set('reasonnum', $reason->get('reasonnum'));
163       $self->set('reason', '');
164     }
165   }
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" 
289     if $self->closed =~ /^Y/i && !$FS::payinfo_Mixin::allow_closed_replace;
290   $self->SUPER::replace(@_);
291 }
292
293 =item check
294
295 Checks all fields to make sure this is a valid refund.  If there is an error,
296 returns the error, otherwise returns false.  Called by the insert method.
297
298 =cut
299
300 sub check {
301   my $self = shift;
302
303   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
304
305   my $error =
306     $self->ut_numbern('refundnum')
307     || $self->ut_numbern('custnum')
308     || $self->ut_money('refund')
309     || $self->ut_alphan('otaker')
310     || $self->ut_textn('reason')
311     || $self->ut_numbern('_date')
312     || $self->ut_textn('paybatch')
313     || $self->ut_enum('closed', [ '', 'Y' ])
314     || $self->ut_foreign_keyn('source_paynum', 'cust_pay', 'paynum')
315   ;
316   return $error if $error;
317
318   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
319   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
320   return $error if $error;
321
322   return "refund must be > 0 " if $self->refund <= 0;
323
324   $self->_date(time) unless $self->_date;
325
326   return "unknown cust_main.custnum: ". $self->custnum
327     unless $self->crednum 
328            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
329
330   $error = $self->payinfo_check;
331   return $error if $error;
332
333   $self->SUPER::check;
334 }
335
336 =item cust_credit_refund
337
338 Returns all applications to credits (see L<FS::cust_credit_refund>) for this
339 refund.
340
341 =cut
342
343 sub cust_credit_refund {
344   my $self = shift;
345   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
346   sort { $a->_date <=> $b->_date }
347     qsearch( 'cust_credit_refund', { 'refundnum' => $self->refundnum } )
348   ;
349 }
350
351 =item cust_pay_refund
352
353 Returns all applications to payments (see L<FS::cust_pay_refund>) for this
354 refund.
355
356 =cut
357
358 sub cust_pay_refund {
359   my $self = shift;
360   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
361   sort { $a->_date <=> $b->_date }
362     qsearch( 'cust_pay_refund', { 'refundnum' => $self->refundnum } )
363   ;
364 }
365
366 =item unapplied
367
368 Returns the amount of this refund that is still unapplied; which is
369 amount minus all credit applications (see L<FS::cust_credit_refund>) and
370 payment applications (see L<FS::cust_pay_refund>).
371
372 =cut
373
374 sub unapplied {
375   my $self = shift;
376   my $amount = $self->refund;
377   $amount -= $_->amount foreach ( $self->cust_credit_refund );
378   $amount -= $_->amount foreach ( $self->cust_pay_refund );
379   sprintf("%.2f", $amount );
380 }
381
382 =item send_receipt HASHREF | OPTION => VALUE ...
383
384 Sends a payment receipt for this payment.
385
386 refund_receipt_msgnum must be configured.
387
388 Available options:
389
390 =over 4
391
392 =item cust_main
393
394 Customer (FS::cust_main) object (for efficiency).
395
396 =cut
397
398 =back
399
400 =cut
401
402 sub send_receipt {
403   my $self = shift;
404   my $opt = ref($_[0]) ? shift : { @_ };
405
406   my $cust_main = $opt->{'cust_main'} || $self->cust_main;
407
408   my $conf = new FS::Conf;
409   
410   my $msgnum = $conf->config('refund_receipt_msgnum', $cust_main->agentnum);
411   return "No refund_receipt_msgnum configured" unless $msgnum;
412
413   my $msg_template = qsearchs('msg_template',{ msgnum => $msgnum});
414   return "Could not load template"
415     unless $msg_template;
416
417   my $queue = new FS::queue {
418     'job'     => 'FS::Misc::process_send_email',
419     'custnum' => $cust_main->custnum,
420   };
421   my $error = $queue->insert(
422     FS::msg_template->by_key($msgnum)->prepare(
423       'cust_main'     => $cust_main,
424       'object'        => $self,
425     ),
426     'msgtype' => 'receipt', # override msg_template's default
427   );
428
429   return $error;
430 }
431
432 =back
433
434 =head1 CLASS METHODS
435
436 =over 4
437
438 =item unapplied_sql
439
440 Returns an SQL fragment to retreive the unapplied amount.
441
442 =cut 
443
444 sub unapplied_sql {
445   my ($class, $start, $end) = @_;
446   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
447   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
448   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
449   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
450
451   "refund
452     - COALESCE( 
453                 ( SELECT SUM(amount) FROM cust_credit_refund
454                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
455                     $credit_start $credit_end )
456                 ,0
457               )
458     - COALESCE(
459                 ( SELECT SUM(amount) FROM cust_pay_refund
460                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
461                     $pay_start $pay_end )
462                 ,0
463               )
464   ";
465
466 }
467
468 =item reason
469
470 Returns the text of the associated reason (see L<FS::reason>) for this credit.
471
472 =cut
473
474 sub reason {
475   my ($self, $value, %options) = @_;
476   my $dbh = dbh;
477   my $reason;
478   my $typenum = $options{'reason_type'};
479
480   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
481   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
482
483   if ( defined( $value ) ) {
484     my $hashref = { 'reason' => $value };
485     $hashref->{'reason_type'} = $typenum if $typenum;
486     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
487     my $extra_sql = " AND reason_type.class='F'";
488
489     $reason = qsearchs( { 'table'     => 'reason',
490                           'hashref'   => $hashref,
491                           'addl_from' => $addl_from,
492                           'extra_sql' => $extra_sql,
493                        } );
494
495     if (!$reason && $typenum) {
496       $reason = new FS::reason( { 'reason_type' => $typenum,
497                                   'reason' => $value,
498                                   'disabled' => 'Y',
499                               } );
500       my $error = $reason->insert;
501       if ( $error ) {
502         warn "error inserting reason: $error\n";
503         $reason = undef;
504       }
505     }
506
507     $self->reasonnum($reason ? $reason->reasonnum : '') ;
508     warn "$me reason used in set mode with non-existant reason -- clearing"
509       unless $reason;
510   }
511   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
512
513   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
514
515   ( $reason ? $reason->reason : '' ).
516   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
517 }
518
519 # Used by FS::Upgrade to migrate to a new database.
520 sub _upgrade_data {  # class method
521   my ($class, %opts) = @_;
522   $class->_upgrade_reasonnum(%opts);
523   $class->_upgrade_otaker(%opts);
524
525   local $ignore_empty_reasonnum = 1;
526
527   # don't set paycardtype until 4.x
528   #$class->upgrade_set_cardtype;
529 }
530
531 =back
532
533 =head1 BUGS
534
535 Delete and replace methods.
536
537 =head1 SEE ALSO
538
539 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
540
541 =cut
542
543 1;
544