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