encryption fixes from huntsberg & jayce
[freeside.git] / FS / FS / cust_pay.pm
1 package FS::cust_pay;
2
3 use strict;
4 use vars qw( @ISA $conf $unsuspendauto $ignore_noapply @encrypted_fields );
5 use Date::Format;
6 use Business::CreditCard;
7 use Text::Template;
8 use FS::Misc qw(send_email);
9 use FS::Record qw( dbh qsearch qsearchs );
10 use FS::cust_main_Mixin;
11 use FS::cust_bill;
12 use FS::cust_bill_pay;
13 use FS::cust_pay_refund;
14 use FS::cust_main;
15 use FS::cust_pay_void;
16
17 @ISA = qw(FS::Record FS::cust_main_Mixin FS::payinfo_Mixin  );
18
19 $ignore_noapply = 0;
20
21 #ask FS::UID to run this stuff for us later
22 FS::UID->install_callback( sub { 
23   $conf = new FS::Conf;
24   $unsuspendauto = $conf->exists('unsuspendauto');
25 } );
26
27 @encrypted_fields = ('payinfo');
28
29 =head1 NAME
30
31 FS::cust_pay - Object methods for cust_pay objects
32
33 =head1 SYNOPSIS
34
35   use FS::cust_pay;
36
37   $record = new FS::cust_pay \%hash;
38   $record = new FS::cust_pay { 'column' => 'value' };
39
40   $error = $record->insert;
41
42   $error = $new_record->replace($old_record);
43
44   $error = $record->delete;
45
46   $error = $record->check;
47
48 =head1 DESCRIPTION
49
50 An FS::cust_pay object represents a payment; the transfer of money from a
51 customer.  FS::cust_pay inherits from FS::Record.  The following fields are
52 currently supported:
53
54 =over 4
55
56 =item paynum - primary key (assigned automatically for new payments)
57
58 =item custnum - customer (see L<FS::cust_main>)
59
60 =item paid - Amount of this payment
61
62 =item _date - 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 - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
66
67 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
68
69 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
70
71 =item paybatch - text field for tracking card processing
72
73 =item closed - books closed flag, empty or `Y'
74
75 =back
76
77 =head1 METHODS
78
79 =over 4 
80
81 =item new HASHREF
82
83 Creates a new payment.  To add the payment to the databse, see L<"insert">.
84
85 =cut
86
87 sub table { 'cust_pay'; }
88 sub cust_linked { $_[0]->cust_main_custnum; } 
89 sub cust_unlinked_msg {
90   my $self = shift;
91   "WARNING: can't find cust_main.custnum ". $self->custnum.
92   ' (cust_pay.paynum '. $self->paynum. ')';
93 }
94
95 =item insert
96
97 Adds this payment to the database.
98
99 For backwards-compatibility and convenience, if the additional field invnum
100 is defined, an FS::cust_bill_pay record for the full amount of the payment
101 will be created.  In this case, custnum is optional.
102
103 =cut
104
105 sub insert {
106   my $self = shift;
107
108   local $SIG{HUP} = 'IGNORE';
109   local $SIG{INT} = 'IGNORE';
110   local $SIG{QUIT} = 'IGNORE';
111   local $SIG{TERM} = 'IGNORE';
112   local $SIG{TSTP} = 'IGNORE';
113   local $SIG{PIPE} = 'IGNORE';
114
115   my $oldAutoCommit = $FS::UID::AutoCommit;
116   local $FS::UID::AutoCommit = 0;
117   my $dbh = dbh;
118
119   if ( $self->invnum ) {
120     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
121       or do {
122         $dbh->rollback if $oldAutoCommit;
123         return "Unknown cust_bill.invnum: ". $self->invnum;
124       };
125     $self->custnum($cust_bill->custnum );
126   }
127
128
129   my $error = $self->check;
130   return $error if $error;
131
132   my $cust_main = $self->cust_main;
133   my $old_balance = $cust_main->balance;
134
135   $error = $self->SUPER::insert;
136   if ( $error ) {
137     $dbh->rollback if $oldAutoCommit;
138     return "error inserting $self: $error";
139   }
140
141   if ( $self->invnum ) {
142     my $cust_bill_pay = new FS::cust_bill_pay {
143       'invnum' => $self->invnum,
144       'paynum' => $self->paynum,
145       'amount' => $self->paid,
146       '_date'  => $self->_date,
147     };
148     $error = $cust_bill_pay->insert;
149     if ( $error ) {
150       if ( $ignore_noapply ) {
151         warn "warning: error inserting $cust_bill_pay: $error ".
152              "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
153       } else {
154         $dbh->rollback if $oldAutoCommit;
155         return "error inserting $cust_bill_pay: $error";
156       }
157     }
158   }
159
160   if ( $self->paybatch =~ /^webui-/ ) {
161     my @cust_pay = qsearch('cust_pay', {
162       'custnum' => $self->custnum,
163       'paybatch' => $self->paybatch,
164     } );
165     if ( scalar(@cust_pay) > 1 ) {
166       $dbh->rollback if $oldAutoCommit;
167       return "a payment with webui token ". $self->paybatch. " already exists";
168     }
169   }
170
171   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
172
173   #false laziness w/ cust_credit::insert
174   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
175     my @errors = $cust_main->unsuspend;
176     #return 
177     # side-fx with nested transactions?  upstack rolls back?
178     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
179          join(' / ', @errors)
180       if @errors;
181   }
182   #eslaf
183
184   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
185
186   #my $cust_main = $self->cust_main;
187   if ( $conf->exists('payment_receipt_email')
188        && grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list
189   ) {
190
191     my $receipt_template = new Text::Template (
192       TYPE   => 'ARRAY',
193       SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
194     ) or do {
195       warn "can't create payment receipt template: $Text::Template::ERROR";
196       return '';
197     };
198
199     my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list;
200
201     my $payby = $self->payby;
202     my $payinfo = $self->payinfo;
203     $payby =~ s/^BILL$/Check/ if $payinfo;
204     $payinfo = $self->payinfo_masked if $payby eq 'CARD' || $payby eq 'CHEK';
205     $payby =~ s/^CHEK$/Electronic check/;
206
207     my $error = send_email(
208       'from'    => $conf->config('invoice_from'), #??? well as good as any
209       'to'      => \@invoicing_list,
210       'subject' => 'Payment receipt',
211       'body'    => [ $receipt_template->fill_in( HASH => {
212                        'date'    => time2str("%a %B %o, %Y", $self->_date),
213                        'name'    => $cust_main->name,
214                        'paynum'  => $self->paynum,
215                        'paid'    => sprintf("%.2f", $self->paid),
216                        'payby'   => ucfirst(lc($payby)),
217                        'payinfo' => $payinfo,
218                        'balance' => $cust_main->balance,
219                    } ) ],
220     );
221     if ( $error ) {
222       warn "can't send payment receipt: $error";
223     }
224
225   }
226
227   '';
228
229 }
230
231 =item void [ REASON ]
232
233 Voids this payment: deletes the payment and all associated applications and
234 adds a record of the voided payment to the FS::cust_pay_void table.
235
236 =cut
237
238 sub void {
239   my $self = shift;
240
241   local $SIG{HUP} = 'IGNORE';
242   local $SIG{INT} = 'IGNORE';
243   local $SIG{QUIT} = 'IGNORE';
244   local $SIG{TERM} = 'IGNORE';
245   local $SIG{TSTP} = 'IGNORE';
246   local $SIG{PIPE} = 'IGNORE';
247
248   my $oldAutoCommit = $FS::UID::AutoCommit;
249   local $FS::UID::AutoCommit = 0;
250   my $dbh = dbh;
251
252   my $cust_pay_void = new FS::cust_pay_void ( {
253     map { $_ => $self->get($_) } $self->fields
254   } );
255   $cust_pay_void->reason(shift) if scalar(@_);
256   my $error = $cust_pay_void->insert;
257   if ( $error ) {
258     $dbh->rollback if $oldAutoCommit;
259     return $error;
260   }
261
262   $error = $self->delete;
263   if ( $error ) {
264     $dbh->rollback if $oldAutoCommit;
265     return $error;
266   }
267
268   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
269
270   '';
271
272 }
273
274 =item delete
275
276 Unless the closed flag is set, deletes this payment and all associated
277 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>).  In most
278 cases, you want to use the void method instead to leave a record of the
279 deleted payment.
280
281 =cut
282
283 # very similar to FS::cust_credit::delete
284 sub delete {
285   my $self = shift;
286   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
287
288   local $SIG{HUP} = 'IGNORE';
289   local $SIG{INT} = 'IGNORE';
290   local $SIG{QUIT} = 'IGNORE';
291   local $SIG{TERM} = 'IGNORE';
292   local $SIG{TSTP} = 'IGNORE';
293   local $SIG{PIPE} = 'IGNORE';
294
295   my $oldAutoCommit = $FS::UID::AutoCommit;
296   local $FS::UID::AutoCommit = 0;
297   my $dbh = dbh;
298
299   foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
300     my $error = $app->delete;
301     if ( $error ) {
302       $dbh->rollback if $oldAutoCommit;
303       return $error;
304     }
305   }
306
307   my $error = $self->SUPER::delete(@_);
308   if ( $error ) {
309     $dbh->rollback if $oldAutoCommit;
310     return $error;
311   }
312
313   if ( $conf->config('deletepayments') ne '' ) {
314
315     my $cust_main = $self->cust_main;
316
317     my $error = send_email(
318       'from'    => $conf->config('invoice_from'), #??? well as good as any
319       'to'      => $conf->config('deletepayments'),
320       'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
321       'body'    => [
322         "This is an automatic message from your Freeside installation\n",
323         "informing you that the following payment has been deleted:\n",
324         "\n",
325         'paynum: '. $self->paynum. "\n",
326         'custnum: '. $self->custnum.
327           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
328         'paid: $'. sprintf("%.2f", $self->paid). "\n",
329         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
330         'payby: '. $self->payby. "\n",
331         'payinfo: '. $self->paymask. "\n",
332         'paybatch: '. $self->paybatch. "\n",
333       ],
334     );
335
336     if ( $error ) {
337       $dbh->rollback if $oldAutoCommit;
338       return "can't send payment deletion notification: $error";
339     }
340
341   }
342
343   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
344
345   '';
346
347 }
348
349 =item replace OLD_RECORD
350
351 You can, but probably shouldn't modify payments...
352
353 =cut
354
355 sub replace {
356   #return "Can't modify payment!"
357   my $self = shift;
358   return "Can't modify closed payment" if $self->closed =~ /^Y/i;
359   $self->SUPER::replace(@_);
360 }
361
362 =item check
363
364 Checks all fields to make sure this is a valid payment.  If there is an error,
365 returns the error, otherwise returns false.  Called by the insert method.
366
367 =cut
368
369 sub check {
370   my $self = shift;
371
372   my $error =
373     $self->ut_numbern('paynum')
374     || $self->ut_numbern('custnum')
375     || $self->ut_money('paid')
376     || $self->ut_numbern('_date')
377     || $self->ut_textn('paybatch')
378     || $self->ut_enum('closed', [ '', 'Y' ])
379     || $self->payinfo_check()
380   ;
381   return $error if $error;
382
383   return "paid must be > 0 " if $self->paid <= 0;
384
385   return "unknown cust_main.custnum: ". $self->custnum
386     unless $self->invnum
387            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
388
389   $self->_date(time) unless $self->_date;
390
391   $self->SUPER::check;
392 }
393
394 =item batch_insert CUST_PAY_OBJECT, ...
395
396 Class method which inserts multiple payments.  Takes a list of FS::cust_pay
397 objects.  Returns a list, each element representing the status of inserting the
398 corresponding payment - empty.  If there is an error inserting any payment, the
399 entire transaction is rolled back, i.e. all payments are inserted or none are.
400
401 For example:
402
403   my @errors = FS::cust_pay->batch_insert(@cust_pay);
404   my $num_errors = scalar(grep $_, @errors);
405   if ( $num_errors == 0 ) {
406     #success; all payments were inserted
407   } else {
408     #failure; no payments were inserted.
409   }
410
411 =cut
412
413 sub batch_insert {
414   my $self = shift; #class method
415
416   local $SIG{HUP} = 'IGNORE';
417   local $SIG{INT} = 'IGNORE';
418   local $SIG{QUIT} = 'IGNORE';
419   local $SIG{TERM} = 'IGNORE';
420   local $SIG{TSTP} = 'IGNORE';
421   local $SIG{PIPE} = 'IGNORE';
422
423   my $oldAutoCommit = $FS::UID::AutoCommit;
424   local $FS::UID::AutoCommit = 0;
425   my $dbh = dbh;
426
427   my $errors = 0;
428   
429   my @errors = map {
430     my $error = $_->insert;
431     if ( $error ) { 
432       $errors++;
433     } else {
434       $_->cust_main->apply_payments;
435     }
436     $error;
437   } @_;
438
439   if ( $errors ) {
440     $dbh->rollback if $oldAutoCommit;
441   } else {
442     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
443   }
444
445   @errors;
446
447 }
448
449 =item cust_bill_pay
450
451 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
452 payment.
453
454 =cut
455
456 sub cust_bill_pay {
457   my $self = shift;
458   sort {    $a->_date  <=> $b->_date
459          || $a->invnum <=> $b->invnum }
460     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
461   ;
462 }
463
464 =item cust_pay_refund
465
466 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
467 payment.
468
469 =cut
470
471 sub cust_pay_refund {
472   my $self = shift;
473   sort { $a->_date <=> $b->_date }
474     qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
475   ;
476 }
477
478
479 =item unapplied
480
481 Returns the amount of this payment that is still unapplied; which is
482 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
483 applications (see L<FS::cust_pay_refund>).
484
485 =cut
486
487 sub unapplied {
488   my $self = shift;
489   my $amount = $self->paid;
490   $amount -= $_->amount foreach ( $self->cust_bill_pay );
491   $amount -= $_->amount foreach ( $self->cust_pay_refund );
492   sprintf("%.2f", $amount );
493 }
494
495 =item unrefunded
496
497 Returns the amount of this payment that has not been refuned; which is
498 paid minus all  refund applications (see L<FS::cust_pay_refund>).
499
500 =cut
501
502 sub unrefunded {
503   my $self = shift;
504   my $amount = $self->paid;
505   $amount -= $_->amount foreach ( $self->cust_pay_refund );
506   sprintf("%.2f", $amount );
507 }
508
509
510 =item cust_main
511
512 Returns the parent customer object (see L<FS::cust_main>).
513
514 =cut
515
516 sub cust_main {
517   my $self = shift;
518   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
519 }
520
521 =item payinfo_masked
522
523 <DEPRICATED> Use $self->paymask
524
525 Returns a "masked" payinfo field appropriate to the payment type.  Masked characters are replaced by 'x'es.  Use this to display publicly accessable account Information.
526
527 Credit Cards - Mask all but the last four characters.
528 Checks - Mask all but last 2 of account number and bank routing number.
529 Others - Do nothing, return the unmasked string.
530
531 =cut
532
533 sub payinfo_masked {
534   my $self = shift;
535   return $self->paymask;
536 }
537
538
539 =back
540
541 =head1 BUGS
542
543 Delete and replace methods.  
544
545 =head1 SEE ALSO
546
547 L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
548 base documentation.
549
550 =cut
551
552 1;
553