have the UI use full country names, and state names outside the US...
[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 Deletes this payment and all associated applications (see L<FS::cust_bill_pay>),
276 unless the closed flag is set.  In most cases, you want to use the void
277 method instead to leave a record of the deleted payment.
278
279 =cut
280
281 sub delete {
282   my $self = shift;
283   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
284
285   local $SIG{HUP} = 'IGNORE';
286   local $SIG{INT} = 'IGNORE';
287   local $SIG{QUIT} = 'IGNORE';
288   local $SIG{TERM} = 'IGNORE';
289   local $SIG{TSTP} = 'IGNORE';
290   local $SIG{PIPE} = 'IGNORE';
291
292   my $oldAutoCommit = $FS::UID::AutoCommit;
293   local $FS::UID::AutoCommit = 0;
294   my $dbh = dbh;
295
296   foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
297     my $error = $app->delete;
298     if ( $error ) {
299       $dbh->rollback if $oldAutoCommit;
300       return $error;
301     }
302   }
303
304   my $error = $self->SUPER::delete(@_);
305   if ( $error ) {
306     $dbh->rollback if $oldAutoCommit;
307     return $error;
308   }
309
310   if ( $conf->config('deletepayments') ne '' ) {
311
312     my $cust_main = $self->cust_main;
313
314     my $error = send_email(
315       'from'    => $conf->config('invoice_from'), #??? well as good as any
316       'to'      => $conf->config('deletepayments'),
317       'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
318       'body'    => [
319         "This is an automatic message from your Freeside installation\n",
320         "informing you that the following payment has been deleted:\n",
321         "\n",
322         'paynum: '. $self->paynum. "\n",
323         'custnum: '. $self->custnum.
324           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
325         'paid: $'. sprintf("%.2f", $self->paid). "\n",
326         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
327         'payby: '. $self->payby. "\n",
328         'payinfo: '. $self->payinfo. "\n",
329         'paybatch: '. $self->paybatch. "\n",
330       ],
331     );
332
333     if ( $error ) {
334       $dbh->rollback if $oldAutoCommit;
335       return "can't send payment deletion notification: $error";
336     }
337
338   }
339
340   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
341
342   '';
343
344 }
345
346 =item replace OLD_RECORD
347
348 You probably shouldn't modify payments...
349
350 =item check
351
352 Checks all fields to make sure this is a valid payment.  If there is an error,
353 returns the error, otherwise returns false.  Called by the insert method.
354
355 =cut
356
357 sub check {
358   my $self = shift;
359
360   my $error =
361     $self->ut_numbern('paynum')
362     || $self->ut_numbern('custnum')
363     || $self->ut_money('paid')
364     || $self->ut_numbern('_date')
365     || $self->ut_textn('paybatch')
366     || $self->ut_enum('closed', [ '', 'Y' ])
367   ;
368   return $error if $error;
369
370   return "paid must be > 0 " if $self->paid <= 0;
371
372   return "unknown cust_main.custnum: ". $self->custnum
373     unless $self->invnum
374            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
375
376   $self->_date(time) unless $self->_date;
377
378   $self->payby =~ /^(CARD|CHEK|LECB|BILL|COMP|PREP|CASH|WEST|MCRD)$/
379     or return "Illegal payby";
380   $self->payby($1);
381
382   #false laziness with cust_refund::check
383   if ( $self->payby eq 'CARD' ) {
384     my $payinfo = $self->payinfo;
385     $payinfo =~ s/\D//g;
386     $self->payinfo($payinfo);
387     if ( $self->payinfo ) {
388       $self->payinfo =~ /^(\d{13,16})$/
389         or return "Illegal (mistyped?) credit card number (payinfo)";
390       $self->payinfo($1);
391       validate($self->payinfo) or return "Illegal credit card number";
392       return "Unknown card type" if cardtype($self->payinfo) eq "Unknown";
393     } else {
394       $self->payinfo('N/A');
395     }
396
397   } else {
398     $error = $self->ut_textn('payinfo');
399     return $error if $error;
400   }
401
402   $self->SUPER::check;
403 }
404
405 =item batch_insert CUST_PAY_OBJECT, ...
406
407 Class method which inserts multiple payments.  Takes a list of FS::cust_pay
408 objects.  Returns a list, each element representing the status of inserting the
409 corresponding payment - empty.  If there is an error inserting any payment, the
410 entire transaction is rolled back, i.e. all payments are inserted or none are.
411
412 For example:
413
414   my @errors = FS::cust_pay->batch_insert(@cust_pay);
415   my $num_errors = scalar(grep $_, @errors);
416   if ( $num_errors == 0 ) {
417     #success; all payments were inserted
418   } else {
419     #failure; no payments were inserted.
420   }
421
422 =cut
423
424 sub batch_insert {
425   my $self = shift; #class method
426
427   local $SIG{HUP} = 'IGNORE';
428   local $SIG{INT} = 'IGNORE';
429   local $SIG{QUIT} = 'IGNORE';
430   local $SIG{TERM} = 'IGNORE';
431   local $SIG{TSTP} = 'IGNORE';
432   local $SIG{PIPE} = 'IGNORE';
433
434   my $oldAutoCommit = $FS::UID::AutoCommit;
435   local $FS::UID::AutoCommit = 0;
436   my $dbh = dbh;
437
438   my $errors = 0;
439   
440   my @errors = map {
441     my $error = $_->insert;
442     if ( $error ) { 
443       $errors++;
444     } else {
445       $_->cust_main->apply_payments;
446     }
447     $error;
448   } @_;
449
450   if ( $errors ) {
451     $dbh->rollback if $oldAutoCommit;
452   } else {
453     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
454   }
455
456   @errors;
457
458 }
459
460 =item cust_bill_pay
461
462 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
463 payment.
464
465 =cut
466
467 sub cust_bill_pay {
468   my $self = shift;
469   sort {    $a->_date  <=> $b->_date
470          || $a->invnum <=> $b->invnum }
471     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
472   ;
473 }
474
475 =item cust_pay_refund
476
477 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
478 payment.
479
480 =cut
481
482 sub cust_pay_refund {
483   my $self = shift;
484   sort { $a->_date <=> $b->_date }
485     qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
486   ;
487 }
488
489
490 =item unapplied
491
492 Returns the amount of this payment that is still unapplied; which is
493 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
494 applications (see L<FS::cust_pay_refund>).
495
496 =cut
497
498 sub unapplied {
499   my $self = shift;
500   my $amount = $self->paid;
501   $amount -= $_->amount foreach ( $self->cust_bill_pay );
502   $amount -= $_->amount foreach ( $self->cust_pay_refund );
503   sprintf("%.2f", $amount );
504 }
505
506 =item unrefunded
507
508 Returns the amount of this payment that has not been refuned; which is
509 paid minus all  refund applications (see L<FS::cust_pay_refund>).
510
511 =cut
512
513 sub unrefunded {
514   my $self = shift;
515   my $amount = $self->paid;
516   $amount -= $_->amount foreach ( $self->cust_pay_refund );
517   sprintf("%.2f", $amount );
518 }
519
520
521 =item cust_main
522
523 Returns the parent customer object (see L<FS::cust_main>).
524
525 =cut
526
527 sub cust_main {
528   my $self = shift;
529   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
530 }
531
532 =item payinfo_masked
533
534 Returns a "masked" payinfo field with all but the last four characters replaced
535 by 'x'es.  Useful for displaying credit cards.
536
537 =cut
538
539 sub payinfo_masked {
540   my $self = shift;
541   #some false laziness w/cust_main::paymask
542   if ( $self->payby eq 'CARD' ) {
543     my $payinfo = $self->payinfo;
544     'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
545   } elsif ( $self->payby eq 'CHEK' ) {
546     my( $account, $aba ) = split('@', $self->payinfo );
547     'x'x(length($account)-2). substr($account,(length($account)-2)). "@". $aba;
548   } else {
549     $self->payinfo;
550   }
551 }
552
553 =back
554
555 =head1 BUGS
556
557 Delete and replace methods.  payinfo_masked false laziness with cust_main.pm
558 and cust_refund.pm
559
560 =head1 SEE ALSO
561
562 L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
563 base documentation.
564
565 =cut
566
567 1;
568