Mail::Internet 1.44
[freeside.git] / FS / FS / cust_pay.pm
1 package FS::cust_pay;
2
3 use strict;
4 use vars qw( @ISA $conf $unsuspendauto $smtpmachine $invoice_from );
5 use Date::Format;
6 use Mail::Header;
7 use Mail::Internet 1.44;
8 use Business::CreditCard;
9 use FS::UID qw( dbh );
10 use FS::Record qw( dbh qsearch qsearchs dbh );
11 use FS::cust_bill;
12 use FS::cust_bill_pay;
13 use FS::cust_main;
14
15 @ISA = qw( FS::Record );
16
17 #ask FS::UID to run this stuff for us later
18 $FS::UID::callback{'FS::cust_pay'} = sub { 
19
20   $conf = new FS::Conf;
21   $unsuspendauto = $conf->exists('unsuspendauto');
22   $smtpmachine = $conf->config('smtpmachine');
23   $invoice_from = $conf->config('invoice_from');
24
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), `BILL' (billing), or `COMP' (free)
64
65 =item payinfo - card number, check #, or comp issuer (4-8 lowercase alphanumerics; think username), respectively
66
67 =item paybatch - text field for tracking card processing
68
69 =item closed - books closed flag, empty or `Y'
70
71 =back
72
73 =head1 METHODS
74
75 =over 4 
76
77 =item new HASHREF
78
79 Creates a new payment.  To add the payment to the databse, see L<"insert">.
80
81 =cut
82
83 sub table { 'cust_pay'; }
84
85 =item insert
86
87 Adds this payment to the database.
88
89 For backwards-compatibility and convenience, if the additional field invnum
90 is defined, an FS::cust_bill_pay record for the full amount of the payment
91 will be created.  In this case, custnum is optional.
92
93 =cut
94
95 sub insert {
96   my $self = shift;
97
98   local $SIG{HUP} = 'IGNORE';
99   local $SIG{INT} = 'IGNORE';
100   local $SIG{QUIT} = 'IGNORE';
101   local $SIG{TERM} = 'IGNORE';
102   local $SIG{TSTP} = 'IGNORE';
103   local $SIG{PIPE} = 'IGNORE';
104
105   my $oldAutoCommit = $FS::UID::AutoCommit;
106   local $FS::UID::AutoCommit = 0;
107   my $dbh = dbh;
108
109   if ( $self->invnum ) {
110     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
111       or do {
112         $dbh->rollback if $oldAutoCommit;
113         return "Unknown cust_bill.invnum: ". $self->invnum;
114       };
115     $self->custnum($cust_bill->custnum );
116   }
117
118   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
119   my $old_balance = $cust_main->balance;
120
121   my $error = $self->check;
122   return $error if $error;
123
124   $error = $self->SUPER::insert;
125   if ( $error ) {
126     $dbh->rollback if $oldAutoCommit;
127     return "error inserting $self: $error";
128   }
129
130   if ( $self->invnum ) {
131     my $cust_bill_pay = new FS::cust_bill_pay {
132       'invnum' => $self->invnum,
133       'paynum' => $self->paynum,
134       'amount' => $self->paid,
135       '_date'  => $self->_date,
136     };
137     $error = $cust_bill_pay->insert;
138     if ( $error ) {
139       $dbh->rollback if $oldAutoCommit;
140       return "error inserting $cust_bill_pay: $error";
141     }
142   }
143
144   if ( $self->paybatch =~ /^webui-/ ) {
145     my @cust_pay = qsearch('cust_pay', {
146       'custnum' => $self->custnum,
147       'paybatch' => $self->paybatch,
148     } );
149     if ( scalar(@cust_pay) > 1 ) {
150       $dbh->rollback if $oldAutoCommit;
151       return "a payment with webui token ". $self->paybatch. " already exists";
152     }
153   }
154
155   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
156
157   #false laziness w/ cust_credit::insert
158   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
159     my @errors = $cust_main->unsuspend;
160     #return 
161     # side-fx with nested transactions?  upstack rolls back?
162     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
163          join(' / ', @errors)
164       if @errors;
165   }
166   #eslaf
167
168   '';
169
170 }
171
172 sub upgrade_replace { #1.3.x->1.4.x
173   my $self = shift;
174
175   local $SIG{HUP} = 'IGNORE';
176   local $SIG{INT} = 'IGNORE';
177   local $SIG{QUIT} = 'IGNORE';
178   local $SIG{TERM} = 'IGNORE';
179   local $SIG{TSTP} = 'IGNORE';
180   local $SIG{PIPE} = 'IGNORE';
181
182   my $oldAutoCommit = $FS::UID::AutoCommit;
183   local $FS::UID::AutoCommit = 0;
184   my $dbh = dbh;
185
186   my $error = $self->check;
187   return $error if $error;
188
189   my %new = $self->hash;
190   my $new = FS::cust_pay->new(\%new);
191
192   if ( $self->invnum ) {
193     my $cust_bill_pay = new FS::cust_bill_pay {
194       'invnum' => $self->invnum,
195       'paynum' => $self->paynum,
196       'amount' => $self->paid,
197       '_date'  => $self->_date,
198     };
199     $error = $cust_bill_pay->insert;
200     if ( $error =~ 
201            /total cust_bill_pay.amount and cust_credit_bill.amount .* for invnum .* greater than cust_bill.charged/ ) {
202       #warn $error;
203       my $cust_bill = qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
204       $new->custnum($cust_bill->custnum);
205     } elsif ( $error ) {
206       $dbh->rollback if $oldAutoCommit;
207       return $error;
208     } else {
209       $new->custnum($cust_bill_pay->cust_bill->custnum);
210     }
211   } else {
212     die;
213   }
214
215   $error = $new->SUPER::replace($self);
216   if ( $error ) {
217     $dbh->rollback if $oldAutoCommit;
218     return $error;
219   }
220
221   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
222
223   '';
224
225
226 }
227
228 =item delete
229
230 Deletes this payment and all associated applications (see L<FS::cust_bill_pay>),
231 unless the closed flag is set.
232
233 =cut
234
235 sub delete {
236   my $self = shift;
237   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
238
239   local $SIG{HUP} = 'IGNORE';
240   local $SIG{INT} = 'IGNORE';
241   local $SIG{QUIT} = 'IGNORE';
242   local $SIG{TERM} = 'IGNORE';
243   local $SIG{TSTP} = 'IGNORE';
244   local $SIG{PIPE} = 'IGNORE';
245
246   my $oldAutoCommit = $FS::UID::AutoCommit;
247   local $FS::UID::AutoCommit = 0;
248   my $dbh = dbh;
249
250   foreach my $cust_bill_pay ( $self->cust_bill_pay ) {
251     my $error = $cust_bill_pay->delete;
252     if ( $error ) {
253       $dbh->rollback if $oldAutoCommit;
254       return $error;
255     }
256   }
257
258   my $error = $self->SUPER::delete(@_);
259   if ( $error ) {
260     $dbh->rollback if $oldAutoCommit;
261     return $error;
262   }
263
264   if ( $conf->config('deletepayments') ne '' ) {
265
266     my $cust_main = qsearchs('cust_main',{ 'custnum' => $self->custnum });
267     #false laziness w/FS::cust_bill::send & fs_signup_server
268     $ENV{MAILADDRESS} = $invoice_from; #??? well as good as any
269     my $header = new Mail::Header ( [
270       "From: $invoice_from",
271       "To: ". $conf->config('deletepayments'),
272       "Sender: $invoice_from",
273       "Reply-To: $invoice_from",
274       "Date: ". time2str("%a, %d %b %Y %X %z", time),
275       "Subject: FREESIDE NOTIFICATION: Payment deleted",
276     ] );
277     my $message = new Mail::Internet (
278       'Header' => $header,
279       'Body' => [ 
280         "This is an automatic message from your Freeside installation\n",
281         "informing you that the following payment has been deleted:\n",
282         "\n",
283         'paynum: '. $self->paynum. "\n",
284         'custnum: '. $self->custnum.
285           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
286         'paid: $'. sprintf("%.2f", $self->paid). "\n",
287         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
288         'payby: '. $self->payby. "\n",
289         'payinfo: '. $self->payinfo. "\n",
290         'paybatch: '. $self->paybatch. "\n",
291       ],
292     );
293     $!=0;
294     $message->smtpsend( Host => $smtpmachine )
295       or $message->smtpsend( Host => $smtpmachine, Debug => 1 )
296         or do {
297           $dbh->rollback if $oldAutoCommit;
298           return "(customer # ". $self->custnum.
299                  ") can't send payment deletion email to ".
300                  $conf->config('deletepayments').
301                  " via server $smtpmachine with SMTP: $!";
302         };
303   }
304
305   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
306
307   '';
308
309 }
310
311 =item replace OLD_RECORD
312
313 Currently unimplemented (accounting reasons).
314
315 =cut
316
317 sub replace {
318    return "Can't (yet?) modify cust_pay records!";
319 }
320
321 =item check
322
323 Checks all fields to make sure this is a valid payment.  If there is an error,
324 returns the error, otherwise returns false.  Called by the insert method.
325
326 =cut
327
328 sub check {
329   my $self = shift;
330
331   my $error =
332     $self->ut_numbern('paynum')
333     || $self->ut_numbern('custnum')
334     || $self->ut_money('paid')
335     || $self->ut_numbern('_date')
336     || $self->ut_textn('paybatch')
337     || $self->ut_enum('closed', [ '', 'Y' ])
338   ;
339   return $error if $error;
340
341   return "paid must be > 0 " if $self->paid <= 0;
342
343   return "unknown cust_main.custnum: ". $self->custnum
344     unless $self->invnum
345            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
346
347   $self->_date(time) unless $self->_date;
348
349   $self->payby =~ /^(CARD|BILL|COMP)$/ or return "Illegal payby";
350   $self->payby($1);
351
352   #false laziness with cust_refund::check
353   if ( $self->payby eq 'CARD' ) {
354     my $payinfo = $self->payinfo;
355     $payinfo =~ s/\D//g;
356     $self->payinfo($payinfo);
357     if ( $self->payinfo ) {
358       $self->payinfo =~ /^(\d{13,16})$/
359         or return "Illegal (mistyped?) credit card number (payinfo)";
360       $self->payinfo($1);
361       validate($self->payinfo) or return "Illegal credit card number";
362       return "Unknown card type" if cardtype($self->payinfo) eq "Unknown";
363     } else {
364       $self->payinfo('N/A');
365     }
366
367   } else {
368     $error = $self->ut_textn('payinfo');
369     return $error if $error;
370   }
371
372   ''; #no error
373
374 }
375
376 =item cust_bill_pay
377
378 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
379 payment.
380
381 =cut
382
383 sub cust_bill_pay {
384   my $self = shift;
385   sort { $a->_date <=> $b->_date }
386     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
387   ;
388 }
389
390 =item unapplied
391
392 Returns the amount of this payment that is still unapplied; which is
393 paid minus all payment applications (see L<FS::cust_bill_pay>).
394
395 =cut
396
397 sub unapplied {
398   my $self = shift;
399   my $amount = $self->paid;
400   $amount -= $_->amount foreach ( $self->cust_bill_pay );
401   sprintf("%.2f", $amount );
402 }
403
404 =back
405
406 =head1 VERSION
407
408 $Id: cust_pay.pm,v 1.20 2002-05-18 09:51:30 ivan Exp $
409
410 =head1 BUGS
411
412 Delete and replace methods.
413
414 =head1 SEE ALSO
415
416 L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
417 base documentation.
418
419 =cut
420
421 1;
422