This commit was generated by cvs2svn to compensate for changes in r4407,
[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
126   my $error = $self->check;
127   return $error if $error;
128
129   my $cust_main = $self->cust_main;
130   my $old_balance = $cust_main->balance;
131
132   $error = $self->SUPER::insert;
133   if ( $error ) {
134     $dbh->rollback if $oldAutoCommit;
135     return "error inserting $self: $error";
136   }
137
138   if ( $self->invnum ) {
139     my $cust_bill_pay = new FS::cust_bill_pay {
140       'invnum' => $self->invnum,
141       'paynum' => $self->paynum,
142       'amount' => $self->paid,
143       '_date'  => $self->_date,
144     };
145     $error = $cust_bill_pay->insert;
146     if ( $error ) {
147       if ( $ignore_noapply ) {
148         warn "warning: error inserting $cust_bill_pay: $error ".
149              "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
150       } else {
151         $dbh->rollback if $oldAutoCommit;
152         return "error inserting $cust_bill_pay: $error";
153       }
154     }
155   }
156
157   if ( $self->paybatch =~ /^webui-/ ) {
158     my @cust_pay = qsearch('cust_pay', {
159       'custnum' => $self->custnum,
160       'paybatch' => $self->paybatch,
161     } );
162     if ( scalar(@cust_pay) > 1 ) {
163       $dbh->rollback if $oldAutoCommit;
164       return "a payment with webui token ". $self->paybatch. " already exists";
165     }
166   }
167
168   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
169
170   #false laziness w/ cust_credit::insert
171   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
172     my @errors = $cust_main->unsuspend;
173     #return 
174     # side-fx with nested transactions?  upstack rolls back?
175     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
176          join(' / ', @errors)
177       if @errors;
178   }
179   #eslaf
180
181   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
182
183   #my $cust_main = $self->cust_main;
184   if ( $conf->exists('payment_receipt_email')
185        && grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list
186   ) {
187
188     my $receipt_template = new Text::Template (
189       TYPE   => 'ARRAY',
190       SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
191     ) or do {
192       warn "can't create payment receipt template: $Text::Template::ERROR";
193       return '';
194     };
195
196     my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list;
197
198     my $payby = $self->payby;
199     my $payinfo = $self->payinfo;
200     $payby =~ s/^BILL$/Check/ if $payinfo;
201     $payinfo = $self->payinfo_masked if $payby eq 'CARD' || $payby eq 'CHEK';
202     $payby =~ s/^CHEK$/Electronic check/;
203
204     my $error = send_email(
205       'from'    => $conf->config('invoice_from'), #??? well as good as any
206       'to'      => \@invoicing_list,
207       'subject' => 'Payment receipt',
208       'body'    => [ $receipt_template->fill_in( HASH => {
209                        'date'    => time2str("%a %B %o, %Y", $self->_date),
210                        'name'    => $cust_main->name,
211                        'paynum'  => $self->paynum,
212                        'paid'    => sprintf("%.2f", $self->paid),
213                        'payby'   => ucfirst(lc($payby)),
214                        'payinfo' => $payinfo,
215                        'balance' => $cust_main->balance,
216                    } ) ],
217     );
218     if ( $error ) {
219       warn "can't send payment receipt: $error";
220     }
221
222   }
223
224   '';
225
226 }
227
228 =item void [ REASON ]
229
230 Voids this payment: deletes the payment and all associated applications and
231 adds a record of the voided payment to the FS::cust_pay_void table.
232
233 =cut
234
235 sub void {
236   my $self = shift;
237
238   local $SIG{HUP} = 'IGNORE';
239   local $SIG{INT} = 'IGNORE';
240   local $SIG{QUIT} = 'IGNORE';
241   local $SIG{TERM} = 'IGNORE';
242   local $SIG{TSTP} = 'IGNORE';
243   local $SIG{PIPE} = 'IGNORE';
244
245   my $oldAutoCommit = $FS::UID::AutoCommit;
246   local $FS::UID::AutoCommit = 0;
247   my $dbh = dbh;
248
249   my $cust_pay_void = new FS::cust_pay_void ( {
250     map { $_ => $self->get($_) } $self->fields
251   } );
252   $cust_pay_void->reason(shift) if scalar(@_);
253   my $error = $cust_pay_void->insert;
254   if ( $error ) {
255     $dbh->rollback if $oldAutoCommit;
256     return $error;
257   }
258
259   $error = $self->delete;
260   if ( $error ) {
261     $dbh->rollback if $oldAutoCommit;
262     return $error;
263   }
264
265   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
266
267   '';
268
269 }
270
271 =item delete
272
273 Deletes this payment and all associated applications (see L<FS::cust_bill_pay>),
274 unless the closed flag is set.  In most cases, you want to use the void
275 method instead to leave a record of the deleted payment.
276
277 =cut
278
279 sub delete {
280   my $self = shift;
281   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
282
283   local $SIG{HUP} = 'IGNORE';
284   local $SIG{INT} = 'IGNORE';
285   local $SIG{QUIT} = 'IGNORE';
286   local $SIG{TERM} = 'IGNORE';
287   local $SIG{TSTP} = 'IGNORE';
288   local $SIG{PIPE} = 'IGNORE';
289
290   my $oldAutoCommit = $FS::UID::AutoCommit;
291   local $FS::UID::AutoCommit = 0;
292   my $dbh = dbh;
293
294   foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
295     my $error = $app->delete;
296     if ( $error ) {
297       $dbh->rollback if $oldAutoCommit;
298       return $error;
299     }
300   }
301
302   my $error = $self->SUPER::delete(@_);
303   if ( $error ) {
304     $dbh->rollback if $oldAutoCommit;
305     return $error;
306   }
307
308   if ( $conf->config('deletepayments') ne '' ) {
309
310     my $cust_main = $self->cust_main;
311
312     my $error = send_email(
313       'from'    => $conf->config('invoice_from'), #??? well as good as any
314       'to'      => $conf->config('deletepayments'),
315       'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
316       'body'    => [
317         "This is an automatic message from your Freeside installation\n",
318         "informing you that the following payment has been deleted:\n",
319         "\n",
320         'paynum: '. $self->paynum. "\n",
321         'custnum: '. $self->custnum.
322           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
323         'paid: $'. sprintf("%.2f", $self->paid). "\n",
324         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
325         'payby: '. $self->payby. "\n",
326         'payinfo: '. $self->payinfo. "\n",
327         'paybatch: '. $self->paybatch. "\n",
328       ],
329     );
330
331     if ( $error ) {
332       $dbh->rollback if $oldAutoCommit;
333       return "can't send payment deletion notification: $error";
334     }
335
336   }
337
338   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
339
340   '';
341
342 }
343
344 =item replace OLD_RECORD
345
346 You probably shouldn't modify payments...
347
348 =item check
349
350 Checks all fields to make sure this is a valid payment.  If there is an error,
351 returns the error, otherwise returns false.  Called by the insert method.
352
353 =cut
354
355 sub check {
356   my $self = shift;
357
358   my $error =
359     $self->ut_numbern('paynum')
360     || $self->ut_numbern('custnum')
361     || $self->ut_money('paid')
362     || $self->ut_numbern('_date')
363     || $self->ut_textn('paybatch')
364     || $self->ut_enum('closed', [ '', 'Y' ])
365   ;
366   return $error if $error;
367
368   return "paid must be > 0 " if $self->paid <= 0;
369
370   return "unknown cust_main.custnum: ". $self->custnum
371     unless $self->invnum
372            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
373
374   $self->_date(time) unless $self->_date;
375
376   $self->payby =~ /^(CARD|CHEK|LECB|BILL|COMP|PREP)$/ or return "Illegal payby";
377   $self->payby($1);
378
379   #false laziness with cust_refund::check
380   if ( $self->payby eq 'CARD' ) {
381     my $payinfo = $self->payinfo;
382     $payinfo =~ s/\D//g;
383     $self->payinfo($payinfo);
384     if ( $self->payinfo ) {
385       $self->payinfo =~ /^(\d{13,16})$/
386         or return "Illegal (mistyped?) credit card number (payinfo)";
387       $self->payinfo($1);
388       validate($self->payinfo) or return "Illegal credit card number";
389       return "Unknown card type" if cardtype($self->payinfo) eq "Unknown";
390     } else {
391       $self->payinfo('N/A');
392     }
393
394   } else {
395     $error = $self->ut_textn('payinfo');
396     return $error if $error;
397   }
398
399   $self->SUPER::check;
400 }
401
402 =item batch_insert CUST_PAY_OBJECT, ...
403
404 Class method which inserts multiple payments.  Takes a list of FS::cust_pay
405 objects.  Returns a list, each element representing the status of inserting the
406 corresponding payment - empty.  If there is an error inserting any payment, the
407 entire transaction is rolled back, i.e. all payments are inserted or none are.
408
409 For example:
410
411   my @errors = FS::cust_pay->batch_insert(@cust_pay);
412   my $num_errors = scalar(grep $_, @errors);
413   if ( $num_errors == 0 ) {
414     #success; all payments were inserted
415   } else {
416     #failure; no payments were inserted.
417   }
418
419 =cut
420
421 sub batch_insert {
422   my $self = shift; #class method
423
424   local $SIG{HUP} = 'IGNORE';
425   local $SIG{INT} = 'IGNORE';
426   local $SIG{QUIT} = 'IGNORE';
427   local $SIG{TERM} = 'IGNORE';
428   local $SIG{TSTP} = 'IGNORE';
429   local $SIG{PIPE} = 'IGNORE';
430
431   my $oldAutoCommit = $FS::UID::AutoCommit;
432   local $FS::UID::AutoCommit = 0;
433   my $dbh = dbh;
434
435   my $errors = 0;
436   
437   my @errors = map {
438     my $error = $_->insert;
439     if ( $error ) { 
440       $errors++;
441     } else {
442       $_->cust_main->apply_payments;
443     }
444     $error;
445   } @_;
446
447   if ( $errors ) {
448     $dbh->rollback if $oldAutoCommit;
449   } else {
450     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
451   }
452
453   @errors;
454
455 }
456
457 =item cust_bill_pay
458
459 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
460 payment.
461
462 =cut
463
464 sub cust_bill_pay {
465   my $self = shift;
466   sort {    $a->_date  <=> $b->_date
467          || $a->invnum <=> $b->invnum }
468     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
469   ;
470 }
471
472 =item cust_pay_refund
473
474 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
475 payment.
476
477 =cut
478
479 sub cust_pay_refund {
480   my $self = shift;
481   sort { $a->_date <=> $b->_date }
482     qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
483   ;
484 }
485
486
487 =item unapplied
488
489 Returns the amount of this payment that is still unapplied; which is
490 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
491 applications (see L<FS::cust_pay_refund>).
492
493 =cut
494
495 sub unapplied {
496   my $self = shift;
497   my $amount = $self->paid;
498   $amount -= $_->amount foreach ( $self->cust_bill_pay );
499   $amount -= $_->amount foreach ( $self->cust_pay_refund );
500   sprintf("%.2f", $amount );
501 }
502
503 =item unrefunded
504
505 Returns the amount of this payment that has not been refuned; which is
506 paid minus all  refund applications (see L<FS::cust_pay_refund>).
507
508 =cut
509
510 sub unrefunded {
511   my $self = shift;
512   my $amount = $self->paid;
513   $amount -= $_->amount foreach ( $self->cust_pay_refund );
514   sprintf("%.2f", $amount );
515 }
516
517
518 =item cust_main
519
520 Returns the parent customer object (see L<FS::cust_main>).
521
522 =cut
523
524 sub cust_main {
525   my $self = shift;
526   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
527 }
528
529 =item payinfo_masked
530
531 Returns a "masked" payinfo field with all but the last four characters replaced
532 by 'x'es.  Useful for displaying credit cards.
533
534 =cut
535
536 sub payinfo_masked {
537   my $self = shift;
538   #some false laziness w/cust_main::paymask
539   if ( $self->payby eq 'CARD' ) {
540     my $payinfo = $self->payinfo;
541     'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
542   } elsif ( $self->payby eq 'CHEK' ) {
543     my( $account, $aba ) = split('@', $self->payinfo );
544     'x'x(length($account)-2). substr($account,(length($account)-2)). "@". $aba;
545   } else {
546     $self->payinfo;
547   }
548 }
549
550 =back
551
552 =head1 BUGS
553
554 Delete and replace methods.  payinfo_masked false laziness with cust_main.pm
555 and cust_refund.pm
556
557 =head1 SEE ALSO
558
559 L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
560 base documentation.
561
562 =cut
563
564 1;
565