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