1 #this is so kludgy i'd be embarassed if it wasn't cybercash's fault
3 use vars qw($paymentserversecret $paymentserverport $paymentserverhost);
8 use vars qw(@ISA @EXPORT_OK $conf $lpr $processor $xaction $E_NoErr);
15 use Business::CreditCard;
16 use FS::UID qw(getotaker);
17 use FS::Record qw(fields hfields qsearchs qsearch);
20 use FS::cust_bill_pkg;
23 use FS::cust_pay_batch;
25 @ISA = qw(FS::Record Exporter);
26 @EXPORT_OK = qw(hfields);
28 #ask FS::UID to run this stuff for us later
29 $FS::UID::callback{'FS::cust_main'} = sub {
31 $lpr = $conf->config('lpr');
33 if ( $conf->exists('cybercash3.2') ) {
35 #qw($MCKversion %Config InitConfig CCError CCDebug CCDebug2);
36 require CCMckDirectLib3_2;
38 require CCMckErrno3_2;
39 #qw(MCKGetErrorMessage $E_NoErr);
40 import CCMckErrno3_2 qw($E_NoErr);
43 ($merchant_conf,$xaction)= $conf->config('cybercash3.2');
44 my $status = &CCMckLib3_2::InitConfig($merchant_conf);
45 if ( $status != $E_NoErr ) {
46 warn "CCMckLib3_2::InitConfig error:\n";
47 foreach my $key (keys %CCMckLib3_2::Config) {
48 warn " $key => $CCMckLib3_2::Config{$key}\n"
50 my($errmsg) = &CCMckErrno3_2::MCKGetErrorMessage($status);
51 die "CCMckLib3_2::InitConfig fatal error: $errmsg\n";
53 $processor='cybercash3.2';
54 } elsif ( $conf->exists('cybercash2') ) {
57 ( $main::paymentserverhost,
58 $main::paymentserverport,
59 $main::paymentserversecret,
61 ) = $conf->config('cybercash2');
62 $processor='cybercash2';
68 FS::cust_main - Object methods for cust_main records
74 $record = create FS::cust_main \%hash;
75 $record = create FS::cust_main { 'column' => 'value' };
77 $error = $record->insert;
79 $error = $new_record->replace($old_record);
81 $error = $record->delete;
83 $error = $record->check;
85 @cust_pkg = $record->all_pkgs;
87 @cust_pkg = $record->ncancelled_pkgs;
89 $error = $record->bill;
90 $error = $record->bill %options;
91 $error = $record->bill 'time' => $time;
93 $error = $record->collect;
94 $error = $record->collect %options;
95 $error = $record->collect 'invoice_time' => $time,
96 'batch_card' => 'yes',
97 'report_badcard' => 'yes',
102 An FS::cust_main object represents a customer. FS::cust_main inherits from
103 FS::Record. The following fields are currently supported:
107 =item custnum - primary key (assigned automatically for new customers)
109 =item agentnum - agent (see L<FS::agent>)
111 =item refnum - referral (see L<FS::part_referral>)
117 =item ss - social security number (optional)
119 =item company - (optional)
123 =item address2 - (optional)
127 =item county - (optional, see L<FS::cust_main_county>)
129 =item state - (see L<FS::cust_main_county>)
133 =item country - (see L<FS::cust_main_county>)
135 =item daytime - phone (optional)
137 =item night - phone (optional)
139 =item payby - `CARD' (credit cards), `BILL' (billing), or `COMP' (free)
141 =item payinfo - card number, P.O.#, or comp issuer (4-8 lowercase alphanumerics; think username)
143 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
145 =item payname - name on card or billing name
147 =item tax - tax exempt, empty or `Y'
149 =item otaker - order taker (assigned automatically, see L<FS::UID>)
159 Creates a new customer. To add the customer to the database, see L<"insert">.
161 Note that this stores the hash reference, not a distinct copy of the hash it
162 points to. You can ask the object for a copy with the I<hash> method.
167 my($proto,$hashref)=@_;
169 #now in FS::Record::new
171 #foreach $field (fields('cust_main')) {
172 # $hashref->{$field}='' unless defined $hashref->{$field};
175 $proto->new('cust_main',$hashref);
180 Adds this customer to the database. If there is an error, returns the error,
181 otherwise returns false.
188 #no callbacks in check, only data checks
189 #local $SIG{HUP} = 'IGNORE';
190 #local $SIG{INT} = 'IGNORE';
191 #local $SIG{QUIT} = 'IGNORE';
192 #local $SIG{TERM} = 'IGNORE';
193 #local $SIG{TSTP} = 'IGNORE';
201 Currently unimplemented. Maybe cancel all of this customer's
204 I don't remove the customer record in the database because there would then
205 be no record the customer ever existed (which is bad, no?)
209 # Usage: $error = $record -> delete;
211 return "Can't (yet?) delete customers.";
217 =item replace OLD_RECORD
219 Replaces the OLD_RECORD with this one in the database. If there is an error,
220 returns the error, otherwise returns false.
226 return "(Old) Not a cust_main record!" unless $old->table eq "cust_main";
227 return "Can't change custnum!"
228 unless $old->getfield('custnum') eq $new->getfield('custnum');
235 Checks all fields to make sure this is a valid customer record. If there is
236 an error, returns the error, otherwise returns false. Called by the insert
244 return "Not a cust_main record!" unless $self->table eq "cust_main";
247 $self->ut_number('agentnum')
248 || $self->ut_number('refnum')
249 || $self->ut_textn('company')
250 || $self->ut_text('address1')
251 || $self->ut_textn('address2')
252 || $self->ut_text('city')
253 || $self->ut_textn('county')
254 || $self->ut_text('state')
255 || $self->ut_phonen('daytime')
256 || $self->ut_phonen('night')
257 || $self->ut_phonen('fax')
259 return $error if $error;
261 return "Unknown agent"
262 unless qsearchs('agent',{'agentnum'=>$self->agentnum});
264 return "Unknown referral"
265 unless qsearchs('part_referral',{'refnum'=>$self->refnum});
267 $self->getfield('last') =~ /^([\w \,\.\-\']+)$/ or return "Illegal last name";
268 $self->setfield('last',$1);
270 $self->first =~ /^([\w \,\.\-\']+)$/ or return "Illegal first name";
273 if ( $self->ss eq '' ) {
278 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
279 or return "Illegal social security number";
280 $self->ss("$1-$2-$3");
283 return "Unknown state/county/country"
284 unless qsearchs('cust_main_county',{
285 'state' => $self->state,
286 'county' => $self->county,
290 $self->zip =~ /^(\d{5}(-\d{4})?)$/ or return "Illegal zip";
294 $self->country =~ /^(US)$/ or return "Illegal country";
297 $self->payby =~ /^(CARD|BILL|COMP)$/ or return "Illegal payby";
300 if ( $self->payby eq 'CARD' ) {
302 my $payinfo = $self->payinfo;
304 $payinfo =~ /^(\d{13,16})$/
305 or return "Illegal credit card number";
307 $self->payinfo($payinfo);
308 validate($payinfo) or return "Illegal credit card number";
309 my $type = cardtype($payinfo);
310 return "Unknown credit card type"
311 unless ( $type =~ /^VISA/ ||
312 $type =~ /^MasterCard/ ||
313 $type =~ /^American Express/ ||
314 $type =~ /^Discover/ );
316 } elsif ( $self->payby eq 'BILL' ) {
318 $self->payinfo =~ /^([\w \-]*)$/ or return "Illegal P.O. number";
321 } elsif ( $self->payby eq 'COMP' ) {
323 $self->payinfo =~ /^(\w{2,8})$/ or return "Illegal comp account issuer";
328 if ( $self->paydate eq '' ) {
329 return "Expriation date required" unless $self->payby eq 'BILL';
332 $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
333 or return "Illegal expiration date";
334 if ( length($2) == 4 ) {
335 $self->paydate("$2-$1-01");
336 } elsif ( $2 > 97 ) { #should pry change to check for "this year"
337 $self->paydate("19$2-$1-01");
339 $self->paydate("20$2-$1-01");
343 if ( $self->payname eq '' ) {
344 $self->payname( $self->first. " ". $self->getfield('last') );
346 $self->payname =~ /^([\w \,\.\-\']+)$/
347 or return "Illegal billing name";
351 $self->tax =~ /^(Y?)$/ or return "Illegal tax";
354 $self->otaker(getotaker);
361 Returns all packages (see L<FS::cust_pkg>) for this customer.
367 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
370 =item ncancelled_pkgs
372 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
376 sub ncancelled_pkgs {
378 qsearch( 'cust_pkg', {
379 'custnum' => $self->custnum,
386 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
387 conjunction with the collect method.
389 The only currently available option is `time', which bills the customer as if
390 it were that time. It is specified as a UNIX timestamp; see
391 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
394 If there is an error, returns the error, otherwise returns false.
399 my($self,%options)=@_;
400 my($time) = $options{'time'} || $^T;
405 local $SIG{HUP} = 'IGNORE';
406 local $SIG{INT} = 'IGNORE';
407 local $SIG{QUIT} = 'IGNORE';
408 local $SIG{TERM} = 'IGNORE';
409 local $SIG{TSTP} = 'IGNORE';
411 # find the packages which are due for billing, find out how much they are
412 # & generate invoice database.
414 my($total_setup,$total_recur)=(0,0);
420 qsearch('cust_pkg',{'custnum'=> $self->getfield('custnum') } )
423 bless($cust_pkg,"FS::cust_pkg");
425 next if ( $cust_pkg->getfield('cancel') );
427 #? to avoid use of uninitialized value errors... ?
428 $cust_pkg->setfield('bill', '')
429 unless defined($cust_pkg->bill);
432 qsearchs('part_pkg',{'pkgpart'=> $cust_pkg->pkgpart } );
434 #so we don't modify cust_pkg record unnecessarily
435 my($cust_pkg_mod_flag)=0;
436 my(%hash)=$cust_pkg->hash;
437 my($old_cust_pkg)=create FS::cust_pkg(\%hash);
441 unless ( $cust_pkg->setup ) {
442 my($setup_prog)=$part_pkg->getfield('setup');
444 #$cpt->permit(); #what is necessary?
445 $cpt->share(qw($cust_pkg)); #can $cpt now use $cust_pkg methods?
446 $setup = $cpt->reval($setup_prog);
447 unless ( defined($setup) ) {
448 warn "Error reval-ing part_pkg->setup pkgpart ",
449 $part_pkg->pkgpart, ": $@";
451 $cust_pkg->setfield('setup',$time);
452 $cust_pkg_mod_flag=1;
459 if ( $part_pkg->getfield('freq') > 0 &&
460 ! $cust_pkg->getfield('susp') &&
461 ( $cust_pkg->getfield('bill') || 0 ) < $time
463 my($recur_prog)=$part_pkg->getfield('recur');
465 #$cpt->permit(); #what is necessary?
466 $cpt->share(qw($cust_pkg)); #can $cpt now use $cust_pkg methods?
467 $recur = $cpt->reval($recur_prog);
468 unless ( defined($recur) ) {
469 warn "Error reval-ing part_pkg->recur pkgpart ",
470 $part_pkg->pkgpart, ": $@";
472 #change this bit to use Date::Manip?
473 #$sdate=$cust_pkg->bill || time;
474 #$sdate=$cust_pkg->bill || $time;
475 $sdate=$cust_pkg->bill || $cust_pkg->setup || $time;
476 my($sec,$min,$hour,$mday,$mon,$year)=
477 (localtime($sdate) )[0,1,2,3,4,5];
478 $mon += $part_pkg->getfield('freq');
479 until ( $mon < 12 ) { $mon -= 12; $year++; }
480 $cust_pkg->setfield('bill',timelocal($sec,$min,$hour,$mday,$mon,$year));
481 $cust_pkg_mod_flag=1;
485 warn "setup is undefinded" unless defined($setup);
486 warn "recur is undefinded" unless defined($recur);
487 warn "cust_pkg bill is undefinded" unless defined($cust_pkg->bill);
489 if ($cust_pkg_mod_flag) {
490 $error=$cust_pkg->replace($old_cust_pkg);
492 warn "Error modifying pkgnum ", $cust_pkg->pkgnum, ": $error";
495 $setup=sprintf("%.2f",$setup);
496 $recur=sprintf("%.2f",$recur);
497 my($cust_bill_pkg)=create FS::cust_bill_pkg ({
498 'pkgnum' => $cust_pkg->pkgnum,
502 'edate' => $cust_pkg->bill,
504 push @cust_bill_pkg, $cust_bill_pkg;
505 $total_setup += $setup;
506 $total_recur += $recur;
512 my($charged)=sprintf("%.2f",$total_setup + $total_recur);
514 return '' if scalar(@cust_bill_pkg) == 0;
516 unless ( $self->getfield('tax') eq 'Y' ||
517 $self->getfield('tax') eq 'y' ||
518 $self->getfield('payby') eq 'COMP'
520 my($cust_main_county) = qsearchs('cust_main_county',{
521 'county' => $self->getfield('county'),
522 'state' => $self->getfield('state'),
524 my($tax) = sprintf("%.2f",
525 $charged * ( $cust_main_county->getfield('tax') / 100 )
527 $charged = sprintf("%.2f",$charged+$tax);
529 my($cust_bill_pkg)=create FS::cust_bill_pkg ({
536 push @cust_bill_pkg, $cust_bill_pkg;
539 my($cust_bill) = create FS::cust_bill ( {
540 'custnum' => $self->getfield('custnum'),
542 'charged' => $charged,
544 $error=$cust_bill->insert;
545 #shouldn't happen, but how else to handle this? (wrap me in eval, to catch
547 die "Error creating cust_bill record: $error!\n",
548 "Check updated but unbilled packages for customer", $self->custnum, "\n"
551 my($invnum)=$cust_bill->invnum;
553 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
554 $cust_bill_pkg->setfield('invnum',$invnum);
555 $error=$cust_bill_pkg->insert;
556 #shouldn't happen, but how else tohandle this?
557 die "Error creating cust_bill_pkg record: $error!\n",
558 "Check incomplete invoice ", $invnum, "\n"
565 =item collect OPTIONS
567 (Attempt to) collect money for this customer's outstanding invoices (see
568 L<FS::cust_bill>). Usually used after the bill method.
570 Depending on the value of `payby', this may print an invoice (`BILL'), charge
571 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
573 If there is an error, returns the error, otherwise returns false.
575 Currently available options are:
577 invoice_time - Use this time when deciding when to print invoices and
578 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>
579 for conversion functions.
581 batch_card - Set this true to batch cards (see L<cust_pay_batch>). By
582 default, cards are processed immediately, which will generate an error if
583 CyberCash is not installed.
585 report_badcard - Set this true if you want bad card transactions to
586 return an error. By default, they don't.
591 my($self,%options)=@_;
592 my($invoice_time) = $options{'invoice_time'} || $^T;
594 my($total_owed) = $self->balance;
595 return '' unless $total_owed > 0; #redundant?????
598 local $SIG{HUP} = 'IGNORE';
599 local $SIG{INT} = 'IGNORE';
600 local $SIG{QUIT} = 'IGNORE';
601 local $SIG{TERM} = 'IGNORE';
602 local $SIG{TSTP} = 'IGNORE';
604 foreach my $cust_bill ( qsearch('cust_bill', {
605 'custnum' => $self->getfield('custnum'),
608 bless($cust_bill,"FS::cust_bill");
610 #this has to be before next's
611 my($amount) = sprintf("%.2f", $total_owed < $cust_bill->owed
615 $total_owed = sprintf("%.2f",$total_owed-$amount);
617 next unless $cust_bill->owed > 0;
619 next if qsearchs('cust_pay_batch',{'invnum'=> $cust_bill->invnum });
621 #warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, total_owed $total_owed)";
623 next unless $amount > 0;
625 if ( $self->getfield('payby') eq 'BILL' ) {
628 my($since)=$invoice_time - ( $cust_bill->_date || 0 );
629 #warn "$invoice_time ", $cust_bill->_date, " $since";
630 if ( $since >= 0 #don't print future invoices
631 && ( $cust_bill->printed * 2592000 ) <= $since
634 open(LPR,"|$lpr") or die "Can't open $lpr: $!";
635 print LPR $cust_bill->print_text; #( date )
637 or die $! ? "Error closing $lpr: $!"
638 : "Exit status $? from $lpr";
640 my(%hash)=$cust_bill->hash;
642 my($new_cust_bill)=create FS::cust_bill(\%hash);
643 my($error)=$new_cust_bill->replace($cust_bill);
645 warn "Error updating $cust_bill->printed: $error";
650 } elsif ( $self->getfield('payby') eq 'COMP' ) {
651 my($cust_pay) = create FS::cust_pay ( {
652 'invnum' => $cust_bill->getfield('invnum'),
656 'payinfo' => $self->getfield('payinfo'),
659 my($error)=$cust_pay->insert;
660 return 'Error COMPing invnum #' . $cust_bill->getfield('invnum') .
661 ':' . $error if $error;
662 } elsif ( $self->getfield('payby') eq 'CARD' ) {
664 if ( $options{'batch_card'} ne 'yes' ) {
666 return "Real time card processing not enabled!" unless $processor;
668 if ( $processor =~ /cybercash/ ) {
670 #fix exp. date for cybercash
671 $self->getfield('paydate') =~ /^(\d+)\/\d*(\d{2})$/;
674 my($paybatch)= $cust_bill->getfield('invnum') .
675 '-' . time2str("%y%m%d%H%M%S",time);
677 my($payname)= $self->getfield('payname') ||
678 $self->getfield('first') . ' ' .$self->getfield('last');
680 my($address)= $self->getfield('address1');
681 $address .= ", " . $self->getfield('address2')
682 if $self->getfield('address2');
684 my($country) = $self->getfield('country') eq 'US' ?
685 'USA' : $self->getfield('country');
687 my(@full_xaction)=($xaction,
688 'Order-ID' => $paybatch,
689 'Amount' => "usd $amount",
690 'Card-Number' => $self->getfield('payinfo'),
691 'Card-Name' => $payname,
692 'Card-Address' => $address,
693 'Card-City' => $self->getfield('city'),
694 'Card-State' => $self->getfield('state'),
695 'Card-Zip' => $self->getfield('zip'),
696 'Card-Country' => $country,
701 if ( $processor eq 'cybercash2' ) {
702 $^W=0; #CCLib isn't -w safe, ugh!
703 %result = &CCLib::sendmserver(@full_xaction);
705 } elsif ( $processor eq 'cybercash3.2' ) {
706 %result = &CCMckDirectLib3_2::SendCC2_1Server(@full_xaction);
708 return "Unkonwn real-time processor $processor\n";
711 #if ( $result{'MActionCode'} == 7 ) { #cybercash smps v.1.1.3
712 #if ( $result{'action-code'} == 7 ) { #cybercash smps v.2.1
713 if ( $result{'MStatus'} eq 'success' ) { #cybercash smps v.2 or 3
714 my($cust_pay) = create FS::cust_pay ( {
715 'invnum' => $cust_bill->getfield('invnum'),
719 'payinfo' => $self->getfield('payinfo'),
720 'paybatch' => "$processor:$paybatch",
722 my($error)=$cust_pay->insert;
723 return 'Error applying payment, invnum #' .
724 $cust_bill->getfield('invnum') . ':' . $error if $error;
725 } elsif ( $result{'Mstatus'} ne 'failure-bad-money'
726 || $options{'report_badcard'} ) {
727 return 'Cybercash error, invnum #' .
728 $cust_bill->getfield('invnum') . ':' . $result{'MErrMsg'};
734 return "Unkonwn real-time processor $processor\n";
739 # my($cust_pay_batch) = create FS::cust_pay_batch ( {
740 my($cust_pay_batch) = new FS::Record ('cust_pay_batch', {
741 'invnum' => $cust_bill->getfield('invnum'),
742 'custnum' => $self->getfield('custnum'),
743 'last' => $self->getfield('last'),
744 'first' => $self->getfield('first'),
745 'address1' => $self->getfield('address1'),
746 'address2' => $self->getfield('address2'),
747 'city' => $self->getfield('city'),
748 'state' => $self->getfield('state'),
749 'zip' => $self->getfield('zip'),
750 'country' => $self->getfield('country'),
752 'cardnum' => $self->getfield('payinfo'),
753 'exp' => $self->getfield('paydate'),
754 'payname' => $self->getfield('payname'),
757 # my($error)=$cust_pay_batch->insert;
758 my($error)=$cust_pay_batch->add;
759 return "Error adding to cust_pay_batch: $error" if $error;
764 return "Unknown payment type ".$self->getfield('payby');
774 Returns the total owed for this customer on all invoices
775 (see L<FS::cust_bill>).
783 foreach $cust_bill ( qsearch('cust_bill', {
784 'custnum' => $self->getfield('custnum'),
786 $total_bill += $cust_bill->getfield('owed');
788 sprintf("%.2f",$total_bill);
793 Returns the total credits (see L<FS::cust_credit>) for this customer.
799 my($total_credit) = 0;
801 foreach $cust_credit ( qsearch('cust_credit', {
802 'custnum' => $self->getfield('custnum'),
804 $total_credit += $cust_credit->getfield('credited');
806 sprintf("%.2f",$total_credit);
811 Returns the balance for this customer (total owed minus total credited).
817 sprintf("%.2f",$self->total_owed - $self->total_credited);
826 It doesn't properly override FS::Record yet.
828 hfields should be removed.
830 Bill and collect options should probably be passed as references instead of a
833 CyberCash v2 forces us to define some variables in package main.
837 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
838 L<FS::cust_pay_batch>, L<FS::agent>, L<FS::part_referral>,
839 L<FS::cust_main_county>, L<FS::UID>, schema.html from the base documentation.
843 ivan@voicenet.com 97-jul-28
845 Changed to standard Business::CreditCard
847 EXPORT_OK FS::Record's hfields
848 removed unique calls and locking (not needed here now)
849 wrapped the (now) optional fields in if statements in sub check (notyetdone!)
850 ivan@sisd.com 97-nov-12
852 updated paydate with SQL-type date info ivan@sisd.com 98-mar-5
854 Added export of datasrc from UID.pm for Pg6.3
855 changed 'day' to 'daytime' because Pg6.3 reserves the day word
856 bmccane@maxbaud.net 98-apr-3
858 in ->create, s/svc_acct/cust_main/, now it should actually eliminate the
859 warnings it was meant to ivan@sisd.com 98-jul-16
861 don't require a phone number and allow '/' in company names
862 ivan@sisd.com 98-jul-18
864 use ut_ and rewrite &check, &*_pkgs ivan@sisd.com 98-sep-5
866 pod, merge with FS::Bill (about time!), total_owed, total_credited and balance
867 methods, cleaned collect method, source modifications no longer necessary to
868 enable cybercash, cybercash v3 support, don't need to import
869 FS::UID::{datasrc,checkruid} ivan@sisd.com 98-sep-19-21
871 $Log: cust_main.pm,v $
872 Revision 1.4 1998-11-15 05:30:48 ivan
873 bugfix for new config layout
875 Revision 1.3 1998/11/13 09:56:54 ivan
876 change configuration file layout to support multiple distinct databases (with
877 own set of config files, export, etc.)
879 Revision 1.2 1998/11/07 10:24:25 ivan
880 don't use depriciated FS::Bill and FS::Invoice, other miscellania