fix encryption upgrades when a payment is refunded, then deleted. RT#74270, RT#73085
[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" 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 $queue = new FS::queue {
417     'job'     => 'FS::Misc::process_send_email',
418     'custnum' => $cust_main->custnum,
419   };
420   my $error = $queue->insert(
421     FS::msg_template->by_key($msgnum)->prepare(
422       'cust_main'     => $cust_main,
423       'object'        => $self,
424     ),
425     'msgtype' => 'receipt', # override msg_template's default
426   );
427
428   return $error;
429 }
430
431 =back
432
433 =head1 CLASS METHODS
434
435 =over 4
436
437 =item unapplied_sql
438
439 Returns an SQL fragment to retreive the unapplied amount.
440
441 =cut 
442
443 sub unapplied_sql {
444   my ($class, $start, $end) = @_;
445   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
446   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
447   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
448   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
449
450   "refund
451     - COALESCE( 
452                 ( SELECT SUM(amount) FROM cust_credit_refund
453                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
454                     $credit_start $credit_end )
455                 ,0
456               )
457     - COALESCE(
458                 ( SELECT SUM(amount) FROM cust_pay_refund
459                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
460                     $pay_start $pay_end )
461                 ,0
462               )
463   ";
464
465 }
466
467 =item reason
468
469 Returns the text of the associated reason (see L<FS::reason>) for this credit.
470
471 =cut
472
473 sub reason {
474   my ($self, $value, %options) = @_;
475   my $dbh = dbh;
476   my $reason;
477   my $typenum = $options{'reason_type'};
478
479   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
480   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
481
482   if ( defined( $value ) ) {
483     my $hashref = { 'reason' => $value };
484     $hashref->{'reason_type'} = $typenum if $typenum;
485     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
486     my $extra_sql = " AND reason_type.class='F'";
487
488     $reason = qsearchs( { 'table'     => 'reason',
489                           'hashref'   => $hashref,
490                           'addl_from' => $addl_from,
491                           'extra_sql' => $extra_sql,
492                        } );
493
494     if (!$reason && $typenum) {
495       $reason = new FS::reason( { 'reason_type' => $typenum,
496                                   'reason' => $value,
497                                   'disabled' => 'Y',
498                               } );
499       my $error = $reason->insert;
500       if ( $error ) {
501         warn "error inserting reason: $error\n";
502         $reason = undef;
503       }
504     }
505
506     $self->reasonnum($reason ? $reason->reasonnum : '') ;
507     warn "$me reason used in set mode with non-existant reason -- clearing"
508       unless $reason;
509   }
510   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
511
512   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
513
514   ( $reason ? $reason->reason : '' ).
515   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
516 }
517
518 sub _upgrade_schema {
519   #my ($class, %opts) = @_;
520
521   my $sql = 'UPDATE cust_refund SET source_paynum = NULL
522                WHERE source_paynum IS NOT NULL
523                  AND NOT EXISTS ( SELECT 1 FROM cust_pay
524                                     WHERE paynum = cust_refund.source_paynum )
525             ';
526   my $sth = dbh->prepare($sql) or die dbh->errstr;
527   $sth->execute or die $sth->errstr;
528   '';
529 }
530
531 # Used by FS::Upgrade to migrate to a new database.
532 sub _upgrade_data {  # class method
533   my ($class, %opts) = @_;
534   $class->_upgrade_reasonnum(%opts);
535   $class->_upgrade_otaker(%opts);
536
537   local $ignore_empty_reasonnum = 1;
538
539   # don't set paycardtype until 4.x
540   #$class->upgrade_set_cardtype;
541 }
542
543 =back
544
545 =head1 BUGS
546
547 Delete and replace methods.
548
549 =head1 SEE ALSO
550
551 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
552
553 =cut
554
555 1;
556