payyment receipts: pass body has an arrayref, also fill in name filed
[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::UID qw( dbh );
9 use FS::Record qw( dbh qsearch qsearchs dbh );
10 use FS::Misc qw(send_email);
11 use FS::cust_bill;
12 use FS::cust_bill_pay;
13 use FS::cust_pay_refund;
14 use FS::cust_main;
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   #false laziness w/ cust_credit::insert
154   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
155     my @errors = $cust_main->unsuspend;
156     #return 
157     # side-fx with nested transactions?  upstack rolls back?
158     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
159          join(' / ', @errors)
160       if @errors;
161   }
162   #eslaf
163
164   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
165
166   #my $cust_main = $self->cust_main;
167   if ( $conf->exists('payment_receipt_email')
168        && grep { $_ ne 'POST' } $cust_main->invoicing_list
169   ) {
170
171     my $receipt_template = new Text::Template (
172       TYPE   => 'ARRAY',
173       SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
174     ) or do {
175       warn "can't create payment receipt template: $Text::Template::ERROR";
176       return '';
177     };
178
179     my @invoicing_list = grep { $_ ne 'POST' } $cust_main->invoicing_list;
180
181     my $error = send_email(
182       'from'    => $conf->config('invoice_from'), #??? well as good as any
183       'to'      => \@invoicing_list,
184       'subject' => 'Payment receipt',
185       'body'    => [ $receipt_template->fill_in( HASH => {
186                        'date'    => time2str("%a %B %o, %Y", $self->_date),
187                        'name'    => $cust_main->name,
188                        'paynum'  => $self->paynum,
189                        'paid'    => $self->paid,
190                        'payby'   => ucfirst(lc($self->payby)),
191                        'payinfo' => ( $self->payby eq 'CARD'
192                                         ? $self->payinfo_masked
193                                         : $self->payinfo        ),
194                        'balance' => $cust_main->balance,
195                    } ) ],
196     );
197     if ( $error ) {
198       warn "can't send payment receipt: $error";
199     }
200
201   }
202
203   '';
204
205 }
206
207 =item delete
208
209 Deletes this payment and all associated applications (see L<FS::cust_bill_pay>),
210 unless the closed flag is set.
211
212 =cut
213
214 sub delete {
215   my $self = shift;
216   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
217
218   local $SIG{HUP} = 'IGNORE';
219   local $SIG{INT} = 'IGNORE';
220   local $SIG{QUIT} = 'IGNORE';
221   local $SIG{TERM} = 'IGNORE';
222   local $SIG{TSTP} = 'IGNORE';
223   local $SIG{PIPE} = 'IGNORE';
224
225   my $oldAutoCommit = $FS::UID::AutoCommit;
226   local $FS::UID::AutoCommit = 0;
227   my $dbh = dbh;
228
229   foreach my $cust_bill_pay ( $self->cust_bill_pay ) {
230     my $error = $cust_bill_pay->delete;
231     if ( $error ) {
232       $dbh->rollback if $oldAutoCommit;
233       return $error;
234     }
235   }
236
237   my $error = $self->SUPER::delete(@_);
238   if ( $error ) {
239     $dbh->rollback if $oldAutoCommit;
240     return $error;
241   }
242
243   if ( $conf->config('deletepayments') ne '' ) {
244
245     my $cust_main = $self->cust_main;
246
247     my $error = send_email(
248       'from'    => $conf->config('invoice_from'), #??? well as good as any
249       'to'      => $conf->config('deletepayments'),
250       'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
251       'body'    => [
252         "This is an automatic message from your Freeside installation\n",
253         "informing you that the following payment has been deleted:\n",
254         "\n",
255         'paynum: '. $self->paynum. "\n",
256         'custnum: '. $self->custnum.
257           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
258         'paid: $'. sprintf("%.2f", $self->paid). "\n",
259         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
260         'payby: '. $self->payby. "\n",
261         'payinfo: '. $self->payinfo. "\n",
262         'paybatch: '. $self->paybatch. "\n",
263       ],
264     );
265
266     if ( $error ) {
267       $dbh->rollback if $oldAutoCommit;
268       return "can't send payment deletion notification: $error";
269     }
270
271   }
272
273   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
274
275   '';
276
277 }
278
279 =item replace OLD_RECORD
280
281 Currently unimplemented (accounting reasons).
282
283 =cut
284
285 sub replace {
286    return "Can't (yet?) modify cust_pay records!";
287 }
288
289 =item check
290
291 Checks all fields to make sure this is a valid payment.  If there is an error,
292 returns the error, otherwise returns false.  Called by the insert method.
293
294 =cut
295
296 sub check {
297   my $self = shift;
298
299   my $error =
300     $self->ut_numbern('paynum')
301     || $self->ut_numbern('custnum')
302     || $self->ut_money('paid')
303     || $self->ut_numbern('_date')
304     || $self->ut_textn('paybatch')
305     || $self->ut_enum('closed', [ '', 'Y' ])
306   ;
307   return $error if $error;
308
309   return "paid must be > 0 " if $self->paid <= 0;
310
311   return "unknown cust_main.custnum: ". $self->custnum
312     unless $self->invnum
313            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
314
315   $self->_date(time) unless $self->_date;
316
317   $self->payby =~ /^(CARD|CHEK|LECB|BILL|COMP)$/ or return "Illegal payby";
318   $self->payby($1);
319
320   #false laziness with cust_refund::check
321   if ( $self->payby eq 'CARD' ) {
322     my $payinfo = $self->payinfo;
323     $payinfo =~ s/\D//g;
324     $self->payinfo($payinfo);
325     if ( $self->payinfo ) {
326       $self->payinfo =~ /^(\d{13,16})$/
327         or return "Illegal (mistyped?) credit card number (payinfo)";
328       $self->payinfo($1);
329       validate($self->payinfo) or return "Illegal credit card number";
330       return "Unknown card type" if cardtype($self->payinfo) eq "Unknown";
331     } else {
332       $self->payinfo('N/A');
333     }
334
335   } else {
336     $error = $self->ut_textn('payinfo');
337     return $error if $error;
338   }
339
340   $self->SUPER::check;
341 }
342
343 =item cust_bill_pay
344
345 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
346 payment.
347
348 =cut
349
350 sub cust_bill_pay {
351   my $self = shift;
352   sort { $a->_date <=> $b->_date }
353     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
354   ;
355 }
356
357 =item cust_pay_refund
358
359 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
360 payment.
361
362 =cut
363
364 sub cust_pay_refund {
365   my $self = shift;
366   sort { $a->_date <=> $b->_date }
367     qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
368   ;
369 }
370
371
372 =item unapplied
373
374 Returns the amount of this payment that is still unapplied; which is
375 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
376 applications (see L<FS::cust_pay_refund>).
377
378 =cut
379
380 sub unapplied {
381   my $self = shift;
382   my $amount = $self->paid;
383   $amount -= $_->amount foreach ( $self->cust_bill_pay );
384   $amount -= $_->amount foreach ( $self->cust_pay_refund );
385   sprintf("%.2f", $amount );
386 }
387
388 =item cust_main
389
390 Returns the parent customer object (see L<FS::cust_main>).
391
392 =cut
393
394 sub cust_main {
395   my $self = shift;
396   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
397 }
398
399 =item payinfo_masked
400
401 Returns a "masked" payinfo field with all but the last four characters replaced
402 by 'x'es.  Useful for displaying credit cards.
403
404 =cut
405
406 sub payinfo_masked {
407   my $self = shift;
408   my $payinfo = $self->payinfo;
409   'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
410 }
411
412 =back
413
414 =head1 BUGS
415
416 Delete and replace methods.  payinfo_masked false laziness with cust_main.pm
417 and cust_refund.pm
418
419 =head1 SEE ALSO
420
421 L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
422 base documentation.
423
424 =cut
425
426 1;
427