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