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