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