5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6 FS::cust_main::NationalID
7 FS::cust_main::Billing FS::cust_main::Billing_Realtime
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
12 FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
17 use vars qw( $DEBUG $me $conf
20 $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
31 use Digest::MD5 qw(md5_base64);
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
37 use FS::UID qw( getotaker dbh driver_name );
38 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
39 use FS::Misc qw( generate_email send_email generate_ps do_print );
40 use FS::Msgcat qw(gettext);
47 use FS::cust_bill_void;
48 use FS::legacy_cust_bill;
50 use FS::cust_pay_pending;
51 use FS::cust_pay_void;
52 use FS::cust_pay_batch;
55 use FS::part_referral;
56 use FS::cust_main_county;
57 use FS::cust_location;
59 use FS::cust_main_exemption;
60 use FS::cust_tax_adjustment;
61 use FS::cust_tax_location;
63 use FS::cust_main_invoice;
65 use FS::prepay_credit;
71 use FS::payment_gateway;
72 use FS::agent_payment_gateway;
74 use FS::cust_main_note;
75 use FS::cust_attachment;
78 use FS::upgrade_journal;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 $me = '[FS::cust_main]';
87 $ignore_expired_card = 0;
88 $ignore_banned_card = 0;
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub {
99 install_callback FS::UID sub {
100 $conf = new FS::Conf;
101 #yes, need it for stuff below (prolly should be cached)
106 my ( $hashref, $cache ) = @_;
107 if ( exists $hashref->{'pkgnum'} ) {
108 #@{ $self->{'_pkgnum'} } = ();
109 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110 $self->{'_pkgnum'} = $subcache;
111 #push @{ $self->{'_pkgnum'} },
112 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
118 FS::cust_main - Object methods for cust_main records
124 $record = new FS::cust_main \%hash;
125 $record = new FS::cust_main { 'column' => 'value' };
127 $error = $record->insert;
129 $error = $new_record->replace($old_record);
131 $error = $record->delete;
133 $error = $record->check;
135 @cust_pkg = $record->all_pkgs;
137 @cust_pkg = $record->ncancelled_pkgs;
139 @cust_pkg = $record->suspended_pkgs;
141 $error = $record->bill;
142 $error = $record->bill %options;
143 $error = $record->bill 'time' => $time;
145 $error = $record->collect;
146 $error = $record->collect %options;
147 $error = $record->collect 'invoice_time' => $time,
152 An FS::cust_main object represents a customer. FS::cust_main inherits from
153 FS::Record. The following fields are currently supported:
159 Primary key (assigned automatically for new customers)
163 Agent (see L<FS::agent>)
167 Advertising source (see L<FS::part_referral>)
179 Cocial security number (optional)
203 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
207 Payment Information (See L<FS::payinfo_Mixin> for data format)
211 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
215 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
219 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
223 Start date month (maestro/solo cards only)
227 Start date year (maestro/solo cards only)
231 Issue number (maestro/solo cards only)
235 Name on card or billing name
239 IP address from which payment information was received
243 Tax exempt, empty or `Y'
247 Order taker (see L<FS::access_user>)
253 =item referral_custnum
255 Referring customer number
259 Enable individual CDR spooling, empty or `Y'
263 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
267 Discourage individual CDR printing, empty or `Y'
271 Allow self-service editing of ticket subjects, empty or 'Y'
273 =item calling_list_exempt
275 Do not call, empty or 'Y'
277 =item invoice_ship_address
279 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
289 Creates a new customer. To add the customer to the database, see L<"insert">.
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to. You can ask the object for a copy with the I<hash> method.
296 sub table { 'cust_main'; }
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
300 Adds this customer to the database. If there is an error, returns the error,
301 otherwise returns false.
303 Usually the customer's location will not yet exist in the database, and
304 the C<bill_location> and C<ship_location> pseudo-fields must be set to
305 uninserted L<FS::cust_location> objects. These will be inserted and linked
306 (in both directions) to the new customer record. If they're references
307 to the same object, they will become the same location.
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back. Passing an empty
312 hash reference is equivalent to not supplying this parameter. There should be
313 a better explanation of this, but until then, here's an example:
316 tie %hash, 'Tie::RefHash'; #this part is important
318 $cust_pkg => [ $svc_acct ],
321 $cust_main->insert( \%hash );
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">). Errors return as
325 expected and rollback the entire transaction; it is not necessary to call
326 check_invoicing_list first. The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct. Here's an example:
330 $cust_main->insert( {}, [ $email, 'POST' ] );
332 Currently available options are: I<depend_jobnum>, I<noexport>,
333 I<tax_exemption> and I<prospectnum>.
335 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
336 on the supplied jobnum (they will not run until the specific job completes).
337 This can be used to defer provisioning until some action completes (such
338 as running the customer's credit card successfully).
340 The I<noexport> option is deprecated. If I<noexport> is set true, no
341 provisioning jobs (exports) are scheduled. (You can schedule them later with
342 the B<reexport> method.)
344 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
345 of tax names and exemption numbers. FS::cust_main_exemption records will be
346 created and inserted.
348 If I<prospectnum> is set, moves contacts and locations from that prospect.
354 my $cust_pkgs = @_ ? shift : {};
355 my $invoicing_list = @_ ? shift : '';
357 warn "$me insert called with options ".
358 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
361 local $SIG{HUP} = 'IGNORE';
362 local $SIG{INT} = 'IGNORE';
363 local $SIG{QUIT} = 'IGNORE';
364 local $SIG{TERM} = 'IGNORE';
365 local $SIG{TSTP} = 'IGNORE';
366 local $SIG{PIPE} = 'IGNORE';
368 my $oldAutoCommit = $FS::UID::AutoCommit;
369 local $FS::UID::AutoCommit = 0;
372 my $prepay_identifier = '';
373 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
375 if ( $self->payby eq 'PREPAY' ) {
377 $self->payby('BILL');
378 $prepay_identifier = $self->payinfo;
381 warn " looking up prepaid card $prepay_identifier\n"
384 my $error = $self->get_prepay( $prepay_identifier,
385 'amount_ref' => \$amount,
386 'seconds_ref' => \$seconds,
387 'upbytes_ref' => \$upbytes,
388 'downbytes_ref' => \$downbytes,
389 'totalbytes_ref' => \$totalbytes,
392 $dbh->rollback if $oldAutoCommit;
393 #return "error applying prepaid card (transaction rolled back): $error";
397 $payby = 'PREP' if $amount;
399 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
402 $self->payby('BILL');
403 $amount = $self->paid;
408 foreach my $l (qw(bill_location ship_location)) {
410 my $loc = delete $self->hashref->{$l} or return "$l not set";
412 if ( !$loc->locationnum ) {
413 # warn the location that we're going to insert it with no custnum
414 $loc->set(custnum_pending => 1);
415 warn " inserting $l\n"
417 my $error = $loc->insert;
419 $dbh->rollback if $oldAutoCommit;
420 my $label = $l eq 'ship_location' ? 'service' : 'billing';
421 return "$error (in $label location)";
424 } elsif ( $loc->prospectnum ) {
426 $loc->prospectnum('');
427 $loc->set(custnum_pending => 1);
428 my $error = $loc->replace;
430 $dbh->rollback if $oldAutoCommit;
431 my $label = $l eq 'ship_location' ? 'service' : 'billing';
432 return "$error (moving $label location)";
435 } elsif ( ($loc->custnum || 0) > 0 ) {
436 # then it somehow belongs to another customer--shouldn't happen
437 $dbh->rollback if $oldAutoCommit;
438 return "$l belongs to customer ".$loc->custnum;
440 # else it already belongs to this customer
441 # (happens when ship_location is identical to bill_location)
443 $self->set($l.'num', $loc->locationnum);
445 if ( $self->get($l.'num') eq '' ) {
446 $dbh->rollback if $oldAutoCommit;
451 $self->_loc_change();
453 warn " inserting $self\n"
456 $self->signupdate(time) unless $self->signupdate;
458 $self->auto_agent_custid()
459 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
461 my $error = $self->SUPER::insert;
463 $dbh->rollback if $oldAutoCommit;
464 #return "inserting cust_main record (transaction rolled back): $error";
468 # now set cust_location.custnum
469 foreach my $l (qw(bill_location ship_location)) {
470 warn " setting $l.custnum\n"
473 unless ( $loc->custnum ) {
474 $loc->set(custnum => $self->custnum);
475 $error ||= $loc->replace;
479 $dbh->rollback if $oldAutoCommit;
480 return "error setting $l custnum: $error";
484 warn " setting invoicing list\n"
487 if ( $invoicing_list ) {
488 $error = $self->check_invoicing_list( $invoicing_list );
490 $dbh->rollback if $oldAutoCommit;
491 #return "checking invoicing_list (transaction rolled back): $error";
494 $self->invoicing_list( $invoicing_list );
497 warn " setting customer tags\n"
500 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
501 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
502 'custnum' => $self->custnum };
503 my $error = $cust_tag->insert;
505 $dbh->rollback if $oldAutoCommit;
510 my $prospectnum = delete $options{'prospectnum'};
511 if ( $prospectnum ) {
513 warn " moving contacts and locations from prospect $prospectnum\n"
517 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
518 unless ( $prospect_main ) {
519 $dbh->rollback if $oldAutoCommit;
520 return "Unknown prospectnum $prospectnum";
522 $prospect_main->custnum($self->custnum);
523 $prospect_main->disabled('Y');
524 my $error = $prospect_main->replace;
526 $dbh->rollback if $oldAutoCommit;
530 my @contact = $prospect_main->contact;
531 my @cust_location = $prospect_main->cust_location;
532 my @qual = $prospect_main->qual;
534 foreach my $r ( @contact, @cust_location, @qual ) {
536 $r->custnum($self->custnum);
537 my $error = $r->replace;
539 $dbh->rollback if $oldAutoCommit;
546 warn " setting cust_main_exemption\n"
549 my $tax_exemption = delete $options{'tax_exemption'};
550 if ( $tax_exemption ) {
552 $tax_exemption = { map { $_ => '' } @$tax_exemption }
553 if ref($tax_exemption) eq 'ARRAY';
555 foreach my $taxname ( keys %$tax_exemption ) {
556 my $cust_main_exemption = new FS::cust_main_exemption {
557 'custnum' => $self->custnum,
558 'taxname' => $taxname,
559 'exempt_number' => $tax_exemption->{$taxname},
561 my $error = $cust_main_exemption->insert;
563 $dbh->rollback if $oldAutoCommit;
564 return "inserting cust_main_exemption (transaction rolled back): $error";
569 warn " ordering packages\n"
572 $error = $self->order_pkgs( $cust_pkgs,
574 'seconds_ref' => \$seconds,
575 'upbytes_ref' => \$upbytes,
576 'downbytes_ref' => \$downbytes,
577 'totalbytes_ref' => \$totalbytes,
580 $dbh->rollback if $oldAutoCommit;
585 $dbh->rollback if $oldAutoCommit;
586 return "No svc_acct record to apply pre-paid time";
588 if ( $upbytes || $downbytes || $totalbytes ) {
589 $dbh->rollback if $oldAutoCommit;
590 return "No svc_acct record to apply pre-paid data";
594 warn " inserting initial $payby payment of $amount\n"
596 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
598 $dbh->rollback if $oldAutoCommit;
599 return "inserting payment (transaction rolled back): $error";
603 unless ( $import || $skip_fuzzyfiles ) {
604 warn " queueing fuzzyfiles update\n"
606 $error = $self->queue_fuzzyfiles_update;
608 $dbh->rollback if $oldAutoCommit;
609 return "updating fuzzy search cache: $error";
613 # FS::geocode_Mixin::after_insert or something?
614 if ( $conf->config('tax_district_method') and !$import ) {
615 # if anything non-empty, try to look it up
616 my $queue = new FS::queue {
617 'job' => 'FS::geocode_Mixin::process_district_update',
618 'custnum' => $self->custnum,
620 my $error = $queue->insert( ref($self), $self->custnum );
622 $dbh->rollback if $oldAutoCommit;
623 return "queueing tax district update: $error";
628 warn " exporting\n" if $DEBUG > 1;
630 my $export_args = $options{'export_args'} || [];
633 map qsearch( 'part_export', {exportnum=>$_} ),
634 $conf->config('cust_main-exports'); #, $agentnum
636 foreach my $part_export ( @part_export ) {
637 my $error = $part_export->export_insert($self, @$export_args);
639 $dbh->rollback if $oldAutoCommit;
640 return "exporting to ". $part_export->exporttype.
641 " (transaction rolled back): $error";
645 #foreach my $depend_jobnum ( @$depend_jobnums ) {
646 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
648 # foreach my $jobnum ( @jobnums ) {
649 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
650 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
652 # my $error = $queue->depend_insert($depend_jobnum);
654 # $dbh->rollback if $oldAutoCommit;
655 # return "error queuing job dependancy: $error";
662 #if ( exists $options{'jobnums'} ) {
663 # push @{ $options{'jobnums'} }, @jobnums;
666 warn " insert complete; committing transaction\n"
669 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
674 use File::CounterFile;
675 sub auto_agent_custid {
678 my $format = $conf->config('cust_main-auto_agent_custid');
680 if ( $format eq '1YMMXXXXXXXX' ) {
682 my $counter = new File::CounterFile 'cust_main.agent_custid';
685 my $ym = 100000000000 + time2str('%y%m00000000', time);
686 if ( $ym > $counter->value ) {
687 $counter->{'value'} = $agent_custid = $ym;
688 $counter->{'updated'} = 1;
690 $agent_custid = $counter->inc;
696 die "Unknown cust_main-auto_agent_custid format: $format";
699 $self->agent_custid($agent_custid);
703 =item PACKAGE METHODS
705 Documentation on customer package methods has been moved to
706 L<FS::cust_main::Packages>.
708 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
710 Recharges this (existing) customer with the specified prepaid card (see
711 L<FS::prepay_credit>), specified either by I<identifier> or as an
712 FS::prepay_credit object. If there is an error, returns the error, otherwise
715 Optionally, five scalar references can be passed as well. They will have their
716 values filled in with the amount, number of seconds, and number of upload,
717 download, and total bytes applied by this prepaid card.
721 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
722 #the only place that uses these args
723 sub recharge_prepay {
724 my( $self, $prepay_credit, $amountref, $secondsref,
725 $upbytesref, $downbytesref, $totalbytesref ) = @_;
727 local $SIG{HUP} = 'IGNORE';
728 local $SIG{INT} = 'IGNORE';
729 local $SIG{QUIT} = 'IGNORE';
730 local $SIG{TERM} = 'IGNORE';
731 local $SIG{TSTP} = 'IGNORE';
732 local $SIG{PIPE} = 'IGNORE';
734 my $oldAutoCommit = $FS::UID::AutoCommit;
735 local $FS::UID::AutoCommit = 0;
738 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
740 my $error = $self->get_prepay( $prepay_credit,
741 'amount_ref' => \$amount,
742 'seconds_ref' => \$seconds,
743 'upbytes_ref' => \$upbytes,
744 'downbytes_ref' => \$downbytes,
745 'totalbytes_ref' => \$totalbytes,
747 || $self->increment_seconds($seconds)
748 || $self->increment_upbytes($upbytes)
749 || $self->increment_downbytes($downbytes)
750 || $self->increment_totalbytes($totalbytes)
751 || $self->insert_cust_pay_prepay( $amount,
753 ? $prepay_credit->identifier
758 $dbh->rollback if $oldAutoCommit;
762 if ( defined($amountref) ) { $$amountref = $amount; }
763 if ( defined($secondsref) ) { $$secondsref = $seconds; }
764 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
765 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
766 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
768 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
773 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
775 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
776 specified either by I<identifier> or as an FS::prepay_credit object.
778 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>. The scalars (provided by references) will be
779 incremented by the values of the prepaid card.
781 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
782 check or set this customer's I<agentnum>.
784 If there is an error, returns the error, otherwise returns false.
790 my( $self, $prepay_credit, %opt ) = @_;
792 local $SIG{HUP} = 'IGNORE';
793 local $SIG{INT} = 'IGNORE';
794 local $SIG{QUIT} = 'IGNORE';
795 local $SIG{TERM} = 'IGNORE';
796 local $SIG{TSTP} = 'IGNORE';
797 local $SIG{PIPE} = 'IGNORE';
799 my $oldAutoCommit = $FS::UID::AutoCommit;
800 local $FS::UID::AutoCommit = 0;
803 unless ( ref($prepay_credit) ) {
805 my $identifier = $prepay_credit;
807 $prepay_credit = qsearchs(
809 { 'identifier' => $identifier },
814 unless ( $prepay_credit ) {
815 $dbh->rollback if $oldAutoCommit;
816 return "Invalid prepaid card: ". $identifier;
821 if ( $prepay_credit->agentnum ) {
822 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
823 $dbh->rollback if $oldAutoCommit;
824 return "prepaid card not valid for agent ". $self->agentnum;
826 $self->agentnum($prepay_credit->agentnum);
829 my $error = $prepay_credit->delete;
831 $dbh->rollback if $oldAutoCommit;
832 return "removing prepay_credit (transaction rolled back): $error";
835 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
836 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
838 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
843 =item increment_upbytes SECONDS
845 Updates this customer's single or primary account (see L<FS::svc_acct>) by
846 the specified number of upbytes. If there is an error, returns the error,
847 otherwise returns false.
851 sub increment_upbytes {
852 _increment_column( shift, 'upbytes', @_);
855 =item increment_downbytes SECONDS
857 Updates this customer's single or primary account (see L<FS::svc_acct>) by
858 the specified number of downbytes. If there is an error, returns the error,
859 otherwise returns false.
863 sub increment_downbytes {
864 _increment_column( shift, 'downbytes', @_);
867 =item increment_totalbytes SECONDS
869 Updates this customer's single or primary account (see L<FS::svc_acct>) by
870 the specified number of totalbytes. If there is an error, returns the error,
871 otherwise returns false.
875 sub increment_totalbytes {
876 _increment_column( shift, 'totalbytes', @_);
879 =item increment_seconds SECONDS
881 Updates this customer's single or primary account (see L<FS::svc_acct>) by
882 the specified number of seconds. If there is an error, returns the error,
883 otherwise returns false.
887 sub increment_seconds {
888 _increment_column( shift, 'seconds', @_);
891 =item _increment_column AMOUNT
893 Updates this customer's single or primary account (see L<FS::svc_acct>) by
894 the specified number of seconds or bytes. If there is an error, returns
895 the error, otherwise returns false.
899 sub _increment_column {
900 my( $self, $column, $amount ) = @_;
901 warn "$me increment_column called: $column, $amount\n"
904 return '' unless $amount;
906 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
907 $self->ncancelled_pkgs;
910 return 'No packages with primary or single services found'.
911 ' to apply pre-paid time';
912 } elsif ( scalar(@cust_pkg) > 1 ) {
913 #maybe have a way to specify the package/account?
914 return 'Multiple packages found to apply pre-paid time';
917 my $cust_pkg = $cust_pkg[0];
918 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
922 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
925 return 'No account found to apply pre-paid time';
926 } elsif ( scalar(@cust_svc) > 1 ) {
927 return 'Multiple accounts found to apply pre-paid time';
930 my $svc_acct = $cust_svc[0]->svc_x;
931 warn " found service svcnum ". $svc_acct->pkgnum.
932 ' ('. $svc_acct->email. ")\n"
935 $column = "increment_$column";
936 $svc_acct->$column($amount);
940 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
942 Inserts a prepayment in the specified amount for this customer. An optional
943 second argument can specify the prepayment identifier for tracking purposes.
944 If there is an error, returns the error, otherwise returns false.
948 sub insert_cust_pay_prepay {
949 shift->insert_cust_pay('PREP', @_);
952 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
954 Inserts a cash payment in the specified amount for this customer. An optional
955 second argument can specify the payment identifier for tracking purposes.
956 If there is an error, returns the error, otherwise returns false.
960 sub insert_cust_pay_cash {
961 shift->insert_cust_pay('CASH', @_);
964 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
966 Inserts a Western Union payment in the specified amount for this customer. An
967 optional second argument can specify the prepayment identifier for tracking
968 purposes. If there is an error, returns the error, otherwise returns false.
972 sub insert_cust_pay_west {
973 shift->insert_cust_pay('WEST', @_);
976 sub insert_cust_pay {
977 my( $self, $payby, $amount ) = splice(@_, 0, 3);
978 my $payinfo = scalar(@_) ? shift : '';
980 my $cust_pay = new FS::cust_pay {
981 'custnum' => $self->custnum,
982 'paid' => sprintf('%.2f', $amount),
983 #'_date' => #date the prepaid card was purchased???
985 'payinfo' => $payinfo,
993 This method is deprecated. See the I<depend_jobnum> option to the insert and
994 order_pkgs methods for a better way to defer provisioning.
996 Re-schedules all exports by calling the B<reexport> method of all associated
997 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
998 otherwise returns false.
1005 carp "WARNING: FS::cust_main::reexport is deprectated; ".
1006 "use the depend_jobnum option to insert or order_pkgs to delay export";
1008 local $SIG{HUP} = 'IGNORE';
1009 local $SIG{INT} = 'IGNORE';
1010 local $SIG{QUIT} = 'IGNORE';
1011 local $SIG{TERM} = 'IGNORE';
1012 local $SIG{TSTP} = 'IGNORE';
1013 local $SIG{PIPE} = 'IGNORE';
1015 my $oldAutoCommit = $FS::UID::AutoCommit;
1016 local $FS::UID::AutoCommit = 0;
1019 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1020 my $error = $cust_pkg->reexport;
1022 $dbh->rollback if $oldAutoCommit;
1027 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1032 =item delete [ OPTION => VALUE ... ]
1034 This deletes the customer. If there is an error, returns the error, otherwise
1037 This will completely remove all traces of the customer record. This is not
1038 what you want when a customer cancels service; for that, cancel all of the
1039 customer's packages (see L</cancel>).
1041 If the customer has any uncancelled packages, you need to pass a new (valid)
1042 customer number for those packages to be transferred to, as the "new_customer"
1043 option. Cancelled packages will be deleted. Did I mention that this is NOT
1044 what you want when a customer cancels service and that you really should be
1045 looking at L<FS::cust_pkg/cancel>?
1047 You can't delete a customer with invoices (see L<FS::cust_bill>),
1048 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1049 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1050 set the "delete_financials" option to a true value.
1055 my( $self, %opt ) = @_;
1057 local $SIG{HUP} = 'IGNORE';
1058 local $SIG{INT} = 'IGNORE';
1059 local $SIG{QUIT} = 'IGNORE';
1060 local $SIG{TERM} = 'IGNORE';
1061 local $SIG{TSTP} = 'IGNORE';
1062 local $SIG{PIPE} = 'IGNORE';
1064 my $oldAutoCommit = $FS::UID::AutoCommit;
1065 local $FS::UID::AutoCommit = 0;
1068 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1069 $dbh->rollback if $oldAutoCommit;
1070 return "Can't delete a master agent customer";
1073 #use FS::access_user
1074 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1075 $dbh->rollback if $oldAutoCommit;
1076 return "Can't delete a master employee customer";
1079 tie my %financial_tables, 'Tie::IxHash',
1080 'cust_bill' => 'invoices',
1081 'cust_statement' => 'statements',
1082 'cust_credit' => 'credits',
1083 'cust_pay' => 'payments',
1084 'cust_refund' => 'refunds',
1087 foreach my $table ( keys %financial_tables ) {
1089 my @records = $self->$table();
1091 if ( @records && ! $opt{'delete_financials'} ) {
1092 $dbh->rollback if $oldAutoCommit;
1093 return "Can't delete a customer with ". $financial_tables{$table};
1096 foreach my $record ( @records ) {
1097 my $error = $record->delete;
1099 $dbh->rollback if $oldAutoCommit;
1100 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1106 my @cust_pkg = $self->ncancelled_pkgs;
1108 my $new_custnum = $opt{'new_custnum'};
1109 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1110 $dbh->rollback if $oldAutoCommit;
1111 return "Invalid new customer number: $new_custnum";
1113 foreach my $cust_pkg ( @cust_pkg ) {
1114 my %hash = $cust_pkg->hash;
1115 $hash{'custnum'} = $new_custnum;
1116 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1117 my $error = $new_cust_pkg->replace($cust_pkg,
1118 options => { $cust_pkg->options },
1121 $dbh->rollback if $oldAutoCommit;
1126 my @cancelled_cust_pkg = $self->all_pkgs;
1127 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1128 my $error = $cust_pkg->delete;
1130 $dbh->rollback if $oldAutoCommit;
1135 #cust_tax_adjustment in financials?
1136 #cust_pay_pending? ouch
1138 foreach my $table (qw(
1139 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1140 cust_location cust_main_note cust_tax_adjustment
1141 cust_pay_void cust_pay_batch queue cust_tax_exempt
1143 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1144 my $error = $record->delete;
1146 $dbh->rollback if $oldAutoCommit;
1152 my $sth = $dbh->prepare(
1153 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1155 my $errstr = $dbh->errstr;
1156 $dbh->rollback if $oldAutoCommit;
1159 $sth->execute($self->custnum) or do {
1160 my $errstr = $sth->errstr;
1161 $dbh->rollback if $oldAutoCommit;
1167 my $ticket_dbh = '';
1168 if ($conf->config('ticket_system') eq 'RT_Internal') {
1170 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1171 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1172 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1173 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1176 if ( $ticket_dbh ) {
1178 my $ticket_sth = $ticket_dbh->prepare(
1179 'DELETE FROM Links WHERE Target = ?'
1181 my $errstr = $ticket_dbh->errstr;
1182 $dbh->rollback if $oldAutoCommit;
1185 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1187 my $errstr = $ticket_sth->errstr;
1188 $dbh->rollback if $oldAutoCommit;
1192 #check and see if the customer is the only link on the ticket, and
1193 #if so, set the ticket to deleted status in RT?
1194 #maybe someday, for now this will at least fix tickets not displaying
1198 #delete the customer record
1200 my $error = $self->SUPER::delete;
1202 $dbh->rollback if $oldAutoCommit;
1206 # cust_main exports!
1208 #my $export_args = $options{'export_args'} || [];
1211 map qsearch( 'part_export', {exportnum=>$_} ),
1212 $conf->config('cust_main-exports'); #, $agentnum
1214 foreach my $part_export ( @part_export ) {
1215 my $error = $part_export->export_delete( $self ); #, @$export_args);
1217 $dbh->rollback if $oldAutoCommit;
1218 return "exporting to ". $part_export->exporttype.
1219 " (transaction rolled back): $error";
1223 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1228 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1230 This merges this customer into the provided new custnum, and then deletes the
1231 customer. If there is an error, returns the error, otherwise returns false.
1233 The source customer's name, company name, phone numbers, agent,
1234 referring customer, customer class, advertising source, order taker, and
1235 billing information (except balance) are discarded.
1237 All packages are moved to the target customer. Packages with package locations
1238 are preserved. Packages without package locations are moved to a new package
1239 location with the source customer's service/shipping address.
1241 All invoices, statements, payments, credits and refunds are moved to the target
1242 customer. The source customer's balance is added to the target customer.
1244 All notes, attachments, tickets and customer tags are moved to the target
1247 Change history is not currently moved.
1252 my( $self, $new_custnum, %opt ) = @_;
1254 return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1256 my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1257 or return "Invalid new customer number: $new_custnum";
1259 return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1260 if $self->agentnum != $new_cust_main->agentnum
1261 && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1263 local $SIG{HUP} = 'IGNORE';
1264 local $SIG{INT} = 'IGNORE';
1265 local $SIG{QUIT} = 'IGNORE';
1266 local $SIG{TERM} = 'IGNORE';
1267 local $SIG{TSTP} = 'IGNORE';
1268 local $SIG{PIPE} = 'IGNORE';
1270 my $oldAutoCommit = $FS::UID::AutoCommit;
1271 local $FS::UID::AutoCommit = 0;
1274 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1275 $dbh->rollback if $oldAutoCommit;
1276 return "Can't merge a master agent customer";
1279 #use FS::access_user
1280 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1281 $dbh->rollback if $oldAutoCommit;
1282 return "Can't merge a master employee customer";
1285 if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1286 'status' => { op=>'!=', value=>'done' },
1290 $dbh->rollback if $oldAutoCommit;
1291 return "Can't merge a customer with pending payments";
1294 tie my %financial_tables, 'Tie::IxHash',
1295 'cust_bill' => 'invoices',
1296 'cust_bill_void' => 'voided invoices',
1297 'cust_statement' => 'statements',
1298 'cust_credit' => 'credits',
1299 'cust_credit_void' => 'voided credits',
1300 'cust_pay' => 'payments',
1301 'cust_pay_void' => 'voided payments',
1302 'cust_refund' => 'refunds',
1305 foreach my $table ( keys %financial_tables ) {
1307 my @records = $self->$table();
1309 foreach my $record ( @records ) {
1310 $record->custnum($new_custnum);
1311 my $error = $record->replace;
1313 $dbh->rollback if $oldAutoCommit;
1314 return "Error merging ". $financial_tables{$table}. ": $error\n";
1320 my $name = $self->ship_name; #?
1322 my $locationnum = '';
1323 foreach my $cust_pkg ( $self->all_pkgs ) {
1324 $cust_pkg->custnum($new_custnum);
1326 unless ( $cust_pkg->locationnum ) {
1327 unless ( $locationnum ) {
1328 my $cust_location = new FS::cust_location {
1329 $self->location_hash,
1330 'custnum' => $new_custnum,
1332 my $error = $cust_location->insert;
1334 $dbh->rollback if $oldAutoCommit;
1337 $locationnum = $cust_location->locationnum;
1339 $cust_pkg->locationnum($locationnum);
1342 my $error = $cust_pkg->replace;
1344 $dbh->rollback if $oldAutoCommit;
1348 # add customer (ship) name to svc_phone.phone_name if blank
1349 my @cust_svc = $cust_pkg->cust_svc;
1350 foreach my $cust_svc (@cust_svc) {
1351 my($label, $value, $svcdb) = $cust_svc->label;
1352 next unless $svcdb eq 'svc_phone';
1353 my $svc_phone = $cust_svc->svc_x;
1354 next if $svc_phone->phone_name;
1355 $svc_phone->phone_name($name);
1356 my $error = $svc_phone->replace;
1358 $dbh->rollback if $oldAutoCommit;
1366 # cust_tax_exempt (texas tax exemptions)
1367 # cust_recon (some sort of not-well understood thing for OnPac)
1369 #these are moved over
1370 foreach my $table (qw(
1371 cust_tag cust_location contact cust_attachment cust_main_note
1372 cust_tax_adjustment cust_pay_batch queue
1374 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1375 $record->custnum($new_custnum);
1376 my $error = $record->replace;
1378 $dbh->rollback if $oldAutoCommit;
1384 #these aren't preserved
1385 foreach my $table (qw(
1386 cust_main_exemption cust_main_invoice
1388 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1389 my $error = $record->delete;
1391 $dbh->rollback if $oldAutoCommit;
1398 my $sth = $dbh->prepare(
1399 'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1401 my $errstr = $dbh->errstr;
1402 $dbh->rollback if $oldAutoCommit;
1405 $sth->execute($new_custnum, $self->custnum) or do {
1406 my $errstr = $sth->errstr;
1407 $dbh->rollback if $oldAutoCommit;
1413 my $ticket_dbh = '';
1414 if ($conf->config('ticket_system') eq 'RT_Internal') {
1416 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1417 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1418 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1419 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1422 if ( $ticket_dbh ) {
1424 my $ticket_sth = $ticket_dbh->prepare(
1425 'UPDATE Links SET Target = ? WHERE Target = ?'
1427 my $errstr = $ticket_dbh->errstr;
1428 $dbh->rollback if $oldAutoCommit;
1431 $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1432 'freeside://freeside/cust_main/'.$self->custnum)
1434 my $errstr = $ticket_sth->errstr;
1435 $dbh->rollback if $oldAutoCommit;
1441 #delete the customer record
1443 my $error = $self->delete;
1445 $dbh->rollback if $oldAutoCommit;
1449 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1454 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1456 Replaces the OLD_RECORD with this one in the database. If there is an error,
1457 returns the error, otherwise returns false.
1459 To change the customer's address, set the pseudo-fields C<bill_location> and
1460 C<ship_location>. The address will still only change if at least one of the
1461 address fields differs from the existing values.
1463 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1464 be set as the invoicing list (see L<"invoicing_list">). Errors return as
1465 expected and rollback the entire transaction; it is not necessary to call
1466 check_invoicing_list first. Here's an example:
1468 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1470 Currently available options are: I<tax_exemption>.
1472 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1473 of tax names and exemption numbers. FS::cust_main_exemption records will be
1474 deleted and inserted as appropriate.
1481 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1483 : $self->replace_old;
1487 warn "$me replace called\n"
1490 my $curuser = $FS::CurrentUser::CurrentUser;
1491 if ( $self->payby eq 'COMP'
1492 && $self->payby ne $old->payby
1493 && ! $curuser->access_right('Complimentary customer')
1496 return "You are not permitted to create complimentary accounts.";
1499 local($ignore_expired_card) = 1
1500 if $old->payby =~ /^(CARD|DCRD)$/
1501 && $self->payby =~ /^(CARD|DCRD)$/
1502 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1504 local($ignore_banned_card) = 1
1505 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1506 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1507 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1509 return "Invoicing locale is required"
1512 && $conf->exists('cust_main-require_locale');
1514 local $SIG{HUP} = 'IGNORE';
1515 local $SIG{INT} = 'IGNORE';
1516 local $SIG{QUIT} = 'IGNORE';
1517 local $SIG{TERM} = 'IGNORE';
1518 local $SIG{TSTP} = 'IGNORE';
1519 local $SIG{PIPE} = 'IGNORE';
1521 my $oldAutoCommit = $FS::UID::AutoCommit;
1522 local $FS::UID::AutoCommit = 0;
1525 for my $l (qw(bill_location ship_location)) {
1526 my $old_loc = $old->$l;
1527 my $new_loc = $self->$l;
1529 # find the existing location if there is one
1530 $new_loc->set('custnum' => $self->custnum);
1531 my $error = $new_loc->find_or_insert;
1533 $dbh->rollback if $oldAutoCommit;
1536 $self->set($l.'num', $new_loc->locationnum);
1539 $self->_loc_change($old);
1541 # replace the customer record
1542 my $error = $self->SUPER::replace($old);
1545 $dbh->rollback if $oldAutoCommit;
1549 # now move packages to the new service location
1550 $self->set('ship_location', ''); #flush cache
1551 if ( $old->ship_locationnum and # should only be null during upgrade...
1552 $old->ship_locationnum != $self->ship_locationnum ) {
1553 $error = $old->ship_location->move_to($self->ship_location);
1555 $dbh->rollback if $oldAutoCommit;
1559 # don't move packages based on the billing location, but
1560 # disable it if it's no longer in use
1561 if ( $old->bill_locationnum and
1562 $old->bill_locationnum != $self->bill_locationnum ) {
1563 $error = $old->bill_location->disable_if_unused;
1565 $dbh->rollback if $oldAutoCommit;
1570 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1571 my $invoicing_list = shift @param;
1572 $error = $self->check_invoicing_list( $invoicing_list );
1574 $dbh->rollback if $oldAutoCommit;
1577 $self->invoicing_list( $invoicing_list );
1580 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1582 #this could be more efficient than deleting and re-inserting, if it matters
1583 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1584 my $error = $cust_tag->delete;
1586 $dbh->rollback if $oldAutoCommit;
1590 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1591 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1592 'custnum' => $self->custnum };
1593 my $error = $cust_tag->insert;
1595 $dbh->rollback if $oldAutoCommit;
1602 my %options = @param;
1604 my $tax_exemption = delete $options{'tax_exemption'};
1605 if ( $tax_exemption ) {
1607 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1608 if ref($tax_exemption) eq 'ARRAY';
1610 my %cust_main_exemption =
1611 map { $_->taxname => $_ }
1612 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1614 foreach my $taxname ( keys %$tax_exemption ) {
1616 if ( $cust_main_exemption{$taxname} &&
1617 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1620 delete $cust_main_exemption{$taxname};
1624 my $cust_main_exemption = new FS::cust_main_exemption {
1625 'custnum' => $self->custnum,
1626 'taxname' => $taxname,
1627 'exempt_number' => $tax_exemption->{$taxname},
1629 my $error = $cust_main_exemption->insert;
1631 $dbh->rollback if $oldAutoCommit;
1632 return "inserting cust_main_exemption (transaction rolled back): $error";
1636 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1637 my $error = $cust_main_exemption->delete;
1639 $dbh->rollback if $oldAutoCommit;
1640 return "deleting cust_main_exemption (transaction rolled back): $error";
1646 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1647 && ( ( $self->get('payinfo') ne $old->get('payinfo')
1648 && $self->get('payinfo') !~ /^99\d{14}$/
1650 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1655 # card/check/lec info has changed, want to retry realtime_ invoice events
1656 my $error = $self->retry_realtime;
1658 $dbh->rollback if $oldAutoCommit;
1663 unless ( $import || $skip_fuzzyfiles ) {
1664 $error = $self->queue_fuzzyfiles_update;
1666 $dbh->rollback if $oldAutoCommit;
1667 return "updating fuzzy search cache: $error";
1671 # tax district update in cust_location
1673 # cust_main exports!
1675 my $export_args = $options{'export_args'} || [];
1678 map qsearch( 'part_export', {exportnum=>$_} ),
1679 $conf->config('cust_main-exports'); #, $agentnum
1681 foreach my $part_export ( @part_export ) {
1682 my $error = $part_export->export_replace( $self, $old, @$export_args);
1684 $dbh->rollback if $oldAutoCommit;
1685 return "exporting to ". $part_export->exporttype.
1686 " (transaction rolled back): $error";
1690 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1695 =item queue_fuzzyfiles_update
1697 Used by insert & replace to update the fuzzy search cache
1701 use FS::cust_main::Search;
1702 sub queue_fuzzyfiles_update {
1705 local $SIG{HUP} = 'IGNORE';
1706 local $SIG{INT} = 'IGNORE';
1707 local $SIG{QUIT} = 'IGNORE';
1708 local $SIG{TERM} = 'IGNORE';
1709 local $SIG{TSTP} = 'IGNORE';
1710 local $SIG{PIPE} = 'IGNORE';
1712 my $oldAutoCommit = $FS::UID::AutoCommit;
1713 local $FS::UID::AutoCommit = 0;
1716 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1717 my $queue = new FS::queue {
1718 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1720 my @args = "cust_main.$field", $self->get($field);
1721 my $error = $queue->insert( @args );
1723 $dbh->rollback if $oldAutoCommit;
1724 return "queueing job (transaction rolled back): $error";
1728 my @locations = $self->bill_location;
1729 push @locations, $self->ship_location if $self->has_ship_address;
1730 foreach my $location (@locations) {
1731 my $queue = new FS::queue {
1732 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1734 my @args = 'cust_location.address1', $location->address1;
1735 my $error = $queue->insert( @args );
1737 $dbh->rollback if $oldAutoCommit;
1738 return "queueing job (transaction rolled back): $error";
1742 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1749 Checks all fields to make sure this is a valid customer record. If there is
1750 an error, returns the error, otherwise returns false. Called by the insert
1751 and replace methods.
1758 warn "$me check BEFORE: \n". $self->_dump
1762 $self->ut_numbern('custnum')
1763 || $self->ut_number('agentnum')
1764 || $self->ut_textn('agent_custid')
1765 || $self->ut_number('refnum')
1766 || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1767 || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1768 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1769 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1770 || $self->ut_textn('custbatch')
1771 || $self->ut_name('last')
1772 || $self->ut_name('first')
1773 || $self->ut_snumbern('signupdate')
1774 || $self->ut_snumbern('birthdate')
1775 || $self->ut_namen('spouse_last')
1776 || $self->ut_namen('spouse_first')
1777 || $self->ut_snumbern('spouse_birthdate')
1778 || $self->ut_snumbern('anniversary_date')
1779 || $self->ut_textn('company')
1780 || $self->ut_textn('ship_company')
1781 || $self->ut_anything('comments')
1782 || $self->ut_numbern('referral_custnum')
1783 || $self->ut_textn('stateid')
1784 || $self->ut_textn('stateid_state')
1785 || $self->ut_textn('invoice_terms')
1786 || $self->ut_floatn('cdr_termination_percentage')
1787 || $self->ut_floatn('credit_limit')
1788 || $self->ut_numbern('billday')
1789 || $self->ut_numbern('prorate_day')
1790 || $self->ut_flag('edit_subject')
1791 || $self->ut_flag('calling_list_exempt')
1792 || $self->ut_flag('invoice_noemail')
1793 || $self->ut_flag('message_noemail')
1794 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1795 || $self->ut_flag('invoice_ship_address')
1798 foreach (qw(company ship_company)) {
1799 my $company = $self->get($_);
1800 $company =~ s/^\s+//;
1801 $company =~ s/\s+$//;
1802 $company =~ s/\s+/ /g;
1803 $self->set($_, $company);
1806 #barf. need message catalogs. i18n. etc.
1807 $error .= "Please select an advertising source."
1808 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1809 return $error if $error;
1811 return "Unknown agent"
1812 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1814 return "Unknown refnum"
1815 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1817 return "Unknown referring custnum: ". $self->referral_custnum
1818 unless ! $self->referral_custnum
1819 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1821 if ( $self->ss eq '' ) {
1826 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1827 or return "Illegal social security number: ". $self->ss;
1828 $self->ss("$1-$2-$3");
1831 # cust_main_county verification now handled by cust_location check
1834 $self->ut_phonen('daytime', $self->country)
1835 || $self->ut_phonen('night', $self->country)
1836 || $self->ut_phonen('fax', $self->country)
1837 || $self->ut_phonen('mobile', $self->country)
1839 return $error if $error;
1841 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1843 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1846 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1848 : FS::Msgcat::_gettext('daytime');
1849 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1851 : FS::Msgcat::_gettext('night');
1853 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1855 : FS::Msgcat::_gettext('mobile');
1857 return "$daytime_label, $night_label or $mobile_label is required"
1861 #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1862 # or return "Illegal payby: ". $self->payby;
1864 FS::payby->can_payby($self->table, $self->payby)
1865 or return "Illegal payby: ". $self->payby;
1867 $error = $self->ut_numbern('paystart_month')
1868 || $self->ut_numbern('paystart_year')
1869 || $self->ut_numbern('payissue')
1870 || $self->ut_textn('paytype')
1872 return $error if $error;
1874 if ( $self->payip eq '' ) {
1877 $error = $self->ut_ip('payip');
1878 return $error if $error;
1881 # If it is encrypted and the private key is not availaible then we can't
1882 # check the credit card.
1883 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1885 # Need some kind of global flag to accept invalid cards, for testing
1887 if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1889 my $payinfo = $self->payinfo;
1890 $payinfo =~ s/\D//g;
1891 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1892 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1894 $self->payinfo($payinfo);
1896 or return gettext('invalid_card'); # . ": ". $self->payinfo;
1898 return gettext('unknown_card_type')
1899 if $self->payinfo !~ /^99\d{14}$/ #token
1900 && cardtype($self->payinfo) eq "Unknown";
1902 unless ( $ignore_banned_card ) {
1903 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1905 if ( $ban->bantype eq 'warn' ) {
1906 #or others depending on value of $ban->reason ?
1907 return '_duplicate_card'.
1908 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1909 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
1910 ' (ban# '. $ban->bannum. ')'
1911 unless $self->override_ban_warn;
1913 return 'Banned credit card: banned on '.
1914 time2str('%a %h %o at %r', $ban->_date).
1915 ' by '. $ban->otaker.
1916 ' (ban# '. $ban->bannum. ')';
1921 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1922 if ( cardtype($self->payinfo) eq 'American Express card' ) {
1923 $self->paycvv =~ /^(\d{4})$/
1924 or return "CVV2 (CID) for American Express cards is four digits.";
1927 $self->paycvv =~ /^(\d{3})$/
1928 or return "CVV2 (CVC2/CID) is three digits.";
1935 my $cardtype = cardtype($payinfo);
1936 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1938 return "Start date or issue number is required for $cardtype cards"
1939 unless $self->paystart_month && $self->paystart_year or $self->payissue;
1941 return "Start month must be between 1 and 12"
1942 if $self->paystart_month
1943 and $self->paystart_month < 1 || $self->paystart_month > 12;
1945 return "Start year must be 1990 or later"
1946 if $self->paystart_year
1947 and $self->paystart_year < 1990;
1949 return "Issue number must be beween 1 and 99"
1951 and $self->payissue < 1 || $self->payissue > 99;
1954 $self->paystart_month('');
1955 $self->paystart_year('');
1956 $self->payissue('');
1959 } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1961 my $payinfo = $self->payinfo;
1962 $payinfo =~ s/[^\d\@\.]//g;
1963 if ( $conf->config('echeck-country') eq 'CA' ) {
1964 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1965 or return 'invalid echeck account@branch.bank';
1966 $payinfo = "$1\@$2.$3";
1967 } elsif ( $conf->config('echeck-country') eq 'US' ) {
1968 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1969 $payinfo = "$1\@$2";
1971 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
1972 $payinfo = "$1\@$2";
1974 $self->payinfo($payinfo);
1977 unless ( $ignore_banned_card ) {
1978 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1980 if ( $ban->bantype eq 'warn' ) {
1981 #or others depending on value of $ban->reason ?
1982 return '_duplicate_ach' unless $self->override_ban_warn;
1984 return 'Banned ACH account: banned on '.
1985 time2str('%a %h %o at %r', $ban->_date).
1986 ' by '. $ban->otaker.
1987 ' (ban# '. $ban->bannum. ')';
1992 } elsif ( $self->payby eq 'LECB' ) {
1994 my $payinfo = $self->payinfo;
1995 $payinfo =~ s/\D//g;
1996 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1998 $self->payinfo($payinfo);
2001 } elsif ( $self->payby eq 'BILL' ) {
2003 $error = $self->ut_textn('payinfo');
2004 return "Illegal P.O. number: ". $self->payinfo if $error;
2007 } elsif ( $self->payby eq 'COMP' ) {
2009 my $curuser = $FS::CurrentUser::CurrentUser;
2010 if ( ! $self->custnum
2011 && ! $curuser->access_right('Complimentary customer')
2014 return "You are not permitted to create complimentary accounts."
2017 $error = $self->ut_textn('payinfo');
2018 return "Illegal comp account issuer: ". $self->payinfo if $error;
2021 } elsif ( $self->payby eq 'PREPAY' ) {
2023 my $payinfo = $self->payinfo;
2024 $payinfo =~ s/\W//g; #anything else would just confuse things
2025 $self->payinfo($payinfo);
2026 $error = $self->ut_alpha('payinfo');
2027 return "Illegal prepayment identifier: ". $self->payinfo if $error;
2028 return "Unknown prepayment identifier"
2029 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2034 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2035 return "Expiration date required"
2036 # shouldn't payinfo_check do this?
2037 unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2041 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2042 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2043 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2044 ( $m, $y ) = ( $2, "19$1" );
2045 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2046 ( $m, $y ) = ( $3, "20$2" );
2048 return "Illegal expiration date: ". $self->paydate;
2050 $m = sprintf('%02d',$m);
2051 $self->paydate("$y-$m-01");
2052 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2053 return gettext('expired_card')
2055 && !$ignore_expired_card
2056 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2059 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2060 ( ! $conf->exists('require_cardname')
2061 || $self->payby !~ /^(CARD|DCRD)$/ )
2063 $self->payname( $self->first. " ". $self->getfield('last') );
2066 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2067 $self->payname =~ /^([\w \,\.\-\']*)$/
2068 or return gettext('illegal_name'). " payname: ". $self->payname;
2071 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2072 or return gettext('illegal_name'). " payname: ". $self->payname;
2078 return "Please select an invoicing locale"
2081 && $conf->exists('cust_main-require_locale');
2083 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2084 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2088 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2090 warn "$me check AFTER: \n". $self->_dump
2093 $self->SUPER::check;
2098 Returns a list of fields which have ship_ duplicates.
2103 qw( last first company
2105 address1 address2 city county state zip country
2107 daytime night fax mobile
2111 =item has_ship_address
2113 Returns true if this customer record has a separate shipping address.
2117 sub has_ship_address {
2119 $self->bill_locationnum != $self->ship_locationnum;
2124 Returns a list of key/value pairs, with the following keys: address1,
2125 adddress2, city, county, state, zip, country, district, and geocode. The
2126 shipping address is used if present.
2132 $self->ship_location->location_hash;
2137 Returns all locations (see L<FS::cust_location>) for this customer.
2143 qsearch('cust_location', { 'custnum' => $self->custnum,
2144 'prospectnum' => '' } );
2149 Returns all contacts (see L<FS::contact>) for this customer.
2153 #already used :/ sub contact {
2156 qsearch('contact', { 'custnum' => $self->custnum } );
2161 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2162 and L<FS::cust_pkg>) for this customer, except those on hold.
2164 Returns a list: an empty list on success or a list of errors.
2170 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2175 Unsuspends all suspended packages in the on-hold state (those without setup
2176 dates) for this customer.
2182 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2187 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2189 Returns a list: an empty list on success or a list of errors.
2195 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2198 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2200 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2201 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2202 of a list of pkgparts; the hashref has the following keys:
2206 =item pkgparts - listref of pkgparts
2208 =item (other options are passed to the suspend method)
2213 Returns a list: an empty list on success or a list of errors.
2217 sub suspend_if_pkgpart {
2219 my (@pkgparts, %opt);
2220 if (ref($_[0]) eq 'HASH'){
2221 @pkgparts = @{$_[0]{pkgparts}};
2226 grep { $_->suspend(%opt) }
2227 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2228 $self->unsuspended_pkgs;
2231 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2233 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2234 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2235 instead of a list of pkgparts; the hashref has the following keys:
2239 =item pkgparts - listref of pkgparts
2241 =item (other options are passed to the suspend method)
2245 Returns a list: an empty list on success or a list of errors.
2249 sub suspend_unless_pkgpart {
2251 my (@pkgparts, %opt);
2252 if (ref($_[0]) eq 'HASH'){
2253 @pkgparts = @{$_[0]{pkgparts}};
2258 grep { $_->suspend(%opt) }
2259 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2260 $self->unsuspended_pkgs;
2263 =item cancel [ OPTION => VALUE ... ]
2265 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2267 Available options are:
2271 =item quiet - can be set true to supress email cancellation notices.
2273 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason. The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
2275 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2277 =item nobill - can be set true to skip billing if it might otherwise be done.
2281 Always returns a list: an empty list on success or a list of errors.
2285 # nb that dates are not specified as valid options to this method
2288 my( $self, %opt ) = @_;
2290 warn "$me cancel called on customer ". $self->custnum. " with options ".
2291 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2294 return ( 'access denied' )
2295 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2297 if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2299 #should try decryption (we might have the private key)
2300 # and if not maybe queue a job for the server that does?
2301 return ( "Can't (yet) ban encrypted credit cards" )
2302 if $self->is_encrypted($self->payinfo);
2304 my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2305 my $error = $ban->insert;
2306 return ( $error ) if $error;
2310 my @pkgs = $self->ncancelled_pkgs;
2312 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2314 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2315 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2319 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2320 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2323 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2326 sub _banned_pay_hashref {
2337 'payby' => $payby2ban{$self->payby},
2338 'payinfo' => $self->payinfo,
2339 #don't ever *search* on reason! #'reason' =>
2343 sub _new_banned_pay_hashref {
2345 my $hr = $self->_banned_pay_hashref;
2346 $hr->{payinfo} = md5_base64($hr->{payinfo});
2352 Returns all notes (see L<FS::cust_main_note>) for this customer.
2357 my($self,$orderby_classnum) = (shift,shift);
2358 my $orderby = "sticky DESC, _date DESC";
2359 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2360 qsearch( 'cust_main_note',
2361 { 'custnum' => $self->custnum },
2363 "ORDER BY $orderby",
2369 Returns the agent (see L<FS::agent>) for this customer.
2375 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2380 Returns the agent name (see L<FS::agent>) for this customer.
2386 $self->agent->agent;
2391 Returns any tags associated with this customer, as FS::cust_tag objects,
2392 or an empty list if there are no tags.
2398 qsearch('cust_tag', { 'custnum' => $self->custnum } );
2403 Returns any tags associated with this customer, as FS::part_tag objects,
2404 or an empty list if there are no tags.
2410 map $_->part_tag, $self->cust_tag;
2416 Returns the customer class, as an FS::cust_class object, or the empty string
2417 if there is no customer class.
2423 if ( $self->classnum ) {
2424 qsearchs('cust_class', { 'classnum' => $self->classnum } );
2432 Returns the customer category name, or the empty string if there is no customer
2439 my $cust_class = $self->cust_class;
2441 ? $cust_class->categoryname
2447 Returns the customer class name, or the empty string if there is no customer
2454 my $cust_class = $self->cust_class;
2456 ? $cust_class->classname
2460 =item BILLING METHODS
2462 Documentation on billing methods has been moved to
2463 L<FS::cust_main::Billing>.
2465 =item REALTIME BILLING METHODS
2467 Documentation on realtime billing methods has been moved to
2468 L<FS::cust_main::Billing_Realtime>.
2472 Removes the I<paycvv> field from the database directly.
2474 If there is an error, returns the error, otherwise returns false.
2480 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2481 or return dbh->errstr;
2482 $sth->execute($self->custnum)
2483 or return $sth->errstr;
2488 =item batch_card OPTION => VALUE...
2490 Adds a payment for this invoice to the pending credit card batch (see
2491 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2492 runs the payment using a realtime gateway.
2494 Options may include:
2496 B<amount>: the amount to be paid; defaults to the customer's balance minus
2497 any payments in transit.
2499 B<payby>: the payment method; defaults to cust_main.payby
2501 B<realtime>: runs this as a realtime payment instead of adding it to a
2504 B<invnum>: sets cust_pay_batch.invnum.
2506 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets
2507 the billing address for the payment; defaults to the customer's billing
2510 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2511 date, and name; defaults to those fields in cust_main.
2516 my ($self, %options) = @_;
2519 if (exists($options{amount})) {
2520 $amount = $options{amount};
2522 $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2524 return '' unless $amount > 0;
2526 my $invnum = delete $options{invnum};
2527 my $payby = $options{payby} || $self->payby; #still dubious
2529 if ($options{'realtime'}) {
2530 return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2536 my $oldAutoCommit = $FS::UID::AutoCommit;
2537 local $FS::UID::AutoCommit = 0;
2540 #this needs to handle mysql as well as Pg, like svc_acct.pm
2541 #(make it into a common function if folks need to do batching with mysql)
2542 $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2543 or return "Cannot lock pay_batch: " . $dbh->errstr;
2547 'payby' => FS::payby->payby2payment($payby),
2549 $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2551 my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2553 unless ( $pay_batch ) {
2554 $pay_batch = new FS::pay_batch \%pay_batch;
2555 my $error = $pay_batch->insert;
2557 $dbh->rollback if $oldAutoCommit;
2558 die "error creating new batch: $error\n";
2562 my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2563 'batchnum' => $pay_batch->batchnum,
2564 'custnum' => $self->custnum,
2567 foreach (qw( address1 address2 city state zip country latitude longitude
2568 payby payinfo paydate payname ))
2570 $options{$_} = '' unless exists($options{$_});
2573 my $loc = $self->bill_location;
2575 my $cust_pay_batch = new FS::cust_pay_batch ( {
2576 'batchnum' => $pay_batch->batchnum,
2577 'invnum' => $invnum || 0, # is there a better value?
2578 # this field should be
2580 # cust_bill_pay_batch now
2581 'custnum' => $self->custnum,
2582 'last' => $self->getfield('last'),
2583 'first' => $self->getfield('first'),
2584 'address1' => $options{address1} || $loc->address1,
2585 'address2' => $options{address2} || $loc->address2,
2586 'city' => $options{city} || $loc->city,
2587 'state' => $options{state} || $loc->state,
2588 'zip' => $options{zip} || $loc->zip,
2589 'country' => $options{country} || $loc->country,
2590 'payby' => $options{payby} || $self->payby,
2591 'payinfo' => $options{payinfo} || $self->payinfo,
2592 'exp' => $options{paydate} || $self->paydate,
2593 'payname' => $options{payname} || $self->payname,
2594 'amount' => $amount, # consolidating
2597 $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2598 if $old_cust_pay_batch;
2601 if ($old_cust_pay_batch) {
2602 $error = $cust_pay_batch->replace($old_cust_pay_batch)
2604 $error = $cust_pay_batch->insert;
2608 $dbh->rollback if $oldAutoCommit;
2612 my $unapplied = $self->total_unapplied_credits
2613 + $self->total_unapplied_payments
2614 + $self->in_transit_payments;
2615 foreach my $cust_bill ($self->open_cust_bill) {
2616 #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2617 my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2618 'invnum' => $cust_bill->invnum,
2619 'paybatchnum' => $cust_pay_batch->paybatchnum,
2620 'amount' => $cust_bill->owed,
2623 if ($unapplied >= $cust_bill_pay_batch->amount){
2624 $unapplied -= $cust_bill_pay_batch->amount;
2627 $cust_bill_pay_batch->amount(sprintf ( "%.2f",
2628 $cust_bill_pay_batch->amount - $unapplied )); $unapplied = 0;
2630 $error = $cust_bill_pay_batch->insert;
2632 $dbh->rollback if $oldAutoCommit;
2637 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2643 Returns the total owed for this customer on all invoices
2644 (see L<FS::cust_bill/owed>).
2650 $self->total_owed_date(2145859200); #12/31/2037
2653 =item total_owed_date TIME
2655 Returns the total owed for this customer on all invoices with date earlier than
2656 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2657 see L<Time::Local> and L<Date::Parse> for conversion functions.
2661 sub total_owed_date {
2665 my $custnum = $self->custnum;
2667 my $owed_sql = FS::cust_bill->owed_sql;
2670 SELECT SUM($owed_sql) FROM cust_bill
2671 WHERE custnum = $custnum
2675 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2679 =item total_owed_pkgnum PKGNUM
2681 Returns the total owed on all invoices for this customer's specific package
2682 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2686 sub total_owed_pkgnum {
2687 my( $self, $pkgnum ) = @_;
2688 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2691 =item total_owed_date_pkgnum TIME PKGNUM
2693 Returns the total owed for this customer's specific package when using
2694 experimental package balances on all invoices with date earlier than
2695 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2696 see L<Time::Local> and L<Date::Parse> for conversion functions.
2700 sub total_owed_date_pkgnum {
2701 my( $self, $time, $pkgnum ) = @_;
2704 foreach my $cust_bill (
2705 grep { $_->_date <= $time }
2706 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2708 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2710 sprintf( "%.2f", $total_bill );
2716 Returns the total amount of all payments.
2723 $total += $_->paid foreach $self->cust_pay;
2724 sprintf( "%.2f", $total );
2727 =item total_unapplied_credits
2729 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2730 customer. See L<FS::cust_credit/credited>.
2732 =item total_credited
2734 Old name for total_unapplied_credits. Don't use.
2738 sub total_credited {
2739 #carp "total_credited deprecated, use total_unapplied_credits";
2740 shift->total_unapplied_credits(@_);
2743 sub total_unapplied_credits {
2746 my $custnum = $self->custnum;
2748 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2751 SELECT SUM($unapplied_sql) FROM cust_credit
2752 WHERE custnum = $custnum
2755 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2759 =item total_unapplied_credits_pkgnum PKGNUM
2761 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2762 customer. See L<FS::cust_credit/credited>.
2766 sub total_unapplied_credits_pkgnum {
2767 my( $self, $pkgnum ) = @_;
2768 my $total_credit = 0;
2769 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2770 sprintf( "%.2f", $total_credit );
2774 =item total_unapplied_payments
2776 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2777 See L<FS::cust_pay/unapplied>.
2781 sub total_unapplied_payments {
2784 my $custnum = $self->custnum;
2786 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2789 SELECT SUM($unapplied_sql) FROM cust_pay
2790 WHERE custnum = $custnum
2793 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2797 =item total_unapplied_payments_pkgnum PKGNUM
2799 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2800 specific package when using experimental package balances. See
2801 L<FS::cust_pay/unapplied>.
2805 sub total_unapplied_payments_pkgnum {
2806 my( $self, $pkgnum ) = @_;
2807 my $total_unapplied = 0;
2808 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2809 sprintf( "%.2f", $total_unapplied );
2813 =item total_unapplied_refunds
2815 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2816 customer. See L<FS::cust_refund/unapplied>.
2820 sub total_unapplied_refunds {
2822 my $custnum = $self->custnum;
2824 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2827 SELECT SUM($unapplied_sql) FROM cust_refund
2828 WHERE custnum = $custnum
2831 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2837 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2838 total_unapplied_credits minus total_unapplied_payments).
2844 $self->balance_date_range;
2847 =item balance_date TIME
2849 Returns the balance for this customer, only considering invoices with date
2850 earlier than TIME (total_owed_date minus total_credited minus
2851 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2852 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2859 $self->balance_date_range(shift);
2862 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2864 Returns the balance for this customer, optionally considering invoices with
2865 date earlier than START_TIME, and not later than END_TIME
2866 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2868 Times are specified as SQL fragments or numeric
2869 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2870 L<Date::Parse> for conversion functions. The empty string can be passed
2871 to disable that time constraint completely.
2873 Accepts the same options as L<balance_date_sql>:
2877 =item unapplied_date
2879 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
2883 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2884 time will be ignored. Note that START_TIME and END_TIME only limit the date
2885 range for invoices and I<unapplied> payments, credits, and refunds.
2891 sub balance_date_range {
2893 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2894 ') FROM cust_main WHERE custnum='. $self->custnum;
2895 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2898 =item balance_pkgnum PKGNUM
2900 Returns the balance for this customer's specific package when using
2901 experimental package balances (total_owed plus total_unrefunded, minus
2902 total_unapplied_credits minus total_unapplied_payments)
2906 sub balance_pkgnum {
2907 my( $self, $pkgnum ) = @_;
2910 $self->total_owed_pkgnum($pkgnum)
2911 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2912 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2913 - $self->total_unapplied_credits_pkgnum($pkgnum)
2914 - $self->total_unapplied_payments_pkgnum($pkgnum)
2918 =item in_transit_payments
2920 Returns the total of requests for payments for this customer pending in
2921 batches in transit to the bank. See L<FS::pay_batch> and L<FS::cust_pay_batch>
2925 sub in_transit_payments {
2927 my $in_transit_payments = 0;
2928 foreach my $pay_batch ( qsearch('pay_batch', {
2931 foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2932 'batchnum' => $pay_batch->batchnum,
2933 'custnum' => $self->custnum,
2935 $in_transit_payments += $cust_pay_batch->amount;
2938 sprintf( "%.2f", $in_transit_payments );
2943 Returns a hash of useful information for making a payment.
2953 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2954 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2955 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2959 For credit card transactions:
2971 For electronic check transactions:
2986 $return{balance} = $self->balance;
2988 $return{payname} = $self->payname
2989 || ( $self->first. ' '. $self->get('last') );
2991 $return{$_} = $self->bill_location->$_
2992 for qw(address1 address2 city state zip);
2994 $return{payby} = $self->payby;
2995 $return{stateid_state} = $self->stateid_state;
2997 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2998 $return{card_type} = cardtype($self->payinfo);
2999 $return{payinfo} = $self->paymask;
3001 @return{'month', 'year'} = $self->paydate_monthyear;
3005 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3006 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3007 $return{payinfo1} = $payinfo1;
3008 $return{payinfo2} = $payinfo2;
3009 $return{paytype} = $self->paytype;
3010 $return{paystate} = $self->paystate;
3014 #doubleclick protection
3016 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3022 =item paydate_monthyear
3024 Returns a two-element list consisting of the month and year of this customer's
3025 paydate (credit card expiration date for CARD customers)
3029 sub paydate_monthyear {
3031 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3033 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3042 Returns the exact time in seconds corresponding to the payment method
3043 expiration date. For CARD/DCRD customers this is the end of the month;
3044 for others (COMP is the only other payby that uses paydate) it's the start.
3045 Returns 0 if the paydate is empty or set to the far future.
3051 my ($month, $year) = $self->paydate_monthyear;
3052 return 0 if !$year or $year >= 2037;
3053 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3055 if ( $month == 13 ) {
3059 return timelocal(0,0,0,1,$month-1,$year) - 1;
3062 return timelocal(0,0,0,1,$month-1,$year);
3066 =item paydate_epoch_sql
3068 Class method. Returns an SQL expression to obtain the payment expiration date
3069 as a number of seconds.
3073 # Special expiration date behavior for non-CARD/DCRD customers has been
3074 # carefully preserved. Do we really use that?
3075 sub paydate_epoch_sql {
3077 my $table = shift || 'cust_main';
3078 my ($case1, $case2);
3079 if ( driver_name eq 'Pg' ) {
3080 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3081 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3083 elsif ( lc(driver_name) eq 'mysql' ) {
3084 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3085 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3088 return "CASE WHEN $table.payby IN('CARD','DCRD')
3094 =item tax_exemption TAXNAME
3099 my( $self, $taxname ) = @_;
3101 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3102 'taxname' => $taxname,
3107 =item cust_main_exemption
3111 sub cust_main_exemption {
3113 qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3116 =item invoicing_list [ ARRAYREF ]
3118 If an arguement is given, sets these email addresses as invoice recipients
3119 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
3120 (except as warnings), so use check_invoicing_list first.
3122 Returns a list of email addresses (with svcnum entries expanded).
3124 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
3125 check it without disturbing anything by passing nothing.
3127 This interface may change in the future.
3131 sub invoicing_list {
3132 my( $self, $arrayref ) = @_;
3135 my @cust_main_invoice;
3136 if ( $self->custnum ) {
3137 @cust_main_invoice =
3138 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3140 @cust_main_invoice = ();
3142 foreach my $cust_main_invoice ( @cust_main_invoice ) {
3143 #warn $cust_main_invoice->destnum;
3144 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3145 #warn $cust_main_invoice->destnum;
3146 my $error = $cust_main_invoice->delete;
3147 warn $error if $error;
3150 if ( $self->custnum ) {
3151 @cust_main_invoice =
3152 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3154 @cust_main_invoice = ();
3156 my %seen = map { $_->address => 1 } @cust_main_invoice;
3157 foreach my $address ( @{$arrayref} ) {
3158 next if exists $seen{$address} && $seen{$address};
3159 $seen{$address} = 1;
3160 my $cust_main_invoice = new FS::cust_main_invoice ( {
3161 'custnum' => $self->custnum,
3164 my $error = $cust_main_invoice->insert;
3165 warn $error if $error;
3169 if ( $self->custnum ) {
3171 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3178 =item check_invoicing_list ARRAYREF
3180 Checks these arguements as valid input for the invoicing_list method. If there
3181 is an error, returns the error, otherwise returns false.
3185 sub check_invoicing_list {
3186 my( $self, $arrayref ) = @_;
3188 foreach my $address ( @$arrayref ) {
3190 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3191 return 'Can\'t add FAX invoice destination with a blank FAX number.';
3194 my $cust_main_invoice = new FS::cust_main_invoice ( {
3195 'custnum' => $self->custnum,
3198 my $error = $self->custnum
3199 ? $cust_main_invoice->check
3200 : $cust_main_invoice->checkdest
3202 return $error if $error;
3206 return "Email address required"
3207 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3208 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3213 =item set_default_invoicing_list
3215 Sets the invoicing list to all accounts associated with this customer,
3216 overwriting any previous invoicing list.
3220 sub set_default_invoicing_list {
3222 $self->invoicing_list($self->all_emails);
3227 Returns the email addresses of all accounts provisioned for this customer.
3234 foreach my $cust_pkg ( $self->all_pkgs ) {
3235 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3237 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3238 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3240 $list{$_}=1 foreach map { $_->email } @svc_acct;
3245 =item invoicing_list_addpost
3247 Adds postal invoicing to this customer. If this customer is already configured
3248 to receive postal invoices, does nothing.
3252 sub invoicing_list_addpost {
3254 return if grep { $_ eq 'POST' } $self->invoicing_list;
3255 my @invoicing_list = $self->invoicing_list;
3256 push @invoicing_list, 'POST';
3257 $self->invoicing_list(\@invoicing_list);
3260 =item invoicing_list_emailonly
3262 Returns the list of email invoice recipients (invoicing_list without non-email
3263 destinations such as POST and FAX).
3267 sub invoicing_list_emailonly {
3269 warn "$me invoicing_list_emailonly called"
3271 grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3274 =item invoicing_list_emailonly_scalar
3276 Returns the list of email invoice recipients (invoicing_list without non-email
3277 destinations such as POST and FAX) as a comma-separated scalar.
3281 sub invoicing_list_emailonly_scalar {
3283 warn "$me invoicing_list_emailonly_scalar called"
3285 join(', ', $self->invoicing_list_emailonly);
3288 =item referral_custnum_cust_main
3290 Returns the customer who referred this customer (or the empty string, if
3291 this customer was not referred).
3293 Note the difference with referral_cust_main method: This method,
3294 referral_custnum_cust_main returns the single customer (if any) who referred
3295 this customer, while referral_cust_main returns an array of customers referred
3300 sub referral_custnum_cust_main {
3302 return '' unless $self->referral_custnum;
3303 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3306 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3308 Returns an array of customers referred by this customer (referral_custnum set
3309 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3310 customers referred by customers referred by this customer and so on, inclusive.
3311 The default behavior is DEPTH 1 (no recursion).
3313 Note the difference with referral_custnum_cust_main method: This method,
3314 referral_cust_main, returns an array of customers referred BY this customer,
3315 while referral_custnum_cust_main returns the single customer (if any) who
3316 referred this customer.
3320 sub referral_cust_main {
3322 my $depth = @_ ? shift : 1;
3323 my $exclude = @_ ? shift : {};
3326 map { $exclude->{$_->custnum}++; $_; }
3327 grep { ! $exclude->{ $_->custnum } }
3328 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3332 map { $_->referral_cust_main($depth-1, $exclude) }
3339 =item referral_cust_main_ncancelled
3341 Same as referral_cust_main, except only returns customers with uncancelled
3346 sub referral_cust_main_ncancelled {
3348 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3351 =item referral_cust_pkg [ DEPTH ]
3353 Like referral_cust_main, except returns a flat list of all unsuspended (and
3354 uncancelled) packages for each customer. The number of items in this list may
3355 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3359 sub referral_cust_pkg {
3361 my $depth = @_ ? shift : 1;
3363 map { $_->unsuspended_pkgs }
3364 grep { $_->unsuspended_pkgs }
3365 $self->referral_cust_main($depth);
3368 =item referring_cust_main
3370 Returns the single cust_main record for the customer who referred this customer
3371 (referral_custnum), or false.
3375 sub referring_cust_main {
3377 return '' unless $self->referral_custnum;
3378 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3381 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3383 Applies a credit to this customer. If there is an error, returns the error,
3384 otherwise returns false.
3386 REASON can be a text string, an FS::reason object, or a scalar reference to
3387 a reasonnum. If a text string, it will be automatically inserted as a new
3388 reason, and a 'reason_type' option must be passed to indicate the
3389 FS::reason_type for the new reason.
3391 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3392 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3393 I<commission_pkgnum>.
3395 Any other options are passed to FS::cust_credit::insert.
3400 my( $self, $amount, $reason, %options ) = @_;
3402 my $cust_credit = new FS::cust_credit {
3403 'custnum' => $self->custnum,
3404 'amount' => $amount,
3407 if ( ref($reason) ) {
3409 if ( ref($reason) eq 'SCALAR' ) {
3410 $cust_credit->reasonnum( $$reason );
3412 $cust_credit->reasonnum( $reason->reasonnum );
3416 $cust_credit->set('reason', $reason)
3419 $cust_credit->$_( delete $options{$_} )
3420 foreach grep exists($options{$_}),
3421 qw( addlinfo eventnum ),
3422 map "commission_$_", qw( agentnum salesnum pkgnum );
3424 $cust_credit->insert(%options);
3428 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3430 Creates a one-time charge for this customer. If there is an error, returns
3431 the error, otherwise returns false.
3433 New-style, with a hashref of options:
3435 my $error = $cust_main->charge(
3439 'start_date' => str2time('7/4/2009'),
3440 'pkg' => 'Description',
3441 'comment' => 'Comment',
3442 'additional' => [], #extra invoice detail
3443 'classnum' => 1, #pkg_class
3445 'setuptax' => '', # or 'Y' for tax exempt
3447 'locationnum'=> 1234, # optional
3450 'taxclass' => 'Tax class',
3453 'taxproduct' => 2, #part_pkg_taxproduct
3454 'override' => {}, #XXX describe
3456 #will be filled in with the new object
3457 'cust_pkg_ref' => \$cust_pkg,
3459 #generate an invoice immediately
3461 'invoice_terms' => '', #with these terms
3467 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3471 #super false laziness w/quotation::charge
3474 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3475 my ( $pkg, $comment, $additional );
3476 my ( $setuptax, $taxclass ); #internal taxes
3477 my ( $taxproduct, $override ); #vendor (CCH) taxes
3479 my $separate_bill = '';
3480 my $cust_pkg_ref = '';
3481 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3483 if ( ref( $_[0] ) ) {
3484 $amount = $_[0]->{amount};
3485 $setup_cost = $_[0]->{setup_cost};
3486 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3487 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3488 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3489 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3490 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3491 : '$'. sprintf("%.2f",$amount);
3492 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3493 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3494 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3495 $additional = $_[0]->{additional} || [];
3496 $taxproduct = $_[0]->{taxproductnum};
3497 $override = { '' => $_[0]->{tax_override} };
3498 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3499 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3500 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3501 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3502 $separate_bill = $_[0]->{separate_bill} || '';
3508 $pkg = @_ ? shift : 'One-time charge';
3509 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3511 $taxclass = @_ ? shift : '';
3515 local $SIG{HUP} = 'IGNORE';
3516 local $SIG{INT} = 'IGNORE';
3517 local $SIG{QUIT} = 'IGNORE';
3518 local $SIG{TERM} = 'IGNORE';
3519 local $SIG{TSTP} = 'IGNORE';
3520 local $SIG{PIPE} = 'IGNORE';
3522 my $oldAutoCommit = $FS::UID::AutoCommit;
3523 local $FS::UID::AutoCommit = 0;
3526 my $part_pkg = new FS::part_pkg ( {
3528 'comment' => $comment,
3532 'classnum' => ( $classnum ? $classnum : '' ),
3533 'setuptax' => $setuptax,
3534 'taxclass' => $taxclass,
3535 'taxproductnum' => $taxproduct,
3536 'setup_cost' => $setup_cost,
3539 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3540 ( 0 .. @$additional - 1 )
3542 'additional_count' => scalar(@$additional),
3543 'setup_fee' => $amount,
3546 my $error = $part_pkg->insert( options => \%options,
3547 tax_overrides => $override,
3550 $dbh->rollback if $oldAutoCommit;
3554 my $pkgpart = $part_pkg->pkgpart;
3555 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3556 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3557 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3558 $error = $type_pkgs->insert;
3560 $dbh->rollback if $oldAutoCommit;
3565 my $cust_pkg = new FS::cust_pkg ( {
3566 'custnum' => $self->custnum,
3567 'pkgpart' => $pkgpart,
3568 'quantity' => $quantity,
3569 'start_date' => $start_date,
3570 'no_auto' => $no_auto,
3571 'separate_bill' => $separate_bill,
3572 'locationnum'=> $locationnum,
3575 $error = $cust_pkg->insert;
3577 $dbh->rollback if $oldAutoCommit;
3579 } elsif ( $cust_pkg_ref ) {
3580 ${$cust_pkg_ref} = $cust_pkg;
3584 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3585 'pkg_list' => [ $cust_pkg ],
3588 $dbh->rollback if $oldAutoCommit;
3593 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3598 #=item charge_postal_fee
3600 #Applies a one time charge this customer. If there is an error,
3601 #returns the error, returns the cust_pkg charge object or false
3602 #if there was no charge.
3606 # This should be a customer event. For that to work requires that bill
3607 # also be a customer event.
3609 sub charge_postal_fee {
3612 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3613 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3615 my $cust_pkg = new FS::cust_pkg ( {
3616 'custnum' => $self->custnum,
3617 'pkgpart' => $pkgpart,
3621 my $error = $cust_pkg->insert;
3622 $error ? $error : $cust_pkg;
3625 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3627 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3629 Optionally, a list or hashref of additional arguments to the qsearch call can
3636 my $opt = ref($_[0]) ? shift : { @_ };
3638 #return $self->num_cust_bill unless wantarray || keys %$opt;
3640 $opt->{'table'} = 'cust_bill';
3641 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3642 $opt->{'hashref'}{'custnum'} = $self->custnum;
3643 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3645 map { $_ } #behavior of sort undefined in scalar context
3646 sort { $a->_date <=> $b->_date }
3650 =item open_cust_bill
3652 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3657 sub open_cust_bill {
3661 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3667 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3669 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3673 sub legacy_cust_bill {
3676 #return $self->num_legacy_cust_bill unless wantarray;
3678 map { $_ } #behavior of sort undefined in scalar context
3679 sort { $a->_date <=> $b->_date }
3680 qsearch({ 'table' => 'legacy_cust_bill',
3681 'hashref' => { 'custnum' => $self->custnum, },
3682 'order_by' => 'ORDER BY _date ASC',
3686 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3688 Returns all the statements (see L<FS::cust_statement>) for this customer.
3690 Optionally, a list or hashref of additional arguments to the qsearch call can
3695 =item cust_bill_void
3697 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3701 sub cust_bill_void {
3704 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3705 sort { $a->_date <=> $b->_date }
3706 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3709 sub cust_statement {
3711 my $opt = ref($_[0]) ? shift : { @_ };
3713 #return $self->num_cust_statement unless wantarray || keys %$opt;
3715 $opt->{'table'} = 'cust_statement';
3716 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3717 $opt->{'hashref'}{'custnum'} = $self->custnum;
3718 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3720 map { $_ } #behavior of sort undefined in scalar context
3721 sort { $a->_date <=> $b->_date }
3725 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3727 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3729 Optionally, a list or hashref of additional arguments to the qsearch call can
3730 be passed following the SVCDB.
3737 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3738 warn "$me svc_x requires a svcdb";
3741 my $opt = ref($_[0]) ? shift : { @_ };
3743 $opt->{'table'} = $svcdb;
3744 $opt->{'addl_from'} =
3745 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3746 ($opt->{'addl_from'} || '');
3748 my $custnum = $self->custnum;
3749 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3750 my $where = "cust_pkg.custnum = $custnum";
3752 my $extra_sql = $opt->{'extra_sql'} || '';
3753 if ( keys %{ $opt->{'hashref'} } ) {
3754 $extra_sql = " AND $where $extra_sql";
3757 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3758 $extra_sql = "WHERE $where AND $1";
3761 $extra_sql = "WHERE $where $extra_sql";
3764 $opt->{'extra_sql'} = $extra_sql;
3769 # required for use as an eventtable;
3772 $self->svc_x('svc_acct', @_);
3777 Returns all the credits (see L<FS::cust_credit>) for this customer.
3783 map { $_ } #return $self->num_cust_credit unless wantarray;
3784 sort { $a->_date <=> $b->_date }
3785 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3788 =item cust_credit_pkgnum
3790 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3791 package when using experimental package balances.
3795 sub cust_credit_pkgnum {
3796 my( $self, $pkgnum ) = @_;
3797 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3798 sort { $a->_date <=> $b->_date }
3799 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3800 'pkgnum' => $pkgnum,
3805 =item cust_credit_void
3807 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3811 sub cust_credit_void {
3814 sort { $a->_date <=> $b->_date }
3815 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3820 Returns all the payments (see L<FS::cust_pay>) for this customer.
3826 my $opt = ref($_[0]) ? shift : { @_ };
3828 return $self->num_cust_pay unless wantarray || keys %$opt;
3830 $opt->{'table'} = 'cust_pay';
3831 $opt->{'hashref'}{'custnum'} = $self->custnum;
3833 map { $_ } #behavior of sort undefined in scalar context
3834 sort { $a->_date <=> $b->_date }
3841 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3842 called automatically when the cust_pay method is used in a scalar context.
3848 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3849 my $sth = dbh->prepare($sql) or die dbh->errstr;
3850 $sth->execute($self->custnum) or die $sth->errstr;
3851 $sth->fetchrow_arrayref->[0];
3854 =item unapplied_cust_pay
3856 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3860 sub unapplied_cust_pay {
3864 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3870 =item cust_pay_pkgnum
3872 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3873 package when using experimental package balances.
3877 sub cust_pay_pkgnum {
3878 my( $self, $pkgnum ) = @_;
3879 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3880 sort { $a->_date <=> $b->_date }
3881 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3882 'pkgnum' => $pkgnum,
3889 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3895 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3896 sort { $a->_date <=> $b->_date }
3897 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3900 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3902 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3904 Optionally, a list or hashref of additional arguments to the qsearch call can
3909 sub cust_pay_batch {
3911 my $opt = ref($_[0]) ? shift : { @_ };
3913 #return $self->num_cust_statement unless wantarray || keys %$opt;
3915 $opt->{'table'} = 'cust_pay_batch';
3916 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3917 $opt->{'hashref'}{'custnum'} = $self->custnum;
3918 $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3920 map { $_ } #behavior of sort undefined in scalar context
3921 sort { $a->paybatchnum <=> $b->paybatchnum }
3925 =item cust_pay_pending
3927 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3928 (without status "done").
3932 sub cust_pay_pending {
3934 return $self->num_cust_pay_pending unless wantarray;
3935 sort { $a->_date <=> $b->_date }
3936 qsearch( 'cust_pay_pending', {
3937 'custnum' => $self->custnum,
3938 'status' => { op=>'!=', value=>'done' },
3943 =item cust_pay_pending_attempt
3945 Returns all payment attempts / declined payments for this customer, as pending
3946 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3947 a corresponding payment (see L<FS::cust_pay>).
3951 sub cust_pay_pending_attempt {
3953 return $self->num_cust_pay_pending_attempt unless wantarray;
3954 sort { $a->_date <=> $b->_date }
3955 qsearch( 'cust_pay_pending', {
3956 'custnum' => $self->custnum,
3963 =item num_cust_pay_pending
3965 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3966 customer (without status "done"). Also called automatically when the
3967 cust_pay_pending method is used in a scalar context.
3971 sub num_cust_pay_pending {
3974 " SELECT COUNT(*) FROM cust_pay_pending ".
3975 " WHERE custnum = ? AND status != 'done' ",
3980 =item num_cust_pay_pending_attempt
3982 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3983 customer, with status "done" but without a corresp. Also called automatically when the
3984 cust_pay_pending method is used in a scalar context.
3988 sub num_cust_pay_pending_attempt {
3991 " SELECT COUNT(*) FROM cust_pay_pending ".
3992 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3999 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4005 map { $_ } #return $self->num_cust_refund unless wantarray;
4006 sort { $a->_date <=> $b->_date }
4007 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4010 =item display_custnum
4012 Returns the displayed customer number for this customer: agent_custid if
4013 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4017 sub display_custnum {
4020 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4021 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
4022 if ( $special eq 'CoStAg' ) {
4023 $prefix = uc( join('',
4025 ($self->state =~ /^(..)/),
4026 $prefix || ($self->agent->agent =~ /^(..)/)
4029 elsif ( $special eq 'CoStCl' ) {
4030 $prefix = uc( join('',
4032 ($self->state =~ /^(..)/),
4033 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
4036 # add any others here if needed
4039 my $length = $conf->config('cust_main-custnum-display_length');
4040 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
4041 return $self->agent_custid;
4042 } elsif ( $prefix ) {
4043 $length = 8 if !defined($length);
4045 sprintf('%0'.$length.'d', $self->custnum)
4046 } elsif ( $length ) {
4047 return sprintf('%0'.$length.'d', $self->custnum);
4049 return $self->custnum;
4055 Returns a name string for this customer, either "Company (Last, First)" or
4062 my $name = $self->contact;
4063 $name = $self->company. " ($name)" if $self->company;
4067 =item service_contact
4069 Returns the L<FS::contact> object for this customer that has the 'Service'
4070 contact class, or undef if there is no such contact. Deprecated; don't use
4075 sub service_contact {
4077 if ( !exists($self->{service_contact}) ) {
4078 my $classnum = $self->scalar_sql(
4079 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4080 ) || 0; #if it's zero, qsearchs will return nothing
4081 $self->{service_contact} = qsearchs('contact', {
4082 'classnum' => $classnum, 'custnum' => $self->custnum
4085 $self->{service_contact};
4090 Returns a name string for this (service/shipping) contact, either
4091 "Company (Last, First)" or "Last, First".
4098 my $name = $self->ship_contact;
4099 $name = $self->company. " ($name)" if $self->company;
4105 Returns a name string for this customer, either "Company" or "First Last".
4111 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4114 =item ship_name_short
4116 Returns a name string for this (service/shipping) contact, either "Company"
4121 sub ship_name_short {
4123 $self->service_contact
4124 ? $self->ship_contact_firstlast
4130 Returns this customer's full (billing) contact name only, "Last, First"
4136 $self->get('last'). ', '. $self->first;
4141 Returns this customer's full (shipping) contact name only, "Last, First"
4147 my $contact = $self->service_contact || $self;
4148 $contact->get('last') . ', ' . $contact->get('first');
4151 =item contact_firstlast
4153 Returns this customers full (billing) contact name only, "First Last".
4157 sub contact_firstlast {
4159 $self->first. ' '. $self->get('last');
4162 =item ship_contact_firstlast
4164 Returns this customer's full (shipping) contact name only, "First Last".
4168 sub ship_contact_firstlast {
4170 my $contact = $self->service_contact || $self;
4171 $contact->get('first') . ' '. $contact->get('last');
4174 #XXX this doesn't work in 3.x+
4177 #Returns this customer's full country name
4183 # code2country($self->country);
4186 sub bill_country_full {
4188 code2country($self->bill_location->country);
4191 sub ship_country_full {
4193 code2country($self->ship_location->country);
4196 =item county_state_county [ PREFIX ]
4198 Returns a string consisting of just the county, state and country.
4202 sub county_state_country {
4205 if ( @_ && $_[0] && $self->has_ship_address ) {
4206 $locationnum = $self->ship_locationnum;
4208 $locationnum = $self->bill_locationnum;
4210 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4211 $cust_location->county_state_country;
4214 =item geocode DATA_VENDOR
4216 Returns a value for the customer location as encoded by DATA_VENDOR.
4217 Currently this only makes sense for "CCH" as DATA_VENDOR.
4225 Returns a status string for this customer, currently:
4229 =item prospect - No packages have ever been ordered
4231 =item ordered - Recurring packages all are new (not yet billed).
4233 =item active - One or more recurring packages is active
4235 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4237 =item suspended - All non-cancelled recurring packages are suspended
4239 =item cancelled - All recurring packages are cancelled
4243 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4244 cust_main-status_module configuration option.
4248 sub status { shift->cust_status(@_); }
4252 for my $status ( FS::cust_main->statuses() ) {
4253 my $method = $status.'_sql';
4254 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4255 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4256 $sth->execute( ($self->custnum) x $numnum )
4257 or die "Error executing 'SELECT $sql': ". $sth->errstr;
4258 return $status if $sth->fetchrow_arrayref->[0];
4262 =item is_status_delay_cancel
4264 Returns true if customer status is 'suspended'
4265 and all suspended cust_pkg return true for
4266 cust_pkg->is_status_delay_cancel.
4268 This is not a real status, this only meant for hacking display
4269 values, because otherwise treating the customer as suspended is
4270 really the whole point of the delay_cancel option.
4274 sub is_status_delay_cancel {
4276 return 0 unless $self->status eq 'suspended';
4277 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4278 return 0 unless $cust_pkg->is_status_delay_cancel;
4283 =item ucfirst_cust_status
4285 =item ucfirst_status
4287 Returns the status with the first character capitalized.
4291 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4293 sub ucfirst_cust_status {
4295 ucfirst($self->cust_status);
4300 Returns a hex triplet color string for this customer's status.
4304 sub statuscolor { shift->cust_statuscolor(@_); }
4306 sub cust_statuscolor {
4308 __PACKAGE__->statuscolors->{$self->cust_status};
4311 =item tickets [ STATUS ]
4313 Returns an array of hashes representing the customer's RT tickets.
4315 An optional status (or arrayref or hashref of statuses) may be specified.
4321 my $status = ( @_ && $_[0] ) ? shift : '';
4323 my $num = $conf->config('cust_main-max_tickets') || 10;
4326 if ( $conf->config('ticket_system') ) {
4327 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4329 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4338 foreach my $priority (
4339 $conf->config('ticket_system-custom_priority_field-values'), ''
4341 last if scalar(@tickets) >= $num;
4343 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4344 $num - scalar(@tickets),
4355 # Return services representing svc_accts in customer support packages
4356 sub support_services {
4358 my %packages = map { $_ => 1 } $conf->config('support_packages');
4360 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4361 grep { $_->part_svc->svcdb eq 'svc_acct' }
4362 map { $_->cust_svc }
4363 grep { exists $packages{ $_->pkgpart } }
4364 $self->ncancelled_pkgs;
4368 # Return a list of latitude/longitude for one of the services (if any)
4369 sub service_coordinates {
4373 grep { $_->latitude && $_->longitude }
4375 map { $_->cust_svc }
4376 $self->ncancelled_pkgs;
4378 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4383 Returns a masked version of the named field
4388 my ($self,$field) = @_;
4392 'x'x(length($self->getfield($field))-4).
4393 substr($self->getfield($field), (length($self->getfield($field))-4));
4399 =head1 CLASS METHODS
4405 Class method that returns the list of possible status strings for customers
4406 (see L<the status method|/status>). For example:
4408 @statuses = FS::cust_main->statuses();
4414 keys %{ $self->statuscolors };
4417 =item cust_status_sql
4419 Returns an SQL fragment to determine the status of a cust_main record, as a
4424 sub cust_status_sql {
4426 for my $status ( FS::cust_main->statuses() ) {
4427 my $method = $status.'_sql';
4428 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4437 Returns an SQL expression identifying prospective cust_main records (customers
4438 with no packages ever ordered)
4442 use vars qw($select_count_pkgs);
4443 $select_count_pkgs =
4444 "SELECT COUNT(*) FROM cust_pkg
4445 WHERE cust_pkg.custnum = cust_main.custnum";
4447 sub select_count_pkgs_sql {
4452 " 0 = ( $select_count_pkgs ) ";
4457 Returns an SQL expression identifying ordered cust_main records (customers with
4458 no active packages, but recurring packages not yet setup or one time charges
4464 FS::cust_main->none_active_sql.
4465 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4470 Returns an SQL expression identifying active cust_main records (customers with
4471 active recurring packages).
4476 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4479 =item none_active_sql
4481 Returns an SQL expression identifying cust_main records with no active
4482 recurring packages. This includes customers of status prospect, ordered,
4483 inactive, and suspended.
4487 sub none_active_sql {
4488 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4493 Returns an SQL expression identifying inactive cust_main records (customers with
4494 no active recurring packages, but otherwise unsuspended/uncancelled).
4499 FS::cust_main->none_active_sql.
4500 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4506 Returns an SQL expression identifying suspended cust_main records.
4511 sub suspended_sql { susp_sql(@_); }
4513 FS::cust_main->none_active_sql.
4514 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4520 Returns an SQL expression identifying cancelled cust_main records.
4524 sub cancel_sql { shift->cancelled_sql(@_); }
4527 =item uncancelled_sql
4529 Returns an SQL expression identifying un-cancelled cust_main records.
4533 sub uncancelled_sql { uncancel_sql(@_); }
4534 sub uncancel_sql { "
4535 ( 0 < ( $select_count_pkgs
4536 AND ( cust_pkg.cancel IS NULL
4537 OR cust_pkg.cancel = 0
4540 OR 0 = ( $select_count_pkgs )
4546 Returns an SQL fragment to retreive the balance.
4551 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4552 WHERE cust_bill.custnum = cust_main.custnum )
4553 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4554 WHERE cust_pay.custnum = cust_main.custnum )
4555 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4556 WHERE cust_credit.custnum = cust_main.custnum )
4557 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4558 WHERE cust_refund.custnum = cust_main.custnum )
4561 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4563 Returns an SQL fragment to retreive the balance for this customer, optionally
4564 considering invoices with date earlier than START_TIME, and not
4565 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4566 total_unapplied_payments).
4568 Times are specified as SQL fragments or numeric
4569 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4570 L<Date::Parse> for conversion functions. The empty string can be passed
4571 to disable that time constraint completely.
4573 Available options are:
4577 =item unapplied_date
4579 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
4584 set to true to remove all customer comparison clauses, for totals
4589 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4594 JOIN clause (typically used with the total option)
4598 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4599 time will be ignored. Note that START_TIME and END_TIME only limit the date
4600 range for invoices and I<unapplied> payments, credits, and refunds.
4606 sub balance_date_sql {
4607 my( $class, $start, $end, %opt ) = @_;
4609 my $cutoff = $opt{'cutoff'};
4611 my $owed = FS::cust_bill->owed_sql($cutoff);
4612 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4613 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4614 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4616 my $j = $opt{'join'} || '';
4618 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4619 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4620 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4621 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4623 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4624 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4625 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4626 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4631 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4633 Returns an SQL fragment to retreive the total unapplied payments for this
4634 customer, only considering payments with date earlier than START_TIME, and
4635 optionally not later than END_TIME.
4637 Times are specified as SQL fragments or numeric
4638 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4639 L<Date::Parse> for conversion functions. The empty string can be passed
4640 to disable that time constraint completely.
4642 Available options are:
4646 sub unapplied_payments_date_sql {
4647 my( $class, $start, $end, %opt ) = @_;
4649 my $cutoff = $opt{'cutoff'};
4651 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4653 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4654 'unapplied_date'=>1 );
4656 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4659 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4661 Helper method for balance_date_sql; name (and usage) subject to change
4662 (suggestions welcome).
4664 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4665 cust_refund, cust_credit or cust_pay).
4667 If TABLE is "cust_bill" or the unapplied_date option is true, only
4668 considers records with date earlier than START_TIME, and optionally not
4669 later than END_TIME .
4673 sub _money_table_where {
4674 my( $class, $table, $start, $end, %opt ) = @_;
4677 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4678 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4679 push @where, "$table._date <= $start" if defined($start) && length($start);
4680 push @where, "$table._date > $end" if defined($end) && length($end);
4682 push @where, @{$opt{'where'}} if $opt{'where'};
4683 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4689 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4690 use FS::cust_main::Search;
4693 FS::cust_main::Search->search(@_);
4708 #warn join('-',keys %$param);
4709 my $fh = $param->{filehandle};
4710 my $agentnum = $param->{agentnum};
4711 my $format = $param->{format};
4713 my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4716 if ( $format eq 'simple' ) {
4717 @fields = qw( custnum agent_custid amount pkg );
4719 die "unknown format $format";
4722 eval "use Text::CSV_XS;";
4725 my $csv = new Text::CSV_XS;
4732 local $SIG{HUP} = 'IGNORE';
4733 local $SIG{INT} = 'IGNORE';
4734 local $SIG{QUIT} = 'IGNORE';
4735 local $SIG{TERM} = 'IGNORE';
4736 local $SIG{TSTP} = 'IGNORE';
4737 local $SIG{PIPE} = 'IGNORE';
4739 my $oldAutoCommit = $FS::UID::AutoCommit;
4740 local $FS::UID::AutoCommit = 0;
4743 #while ( $columns = $csv->getline($fh) ) {
4745 while ( defined($line=<$fh>) ) {
4747 $csv->parse($line) or do {
4748 $dbh->rollback if $oldAutoCommit;
4749 return "can't parse: ". $csv->error_input();
4752 my @columns = $csv->fields();
4753 #warn join('-',@columns);
4756 foreach my $field ( @fields ) {
4757 $row{$field} = shift @columns;
4760 if ( $row{custnum} && $row{agent_custid} ) {
4761 dbh->rollback if $oldAutoCommit;
4762 return "can't specify custnum with agent_custid $row{agent_custid}";
4766 if ( $row{agent_custid} && $agentnum ) {
4767 %hash = ( 'agent_custid' => $row{agent_custid},
4768 'agentnum' => $agentnum,
4772 if ( $row{custnum} ) {
4773 %hash = ( 'custnum' => $row{custnum} );
4776 unless ( scalar(keys %hash) ) {
4777 $dbh->rollback if $oldAutoCommit;
4778 return "can't find customer without custnum or agent_custid and agentnum";
4781 my $cust_main = qsearchs('cust_main', { %hash } );
4782 unless ( $cust_main ) {
4783 $dbh->rollback if $oldAutoCommit;
4784 my $custnum = $row{custnum} || $row{agent_custid};
4785 return "unknown custnum $custnum";
4788 if ( $row{'amount'} > 0 ) {
4789 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4791 $dbh->rollback if $oldAutoCommit;
4795 } elsif ( $row{'amount'} < 0 ) {
4796 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4799 $dbh->rollback if $oldAutoCommit;
4809 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4811 return "Empty file!" unless $imported;
4817 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4819 Deprecated. Use event notification and message templates
4820 (L<FS::msg_template>) instead.
4822 Sends a templated email notification to the customer (see L<Text::Template>).
4824 OPTIONS is a hash and may include
4826 I<from> - the email sender (default is invoice_from)
4828 I<to> - comma-separated scalar or arrayref of recipients
4829 (default is invoicing_list)
4831 I<subject> - The subject line of the sent email notification
4832 (default is "Notice from company_name")
4834 I<extra_fields> - a hashref of name/value pairs which will be substituted
4837 The following variables are vavailable in the template.
4839 I<$first> - the customer first name
4840 I<$last> - the customer last name
4841 I<$company> - the customer company
4842 I<$payby> - a description of the method of payment for the customer
4843 # would be nice to use FS::payby::shortname
4844 I<$payinfo> - the account information used to collect for this customer
4845 I<$expdate> - the expiration of the customer payment in seconds from epoch
4850 my ($self, $template, %options) = @_;
4852 return unless $conf->exists($template);
4854 my $from = $conf->invoice_from_full($self->agentnum)
4855 if $conf->exists('invoice_from', $self->agentnum);
4856 $from = $options{from} if exists($options{from});
4858 my $to = join(',', $self->invoicing_list_emailonly);
4859 $to = $options{to} if exists($options{to});
4861 my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4862 if $conf->exists('company_name', $self->agentnum);
4863 $subject = $options{subject} if exists($options{subject});
4865 my $notify_template = new Text::Template (TYPE => 'ARRAY',
4866 SOURCE => [ map "$_\n",
4867 $conf->config($template)]
4869 or die "can't create new Text::Template object: Text::Template::ERROR";
4870 $notify_template->compile()
4871 or die "can't compile template: Text::Template::ERROR";
4873 $FS::notify_template::_template::company_name =
4874 $conf->config('company_name', $self->agentnum);
4875 $FS::notify_template::_template::company_address =
4876 join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4878 my $paydate = $self->paydate || '2037-12-31';
4879 $FS::notify_template::_template::first = $self->first;
4880 $FS::notify_template::_template::last = $self->last;
4881 $FS::notify_template::_template::company = $self->company;
4882 $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4883 my $payby = $self->payby;
4884 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4885 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4887 #credit cards expire at the end of the month/year of their exp date
4888 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4889 $FS::notify_template::_template::payby = 'credit card';
4890 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4891 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4893 }elsif ($payby eq 'COMP') {
4894 $FS::notify_template::_template::payby = 'complimentary account';
4896 $FS::notify_template::_template::payby = 'current method';
4898 $FS::notify_template::_template::expdate = $expire_time;
4900 for (keys %{$options{extra_fields}}){
4902 ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4905 send_email(from => $from,
4907 subject => $subject,
4908 body => $notify_template->fill_in( PACKAGE =>
4909 'FS::notify_template::_template' ),
4914 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4916 Generates a templated notification to the customer (see L<Text::Template>).
4918 OPTIONS is a hash and may include
4920 I<extra_fields> - a hashref of name/value pairs which will be substituted
4921 into the template. These values may override values mentioned below
4922 and those from the customer record.
4924 The following variables are available in the template instead of or in addition
4925 to the fields of the customer record.
4927 I<$payby> - a description of the method of payment for the customer
4928 # would be nice to use FS::payby::shortname
4929 I<$payinfo> - the masked account information used to collect for this customer
4930 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4931 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4935 # a lot like cust_bill::print_latex
4936 sub generate_letter {
4937 my ($self, $template, %options) = @_;
4939 return unless $conf->exists($template);
4941 my $letter_template = new Text::Template
4943 SOURCE => [ map "$_\n", $conf->config($template)],
4944 DELIMITERS => [ '[@--', '--@]' ],
4946 or die "can't create new Text::Template object: Text::Template::ERROR";
4948 $letter_template->compile()
4949 or die "can't compile template: Text::Template::ERROR";
4951 my %letter_data = map { $_ => $self->$_ } $self->fields;
4952 $letter_data{payinfo} = $self->mask_payinfo;
4954 #my $paydate = $self->paydate || '2037-12-31';
4955 my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4957 my $payby = $self->payby;
4958 my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4959 my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4961 #credit cards expire at the end of the month/year of their exp date
4962 if ($payby eq 'CARD' || $payby eq 'DCRD') {
4963 $letter_data{payby} = 'credit card';
4964 ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4965 $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4967 }elsif ($payby eq 'COMP') {
4968 $letter_data{payby} = 'complimentary account';
4970 $letter_data{payby} = 'current method';
4972 $letter_data{expdate} = $expire_time;
4974 for (keys %{$options{extra_fields}}){
4975 $letter_data{$_} = $options{extra_fields}->{$_};
4978 unless(exists($letter_data{returnaddress})){
4979 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4980 $self->agent_template)
4982 if ( length($retadd) ) {
4983 $letter_data{returnaddress} = $retadd;
4984 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4985 $letter_data{returnaddress} =
4986 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4990 ( $conf->config('company_name', $self->agentnum),
4991 $conf->config('company_address', $self->agentnum),
4995 $letter_data{returnaddress} = '~';
4999 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5001 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5003 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5005 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5009 ) or die "can't open temp file: $!\n";
5010 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5011 or die "can't write temp file: $!\n";
5013 $letter_data{'logo_file'} = $lh->filename;
5015 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5019 ) or die "can't open temp file: $!\n";
5021 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5023 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5024 return ($1, $letter_data{'logo_file'});
5028 =item print_ps TEMPLATE
5030 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5036 my($file, $lfile) = $self->generate_letter(@_);
5037 my $ps = FS::Misc::generate_ps($file);
5038 unlink($file.'.tex');
5044 =item print TEMPLATE
5046 Prints the filled in template.
5048 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5052 sub queueable_print {
5055 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5056 or die "invalid customer number: " . $opt{custnum};
5058 my $error = $self->print( { 'template' => $opt{template} } );
5059 die $error if $error;
5063 my ($self, $template) = (shift, shift);
5065 [ $self->print_ps($template) ],
5066 'agentnum' => $self->agentnum,
5070 #these three subs should just go away once agent stuff is all config overrides
5072 sub agent_template {
5074 $self->_agent_plandata('agent_templatename');
5077 sub agent_invoice_from {
5079 $self->_agent_plandata('agent_invoice_from');
5082 sub _agent_plandata {
5083 my( $self, $option ) = @_;
5085 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5086 #agent-specific Conf
5088 use FS::part_event::Condition;
5090 my $agentnum = $self->agentnum;
5092 my $regexp = regexp_sql();
5094 my $part_event_option =
5096 'select' => 'part_event_option.*',
5097 'table' => 'part_event_option',
5099 LEFT JOIN part_event USING ( eventpart )
5100 LEFT JOIN part_event_option AS peo_agentnum
5101 ON ( part_event.eventpart = peo_agentnum.eventpart
5102 AND peo_agentnum.optionname = 'agentnum'
5103 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5105 LEFT JOIN part_event_condition
5106 ON ( part_event.eventpart = part_event_condition.eventpart
5107 AND part_event_condition.conditionname = 'cust_bill_age'
5109 LEFT JOIN part_event_condition_option
5110 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5111 AND part_event_condition_option.optionname = 'age'
5114 #'hashref' => { 'optionname' => $option },
5115 #'hashref' => { 'part_event_option.optionname' => $option },
5117 " WHERE part_event_option.optionname = ". dbh->quote($option).
5118 " AND action = 'cust_bill_send_agent' ".
5119 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5120 " AND peo_agentnum.optionname = 'agentnum' ".
5121 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5123 CASE WHEN part_event_condition_option.optionname IS NULL
5125 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5127 , part_event.weight".
5131 unless ( $part_event_option ) {
5132 return $self->agent->invoice_template || ''
5133 if $option eq 'agent_templatename';
5137 $part_event_option->optionvalue;
5141 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5143 Subroutine (not a method), designed to be called from the queue.
5145 Takes a list of options and values.
5147 Pulls up the customer record via the custnum option and calls bill_and_collect.
5152 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5154 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5155 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5157 #without this errors don't get rolled back
5158 $args{'fatal'} = 1; # runs from job queue, will be caught
5160 $cust_main->bill_and_collect( %args );
5163 sub process_bill_and_collect {
5165 my $param = thaw(decode_base64(shift));
5166 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5167 or die "custnum '$param->{custnum}' not found!\n";
5168 $param->{'job'} = $job;
5169 $param->{'fatal'} = 1; # runs from job queue, will be caught
5170 $param->{'retry'} = 1;
5172 $cust_main->bill_and_collect( %$param );
5175 #hook for insert/replace
5176 #runs after locations have been set
5177 #but before custnum has been set (for insert)
5181 #turn off invoice_ship_address if ship & bill are the same
5182 if ($self->bill_locationnum eq $self->ship_locationnum) {
5183 $self->invoice_ship_address('');
5185 #preserve old value if global config is set (replace only)
5186 elsif ($old && $conf->exists('invoice-ship_address')) {
5187 $self->invoice_ship_address($old->invoice_ship_address);
5191 #starting to take quite a while for big dbs
5192 # (JRNL: journaled so it only happens once per database)
5193 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5194 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5195 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5196 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5197 # JRNL leading/trailing spaces in first, last, company
5198 # - otaker upgrade? journal and call it good? (double check to make sure
5199 # we're not still setting otaker here)
5201 #only going to get worse with new location stuff...
5203 sub _upgrade_data { #class method
5204 my ($class, %opts) = @_;
5207 'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5210 #this seems to be the only expensive one.. why does it take so long?
5211 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5213 'UPDATE cust_main SET signupdate = (SELECT signupdate FROM h_cust_main WHERE signupdate IS NOT NULL AND h_cust_main.custnum = cust_main.custnum ORDER BY historynum DESC LIMIT 1) WHERE signupdate IS NULL';
5214 FS::upgrade_journal->set_done('cust_main__signupdate');
5217 unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5219 # fix yyyy-m-dd formatted paydates
5220 if ( driver_name =~ /^mysql/i ) {
5222 "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5223 } else { # the SQL standard
5225 "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5227 FS::upgrade_journal->set_done('cust_main__paydate');
5230 unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5232 push @statements, #fix the weird BILL with a cc# in payinfo problem
5234 "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5236 FS::upgrade_journal->set_done('cust_main__payinfo');
5241 foreach my $sql ( @statements ) {
5242 my $sth = dbh->prepare($sql) or die dbh->errstr;
5243 $sth->execute or die $sth->errstr;
5244 #warn ( (time - $t). " seconds\n" );
5248 local($ignore_expired_card) = 1;
5249 local($ignore_banned_card) = 1;
5250 local($skip_fuzzyfiles) = 1;
5251 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5253 FS::cust_main::Location->_upgrade_data(%opts);
5255 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5257 foreach my $cust_main ( qsearch({
5258 'table' => 'cust_main',
5260 'extra_sql' => 'WHERE '.
5262 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5263 qw( first last company )
5266 my $error = $cust_main->replace;
5267 die $error if $error;
5270 FS::upgrade_journal->set_done('cust_main__trimspaces');
5274 $class->_upgrade_otaker(%opts);
5284 The delete method should possibly take an FS::cust_main object reference
5285 instead of a scalar customer number.
5287 Bill and collect options should probably be passed as references instead of a
5290 There should probably be a configuration file with a list of allowed credit
5293 No multiple currency support (probably a larger project than just this module).
5295 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5297 Birthdates rely on negative epoch values.
5299 The payby for card/check batches is broken. With mixed batching, bad
5302 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5306 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5307 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5308 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.