add stack backtrace to fatal problems in virtual field check
[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 FS::UID qw( dbh );
8 use FS::Record qw( dbh qsearch qsearchs dbh );
9 use FS::Misc qw(send_email);
10 use FS::cust_bill;
11 use FS::cust_bill_pay;
12 use FS::cust_main;
13
14 @ISA = qw( FS::Record );
15
16 #ask FS::UID to run this stuff for us later
17 FS::UID->install_callback( sub { 
18   $conf = new FS::Conf;
19   $unsuspendauto = $conf->exists('unsuspendauto');
20 } );
21
22 =head1 NAME
23
24 FS::cust_pay - Object methods for cust_pay objects
25
26 =head1 SYNOPSIS
27
28   use FS::cust_pay;
29
30   $record = new FS::cust_pay \%hash;
31   $record = new FS::cust_pay { 'column' => 'value' };
32
33   $error = $record->insert;
34
35   $error = $new_record->replace($old_record);
36
37   $error = $record->delete;
38
39   $error = $record->check;
40
41 =head1 DESCRIPTION
42
43 An FS::cust_pay object represents a payment; the transfer of money from a
44 customer.  FS::cust_pay inherits from FS::Record.  The following fields are
45 currently supported:
46
47 =over 4
48
49 =item paynum - primary key (assigned automatically for new payments)
50
51 =item custnum - customer (see L<FS::cust_main>)
52
53 =item paid - Amount of this payment
54
55 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
56 L<Time::Local> and L<Date::Parse> for conversion functions.
57
58 =item payby - `CARD' (credit cards), `CHEK' (electronic check/ACH),
59 `LECB' (phone bill billing), `BILL' (billing), or `COMP' (free)
60
61 =item payinfo - card number, check #, or comp issuer (4-8 lowercase alphanumerics; think username), respectively
62
63 =item paybatch - text field for tracking card processing
64
65 =item closed - books closed flag, empty or `Y'
66
67 =back
68
69 =head1 METHODS
70
71 =over 4 
72
73 =item new HASHREF
74
75 Creates a new payment.  To add the payment to the databse, see L<"insert">.
76
77 =cut
78
79 sub table { 'cust_pay'; }
80
81 =item insert
82
83 Adds this payment to the database.
84
85 For backwards-compatibility and convenience, if the additional field invnum
86 is defined, an FS::cust_bill_pay record for the full amount of the payment
87 will be created.  In this case, custnum is optional.
88
89 =cut
90
91 sub insert {
92   my $self = shift;
93
94   local $SIG{HUP} = 'IGNORE';
95   local $SIG{INT} = 'IGNORE';
96   local $SIG{QUIT} = 'IGNORE';
97   local $SIG{TERM} = 'IGNORE';
98   local $SIG{TSTP} = 'IGNORE';
99   local $SIG{PIPE} = 'IGNORE';
100
101   my $oldAutoCommit = $FS::UID::AutoCommit;
102   local $FS::UID::AutoCommit = 0;
103   my $dbh = dbh;
104
105   if ( $self->invnum ) {
106     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
107       or do {
108         $dbh->rollback if $oldAutoCommit;
109         return "Unknown cust_bill.invnum: ". $self->invnum;
110       };
111     $self->custnum($cust_bill->custnum );
112   }
113
114   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
115   my $old_balance = $cust_main->balance;
116
117   my $error = $self->check;
118   return $error if $error;
119
120   $error = $self->SUPER::insert;
121   if ( $error ) {
122     $dbh->rollback if $oldAutoCommit;
123     return "error inserting $self: $error";
124   }
125
126   if ( $self->invnum ) {
127     my $cust_bill_pay = new FS::cust_bill_pay {
128       'invnum' => $self->invnum,
129       'paynum' => $self->paynum,
130       'amount' => $self->paid,
131       '_date'  => $self->_date,
132     };
133     $error = $cust_bill_pay->insert;
134     if ( $error ) {
135       $dbh->rollback if $oldAutoCommit;
136       return "error inserting $cust_bill_pay: $error";
137     }
138   }
139
140   if ( $self->paybatch =~ /^webui-/ ) {
141     my @cust_pay = qsearch('cust_pay', {
142       'custnum' => $self->custnum,
143       'paybatch' => $self->paybatch,
144     } );
145     if ( scalar(@cust_pay) > 1 ) {
146       $dbh->rollback if $oldAutoCommit;
147       return "a payment with webui token ". $self->paybatch. " already exists";
148     }
149   }
150
151   #false laziness w/ cust_credit::insert
152   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
153     my @errors = $cust_main->unsuspend;
154     #return 
155     # side-fx with nested transactions?  upstack rolls back?
156     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
157          join(' / ', @errors)
158       if @errors;
159   }
160   #eslaf
161
162   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
163
164   '';
165
166 }
167
168 sub upgrade_replace { #1.3.x->1.4.x
169   my $self = shift;
170
171   local $SIG{HUP} = 'IGNORE';
172   local $SIG{INT} = 'IGNORE';
173   local $SIG{QUIT} = 'IGNORE';
174   local $SIG{TERM} = 'IGNORE';
175   local $SIG{TSTP} = 'IGNORE';
176   local $SIG{PIPE} = 'IGNORE';
177
178   my $oldAutoCommit = $FS::UID::AutoCommit;
179   local $FS::UID::AutoCommit = 0;
180   my $dbh = dbh;
181
182   my $error = $self->check;
183   return $error if $error;
184
185   my %new = $self->hash;
186   my $new = FS::cust_pay->new(\%new);
187
188   if ( $self->invnum ) {
189     my $cust_bill_pay = new FS::cust_bill_pay {
190       'invnum' => $self->invnum,
191       'paynum' => $self->paynum,
192       'amount' => $self->paid,
193       '_date'  => $self->_date,
194     };
195     $error = $cust_bill_pay->insert;
196     if ( $error =~ 
197            /total cust_bill_pay.amount and cust_credit_bill.amount .* for invnum .* greater than cust_bill.charged/ ) {
198       #warn $error;
199       my $cust_bill = qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
200       $new->custnum($cust_bill->custnum);
201     } elsif ( $error ) {
202       $dbh->rollback if $oldAutoCommit;
203       return $error;
204     } else {
205       $new->custnum($cust_bill_pay->cust_bill->custnum);
206     }
207   } else {
208     die;
209   }
210
211   $error = $new->SUPER::replace($self);
212   if ( $error ) {
213     $dbh->rollback if $oldAutoCommit;
214     return $error;
215   }
216
217   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
218
219   '';
220
221
222 }
223
224 =item delete
225
226 Deletes this payment and all associated applications (see L<FS::cust_bill_pay>),
227 unless the closed flag is set.
228
229 =cut
230
231 sub delete {
232   my $self = shift;
233   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
234
235   local $SIG{HUP} = 'IGNORE';
236   local $SIG{INT} = 'IGNORE';
237   local $SIG{QUIT} = 'IGNORE';
238   local $SIG{TERM} = 'IGNORE';
239   local $SIG{TSTP} = 'IGNORE';
240   local $SIG{PIPE} = 'IGNORE';
241
242   my $oldAutoCommit = $FS::UID::AutoCommit;
243   local $FS::UID::AutoCommit = 0;
244   my $dbh = dbh;
245
246   foreach my $cust_bill_pay ( $self->cust_bill_pay ) {
247     my $error = $cust_bill_pay->delete;
248     if ( $error ) {
249       $dbh->rollback if $oldAutoCommit;
250       return $error;
251     }
252   }
253
254   my $error = $self->SUPER::delete(@_);
255   if ( $error ) {
256     $dbh->rollback if $oldAutoCommit;
257     return $error;
258   }
259
260   if ( $conf->config('deletepayments') ne '' ) {
261
262     my $cust_main = qsearchs('cust_main',{ 'custnum' => $self->custnum });
263
264     my $error = send_email(
265       'from'    => $conf->config('invoice_from'), #??? well as good as any
266       'to'      => $conf->config('deletepayments'),
267       'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
268       'body'    => [
269         "This is an automatic message from your Freeside installation\n",
270         "informing you that the following payment has been deleted:\n",
271         "\n",
272         'paynum: '. $self->paynum. "\n",
273         'custnum: '. $self->custnum.
274           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
275         'paid: $'. sprintf("%.2f", $self->paid). "\n",
276         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
277         'payby: '. $self->payby. "\n",
278         'payinfo: '. $self->payinfo. "\n",
279         'paybatch: '. $self->paybatch. "\n",
280       ],
281     );
282
283     if ( $error ) {
284       $dbh->rollback if $oldAutoCommit;
285       return "can't send payment deletion notification: $error";
286     }
287
288   }
289
290   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
291
292   '';
293
294 }
295
296 =item replace OLD_RECORD
297
298 Currently unimplemented (accounting reasons).
299
300 =cut
301
302 sub replace {
303    return "Can't (yet?) modify cust_pay records!";
304 }
305
306 =item check
307
308 Checks all fields to make sure this is a valid payment.  If there is an error,
309 returns the error, otherwise returns false.  Called by the insert method.
310
311 =cut
312
313 sub check {
314   my $self = shift;
315
316   my $error =
317     $self->ut_numbern('paynum')
318     || $self->ut_numbern('custnum')
319     || $self->ut_money('paid')
320     || $self->ut_numbern('_date')
321     || $self->ut_textn('paybatch')
322     || $self->ut_enum('closed', [ '', 'Y' ])
323   ;
324   return $error if $error;
325
326   return "paid must be > 0 " if $self->paid <= 0;
327
328   return "unknown cust_main.custnum: ". $self->custnum
329     unless $self->invnum
330            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
331
332   $self->_date(time) unless $self->_date;
333
334   $self->payby =~ /^(CARD|CHEK|LECB|BILL|COMP)$/ or return "Illegal payby";
335   $self->payby($1);
336
337   #false laziness with cust_refund::check
338   if ( $self->payby eq 'CARD' ) {
339     my $payinfo = $self->payinfo;
340     $payinfo =~ s/\D//g;
341     $self->payinfo($payinfo);
342     if ( $self->payinfo ) {
343       $self->payinfo =~ /^(\d{13,16})$/
344         or return "Illegal (mistyped?) credit card number (payinfo)";
345       $self->payinfo($1);
346       validate($self->payinfo) or return "Illegal credit card number";
347       return "Unknown card type" if cardtype($self->payinfo) eq "Unknown";
348     } else {
349       $self->payinfo('N/A');
350     }
351
352   } else {
353     $error = $self->ut_textn('payinfo');
354     return $error if $error;
355   }
356
357   $self->SUPER::check;
358 }
359
360 =item cust_bill_pay
361
362 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
363 payment.
364
365 =cut
366
367 sub cust_bill_pay {
368   my $self = shift;
369   sort { $a->_date <=> $b->_date }
370     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
371   ;
372 }
373
374 =item unapplied
375
376 Returns the amount of this payment that is still unapplied; which is
377 paid minus all payment applications (see L<FS::cust_bill_pay>).
378
379 =cut
380
381 sub unapplied {
382   my $self = shift;
383   my $amount = $self->paid;
384   $amount -= $_->amount foreach ( $self->cust_bill_pay );
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