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