179151009f9546a81d57dda7d807fc816a9128ec
[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     || $self->ut_foreign_keyn('source_paynum', 'cust_pay', 'paynum')
310   ;
311   return $error if $error;
312
313   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
314   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
315   return $error if $error;
316
317   return "refund must be > 0 " if $self->refund <= 0;
318
319   $self->_date(time) unless $self->_date;
320
321   return "unknown cust_main.custnum: ". $self->custnum
322     unless $self->crednum 
323            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
324
325   $error = $self->payinfo_check;
326   return $error if $error;
327
328   $self->SUPER::check;
329 }
330
331 =item cust_credit_refund
332
333 Returns all applications to credits (see L<FS::cust_credit_refund>) for this
334 refund.
335
336 =cut
337
338 sub cust_credit_refund {
339   my $self = shift;
340   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
341   sort { $a->_date <=> $b->_date }
342     qsearch( 'cust_credit_refund', { 'refundnum' => $self->refundnum } )
343   ;
344 }
345
346 =item cust_pay_refund
347
348 Returns all applications to payments (see L<FS::cust_pay_refund>) for this
349 refund.
350
351 =cut
352
353 sub cust_pay_refund {
354   my $self = shift;
355   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
356   sort { $a->_date <=> $b->_date }
357     qsearch( 'cust_pay_refund', { 'refundnum' => $self->refundnum } )
358   ;
359 }
360
361 =item unapplied
362
363 Returns the amount of this refund that is still unapplied; which is
364 amount minus all credit applications (see L<FS::cust_credit_refund>) and
365 payment applications (see L<FS::cust_pay_refund>).
366
367 =cut
368
369 sub unapplied {
370   my $self = shift;
371   my $amount = $self->refund;
372   $amount -= $_->amount foreach ( $self->cust_credit_refund );
373   $amount -= $_->amount foreach ( $self->cust_pay_refund );
374   sprintf("%.2f", $amount );
375 }
376
377 =item send_receipt HASHREF | OPTION => VALUE ...
378
379 Sends a payment receipt for this payment.
380
381 refund_receipt_msgnum must be configured.
382
383 Available options:
384
385 =over 4
386
387 =item cust_main
388
389 Customer (FS::cust_main) object (for efficiency).
390
391 =cut
392
393 =back
394
395 =cut
396
397 sub send_receipt {
398   my $self = shift;
399   my $opt = ref($_[0]) ? shift : { @_ };
400
401   my $cust_main = $opt->{'cust_main'} || $self->cust_main;
402
403   my $conf = new FS::Conf;
404   
405   my $msgnum = $conf->config('refund_receipt_msgnum', $cust_main->agentnum);
406   return "No refund_receipt_msgnum configured" unless $msgnum;
407
408   my $msg_template = qsearchs('msg_template',{ msgnum => $msgnum});
409   return "Could not load template"
410     unless $msg_template;
411
412   my $queue = new FS::queue {
413     'job'     => 'FS::Misc::process_send_email',
414     'custnum' => $cust_main->custnum,
415   };
416   my $error = $queue->insert(
417     FS::msg_template->by_key($msgnum)->prepare(
418       'cust_main'     => $cust_main,
419       'object'        => $self,
420     ),
421     'msgtype' => 'receipt', # override msg_template's default
422   );
423
424   return $error;
425 }
426
427 =back
428
429 =head1 CLASS METHODS
430
431 =over 4
432
433 =item unapplied_sql
434
435 Returns an SQL fragment to retreive the unapplied amount.
436
437 =cut 
438
439 sub unapplied_sql {
440   my ($class, $start, $end) = @_;
441   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
442   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
443   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
444   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
445
446   "refund
447     - COALESCE( 
448                 ( SELECT SUM(amount) FROM cust_credit_refund
449                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
450                     $credit_start $credit_end )
451                 ,0
452               )
453     - COALESCE(
454                 ( SELECT SUM(amount) FROM cust_pay_refund
455                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
456                     $pay_start $pay_end )
457                 ,0
458               )
459   ";
460
461 }
462
463 =item reason
464
465 Returns the text of the associated reason (see L<FS::reason>) for this credit.
466
467 =cut
468
469 sub reason {
470   my ($self, $value, %options) = @_;
471   my $dbh = dbh;
472   my $reason;
473   my $typenum = $options{'reason_type'};
474
475   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
476   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
477
478   if ( defined( $value ) ) {
479     my $hashref = { 'reason' => $value };
480     $hashref->{'reason_type'} = $typenum if $typenum;
481     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
482     my $extra_sql = " AND reason_type.class='F'";
483
484     $reason = qsearchs( { 'table'     => 'reason',
485                           'hashref'   => $hashref,
486                           'addl_from' => $addl_from,
487                           'extra_sql' => $extra_sql,
488                        } );
489
490     if (!$reason && $typenum) {
491       $reason = new FS::reason( { 'reason_type' => $typenum,
492                                   'reason' => $value,
493                                   'disabled' => 'Y',
494                               } );
495       my $error = $reason->insert;
496       if ( $error ) {
497         warn "error inserting reason: $error\n";
498         $reason = undef;
499       }
500     }
501
502     $self->reasonnum($reason ? $reason->reasonnum : '') ;
503     warn "$me reason used in set mode with non-existant reason -- clearing"
504       unless $reason;
505   }
506   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
507
508   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
509
510   ( $reason ? $reason->reason : '' ).
511   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
512 }
513
514 # Used by FS::Upgrade to migrate to a new database.
515 sub _upgrade_data {  # class method
516   my ($class, %opts) = @_;
517   $class->_upgrade_reasonnum(%opts);
518   $class->_upgrade_otaker(%opts);
519 }
520
521 =back
522
523 =head1 BUGS
524
525 Delete and replace methods.
526
527 =head1 SEE ALSO
528
529 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
530
531 =cut
532
533 1;
534