097ed2df332af7bec72bf17efa0ead6b95dd50ed
[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 $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 =back
374
375 =head1 CLASS METHODS
376
377 =over 4
378
379 =item unapplied_sql
380
381 Returns an SQL fragment to retreive the unapplied amount.
382
383 =cut 
384
385 sub unapplied_sql {
386   my ($class, $start, $end) = @_;
387   my $credit_start = $start ? "AND cust_credit_refund._date <= $start" : '';
388   my $credit_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
389   my $pay_start    = $start ? "AND cust_pay_refund._date <= $start"    : '';
390   my $pay_end      = $end   ? "AND cust_pay_refund._date > $end"      : '';
391
392   "refund
393     - COALESCE( 
394                 ( SELECT SUM(amount) FROM cust_credit_refund
395                     WHERE cust_refund.refundnum = cust_credit_refund.refundnum
396                     $credit_start $credit_end )
397                 ,0
398               )
399     - COALESCE(
400                 ( SELECT SUM(amount) FROM cust_pay_refund
401                     WHERE cust_refund.refundnum = cust_pay_refund.refundnum
402                     $pay_start $pay_end )
403                 ,0
404               )
405   ";
406
407 }
408
409 =item reason
410
411 Returns the text of the associated reason (see L<FS::reason>) for this credit.
412
413 =cut
414
415 sub reason {
416   my ($self, $value, %options) = @_;
417   my $dbh = dbh;
418   my $reason;
419   my $typenum = $options{'reason_type'};
420
421   my $oldAutoCommit = $FS::UID::AutoCommit;  # this should already be in
422   local $FS::UID::AutoCommit = 0;            # a transaction if it matters
423
424   if ( defined( $value ) ) {
425     my $hashref = { 'reason' => $value };
426     $hashref->{'reason_type'} = $typenum if $typenum;
427     my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
428     my $extra_sql = " AND reason_type.class='F'";
429
430     $reason = qsearchs( { 'table'     => 'reason',
431                           'hashref'   => $hashref,
432                           'addl_from' => $addl_from,
433                           'extra_sql' => $extra_sql,
434                        } );
435
436     if (!$reason && $typenum) {
437       $reason = new FS::reason( { 'reason_type' => $typenum,
438                                   'reason' => $value,
439                                   'disabled' => 'Y',
440                               } );
441       my $error = $reason->insert;
442       if ( $error ) {
443         warn "error inserting reason: $error\n";
444         $reason = undef;
445       }
446     }
447
448     $self->reasonnum($reason ? $reason->reasonnum : '') ;
449     warn "$me reason used in set mode with non-existant reason -- clearing"
450       unless $reason;
451   }
452   $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
453
454   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
455
456   ( $reason ? $reason->reason : '' ).
457   ( $self->addlinfo ? ' '.$self->addlinfo : '' );
458 }
459
460 # Used by FS::Upgrade to migrate to a new database.
461 sub _upgrade_data {  # class method
462   my ($class, %opts) = @_;
463
464   warn "$me upgrading $class\n" if $DEBUG;
465
466   if (defined dbdef->table($class->table)->column('reason')) {
467
468     warn "$me Checking for unmigrated reasons\n" if $DEBUG;
469
470     my @cust_refunds = qsearch({ 'table'     => $class->table,
471                                  'hashref'   => {},
472                                  'extra_sql' => 'WHERE reason IS NOT NULL',
473                               });
474
475     if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_refunds)) {
476       warn "$me Found unmigrated reasons\n" if $DEBUG;
477       my $hashref = { 'class' => 'F', 'type' => 'Legacy' };
478       my $reason_type = qsearchs( 'reason_type', $hashref );
479       unless ($reason_type) {
480         $reason_type  = new FS::reason_type( $hashref );
481         my $error   = $reason_type->insert();
482         die "$class had error inserting FS::reason_type into database: $error\n"
483           if $error;
484       }
485
486       $hashref = { 'reason_type' => $reason_type->typenum,
487                    'reason' => '(none)'
488                  };
489       my $noreason = qsearchs( 'reason', $hashref );
490       unless ($noreason) {
491         $hashref->{'disabled'} = 'Y';
492         $noreason = new FS::reason( $hashref );
493         my $error  = $noreason->insert();
494         die "can't insert legacy reason '(none)' into database: $error\n"
495           if $error;
496       }
497
498       foreach my $cust_refund ( @cust_refunds ) {
499         my $reason = $cust_refund->getfield('reason');
500         warn "Contemplating reason $reason\n" if $DEBUG > 1;
501         if ($reason =~ /\S/) {
502           $cust_refund->reason($reason, 'reason_type' => $reason_type->typenum)
503             or die "can't insert legacy reason $reason into database\n";
504         }else{
505           $cust_refund->reasonnum($noreason->reasonnum);
506         }
507
508         $cust_refund->setfield('reason', '');
509         my $error = $cust_refund->replace;
510
511         warn "*** WARNING: error replacing reason in $class ".
512              $cust_refund->refundnum. ": $error ***\n"
513           if $error;
514       }
515     }
516   }
517   $class->_upgrade_otaker(%opts);
518 }
519
520 =back
521
522 =head1 BUGS
523
524 Delete and replace methods.
525
526 =head1 SEE ALSO
527
528 L<FS::Record>, L<FS::cust_credit>, schema.html from the base documentation.
529
530 =cut
531
532 1;
533