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;
24 use FS::part_referral;
25 use FS::cust_main_county;
28 @ISA = qw(FS::Record Exporter);
29 @EXPORT_OK = qw(hfields);
31 #ask FS::UID to run this stuff for us later
32 $FS::UID::callback{'FS::cust_main'} = sub {
34 $lpr = $conf->config('lpr');
36 if ( $conf->exists('cybercash3.2') ) {
38 #qw($MCKversion %Config InitConfig CCError CCDebug CCDebug2);
39 require CCMckDirectLib3_2;
41 require CCMckErrno3_2;
42 #qw(MCKGetErrorMessage $E_NoErr);
43 import CCMckErrno3_2 qw($E_NoErr);
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"
53 my($errmsg) = &CCMckErrno3_2::MCKGetErrorMessage($status);
54 die "CCMckLib3_2::InitConfig fatal error: $errmsg\n";
56 $processor='cybercash3.2';
57 } elsif ( $conf->exists('cybercash2') ) {
60 ( $main::paymentserverhost,
61 $main::paymentserverport,
62 $main::paymentserversecret,
64 ) = $conf->config('cybercash2');
65 $processor='cybercash2';
71 FS::cust_main - Object methods for cust_main records
77 $record = create FS::cust_main \%hash;
78 $record = create FS::cust_main { 'column' => 'value' };
80 $error = $record->insert;
82 $error = $new_record->replace($old_record);
84 $error = $record->delete;
86 $error = $record->check;
88 @cust_pkg = $record->all_pkgs;
90 @cust_pkg = $record->ncancelled_pkgs;
92 $error = $record->bill;
93 $error = $record->bill %options;
94 $error = $record->bill 'time' => $time;
96 $error = $record->collect;
97 $error = $record->collect %options;
98 $error = $record->collect 'invoice_time' => $time,
99 'batch_card' => 'yes',
100 'report_badcard' => 'yes',
105 An FS::cust_main object represents a customer. FS::cust_main inherits from
106 FS::Record. The following fields are currently supported:
110 =item custnum - primary key (assigned automatically for new customers)
112 =item agentnum - agent (see L<FS::agent>)
114 =item refnum - referral (see L<FS::part_referral>)
120 =item ss - social security number (optional)
122 =item company - (optional)
126 =item address2 - (optional)
130 =item county - (optional, see L<FS::cust_main_county>)
132 =item state - (see L<FS::cust_main_county>)
136 =item country - (see L<FS::cust_main_county>)
138 =item daytime - phone (optional)
140 =item night - phone (optional)
142 =item payby - `CARD' (credit cards), `BILL' (billing), or `COMP' (free)
144 =item payinfo - card number, P.O.#, or comp issuer (4-8 lowercase alphanumerics; think username)
146 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
148 =item payname - name on card or billing name
150 =item tax - tax exempt, empty or `Y'
152 =item otaker - order taker (assigned automatically, see L<FS::UID>)
162 Creates a new customer. To add the customer to the database, see L<"insert">.
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.
170 my($proto,$hashref)=@_;
172 #now in FS::Record::new
174 #foreach $field (fields('cust_main')) {
175 # $hashref->{$field}='' unless defined $hashref->{$field};
178 $proto->new('cust_main',$hashref);
183 Adds this customer to the database. If there is an error, returns the error,
184 otherwise returns false.
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';
204 Currently unimplemented. Maybe cancel all of this customer's
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?)
212 # Usage: $error = $record -> delete;
214 return "Can't (yet?) delete customers.";
220 =item replace OLD_RECORD
222 Replaces the OLD_RECORD with this one in the database. If there is an error,
223 returns the error, otherwise returns false.
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');
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
247 return "Not a cust_main record!" unless $self->table eq "cust_main";
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')
262 return $error if $error;
264 return "Unknown agent"
265 unless qsearchs('agent',{'agentnum'=>$self->agentnum});
267 return "Unknown referral"
268 unless qsearchs('part_referral',{'refnum'=>$self->refnum});
270 $self->getfield('last') =~ /^([\w \,\.\-\']+)$/ or return "Illegal last name";
271 $self->setfield('last',$1);
273 $self->first =~ /^([\w \,\.\-\']+)$/ or return "Illegal first name";
276 if ( $self->ss eq '' ) {
281 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
282 or return "Illegal social security number";
283 $self->ss("$1-$2-$3");
286 $self->country =~ /^(\w\w)$/ or return "Illegal country";
288 unless ( qsearchs('cust_main_county', {
289 'country' => $self->country,
292 return "Unknown state/county/country"
293 #" state ". $self->state. " county ". $self->county. " country ". $self->country
294 unless qsearchs('cust_main_county',{
295 'state' => $self->state,
296 'county' => $self->county,
297 'country' => $self->country,
301 $self->zip =~ /^([\w\-]{10})$/ or return "Illegal zip";
304 $self->payby =~ /^(CARD|BILL|COMP)$/ or return "Illegal payby";
307 if ( $self->payby eq 'CARD' ) {
309 my $payinfo = $self->payinfo;
311 $payinfo =~ /^(\d{13,16})$/
312 or return "Illegal credit card number";
314 $self->payinfo($payinfo);
315 validate($payinfo) or return "Illegal credit card number";
316 my $type = cardtype($payinfo);
317 return "Unknown credit card type"
318 unless ( $type =~ /^VISA/ ||
319 $type =~ /^MasterCard/ ||
320 $type =~ /^American Express/ ||
321 $type =~ /^Discover/ );
323 } elsif ( $self->payby eq 'BILL' ) {
325 $self->payinfo =~ /^([\w \-]*)$/ or return "Illegal P.O. number";
328 } elsif ( $self->payby eq 'COMP' ) {
330 $self->payinfo =~ /^(\w{2,8})$/ or return "Illegal comp account issuer";
335 if ( $self->paydate eq '' ) {
336 return "Expriation date required" unless $self->payby eq 'BILL';
339 $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
340 or return "Illegal expiration date";
341 if ( length($2) == 4 ) {
342 $self->paydate("$2-$1-01");
343 } elsif ( $2 > 97 ) { #should pry change to check for "this year"
344 $self->paydate("19$2-$1-01");
346 $self->paydate("20$2-$1-01");
350 if ( $self->payname eq '' ) {
351 $self->payname( $self->first. " ". $self->getfield('last') );
353 $self->payname =~ /^([\w \,\.\-\']+)$/
354 or return "Illegal billing name";
358 $self->tax =~ /^(Y?)$/ or return "Illegal tax";
361 $self->otaker(getotaker);
368 Returns all packages (see L<FS::cust_pkg>) for this customer.
374 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
377 =item ncancelled_pkgs
379 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
383 sub ncancelled_pkgs {
385 qsearch( 'cust_pkg', {
386 'custnum' => $self->custnum,
393 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
394 conjunction with the collect method.
396 The only currently available option is `time', which bills the customer as if
397 it were that time. It is specified as a UNIX timestamp; see
398 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
401 If there is an error, returns the error, otherwise returns false.
406 my($self,%options)=@_;
407 my($time) = $options{'time'} || $^T;
412 local $SIG{HUP} = 'IGNORE';
413 local $SIG{INT} = 'IGNORE';
414 local $SIG{QUIT} = 'IGNORE';
415 local $SIG{TERM} = 'IGNORE';
416 local $SIG{TSTP} = 'IGNORE';
418 # find the packages which are due for billing, find out how much they are
419 # & generate invoice database.
421 my($total_setup,$total_recur)=(0,0);
427 qsearch('cust_pkg',{'custnum'=> $self->getfield('custnum') } )
430 bless($cust_pkg,"FS::cust_pkg");
432 next if ( $cust_pkg->getfield('cancel') );
434 #? to avoid use of uninitialized value errors... ?
435 $cust_pkg->setfield('bill', '')
436 unless defined($cust_pkg->bill);
439 qsearchs('part_pkg',{'pkgpart'=> $cust_pkg->pkgpart } );
441 #so we don't modify cust_pkg record unnecessarily
442 my($cust_pkg_mod_flag)=0;
443 my(%hash)=$cust_pkg->hash;
444 my($old_cust_pkg)=create FS::cust_pkg(\%hash);
448 unless ( $cust_pkg->setup ) {
449 my($setup_prog)=$part_pkg->getfield('setup');
451 #$cpt->permit(); #what is necessary?
452 $cpt->share(qw($cust_pkg)); #can $cpt now use $cust_pkg methods?
453 $setup = $cpt->reval($setup_prog);
454 unless ( defined($setup) ) {
455 warn "Error reval-ing part_pkg->setup pkgpart ",
456 $part_pkg->pkgpart, ": $@";
458 $cust_pkg->setfield('setup',$time);
459 $cust_pkg_mod_flag=1;
466 if ( $part_pkg->getfield('freq') > 0 &&
467 ! $cust_pkg->getfield('susp') &&
468 ( $cust_pkg->getfield('bill') || 0 ) < $time
470 my($recur_prog)=$part_pkg->getfield('recur');
472 #$cpt->permit(); #what is necessary?
473 $cpt->share(qw($cust_pkg)); #can $cpt now use $cust_pkg methods?
474 $recur = $cpt->reval($recur_prog);
475 unless ( defined($recur) ) {
476 warn "Error reval-ing part_pkg->recur pkgpart ",
477 $part_pkg->pkgpart, ": $@";
479 #change this bit to use Date::Manip?
480 #$sdate=$cust_pkg->bill || time;
481 #$sdate=$cust_pkg->bill || $time;
482 $sdate=$cust_pkg->bill || $cust_pkg->setup || $time;
483 my($sec,$min,$hour,$mday,$mon,$year)=
484 (localtime($sdate) )[0,1,2,3,4,5];
485 $mon += $part_pkg->getfield('freq');
486 until ( $mon < 12 ) { $mon -= 12; $year++; }
487 $cust_pkg->setfield('bill',timelocal($sec,$min,$hour,$mday,$mon,$year));
488 $cust_pkg_mod_flag=1;
492 warn "setup is undefinded" unless defined($setup);
493 warn "recur is undefinded" unless defined($recur);
494 warn "cust_pkg bill is undefinded" unless defined($cust_pkg->bill);
496 if ($cust_pkg_mod_flag) {
497 $error=$cust_pkg->replace($old_cust_pkg);
499 warn "Error modifying pkgnum ", $cust_pkg->pkgnum, ": $error";
502 $setup=sprintf("%.2f",$setup);
503 $recur=sprintf("%.2f",$recur);
504 my($cust_bill_pkg)=create FS::cust_bill_pkg ({
505 'pkgnum' => $cust_pkg->pkgnum,
509 'edate' => $cust_pkg->bill,
511 push @cust_bill_pkg, $cust_bill_pkg;
512 $total_setup += $setup;
513 $total_recur += $recur;
519 my($charged)=sprintf("%.2f",$total_setup + $total_recur);
521 return '' if scalar(@cust_bill_pkg) == 0;
523 unless ( $self->getfield('tax') eq 'Y' ||
524 $self->getfield('tax') eq 'y' ||
525 $self->getfield('payby') eq 'COMP'
527 my($cust_main_county) = qsearchs('cust_main_county',{
528 'county' => $self->getfield('county'),
529 'state' => $self->getfield('state'),
531 my($tax) = sprintf("%.2f",
532 $charged * ( $cust_main_county->getfield('tax') / 100 )
534 $charged = sprintf("%.2f",$charged+$tax);
536 my($cust_bill_pkg)=create FS::cust_bill_pkg ({
543 push @cust_bill_pkg, $cust_bill_pkg;
546 my($cust_bill) = create FS::cust_bill ( {
547 'custnum' => $self->getfield('custnum'),
549 'charged' => $charged,
551 $error=$cust_bill->insert;
552 #shouldn't happen, but how else to handle this? (wrap me in eval, to catch
554 die "Error creating cust_bill record: $error!\n",
555 "Check updated but unbilled packages for customer", $self->custnum, "\n"
558 my($invnum)=$cust_bill->invnum;
560 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
561 $cust_bill_pkg->setfield('invnum',$invnum);
562 $error=$cust_bill_pkg->insert;
563 #shouldn't happen, but how else tohandle this?
564 die "Error creating cust_bill_pkg record: $error!\n",
565 "Check incomplete invoice ", $invnum, "\n"
572 =item collect OPTIONS
574 (Attempt to) collect money for this customer's outstanding invoices (see
575 L<FS::cust_bill>). Usually used after the bill method.
577 Depending on the value of `payby', this may print an invoice (`BILL'), charge
578 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
580 If there is an error, returns the error, otherwise returns false.
582 Currently available options are:
584 invoice_time - Use this time when deciding when to print invoices and
585 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>
586 for conversion functions.
588 batch_card - Set this true to batch cards (see L<cust_pay_batch>). By
589 default, cards are processed immediately, which will generate an error if
590 CyberCash is not installed.
592 report_badcard - Set this true if you want bad card transactions to
593 return an error. By default, they don't.
598 my($self,%options)=@_;
599 my($invoice_time) = $options{'invoice_time'} || $^T;
601 my($total_owed) = $self->balance;
602 return '' unless $total_owed > 0; #redundant?????
605 local $SIG{HUP} = 'IGNORE';
606 local $SIG{INT} = 'IGNORE';
607 local $SIG{QUIT} = 'IGNORE';
608 local $SIG{TERM} = 'IGNORE';
609 local $SIG{TSTP} = 'IGNORE';
611 foreach my $cust_bill ( qsearch('cust_bill', {
612 'custnum' => $self->getfield('custnum'),
615 bless($cust_bill,"FS::cust_bill");
617 #this has to be before next's
618 my($amount) = sprintf("%.2f", $total_owed < $cust_bill->owed
622 $total_owed = sprintf("%.2f",$total_owed-$amount);
624 next unless $cust_bill->owed > 0;
626 next if qsearchs('cust_pay_batch',{'invnum'=> $cust_bill->invnum });
628 #warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, total_owed $total_owed)";
630 next unless $amount > 0;
632 if ( $self->getfield('payby') eq 'BILL' ) {
635 my($since)=$invoice_time - ( $cust_bill->_date || 0 );
636 #warn "$invoice_time ", $cust_bill->_date, " $since";
637 if ( $since >= 0 #don't print future invoices
638 && ( $cust_bill->printed * 2592000 ) <= $since
641 open(LPR,"|$lpr") or die "Can't open $lpr: $!";
642 print LPR $cust_bill->print_text; #( date )
644 or die $! ? "Error closing $lpr: $!"
645 : "Exit status $? from $lpr";
647 my(%hash)=$cust_bill->hash;
649 my($new_cust_bill)=create FS::cust_bill(\%hash);
650 my($error)=$new_cust_bill->replace($cust_bill);
652 warn "Error updating $cust_bill->printed: $error";
657 } elsif ( $self->getfield('payby') eq 'COMP' ) {
658 my($cust_pay) = create FS::cust_pay ( {
659 'invnum' => $cust_bill->getfield('invnum'),
663 'payinfo' => $self->getfield('payinfo'),
666 my($error)=$cust_pay->insert;
667 return 'Error COMPing invnum #' . $cust_bill->getfield('invnum') .
668 ':' . $error if $error;
669 } elsif ( $self->getfield('payby') eq 'CARD' ) {
671 if ( $options{'batch_card'} ne 'yes' ) {
673 return "Real time card processing not enabled!" unless $processor;
675 if ( $processor =~ /cybercash/ ) {
677 #fix exp. date for cybercash
678 $self->getfield('paydate') =~ /^(\d+)\/\d*(\d{2})$/;
681 my($paybatch)= $cust_bill->getfield('invnum') .
682 '-' . time2str("%y%m%d%H%M%S",time);
684 my($payname)= $self->getfield('payname') ||
685 $self->getfield('first') . ' ' .$self->getfield('last');
687 my($address)= $self->getfield('address1');
688 $address .= ", " . $self->getfield('address2')
689 if $self->getfield('address2');
691 my($country) = $self->getfield('country') eq 'US' ?
692 'USA' : $self->getfield('country');
694 my(@full_xaction)=($xaction,
695 'Order-ID' => $paybatch,
696 'Amount' => "usd $amount",
697 'Card-Number' => $self->getfield('payinfo'),
698 'Card-Name' => $payname,
699 'Card-Address' => $address,
700 'Card-City' => $self->getfield('city'),
701 'Card-State' => $self->getfield('state'),
702 'Card-Zip' => $self->getfield('zip'),
703 'Card-Country' => $country,
708 if ( $processor eq 'cybercash2' ) {
709 $^W=0; #CCLib isn't -w safe, ugh!
710 %result = &CCLib::sendmserver(@full_xaction);
712 } elsif ( $processor eq 'cybercash3.2' ) {
713 %result = &CCMckDirectLib3_2::SendCC2_1Server(@full_xaction);
715 return "Unkonwn real-time processor $processor\n";
718 #if ( $result{'MActionCode'} == 7 ) { #cybercash smps v.1.1.3
719 #if ( $result{'action-code'} == 7 ) { #cybercash smps v.2.1
720 if ( $result{'MStatus'} eq 'success' ) { #cybercash smps v.2 or 3
721 my($cust_pay) = create FS::cust_pay ( {
722 'invnum' => $cust_bill->getfield('invnum'),
726 'payinfo' => $self->getfield('payinfo'),
727 'paybatch' => "$processor:$paybatch",
729 my($error)=$cust_pay->insert;
730 return 'Error applying payment, invnum #' .
731 $cust_bill->getfield('invnum') . ':' . $error if $error;
732 } elsif ( $result{'Mstatus'} ne 'failure-bad-money'
733 || $options{'report_badcard'} ) {
734 return 'Cybercash error, invnum #' .
735 $cust_bill->getfield('invnum') . ':' . $result{'MErrMsg'};
741 return "Unkonwn real-time processor $processor\n";
746 # my($cust_pay_batch) = create FS::cust_pay_batch ( {
747 my($cust_pay_batch) = new FS::Record ('cust_pay_batch', {
748 'invnum' => $cust_bill->getfield('invnum'),
749 'custnum' => $self->getfield('custnum'),
750 'last' => $self->getfield('last'),
751 'first' => $self->getfield('first'),
752 'address1' => $self->getfield('address1'),
753 'address2' => $self->getfield('address2'),
754 'city' => $self->getfield('city'),
755 'state' => $self->getfield('state'),
756 'zip' => $self->getfield('zip'),
757 'country' => $self->getfield('country'),
759 'cardnum' => $self->getfield('payinfo'),
760 'exp' => $self->getfield('paydate'),
761 'payname' => $self->getfield('payname'),
764 # my($error)=$cust_pay_batch->insert;
765 my($error)=$cust_pay_batch->add;
766 return "Error adding to cust_pay_batch: $error" if $error;
771 return "Unknown payment type ".$self->getfield('payby');
781 Returns the total owed for this customer on all invoices
782 (see L<FS::cust_bill>).
790 foreach $cust_bill ( qsearch('cust_bill', {
791 'custnum' => $self->getfield('custnum'),
793 $total_bill += $cust_bill->getfield('owed');
795 sprintf("%.2f",$total_bill);
800 Returns the total credits (see L<FS::cust_credit>) for this customer.
806 my($total_credit) = 0;
808 foreach $cust_credit ( qsearch('cust_credit', {
809 'custnum' => $self->getfield('custnum'),
811 $total_credit += $cust_credit->getfield('credited');
813 sprintf("%.2f",$total_credit);
818 Returns the balance for this customer (total owed minus total credited).
824 sprintf("%.2f",$self->total_owed - $self->total_credited);
833 It doesn't properly override FS::Record yet.
835 hfields should be removed.
837 Bill and collect options should probably be passed as references instead of a
840 CyberCash v2 forces us to define some variables in package main.
844 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
845 L<FS::cust_pay_batch>, L<FS::agent>, L<FS::part_referral>,
846 L<FS::cust_main_county>, L<FS::UID>, schema.html from the base documentation.
850 ivan@voicenet.com 97-jul-28
852 Changed to standard Business::CreditCard
854 EXPORT_OK FS::Record's hfields
855 removed unique calls and locking (not needed here now)
856 wrapped the (now) optional fields in if statements in sub check (notyetdone!)
857 ivan@sisd.com 97-nov-12
859 updated paydate with SQL-type date info ivan@sisd.com 98-mar-5
861 Added export of datasrc from UID.pm for Pg6.3
862 changed 'day' to 'daytime' because Pg6.3 reserves the day word
863 bmccane@maxbaud.net 98-apr-3
865 in ->create, s/svc_acct/cust_main/, now it should actually eliminate the
866 warnings it was meant to ivan@sisd.com 98-jul-16
868 don't require a phone number and allow '/' in company names
869 ivan@sisd.com 98-jul-18
871 use ut_ and rewrite &check, &*_pkgs ivan@sisd.com 98-sep-5
873 pod, merge with FS::Bill (about time!), total_owed, total_credited and balance
874 methods, cleaned collect method, source modifications no longer necessary to
875 enable cybercash, cybercash v3 support, don't need to import
876 FS::UID::{datasrc,checkruid} ivan@sisd.com 98-sep-19-21
878 $Log: cust_main.pm,v $
879 Revision 1.6 1998-11-18 09:01:42 ivan
882 Revision 1.5 1998/11/15 11:23:14 ivan
883 use FS::table_name for all searches to eliminate warnings,
884 emit state/county when they don't match
886 Revision 1.4 1998/11/15 05:30:48 ivan
887 bugfix for new config layout
889 Revision 1.3 1998/11/13 09:56:54 ivan
890 change configuration file layout to support multiple distinct databases (with
891 own set of config files, export, etc.)
893 Revision 1.2 1998/11/07 10:24:25 ivan
894 don't use depriciated FS::Bill and FS::Invoice, other miscellania