2 use base qw( FS::cust_main::Packages
4 FS::cust_main::NationalID
6 FS::cust_main::Billing_Realtime
7 FS::cust_main::Billing_Batch
8 FS::cust_main::Billing_Discount
9 FS::cust_main::Billing_ThirdParty
10 FS::cust_main::Location
11 FS::cust_main::Credit_Limit
14 FS::otaker_Mixin FS::cust_main_Mixin
15 FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
23 use Scalar::Util qw( blessed );
24 use Time::Local qw(timelocal);
29 use File::Temp; #qw( tempfile );
30 use Business::CreditCard 0.28;
31 use FS::UID qw( dbh driver_name );
32 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
34 use FS::Misc qw( generate_ps do_print money_pretty card_types );
35 use FS::Msgcat qw(gettext);
42 use FS::cust_bill_void;
43 use FS::legacy_cust_bill;
45 use FS::cust_pay_pending;
46 use FS::cust_pay_void;
47 use FS::cust_pay_batch;
50 use FS::part_referral;
51 use FS::cust_main_county;
52 use FS::cust_location;
55 use FS::cust_main_exemption;
56 use FS::cust_tax_adjustment;
57 use FS::cust_tax_location;
58 use FS::agent_currency;
59 use FS::cust_main_invoice;
61 use FS::prepay_credit;
67 use FS::payment_gateway;
68 use FS::agent_payment_gateway;
70 use FS::cust_main_note;
71 use FS::cust_attachment;
74 use FS::upgrade_journal;
79 # 1 is mostly method/subroutine entry and options
80 # 2 traces progress of some operations
81 # 3 is even more information including possibly sensitive data
83 our $me = '[FS::cust_main]';
86 our $ignore_expired_card = 0;
87 our $ignore_banned_card = 0;
88 our $ignore_invalid_card = 0;
90 our $skip_fuzzyfiles = 0;
92 our $ucfirst_nowarn = 0;
94 #this info is in cust_payby as of 4.x
95 #this and the fields themselves can be removed in 5.x
96 our @encrypted_fields = ('payinfo', 'paycvv');
97 sub nohistory_fields { ('payinfo', 'paycvv'); }
100 #ask FS::UID to run this stuff for us later
101 #$FS::UID::callback{'FS::cust_main'} = sub {
102 install_callback FS::UID sub {
103 $conf = new FS::Conf;
104 #yes, need it for stuff below (prolly should be cached)
105 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
110 my ( $hashref, $cache ) = @_;
111 if ( exists $hashref->{'pkgnum'} ) {
112 #@{ $self->{'_pkgnum'} } = ();
113 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
114 $self->{'_pkgnum'} = $subcache;
115 #push @{ $self->{'_pkgnum'} },
116 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
122 FS::cust_main - Object methods for cust_main records
128 $record = new FS::cust_main \%hash;
129 $record = new FS::cust_main { 'column' => 'value' };
131 $error = $record->insert;
133 $error = $new_record->replace($old_record);
135 $error = $record->delete;
137 $error = $record->check;
139 @cust_pkg = $record->all_pkgs;
141 @cust_pkg = $record->ncancelled_pkgs;
143 @cust_pkg = $record->suspended_pkgs;
145 $error = $record->bill;
146 $error = $record->bill %options;
147 $error = $record->bill 'time' => $time;
149 $error = $record->collect;
150 $error = $record->collect %options;
151 $error = $record->collect 'invoice_time' => $time,
156 An FS::cust_main object represents a customer. FS::cust_main inherits from
157 FS::Record. The following fields are currently supported:
163 Primary key (assigned automatically for new customers)
167 Agent (see L<FS::agent>)
171 Advertising source (see L<FS::part_referral>)
183 Cocial security number (optional)
207 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
211 Payment Information (See L<FS::payinfo_Mixin> for data format)
215 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
219 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
223 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
227 Start date month (maestro/solo cards only)
231 Start date year (maestro/solo cards only)
235 Issue number (maestro/solo cards only)
239 Name on card or billing name
243 IP address from which payment information was received
247 Tax exempt, empty or `Y'
251 Order taker (see L<FS::access_user>)
257 =item referral_custnum
259 Referring customer number
263 Enable individual CDR spooling, empty or `Y'
267 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
271 Discourage individual CDR printing, empty or `Y'
275 Allow self-service editing of ticket subjects, empty or 'Y'
277 =item calling_list_exempt
279 Do not call, empty or 'Y'
281 =item invoice_ship_address
283 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
293 Creates a new customer. To add the customer to the database, see L<"insert">.
295 Note that this stores the hash reference, not a distinct copy of the hash it
296 points to. You can ask the object for a copy with the I<hash> method.
300 sub table { 'cust_main'; }
302 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
304 Adds this customer to the database. If there is an error, returns the error,
305 otherwise returns false.
307 Usually the customer's location will not yet exist in the database, and
308 the C<bill_location> and C<ship_location> pseudo-fields must be set to
309 uninserted L<FS::cust_location> objects. These will be inserted and linked
310 (in both directions) to the new customer record. If they're references
311 to the same object, they will become the same location.
313 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
314 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
315 are inserted atomicly, or the transaction is rolled back. Passing an empty
316 hash reference is equivalent to not supplying this parameter. There should be
317 a better explanation of this, but until then, here's an example:
320 tie %hash, 'Tie::RefHash'; #this part is important
322 $cust_pkg => [ $svc_acct ],
325 $cust_main->insert( \%hash );
327 INVOICING_LIST_ARYREF: No longer supported.
329 Currently available options are: I<depend_jobnum>, I<noexport>,
330 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
332 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
333 on the supplied jobnum (they will not run until the specific job completes).
334 This can be used to defer provisioning until some action completes (such
335 as running the customer's credit card successfully).
337 The I<noexport> option is deprecated. If I<noexport> is set true, no
338 provisioning jobs (exports) are scheduled. (You can schedule them later with
339 the B<reexport> method.)
341 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
342 of tax names and exemption numbers. FS::cust_main_exemption records will be
343 created and inserted.
345 If I<prospectnum> is set, moves contacts and locations from that prospect.
347 If I<contact> is set to an arrayref of FS::contact objects, those will be
350 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
351 unset), inserts those new contacts with this new customer. Handles CGI
352 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
354 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
355 new stored payment records with this new customer. Handles CGI parameters
356 for an "m2" multiple entry field as passed by edit/cust_main.cgi
362 my $cust_pkgs = @_ ? shift : {};
364 if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
365 warn "cust_main::insert using deprecated invoicing list argument";
366 $invoicing_list = shift;
369 warn "$me insert called with options ".
370 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
373 local $SIG{HUP} = 'IGNORE';
374 local $SIG{INT} = 'IGNORE';
375 local $SIG{QUIT} = 'IGNORE';
376 local $SIG{TERM} = 'IGNORE';
377 local $SIG{TSTP} = 'IGNORE';
378 local $SIG{PIPE} = 'IGNORE';
380 my $oldAutoCommit = $FS::UID::AutoCommit;
381 local $FS::UID::AutoCommit = 0;
384 my $prepay_identifier = '';
385 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
387 if ( $self->payby eq 'PREPAY' ) {
389 $self->payby(''); #'BILL');
390 $prepay_identifier = $self->payinfo;
393 warn " looking up prepaid card $prepay_identifier\n"
396 my $error = $self->get_prepay( $prepay_identifier,
397 'amount_ref' => \$amount,
398 'seconds_ref' => \$seconds,
399 'upbytes_ref' => \$upbytes,
400 'downbytes_ref' => \$downbytes,
401 'totalbytes_ref' => \$totalbytes,
404 $dbh->rollback if $oldAutoCommit;
405 #return "error applying prepaid card (transaction rolled back): $error";
409 $payby = 'PREP' if $amount;
411 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
414 $self->payby(''); #'BILL');
415 $amount = $self->paid;
420 foreach my $l (qw(bill_location ship_location)) {
422 my $loc = delete $self->hashref->{$l} or next;
424 if ( !$loc->locationnum ) {
425 # warn the location that we're going to insert it with no custnum
426 $loc->set(custnum_pending => 1);
427 warn " inserting $l\n"
429 my $error = $loc->insert;
431 $dbh->rollback if $oldAutoCommit;
432 my $label = $l eq 'ship_location' ? 'service' : 'billing';
433 return "$error (in $label location)";
436 } elsif ( $loc->prospectnum ) {
438 $loc->prospectnum('');
439 $loc->set(custnum_pending => 1);
440 my $error = $loc->replace;
442 $dbh->rollback if $oldAutoCommit;
443 my $label = $l eq 'ship_location' ? 'service' : 'billing';
444 return "$error (moving $label location)";
447 } elsif ( ($loc->custnum || 0) > 0 ) {
448 # then it somehow belongs to another customer--shouldn't happen
449 $dbh->rollback if $oldAutoCommit;
450 return "$l belongs to customer ".$loc->custnum;
452 # else it already belongs to this customer
453 # (happens when ship_location is identical to bill_location)
455 $self->set($l.'num', $loc->locationnum);
457 if ( $self->get($l.'num') eq '' ) {
458 $dbh->rollback if $oldAutoCommit;
463 warn " inserting $self\n"
466 $self->signupdate(time) unless $self->signupdate;
468 $self->auto_agent_custid()
469 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
471 my $error = $self->check_payinfo_cardtype
472 || $self->SUPER::insert;
474 $dbh->rollback if $oldAutoCommit;
475 #return "inserting cust_main record (transaction rolled back): $error";
479 # now set cust_location.custnum
480 foreach my $l (qw(bill_location ship_location)) {
481 warn " setting $l.custnum\n"
483 my $loc = $self->$l or next;
484 unless ( $loc->custnum ) {
485 $loc->set(custnum => $self->custnum);
486 $error ||= $loc->replace;
490 $dbh->rollback if $oldAutoCommit;
491 return "error setting $l custnum: $error";
495 warn " setting customer tags\n"
498 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
499 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
500 'custnum' => $self->custnum };
501 my $error = $cust_tag->insert;
503 $dbh->rollback if $oldAutoCommit;
508 my $prospectnum = delete $options{'prospectnum'};
509 if ( $prospectnum ) {
511 warn " moving contacts and locations from prospect $prospectnum\n"
515 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
516 unless ( $prospect_main ) {
517 $dbh->rollback if $oldAutoCommit;
518 return "Unknown prospectnum $prospectnum";
520 $prospect_main->custnum($self->custnum);
521 $prospect_main->disabled('Y');
522 my $error = $prospect_main->replace;
524 $dbh->rollback if $oldAutoCommit;
528 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
529 my $cust_contact = new FS::cust_contact {
530 'custnum' => $self->custnum,
531 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
533 my $error = $cust_contact->insert
534 || $prospect_contact->delete;
536 $dbh->rollback if $oldAutoCommit;
541 my @cust_location = $prospect_main->cust_location;
542 my @qual = $prospect_main->qual;
544 foreach my $r ( @cust_location, @qual ) {
546 $r->custnum($self->custnum);
547 my $error = $r->replace;
549 $dbh->rollback if $oldAutoCommit;
556 warn " setting contacts\n"
559 $invoicing_list ||= $options{'invoicing_list'};
560 if ( $invoicing_list ) {
562 $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
565 foreach my $dest (@$invoicing_list ) {
566 if ($dest eq 'POST') {
567 $self->set('postal_invoice', 'Y');
570 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
571 if ( $contact_email ) {
572 my $cust_contact = FS::cust_contact->new({
573 contactnum => $contact_email->contactnum,
574 custnum => $self->custnum,
576 $cust_contact->set('invoice_dest', 'Y');
577 my $error = $cust_contact->contactnum ?
578 $cust_contact->replace : $cust_contact->insert;
580 $dbh->rollback if $oldAutoCommit;
581 return "$error (linking to email address $dest)";
585 # this email address is not yet linked to any contact
586 $email .= ',' if length($email);
592 my $contact = FS::contact->new({
593 'custnum' => $self->get('custnum'),
594 'last' => $self->get('last'),
595 'first' => $self->get('first'),
596 'emailaddress' => $email,
597 'invoice_dest' => 'Y', # yes, you can set this via the contact
599 my $error = $contact->insert;
601 $dbh->rollback if $oldAutoCommit;
607 if ( my $contact = delete $options{'contact'} ) {
609 foreach my $c ( @$contact ) {
610 $c->custnum($self->custnum);
611 my $error = $c->insert;
613 $dbh->rollback if $oldAutoCommit;
619 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
621 my $error = $self->process_o2m( 'table' => 'contact',
622 'fields' => FS::contact->cgi_contact_fields,
623 'params' => $contact_params,
626 $dbh->rollback if $oldAutoCommit;
631 warn " setting cust_payby\n"
634 if ( $options{cust_payby} ) {
636 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
637 $cust_payby->custnum($self->custnum);
638 my $error = $cust_payby->insert;
640 $dbh->rollback if $oldAutoCommit;
645 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
647 my $error = $self->process_o2m(
648 'table' => 'cust_payby',
649 'fields' => FS::cust_payby->cgi_cust_payby_fields,
650 'params' => $cust_payby_params,
651 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
654 $dbh->rollback if $oldAutoCommit;
660 warn " setting cust_main_exemption\n"
663 my $tax_exemption = delete $options{'tax_exemption'};
664 if ( $tax_exemption ) {
666 $tax_exemption = { map { $_ => '' } @$tax_exemption }
667 if ref($tax_exemption) eq 'ARRAY';
669 foreach my $taxname ( keys %$tax_exemption ) {
670 my $cust_main_exemption = new FS::cust_main_exemption {
671 'custnum' => $self->custnum,
672 'taxname' => $taxname,
673 'exempt_number' => $tax_exemption->{$taxname},
675 my $error = $cust_main_exemption->insert;
677 $dbh->rollback if $oldAutoCommit;
678 return "inserting cust_main_exemption (transaction rolled back): $error";
683 warn " ordering packages\n"
686 $error = $self->order_pkgs( $cust_pkgs,
688 'seconds_ref' => \$seconds,
689 'upbytes_ref' => \$upbytes,
690 'downbytes_ref' => \$downbytes,
691 'totalbytes_ref' => \$totalbytes,
694 $dbh->rollback if $oldAutoCommit;
699 $dbh->rollback if $oldAutoCommit;
700 return "No svc_acct record to apply pre-paid time";
702 if ( $upbytes || $downbytes || $totalbytes ) {
703 $dbh->rollback if $oldAutoCommit;
704 return "No svc_acct record to apply pre-paid data";
708 warn " inserting initial $payby payment of $amount\n"
710 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
712 $dbh->rollback if $oldAutoCommit;
713 return "inserting payment (transaction rolled back): $error";
717 unless ( $import || $skip_fuzzyfiles ) {
718 warn " queueing fuzzyfiles update\n"
720 $error = $self->queue_fuzzyfiles_update;
722 $dbh->rollback if $oldAutoCommit;
723 return "updating fuzzy search cache: $error";
727 # FS::geocode_Mixin::after_insert or something?
728 if ( $conf->config('tax_district_method') and !$import ) {
729 # if anything non-empty, try to look it up
730 my $queue = new FS::queue {
731 'job' => 'FS::geocode_Mixin::process_district_update',
732 'custnum' => $self->custnum,
734 my $error = $queue->insert( ref($self), $self->custnum );
736 $dbh->rollback if $oldAutoCommit;
737 return "queueing tax district update: $error";
742 warn " exporting\n" if $DEBUG > 1;
744 my $export_args = $options{'export_args'} || [];
747 map qsearch( 'part_export', {exportnum=>$_} ),
748 $conf->config('cust_main-exports'); #, $agentnum
750 foreach my $part_export ( @part_export ) {
751 my $error = $part_export->export_insert($self, @$export_args);
753 $dbh->rollback if $oldAutoCommit;
754 return "exporting to ". $part_export->exporttype.
755 " (transaction rolled back): $error";
759 #foreach my $depend_jobnum ( @$depend_jobnums ) {
760 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
762 # foreach my $jobnum ( @jobnums ) {
763 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
764 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
766 # my $error = $queue->depend_insert($depend_jobnum);
768 # $dbh->rollback if $oldAutoCommit;
769 # return "error queuing job dependancy: $error";
776 #if ( exists $options{'jobnums'} ) {
777 # push @{ $options{'jobnums'} }, @jobnums;
780 warn " insert complete; committing transaction\n"
783 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
788 use File::CounterFile;
789 sub auto_agent_custid {
792 my $format = $conf->config('cust_main-auto_agent_custid');
794 if ( $format eq '1YMMXXXXXXXX' ) {
796 my $counter = new File::CounterFile 'cust_main.agent_custid';
799 my $ym = 100000000000 + time2str('%y%m00000000', time);
800 if ( $ym > $counter->value ) {
801 $counter->{'value'} = $agent_custid = $ym;
802 $counter->{'updated'} = 1;
804 $agent_custid = $counter->inc;
810 die "Unknown cust_main-auto_agent_custid format: $format";
813 $self->agent_custid($agent_custid);
817 =item PACKAGE METHODS
819 Documentation on customer package methods has been moved to
820 L<FS::cust_main::Packages>.
822 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
824 Recharges this (existing) customer with the specified prepaid card (see
825 L<FS::prepay_credit>), specified either by I<identifier> or as an
826 FS::prepay_credit object. If there is an error, returns the error, otherwise
829 Optionally, five scalar references can be passed as well. They will have their
830 values filled in with the amount, number of seconds, and number of upload,
831 download, and total bytes applied by this prepaid card.
835 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
836 #the only place that uses these args
837 sub recharge_prepay {
838 my( $self, $prepay_credit, $amountref, $secondsref,
839 $upbytesref, $downbytesref, $totalbytesref ) = @_;
841 local $SIG{HUP} = 'IGNORE';
842 local $SIG{INT} = 'IGNORE';
843 local $SIG{QUIT} = 'IGNORE';
844 local $SIG{TERM} = 'IGNORE';
845 local $SIG{TSTP} = 'IGNORE';
846 local $SIG{PIPE} = 'IGNORE';
848 my $oldAutoCommit = $FS::UID::AutoCommit;
849 local $FS::UID::AutoCommit = 0;
852 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
854 my $error = $self->get_prepay( $prepay_credit,
855 'amount_ref' => \$amount,
856 'seconds_ref' => \$seconds,
857 'upbytes_ref' => \$upbytes,
858 'downbytes_ref' => \$downbytes,
859 'totalbytes_ref' => \$totalbytes,
861 || $self->increment_seconds($seconds)
862 || $self->increment_upbytes($upbytes)
863 || $self->increment_downbytes($downbytes)
864 || $self->increment_totalbytes($totalbytes)
865 || $self->insert_cust_pay_prepay( $amount,
867 ? $prepay_credit->identifier
872 $dbh->rollback if $oldAutoCommit;
876 if ( defined($amountref) ) { $$amountref = $amount; }
877 if ( defined($secondsref) ) { $$secondsref = $seconds; }
878 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
879 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
880 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
882 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
887 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
889 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
890 specified either by I<identifier> or as an FS::prepay_credit object.
892 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
893 incremented by the values of the prepaid card.
895 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
896 check or set this customer's I<agentnum>.
898 If there is an error, returns the error, otherwise returns false.
904 my( $self, $prepay_credit, %opt ) = @_;
906 local $SIG{HUP} = 'IGNORE';
907 local $SIG{INT} = 'IGNORE';
908 local $SIG{QUIT} = 'IGNORE';
909 local $SIG{TERM} = 'IGNORE';
910 local $SIG{TSTP} = 'IGNORE';
911 local $SIG{PIPE} = 'IGNORE';
913 my $oldAutoCommit = $FS::UID::AutoCommit;
914 local $FS::UID::AutoCommit = 0;
917 unless ( ref($prepay_credit) ) {
919 my $identifier = $prepay_credit;
921 $prepay_credit = qsearchs(
923 { 'identifier' => $identifier },
928 unless ( $prepay_credit ) {
929 $dbh->rollback if $oldAutoCommit;
930 return "Invalid prepaid card: ". $identifier;
935 if ( $prepay_credit->agentnum ) {
936 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
937 $dbh->rollback if $oldAutoCommit;
938 return "prepaid card not valid for agent ". $self->agentnum;
940 $self->agentnum($prepay_credit->agentnum);
943 my $error = $prepay_credit->delete;
945 $dbh->rollback if $oldAutoCommit;
946 return "removing prepay_credit (transaction rolled back): $error";
949 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
950 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
952 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
957 =item increment_upbytes SECONDS
959 Updates this customer's single or primary account (see L<FS::svc_acct>) by
960 the specified number of upbytes. If there is an error, returns the error,
961 otherwise returns false.
965 sub increment_upbytes {
966 _increment_column( shift, 'upbytes', @_);
969 =item increment_downbytes SECONDS
971 Updates this customer's single or primary account (see L<FS::svc_acct>) by
972 the specified number of downbytes. If there is an error, returns the error,
973 otherwise returns false.
977 sub increment_downbytes {
978 _increment_column( shift, 'downbytes', @_);
981 =item increment_totalbytes SECONDS
983 Updates this customer's single or primary account (see L<FS::svc_acct>) by
984 the specified number of totalbytes. If there is an error, returns the error,
985 otherwise returns false.
989 sub increment_totalbytes {
990 _increment_column( shift, 'totalbytes', @_);
993 =item increment_seconds SECONDS
995 Updates this customer's single or primary account (see L<FS::svc_acct>) by
996 the specified number of seconds. If there is an error, returns the error,
997 otherwise returns false.
1001 sub increment_seconds {
1002 _increment_column( shift, 'seconds', @_);
1005 =item _increment_column AMOUNT
1007 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1008 the specified number of seconds or bytes. If there is an error, returns
1009 the error, otherwise returns false.
1013 sub _increment_column {
1014 my( $self, $column, $amount ) = @_;
1015 warn "$me increment_column called: $column, $amount\n"
1018 return '' unless $amount;
1020 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1021 $self->ncancelled_pkgs;
1023 if ( ! @cust_pkg ) {
1024 return 'No packages with primary or single services found'.
1025 ' to apply pre-paid time';
1026 } elsif ( scalar(@cust_pkg) > 1 ) {
1027 #maybe have a way to specify the package/account?
1028 return 'Multiple packages found to apply pre-paid time';
1031 my $cust_pkg = $cust_pkg[0];
1032 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1036 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1038 if ( ! @cust_svc ) {
1039 return 'No account found to apply pre-paid time';
1040 } elsif ( scalar(@cust_svc) > 1 ) {
1041 return 'Multiple accounts found to apply pre-paid time';
1044 my $svc_acct = $cust_svc[0]->svc_x;
1045 warn " found service svcnum ". $svc_acct->pkgnum.
1046 ' ('. $svc_acct->email. ")\n"
1049 $column = "increment_$column";
1050 $svc_acct->$column($amount);
1054 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1056 Inserts a prepayment in the specified amount for this customer. An optional
1057 second argument can specify the prepayment identifier for tracking purposes.
1058 If there is an error, returns the error, otherwise returns false.
1062 sub insert_cust_pay_prepay {
1063 shift->insert_cust_pay('PREP', @_);
1066 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1068 Inserts a cash payment in the specified amount for this customer. An optional
1069 second argument can specify the payment identifier for tracking purposes.
1070 If there is an error, returns the error, otherwise returns false.
1074 sub insert_cust_pay_cash {
1075 shift->insert_cust_pay('CASH', @_);
1078 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1080 Inserts a Western Union payment in the specified amount for this customer. An
1081 optional second argument can specify the prepayment identifier for tracking
1082 purposes. If there is an error, returns the error, otherwise returns false.
1086 sub insert_cust_pay_west {
1087 shift->insert_cust_pay('WEST', @_);
1090 sub insert_cust_pay {
1091 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1092 my $payinfo = scalar(@_) ? shift : '';
1094 my $cust_pay = new FS::cust_pay {
1095 'custnum' => $self->custnum,
1096 'paid' => sprintf('%.2f', $amount),
1097 #'_date' => #date the prepaid card was purchased???
1099 'payinfo' => $payinfo,
1105 =item delete [ OPTION => VALUE ... ]
1107 This deletes the customer. If there is an error, returns the error, otherwise
1110 This will completely remove all traces of the customer record. This is not
1111 what you want when a customer cancels service; for that, cancel all of the
1112 customer's packages (see L</cancel>).
1114 If the customer has any uncancelled packages, you need to pass a new (valid)
1115 customer number for those packages to be transferred to, as the "new_customer"
1116 option. Cancelled packages will be deleted. Did I mention that this is NOT
1117 what you want when a customer cancels service and that you really should be
1118 looking at L<FS::cust_pkg/cancel>?
1120 You can't delete a customer with invoices (see L<FS::cust_bill>),
1121 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1122 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1123 set the "delete_financials" option to a true value.
1128 my( $self, %opt ) = @_;
1130 local $SIG{HUP} = 'IGNORE';
1131 local $SIG{INT} = 'IGNORE';
1132 local $SIG{QUIT} = 'IGNORE';
1133 local $SIG{TERM} = 'IGNORE';
1134 local $SIG{TSTP} = 'IGNORE';
1135 local $SIG{PIPE} = 'IGNORE';
1137 my $oldAutoCommit = $FS::UID::AutoCommit;
1138 local $FS::UID::AutoCommit = 0;
1141 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1142 $dbh->rollback if $oldAutoCommit;
1143 return "Can't delete a master agent customer";
1146 #use FS::access_user
1147 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1148 $dbh->rollback if $oldAutoCommit;
1149 return "Can't delete a master employee customer";
1152 tie my %financial_tables, 'Tie::IxHash',
1153 'cust_bill' => 'invoices',
1154 'cust_statement' => 'statements',
1155 'cust_credit' => 'credits',
1156 'cust_pay' => 'payments',
1157 'cust_refund' => 'refunds',
1160 foreach my $table ( keys %financial_tables ) {
1162 my @records = $self->$table();
1164 if ( @records && ! $opt{'delete_financials'} ) {
1165 $dbh->rollback if $oldAutoCommit;
1166 return "Can't delete a customer with ". $financial_tables{$table};
1169 foreach my $record ( @records ) {
1170 my $error = $record->delete;
1172 $dbh->rollback if $oldAutoCommit;
1173 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1179 my @cust_pkg = $self->ncancelled_pkgs;
1181 my $new_custnum = $opt{'new_custnum'};
1182 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1183 $dbh->rollback if $oldAutoCommit;
1184 return "Invalid new customer number: $new_custnum";
1186 foreach my $cust_pkg ( @cust_pkg ) {
1187 my %hash = $cust_pkg->hash;
1188 $hash{'custnum'} = $new_custnum;
1189 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1190 my $error = $new_cust_pkg->replace($cust_pkg,
1191 options => { $cust_pkg->options },
1194 $dbh->rollback if $oldAutoCommit;
1199 my @cancelled_cust_pkg = $self->all_pkgs;
1200 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1201 my $error = $cust_pkg->delete;
1203 $dbh->rollback if $oldAutoCommit;
1208 #cust_tax_adjustment in financials?
1209 #cust_pay_pending? ouch
1210 foreach my $table (qw(
1211 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1212 cust_payby cust_location cust_main_note cust_tax_adjustment
1213 cust_pay_void cust_pay_batch queue cust_tax_exempt
1215 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1216 my $error = $record->delete;
1218 $dbh->rollback if $oldAutoCommit;
1224 my $sth = $dbh->prepare(
1225 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1227 my $errstr = $dbh->errstr;
1228 $dbh->rollback if $oldAutoCommit;
1231 $sth->execute($self->custnum) or do {
1232 my $errstr = $sth->errstr;
1233 $dbh->rollback if $oldAutoCommit;
1239 my $ticket_dbh = '';
1240 if ($conf->config('ticket_system') eq 'RT_Internal') {
1242 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1243 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1244 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1245 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1248 if ( $ticket_dbh ) {
1250 my $ticket_sth = $ticket_dbh->prepare(
1251 'DELETE FROM Links WHERE Target = ?'
1253 my $errstr = $ticket_dbh->errstr;
1254 $dbh->rollback if $oldAutoCommit;
1257 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1259 my $errstr = $ticket_sth->errstr;
1260 $dbh->rollback if $oldAutoCommit;
1264 #check and see if the customer is the only link on the ticket, and
1265 #if so, set the ticket to deleted status in RT?
1266 #maybe someday, for now this will at least fix tickets not displaying
1270 #delete the customer record
1272 my $error = $self->SUPER::delete;
1274 $dbh->rollback if $oldAutoCommit;
1278 # cust_main exports!
1280 #my $export_args = $options{'export_args'} || [];
1283 map qsearch( 'part_export', {exportnum=>$_} ),
1284 $conf->config('cust_main-exports'); #, $agentnum
1286 foreach my $part_export ( @part_export ) {
1287 my $error = $part_export->export_delete( $self ); #, @$export_args);
1289 $dbh->rollback if $oldAutoCommit;
1290 return "exporting to ". $part_export->exporttype.
1291 " (transaction rolled back): $error";
1295 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1300 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1302 Replaces the OLD_RECORD with this one in the database. If there is an error,
1303 returns the error, otherwise returns false.
1305 To change the customer's address, set the pseudo-fields C<bill_location> and
1306 C<ship_location>. The address will still only change if at least one of the
1307 address fields differs from the existing values.
1309 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1310 set as the contact email address for a default contact with the same name as
1313 Currently available options are: I<tax_exemption>, I<cust_payby_params>,
1314 I<contact_params>, I<invoicing_list>.
1316 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1317 of tax names and exemption numbers. FS::cust_main_exemption records will be
1318 deleted and inserted as appropriate.
1320 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1321 groups (describing the customer's payment methods and contacts, respectively)
1322 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1323 and L<FS::contact> for the fields these can contain.
1325 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1326 should be used instead if possible.
1333 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1335 : $self->replace_old;
1339 warn "$me replace called\n"
1342 my $curuser = $FS::CurrentUser::CurrentUser;
1343 return "You are not permitted to create complimentary accounts."
1344 if $self->complimentary eq 'Y'
1345 && $self->complimentary ne $old->complimentary
1346 && ! $curuser->access_right('Complimentary customer');
1348 local($ignore_expired_card) = 1
1349 if $old->payby =~ /^(CARD|DCRD)$/
1350 && $self->payby =~ /^(CARD|DCRD)$/
1351 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1353 local($ignore_banned_card) = 1
1354 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1355 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1356 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1358 if ( $self->payby =~ /^(CARD|DCRD)$/
1359 && $old->payinfo ne $self->payinfo
1360 && $old->paymask ne $self->paymask )
1362 my $error = $self->check_payinfo_cardtype;
1363 return $error if $error;
1366 return "Invoicing locale is required"
1369 && $conf->exists('cust_main-require_locale');
1371 local $SIG{HUP} = 'IGNORE';
1372 local $SIG{INT} = 'IGNORE';
1373 local $SIG{QUIT} = 'IGNORE';
1374 local $SIG{TERM} = 'IGNORE';
1375 local $SIG{TSTP} = 'IGNORE';
1376 local $SIG{PIPE} = 'IGNORE';
1378 my $oldAutoCommit = $FS::UID::AutoCommit;
1379 local $FS::UID::AutoCommit = 0;
1382 for my $l (qw(bill_location ship_location)) {
1383 #my $old_loc = $old->$l;
1384 my $new_loc = $self->$l or next;
1386 # find the existing location if there is one
1387 $new_loc->set('custnum' => $self->custnum);
1388 my $error = $new_loc->find_or_insert;
1390 $dbh->rollback if $oldAutoCommit;
1393 $self->set($l.'num', $new_loc->locationnum);
1397 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1398 warn "cust_main::replace: using deprecated invoicing list argument";
1399 $invoicing_list = shift @param;
1402 my %options = @param;
1404 $invoicing_list ||= $options{invoicing_list};
1406 my @contacts = map { $_->contact } $self->cust_contact;
1407 # find a contact that matches the customer's name
1408 my ($implicit_contact) = grep { $_->first eq $old->get('first')
1409 and $_->last eq $old->get('last') }
1411 $implicit_contact ||= FS::contact->new({
1412 'custnum' => $self->custnum,
1413 'locationnum' => $self->get('bill_locationnum'),
1416 # for any of these that are already contact emails, link to the existing
1418 if ( $invoicing_list ) {
1421 # kind of like process_m2m on these, except:
1422 # - the other side is two tables in a join
1423 # - and we might have to create new contact_emails
1424 # - and possibly a new contact
1426 # Find existing invoice emails that aren't on the implicit contact.
1427 # Any of these that are not on the new invoicing list will be removed.
1428 my %old_email_cust_contact;
1429 foreach my $cust_contact ($self->cust_contact) {
1430 next if !$cust_contact->invoice_dest;
1431 next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1433 foreach my $contact_email ($cust_contact->contact->contact_email) {
1434 $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1438 foreach my $dest (@$invoicing_list) {
1440 if ($dest eq 'POST') {
1442 $self->set('postal_invoice', 'Y');
1444 } elsif ( exists($old_email_cust_contact{$dest}) ) {
1446 delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1450 # See if it belongs to some other contact; if so, link it.
1451 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1453 and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1454 my $cust_contact = qsearchs('cust_contact', {
1455 contactnum => $contact_email->contactnum,
1456 custnum => $self->custnum,
1457 }) || FS::cust_contact->new({
1458 contactnum => $contact_email->contactnum,
1459 custnum => $self->custnum,
1461 $cust_contact->set('invoice_dest', 'Y');
1462 my $error = $cust_contact->custcontactnum ?
1463 $cust_contact->replace : $cust_contact->insert;
1465 $dbh->rollback if $oldAutoCommit;
1466 return "$error (linking to email address $dest)";
1470 # This email address is not yet linked to any contact, so it will
1471 # be added to the implicit contact.
1472 $email .= ',' if length($email);
1478 foreach my $remove_dest (keys %old_email_cust_contact) {
1479 my $cust_contact = $old_email_cust_contact{$remove_dest};
1480 # These were not in the list of requested destinations, so take them off.
1481 $cust_contact->set('invoice_dest', '');
1482 my $error = $cust_contact->replace;
1484 $dbh->rollback if $oldAutoCommit;
1485 return "$error (unlinking email address $remove_dest)";
1489 # make sure it keeps up with the changed customer name, if any
1490 $implicit_contact->set('last', $self->get('last'));
1491 $implicit_contact->set('first', $self->get('first'));
1492 $implicit_contact->set('emailaddress', $email);
1493 $implicit_contact->set('invoice_dest', 'Y');
1494 $implicit_contact->set('custnum', $self->custnum);
1497 if ( $implicit_contact->contactnum ) {
1498 $error = $implicit_contact->replace;
1499 } elsif ( length($email) ) { # don't create a new contact if not needed
1500 $error = $implicit_contact->insert;
1504 $dbh->rollback if $oldAutoCommit;
1505 return "$error (adding email address $email)";
1510 # replace the customer record
1511 my $error = $self->SUPER::replace($old);
1514 $dbh->rollback if $oldAutoCommit;
1518 # now move packages to the new service location
1519 $self->set('ship_location', ''); #flush cache
1520 if ( $old->ship_locationnum and # should only be null during upgrade...
1521 $old->ship_locationnum != $self->ship_locationnum ) {
1522 $error = $old->ship_location->move_to($self->ship_location);
1524 $dbh->rollback if $oldAutoCommit;
1528 # don't move packages based on the billing location, but
1529 # disable it if it's no longer in use
1530 if ( $old->bill_locationnum and
1531 $old->bill_locationnum != $self->bill_locationnum ) {
1532 $error = $old->bill_location->disable_if_unused;
1534 $dbh->rollback if $oldAutoCommit;
1539 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1541 #this could be more efficient than deleting and re-inserting, if it matters
1542 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1543 my $error = $cust_tag->delete;
1545 $dbh->rollback if $oldAutoCommit;
1549 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1550 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1551 'custnum' => $self->custnum };
1552 my $error = $cust_tag->insert;
1554 $dbh->rollback if $oldAutoCommit;
1561 my $tax_exemption = delete $options{'tax_exemption'};
1562 if ( $tax_exemption ) {
1564 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1565 if ref($tax_exemption) eq 'ARRAY';
1567 my %cust_main_exemption =
1568 map { $_->taxname => $_ }
1569 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1571 foreach my $taxname ( keys %$tax_exemption ) {
1573 if ( $cust_main_exemption{$taxname} &&
1574 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1577 delete $cust_main_exemption{$taxname};
1581 my $cust_main_exemption = new FS::cust_main_exemption {
1582 'custnum' => $self->custnum,
1583 'taxname' => $taxname,
1584 'exempt_number' => $tax_exemption->{$taxname},
1586 my $error = $cust_main_exemption->insert;
1588 $dbh->rollback if $oldAutoCommit;
1589 return "inserting cust_main_exemption (transaction rolled back): $error";
1593 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1594 my $error = $cust_main_exemption->delete;
1596 $dbh->rollback if $oldAutoCommit;
1597 return "deleting cust_main_exemption (transaction rolled back): $error";
1603 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1605 my $error = $self->process_o2m(
1606 'table' => 'cust_payby',
1607 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1608 'params' => $cust_payby_params,
1609 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1612 $dbh->rollback if $oldAutoCommit;
1618 if ( my $contact_params = delete $options{'contact_params'} ) {
1620 # this can potentially replace contacts that were created by the
1621 # invoicing list argument, but the UI shouldn't allow both of them
1624 my $error = $self->process_o2m(
1625 'table' => 'contact',
1626 'fields' => FS::contact->cgi_contact_fields,
1627 'params' => $contact_params,
1630 $dbh->rollback if $oldAutoCommit;
1636 unless ( $import || $skip_fuzzyfiles ) {
1637 $error = $self->queue_fuzzyfiles_update;
1639 $dbh->rollback if $oldAutoCommit;
1640 return "updating fuzzy search cache: $error";
1644 # tax district update in cust_location
1646 # cust_main exports!
1648 my $export_args = $options{'export_args'} || [];
1651 map qsearch( 'part_export', {exportnum=>$_} ),
1652 $conf->config('cust_main-exports'); #, $agentnum
1654 foreach my $part_export ( @part_export ) {
1655 my $error = $part_export->export_replace( $self, $old, @$export_args);
1657 $dbh->rollback if $oldAutoCommit;
1658 return "exporting to ". $part_export->exporttype.
1659 " (transaction rolled back): $error";
1663 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1668 =item queue_fuzzyfiles_update
1670 Used by insert & replace to update the fuzzy search cache
1674 use FS::cust_main::Search;
1675 sub queue_fuzzyfiles_update {
1678 local $SIG{HUP} = 'IGNORE';
1679 local $SIG{INT} = 'IGNORE';
1680 local $SIG{QUIT} = 'IGNORE';
1681 local $SIG{TERM} = 'IGNORE';
1682 local $SIG{TSTP} = 'IGNORE';
1683 local $SIG{PIPE} = 'IGNORE';
1685 my $oldAutoCommit = $FS::UID::AutoCommit;
1686 local $FS::UID::AutoCommit = 0;
1689 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1690 my $queue = new FS::queue {
1691 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1693 my @args = "cust_main.$field", $self->get($field);
1694 my $error = $queue->insert( @args );
1696 $dbh->rollback if $oldAutoCommit;
1697 return "queueing job (transaction rolled back): $error";
1702 push @locations, $self->bill_location if $self->bill_locationnum;
1703 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1704 foreach my $location (@locations) {
1705 my $queue = new FS::queue {
1706 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1708 my @args = 'cust_location.address1', $location->address1;
1709 my $error = $queue->insert( @args );
1711 $dbh->rollback if $oldAutoCommit;
1712 return "queueing job (transaction rolled back): $error";
1716 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1723 Checks all fields to make sure this is a valid customer record. If there is
1724 an error, returns the error, otherwise returns false. Called by the insert
1725 and replace methods.
1732 warn "$me check BEFORE: \n". $self->_dump
1736 $self->ut_numbern('custnum')
1737 || $self->ut_number('agentnum')
1738 || $self->ut_textn('agent_custid')
1739 || $self->ut_number('refnum')
1740 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1741 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1742 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1743 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1744 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1745 || $self->ut_textn('custbatch')
1746 || $self->ut_name('last')
1747 || $self->ut_name('first')
1748 || $self->ut_snumbern('signupdate')
1749 || $self->ut_snumbern('birthdate')
1750 || $self->ut_namen('spouse_last')
1751 || $self->ut_namen('spouse_first')
1752 || $self->ut_snumbern('spouse_birthdate')
1753 || $self->ut_snumbern('anniversary_date')
1754 || $self->ut_textn('company')
1755 || $self->ut_textn('ship_company')
1756 || $self->ut_anything('comments')
1757 || $self->ut_numbern('referral_custnum')
1758 || $self->ut_textn('stateid')
1759 || $self->ut_textn('stateid_state')
1760 || $self->ut_textn('invoice_terms')
1761 || $self->ut_floatn('cdr_termination_percentage')
1762 || $self->ut_floatn('credit_limit')
1763 || $self->ut_numbern('billday')
1764 || $self->ut_numbern('prorate_day')
1765 || $self->ut_flag('edit_subject')
1766 || $self->ut_flag('calling_list_exempt')
1767 || $self->ut_flag('invoice_noemail')
1768 || $self->ut_flag('message_noemail')
1769 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1770 || $self->ut_currencyn('currency')
1771 || $self->ut_alphan('po_number')
1772 || $self->ut_enum('complimentary', [ '', 'Y' ])
1773 || $self->ut_flag('invoice_ship_address')
1774 || $self->ut_flag('invoice_dest')
1777 foreach (qw(company ship_company)) {
1778 my $company = $self->get($_);
1779 $company =~ s/^\s+//;
1780 $company =~ s/\s+$//;
1781 $company =~ s/\s+/ /g;
1782 $self->set($_, $company);
1785 #barf. need message catalogs. i18n. etc.
1786 $error .= "Please select an advertising source."
1787 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1788 return $error if $error;
1790 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1791 or return "Unknown agent";
1793 if ( $self->currency ) {
1794 my $agent_currency = qsearchs( 'agent_currency', {
1795 'agentnum' => $agent->agentnum,
1796 'currency' => $self->currency,
1798 or return "Agent ". $agent->agent.
1799 " not permitted to offer ". $self->currency. " invoicing";
1802 return "Unknown refnum"
1803 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1805 return "Unknown referring custnum: ". $self->referral_custnum
1806 unless ! $self->referral_custnum
1807 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1809 if ( $self->ss eq '' ) {
1814 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1815 or return "Illegal social security number: ". $self->ss;
1816 $self->ss("$1-$2-$3");
1819 #turn off invoice_ship_address if ship & bill are the same
1820 if ($self->bill_locationnum eq $self->ship_locationnum) {
1821 $self->invoice_ship_address('');
1824 # cust_main_county verification now handled by cust_location check
1827 $self->ut_phonen('daytime', $self->country)
1828 || $self->ut_phonen('night', $self->country)
1829 || $self->ut_phonen('fax', $self->country)
1830 || $self->ut_phonen('mobile', $self->country)
1832 return $error if $error;
1834 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1836 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1839 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1841 : FS::Msgcat::_gettext('daytime');
1842 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1844 : FS::Msgcat::_gettext('night');
1846 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1848 : FS::Msgcat::_gettext('mobile');
1850 return "$daytime_label, $night_label or $mobile_label is required"
1854 return "Please select an invoicing locale"
1857 && $conf->exists('cust_main-require_locale');
1859 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1860 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1864 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1866 warn "$me check AFTER: \n". $self->_dump
1869 $self->SUPER::check;
1872 sub check_payinfo_cardtype {
1875 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
1877 my $payinfo = $self->payinfo;
1878 $payinfo =~ s/\D//g;
1880 return '' if $payinfo =~ /^99\d{14}$/; #token
1882 my %bop_card_types = map { $_=>1 } values %{ card_types() };
1883 my $cardtype = cardtype($payinfo);
1885 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
1893 Additional checks for replace only.
1898 my ($new,$old) = @_;
1899 #preserve old value if global config is set
1900 if ($old && $conf->exists('invoice-ship_address')) {
1901 $new->invoice_ship_address($old->invoice_ship_address);
1908 Returns a list of fields which have ship_ duplicates.
1913 qw( last first company
1915 address1 address2 city county state zip country
1917 daytime night fax mobile
1921 =item has_ship_address
1923 Returns true if this customer record has a separate shipping address.
1927 sub has_ship_address {
1929 $self->bill_locationnum != $self->ship_locationnum;
1934 Returns a list of key/value pairs, with the following keys: address1,
1935 adddress2, city, county, state, zip, country, district, and geocode. The
1936 shipping address is used if present.
1942 $self->ship_location->location_hash;
1947 Returns all locations (see L<FS::cust_location>) for this customer.
1953 qsearch('cust_location', { 'custnum' => $self->custnum,
1954 'prospectnum' => '' } );
1959 Returns all contact associations (see L<FS::cust_contact>) for this customer.
1965 qsearch('cust_contact', { 'custnum' => $self->custnum } );
1968 =item cust_payby PAYBY
1970 Returns all payment methods (see L<FS::cust_payby>) for this customer.
1972 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
1973 Does not validate PAYBY.
1981 'table' => 'cust_payby',
1982 'hashref' => { 'custnum' => $self->custnum },
1983 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
1985 $search->{'extra_sql'} = ' AND payby IN ( ' . join(',', map { dbh->quote($_) } @payby) . ' ) '
1991 =item has_cust_payby_auto
1993 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
1997 sub has_cust_payby_auto {
2000 'table' => 'cust_payby',
2001 'hashref' => { 'custnum' => $self->custnum, },
2002 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2003 'order_by' => 'LIMIT 1',
2010 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2011 and L<FS::cust_pkg>) for this customer, except those on hold.
2013 Returns a list: an empty list on success or a list of errors.
2019 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2024 Unsuspends all suspended packages in the on-hold state (those without setup
2025 dates) for this customer.
2031 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2036 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2038 Returns a list: an empty list on success or a list of errors.
2044 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2047 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2049 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2050 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2051 of a list of pkgparts; the hashref has the following keys:
2055 =item pkgparts - listref of pkgparts
2057 =item (other options are passed to the suspend method)
2062 Returns a list: an empty list on success or a list of errors.
2066 sub suspend_if_pkgpart {
2068 my (@pkgparts, %opt);
2069 if (ref($_[0]) eq 'HASH'){
2070 @pkgparts = @{$_[0]{pkgparts}};
2075 grep { $_->suspend(%opt) }
2076 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2077 $self->unsuspended_pkgs;
2080 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2082 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2083 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2084 instead of a list of pkgparts; the hashref has the following keys:
2088 =item pkgparts - listref of pkgparts
2090 =item (other options are passed to the suspend method)
2094 Returns a list: an empty list on success or a list of errors.
2098 sub suspend_unless_pkgpart {
2100 my (@pkgparts, %opt);
2101 if (ref($_[0]) eq 'HASH'){
2102 @pkgparts = @{$_[0]{pkgparts}};
2107 grep { $_->suspend(%opt) }
2108 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2109 $self->unsuspended_pkgs;
2112 =item cancel [ OPTION => VALUE ... ]
2114 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2116 Available options are:
2120 =item quiet - can be set true to supress email cancellation notices.
2122 =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.
2124 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2126 =item nobill - can be set true to skip billing if it might otherwise be done.
2130 Always returns a list: an empty list on success or a list of errors.
2134 # nb that dates are not specified as valid options to this method
2137 my( $self, %opt ) = @_;
2139 warn "$me cancel called on customer ". $self->custnum. " with options ".
2140 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2143 return ( 'access denied' )
2144 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2146 if ( $opt{'ban'} ) {
2148 foreach my $cust_payby ( $self->cust_payby ) {
2150 #well, if they didn't get decrypted on search, then we don't have to
2151 # try again... queue a job for the server that does have decryption
2152 # capability if we're in a paranoid multi-server implementation?
2153 return ( "Can't (yet) ban encrypted credit cards" )
2154 if $cust_payby->is_encrypted($cust_payby->payinfo);
2156 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2157 my $error = $ban->insert;
2158 return ( $error ) if $error;
2164 my @pkgs = $self->ncancelled_pkgs;
2166 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2168 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2169 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2173 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2174 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2177 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2180 sub _banned_pay_hashref {
2181 die 'cust_main->_banned_pay_hashref deprecated';
2193 'payby' => $payby2ban{$self->payby},
2194 'payinfo' => $self->payinfo,
2195 #don't ever *search* on reason! #'reason' =>
2201 Returns all notes (see L<FS::cust_main_note>) for this customer.
2206 my($self,$orderby_classnum) = (shift,shift);
2207 my $orderby = "sticky DESC, _date DESC";
2208 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2209 qsearch( 'cust_main_note',
2210 { 'custnum' => $self->custnum },
2212 "ORDER BY $orderby",
2218 Returns the agent (see L<FS::agent>) for this customer.
2222 Returns the agent name (see L<FS::agent>) for this customer.
2228 $self->agent->agent;
2233 Returns any tags associated with this customer, as FS::cust_tag objects,
2234 or an empty list if there are no tags.
2238 Returns any tags associated with this customer, as FS::part_tag objects,
2239 or an empty list if there are no tags.
2245 map $_->part_tag, $self->cust_tag;
2251 Returns the customer class, as an FS::cust_class object, or the empty string
2252 if there is no customer class.
2256 Returns the customer category name, or the empty string if there is no customer
2263 my $cust_class = $self->cust_class;
2265 ? $cust_class->categoryname
2271 Returns the customer class name, or the empty string if there is no customer
2278 my $cust_class = $self->cust_class;
2280 ? $cust_class->classname
2286 Returns the external tax status, as an FS::tax_status object, or the empty
2287 string if there is no tax status.
2293 if ( $self->taxstatusnum ) {
2294 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2302 Returns the tax status code if there is one.
2308 my $tax_status = $self->tax_status;
2310 ? $tax_status->taxstatus
2314 =item BILLING METHODS
2316 Documentation on billing methods has been moved to
2317 L<FS::cust_main::Billing>.
2319 =item REALTIME BILLING METHODS
2321 Documentation on realtime billing methods has been moved to
2322 L<FS::cust_main::Billing_Realtime>.
2326 Removes the I<paycvv> field from the database directly.
2328 If there is an error, returns the error, otherwise returns false.
2333 die 'cust_main->remove_cvv deprecated';
2335 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2336 or return dbh->errstr;
2337 $sth->execute($self->custnum)
2338 or return $sth->errstr;
2345 Returns the total owed for this customer on all invoices
2346 (see L<FS::cust_bill/owed>).
2352 $self->total_owed_date(2145859200); #12/31/2037
2355 =item total_owed_date TIME
2357 Returns the total owed for this customer on all invoices with date earlier than
2358 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2359 see L<Time::Local> and L<Date::Parse> for conversion functions.
2363 sub total_owed_date {
2367 my $custnum = $self->custnum;
2369 my $owed_sql = FS::cust_bill->owed_sql;
2372 SELECT SUM($owed_sql) FROM cust_bill
2373 WHERE custnum = $custnum
2377 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2381 =item total_owed_pkgnum PKGNUM
2383 Returns the total owed on all invoices for this customer's specific package
2384 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2388 sub total_owed_pkgnum {
2389 my( $self, $pkgnum ) = @_;
2390 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2393 =item total_owed_date_pkgnum TIME PKGNUM
2395 Returns the total owed for this customer's specific package when using
2396 experimental package balances on all invoices with date earlier than
2397 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2398 see L<Time::Local> and L<Date::Parse> for conversion functions.
2402 sub total_owed_date_pkgnum {
2403 my( $self, $time, $pkgnum ) = @_;
2406 foreach my $cust_bill (
2407 grep { $_->_date <= $time }
2408 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2410 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2412 sprintf( "%.2f", $total_bill );
2418 Returns the total amount of all payments.
2425 $total += $_->paid foreach $self->cust_pay;
2426 sprintf( "%.2f", $total );
2429 =item total_unapplied_credits
2431 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2432 customer. See L<FS::cust_credit/credited>.
2434 =item total_credited
2436 Old name for total_unapplied_credits. Don't use.
2440 sub total_credited {
2441 #carp "total_credited deprecated, use total_unapplied_credits";
2442 shift->total_unapplied_credits(@_);
2445 sub total_unapplied_credits {
2448 my $custnum = $self->custnum;
2450 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2453 SELECT SUM($unapplied_sql) FROM cust_credit
2454 WHERE custnum = $custnum
2457 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2461 =item total_unapplied_credits_pkgnum PKGNUM
2463 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2464 customer. See L<FS::cust_credit/credited>.
2468 sub total_unapplied_credits_pkgnum {
2469 my( $self, $pkgnum ) = @_;
2470 my $total_credit = 0;
2471 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2472 sprintf( "%.2f", $total_credit );
2476 =item total_unapplied_payments
2478 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2479 See L<FS::cust_pay/unapplied>.
2483 sub total_unapplied_payments {
2486 my $custnum = $self->custnum;
2488 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2491 SELECT SUM($unapplied_sql) FROM cust_pay
2492 WHERE custnum = $custnum
2495 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2499 =item total_unapplied_payments_pkgnum PKGNUM
2501 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2502 specific package when using experimental package balances. See
2503 L<FS::cust_pay/unapplied>.
2507 sub total_unapplied_payments_pkgnum {
2508 my( $self, $pkgnum ) = @_;
2509 my $total_unapplied = 0;
2510 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2511 sprintf( "%.2f", $total_unapplied );
2515 =item total_unapplied_refunds
2517 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2518 customer. See L<FS::cust_refund/unapplied>.
2522 sub total_unapplied_refunds {
2524 my $custnum = $self->custnum;
2526 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2529 SELECT SUM($unapplied_sql) FROM cust_refund
2530 WHERE custnum = $custnum
2533 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2539 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2540 total_unapplied_credits minus total_unapplied_payments).
2546 $self->balance_date_range;
2549 =item balance_date TIME
2551 Returns the balance for this customer, only considering invoices with date
2552 earlier than TIME (total_owed_date minus total_credited minus
2553 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2554 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2561 $self->balance_date_range(shift);
2564 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2566 Returns the balance for this customer, optionally considering invoices with
2567 date earlier than START_TIME, and not later than END_TIME
2568 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2570 Times are specified as SQL fragments or numeric
2571 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2572 L<Date::Parse> for conversion functions. The empty string can be passed
2573 to disable that time constraint completely.
2575 Accepts the same options as L<balance_date_sql>:
2579 =item unapplied_date
2581 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)
2585 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2586 time will be ignored. Note that START_TIME and END_TIME only limit the date
2587 range for invoices and I<unapplied> payments, credits, and refunds.
2593 sub balance_date_range {
2595 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2596 ') FROM cust_main WHERE custnum='. $self->custnum;
2597 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2600 =item balance_pkgnum PKGNUM
2602 Returns the balance for this customer's specific package when using
2603 experimental package balances (total_owed plus total_unrefunded, minus
2604 total_unapplied_credits minus total_unapplied_payments)
2608 sub balance_pkgnum {
2609 my( $self, $pkgnum ) = @_;
2612 $self->total_owed_pkgnum($pkgnum)
2613 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2614 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2615 - $self->total_unapplied_credits_pkgnum($pkgnum)
2616 - $self->total_unapplied_payments_pkgnum($pkgnum)
2622 Returns a hash of useful information for making a payment.
2632 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2633 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2634 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2638 For credit card transactions:
2650 For electronic check transactions:
2660 #XXX i need to be updated for 4.x+
2666 $return{balance} = $self->balance;
2668 $return{payname} = $self->payname
2669 || ( $self->first. ' '. $self->get('last') );
2671 $return{$_} = $self->bill_location->$_
2672 for qw(address1 address2 city state zip);
2674 $return{payby} = $self->payby;
2675 $return{stateid_state} = $self->stateid_state;
2677 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2678 $return{card_type} = cardtype($self->payinfo);
2679 $return{payinfo} = $self->paymask;
2681 @return{'month', 'year'} = $self->paydate_monthyear;
2685 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2686 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2687 $return{payinfo1} = $payinfo1;
2688 $return{payinfo2} = $payinfo2;
2689 $return{paytype} = $self->paytype;
2690 $return{paystate} = $self->paystate;
2694 #doubleclick protection
2696 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2704 Returns the exact time in seconds corresponding to the payment method
2705 expiration date. For CARD/DCRD customers this is the end of the month;
2706 for others (COMP is the only other payby that uses paydate) it's the start.
2707 Returns 0 if the paydate is empty or set to the far future.
2711 #XXX i need to be updated for 4.x+
2714 my ($month, $year) = $self->paydate_monthyear;
2715 return 0 if !$year or $year >= 2037;
2716 if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
2718 if ( $month == 13 ) {
2722 return timelocal(0,0,0,1,$month-1,$year) - 1;
2725 return timelocal(0,0,0,1,$month-1,$year);
2729 =item paydate_epoch_sql
2731 Class method. Returns an SQL expression to obtain the payment expiration date
2732 as a number of seconds.
2736 # XXX i need to be updated for 4.x+
2737 # Special expiration date behavior for non-CARD/DCRD customers has been
2738 # carefully preserved. Do we really use that?
2739 sub paydate_epoch_sql {
2741 my $table = shift || 'cust_main';
2742 my ($case1, $case2);
2743 if ( driver_name eq 'Pg' ) {
2744 $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
2745 $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
2747 elsif ( lc(driver_name) eq 'mysql' ) {
2748 $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
2749 $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
2752 return "CASE WHEN $table.payby IN('CARD','DCRD')
2758 =item tax_exemption TAXNAME
2763 my( $self, $taxname ) = @_;
2765 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2766 'taxname' => $taxname,
2771 =item cust_main_exemption
2773 =item invoicing_list
2775 Returns a list of email addresses (with svcnum entries expanded), and the word
2776 'POST' if the customer receives postal invoices.
2780 sub invoicing_list {
2781 my( $self, $arrayref ) = @_;
2784 warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
2787 my @emails = $self->invoicing_list_emailonly;
2788 push @emails, 'POST' if $self->get('postal_invoice');
2793 =item check_invoicing_list ARRAYREF
2795 Checks these arguements as valid input for the invoicing_list method. If there
2796 is an error, returns the error, otherwise returns false.
2800 sub check_invoicing_list {
2801 my( $self, $arrayref ) = @_;
2803 foreach my $address ( @$arrayref ) {
2805 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2806 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2809 my $cust_main_invoice = new FS::cust_main_invoice ( {
2810 'custnum' => $self->custnum,
2813 my $error = $self->custnum
2814 ? $cust_main_invoice->check
2815 : $cust_main_invoice->checkdest
2817 return $error if $error;
2821 return "Email address required"
2822 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2823 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2830 Returns the email addresses of all accounts provisioned for this customer.
2837 foreach my $cust_pkg ( $self->all_pkgs ) {
2838 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2840 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2841 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2843 $list{$_}=1 foreach map { $_->email } @svc_acct;
2848 =item invoicing_list_addpost
2850 Adds postal invoicing to this customer. If this customer is already configured
2851 to receive postal invoices, does nothing.
2855 sub invoicing_list_addpost {
2857 if ( $self->get('postal_invoice') eq '' ) {
2858 $self->set('postal_invoice', 'Y');
2859 my $error = $self->replace;
2860 warn $error if $error; # should fail harder, but this is traditional
2864 =item invoicing_list_emailonly
2866 Returns the list of email invoice recipients (invoicing_list without non-email
2867 destinations such as POST and FAX).
2871 sub invoicing_list_emailonly {
2873 warn "$me invoicing_list_emailonly called"
2875 return () if !$self->custnum; # not yet inserted
2876 return map { $_->emailaddress }
2878 table => 'cust_contact',
2879 select => 'emailaddress',
2880 addl_from => ' JOIN contact USING (contactnum) '.
2881 ' JOIN contact_email USING (contactnum)',
2882 hashref => { 'custnum' => $self->custnum, },
2883 extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
2887 =item invoicing_list_emailonly_scalar
2889 Returns the list of email invoice recipients (invoicing_list without non-email
2890 destinations such as POST and FAX) as a comma-separated scalar.
2894 sub invoicing_list_emailonly_scalar {
2896 warn "$me invoicing_list_emailonly_scalar called"
2898 join(', ', $self->invoicing_list_emailonly);
2901 =item referral_custnum_cust_main
2903 Returns the customer who referred this customer (or the empty string, if
2904 this customer was not referred).
2906 Note the difference with referral_cust_main method: This method,
2907 referral_custnum_cust_main returns the single customer (if any) who referred
2908 this customer, while referral_cust_main returns an array of customers referred
2913 sub referral_custnum_cust_main {
2915 return '' unless $self->referral_custnum;
2916 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2919 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
2921 Returns an array of customers referred by this customer (referral_custnum set
2922 to this custnum). If DEPTH is given, recurses up to the given depth, returning
2923 customers referred by customers referred by this customer and so on, inclusive.
2924 The default behavior is DEPTH 1 (no recursion).
2926 Note the difference with referral_custnum_cust_main method: This method,
2927 referral_cust_main, returns an array of customers referred BY this customer,
2928 while referral_custnum_cust_main returns the single customer (if any) who
2929 referred this customer.
2933 sub referral_cust_main {
2935 my $depth = @_ ? shift : 1;
2936 my $exclude = @_ ? shift : {};
2939 map { $exclude->{$_->custnum}++; $_; }
2940 grep { ! $exclude->{ $_->custnum } }
2941 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
2945 map { $_->referral_cust_main($depth-1, $exclude) }
2952 =item referral_cust_main_ncancelled
2954 Same as referral_cust_main, except only returns customers with uncancelled
2959 sub referral_cust_main_ncancelled {
2961 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
2964 =item referral_cust_pkg [ DEPTH ]
2966 Like referral_cust_main, except returns a flat list of all unsuspended (and
2967 uncancelled) packages for each customer. The number of items in this list may
2968 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
2972 sub referral_cust_pkg {
2974 my $depth = @_ ? shift : 1;
2976 map { $_->unsuspended_pkgs }
2977 grep { $_->unsuspended_pkgs }
2978 $self->referral_cust_main($depth);
2981 =item referring_cust_main
2983 Returns the single cust_main record for the customer who referred this customer
2984 (referral_custnum), or false.
2988 sub referring_cust_main {
2990 return '' unless $self->referral_custnum;
2991 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2994 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
2996 Applies a credit to this customer. If there is an error, returns the error,
2997 otherwise returns false.
2999 REASON can be a text string, an FS::reason object, or a scalar reference to
3000 a reasonnum. If a text string, it will be automatically inserted as a new
3001 reason, and a 'reason_type' option must be passed to indicate the
3002 FS::reason_type for the new reason.
3004 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3005 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3006 I<commission_pkgnum>.
3008 Any other options are passed to FS::cust_credit::insert.
3013 my( $self, $amount, $reason, %options ) = @_;
3015 my $cust_credit = new FS::cust_credit {
3016 'custnum' => $self->custnum,
3017 'amount' => $amount,
3020 if ( ref($reason) ) {
3022 if ( ref($reason) eq 'SCALAR' ) {
3023 $cust_credit->reasonnum( $$reason );
3025 $cust_credit->reasonnum( $reason->reasonnum );
3029 $cust_credit->set('reason', $reason)
3032 $cust_credit->$_( delete $options{$_} )
3033 foreach grep exists($options{$_}),
3034 qw( addlinfo eventnum ),
3035 map "commission_$_", qw( agentnum salesnum pkgnum );
3037 $cust_credit->insert(%options);
3041 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3043 Creates a one-time charge for this customer. If there is an error, returns
3044 the error, otherwise returns false.
3046 New-style, with a hashref of options:
3048 my $error = $cust_main->charge(
3052 'start_date' => str2time('7/4/2009'),
3053 'pkg' => 'Description',
3054 'comment' => 'Comment',
3055 'additional' => [], #extra invoice detail
3056 'classnum' => 1, #pkg_class
3058 'setuptax' => '', # or 'Y' for tax exempt
3060 'locationnum'=> 1234, # optional
3063 'taxclass' => 'Tax class',
3066 'taxproduct' => 2, #part_pkg_taxproduct
3067 'override' => {}, #XXX describe
3069 #will be filled in with the new object
3070 'cust_pkg_ref' => \$cust_pkg,
3072 #generate an invoice immediately
3074 'invoice_terms' => '', #with these terms
3080 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3084 #super false laziness w/quotation::charge
3087 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3088 my ( $pkg, $comment, $additional );
3089 my ( $setuptax, $taxclass ); #internal taxes
3090 my ( $taxproduct, $override ); #vendor (CCH) taxes
3092 my $separate_bill = '';
3093 my $cust_pkg_ref = '';
3094 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3096 if ( ref( $_[0] ) ) {
3097 $amount = $_[0]->{amount};
3098 $setup_cost = $_[0]->{setup_cost};
3099 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3100 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3101 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3102 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3103 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3104 : '$'. sprintf("%.2f",$amount);
3105 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3106 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3107 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3108 $additional = $_[0]->{additional} || [];
3109 $taxproduct = $_[0]->{taxproductnum};
3110 $override = { '' => $_[0]->{tax_override} };
3111 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3112 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3113 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3114 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3115 $separate_bill = $_[0]->{separate_bill} || '';
3121 $pkg = @_ ? shift : 'One-time charge';
3122 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3124 $taxclass = @_ ? shift : '';
3128 local $SIG{HUP} = 'IGNORE';
3129 local $SIG{INT} = 'IGNORE';
3130 local $SIG{QUIT} = 'IGNORE';
3131 local $SIG{TERM} = 'IGNORE';
3132 local $SIG{TSTP} = 'IGNORE';
3133 local $SIG{PIPE} = 'IGNORE';
3135 my $oldAutoCommit = $FS::UID::AutoCommit;
3136 local $FS::UID::AutoCommit = 0;
3139 my $part_pkg = new FS::part_pkg ( {
3141 'comment' => $comment,
3145 'classnum' => ( $classnum ? $classnum : '' ),
3146 'setuptax' => $setuptax,
3147 'taxclass' => $taxclass,
3148 'taxproductnum' => $taxproduct,
3149 'setup_cost' => $setup_cost,
3152 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3153 ( 0 .. @$additional - 1 )
3155 'additional_count' => scalar(@$additional),
3156 'setup_fee' => $amount,
3159 my $error = $part_pkg->insert( options => \%options,
3160 tax_overrides => $override,
3163 $dbh->rollback if $oldAutoCommit;
3167 my $pkgpart = $part_pkg->pkgpart;
3168 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3169 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3170 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3171 $error = $type_pkgs->insert;
3173 $dbh->rollback if $oldAutoCommit;
3178 my $cust_pkg = new FS::cust_pkg ( {
3179 'custnum' => $self->custnum,
3180 'pkgpart' => $pkgpart,
3181 'quantity' => $quantity,
3182 'start_date' => $start_date,
3183 'no_auto' => $no_auto,
3184 'separate_bill' => $separate_bill,
3185 'locationnum'=> $locationnum,
3188 $error = $cust_pkg->insert;
3190 $dbh->rollback if $oldAutoCommit;
3192 } elsif ( $cust_pkg_ref ) {
3193 ${$cust_pkg_ref} = $cust_pkg;
3197 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3198 'pkg_list' => [ $cust_pkg ],
3201 $dbh->rollback if $oldAutoCommit;
3206 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3211 #=item charge_postal_fee
3213 #Applies a one time charge this customer. If there is an error,
3214 #returns the error, returns the cust_pkg charge object or false
3215 #if there was no charge.
3219 # This should be a customer event. For that to work requires that bill
3220 # also be a customer event.
3222 sub charge_postal_fee {
3225 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3226 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3228 my $cust_pkg = new FS::cust_pkg ( {
3229 'custnum' => $self->custnum,
3230 'pkgpart' => $pkgpart,
3234 my $error = $cust_pkg->insert;
3235 $error ? $error : $cust_pkg;
3238 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3240 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3242 Optionally, a list or hashref of additional arguments to the qsearch call can
3249 my $opt = ref($_[0]) ? shift : { @_ };
3251 #return $self->num_cust_bill unless wantarray || keys %$opt;
3253 $opt->{'table'} = 'cust_bill';
3254 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3255 $opt->{'hashref'}{'custnum'} = $self->custnum;
3256 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3258 map { $_ } #behavior of sort undefined in scalar context
3259 sort { $a->_date <=> $b->_date }
3263 =item open_cust_bill
3265 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3270 sub open_cust_bill {
3274 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3280 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3282 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3286 sub legacy_cust_bill {
3289 #return $self->num_legacy_cust_bill unless wantarray;
3291 map { $_ } #behavior of sort undefined in scalar context
3292 sort { $a->_date <=> $b->_date }
3293 qsearch({ 'table' => 'legacy_cust_bill',
3294 'hashref' => { 'custnum' => $self->custnum, },
3295 'order_by' => 'ORDER BY _date ASC',
3299 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3301 Returns all the statements (see L<FS::cust_statement>) for this customer.
3303 Optionally, a list or hashref of additional arguments to the qsearch call can
3308 =item cust_bill_void
3310 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3314 sub cust_bill_void {
3317 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3318 sort { $a->_date <=> $b->_date }
3319 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3322 sub cust_statement {
3324 my $opt = ref($_[0]) ? shift : { @_ };
3326 #return $self->num_cust_statement unless wantarray || keys %$opt;
3328 $opt->{'table'} = 'cust_statement';
3329 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3330 $opt->{'hashref'}{'custnum'} = $self->custnum;
3331 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3333 map { $_ } #behavior of sort undefined in scalar context
3334 sort { $a->_date <=> $b->_date }
3338 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3340 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3342 Optionally, a list or hashref of additional arguments to the qsearch call can
3343 be passed following the SVCDB.
3350 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3351 warn "$me svc_x requires a svcdb";
3354 my $opt = ref($_[0]) ? shift : { @_ };
3356 $opt->{'table'} = $svcdb;
3357 $opt->{'addl_from'} =
3358 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3359 ($opt->{'addl_from'} || '');
3361 my $custnum = $self->custnum;
3362 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3363 my $where = "cust_pkg.custnum = $custnum";
3365 my $extra_sql = $opt->{'extra_sql'} || '';
3366 if ( keys %{ $opt->{'hashref'} } ) {
3367 $extra_sql = " AND $where $extra_sql";
3370 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3371 $extra_sql = "WHERE $where AND $1";
3374 $extra_sql = "WHERE $where $extra_sql";
3377 $opt->{'extra_sql'} = $extra_sql;
3382 # required for use as an eventtable;
3385 $self->svc_x('svc_acct', @_);
3390 Returns all the credits (see L<FS::cust_credit>) for this customer.
3396 map { $_ } #return $self->num_cust_credit unless wantarray;
3397 sort { $a->_date <=> $b->_date }
3398 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3401 =item cust_credit_pkgnum
3403 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3404 package when using experimental package balances.
3408 sub cust_credit_pkgnum {
3409 my( $self, $pkgnum ) = @_;
3410 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3411 sort { $a->_date <=> $b->_date }
3412 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3413 'pkgnum' => $pkgnum,
3418 =item cust_credit_void
3420 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3424 sub cust_credit_void {
3427 sort { $a->_date <=> $b->_date }
3428 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3433 Returns all the payments (see L<FS::cust_pay>) for this customer.
3439 my $opt = ref($_[0]) ? shift : { @_ };
3441 return $self->num_cust_pay unless wantarray || keys %$opt;
3443 $opt->{'table'} = 'cust_pay';
3444 $opt->{'hashref'}{'custnum'} = $self->custnum;
3446 map { $_ } #behavior of sort undefined in scalar context
3447 sort { $a->_date <=> $b->_date }
3454 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3455 called automatically when the cust_pay method is used in a scalar context.
3461 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3462 my $sth = dbh->prepare($sql) or die dbh->errstr;
3463 $sth->execute($self->custnum) or die $sth->errstr;
3464 $sth->fetchrow_arrayref->[0];
3467 =item unapplied_cust_pay
3469 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3473 sub unapplied_cust_pay {
3477 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3483 =item cust_pay_pkgnum
3485 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3486 package when using experimental package balances.
3490 sub cust_pay_pkgnum {
3491 my( $self, $pkgnum ) = @_;
3492 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3493 sort { $a->_date <=> $b->_date }
3494 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3495 'pkgnum' => $pkgnum,
3502 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3508 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3509 sort { $a->_date <=> $b->_date }
3510 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3513 =item cust_pay_pending
3515 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3516 (without status "done").
3520 sub cust_pay_pending {
3522 return $self->num_cust_pay_pending unless wantarray;
3523 sort { $a->_date <=> $b->_date }
3524 qsearch( 'cust_pay_pending', {
3525 'custnum' => $self->custnum,
3526 'status' => { op=>'!=', value=>'done' },
3531 =item cust_pay_pending_attempt
3533 Returns all payment attempts / declined payments for this customer, as pending
3534 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3535 a corresponding payment (see L<FS::cust_pay>).
3539 sub cust_pay_pending_attempt {
3541 return $self->num_cust_pay_pending_attempt unless wantarray;
3542 sort { $a->_date <=> $b->_date }
3543 qsearch( 'cust_pay_pending', {
3544 'custnum' => $self->custnum,
3551 =item num_cust_pay_pending
3553 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3554 customer (without status "done"). Also called automatically when the
3555 cust_pay_pending method is used in a scalar context.
3559 sub num_cust_pay_pending {
3562 " SELECT COUNT(*) FROM cust_pay_pending ".
3563 " WHERE custnum = ? AND status != 'done' ",
3568 =item num_cust_pay_pending_attempt
3570 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3571 customer, with status "done" but without a corresp. Also called automatically when the
3572 cust_pay_pending method is used in a scalar context.
3576 sub num_cust_pay_pending_attempt {
3579 " SELECT COUNT(*) FROM cust_pay_pending ".
3580 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3587 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3593 map { $_ } #return $self->num_cust_refund unless wantarray;
3594 sort { $a->_date <=> $b->_date }
3595 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3598 =item display_custnum
3600 Returns the displayed customer number for this customer: agent_custid if
3601 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3605 sub display_custnum {
3608 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3609 if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
3610 if ( $special eq 'CoStAg' ) {
3611 $prefix = uc( join('',
3613 ($self->state =~ /^(..)/),
3614 $prefix || ($self->agent->agent =~ /^(..)/)
3617 elsif ( $special eq 'CoStCl' ) {
3618 $prefix = uc( join('',
3620 ($self->state =~ /^(..)/),
3621 ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
3624 # add any others here if needed
3627 my $length = $conf->config('cust_main-custnum-display_length');
3628 if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3629 return $self->agent_custid;
3630 } elsif ( $prefix ) {
3631 $length = 8 if !defined($length);
3633 sprintf('%0'.$length.'d', $self->custnum)
3634 } elsif ( $length ) {
3635 return sprintf('%0'.$length.'d', $self->custnum);
3637 return $self->custnum;
3643 Returns a name string for this customer, either "Company (Last, First)" or
3650 my $name = $self->contact;
3651 $name = $self->company. " ($name)" if $self->company;
3655 =item service_contact
3657 Returns the L<FS::contact> object for this customer that has the 'Service'
3658 contact class, or undef if there is no such contact. Deprecated; don't use
3663 sub service_contact {
3665 if ( !exists($self->{service_contact}) ) {
3666 my $classnum = $self->scalar_sql(
3667 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3668 ) || 0; #if it's zero, qsearchs will return nothing
3669 my $cust_contact = qsearchs('cust_contact', {
3670 'classnum' => $classnum,
3671 'custnum' => $self->custnum,
3673 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3675 $self->{service_contact};
3680 Returns a name string for this (service/shipping) contact, either
3681 "Company (Last, First)" or "Last, First".
3688 my $name = $self->ship_contact;
3689 $name = $self->company. " ($name)" if $self->company;
3695 Returns a name string for this customer, either "Company" or "First Last".
3701 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3704 =item ship_name_short
3706 Returns a name string for this (service/shipping) contact, either "Company"
3711 sub ship_name_short {
3713 $self->service_contact
3714 ? $self->ship_contact_firstlast
3720 Returns this customer's full (billing) contact name only, "Last, First"
3726 $self->get('last'). ', '. $self->first;
3731 Returns this customer's full (shipping) contact name only, "Last, First"
3737 my $contact = $self->service_contact || $self;
3738 $contact->get('last') . ', ' . $contact->get('first');
3741 =item contact_firstlast
3743 Returns this customers full (billing) contact name only, "First Last".
3747 sub contact_firstlast {
3749 $self->first. ' '. $self->get('last');
3752 =item ship_contact_firstlast
3754 Returns this customer's full (shipping) contact name only, "First Last".
3758 sub ship_contact_firstlast {
3760 my $contact = $self->service_contact || $self;
3761 $contact->get('first') . ' '. $contact->get('last');
3764 sub bill_country_full {
3766 $self->bill_location->country_full;
3769 sub ship_country_full {
3771 $self->ship_location->country_full;
3774 =item county_state_county [ PREFIX ]
3776 Returns a string consisting of just the county, state and country.
3780 sub county_state_country {
3783 if ( @_ && $_[0] && $self->has_ship_address ) {
3784 $locationnum = $self->ship_locationnum;
3786 $locationnum = $self->bill_locationnum;
3788 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3789 $cust_location->county_state_country;
3792 =item geocode DATA_VENDOR
3794 Returns a value for the customer location as encoded by DATA_VENDOR.
3795 Currently this only makes sense for "CCH" as DATA_VENDOR.
3803 Returns a status string for this customer, currently:
3809 No packages have ever been ordered. Displayed as "No packages".
3813 Recurring packages all are new (not yet billed).
3817 One or more recurring packages is active.
3821 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3825 All non-cancelled recurring packages are suspended.
3829 All recurring packages are cancelled.
3833 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3834 cust_main-status_module configuration option.
3838 sub status { shift->cust_status(@_); }
3842 for my $status ( FS::cust_main->statuses() ) {
3843 my $method = $status.'_sql';
3844 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3845 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3846 $sth->execute( ($self->custnum) x $numnum )
3847 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3848 return $status if $sth->fetchrow_arrayref->[0];
3852 =item is_status_delay_cancel
3854 Returns true if customer status is 'suspended'
3855 and all suspended cust_pkg return true for
3856 cust_pkg->is_status_delay_cancel.
3858 This is not a real status, this only meant for hacking display
3859 values, because otherwise treating the customer as suspended is
3860 really the whole point of the delay_cancel option.
3864 sub is_status_delay_cancel {
3866 return 0 unless $self->status eq 'suspended';
3867 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3868 return 0 unless $cust_pkg->is_status_delay_cancel;
3873 =item ucfirst_cust_status
3875 =item ucfirst_status
3877 Deprecated, use the cust_status_label method instead.
3879 Returns the status with the first character capitalized.
3883 sub ucfirst_status {
3884 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3885 local($ucfirst_nowarn) = 1;
3886 shift->ucfirst_cust_status(@_);
3889 sub ucfirst_cust_status {
3890 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3892 ucfirst($self->cust_status);
3895 =item cust_status_label
3899 Returns the display label for this status.
3903 sub status_label { shift->cust_status_label(@_); }
3905 sub cust_status_label {
3907 __PACKAGE__->statuslabels->{$self->cust_status};
3912 Returns a hex triplet color string for this customer's status.
3916 sub statuscolor { shift->cust_statuscolor(@_); }
3918 sub cust_statuscolor {
3920 __PACKAGE__->statuscolors->{$self->cust_status};
3923 =item tickets [ STATUS ]
3925 Returns an array of hashes representing the customer's RT tickets.
3927 An optional status (or arrayref or hashref of statuses) may be specified.
3933 my $status = ( @_ && $_[0] ) ? shift : '';
3935 my $num = $conf->config('cust_main-max_tickets') || 10;
3938 if ( $conf->config('ticket_system') ) {
3939 unless ( $conf->config('ticket_system-custom_priority_field') ) {
3941 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
3950 foreach my $priority (
3951 $conf->config('ticket_system-custom_priority_field-values'), ''
3953 last if scalar(@tickets) >= $num;
3955 @{ FS::TicketSystem->customer_tickets( $self->custnum,
3956 $num - scalar(@tickets),
3967 =item appointments [ STATUS ]
3969 Returns an array of hashes representing the customer's RT tickets which
3976 my $status = ( @_ && $_[0] ) ? shift : '';
3978 return () unless $conf->config('ticket_system');
3980 my $queueid = $conf->config('ticket_system-appointment-queueid');
3982 @{ FS::TicketSystem->customer_tickets( $self->custnum,
3991 # Return services representing svc_accts in customer support packages
3992 sub support_services {
3994 my %packages = map { $_ => 1 } $conf->config('support_packages');
3996 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
3997 grep { $_->part_svc->svcdb eq 'svc_acct' }
3998 map { $_->cust_svc }
3999 grep { exists $packages{ $_->pkgpart } }
4000 $self->ncancelled_pkgs;
4004 # Return a list of latitude/longitude for one of the services (if any)
4005 sub service_coordinates {
4009 grep { $_->latitude && $_->longitude }
4011 map { $_->cust_svc }
4012 $self->ncancelled_pkgs;
4014 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4019 Returns a masked version of the named field
4024 my ($self,$field) = @_;
4028 'x'x(length($self->getfield($field))-4).
4029 substr($self->getfield($field), (length($self->getfield($field))-4));
4033 =item payment_history
4035 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4036 cust_credit and cust_refund objects. Each hashref has the following fields:
4038 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4040 I<date> - value of _date field, unix timestamp
4042 I<date_pretty> - user-friendly date
4044 I<description> - user-friendly description of item
4046 I<amount> - impact of item on user's balance
4047 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4048 Not to be confused with the native 'amount' field in cust_credit, see below.
4050 I<amount_pretty> - includes money char
4052 I<balance> - customer balance, chronologically as of this item
4054 I<balance_pretty> - includes money char
4056 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4058 I<paid> - amount paid for cust_pay records, undef for other types
4060 I<credit> - amount credited for cust_credit records, undef for other types.
4061 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4063 I<refund> - amount refunded for cust_refund records, undef for other types
4065 The four table-specific keys always have positive values, whether they reflect charges or payments.
4067 The following options may be passed to this method:
4069 I<line_items> - if true, returns charges ('Line item') rather than invoices
4071 I<start_date> - unix timestamp, only include records on or after.
4072 If specified, an item of type 'Previous' will also be included.
4073 It does not have table-specific fields.
4075 I<end_date> - unix timestamp, only include records before
4077 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4079 I<conf> - optional already-loaded FS::Conf object.
4083 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4084 # and also for sending customer statements, which should both be kept customer-friendly.
4085 # If you add anything that shouldn't be passed on through the API or exposed
4086 # to customers, add a new option to include it, don't include it by default
4087 sub payment_history {
4089 my $opt = ref($_[0]) ? $_[0] : { @_ };
4091 my $conf = $$opt{'conf'} || new FS::Conf;
4092 my $money_char = $conf->config("money_char") || '$',
4094 #first load entire history,
4095 #need previous to calculate previous balance
4096 #loading after end_date shouldn't hurt too much?
4098 if ( $$opt{'line_items'} ) {
4100 foreach my $cust_bill ( $self->cust_bill ) {
4103 'type' => 'Line item',
4104 'description' => $_->desc( $self->locale ).
4105 ( $_->sdate && $_->edate
4106 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4107 ' To '. time2str('%d-%b-%Y', $_->edate)
4110 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4111 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4112 'date' => $cust_bill->_date,
4113 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4115 foreach $cust_bill->cust_bill_pkg;
4122 'type' => 'Invoice',
4123 'description' => 'Invoice #'. $_->display_invnum,
4124 'amount' => sprintf('%.2f', $_->charged ),
4125 'charged' => sprintf('%.2f', $_->charged ),
4126 'date' => $_->_date,
4127 'date_pretty' => $self->time2str_local('short', $_->_date ),
4129 foreach $self->cust_bill;
4134 'type' => 'Payment',
4135 'description' => 'Payment', #XXX type
4136 'amount' => sprintf('%.2f', 0 - $_->paid ),
4137 'paid' => sprintf('%.2f', $_->paid ),
4138 'date' => $_->_date,
4139 'date_pretty' => $self->time2str_local('short', $_->_date ),
4141 foreach $self->cust_pay;
4145 'description' => 'Credit', #more info?
4146 'amount' => sprintf('%.2f', 0 -$_->amount ),
4147 'credit' => sprintf('%.2f', $_->amount ),
4148 'date' => $_->_date,
4149 'date_pretty' => $self->time2str_local('short', $_->_date ),
4151 foreach $self->cust_credit;
4155 'description' => 'Refund', #more info? type, like payment?
4156 'amount' => $_->refund,
4157 'refund' => $_->refund,
4158 'date' => $_->_date,
4159 'date_pretty' => $self->time2str_local('short', $_->_date ),
4161 foreach $self->cust_refund;
4163 #put it all in chronological order
4164 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4166 #calculate balance, filter items outside date range
4170 foreach my $item (@history) {
4171 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4172 $balance += $$item{'amount'};
4173 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4174 $previous += $$item{'amount'};
4177 $$item{'balance'} = sprintf("%.2f",$balance);
4178 foreach my $key ( qw(amount balance) ) {
4179 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4184 # start with previous balance, if there was one
4187 'type' => 'Previous',
4188 'description' => 'Previous balance',
4189 'amount' => sprintf("%.2f",$previous),
4190 'balance' => sprintf("%.2f",$previous),
4191 'date' => $$opt{'start_date'},
4192 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4194 #false laziness with above
4195 foreach my $key ( qw(amount balance) ) {
4196 $$item{$key.'_pretty'} = $$item{$key};
4197 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4199 unshift(@out,$item);
4202 @out = reverse @history if $$opt{'reverse_sort'};
4207 =item save_cust_payby
4209 Saves a new cust_payby for this customer, replacing an existing entry only
4210 in select circumstances. Does not validate input.
4212 If auto is specified, marks this as the customer's primary method, or the
4213 specified weight. Existing payment methods have their weight incremented as
4216 If bill_location is specified with auto, also sets location in cust_main.
4218 Will not insert complete duplicates of existing records, or records in which the
4219 only difference from an existing record is to turn off automatic payment (will
4220 return without error.) Will replace existing records in which the only difference
4221 is to add a value to a previously empty preserved field and/or turn on automatic payment.
4222 Fields marked as preserved are optional, and existing values will not be overwritten with
4223 blanks when replacing.
4225 Accepts the following named parameters:
4235 save as an automatic payment type (CARD/CHEK if true, DCRD/DCHK if false)
4239 optional, set higher than 1 for secondary, etc.
4247 optional, but should be specified for anything that might be tokenized, will be preserved when replacing
4255 optional, will be preserved when replacing
4263 CARD only, required, FS::cust_location object
4265 =item paystart_month
4267 CARD only, optional, will be preserved when replacing
4271 CARD only, optional, will be preserved when replacing
4275 CARD only, optional, will be preserved when replacing
4279 CARD only, only used if conf cvv-save is set appropriately
4293 #The code for this option is in place, but it's not currently used
4297 # existing cust_payby object to be replaced (must match custnum)
4299 # stateid/stateid_state/ss are not currently supported in cust_payby,
4300 # might not even work properly in 4.x, but will need to work here if ever added
4302 sub save_cust_payby {
4306 my $old = $opt{'replace'};
4307 my $new = new FS::cust_payby { $old ? $old->hash : () };
4308 return "Customer number does not match" if $new->custnum and $new->custnum != $self->custnum;
4309 $new->set( 'custnum' => $self->custnum );
4311 my $payby = $opt{'payment_payby'};
4312 return "Bad payby" unless grep(/^$payby$/,('CARD','CHEK'));
4314 # don't allow turning off auto when replacing
4315 $opt{'auto'} ||= 1 if $old and $old->payby !~ /^D/;
4317 my @check_existing; # payby relevant to this payment_payby
4319 # set payby based on auto
4320 if ( $payby eq 'CARD' ) {
4321 $new->set( 'payby' => ( $opt{'auto'} ? 'CARD' : 'DCRD' ) );
4322 @check_existing = qw( CARD DCRD );
4323 } elsif ( $payby eq 'CHEK' ) {
4324 $new->set( 'payby' => ( $opt{'auto'} ? 'CHEK' : 'DCHK' ) );
4325 @check_existing = qw( CHEK DCHK );
4328 $new->set( 'weight' => $opt{'auto'} ? $opt{'weight'} : '' );
4331 $new->payinfo($opt{'payinfo'}); # sets default paymask, but not if it's already tokenized
4332 $new->paymask($opt{'paymask'}) if $opt{'paymask'}; # in case it's been tokenized, override with loaded paymask
4333 $new->set( 'payname' => $opt{'payname'} );
4334 $new->set( 'payip' => $opt{'payip'} ); # will be preserved below
4336 my $conf = new FS::Conf;
4338 # compare to FS::cust_main::realtime_bop - check both to make sure working correctly
4339 if ( $payby eq 'CARD' &&
4340 grep { $_ eq cardtype($opt{'payinfo'}) } $conf->config('cvv-save') ) {
4341 $new->set( 'paycvv' => $opt{'paycvv'} );
4343 $new->set( 'paycvv' => '');
4346 local $SIG{HUP} = 'IGNORE';
4347 local $SIG{INT} = 'IGNORE';
4348 local $SIG{QUIT} = 'IGNORE';
4349 local $SIG{TERM} = 'IGNORE';
4350 local $SIG{TSTP} = 'IGNORE';
4351 local $SIG{PIPE} = 'IGNORE';
4353 my $oldAutoCommit = $FS::UID::AutoCommit;
4354 local $FS::UID::AutoCommit = 0;
4357 # set fields specific to payment_payby
4358 if ( $payby eq 'CARD' ) {
4359 if ($opt{'bill_location'}) {
4360 $opt{'bill_location'}->set('custnum' => $self->custnum);
4361 my $error = $opt{'bill_location'}->find_or_insert;
4363 $dbh->rollback if $oldAutoCommit;
4366 $new->set( 'locationnum' => $opt{'bill_location'}->locationnum );
4368 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
4369 $new->set( $field => $opt{$field} );
4372 foreach my $field ( qw(paytype paystate) ) {
4373 $new->set( $field => $opt{$field} );
4377 # other cust_payby to compare this to
4378 my @existing = $self->cust_payby(@check_existing);
4380 # fields that can overwrite blanks with values, but not values with blanks
4381 my @preserve = qw( paymask locationnum paystart_month paystart_year payissue payip );
4383 my $skip_cust_payby = 0; # true if we don't need to save or reweight cust_payby
4385 # generally, we don't want to overwrite existing cust_payby with this,
4386 # but we can replace if we're only marking it auto or adding a preserved field
4387 # and we can avoid saving a total duplicate or merely turning off auto
4389 foreach my $cust_payby (@existing) {
4390 # check fields that absolutely should not change
4391 foreach my $field ($new->fields) {
4392 next if grep(/^$field$/, qw( custpaybynum payby weight ) );
4393 next if grep(/^$field$/, @preserve );
4394 next PAYBYLOOP unless $new->get($field) eq $cust_payby->get($field);
4396 # now check fields that can replace if one value is blank
4398 foreach my $field (@preserve) {
4400 ( $new->get($field) and !$cust_payby->get($field) ) or
4401 ( $cust_payby->get($field) and !$new->get($field) )
4403 # prevention of overwriting values with blanks happens farther below
4405 } elsif ( $new->get($field) ne $cust_payby->get($field) ) {
4409 unless ( $replace ) {
4410 # nearly identical, now check weight
4411 if ($new->get('weight') eq $cust_payby->get('weight') or !$new->get('weight')) {
4412 # ignore identical cust_payby, and ignore attempts to turn off auto
4413 # no need to save or re-weight cust_payby (but still need to update/commit $self)
4414 $skip_cust_payby = 1;
4417 # otherwise, only change is to mark this as primary
4419 # if we got this far, we're definitely replacing
4426 $new->set( 'custpaybynum' => $old->custpaybynum );
4427 # don't turn off automatic payment (but allow it to be turned on)
4428 if ($new->payby =~ /^D/ and $new->payby ne $old->payby) {
4430 $new->set( 'payby' => $old->payby );
4431 $new->set( 'weight' => 1 );
4433 # make sure we're not overwriting values with blanks
4434 foreach my $field (@preserve) {
4435 if ( $old->get($field) and !$new->get($field) ) {
4436 $new->set( $field => $old->get($field) );
4441 # only overwrite cust_main bill_location if auto
4442 if ($opt{'auto'} && $opt{'bill_location'}) {
4443 $self->set('bill_location' => $opt{'bill_location'});
4444 my $error = $self->replace;
4446 $dbh->rollback if $oldAutoCommit;
4451 # done with everything except reweighting and saving cust_payby
4452 # still need to commit changes to cust_main and cust_location
4453 if ($skip_cust_payby) {
4454 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4458 # re-weight existing primary cust_pay for this payby
4460 foreach my $cust_payby (@existing) {
4461 # relies on cust_payby return order
4462 last unless $cust_payby->payby !~ /^D/;
4463 last if $cust_payby->weight > 1;
4464 next if $new->custpaybynum eq $cust_payby->custpaybynum;
4465 next if $cust_payby->weight < ($opt{'weight'} || 1);
4466 $cust_payby->weight( $cust_payby->weight + 1 );
4467 my $error = $cust_payby->replace;
4469 $dbh->rollback if $oldAutoCommit;
4470 return "Error reweighting cust_payby: $error";
4475 # finally, save cust_payby
4476 my $error = $old ? $new->replace($old) : $new->insert;
4478 $dbh->rollback if $oldAutoCommit;
4482 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4489 =head1 CLASS METHODS
4495 Class method that returns the list of possible status strings for customers
4496 (see L<the status method|/status>). For example:
4498 @statuses = FS::cust_main->statuses();
4504 keys %{ $self->statuscolors };
4507 =item cust_status_sql
4509 Returns an SQL fragment to determine the status of a cust_main record, as a
4514 sub cust_status_sql {
4516 for my $status ( FS::cust_main->statuses() ) {
4517 my $method = $status.'_sql';
4518 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4527 Returns an SQL expression identifying prospective cust_main records (customers
4528 with no packages ever ordered)
4532 use vars qw($select_count_pkgs);
4533 $select_count_pkgs =
4534 "SELECT COUNT(*) FROM cust_pkg
4535 WHERE cust_pkg.custnum = cust_main.custnum";
4537 sub select_count_pkgs_sql {
4542 " 0 = ( $select_count_pkgs ) ";
4547 Returns an SQL expression identifying ordered cust_main records (customers with
4548 no active packages, but recurring packages not yet setup or one time charges
4554 FS::cust_main->none_active_sql.
4555 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4560 Returns an SQL expression identifying active cust_main records (customers with
4561 active recurring packages).
4566 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4569 =item none_active_sql
4571 Returns an SQL expression identifying cust_main records with no active
4572 recurring packages. This includes customers of status prospect, ordered,
4573 inactive, and suspended.
4577 sub none_active_sql {
4578 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4583 Returns an SQL expression identifying inactive cust_main records (customers with
4584 no active recurring packages, but otherwise unsuspended/uncancelled).
4589 FS::cust_main->none_active_sql.
4590 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4596 Returns an SQL expression identifying suspended cust_main records.
4601 sub suspended_sql { susp_sql(@_); }
4603 FS::cust_main->none_active_sql.
4604 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4610 Returns an SQL expression identifying cancelled cust_main records.
4614 sub cancel_sql { shift->cancelled_sql(@_); }
4617 =item uncancelled_sql
4619 Returns an SQL expression identifying un-cancelled cust_main records.
4623 sub uncancelled_sql { uncancel_sql(@_); }
4624 sub uncancel_sql { "
4625 ( 0 < ( $select_count_pkgs
4626 AND ( cust_pkg.cancel IS NULL
4627 OR cust_pkg.cancel = 0
4630 OR 0 = ( $select_count_pkgs )
4636 Returns an SQL fragment to retreive the balance.
4641 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4642 WHERE cust_bill.custnum = cust_main.custnum )
4643 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4644 WHERE cust_pay.custnum = cust_main.custnum )
4645 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4646 WHERE cust_credit.custnum = cust_main.custnum )
4647 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4648 WHERE cust_refund.custnum = cust_main.custnum )
4651 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4653 Returns an SQL fragment to retreive the balance for this customer, optionally
4654 considering invoices with date earlier than START_TIME, and not
4655 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4656 total_unapplied_payments).
4658 Times are specified as SQL fragments or numeric
4659 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4660 L<Date::Parse> for conversion functions. The empty string can be passed
4661 to disable that time constraint completely.
4663 Available options are:
4667 =item unapplied_date
4669 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)
4674 set to true to remove all customer comparison clauses, for totals
4679 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4684 JOIN clause (typically used with the total option)
4688 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4689 time will be ignored. Note that START_TIME and END_TIME only limit the date
4690 range for invoices and I<unapplied> payments, credits, and refunds.
4696 sub balance_date_sql {
4697 my( $class, $start, $end, %opt ) = @_;
4699 my $cutoff = $opt{'cutoff'};
4701 my $owed = FS::cust_bill->owed_sql($cutoff);
4702 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4703 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4704 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4706 my $j = $opt{'join'} || '';
4708 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4709 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4710 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4711 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4713 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4714 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4715 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4716 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4721 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4723 Returns an SQL fragment to retreive the total unapplied payments for this
4724 customer, only considering payments with date earlier than START_TIME, and
4725 optionally not later than END_TIME.
4727 Times are specified as SQL fragments or numeric
4728 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4729 L<Date::Parse> for conversion functions. The empty string can be passed
4730 to disable that time constraint completely.
4732 Available options are:
4736 sub unapplied_payments_date_sql {
4737 my( $class, $start, $end, %opt ) = @_;
4739 my $cutoff = $opt{'cutoff'};
4741 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4743 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4744 'unapplied_date'=>1 );
4746 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4749 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4751 Helper method for balance_date_sql; name (and usage) subject to change
4752 (suggestions welcome).
4754 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4755 cust_refund, cust_credit or cust_pay).
4757 If TABLE is "cust_bill" or the unapplied_date option is true, only
4758 considers records with date earlier than START_TIME, and optionally not
4759 later than END_TIME .
4763 sub _money_table_where {
4764 my( $class, $table, $start, $end, %opt ) = @_;
4767 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4768 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4769 push @where, "$table._date <= $start" if defined($start) && length($start);
4770 push @where, "$table._date > $end" if defined($end) && length($end);
4772 push @where, @{$opt{'where'}} if $opt{'where'};
4773 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4779 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4780 use FS::cust_main::Search;
4783 FS::cust_main::Search->search(@_);
4792 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4794 Generates a templated notification to the customer (see L<Text::Template>).
4796 OPTIONS is a hash and may include
4798 I<extra_fields> - a hashref of name/value pairs which will be substituted
4799 into the template. These values may override values mentioned below
4800 and those from the customer record.
4802 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
4804 The following variables are available in the template instead of or in addition
4805 to the fields of the customer record.
4807 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4811 # a lot like cust_bill::print_latex
4812 sub generate_letter {
4813 my ($self, $template, %options) = @_;
4815 warn "Template $template does not exist" && return
4816 unless $conf->exists($template) || $options{'template_text'};
4818 my $template_source = $options{'template_text'}
4819 ? [ $options{'template_text'} ]
4820 : [ map "$_\n", $conf->config($template) ];
4822 my $letter_template = new Text::Template
4824 SOURCE => $template_source,
4825 DELIMITERS => [ '[@--', '--@]' ],
4827 or die "can't create new Text::Template object: Text::Template::ERROR";
4829 $letter_template->compile()
4830 or die "can't compile template: Text::Template::ERROR";
4832 my %letter_data = map { $_ => $self->$_ } $self->fields;
4834 for (keys %{$options{extra_fields}}){
4835 $letter_data{$_} = $options{extra_fields}->{$_};
4838 unless(exists($letter_data{returnaddress})){
4839 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4840 $self->agent_template)
4842 if ( length($retadd) ) {
4843 $letter_data{returnaddress} = $retadd;
4844 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4845 $letter_data{returnaddress} =
4846 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4850 ( $conf->config('company_name', $self->agentnum),
4851 $conf->config('company_address', $self->agentnum),
4855 $letter_data{returnaddress} = '~';
4859 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4861 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4863 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4865 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4869 ) or die "can't open temp file: $!\n";
4870 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4871 or die "can't write temp file: $!\n";
4873 $letter_data{'logo_file'} = $lh->filename;
4875 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4879 ) or die "can't open temp file: $!\n";
4881 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4883 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4884 return ($1, $letter_data{'logo_file'});
4888 =item print_ps TEMPLATE
4890 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4896 my($file, $lfile) = $self->generate_letter(@_);
4897 my $ps = FS::Misc::generate_ps($file);
4898 unlink($file.'.tex');
4904 =item print TEMPLATE
4906 Prints the filled in template.
4908 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4912 sub queueable_print {
4915 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4916 or die "invalid customer number: " . $opt{custnum};
4918 #do not backport this change to 3.x
4919 # my $error = $self->print( { 'template' => $opt{template} } );
4920 my $error = $self->print( $opt{'template'} );
4921 die $error if $error;
4925 my ($self, $template) = (shift, shift);
4927 [ $self->print_ps($template) ],
4928 'agentnum' => $self->agentnum,
4932 #these three subs should just go away once agent stuff is all config overrides
4934 sub agent_template {
4936 $self->_agent_plandata('agent_templatename');
4939 sub agent_invoice_from {
4941 $self->_agent_plandata('agent_invoice_from');
4944 sub _agent_plandata {
4945 my( $self, $option ) = @_;
4947 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4948 #agent-specific Conf
4950 use FS::part_event::Condition;
4952 my $agentnum = $self->agentnum;
4954 my $regexp = regexp_sql();
4956 my $part_event_option =
4958 'select' => 'part_event_option.*',
4959 'table' => 'part_event_option',
4961 LEFT JOIN part_event USING ( eventpart )
4962 LEFT JOIN part_event_option AS peo_agentnum
4963 ON ( part_event.eventpart = peo_agentnum.eventpart
4964 AND peo_agentnum.optionname = 'agentnum'
4965 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4967 LEFT JOIN part_event_condition
4968 ON ( part_event.eventpart = part_event_condition.eventpart
4969 AND part_event_condition.conditionname = 'cust_bill_age'
4971 LEFT JOIN part_event_condition_option
4972 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4973 AND part_event_condition_option.optionname = 'age'
4976 #'hashref' => { 'optionname' => $option },
4977 #'hashref' => { 'part_event_option.optionname' => $option },
4979 " WHERE part_event_option.optionname = ". dbh->quote($option).
4980 " AND action = 'cust_bill_send_agent' ".
4981 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4982 " AND peo_agentnum.optionname = 'agentnum' ".
4983 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4985 CASE WHEN part_event_condition_option.optionname IS NULL
4987 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4989 , part_event.weight".
4993 unless ( $part_event_option ) {
4994 return $self->agent->invoice_template || ''
4995 if $option eq 'agent_templatename';
4999 $part_event_option->optionvalue;
5003 sub process_o2m_qsearch {
5006 return qsearch($table, @_) unless $table eq 'contact';
5008 my $hashref = shift;
5009 my %hash = %$hashref;
5010 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5011 or die 'guru meditation #4343';
5013 qsearch({ 'table' => 'contact',
5014 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5015 'hashref' => \%hash,
5016 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5017 " cust_contact.custnum = $custnum "
5021 sub process_o2m_qsearchs {
5024 return qsearchs($table, @_) unless $table eq 'contact';
5026 my $hashref = shift;
5027 my %hash = %$hashref;
5028 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5029 or die 'guru meditation #2121';
5031 qsearchs({ 'table' => 'contact',
5032 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5033 'hashref' => \%hash,
5034 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5035 " cust_contact.custnum = $custnum "
5039 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5041 Subroutine (not a method), designed to be called from the queue.
5043 Takes a list of options and values.
5045 Pulls up the customer record via the custnum option and calls bill_and_collect.
5050 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5052 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5053 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5055 #without this errors don't get rolled back
5056 $args{'fatal'} = 1; # runs from job queue, will be caught
5058 $cust_main->bill_and_collect( %args );
5061 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5063 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5064 C<collect> part. This is used in batch tax calculation, where invoice
5065 generation and collection events have to be completely separated.
5069 sub queued_collect {
5071 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5073 $cust_main->collect(%args);
5076 sub process_bill_and_collect {
5079 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5080 or die "custnum '$param->{custnum}' not found!\n";
5081 $param->{'job'} = $job;
5082 $param->{'fatal'} = 1; # runs from job queue, will be caught
5083 $param->{'retry'} = 1;
5085 $cust_main->bill_and_collect( %$param );
5088 #starting to take quite a while for big dbs
5089 # (JRNL: journaled so it only happens once per database)
5090 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5091 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5092 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5093 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5094 # JRNL leading/trailing spaces in first, last, company
5095 # JRNL migrate to cust_payby
5096 # - otaker upgrade? journal and call it good? (double check to make sure
5097 # we're not still setting otaker here)
5099 #only going to get worse with new location stuff...
5101 sub _upgrade_data { #class method
5102 my ($class, %opts) = @_;
5104 my @statements = ();
5106 #this seems to be the only expensive one.. why does it take so long?
5107 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5109 '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';
5110 FS::upgrade_journal->set_done('cust_main__signupdate');
5114 foreach my $sql ( @statements ) {
5115 my $sth = dbh->prepare($sql) or die dbh->errstr;
5116 $sth->execute or die $sth->errstr;
5117 #warn ( (time - $t). " seconds\n" );
5121 local($ignore_expired_card) = 1;
5122 local($ignore_banned_card) = 1;
5123 local($skip_fuzzyfiles) = 1;
5124 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5126 FS::cust_main::Location->_upgrade_data(%opts);
5128 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5130 foreach my $cust_main ( qsearch({
5131 'table' => 'cust_main',
5133 'extra_sql' => 'WHERE '.
5135 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5136 qw( first last company )
5139 my $error = $cust_main->replace;
5140 die $error if $error;
5143 FS::upgrade_journal->set_done('cust_main__trimspaces');
5147 unless ( FS::upgrade_journal->is_done('cust_main__cust_payby') ) {
5149 #we don't want to decrypt them, just stuff them as-is into cust_payby
5150 local(@encrypted_fields) = ();
5152 local($FS::cust_payby::ignore_expired_card) = 1;
5153 local($FS::cust_payby::ignore_banned_card) = 1;
5155 my @payfields = qw( payby payinfo paycvv paymask
5156 paydate paystart_month paystart_year payissue
5157 payname paystate paytype payip
5160 my $search = new FS::Cursor {
5161 'table' => 'cust_main',
5162 'extra_sql' => " WHERE ( payby IS NOT NULL AND payby != '' ) ",
5165 while (my $cust_main = $search->fetch) {
5167 unless ( $cust_main->payby =~ /^(BILL|COMP)$/ ) {
5169 my $cust_payby = new FS::cust_payby {
5170 'custnum' => $cust_main->custnum,
5172 map { $_ => $cust_main->$_(); } @payfields
5175 my $error = $cust_payby->insert;
5176 die $error if $error;
5180 # at the time we do this, also migrate paytype into cust_pay_batch
5181 # so that batches that are open before the migration can still be
5183 my @cust_pay_batch = qsearch('cust_pay_batch', {
5184 'custnum' => $cust_main->custnum,
5188 foreach my $cust_pay_batch (@cust_pay_batch) {
5189 $cust_pay_batch->set('paytype', $cust_main->get('paytype'));
5190 my $error = $cust_pay_batch->replace;
5191 die "$error (setting cust_pay_batch.paytype)" if $error;
5194 $cust_main->complimentary('Y') if $cust_main->payby eq 'COMP';
5196 $cust_main->invoice_attn( $cust_main->payname )
5197 if $cust_main->payby eq 'BILL' && $cust_main->payname;
5198 $cust_main->po_number( $cust_main->payinfo )
5199 if $cust_main->payby eq 'BILL' && $cust_main->payinfo;
5201 $cust_main->setfield($_, '') foreach @payfields;
5202 my $error = $cust_main->replace;
5203 die "Error upgradging payment information for custnum ".
5204 $cust_main->custnum. ": $error"
5209 FS::upgrade_journal->set_done('cust_main__cust_payby');
5212 $class->_upgrade_otaker(%opts);
5222 The delete method should possibly take an FS::cust_main object reference
5223 instead of a scalar customer number.
5225 Bill and collect options should probably be passed as references instead of a
5228 There should probably be a configuration file with a list of allowed credit
5231 No multiple currency support (probably a larger project than just this module).
5233 Birthdates rely on negative epoch values.
5235 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5239 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5240 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5241 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.