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