fix recording of BOP refunds, fallout from #39398
[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   }
162
163   if ( $self->crednum ) {
164     my $cust_credit = qsearchs('cust_credit', { 'crednum' => $self->crednum } )
165       or do {
166         $dbh->rollback if $oldAutoCommit;
167         return "Unknown cust_credit.crednum: ". $self->crednum;
168       };
169     $self->custnum($cust_credit->custnum);
170   } elsif ( $self->paynum ) {
171     my $cust_pay = qsearchs('cust_pay', { 'paynum' => $self->paynum } )
172       or do {
173         $dbh->rollback if $oldAutoCommit;
174         return "Unknown cust_pay.paynum: ". $self->paynum;
175       };
176     $self->custnum($cust_pay->custnum);
177   }
178
179   my $error = $self->check;
180   return $error if $error;
181
182   $error = $self->SUPER::insert;
183   if ( $error ) {
184     $dbh->rollback if $oldAutoCommit;
185     return $error;
186   }
187
188   if ( $self->crednum ) {
189     my $cust_credit_refund = new FS::cust_credit_refund {
190       'crednum'   => $self->crednum,
191       'refundnum' => $self->refundnum,
192       'amount'    => $self->refund,
193       '_date'     => $self->_date,
194     };
195     $error = $cust_credit_refund->insert;
196     if ( $error ) {
197       $dbh->rollback if $oldAutoCommit;
198       return $error;
199     }
200     #$self->custnum($cust_credit_refund->cust_credit->custnum);
201   } elsif ( $self->paynum ) {
202     my $cust_pay_refund = new FS::cust_pay_refund {
203       'paynum'    => $self->paynum,
204       'refundnum' => $self->refundnum,
205       'amount'    => $self->refund,
206       '_date'     => $self->_date,
207     };
208     $error = $cust_pay_refund->insert;
209     if ( $error ) {
210       $dbh->rollback if $oldAutoCommit;
211       return $error;
212     }
213   }
214
215
216   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
217
218   '';
219
220 }
221
222 =item delete
223
224 Unless the closed flag is set, deletes this refund and all associated
225 applications (see L<FS::cust_credit_refund> and L<FS::cust_pay_refund>).
226
227 =cut
228
229 sub delete {
230   my $self = shift;
231   return "Can't delete closed refund" if $self->closed =~ /^Y/i;
232
233   local $SIG{HUP} = 'IGNORE';
234   local $SIG{INT} = 'IGNORE';
235   local $SIG{QUIT} = 'IGNORE';
236   local $SIG{TERM} = 'IGNORE';
237   local $SIG{TSTP} = 'IGNORE';
238   local $SIG{PIPE} = 'IGNORE';
239
240   my $oldAutoCommit = $FS::UID::AutoCommit;
241   local $FS::UID::AutoCommit = 0;
242   my $dbh = dbh;
243
244   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
245     my $error = $cust_credit_refund->delete;
246     if ( $error ) {
247       $dbh->rollback if $oldAutoCommit;
248       return $error;
249     }
250   }
251
252   foreach my $cust_pay_refund ( $self->cust_pay_refund ) {
253     my $error = $cust_pay_refund->delete;
254     if ( $error ) {
255       $dbh->rollback if $oldAutoCommit;
256       return $error;
257     }
258   }
259
260   my $error = $self->SUPER::delete(@_);
261   if ( $error ) {
262     $dbh->rollback if $oldAutoCommit;
263     return $error;
264   }
265
266   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
267
268   '';
269
270 }
271
272 =item replace OLD_RECORD
273
274 You can, but probably shouldn't modify refunds... 
275
276 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
277 supplied, replaces this record.  If there is an error, returns the error,
278 otherwise returns false.
279
280 =cut
281
282 sub replace {
283   my $self = shift;
284   return "Can't modify closed refund" if $self->closed =~ /^Y/i;
285   $self->SUPER::replace(@_);
286 }
287
288 =item check
289
290 Checks all fields to make sure this is a valid refund.  If there is an error,
291 returns the error, otherwise returns false.  Called by the insert method.
292
293 =cut
294
295 sub check {
296   my $self = shift;
297
298   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
299
300   my $error =
301     $self->ut_numbern('refundnum')
302     || $self->ut_numbern('custnum')
303     || $self->ut_money('refund')
304     || $self->ut_alphan('otaker')
305     || $self->ut_textn('reason')
306     || $self->ut_numbern('_date')
307     || $self->ut_textn('paybatch')
308     || $self->ut_enum('closed', [ '', 'Y' ])
309   ;
310   return $error if $error;
311
312   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
313   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
314   return $error if $error;
315
316   return "refund must be > 0 " if $self->refund <= 0;
317
318   $self->_date(time) unless $self->_date;
319
320   return "unknown cust_main.custnum: ". $self->custnum
321     unless $self->crednum 
322            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
323
324   $error = $self->payinfo_check;
325   return $error if $error;
326
327   $self->SUPER::check;
328 }
329
330 =item cust_credit_refund
331
332 Returns all applications to credits (see L<FS::cust_credit_refund>) for this
333 refund.
334
335 =cut
336
337 sub cust_credit_refund {
338   my $self = shift;
339   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
340   sort { $a->_date <=> $b->_date }
341     qsearch( 'cust_credit_refund', { 'refundnum' => $self->refundnum } )
342   ;
343 }
344
345 =item cust_pay_refund
346
347 Returns all applications to payments (see L<FS::cust_pay_refund>) for this
348 refund.
349
350 =cut
351
352 sub cust_pay_refund {
353   my $self = shift;
354   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
355   sort { $a->_date <=> $b->_date }
356     qsearch( 'cust_pay_refund', { 'refundnum' => $self->refundnum } )
357   ;
358 }
359
360 =item unapplied
361
362 Returns the amount of this refund that is still unapplied; which is
363 amount minus all credit applications (see L<FS::cust_credit_refund>) and
364 payment applications (see L<FS::cust_pay_refund>).
365
366 =cut
367
368 sub unapplied {
369   my $self = shift;
370   my $amount = $self->refund;
371   $amount -= $_->amount foreach ( $self->cust_credit_refund );
372   $amount -= $_->amount foreach ( $self->cust_pay_refund );
373   sprintf("%.2f", $amount );
374 }
375
376 =item send_receipt HASHREF | OPTION => VALUE ...
377
378 Sends a payment receipt for this payment.
379
380 refund_receipt_msgnum must be configured.
381
382 Available options:
383
384 =over 4
385
386 =item cust_main
387
388 Customer (FS::cust_main) object (for efficiency).
389
390 =cut
391
392 =back
393
394 =cut
395
396 sub send_receipt {
397   my $self = shift;
398   my $opt = ref($_[0]) ? shift : { @_ };
399
400   my $cust_main = $opt->{'cust_main'} || $self->cust_main;
401
402   my $conf = new FS::Conf;
403   
404   my $msgnum = $conf->config('refund_receipt_msgnum', $cust_main->agentnum);
405   return "No refund_receipt_msgnum configured" unless $msgnum;
406
407   my $msg_template = qsearchs('msg_template',{ msgnum => $msgnum});
408   return "Could not load template"
409     unless $msg_template;
410
411   my $queue = new FS::queue {
412     'job'     => 'FS::Misc::process_send_email',
413     'custnum' => $cust_main->custnum,
414   };
415   my $error = $queue->insert(
416     FS::msg_template->by_key($msgnum)->prepare(
417       'cust_main'     => $cust_main,
418       'object'        => $self,
419     ),
420     'msgtype' => 'receipt', # override msg_template's default
421   );
422
423   return $error;
424 }
425
426 =back
427
428 =head1 CLASS METHODS
429
430 =over 4
431
432 =item unapplied_sql
433
434 Returns an SQL fragment to retreive the unapplied amount.
435
436 =cut 
437
438 sub unapplied_sql {
439   my ($class, $start, $end) = @_;
440   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
441   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
442   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
443   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
444
445   "refund
446     - COALESCE( 
447                 ( SELECT SUM(amount) FROM cust_credit_refund
448                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
449                     $credit_start $credit_end )
450                 ,0
451               )
452     - COALESCE(
453                 ( SELECT SUM(amount) FROM cust_pay_refund
454                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
455                     $pay_start $pay_end )
456                 ,0
457               )
458   ";
459
460 }
461
462 =item reason
463
464 Returns the text of the associated reason (see L<FS::reason>) for this credit.
465
466 =cut
467
468 sub reason {
469   my ($self, $value, %options) = @_;
470   my $dbh = dbh;
471   my $reason;
472   my $typenum = $options{'reason_type'};
473
474   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
475   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
476
477   if ( defined( $value ) ) {
478     my $hashref = { 'reason' => $value };
479     $hashref->{'reason_type'} = $typenum if $typenum;
480     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
481     my $extra_sql = " AND reason_type.class='F'";
482
483     $reason = qsearchs( { 'table'     => 'reason',
484                           'hashref'   => $hashref,
485                           'addl_from' => $addl_from,
486                           'extra_sql' => $extra_sql,
487                        } );
488
489     if (!$reason && $typenum) {
490       $reason = new FS::reason( { 'reason_type' => $typenum,
491                                   'reason' => $value,
492                                   'disabled' => 'Y',
493                               } );
494       my $error = $reason->insert;
495       if ( $error ) {
496         warn "error inserting reason: $error\n";
497         $reason = undef;
498       }
499     }
500
501     $self->reasonnum($reason ? $reason->reasonnum : '') ;
502     warn "$me reason used in set mode with non-existant reason -- clearing"
503       unless $reason;
504   }
505   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
506
507   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
508
509   ( $reason ? $reason->reason : '' ).
510   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
511 }
512
513 # Used by FS::Upgrade to migrate to a new database.
514 sub _upgrade_data {  # class method
515   my ($class, %opts) = @_;
516   $class->_upgrade_reasonnum(%opts);
517   $class->_upgrade_otaker(%opts);
518 }
519
520 =back
521
522 =head1 BUGS
523
524 Delete and replace methods.
525
526 =head1 SEE ALSO
527
528 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
529
530 =cut
531
532 1;
533