use FS::table_name for all searches to eliminate warnings,
[freeside.git] / site_perl / cust_main.pm
1 #this is so kludgy i'd be embarassed if it wasn't cybercash's fault
2 package main;
3 use vars qw($paymentserversecret $paymentserverport $paymentserverhost);
4
5 package FS::cust_main;
6
7 use strict;
8 use vars qw(@ISA @EXPORT_OK $conf $lpr $processor $xaction $E_NoErr);
9 use Safe;
10 use Exporter;
11 use Carp;
12 use Time::Local;
13 use Date::Format;
14 use Date::Manip;
15 use Business::CreditCard;
16 use FS::UID qw(getotaker);
17 use FS::Record qw(fields hfields qsearchs qsearch);
18 use FS::cust_pkg;
19 use FS::cust_bill;
20 use FS::cust_bill_pkg;
21 use FS::cust_pay;
22 use FS::cust_credit;
23 use FS::cust_pay_batch;
24 use FS::part_referral;
25 use FS::cust_main_county;
26 use FS::agent;
27
28 @ISA = qw(FS::Record Exporter);
29 @EXPORT_OK = qw(hfields);
30
31 #ask FS::UID to run this stuff for us later
32 $FS::UID::callback{'FS::cust_main'} = sub { 
33   $conf = new FS::Conf;
34   $lpr = $conf->config('lpr');
35
36   if ( $conf->exists('cybercash3.2') ) {
37     require CCMckLib3_2;
38       #qw($MCKversion %Config InitConfig CCError CCDebug CCDebug2);
39     require CCMckDirectLib3_2;
40       #qw(SendCC2_1Server);
41     require CCMckErrno3_2;
42       #qw(MCKGetErrorMessage $E_NoErr);
43     import CCMckErrno3_2 qw($E_NoErr);
44
45     my $merchant_conf;
46     ($merchant_conf,$xaction)= $conf->config('cybercash3.2');
47     my $status = &CCMckLib3_2::InitConfig($merchant_conf);
48     if ( $status != $E_NoErr ) {
49       warn "CCMckLib3_2::InitConfig error:\n";
50       foreach my $key (keys %CCMckLib3_2::Config) {
51         warn "  $key => $CCMckLib3_2::Config{$key}\n"
52       }
53       my($errmsg) = &CCMckErrno3_2::MCKGetErrorMessage($status);
54       die "CCMckLib3_2::InitConfig fatal error: $errmsg\n";
55     }
56     $processor='cybercash3.2';
57   } elsif ( $conf->exists('cybercash2') ) {
58     require CCLib;
59       #qw(sendmserver);
60     ( $main::paymentserverhost, 
61       $main::paymentserverport, 
62       $main::paymentserversecret,
63       $xaction,
64     ) = $conf->config('cybercash2');
65     $processor='cybercash2';
66   }
67 };
68
69 =head1 NAME
70
71 FS::cust_main - Object methods for cust_main records
72
73 =head1 SYNOPSIS
74
75   use FS::cust_main;
76
77   $record = create FS::cust_main \%hash;
78   $record = create FS::cust_main { 'column' => 'value' };
79
80   $error = $record->insert;
81
82   $error = $new_record->replace($old_record);
83
84   $error = $record->delete;
85
86   $error = $record->check;
87
88   @cust_pkg = $record->all_pkgs;
89
90   @cust_pkg = $record->ncancelled_pkgs;
91
92   $error = $record->bill;
93   $error = $record->bill %options;
94   $error = $record->bill 'time' => $time;
95
96   $error = $record->collect;
97   $error = $record->collect %options;
98   $error = $record->collect 'invoice_time'   => $time,
99                             'batch_card'     => 'yes',
100                             'report_badcard' => 'yes',
101                           ;
102
103 =head1 DESCRIPTION
104
105 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
106 FS::Record.  The following fields are currently supported:
107
108 =over 4
109
110 =item custnum - primary key (assigned automatically for new customers)
111
112 =item agentnum - agent (see L<FS::agent>)
113
114 =item refnum - referral (see L<FS::part_referral>)
115
116 =item first - name
117
118 =item last - name
119
120 =item ss - social security number (optional)
121
122 =item company - (optional)
123
124 =item address1
125
126 =item address2 - (optional)
127
128 =item city
129
130 =item county - (optional, see L<FS::cust_main_county>)
131
132 =item state - (see L<FS::cust_main_county>)
133
134 =item zip
135
136 =item country - (see L<FS::cust_main_county>)
137
138 =item daytime - phone (optional)
139
140 =item night - phone (optional)
141
142 =item payby - `CARD' (credit cards), `BILL' (billing), or `COMP' (free)
143
144 =item payinfo - card number, P.O.#, or comp issuer (4-8 lowercase alphanumerics; think username)
145
146 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
147
148 =item payname - name on card or billing name
149
150 =item tax - tax exempt, empty or `Y'
151
152 =item otaker - order taker (assigned automatically, see L<FS::UID>)
153
154 =back
155
156 =head1 METHODS
157
158 =over 4
159
160 =item create HASHREF
161
162 Creates a new customer.  To add the customer to the database, see L<"insert">.
163
164 Note that this stores the hash reference, not a distinct copy of the hash it
165 points to.  You can ask the object for a copy with the I<hash> method.
166
167 =cut
168
169 sub create {
170   my($proto,$hashref)=@_;
171
172   #now in FS::Record::new
173   #my $field;
174   #foreach $field (fields('cust_main')) {
175   #  $hashref->{$field}='' unless defined $hashref->{$field};
176   #}
177
178   $proto->new('cust_main',$hashref);
179 }
180
181 =item insert
182
183 Adds this customer to the database.  If there is an error, returns the error,
184 otherwise returns false.
185
186 =cut
187
188 sub insert {
189   my($self)=@_;
190
191   #no callbacks in check, only data checks
192   #local $SIG{HUP} = 'IGNORE';
193   #local $SIG{INT} = 'IGNORE';
194   #local $SIG{QUIT} = 'IGNORE';
195   #local $SIG{TERM} = 'IGNORE';
196   #local $SIG{TSTP} = 'IGNORE';
197
198   $self->check or
199   $self->add;
200 }
201
202 =item delete
203
204 Currently unimplemented.  Maybe cancel all of this customer's
205 packages (cust_pkg)?
206
207 I don't remove the customer record in the database because there would then
208 be no record the customer ever existed (which is bad, no?)
209
210 =cut
211
212 # Usage: $error = $record -> delete;
213 sub delete {
214    return "Can't (yet?) delete customers.";
215 #  my($self)=@_;
216 #
217 #  $self->del;
218 }
219
220 =item replace OLD_RECORD
221
222 Replaces the OLD_RECORD with this one in the database.  If there is an error,
223 returns the error, otherwise returns false.
224
225 =cut
226
227 sub replace {
228   my($new,$old)=@_;
229   return "(Old) Not a cust_main record!" unless $old->table eq "cust_main";
230   return "Can't change custnum!"
231     unless $old->getfield('custnum') eq $new->getfield('custnum');
232   $new->check or
233   $new->rep($old);
234 }
235
236 =item check
237
238 Checks all fields to make sure this is a valid customer record.  If there is
239 an error, returns the error, otherwise returns false.  Called by the insert
240 and repalce methods.
241
242 =cut
243
244 sub check {
245   my($self)=@_;
246
247   return "Not a cust_main record!" unless $self->table eq "cust_main";
248
249   my $error =
250     $self->ut_number('agentnum')
251     || $self->ut_number('refnum')
252     || $self->ut_textn('company')
253     || $self->ut_text('address1')
254     || $self->ut_textn('address2')
255     || $self->ut_text('city')
256     || $self->ut_textn('county')
257     || $self->ut_text('state')
258     || $self->ut_phonen('daytime')
259     || $self->ut_phonen('night')
260     || $self->ut_phonen('fax')
261   ;
262   return $error if $error;
263
264   return "Unknown agent"
265     unless qsearchs('agent',{'agentnum'=>$self->agentnum});
266
267   return "Unknown referral"
268     unless qsearchs('part_referral',{'refnum'=>$self->refnum});
269
270   $self->getfield('last') =~ /^([\w \,\.\-\']+)$/ or return "Illegal last name";
271   $self->setfield('last',$1);
272
273   $self->first =~ /^([\w \,\.\-\']+)$/ or return "Illegal first name";
274   $self->first($1);
275
276   if ( $self->ss eq '' ) {
277     $self->ss('');
278   } else {
279     my $ss = $self->ss;
280     $ss =~ s/\D//g;
281     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
282       or return "Illegal social security number";
283     $self->ss("$1-$2-$3");
284   }
285
286   return "Unknown state/county/country, state ".
287       "\"". $self->state. "\" county \"". $self->county. "\""
288     unless qsearchs('cust_main_county',{
289       'state'  => $self->state,
290       'county' => $self->county,
291     } );
292
293   #int'l zips?
294   $self->zip =~ /^(\d{5}(-\d{4})?)$/ or return "Illegal zip";
295   $self->zip($1);
296
297   #int'l countries!
298   $self->country =~ /^(US)$/ or return "Illegal country";
299   $self->country($1);
300
301   $self->payby =~ /^(CARD|BILL|COMP)$/ or return "Illegal payby";
302   $self->payby($1);
303
304   if ( $self->payby eq 'CARD' ) {
305
306     my $payinfo = $self->payinfo;
307     $payinfo =~ s/\D//g;
308     $payinfo =~ /^(\d{13,16})$/
309       or return "Illegal credit card number";
310     $payinfo = $1;
311     $self->payinfo($payinfo);
312     validate($payinfo) or return "Illegal credit card number";
313     my $type = cardtype($payinfo);
314     return "Unknown credit card type"
315       unless ( $type =~ /^VISA/ ||
316                $type =~ /^MasterCard/ ||
317                $type =~ /^American Express/ ||
318                $type =~ /^Discover/ );
319
320   } elsif ( $self->payby eq 'BILL' ) {
321
322     $self->payinfo =~ /^([\w \-]*)$/ or return "Illegal P.O. number";
323     $self->payinfo($1);
324
325   } elsif ( $self->payby eq 'COMP' ) {
326
327     $self->payinfo =~ /^(\w{2,8})$/ or return "Illegal comp account issuer";
328     $self->payinfo($1);
329
330   }
331
332   if ( $self->paydate eq '' ) {
333     return "Expriation date required" unless $self->payby eq 'BILL';
334     $self->paydate('');
335   } else {
336     $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
337       or return "Illegal expiration date";
338     if ( length($2) == 4 ) {
339       $self->paydate("$2-$1-01");
340     } elsif ( $2 > 97 ) { #should pry change to check for "this year"
341       $self->paydate("19$2-$1-01");
342     } else {
343       $self->paydate("20$2-$1-01");
344     }
345   }
346
347   if ( $self->payname eq '' ) {
348     $self->payname( $self->first. " ". $self->getfield('last') );
349   } else {
350     $self->payname =~ /^([\w \,\.\-\']+)$/
351       or return "Illegal billing name";
352     $self->payname($1);
353   }
354
355   $self->tax =~ /^(Y?)$/ or return "Illegal tax";
356   $self->tax($1);
357
358   $self->otaker(getotaker);
359
360   ''; #no error
361 }
362
363 =item all_pkgs
364
365 Returns all packages (see L<FS::cust_pkg>) for this customer.
366
367 =cut
368
369 sub all_pkgs {
370   my($self)=@_;
371   qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
372 }
373
374 =item ncancelled_pkgs
375
376 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
377
378 =cut
379
380 sub ncancelled_pkgs {
381   my($self)=@_;
382   qsearch( 'cust_pkg', {
383     'custnum' => $self->custnum,
384     'cancel'  => '',
385   });
386 }
387
388 =item bill OPTIONS
389
390 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
391 conjunction with the collect method.
392
393 The only currently available option is `time', which bills the customer as if
394 it were that time.  It is specified as a UNIX timestamp; see
395 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
396 functions.
397
398 If there is an error, returns the error, otherwise returns false.
399
400 =cut
401
402 sub bill {
403   my($self,%options)=@_;
404   my($time) = $options{'time'} || $^T;
405
406   my($error);
407
408   #put below somehow?
409   local $SIG{HUP} = 'IGNORE';
410   local $SIG{INT} = 'IGNORE';
411   local $SIG{QUIT} = 'IGNORE';
412   local $SIG{TERM} = 'IGNORE';
413   local $SIG{TSTP} = 'IGNORE';
414
415   # find the packages which are due for billing, find out how much they are
416   # & generate invoice database.
417  
418   my($total_setup,$total_recur)=(0,0);
419
420   my(@cust_bill_pkg);
421
422   my($cust_pkg);
423   foreach $cust_pkg (
424     qsearch('cust_pkg',{'custnum'=> $self->getfield('custnum') } )
425   ) {
426
427     bless($cust_pkg,"FS::cust_pkg");
428  
429     next if ( $cust_pkg->getfield('cancel') );  
430
431     #? to avoid use of uninitialized value errors... ?
432     $cust_pkg->setfield('bill', '')
433       unless defined($cust_pkg->bill);
434  
435     my($part_pkg)=
436       qsearchs('part_pkg',{'pkgpart'=> $cust_pkg->pkgpart } );
437
438     #so we don't modify cust_pkg record unnecessarily
439     my($cust_pkg_mod_flag)=0;
440     my(%hash)=$cust_pkg->hash;
441     my($old_cust_pkg)=create FS::cust_pkg(\%hash);
442
443     # bill setup
444     my($setup)=0;
445     unless ( $cust_pkg->setup ) {
446       my($setup_prog)=$part_pkg->getfield('setup');
447       my($cpt) = new Safe;
448       #$cpt->permit(); #what is necessary?
449       $cpt->share(qw($cust_pkg)); #can $cpt now use $cust_pkg methods?
450       $setup = $cpt->reval($setup_prog);
451       unless ( defined($setup) ) {
452         warn "Error reval-ing part_pkg->setup pkgpart ", 
453              $part_pkg->pkgpart, ": $@";
454       } else {
455         $cust_pkg->setfield('setup',$time);
456         $cust_pkg_mod_flag=1; 
457       }
458     }
459
460     #bill recurring fee
461     my($recur)=0;
462     my($sdate);
463     if ( $part_pkg->getfield('freq') > 0 &&
464          ! $cust_pkg->getfield('susp') &&
465          ( $cust_pkg->getfield('bill') || 0 ) < $time
466     ) {
467       my($recur_prog)=$part_pkg->getfield('recur');
468       my($cpt) = new Safe;
469       #$cpt->permit(); #what is necessary?
470       $cpt->share(qw($cust_pkg)); #can $cpt now use $cust_pkg methods?
471       $recur = $cpt->reval($recur_prog);
472       unless ( defined($recur) ) {
473         warn "Error reval-ing part_pkg->recur pkgpart ",
474              $part_pkg->pkgpart, ": $@";
475       } else {
476         #change this bit to use Date::Manip?
477         #$sdate=$cust_pkg->bill || time;
478         #$sdate=$cust_pkg->bill || $time;
479         $sdate=$cust_pkg->bill || $cust_pkg->setup || $time;
480         my($sec,$min,$hour,$mday,$mon,$year)=
481           (localtime($sdate) )[0,1,2,3,4,5];
482         $mon += $part_pkg->getfield('freq');
483         until ( $mon < 12 ) { $mon -= 12; $year++; }
484         $cust_pkg->setfield('bill',timelocal($sec,$min,$hour,$mday,$mon,$year));
485         $cust_pkg_mod_flag=1; 
486       }
487     }
488
489     warn "setup is undefinded" unless defined($setup);
490     warn "recur is undefinded" unless defined($recur);
491     warn "cust_pkg bill is undefinded" unless defined($cust_pkg->bill);
492
493     if ($cust_pkg_mod_flag) {
494       $error=$cust_pkg->replace($old_cust_pkg);
495       if ( $error ) {
496         warn "Error modifying pkgnum ", $cust_pkg->pkgnum, ": $error";
497       } else {
498         #just in case
499         $setup=sprintf("%.2f",$setup);
500         $recur=sprintf("%.2f",$recur);
501         my($cust_bill_pkg)=create FS::cust_bill_pkg ({
502           'pkgnum' => $cust_pkg->pkgnum,
503           'setup'  => $setup,
504           'recur'  => $recur,
505           'sdate'  => $sdate,
506           'edate'  => $cust_pkg->bill,
507         });
508         push @cust_bill_pkg, $cust_bill_pkg;
509         $total_setup += $setup;
510         $total_recur += $recur;
511       }
512     }
513
514   }
515
516   my($charged)=sprintf("%.2f",$total_setup + $total_recur);
517
518   return '' if scalar(@cust_bill_pkg) == 0;
519
520   unless ( $self->getfield('tax') eq 'Y' ||
521            $self->getfield('tax') eq 'y' ||
522            $self->getfield('payby') eq 'COMP'
523   ) {
524     my($cust_main_county) = qsearchs('cust_main_county',{
525       'county' => $self->getfield('county'),
526       'state'  => $self->getfield('state'),
527     } );
528     my($tax) = sprintf("%.2f",
529       $charged * ( $cust_main_county->getfield('tax') / 100 )
530     );
531     $charged = sprintf("%.2f",$charged+$tax);
532
533     my($cust_bill_pkg)=create FS::cust_bill_pkg ({
534       'pkgnum' => 0,
535       'setup'  => $tax,
536       'recur'  => 0,
537       'sdate'  => '',
538       'edate'  => '',
539     });
540     push @cust_bill_pkg, $cust_bill_pkg;
541   }
542
543   my($cust_bill) = create FS::cust_bill ( {
544     'custnum' => $self->getfield('custnum'),
545     '_date' => $time,
546     'charged' => $charged,
547   } );
548   $error=$cust_bill->insert;
549   #shouldn't happen, but how else to handle this? (wrap me in eval, to catch 
550   # fatal errors)
551   die "Error creating cust_bill record: $error!\n",
552       "Check updated but unbilled packages for customer", $self->custnum, "\n"
553     if $error;
554
555   my($invnum)=$cust_bill->invnum;
556   my($cust_bill_pkg);
557   foreach $cust_bill_pkg ( @cust_bill_pkg ) {
558     $cust_bill_pkg->setfield('invnum',$invnum);
559     $error=$cust_bill_pkg->insert;
560     #shouldn't happen, but how else tohandle this?
561     die "Error creating cust_bill_pkg record: $error!\n",
562         "Check incomplete invoice ", $invnum, "\n"
563       if $error;
564   }
565   
566   ''; #no error
567 }
568
569 =item collect OPTIONS
570
571 (Attempt to) collect money for this customer's outstanding invoices (see
572 L<FS::cust_bill>).  Usually used after the bill method.
573
574 Depending on the value of `payby', this may print an invoice (`BILL'), charge
575 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
576
577 If there is an error, returns the error, otherwise returns false.
578
579 Currently available options are:
580
581 invoice_time - Use this time when deciding when to print invoices and
582 late notices on those invoices.  The default is now.  It is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse>
583 for conversion functions.
584
585 batch_card - Set this true to batch cards (see L<cust_pay_batch>).  By
586 default, cards are processed immediately, which will generate an error if
587 CyberCash is not installed.
588
589 report_badcard - Set this true if you want bad card transactions to
590 return an error.  By default, they don't.
591
592 =cut
593
594 sub collect {
595   my($self,%options)=@_;
596   my($invoice_time) = $options{'invoice_time'} || $^T;
597
598   my($total_owed) = $self->balance;
599   return '' unless $total_owed > 0; #redundant?????
600
601   #put below somehow?
602   local $SIG{HUP} = 'IGNORE';
603   local $SIG{INT} = 'IGNORE';
604   local $SIG{QUIT} = 'IGNORE';
605   local $SIG{TERM} = 'IGNORE';
606   local $SIG{TSTP} = 'IGNORE';
607
608   foreach my $cust_bill ( qsearch('cust_bill', {
609     'custnum' => $self->getfield('custnum'),
610   } ) ) {
611
612     bless($cust_bill,"FS::cust_bill");
613
614     #this has to be before next's
615     my($amount) = sprintf("%.2f", $total_owed < $cust_bill->owed
616                                   ? $total_owed
617                                   : $cust_bill->owed
618     );
619     $total_owed = sprintf("%.2f",$total_owed-$amount);
620
621     next unless $cust_bill->owed > 0;
622
623     next if qsearchs('cust_pay_batch',{'invnum'=> $cust_bill->invnum });
624
625     #warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, total_owed $total_owed)";
626
627     next unless $amount > 0;
628
629     if ( $self->getfield('payby') eq 'BILL' ) {
630
631       #30 days 2592000
632       my($since)=$invoice_time - ( $cust_bill->_date || 0 );
633       #warn "$invoice_time ", $cust_bill->_date, " $since";
634       if ( $since >= 0 #don't print future invoices
635            && ( $cust_bill->printed * 2592000 ) <= $since
636       ) {
637
638         open(LPR,"|$lpr") or die "Can't open $lpr: $!";
639         print LPR $cust_bill->print_text; #( date )
640         close LPR
641           or die $! ? "Error closing $lpr: $!"
642                        : "Exit status $? from $lpr";
643
644         my(%hash)=$cust_bill->hash;
645         $hash{'printed'}++;
646         my($new_cust_bill)=create FS::cust_bill(\%hash);
647         my($error)=$new_cust_bill->replace($cust_bill);
648         if ( $error ) {
649           warn "Error updating $cust_bill->printed: $error";
650         }
651
652       }
653
654     } elsif ( $self->getfield('payby') eq 'COMP' ) {
655       my($cust_pay) = create FS::cust_pay ( {
656          'invnum' => $cust_bill->getfield('invnum'),
657          'paid' => $amount,
658          '_date' => '',
659          'payby' => 'COMP',
660          'payinfo' => $self->getfield('payinfo'),
661          'paybatch' => ''
662       } );
663       my($error)=$cust_pay->insert;
664       return 'Error COMPing invnum #' . $cust_bill->getfield('invnum') .
665              ':' . $error if $error;
666     } elsif ( $self->getfield('payby') eq 'CARD' ) {
667
668       if ( $options{'batch_card'} ne 'yes' ) {
669
670         return "Real time card processing not enabled!" unless $processor;
671
672         if ( $processor =~ /cybercash/ ) {
673
674           #fix exp. date for cybercash
675           $self->getfield('paydate') =~ /^(\d+)\/\d*(\d{2})$/;
676           my($exp)="$1/$2";
677
678           my($paybatch)= $cust_bill->getfield('invnum') . 
679                          '-' . time2str("%y%m%d%H%M%S",time);
680
681           my($payname)= $self->getfield('payname') ||
682                         $self->getfield('first') . ' ' .$self->getfield('last');
683
684           my($address)= $self->getfield('address1');
685           $address .= ", " . $self->getfield('address2')
686             if $self->getfield('address2');
687
688           my($country) = $self->getfield('country') eq 'US' ?
689                          'USA' : $self->getfield('country');
690
691           my(@full_xaction)=($xaction,
692             'Order-ID'     => $paybatch,
693             'Amount'       => "usd $amount",
694             'Card-Number'  => $self->getfield('payinfo'),
695             'Card-Name'    => $payname,
696             'Card-Address' => $address,
697             'Card-City'    => $self->getfield('city'),
698             'Card-State'   => $self->getfield('state'),
699             'Card-Zip'     => $self->getfield('zip'),
700             'Card-Country' => $country,
701             'Card-Exp'     => $exp,
702           );
703
704           my(%result);
705           if ( $processor eq 'cybercash2' ) {
706             $^W=0; #CCLib isn't -w safe, ugh!
707             %result = &CCLib::sendmserver(@full_xaction);
708             $^W=1;
709           } elsif ( $processor eq 'cybercash3.2' ) {
710             %result = &CCMckDirectLib3_2::SendCC2_1Server(@full_xaction);
711           } else {
712             return "Unkonwn real-time processor $processor\n";
713           }
714          
715           #if ( $result{'MActionCode'} == 7 ) { #cybercash smps v.1.1.3
716           #if ( $result{'action-code'} == 7 ) { #cybercash smps v.2.1
717           if ( $result{'MStatus'} eq 'success' ) { #cybercash smps v.2 or 3
718             my($cust_pay) = create FS::cust_pay ( {
719                'invnum'   => $cust_bill->getfield('invnum'),
720                'paid'     => $amount,
721                '_date'     => '',
722                'payby'    => 'CARD',
723                'payinfo'  => $self->getfield('payinfo'),
724                'paybatch' => "$processor:$paybatch",
725             } );
726             my($error)=$cust_pay->insert;
727             return 'Error applying payment, invnum #' . 
728               $cust_bill->getfield('invnum') . ':' . $error if $error;
729           } elsif ( $result{'Mstatus'} ne 'failure-bad-money'
730                  || $options{'report_badcard'} ) {
731              return 'Cybercash error, invnum #' . 
732                $cust_bill->getfield('invnum') . ':' . $result{'MErrMsg'};
733           } else {
734             return '';
735           }
736
737         } else {
738           return "Unkonwn real-time processor $processor\n";
739         }
740
741       } else { #batch card
742
743 #       my($cust_pay_batch) = create FS::cust_pay_batch ( {
744        my($cust_pay_batch) = new FS::Record ('cust_pay_batch', {
745          'invnum'   => $cust_bill->getfield('invnum'),
746          'custnum'  => $self->getfield('custnum'),
747          'last'     => $self->getfield('last'),
748          'first'    => $self->getfield('first'),
749          'address1' => $self->getfield('address1'),
750          'address2' => $self->getfield('address2'),
751          'city'     => $self->getfield('city'),
752          'state'    => $self->getfield('state'),
753          'zip'      => $self->getfield('zip'),
754          'country'  => $self->getfield('country'),
755          'trancode' => 77,
756          'cardnum'  => $self->getfield('payinfo'),
757          'exp'      => $self->getfield('paydate'),
758          'payname'  => $self->getfield('payname'),
759          'amount'   => $amount,
760        } );
761 #       my($error)=$cust_pay_batch->insert;
762        my($error)=$cust_pay_batch->add;
763        return "Error adding to cust_pay_batch: $error" if $error;
764
765       }
766
767     } else {
768       return "Unknown payment type ".$self->getfield('payby');
769     }
770
771   }
772   '';
773
774 }
775
776 =item total_owed
777
778 Returns the total owed for this customer on all invoices
779 (see L<FS::cust_bill>).
780
781 =cut
782
783 sub total_owed {
784   my($self) = @_;
785   my($total_bill) = 0;
786   my($cust_bill);
787   foreach $cust_bill ( qsearch('cust_bill', {
788     'custnum' => $self->getfield('custnum'),
789   } ) ) {
790     $total_bill += $cust_bill->getfield('owed');
791   }
792   sprintf("%.2f",$total_bill);
793 }
794
795 =item total_credited
796
797 Returns the total credits (see L<FS::cust_credit>) for this customer.
798
799 =cut
800
801 sub total_credited {
802   my($self) = @_;
803   my($total_credit) = 0;
804   my($cust_credit);
805   foreach $cust_credit ( qsearch('cust_credit', {
806     'custnum' => $self->getfield('custnum'),
807   } ) ) {
808     $total_credit += $cust_credit->getfield('credited');
809   }
810   sprintf("%.2f",$total_credit);
811 }
812
813 =item balance
814
815 Returns the balance for this customer (total owed minus total credited).
816
817 =cut
818
819 sub balance {
820   my($self) = @_;
821   sprintf("%.2f",$self->total_owed - $self->total_credited);
822 }
823
824 =back
825
826 =head1 BUGS
827
828 The delete method.
829
830 It doesn't properly override FS::Record yet.
831
832 hfields should be removed.
833
834 Bill and collect options should probably be passed as references instead of a
835 list.
836
837 CyberCash v2 forces us to define some variables in package main.
838
839 =head1 SEE ALSO
840
841 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
842 L<FS::cust_pay_batch>, L<FS::agent>, L<FS::part_referral>,
843 L<FS::cust_main_county>, L<FS::UID>, schema.html from the base documentation.
844
845 =head1 HISTORY
846
847 ivan@voicenet.com 97-jul-28
848
849 Changed to standard Business::CreditCard
850 no more TableUtil
851 EXPORT_OK FS::Record's hfields
852 removed unique calls and locking (not needed here now)
853 wrapped the (now) optional fields in if statements in sub check (notyetdone!)
854 ivan@sisd.com 97-nov-12
855
856 updated paydate with SQL-type date info ivan@sisd.com 98-mar-5
857
858 Added export of datasrc from UID.pm for Pg6.3
859 changed 'day' to 'daytime' because Pg6.3 reserves the day word
860         bmccane@maxbaud.net     98-apr-3
861
862 in ->create, s/svc_acct/cust_main/, now it should actually eliminate the
863 warnings it was meant to ivan@sisd.com 98-jul-16
864
865 don't require a phone number and allow '/' in company names
866 ivan@sisd.com 98-jul-18
867
868 use ut_ and rewrite &check, &*_pkgs ivan@sisd.com 98-sep-5
869
870 pod, merge with FS::Bill (about time!), total_owed, total_credited and balance
871 methods, cleaned collect method, source modifications no longer necessary to
872 enable cybercash, cybercash v3 support, don't need to import
873 FS::UID::{datasrc,checkruid} ivan@sisd.com 98-sep-19-21
874
875 $Log: cust_main.pm,v $
876 Revision 1.5  1998-11-15 11:23:14  ivan
877 use FS::table_name for all searches to eliminate warnings,
878 emit state/county when they don't match
879
880 Revision 1.4  1998/11/15 05:30:48  ivan
881 bugfix for new config layout
882
883 Revision 1.3  1998/11/13 09:56:54  ivan
884 change configuration file layout to support multiple distinct databases (with
885 own set of config files, export, etc.)
886
887 Revision 1.2  1998/11/07 10:24:25  ivan
888 don't use depriciated FS::Bill and FS::Invoice, other miscellania
889
890
891 =cut
892
893 1;
894
895