RT#7266: aging report "as of" date now limits applied payments
[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::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 =back
90
91 =head1 METHODS
92
93 =over 4
94
95 =item new HASHREF
96
97 Creates a new refund.  To add the refund to the database, see L<"insert">.
98
99 =cut
100
101 sub table { 'cust_refund'; }
102
103 =item insert
104
105 Adds this refund to the database.
106
107 For backwards-compatibility and convenience, if the additional field crednum is
108 defined, an FS::cust_credit_refund record for the full amount of the refund
109 will be created.  Or (this time for convenience and consistancy), if the
110 additional field paynum is defined, an FS::cust_pay_refund record for the full
111 amount of the refund will be created.  In both cases, custnum is optional.
112
113 =cut
114
115 sub insert {
116   my $self = shift;
117
118   local $SIG{HUP} = 'IGNORE';
119   local $SIG{INT} = 'IGNORE';
120   local $SIG{QUIT} = 'IGNORE';
121   local $SIG{TERM} = 'IGNORE';
122   local $SIG{TSTP} = 'IGNORE';
123   local $SIG{PIPE} = 'IGNORE';
124
125   my $oldAutoCommit = $FS::UID::AutoCommit;
126   local $FS::UID::AutoCommit = 0;
127   my $dbh = dbh;
128
129   if ( $self->crednum ) {
130     my $cust_credit = qsearchs('cust_credit', { 'crednum' => $self->crednum } )
131       or do {
132         $dbh->rollback if $oldAutoCommit;
133         return "Unknown cust_credit.crednum: ". $self->crednum;
134       };
135     $self->custnum($cust_credit->custnum);
136   } elsif ( $self->paynum ) {
137     my $cust_pay = qsearchs('cust_pay', { 'paynum' => $self->paynum } )
138       or do {
139         $dbh->rollback if $oldAutoCommit;
140         return "Unknown cust_pay.paynum: ". $self->paynum;
141       };
142     $self->custnum($cust_pay->custnum);
143   }
144
145   my $error = $self->check;
146   return $error if $error;
147
148   $error = $self->SUPER::insert;
149   if ( $error ) {
150     $dbh->rollback if $oldAutoCommit;
151     return $error;
152   }
153
154   if ( $self->crednum ) {
155     my $cust_credit_refund = new FS::cust_credit_refund {
156       'crednum'   => $self->crednum,
157       'refundnum' => $self->refundnum,
158       'amount'    => $self->refund,
159       '_date'     => $self->_date,
160     };
161     $error = $cust_credit_refund->insert;
162     if ( $error ) {
163       $dbh->rollback if $oldAutoCommit;
164       return $error;
165     }
166     #$self->custnum($cust_credit_refund->cust_credit->custnum);
167   } elsif ( $self->paynum ) {
168     my $cust_pay_refund = new FS::cust_pay_refund {
169       'paynum'    => $self->paynum,
170       'refundnum' => $self->refundnum,
171       'amount'    => $self->refund,
172       '_date'     => $self->_date,
173     };
174     $error = $cust_pay_refund->insert;
175     if ( $error ) {
176       $dbh->rollback if $oldAutoCommit;
177       return $error;
178     }
179   }
180
181
182   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
183
184   '';
185
186 }
187
188 =item delete
189
190 Unless the closed flag is set, deletes this refund and all associated
191 applications (see L<FS::cust_credit_refund> and L<FS::cust_pay_refund>).
192
193 =cut
194
195 sub delete {
196   my $self = shift;
197   return "Can't delete closed refund" if $self->closed =~ /^Y/i;
198
199   local $SIG{HUP} = 'IGNORE';
200   local $SIG{INT} = 'IGNORE';
201   local $SIG{QUIT} = 'IGNORE';
202   local $SIG{TERM} = 'IGNORE';
203   local $SIG{TSTP} = 'IGNORE';
204   local $SIG{PIPE} = 'IGNORE';
205
206   my $oldAutoCommit = $FS::UID::AutoCommit;
207   local $FS::UID::AutoCommit = 0;
208   my $dbh = dbh;
209
210   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
211     my $error = $cust_credit_refund->delete;
212     if ( $error ) {
213       $dbh->rollback if $oldAutoCommit;
214       return $error;
215     }
216   }
217
218   foreach my $cust_pay_refund ( $self->cust_pay_refund ) {
219     my $error = $cust_pay_refund->delete;
220     if ( $error ) {
221       $dbh->rollback if $oldAutoCommit;
222       return $error;
223     }
224   }
225
226   my $error = $self->SUPER::delete(@_);
227   if ( $error ) {
228     $dbh->rollback if $oldAutoCommit;
229     return $error;
230   }
231
232   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
233
234   '';
235
236 }
237
238 =item replace OLD_RECORD
239
240 Modifying a refund?  Well, don't say I didn't warn you.
241
242 =cut
243
244 sub replace {
245   my $self = shift;
246   $self->SUPER::replace(@_);
247 }
248
249 =item check
250
251 Checks all fields to make sure this is a valid refund.  If there is an error,
252 returns the error, otherwise returns false.  Called by the insert method.
253
254 =cut
255
256 sub check {
257   my $self = shift;
258
259   $self->otaker(getotaker) unless $self->otaker;
260
261   my $error =
262     $self->ut_numbern('refundnum')
263     || $self->ut_numbern('custnum')
264     || $self->ut_money('refund')
265     || $self->ut_alphan('otaker')
266     || $self->ut_text('reason')
267     || $self->ut_numbern('_date')
268     || $self->ut_textn('paybatch')
269     || $self->ut_enum('closed', [ '', 'Y' ])
270   ;
271   return $error if $error;
272
273   return "refund must be > 0 " if $self->refund <= 0;
274
275   $self->_date(time) unless $self->_date;
276
277   return "unknown cust_main.custnum: ". $self->custnum
278     unless $self->crednum 
279            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
280
281   $error = $self->payinfo_check;
282   return $error if $error;
283
284   $self->SUPER::check;
285 }
286
287 =item cust_credit_refund
288
289 Returns all applications to credits (see L<FS::cust_credit_refund>) for this
290 refund.
291
292 =cut
293
294 sub cust_credit_refund {
295   my $self = shift;
296   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
297   sort { $a->_date <=> $b->_date }
298     qsearch( 'cust_credit_refund', { 'refundnum' => $self->refundnum } )
299   ;
300 }
301
302 =item cust_pay_refund
303
304 Returns all applications to payments (see L<FS::cust_pay_refund>) for this
305 refund.
306
307 =cut
308
309 sub cust_pay_refund {
310   my $self = shift;
311   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
312   sort { $a->_date <=> $b->_date }
313     qsearch( 'cust_pay_refund', { 'refundnum' => $self->refundnum } )
314   ;
315 }
316
317 =item unapplied
318
319 Returns the amount of this refund that is still unapplied; which is
320 amount minus all credit applications (see L<FS::cust_credit_refund>) and
321 payment applications (see L<FS::cust_pay_refund>).
322
323 =cut
324
325 sub unapplied {
326   my $self = shift;
327   my $amount = $self->refund;
328   $amount -= $_->amount foreach ( $self->cust_credit_refund );
329   $amount -= $_->amount foreach ( $self->cust_pay_refund );
330   sprintf("%.2f", $amount );
331 }
332
333 =back
334
335 =head1 CLASS METHODS
336
337 =over 4
338
339 =item unapplied_sql
340
341 Returns an SQL fragment to retreive the unapplied amount.
342
343 =cut 
344
345 sub unapplied_sql {
346   my ($class, $start, $end) = shift;
347   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
348   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
349   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
350   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
351
352   "refund
353     - COALESCE( 
354                 ( SELECT SUM(amount) FROM cust_credit_refund
355                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
356                     $credit_start $credit_end )
357                 ,0
358               )
359     - COALESCE(
360                 ( SELECT SUM(amount) FROM cust_pay_refund
361                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
362                     $pay_start $pay_end )
363                 ,0
364               )
365   ";
366
367 }
368
369 # Used by FS::Upgrade to migrate to a new database.
370 sub _upgrade_data {  # class method
371   my ($class, %opts) = @_;
372   $class->_upgrade_otaker(%opts);
373 }
374
375 =back
376
377 =head1 BUGS
378
379 Delete and replace methods.
380
381 =head1 SEE ALSO
382
383 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
384
385 =cut
386
387 1;
388