RT#38432: OFM - Send refund receipt
[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::Record qw( qsearch qsearchs dbh dbdef );
9 use FS::CurrentUser;
10 use FS::cust_credit;
11 use FS::cust_credit_refund;
12 use FS::cust_pay_refund;
13 use FS::cust_main;
14 use FS::reason_type;
15 use FS::reason;
16
17 $me = '[ FS::cust_refund ]';
18 $DEBUG = 0;
19
20 $ignore_empty_reasonnum = 0;
21
22 @encrypted_fields = ('payinfo');
23 sub nohistory_fields { ('payinfo'); }
24
25 =head1 NAME
26
27 FS::cust_refund - Object method for cust_refund objects
28
29 =head1 SYNOPSIS
30
31   use FS::cust_refund;
32
33   $record = new FS::cust_refund \%hash;
34   $record = new FS::cust_refund { 'column' => 'value' };
35
36   $error = $record->insert;
37
38   $error = $new_record->replace($old_record);
39
40   $error = $record->delete;
41
42   $error = $record->check;
43
44 =head1 DESCRIPTION
45
46 An FS::cust_refund represents a refund: the transfer of money to a customer;
47 equivalent to a negative payment (see L<FS::cust_pay>).  FS::cust_refund
48 inherits from FS::Record.  The following fields are currently supported:
49
50 =over 4
51
52 =item refundnum
53
54 primary key (assigned automatically for new refunds)
55
56 =item custnum
57
58 customer (see L<FS::cust_main>)
59
60 =item refund
61
62 Amount of the refund
63
64 =item reason
65
66 Text stating the reason for the refund ( deprecated )
67
68 =item reasonnum
69
70 Reason (see L<FS::reason>)
71
72 =item _date
73
74 specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
75 L<Time::Local> and L<Date::Parse> for conversion functions.
76
77 =item payby
78
79 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
80
81 =item payinfo
82
83 Payment Information (See L<FS::payinfo_Mixin> for data format)
84
85 =item paymask
86
87 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
88
89 =item paybatch
90
91 text field for tracking card processing
92
93 =item usernum
94
95 order taker (see L<FS::access_user>
96
97 =item closed
98
99 books closed flag, empty or `Y'
100
101 =item gatewaynum, processor, auth, order_number
102
103 Same as for L<FS::cust_pay>, but specifically the result of realtime 
104 authorization of the refund.
105
106 =back
107
108 =head1 METHODS
109
110 =over 4
111
112 =item new HASHREF
113
114 Creates a new refund.  To add the refund to the database, see L<"insert">.
115
116 =cut
117
118 sub table { 'cust_refund'; }
119
120 =item insert
121
122 Adds this refund to the database.
123
124 For backwards-compatibility and convenience, if the additional field crednum is
125 defined, an FS::cust_credit_refund record for the full amount of the refund
126 will be created.  Or (this time for convenience and consistancy), if the
127 additional field paynum is defined, an FS::cust_pay_refund record for the full
128 amount of the refund will be created.  In both cases, custnum is optional.
129
130 =cut
131
132 sub insert {
133   my ($self, %options) = @_;
134
135   local $SIG{HUP} = 'IGNORE';
136   local $SIG{INT} = 'IGNORE';
137   local $SIG{QUIT} = 'IGNORE';
138   local $SIG{TERM} = 'IGNORE';
139   local $SIG{TSTP} = 'IGNORE';
140   local $SIG{PIPE} = 'IGNORE';
141
142   my $oldAutoCommit = $FS::UID::AutoCommit;
143   local $FS::UID::AutoCommit = 0;
144   my $dbh = dbh;
145
146   unless ($self->reasonnum) {
147     my $result = $self->reason( $self->getfield('reason'),
148                                 exists($options{ 'reason_type' })
149                                   ? ('reason_type' => $options{ 'reason_type' })
150                                   : (),
151                               );
152     unless($result) {
153       $dbh->rollback if $oldAutoCommit;
154       return "failed to set reason for $me"; #: ". $dbh->errstr;
155     }
156   }
157
158   $self->setfield('reason', '');
159
160   if ( $self->crednum ) {
161     my $cust_credit = qsearchs('cust_credit', { 'crednum' => $self->crednum } )
162       or do {
163         $dbh->rollback if $oldAutoCommit;
164         return "Unknown cust_credit.crednum: ". $self->crednum;
165       };
166     $self->custnum($cust_credit->custnum);
167   } elsif ( $self->paynum ) {
168     my $cust_pay = qsearchs('cust_pay', { 'paynum' => $self->paynum } )
169       or do {
170         $dbh->rollback if $oldAutoCommit;
171         return "Unknown cust_pay.paynum: ". $self->paynum;
172       };
173     $self->custnum($cust_pay->custnum);
174   }
175
176   my $error = $self->check;
177   return $error if $error;
178
179   $error = $self->SUPER::insert;
180   if ( $error ) {
181     $dbh->rollback if $oldAutoCommit;
182     return $error;
183   }
184
185   if ( $self->crednum ) {
186     my $cust_credit_refund = new FS::cust_credit_refund {
187       'crednum'   => $self->crednum,
188       'refundnum' => $self->refundnum,
189       'amount'    => $self->refund,
190       '_date'     => $self->_date,
191     };
192     $error = $cust_credit_refund->insert;
193     if ( $error ) {
194       $dbh->rollback if $oldAutoCommit;
195       return $error;
196     }
197     #$self->custnum($cust_credit_refund->cust_credit->custnum);
198   } elsif ( $self->paynum ) {
199     my $cust_pay_refund = new FS::cust_pay_refund {
200       'paynum'    => $self->paynum,
201       'refundnum' => $self->refundnum,
202       'amount'    => $self->refund,
203       '_date'     => $self->_date,
204     };
205     $error = $cust_pay_refund->insert;
206     if ( $error ) {
207       $dbh->rollback if $oldAutoCommit;
208       return $error;
209     }
210   }
211
212
213   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
214
215   '';
216
217 }
218
219 =item delete
220
221 Unless the closed flag is set, deletes this refund and all associated
222 applications (see L<FS::cust_credit_refund> and L<FS::cust_pay_refund>).
223
224 =cut
225
226 sub delete {
227   my $self = shift;
228   return "Can't delete closed refund" if $self->closed =~ /^Y/i;
229
230   local $SIG{HUP} = 'IGNORE';
231   local $SIG{INT} = 'IGNORE';
232   local $SIG{QUIT} = 'IGNORE';
233   local $SIG{TERM} = 'IGNORE';
234   local $SIG{TSTP} = 'IGNORE';
235   local $SIG{PIPE} = 'IGNORE';
236
237   my $oldAutoCommit = $FS::UID::AutoCommit;
238   local $FS::UID::AutoCommit = 0;
239   my $dbh = dbh;
240
241   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
242     my $error = $cust_credit_refund->delete;
243     if ( $error ) {
244       $dbh->rollback if $oldAutoCommit;
245       return $error;
246     }
247   }
248
249   foreach my $cust_pay_refund ( $self->cust_pay_refund ) {
250     my $error = $cust_pay_refund->delete;
251     if ( $error ) {
252       $dbh->rollback if $oldAutoCommit;
253       return $error;
254     }
255   }
256
257   my $error = $self->SUPER::delete(@_);
258   if ( $error ) {
259     $dbh->rollback if $oldAutoCommit;
260     return $error;
261   }
262
263   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
264
265   '';
266
267 }
268
269 =item replace OLD_RECORD
270
271 You can, but probably shouldn't modify refunds... 
272
273 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
274 supplied, replaces this record.  If there is an error, returns the error,
275 otherwise returns false.
276
277 =cut
278
279 sub replace {
280   my $self = shift;
281   return "Can't modify closed refund" if $self->closed =~ /^Y/i;
282   $self->SUPER::replace(@_);
283 }
284
285 =item check
286
287 Checks all fields to make sure this is a valid refund.  If there is an error,
288 returns the error, otherwise returns false.  Called by the insert method.
289
290 =cut
291
292 sub check {
293   my $self = shift;
294
295   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
296
297   my $error =
298     $self->ut_numbern('refundnum')
299     || $self->ut_numbern('custnum')
300     || $self->ut_money('refund')
301     || $self->ut_alphan('otaker')
302     || $self->ut_textn('reason')
303     || $self->ut_numbern('_date')
304     || $self->ut_textn('paybatch')
305     || $self->ut_enum('closed', [ '', 'Y' ])
306   ;
307   return $error if $error;
308
309   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
310   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
311   return $error if $error;
312
313   return "refund must be > 0 " if $self->refund <= 0;
314
315   $self->_date(time) unless $self->_date;
316
317   return "unknown cust_main.custnum: ". $self->custnum
318     unless $self->crednum 
319            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
320
321   $error = $self->payinfo_check;
322   return $error if $error;
323
324   $self->SUPER::check;
325 }
326
327 =item cust_credit_refund
328
329 Returns all applications to credits (see L<FS::cust_credit_refund>) for this
330 refund.
331
332 =cut
333
334 sub cust_credit_refund {
335   my $self = shift;
336   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
337   sort { $a->_date <=> $b->_date }
338     qsearch( 'cust_credit_refund', { 'refundnum' => $self->refundnum } )
339   ;
340 }
341
342 =item cust_pay_refund
343
344 Returns all applications to payments (see L<FS::cust_pay_refund>) for this
345 refund.
346
347 =cut
348
349 sub cust_pay_refund {
350   my $self = shift;
351   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
352   sort { $a->_date <=> $b->_date }
353     qsearch( 'cust_pay_refund', { 'refundnum' => $self->refundnum } )
354   ;
355 }
356
357 =item unapplied
358
359 Returns the amount of this refund that is still unapplied; which is
360 amount minus all credit applications (see L<FS::cust_credit_refund>) and
361 payment applications (see L<FS::cust_pay_refund>).
362
363 =cut
364
365 sub unapplied {
366   my $self = shift;
367   my $amount = $self->refund;
368   $amount -= $_->amount foreach ( $self->cust_credit_refund );
369   $amount -= $_->amount foreach ( $self->cust_pay_refund );
370   sprintf("%.2f", $amount );
371 }
372
373 =item send_receipt HASHREF | OPTION => VALUE ...
374
375 Sends a payment receipt for this payment.
376
377 refund_receipt_msgnum must be configured.
378
379 Available options:
380
381 =over 4
382
383 =item cust_main
384
385 Customer (FS::cust_main) object (for efficiency).
386
387 =cut
388
389 =back
390
391 =cut
392
393 sub send_receipt {
394   my $self = shift;
395   my $opt = ref($_[0]) ? shift : { @_ };
396
397   my $cust_main = $opt->{'cust_main'} || $self->cust_main;
398
399   my $conf = new FS::Conf;
400   
401   my $msgnum = $conf->config('refund_receipt_msgnum', $cust_main->agentnum);
402   return "No refund_receipt_msgnum configured" unless $msgnum;
403
404   my $msg_template = qsearchs('msg_template',{ msgnum => $msgnum});
405   return "Could not load template"
406     unless $msg_template;
407
408   my $cust_msg = $msg_template->prepare(
409     'cust_main'     => $cust_main,
410     'object'        => $self,
411     'msgtype'       => 'receipt',
412   );
413   return 'Error preparing message' unless $cust_msg;
414   my $error = $cust_msg->insert;
415   return $error if $error;
416
417   my $queue = new FS::queue {
418     'job'     => 'FS::cust_msg::process_send',
419     'custnum' => $cust_main->custnum,
420   };
421   $error = $queue->insert( $cust_msg->custmsgnum );
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 # Used by FS::Upgrade to migrate to a new database.
463 sub _upgrade_data {  # class method
464   my ($class, %opts) = @_;
465   $class->_upgrade_reasonnum(%opts);
466   $class->_upgrade_otaker(%opts);
467 }
468
469 =back
470
471 =head1 BUGS
472
473 Delete and replace methods.
474
475 =head1 SEE ALSO
476
477 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
478
479 =cut
480
481 1;
482