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