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 List::Util qw(min);
32 use FS::UID qw( dbh driver_name );
33 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
35 use FS::Misc qw( generate_ps do_print money_pretty card_types );
36 use FS::Msgcat qw(gettext);
43 use FS::cust_bill_void;
44 use FS::legacy_cust_bill;
46 use FS::cust_pay_pending;
47 use FS::cust_pay_void;
48 use FS::cust_pay_batch;
51 use FS::part_referral;
52 use FS::cust_main_county;
53 use FS::cust_location;
56 use FS::cust_main_exemption;
57 use FS::cust_tax_adjustment;
58 use FS::cust_tax_location;
59 use FS::agent_currency;
60 use FS::cust_main_invoice;
62 use FS::prepay_credit;
68 use FS::payment_gateway;
69 use FS::agent_payment_gateway;
71 use FS::cust_main_note;
72 use FS::cust_attachment;
75 use FS::upgrade_journal;
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
84 our $me = '[FS::cust_main]';
87 our $ignore_expired_card = 0;
88 our $ignore_banned_card = 0;
89 our $ignore_invalid_card = 0;
91 our $skip_fuzzyfiles = 0;
93 our $ucfirst_nowarn = 0;
95 #this info is in cust_payby as of 4.x
96 #this and the fields themselves can be removed in 5.x
97 our @encrypted_fields = ('payinfo', 'paycvv');
98 sub nohistory_fields { ('payinfo', 'paycvv'); }
101 our $default_agent_custid;
102 our $custnum_display_length;
103 #ask FS::UID to run this stuff for us later
104 #$FS::UID::callback{'FS::cust_main'} = sub {
105 install_callback FS::UID sub {
106 $conf = new FS::Conf;
107 #yes, need it for stuff below (prolly should be cached)
108 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
109 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
110 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
115 my ( $hashref, $cache ) = @_;
116 if ( exists $hashref->{'pkgnum'} ) {
117 #@{ $self->{'_pkgnum'} } = ();
118 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
119 $self->{'_pkgnum'} = $subcache;
120 #push @{ $self->{'_pkgnum'} },
121 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
127 FS::cust_main - Object methods for cust_main records
133 $record = new FS::cust_main \%hash;
134 $record = new FS::cust_main { 'column' => 'value' };
136 $error = $record->insert;
138 $error = $new_record->replace($old_record);
140 $error = $record->delete;
142 $error = $record->check;
144 @cust_pkg = $record->all_pkgs;
146 @cust_pkg = $record->ncancelled_pkgs;
148 @cust_pkg = $record->suspended_pkgs;
150 $error = $record->bill;
151 $error = $record->bill %options;
152 $error = $record->bill 'time' => $time;
154 $error = $record->collect;
155 $error = $record->collect %options;
156 $error = $record->collect 'invoice_time' => $time,
161 An FS::cust_main object represents a customer. FS::cust_main inherits from
162 FS::Record. The following fields are currently supported:
168 Primary key (assigned automatically for new customers)
172 Agent (see L<FS::agent>)
176 Advertising source (see L<FS::part_referral>)
188 Cocial security number (optional)
212 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
216 Payment Information (See L<FS::payinfo_Mixin> for data format)
220 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
224 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
228 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
232 Start date month (maestro/solo cards only)
236 Start date year (maestro/solo cards only)
240 Issue number (maestro/solo cards only)
244 Name on card or billing name
248 IP address from which payment information was received
252 Tax exempt, empty or `Y'
256 Order taker (see L<FS::access_user>)
262 =item referral_custnum
264 Referring customer number
268 Enable individual CDR spooling, empty or `Y'
272 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
276 Discourage individual CDR printing, empty or `Y'
280 Allow self-service editing of ticket subjects, empty or 'Y'
282 =item calling_list_exempt
284 Do not call, empty or 'Y'
286 =item invoice_ship_address
288 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
298 Creates a new customer. To add the customer to the database, see L<"insert">.
300 Note that this stores the hash reference, not a distinct copy of the hash it
301 points to. You can ask the object for a copy with the I<hash> method.
305 sub table { 'cust_main'; }
307 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
309 Adds this customer to the database. If there is an error, returns the error,
310 otherwise returns false.
312 Usually the customer's location will not yet exist in the database, and
313 the C<bill_location> and C<ship_location> pseudo-fields must be set to
314 uninserted L<FS::cust_location> objects. These will be inserted and linked
315 (in both directions) to the new customer record. If they're references
316 to the same object, they will become the same location.
318 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
319 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
320 are inserted atomicly, or the transaction is rolled back. Passing an empty
321 hash reference is equivalent to not supplying this parameter. There should be
322 a better explanation of this, but until then, here's an example:
325 tie %hash, 'Tie::RefHash'; #this part is important
327 $cust_pkg => [ $svc_acct ],
330 $cust_main->insert( \%hash );
332 INVOICING_LIST_ARYREF: No longer supported.
334 Currently available options are: I<depend_jobnum>, I<noexport>,
335 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
337 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
338 on the supplied jobnum (they will not run until the specific job completes).
339 This can be used to defer provisioning until some action completes (such
340 as running the customer's credit card successfully).
342 The I<noexport> option is deprecated. If I<noexport> is set true, no
343 provisioning jobs (exports) are scheduled. (You can schedule them later with
344 the B<reexport> method.)
346 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
347 of tax names and exemption numbers. FS::cust_main_exemption records will be
348 created and inserted.
350 If I<prospectnum> is set, moves contacts and locations from that prospect.
352 If I<contact> is set to an arrayref of FS::contact objects, those will be
355 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
356 unset), inserts those new contacts with this new customer. Handles CGI
357 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
359 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
360 new stored payment records with this new customer. Handles CGI parameters
361 for an "m2" multiple entry field as passed by edit/cust_main.cgi
367 my $cust_pkgs = @_ ? shift : {};
369 if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
370 warn "cust_main::insert using deprecated invoicing list argument";
371 $invoicing_list = shift;
374 warn "$me insert called with options ".
375 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
378 local $SIG{HUP} = 'IGNORE';
379 local $SIG{INT} = 'IGNORE';
380 local $SIG{QUIT} = 'IGNORE';
381 local $SIG{TERM} = 'IGNORE';
382 local $SIG{TSTP} = 'IGNORE';
383 local $SIG{PIPE} = 'IGNORE';
385 my $oldAutoCommit = $FS::UID::AutoCommit;
386 local $FS::UID::AutoCommit = 0;
389 my $prepay_identifier = '';
390 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
392 if ( $self->payby eq 'PREPAY' ) {
394 $self->payby(''); #'BILL');
395 $prepay_identifier = $self->payinfo;
398 warn " looking up prepaid card $prepay_identifier\n"
401 my $error = $self->get_prepay( $prepay_identifier,
402 'amount_ref' => \$amount,
403 'seconds_ref' => \$seconds,
404 'upbytes_ref' => \$upbytes,
405 'downbytes_ref' => \$downbytes,
406 'totalbytes_ref' => \$totalbytes,
409 $dbh->rollback if $oldAutoCommit;
410 #return "error applying prepaid card (transaction rolled back): $error";
414 $payby = 'PREP' if $amount;
416 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
419 $self->payby(''); #'BILL');
420 $amount = $self->paid;
425 foreach my $l (qw(bill_location ship_location)) {
427 my $loc = delete $self->hashref->{$l} or next;
429 if ( !$loc->locationnum ) {
430 # warn the location that we're going to insert it with no custnum
431 $loc->set(custnum_pending => 1);
432 warn " inserting $l\n"
434 my $error = $loc->insert;
436 $dbh->rollback if $oldAutoCommit;
437 my $label = $l eq 'ship_location' ? 'service' : 'billing';
438 return "$error (in $label location)";
441 } elsif ( $loc->prospectnum ) {
443 $loc->prospectnum('');
444 $loc->set(custnum_pending => 1);
445 my $error = $loc->replace;
447 $dbh->rollback if $oldAutoCommit;
448 my $label = $l eq 'ship_location' ? 'service' : 'billing';
449 return "$error (moving $label location)";
452 } elsif ( ($loc->custnum || 0) > 0 ) {
453 # then it somehow belongs to another customer--shouldn't happen
454 $dbh->rollback if $oldAutoCommit;
455 return "$l belongs to customer ".$loc->custnum;
457 # else it already belongs to this customer
458 # (happens when ship_location is identical to bill_location)
460 $self->set($l.'num', $loc->locationnum);
462 if ( $self->get($l.'num') eq '' ) {
463 $dbh->rollback if $oldAutoCommit;
468 warn " inserting $self\n"
471 $self->signupdate(time) unless $self->signupdate;
473 $self->auto_agent_custid()
474 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
476 my $error = $self->check_payinfo_cardtype
477 || $self->SUPER::insert;
479 $dbh->rollback if $oldAutoCommit;
480 #return "inserting cust_main record (transaction rolled back): $error";
484 # now set cust_location.custnum
485 foreach my $l (qw(bill_location ship_location)) {
486 warn " setting $l.custnum\n"
488 my $loc = $self->$l or next;
489 unless ( $loc->custnum ) {
490 $loc->set(custnum => $self->custnum);
491 $error ||= $loc->replace;
495 $dbh->rollback if $oldAutoCommit;
496 return "error setting $l custnum: $error";
500 warn " setting customer tags\n"
503 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
504 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
505 'custnum' => $self->custnum };
506 my $error = $cust_tag->insert;
508 $dbh->rollback if $oldAutoCommit;
513 my $prospectnum = delete $options{'prospectnum'};
514 if ( $prospectnum ) {
516 warn " moving contacts and locations from prospect $prospectnum\n"
520 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
521 unless ( $prospect_main ) {
522 $dbh->rollback if $oldAutoCommit;
523 return "Unknown prospectnum $prospectnum";
525 $prospect_main->custnum($self->custnum);
526 $prospect_main->disabled('Y');
527 my $error = $prospect_main->replace;
529 $dbh->rollback if $oldAutoCommit;
533 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
534 my $cust_contact = new FS::cust_contact {
535 'custnum' => $self->custnum,
536 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
538 my $error = $cust_contact->insert
539 || $prospect_contact->delete;
541 $dbh->rollback if $oldAutoCommit;
546 my @cust_location = $prospect_main->cust_location;
547 my @qual = $prospect_main->qual;
549 foreach my $r ( @cust_location, @qual ) {
551 $r->custnum($self->custnum);
552 my $error = $r->replace;
554 $dbh->rollback if $oldAutoCommit;
561 warn " setting contacts\n"
564 $invoicing_list ||= $options{'invoicing_list'};
565 if ( $invoicing_list ) {
567 $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
570 foreach my $dest (@$invoicing_list ) {
571 if ($dest eq 'POST') {
572 $self->set('postal_invoice', 'Y');
575 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
576 if ( $contact_email ) {
577 my $cust_contact = FS::cust_contact->new({
578 contactnum => $contact_email->contactnum,
579 custnum => $self->custnum,
581 $cust_contact->set('invoice_dest', 'Y');
582 my $error = $cust_contact->contactnum ?
583 $cust_contact->replace : $cust_contact->insert;
585 $dbh->rollback if $oldAutoCommit;
586 return "$error (linking to email address $dest)";
590 # this email address is not yet linked to any contact
591 $email .= ',' if length($email);
597 my $contact = FS::contact->new({
598 'custnum' => $self->get('custnum'),
599 'last' => $self->get('last'),
600 'first' => $self->get('first'),
601 'emailaddress' => $email,
602 'invoice_dest' => 'Y', # yes, you can set this via the contact
604 my $error = $contact->insert;
606 $dbh->rollback if $oldAutoCommit;
612 if ( my $contact = delete $options{'contact'} ) {
614 foreach my $c ( @$contact ) {
615 $c->custnum($self->custnum);
616 my $error = $c->insert;
618 $dbh->rollback if $oldAutoCommit;
624 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
626 my $error = $self->process_o2m( 'table' => 'contact',
627 'fields' => FS::contact->cgi_contact_fields,
628 'params' => $contact_params,
631 $dbh->rollback if $oldAutoCommit;
636 warn " setting cust_payby\n"
639 if ( $options{cust_payby} ) {
641 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
642 $cust_payby->custnum($self->custnum);
643 my $error = $cust_payby->insert;
645 $dbh->rollback if $oldAutoCommit;
650 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
652 my $error = $self->process_o2m(
653 'table' => 'cust_payby',
654 'fields' => FS::cust_payby->cgi_cust_payby_fields,
655 'params' => $cust_payby_params,
656 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
659 $dbh->rollback if $oldAutoCommit;
665 warn " setting cust_main_exemption\n"
668 my $tax_exemption = delete $options{'tax_exemption'};
669 if ( $tax_exemption ) {
671 $tax_exemption = { map { $_ => '' } @$tax_exemption }
672 if ref($tax_exemption) eq 'ARRAY';
674 foreach my $taxname ( keys %$tax_exemption ) {
675 my $cust_main_exemption = new FS::cust_main_exemption {
676 'custnum' => $self->custnum,
677 'taxname' => $taxname,
678 'exempt_number' => $tax_exemption->{$taxname},
680 my $error = $cust_main_exemption->insert;
682 $dbh->rollback if $oldAutoCommit;
683 return "inserting cust_main_exemption (transaction rolled back): $error";
688 warn " ordering packages\n"
691 $error = $self->order_pkgs( $cust_pkgs,
693 'seconds_ref' => \$seconds,
694 'upbytes_ref' => \$upbytes,
695 'downbytes_ref' => \$downbytes,
696 'totalbytes_ref' => \$totalbytes,
699 $dbh->rollback if $oldAutoCommit;
704 $dbh->rollback if $oldAutoCommit;
705 return "No svc_acct record to apply pre-paid time";
707 if ( $upbytes || $downbytes || $totalbytes ) {
708 $dbh->rollback if $oldAutoCommit;
709 return "No svc_acct record to apply pre-paid data";
713 warn " inserting initial $payby payment of $amount\n"
715 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
717 $dbh->rollback if $oldAutoCommit;
718 return "inserting payment (transaction rolled back): $error";
722 unless ( $import || $skip_fuzzyfiles ) {
723 warn " queueing fuzzyfiles update\n"
725 $error = $self->queue_fuzzyfiles_update;
727 $dbh->rollback if $oldAutoCommit;
728 return "updating fuzzy search cache: $error";
732 # FS::geocode_Mixin::after_insert or something?
733 if ( $conf->config('tax_district_method') and !$import ) {
734 # if anything non-empty, try to look it up
735 my $queue = new FS::queue {
736 'job' => 'FS::geocode_Mixin::process_district_update',
737 'custnum' => $self->custnum,
739 my $error = $queue->insert( ref($self), $self->custnum );
741 $dbh->rollback if $oldAutoCommit;
742 return "queueing tax district update: $error";
747 warn " exporting\n" if $DEBUG > 1;
749 my $export_args = $options{'export_args'} || [];
752 map qsearch( 'part_export', {exportnum=>$_} ),
753 $conf->config('cust_main-exports'); #, $agentnum
755 foreach my $part_export ( @part_export ) {
756 my $error = $part_export->export_insert($self, @$export_args);
758 $dbh->rollback if $oldAutoCommit;
759 return "exporting to ". $part_export->exporttype.
760 " (transaction rolled back): $error";
764 #foreach my $depend_jobnum ( @$depend_jobnums ) {
765 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
767 # foreach my $jobnum ( @jobnums ) {
768 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
769 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
771 # my $error = $queue->depend_insert($depend_jobnum);
773 # $dbh->rollback if $oldAutoCommit;
774 # return "error queuing job dependancy: $error";
781 #if ( exists $options{'jobnums'} ) {
782 # push @{ $options{'jobnums'} }, @jobnums;
785 warn " insert complete; committing transaction\n"
788 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
793 use File::CounterFile;
794 sub auto_agent_custid {
797 my $format = $conf->config('cust_main-auto_agent_custid');
799 if ( $format eq '1YMMXXXXXXXX' ) {
801 my $counter = new File::CounterFile 'cust_main.agent_custid';
804 my $ym = 100000000000 + time2str('%y%m00000000', time);
805 if ( $ym > $counter->value ) {
806 $counter->{'value'} = $agent_custid = $ym;
807 $counter->{'updated'} = 1;
809 $agent_custid = $counter->inc;
815 die "Unknown cust_main-auto_agent_custid format: $format";
818 $self->agent_custid($agent_custid);
822 =item PACKAGE METHODS
824 Documentation on customer package methods has been moved to
825 L<FS::cust_main::Packages>.
827 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
829 Recharges this (existing) customer with the specified prepaid card (see
830 L<FS::prepay_credit>), specified either by I<identifier> or as an
831 FS::prepay_credit object. If there is an error, returns the error, otherwise
834 Optionally, five scalar references can be passed as well. They will have their
835 values filled in with the amount, number of seconds, and number of upload,
836 download, and total bytes applied by this prepaid card.
840 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
841 #the only place that uses these args
842 sub recharge_prepay {
843 my( $self, $prepay_credit, $amountref, $secondsref,
844 $upbytesref, $downbytesref, $totalbytesref ) = @_;
846 local $SIG{HUP} = 'IGNORE';
847 local $SIG{INT} = 'IGNORE';
848 local $SIG{QUIT} = 'IGNORE';
849 local $SIG{TERM} = 'IGNORE';
850 local $SIG{TSTP} = 'IGNORE';
851 local $SIG{PIPE} = 'IGNORE';
853 my $oldAutoCommit = $FS::UID::AutoCommit;
854 local $FS::UID::AutoCommit = 0;
857 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
859 my $error = $self->get_prepay( $prepay_credit,
860 'amount_ref' => \$amount,
861 'seconds_ref' => \$seconds,
862 'upbytes_ref' => \$upbytes,
863 'downbytes_ref' => \$downbytes,
864 'totalbytes_ref' => \$totalbytes,
866 || $self->increment_seconds($seconds)
867 || $self->increment_upbytes($upbytes)
868 || $self->increment_downbytes($downbytes)
869 || $self->increment_totalbytes($totalbytes)
870 || $self->insert_cust_pay_prepay( $amount,
872 ? $prepay_credit->identifier
877 $dbh->rollback if $oldAutoCommit;
881 if ( defined($amountref) ) { $$amountref = $amount; }
882 if ( defined($secondsref) ) { $$secondsref = $seconds; }
883 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
884 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
885 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
887 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
892 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
894 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
895 specified either by I<identifier> or as an FS::prepay_credit object.
897 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
898 incremented by the values of the prepaid card.
900 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
901 check or set this customer's I<agentnum>.
903 If there is an error, returns the error, otherwise returns false.
909 my( $self, $prepay_credit, %opt ) = @_;
911 local $SIG{HUP} = 'IGNORE';
912 local $SIG{INT} = 'IGNORE';
913 local $SIG{QUIT} = 'IGNORE';
914 local $SIG{TERM} = 'IGNORE';
915 local $SIG{TSTP} = 'IGNORE';
916 local $SIG{PIPE} = 'IGNORE';
918 my $oldAutoCommit = $FS::UID::AutoCommit;
919 local $FS::UID::AutoCommit = 0;
922 unless ( ref($prepay_credit) ) {
924 my $identifier = $prepay_credit;
926 $prepay_credit = qsearchs(
928 { 'identifier' => $identifier },
933 unless ( $prepay_credit ) {
934 $dbh->rollback if $oldAutoCommit;
935 return "Invalid prepaid card: ". $identifier;
940 if ( $prepay_credit->agentnum ) {
941 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
942 $dbh->rollback if $oldAutoCommit;
943 return "prepaid card not valid for agent ". $self->agentnum;
945 $self->agentnum($prepay_credit->agentnum);
948 my $error = $prepay_credit->delete;
950 $dbh->rollback if $oldAutoCommit;
951 return "removing prepay_credit (transaction rolled back): $error";
954 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
955 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
957 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
962 =item increment_upbytes SECONDS
964 Updates this customer's single or primary account (see L<FS::svc_acct>) by
965 the specified number of upbytes. If there is an error, returns the error,
966 otherwise returns false.
970 sub increment_upbytes {
971 _increment_column( shift, 'upbytes', @_);
974 =item increment_downbytes SECONDS
976 Updates this customer's single or primary account (see L<FS::svc_acct>) by
977 the specified number of downbytes. If there is an error, returns the error,
978 otherwise returns false.
982 sub increment_downbytes {
983 _increment_column( shift, 'downbytes', @_);
986 =item increment_totalbytes SECONDS
988 Updates this customer's single or primary account (see L<FS::svc_acct>) by
989 the specified number of totalbytes. If there is an error, returns the error,
990 otherwise returns false.
994 sub increment_totalbytes {
995 _increment_column( shift, 'totalbytes', @_);
998 =item increment_seconds SECONDS
1000 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1001 the specified number of seconds. If there is an error, returns the error,
1002 otherwise returns false.
1006 sub increment_seconds {
1007 _increment_column( shift, 'seconds', @_);
1010 =item _increment_column AMOUNT
1012 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1013 the specified number of seconds or bytes. If there is an error, returns
1014 the error, otherwise returns false.
1018 sub _increment_column {
1019 my( $self, $column, $amount ) = @_;
1020 warn "$me increment_column called: $column, $amount\n"
1023 return '' unless $amount;
1025 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1026 $self->ncancelled_pkgs;
1028 if ( ! @cust_pkg ) {
1029 return 'No packages with primary or single services found'.
1030 ' to apply pre-paid time';
1031 } elsif ( scalar(@cust_pkg) > 1 ) {
1032 #maybe have a way to specify the package/account?
1033 return 'Multiple packages found to apply pre-paid time';
1036 my $cust_pkg = $cust_pkg[0];
1037 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1041 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1043 if ( ! @cust_svc ) {
1044 return 'No account found to apply pre-paid time';
1045 } elsif ( scalar(@cust_svc) > 1 ) {
1046 return 'Multiple accounts found to apply pre-paid time';
1049 my $svc_acct = $cust_svc[0]->svc_x;
1050 warn " found service svcnum ". $svc_acct->pkgnum.
1051 ' ('. $svc_acct->email. ")\n"
1054 $column = "increment_$column";
1055 $svc_acct->$column($amount);
1059 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1061 Inserts a prepayment in the specified amount for this customer. An optional
1062 second argument can specify the prepayment identifier for tracking purposes.
1063 If there is an error, returns the error, otherwise returns false.
1067 sub insert_cust_pay_prepay {
1068 shift->insert_cust_pay('PREP', @_);
1071 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1073 Inserts a cash payment in the specified amount for this customer. An optional
1074 second argument can specify the payment identifier for tracking purposes.
1075 If there is an error, returns the error, otherwise returns false.
1079 sub insert_cust_pay_cash {
1080 shift->insert_cust_pay('CASH', @_);
1083 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1085 Inserts a Western Union payment in the specified amount for this customer. An
1086 optional second argument can specify the prepayment identifier for tracking
1087 purposes. If there is an error, returns the error, otherwise returns false.
1091 sub insert_cust_pay_west {
1092 shift->insert_cust_pay('WEST', @_);
1095 sub insert_cust_pay {
1096 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1097 my $payinfo = scalar(@_) ? shift : '';
1099 my $cust_pay = new FS::cust_pay {
1100 'custnum' => $self->custnum,
1101 'paid' => sprintf('%.2f', $amount),
1102 #'_date' => #date the prepaid card was purchased???
1104 'payinfo' => $payinfo,
1110 =item delete [ OPTION => VALUE ... ]
1112 This deletes the customer. If there is an error, returns the error, otherwise
1115 This will completely remove all traces of the customer record. This is not
1116 what you want when a customer cancels service; for that, cancel all of the
1117 customer's packages (see L</cancel>).
1119 If the customer has any uncancelled packages, you need to pass a new (valid)
1120 customer number for those packages to be transferred to, as the "new_customer"
1121 option. Cancelled packages will be deleted. Did I mention that this is NOT
1122 what you want when a customer cancels service and that you really should be
1123 looking at L<FS::cust_pkg/cancel>?
1125 You can't delete a customer with invoices (see L<FS::cust_bill>),
1126 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1127 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1128 set the "delete_financials" option to a true value.
1133 my( $self, %opt ) = @_;
1135 local $SIG{HUP} = 'IGNORE';
1136 local $SIG{INT} = 'IGNORE';
1137 local $SIG{QUIT} = 'IGNORE';
1138 local $SIG{TERM} = 'IGNORE';
1139 local $SIG{TSTP} = 'IGNORE';
1140 local $SIG{PIPE} = 'IGNORE';
1142 my $oldAutoCommit = $FS::UID::AutoCommit;
1143 local $FS::UID::AutoCommit = 0;
1146 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1147 $dbh->rollback if $oldAutoCommit;
1148 return "Can't delete a master agent customer";
1151 #use FS::access_user
1152 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1153 $dbh->rollback if $oldAutoCommit;
1154 return "Can't delete a master employee customer";
1157 tie my %financial_tables, 'Tie::IxHash',
1158 'cust_bill' => 'invoices',
1159 'cust_statement' => 'statements',
1160 'cust_credit' => 'credits',
1161 'cust_pay' => 'payments',
1162 'cust_refund' => 'refunds',
1165 foreach my $table ( keys %financial_tables ) {
1167 my @records = $self->$table();
1169 if ( @records && ! $opt{'delete_financials'} ) {
1170 $dbh->rollback if $oldAutoCommit;
1171 return "Can't delete a customer with ". $financial_tables{$table};
1174 foreach my $record ( @records ) {
1175 my $error = $record->delete;
1177 $dbh->rollback if $oldAutoCommit;
1178 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1184 my @cust_pkg = $self->ncancelled_pkgs;
1186 my $new_custnum = $opt{'new_custnum'};
1187 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1188 $dbh->rollback if $oldAutoCommit;
1189 return "Invalid new customer number: $new_custnum";
1191 foreach my $cust_pkg ( @cust_pkg ) {
1192 my %hash = $cust_pkg->hash;
1193 $hash{'custnum'} = $new_custnum;
1194 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1195 my $error = $new_cust_pkg->replace($cust_pkg,
1196 options => { $cust_pkg->options },
1199 $dbh->rollback if $oldAutoCommit;
1204 my @cancelled_cust_pkg = $self->all_pkgs;
1205 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1206 my $error = $cust_pkg->delete;
1208 $dbh->rollback if $oldAutoCommit;
1213 #cust_tax_adjustment in financials?
1214 #cust_pay_pending? ouch
1215 foreach my $table (qw(
1216 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1217 cust_payby cust_location cust_main_note cust_tax_adjustment
1218 cust_pay_void cust_pay_batch queue cust_tax_exempt
1220 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1221 my $error = $record->delete;
1223 $dbh->rollback if $oldAutoCommit;
1229 my $sth = $dbh->prepare(
1230 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1232 my $errstr = $dbh->errstr;
1233 $dbh->rollback if $oldAutoCommit;
1236 $sth->execute($self->custnum) or do {
1237 my $errstr = $sth->errstr;
1238 $dbh->rollback if $oldAutoCommit;
1244 my $ticket_dbh = '';
1245 if ($conf->config('ticket_system') eq 'RT_Internal') {
1247 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1248 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1249 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1250 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1253 if ( $ticket_dbh ) {
1255 my $ticket_sth = $ticket_dbh->prepare(
1256 'DELETE FROM Links WHERE Target = ?'
1258 my $errstr = $ticket_dbh->errstr;
1259 $dbh->rollback if $oldAutoCommit;
1262 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1264 my $errstr = $ticket_sth->errstr;
1265 $dbh->rollback if $oldAutoCommit;
1269 #check and see if the customer is the only link on the ticket, and
1270 #if so, set the ticket to deleted status in RT?
1271 #maybe someday, for now this will at least fix tickets not displaying
1275 #delete the customer record
1277 my $error = $self->SUPER::delete;
1279 $dbh->rollback if $oldAutoCommit;
1283 # cust_main exports!
1285 #my $export_args = $options{'export_args'} || [];
1288 map qsearch( 'part_export', {exportnum=>$_} ),
1289 $conf->config('cust_main-exports'); #, $agentnum
1291 foreach my $part_export ( @part_export ) {
1292 my $error = $part_export->export_delete( $self ); #, @$export_args);
1294 $dbh->rollback if $oldAutoCommit;
1295 return "exporting to ". $part_export->exporttype.
1296 " (transaction rolled back): $error";
1300 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1305 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1307 Replaces the OLD_RECORD with this one in the database. If there is an error,
1308 returns the error, otherwise returns false.
1310 To change the customer's address, set the pseudo-fields C<bill_location> and
1311 C<ship_location>. The address will still only change if at least one of the
1312 address fields differs from the existing values.
1314 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1315 set as the contact email address for a default contact with the same name as
1318 Currently available options are: I<tax_exemption>, I<cust_payby_params>,
1319 I<contact_params>, I<invoicing_list>.
1321 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1322 of tax names and exemption numbers. FS::cust_main_exemption records will be
1323 deleted and inserted as appropriate.
1325 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1326 groups (describing the customer's payment methods and contacts, respectively)
1327 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1328 and L<FS::contact> for the fields these can contain.
1330 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1331 should be used instead if possible.
1338 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1340 : $self->replace_old;
1344 warn "$me replace called\n"
1347 my $curuser = $FS::CurrentUser::CurrentUser;
1348 return "You are not permitted to create complimentary accounts."
1349 if $self->complimentary eq 'Y'
1350 && $self->complimentary ne $old->complimentary
1351 && ! $curuser->access_right('Complimentary customer');
1353 local($ignore_expired_card) = 1
1354 if $old->payby =~ /^(CARD|DCRD)$/
1355 && $self->payby =~ /^(CARD|DCRD)$/
1356 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1358 local($ignore_banned_card) = 1
1359 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1360 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1361 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1363 if ( $self->payby =~ /^(CARD|DCRD)$/
1364 && $old->payinfo ne $self->payinfo
1365 && $old->paymask ne $self->paymask )
1367 my $error = $self->check_payinfo_cardtype;
1368 return $error if $error;
1371 return "Invoicing locale is required"
1374 && $conf->exists('cust_main-require_locale');
1376 local $SIG{HUP} = 'IGNORE';
1377 local $SIG{INT} = 'IGNORE';
1378 local $SIG{QUIT} = 'IGNORE';
1379 local $SIG{TERM} = 'IGNORE';
1380 local $SIG{TSTP} = 'IGNORE';
1381 local $SIG{PIPE} = 'IGNORE';
1383 my $oldAutoCommit = $FS::UID::AutoCommit;
1384 local $FS::UID::AutoCommit = 0;
1387 for my $l (qw(bill_location ship_location)) {
1388 #my $old_loc = $old->$l;
1389 my $new_loc = $self->$l or next;
1391 # find the existing location if there is one
1392 $new_loc->set('custnum' => $self->custnum);
1393 my $error = $new_loc->find_or_insert;
1395 $dbh->rollback if $oldAutoCommit;
1398 $self->set($l.'num', $new_loc->locationnum);
1402 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1403 warn "cust_main::replace: using deprecated invoicing list argument";
1404 $invoicing_list = shift @param;
1407 my %options = @param;
1409 $invoicing_list ||= $options{invoicing_list};
1411 my @contacts = map { $_->contact } $self->cust_contact;
1412 # find a contact that matches the customer's name
1413 my ($implicit_contact) = grep { $_->first eq $old->get('first')
1414 and $_->last eq $old->get('last') }
1416 $implicit_contact ||= FS::contact->new({
1417 'custnum' => $self->custnum,
1418 'locationnum' => $self->get('bill_locationnum'),
1421 # for any of these that are already contact emails, link to the existing
1423 if ( $invoicing_list ) {
1426 # kind of like process_m2m on these, except:
1427 # - the other side is two tables in a join
1428 # - and we might have to create new contact_emails
1429 # - and possibly a new contact
1431 # Find existing invoice emails that aren't on the implicit contact.
1432 # Any of these that are not on the new invoicing list will be removed.
1433 my %old_email_cust_contact;
1434 foreach my $cust_contact ($self->cust_contact) {
1435 next if !$cust_contact->invoice_dest;
1436 next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1438 foreach my $contact_email ($cust_contact->contact->contact_email) {
1439 $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1443 foreach my $dest (@$invoicing_list) {
1445 if ($dest eq 'POST') {
1447 $self->set('postal_invoice', 'Y');
1449 } elsif ( exists($old_email_cust_contact{$dest}) ) {
1451 delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1455 # See if it belongs to some other contact; if so, link it.
1456 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1458 and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1459 my $cust_contact = qsearchs('cust_contact', {
1460 contactnum => $contact_email->contactnum,
1461 custnum => $self->custnum,
1462 }) || FS::cust_contact->new({
1463 contactnum => $contact_email->contactnum,
1464 custnum => $self->custnum,
1466 $cust_contact->set('invoice_dest', 'Y');
1467 my $error = $cust_contact->custcontactnum ?
1468 $cust_contact->replace : $cust_contact->insert;
1470 $dbh->rollback if $oldAutoCommit;
1471 return "$error (linking to email address $dest)";
1475 # This email address is not yet linked to any contact, so it will
1476 # be added to the implicit contact.
1477 $email .= ',' if length($email);
1483 foreach my $remove_dest (keys %old_email_cust_contact) {
1484 my $cust_contact = $old_email_cust_contact{$remove_dest};
1485 # These were not in the list of requested destinations, so take them off.
1486 $cust_contact->set('invoice_dest', '');
1487 my $error = $cust_contact->replace;
1489 $dbh->rollback if $oldAutoCommit;
1490 return "$error (unlinking email address $remove_dest)";
1494 # make sure it keeps up with the changed customer name, if any
1495 $implicit_contact->set('last', $self->get('last'));
1496 $implicit_contact->set('first', $self->get('first'));
1497 $implicit_contact->set('emailaddress', $email);
1498 $implicit_contact->set('invoice_dest', 'Y');
1499 $implicit_contact->set('custnum', $self->custnum);
1502 if ( $implicit_contact->contactnum ) {
1503 $error = $implicit_contact->replace;
1504 } elsif ( length($email) ) { # don't create a new contact if not needed
1505 $error = $implicit_contact->insert;
1509 $dbh->rollback if $oldAutoCommit;
1510 return "$error (adding email address $email)";
1515 # replace the customer record
1516 my $error = $self->SUPER::replace($old);
1519 $dbh->rollback if $oldAutoCommit;
1523 # now move packages to the new service location
1524 $self->set('ship_location', ''); #flush cache
1525 if ( $old->ship_locationnum and # should only be null during upgrade...
1526 $old->ship_locationnum != $self->ship_locationnum ) {
1527 $error = $old->ship_location->move_to($self->ship_location);
1529 $dbh->rollback if $oldAutoCommit;
1533 # don't move packages based on the billing location, but
1534 # disable it if it's no longer in use
1535 if ( $old->bill_locationnum and
1536 $old->bill_locationnum != $self->bill_locationnum ) {
1537 $error = $old->bill_location->disable_if_unused;
1539 $dbh->rollback if $oldAutoCommit;
1544 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1546 #this could be more efficient than deleting and re-inserting, if it matters
1547 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1548 my $error = $cust_tag->delete;
1550 $dbh->rollback if $oldAutoCommit;
1554 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1555 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1556 'custnum' => $self->custnum };
1557 my $error = $cust_tag->insert;
1559 $dbh->rollback if $oldAutoCommit;
1566 my $tax_exemption = delete $options{'tax_exemption'};
1567 if ( $tax_exemption ) {
1569 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1570 if ref($tax_exemption) eq 'ARRAY';
1572 my %cust_main_exemption =
1573 map { $_->taxname => $_ }
1574 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1576 foreach my $taxname ( keys %$tax_exemption ) {
1578 if ( $cust_main_exemption{$taxname} &&
1579 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1582 delete $cust_main_exemption{$taxname};
1586 my $cust_main_exemption = new FS::cust_main_exemption {
1587 'custnum' => $self->custnum,
1588 'taxname' => $taxname,
1589 'exempt_number' => $tax_exemption->{$taxname},
1591 my $error = $cust_main_exemption->insert;
1593 $dbh->rollback if $oldAutoCommit;
1594 return "inserting cust_main_exemption (transaction rolled back): $error";
1598 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1599 my $error = $cust_main_exemption->delete;
1601 $dbh->rollback if $oldAutoCommit;
1602 return "deleting cust_main_exemption (transaction rolled back): $error";
1608 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1610 my $error = $self->process_o2m(
1611 'table' => 'cust_payby',
1612 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1613 'params' => $cust_payby_params,
1614 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1617 $dbh->rollback if $oldAutoCommit;
1623 if ( my $contact_params = delete $options{'contact_params'} ) {
1625 # this can potentially replace contacts that were created by the
1626 # invoicing list argument, but the UI shouldn't allow both of them
1629 my $error = $self->process_o2m(
1630 'table' => 'contact',
1631 'fields' => FS::contact->cgi_contact_fields,
1632 'params' => $contact_params,
1635 $dbh->rollback if $oldAutoCommit;
1641 unless ( $import || $skip_fuzzyfiles ) {
1642 $error = $self->queue_fuzzyfiles_update;
1644 $dbh->rollback if $oldAutoCommit;
1645 return "updating fuzzy search cache: $error";
1649 # tax district update in cust_location
1651 # cust_main exports!
1653 my $export_args = $options{'export_args'} || [];
1656 map qsearch( 'part_export', {exportnum=>$_} ),
1657 $conf->config('cust_main-exports'); #, $agentnum
1659 foreach my $part_export ( @part_export ) {
1660 my $error = $part_export->export_replace( $self, $old, @$export_args);
1662 $dbh->rollback if $oldAutoCommit;
1663 return "exporting to ". $part_export->exporttype.
1664 " (transaction rolled back): $error";
1668 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1673 =item queue_fuzzyfiles_update
1675 Used by insert & replace to update the fuzzy search cache
1679 use FS::cust_main::Search;
1680 sub queue_fuzzyfiles_update {
1683 local $SIG{HUP} = 'IGNORE';
1684 local $SIG{INT} = 'IGNORE';
1685 local $SIG{QUIT} = 'IGNORE';
1686 local $SIG{TERM} = 'IGNORE';
1687 local $SIG{TSTP} = 'IGNORE';
1688 local $SIG{PIPE} = 'IGNORE';
1690 my $oldAutoCommit = $FS::UID::AutoCommit;
1691 local $FS::UID::AutoCommit = 0;
1694 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1695 my $queue = new FS::queue {
1696 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1698 my @args = "cust_main.$field", $self->get($field);
1699 my $error = $queue->insert( @args );
1701 $dbh->rollback if $oldAutoCommit;
1702 return "queueing job (transaction rolled back): $error";
1707 push @locations, $self->bill_location if $self->bill_locationnum;
1708 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1709 foreach my $location (@locations) {
1710 my $queue = new FS::queue {
1711 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1713 my @args = 'cust_location.address1', $location->address1;
1714 my $error = $queue->insert( @args );
1716 $dbh->rollback if $oldAutoCommit;
1717 return "queueing job (transaction rolled back): $error";
1721 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1728 Checks all fields to make sure this is a valid customer record. If there is
1729 an error, returns the error, otherwise returns false. Called by the insert
1730 and replace methods.
1737 warn "$me check BEFORE: \n". $self->_dump
1741 $self->ut_numbern('custnum')
1742 || $self->ut_number('agentnum')
1743 || $self->ut_textn('agent_custid')
1744 || $self->ut_number('refnum')
1745 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1746 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1747 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1748 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1749 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1750 || $self->ut_textn('custbatch')
1751 || $self->ut_name('last')
1752 || $self->ut_name('first')
1753 || $self->ut_snumbern('signupdate')
1754 || $self->ut_snumbern('birthdate')
1755 || $self->ut_namen('spouse_last')
1756 || $self->ut_namen('spouse_first')
1757 || $self->ut_snumbern('spouse_birthdate')
1758 || $self->ut_snumbern('anniversary_date')
1759 || $self->ut_textn('company')
1760 || $self->ut_textn('ship_company')
1761 || $self->ut_anything('comments')
1762 || $self->ut_numbern('referral_custnum')
1763 || $self->ut_textn('stateid')
1764 || $self->ut_textn('stateid_state')
1765 || $self->ut_textn('invoice_terms')
1766 || $self->ut_floatn('cdr_termination_percentage')
1767 || $self->ut_floatn('credit_limit')
1768 || $self->ut_numbern('billday')
1769 || $self->ut_numbern('prorate_day')
1770 || $self->ut_flag('edit_subject')
1771 || $self->ut_flag('calling_list_exempt')
1772 || $self->ut_flag('invoice_noemail')
1773 || $self->ut_flag('message_noemail')
1774 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1775 || $self->ut_currencyn('currency')
1776 || $self->ut_alphan('po_number')
1777 || $self->ut_enum('complimentary', [ '', 'Y' ])
1778 || $self->ut_flag('invoice_ship_address')
1779 || $self->ut_flag('invoice_dest')
1782 foreach (qw(company ship_company)) {
1783 my $company = $self->get($_);
1784 $company =~ s/^\s+//;
1785 $company =~ s/\s+$//;
1786 $company =~ s/\s+/ /g;
1787 $self->set($_, $company);
1790 #barf. need message catalogs. i18n. etc.
1791 $error .= "Please select an advertising source."
1792 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1793 return $error if $error;
1795 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1796 or return "Unknown agent";
1798 if ( $self->currency ) {
1799 my $agent_currency = qsearchs( 'agent_currency', {
1800 'agentnum' => $agent->agentnum,
1801 'currency' => $self->currency,
1803 or return "Agent ". $agent->agent.
1804 " not permitted to offer ". $self->currency. " invoicing";
1807 return "Unknown refnum"
1808 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1810 return "Unknown referring custnum: ". $self->referral_custnum
1811 unless ! $self->referral_custnum
1812 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1814 if ( $self->ss eq '' ) {
1819 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1820 or return "Illegal social security number: ". $self->ss;
1821 $self->ss("$1-$2-$3");
1824 #turn off invoice_ship_address if ship & bill are the same
1825 if ($self->bill_locationnum eq $self->ship_locationnum) {
1826 $self->invoice_ship_address('');
1829 # cust_main_county verification now handled by cust_location check
1832 $self->ut_phonen('daytime', $self->country)
1833 || $self->ut_phonen('night', $self->country)
1834 || $self->ut_phonen('fax', $self->country)
1835 || $self->ut_phonen('mobile', $self->country)
1837 return $error if $error;
1839 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1841 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1844 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1846 : FS::Msgcat::_gettext('daytime');
1847 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1849 : FS::Msgcat::_gettext('night');
1851 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1853 : FS::Msgcat::_gettext('mobile');
1855 return "$daytime_label, $night_label or $mobile_label is required"
1859 return "Please select an invoicing locale"
1862 && $conf->exists('cust_main-require_locale');
1864 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1865 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1869 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1871 warn "$me check AFTER: \n". $self->_dump
1874 $self->SUPER::check;
1877 sub check_payinfo_cardtype {
1880 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
1882 my $payinfo = $self->payinfo;
1883 $payinfo =~ s/\D//g;
1885 return '' if $payinfo =~ /^99\d{14}$/; #token
1887 my %bop_card_types = map { $_=>1 } values %{ card_types() };
1888 my $cardtype = cardtype($payinfo);
1890 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
1898 Additional checks for replace only.
1903 my ($new,$old) = @_;
1904 #preserve old value if global config is set
1905 if ($old && $conf->exists('invoice-ship_address')) {
1906 $new->invoice_ship_address($old->invoice_ship_address);
1913 Returns a list of fields which have ship_ duplicates.
1918 qw( last first company
1920 address1 address2 city county state zip country
1922 daytime night fax mobile
1926 =item has_ship_address
1928 Returns true if this customer record has a separate shipping address.
1932 sub has_ship_address {
1934 $self->bill_locationnum != $self->ship_locationnum;
1939 Returns a list of key/value pairs, with the following keys: address1,
1940 adddress2, city, county, state, zip, country, district, and geocode. The
1941 shipping address is used if present.
1947 $self->ship_location->location_hash;
1952 Returns all locations (see L<FS::cust_location>) for this customer.
1959 'table' => 'cust_location',
1960 'hashref' => { 'custnum' => $self->custnum,
1961 'prospectnum' => '',
1963 'order_by' => 'ORDER BY country, LOWER(state), LOWER(city), LOWER(county), LOWER(address1), LOWER(address2)',
1969 Returns all contact associations (see L<FS::cust_contact>) for this customer.
1975 qsearch('cust_contact', { 'custnum' => $self->custnum } );
1978 =item cust_payby PAYBY
1980 Returns all payment methods (see L<FS::cust_payby>) for this customer.
1982 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
1983 Does not validate PAYBY.
1991 'table' => 'cust_payby',
1992 'hashref' => { 'custnum' => $self->custnum },
1993 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
1995 $search->{'extra_sql'} = ' AND payby IN ( ' . join(',', map { dbh->quote($_) } @payby) . ' ) '
2001 =item has_cust_payby_auto
2003 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
2007 sub has_cust_payby_auto {
2010 'table' => 'cust_payby',
2011 'hashref' => { 'custnum' => $self->custnum, },
2012 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2013 'order_by' => 'LIMIT 1',
2020 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2021 and L<FS::cust_pkg>) for this customer, except those on hold.
2023 Returns a list: an empty list on success or a list of errors.
2029 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2034 Unsuspends all suspended packages in the on-hold state (those without setup
2035 dates) for this customer.
2041 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2046 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2048 Returns a list: an empty list on success or a list of errors.
2054 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2057 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2059 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2060 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2061 of a list of pkgparts; the hashref has the following keys:
2065 =item pkgparts - listref of pkgparts
2067 =item (other options are passed to the suspend method)
2072 Returns a list: an empty list on success or a list of errors.
2076 sub suspend_if_pkgpart {
2078 my (@pkgparts, %opt);
2079 if (ref($_[0]) eq 'HASH'){
2080 @pkgparts = @{$_[0]{pkgparts}};
2085 grep { $_->suspend(%opt) }
2086 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2087 $self->unsuspended_pkgs;
2090 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2092 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2093 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2094 instead of a list of pkgparts; the hashref has the following keys:
2098 =item pkgparts - listref of pkgparts
2100 =item (other options are passed to the suspend method)
2104 Returns a list: an empty list on success or a list of errors.
2108 sub suspend_unless_pkgpart {
2110 my (@pkgparts, %opt);
2111 if (ref($_[0]) eq 'HASH'){
2112 @pkgparts = @{$_[0]{pkgparts}};
2117 grep { $_->suspend(%opt) }
2118 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2119 $self->unsuspended_pkgs;
2122 =item cancel [ OPTION => VALUE ... ]
2124 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2126 Available options are:
2130 =item quiet - can be set true to supress email cancellation notices.
2132 =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.
2134 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2136 =item nobill - can be set true to skip billing if it might otherwise be done.
2140 Always returns a list: an empty list on success or a list of errors.
2144 # nb that dates are not specified as valid options to this method
2147 my( $self, %opt ) = @_;
2149 warn "$me cancel called on customer ". $self->custnum. " with options ".
2150 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2153 return ( 'access denied' )
2154 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2156 if ( $opt{'ban'} ) {
2158 foreach my $cust_payby ( $self->cust_payby ) {
2160 #well, if they didn't get decrypted on search, then we don't have to
2161 # try again... queue a job for the server that does have decryption
2162 # capability if we're in a paranoid multi-server implementation?
2163 return ( "Can't (yet) ban encrypted credit cards" )
2164 if $cust_payby->is_encrypted($cust_payby->payinfo);
2166 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2167 my $error = $ban->insert;
2168 return ( $error ) if $error;
2174 my @pkgs = $self->ncancelled_pkgs;
2176 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2178 my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2179 warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2183 warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2184 scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2187 grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2190 sub _banned_pay_hashref {
2191 die 'cust_main->_banned_pay_hashref deprecated';
2203 'payby' => $payby2ban{$self->payby},
2204 'payinfo' => $self->payinfo,
2205 #don't ever *search* on reason! #'reason' =>
2211 Returns all notes (see L<FS::cust_main_note>) for this customer.
2216 my($self,$orderby_classnum) = (shift,shift);
2217 my $orderby = "sticky DESC, _date DESC";
2218 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2219 qsearch( 'cust_main_note',
2220 { 'custnum' => $self->custnum },
2222 "ORDER BY $orderby",
2228 Returns the agent (see L<FS::agent>) for this customer.
2232 Returns the agent name (see L<FS::agent>) for this customer.
2238 $self->agent->agent;
2243 Returns any tags associated with this customer, as FS::cust_tag objects,
2244 or an empty list if there are no tags.
2248 Returns any tags associated with this customer, as FS::part_tag objects,
2249 or an empty list if there are no tags.
2255 map $_->part_tag, $self->cust_tag;
2261 Returns the customer class, as an FS::cust_class object, or the empty string
2262 if there is no customer class.
2266 Returns the customer category name, or the empty string if there is no customer
2273 my $cust_class = $self->cust_class;
2275 ? $cust_class->categoryname
2281 Returns the customer class name, or the empty string if there is no customer
2288 my $cust_class = $self->cust_class;
2290 ? $cust_class->classname
2296 Returns the external tax status, as an FS::tax_status object, or the empty
2297 string if there is no tax status.
2303 if ( $self->taxstatusnum ) {
2304 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2312 Returns the tax status code if there is one.
2318 my $tax_status = $self->tax_status;
2320 ? $tax_status->taxstatus
2324 =item BILLING METHODS
2326 Documentation on billing methods has been moved to
2327 L<FS::cust_main::Billing>.
2329 =item REALTIME BILLING METHODS
2331 Documentation on realtime billing methods has been moved to
2332 L<FS::cust_main::Billing_Realtime>.
2336 Removes the I<paycvv> field from the database directly.
2338 If there is an error, returns the error, otherwise returns false.
2343 die 'cust_main->remove_cvv deprecated';
2345 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2346 or return dbh->errstr;
2347 $sth->execute($self->custnum)
2348 or return $sth->errstr;
2355 Returns the total owed for this customer on all invoices
2356 (see L<FS::cust_bill/owed>).
2362 $self->total_owed_date(2145859200); #12/31/2037
2365 =item total_owed_date TIME
2367 Returns the total owed for this customer on all invoices with date earlier than
2368 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2369 see L<Time::Local> and L<Date::Parse> for conversion functions.
2373 sub total_owed_date {
2377 my $custnum = $self->custnum;
2379 my $owed_sql = FS::cust_bill->owed_sql;
2382 SELECT SUM($owed_sql) FROM cust_bill
2383 WHERE custnum = $custnum
2387 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2391 =item total_owed_pkgnum PKGNUM
2393 Returns the total owed on all invoices for this customer's specific package
2394 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2398 sub total_owed_pkgnum {
2399 my( $self, $pkgnum ) = @_;
2400 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2403 =item total_owed_date_pkgnum TIME PKGNUM
2405 Returns the total owed for this customer's specific package when using
2406 experimental package balances on all invoices with date earlier than
2407 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2408 see L<Time::Local> and L<Date::Parse> for conversion functions.
2412 sub total_owed_date_pkgnum {
2413 my( $self, $time, $pkgnum ) = @_;
2416 foreach my $cust_bill (
2417 grep { $_->_date <= $time }
2418 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2420 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2422 sprintf( "%.2f", $total_bill );
2428 Returns the total amount of all payments.
2435 $total += $_->paid foreach $self->cust_pay;
2436 sprintf( "%.2f", $total );
2439 =item total_unapplied_credits
2441 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2442 customer. See L<FS::cust_credit/credited>.
2444 =item total_credited
2446 Old name for total_unapplied_credits. Don't use.
2450 sub total_credited {
2451 #carp "total_credited deprecated, use total_unapplied_credits";
2452 shift->total_unapplied_credits(@_);
2455 sub total_unapplied_credits {
2458 my $custnum = $self->custnum;
2460 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2463 SELECT SUM($unapplied_sql) FROM cust_credit
2464 WHERE custnum = $custnum
2467 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2471 =item total_unapplied_credits_pkgnum PKGNUM
2473 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2474 customer. See L<FS::cust_credit/credited>.
2478 sub total_unapplied_credits_pkgnum {
2479 my( $self, $pkgnum ) = @_;
2480 my $total_credit = 0;
2481 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2482 sprintf( "%.2f", $total_credit );
2486 =item total_unapplied_payments
2488 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2489 See L<FS::cust_pay/unapplied>.
2493 sub total_unapplied_payments {
2496 my $custnum = $self->custnum;
2498 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2501 SELECT SUM($unapplied_sql) FROM cust_pay
2502 WHERE custnum = $custnum
2505 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2509 =item total_unapplied_payments_pkgnum PKGNUM
2511 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2512 specific package when using experimental package balances. See
2513 L<FS::cust_pay/unapplied>.
2517 sub total_unapplied_payments_pkgnum {
2518 my( $self, $pkgnum ) = @_;
2519 my $total_unapplied = 0;
2520 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2521 sprintf( "%.2f", $total_unapplied );
2525 =item total_unapplied_refunds
2527 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2528 customer. See L<FS::cust_refund/unapplied>.
2532 sub total_unapplied_refunds {
2534 my $custnum = $self->custnum;
2536 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2539 SELECT SUM($unapplied_sql) FROM cust_refund
2540 WHERE custnum = $custnum
2543 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2549 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2550 total_unapplied_credits minus total_unapplied_payments).
2556 $self->balance_date_range;
2559 =item balance_date TIME
2561 Returns the balance for this customer, only considering invoices with date
2562 earlier than TIME (total_owed_date minus total_credited minus
2563 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2564 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2571 $self->balance_date_range(shift);
2574 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2576 Returns the balance for this customer, optionally considering invoices with
2577 date earlier than START_TIME, and not later than END_TIME
2578 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2580 Times are specified as SQL fragments or numeric
2581 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2582 L<Date::Parse> for conversion functions. The empty string can be passed
2583 to disable that time constraint completely.
2585 Accepts the same options as L<balance_date_sql>:
2589 =item unapplied_date
2591 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)
2595 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2596 time will be ignored. Note that START_TIME and END_TIME only limit the date
2597 range for invoices and I<unapplied> payments, credits, and refunds.
2603 sub balance_date_range {
2605 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2606 ') FROM cust_main WHERE custnum='. $self->custnum;
2607 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2610 =item balance_pkgnum PKGNUM
2612 Returns the balance for this customer's specific package when using
2613 experimental package balances (total_owed plus total_unrefunded, minus
2614 total_unapplied_credits minus total_unapplied_payments)
2618 sub balance_pkgnum {
2619 my( $self, $pkgnum ) = @_;
2622 $self->total_owed_pkgnum($pkgnum)
2623 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2624 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2625 - $self->total_unapplied_credits_pkgnum($pkgnum)
2626 - $self->total_unapplied_payments_pkgnum($pkgnum)
2632 Returns a hash of useful information for making a payment.
2642 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2643 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2644 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2648 For credit card transactions:
2660 For electronic check transactions:
2670 #XXX i need to be updated for 4.x+
2676 $return{balance} = $self->balance;
2678 $return{payname} = $self->payname
2679 || ( $self->first. ' '. $self->get('last') );
2681 $return{$_} = $self->bill_location->$_
2682 for qw(address1 address2 city state zip);
2684 $return{payby} = $self->payby;
2685 $return{stateid_state} = $self->stateid_state;
2687 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2688 $return{card_type} = cardtype($self->payinfo);
2689 $return{payinfo} = $self->paymask;
2691 @return{'month', 'year'} = $self->paydate_monthyear;
2695 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2696 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2697 $return{payinfo1} = $payinfo1;
2698 $return{payinfo2} = $payinfo2;
2699 $return{paytype} = $self->paytype;
2700 $return{paystate} = $self->paystate;
2704 #doubleclick protection
2706 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2714 Returns the next payment expiration date for this customer. If they have no
2715 payment methods that will expire, returns 0.
2721 # filter out the ones that individually return 0, but then return 0 if
2722 # there are no results
2723 my @epochs = grep { $_ > 0 } map { $_->paydate_epoch } $self->cust_payby;
2724 min( @epochs ) || 0;
2727 =item paydate_epoch_sql
2729 Returns an SQL expression to get the next payment expiration date for a
2730 customer. Returns 2143260000 (2037-12-01) if there are no payment expiration
2731 dates, so that it's safe to test for "will it expire before date X" for any
2736 sub paydate_epoch_sql {
2738 my $paydate = FS::cust_payby->paydate_epoch_sql;
2739 "(SELECT COALESCE(MIN($paydate), 2143260000) FROM cust_payby WHERE cust_payby.custnum = cust_main.custnum)";
2743 my( $self, $taxname ) = @_;
2745 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2746 'taxname' => $taxname,
2751 =item cust_main_exemption
2753 =item invoicing_list
2755 Returns a list of email addresses (with svcnum entries expanded), and the word
2756 'POST' if the customer receives postal invoices.
2760 sub invoicing_list {
2761 my( $self, $arrayref ) = @_;
2764 warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
2767 my @emails = $self->invoicing_list_emailonly;
2768 push @emails, 'POST' if $self->get('postal_invoice');
2773 =item check_invoicing_list ARRAYREF
2775 Checks these arguements as valid input for the invoicing_list method. If there
2776 is an error, returns the error, otherwise returns false.
2780 sub check_invoicing_list {
2781 my( $self, $arrayref ) = @_;
2783 foreach my $address ( @$arrayref ) {
2785 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2786 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2789 my $cust_main_invoice = new FS::cust_main_invoice ( {
2790 'custnum' => $self->custnum,
2793 my $error = $self->custnum
2794 ? $cust_main_invoice->check
2795 : $cust_main_invoice->checkdest
2797 return $error if $error;
2801 return "Email address required"
2802 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2803 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2810 Returns the email addresses of all accounts provisioned for this customer.
2817 foreach my $cust_pkg ( $self->all_pkgs ) {
2818 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2820 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2821 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2823 $list{$_}=1 foreach map { $_->email } @svc_acct;
2828 =item invoicing_list_addpost
2830 Adds postal invoicing to this customer. If this customer is already configured
2831 to receive postal invoices, does nothing.
2835 sub invoicing_list_addpost {
2837 if ( $self->get('postal_invoice') eq '' ) {
2838 $self->set('postal_invoice', 'Y');
2839 my $error = $self->replace;
2840 warn $error if $error; # should fail harder, but this is traditional
2844 =item invoicing_list_emailonly
2846 Returns the list of email invoice recipients (invoicing_list without non-email
2847 destinations such as POST and FAX).
2851 sub invoicing_list_emailonly {
2853 warn "$me invoicing_list_emailonly called"
2855 return () if !$self->custnum; # not yet inserted
2856 return map { $_->emailaddress }
2858 table => 'cust_contact',
2859 select => 'emailaddress',
2860 addl_from => ' JOIN contact USING (contactnum) '.
2861 ' JOIN contact_email USING (contactnum)',
2862 hashref => { 'custnum' => $self->custnum, },
2863 extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
2867 =item invoicing_list_emailonly_scalar
2869 Returns the list of email invoice recipients (invoicing_list without non-email
2870 destinations such as POST and FAX) as a comma-separated scalar.
2874 sub invoicing_list_emailonly_scalar {
2876 warn "$me invoicing_list_emailonly_scalar called"
2878 join(', ', $self->invoicing_list_emailonly);
2881 =item referral_custnum_cust_main
2883 Returns the customer who referred this customer (or the empty string, if
2884 this customer was not referred).
2886 Note the difference with referral_cust_main method: This method,
2887 referral_custnum_cust_main returns the single customer (if any) who referred
2888 this customer, while referral_cust_main returns an array of customers referred
2893 sub referral_custnum_cust_main {
2895 return '' unless $self->referral_custnum;
2896 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2899 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
2901 Returns an array of customers referred by this customer (referral_custnum set
2902 to this custnum). If DEPTH is given, recurses up to the given depth, returning
2903 customers referred by customers referred by this customer and so on, inclusive.
2904 The default behavior is DEPTH 1 (no recursion).
2906 Note the difference with referral_custnum_cust_main method: This method,
2907 referral_cust_main, returns an array of customers referred BY this customer,
2908 while referral_custnum_cust_main returns the single customer (if any) who
2909 referred this customer.
2913 sub referral_cust_main {
2915 my $depth = @_ ? shift : 1;
2916 my $exclude = @_ ? shift : {};
2919 map { $exclude->{$_->custnum}++; $_; }
2920 grep { ! $exclude->{ $_->custnum } }
2921 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
2925 map { $_->referral_cust_main($depth-1, $exclude) }
2932 =item referral_cust_main_ncancelled
2934 Same as referral_cust_main, except only returns customers with uncancelled
2939 sub referral_cust_main_ncancelled {
2941 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
2944 =item referral_cust_pkg [ DEPTH ]
2946 Like referral_cust_main, except returns a flat list of all unsuspended (and
2947 uncancelled) packages for each customer. The number of items in this list may
2948 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
2952 sub referral_cust_pkg {
2954 my $depth = @_ ? shift : 1;
2956 map { $_->unsuspended_pkgs }
2957 grep { $_->unsuspended_pkgs }
2958 $self->referral_cust_main($depth);
2961 =item referring_cust_main
2963 Returns the single cust_main record for the customer who referred this customer
2964 (referral_custnum), or false.
2968 sub referring_cust_main {
2970 return '' unless $self->referral_custnum;
2971 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2974 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
2976 Applies a credit to this customer. If there is an error, returns the error,
2977 otherwise returns false.
2979 REASON can be a text string, an FS::reason object, or a scalar reference to
2980 a reasonnum. If a text string, it will be automatically inserted as a new
2981 reason, and a 'reason_type' option must be passed to indicate the
2982 FS::reason_type for the new reason.
2984 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
2985 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
2986 I<commission_pkgnum>.
2988 Any other options are passed to FS::cust_credit::insert.
2993 my( $self, $amount, $reason, %options ) = @_;
2995 my $cust_credit = new FS::cust_credit {
2996 'custnum' => $self->custnum,
2997 'amount' => $amount,
3000 if ( ref($reason) ) {
3002 if ( ref($reason) eq 'SCALAR' ) {
3003 $cust_credit->reasonnum( $$reason );
3005 $cust_credit->reasonnum( $reason->reasonnum );
3009 $cust_credit->set('reason', $reason)
3012 $cust_credit->$_( delete $options{$_} )
3013 foreach grep exists($options{$_}),
3014 qw( addlinfo eventnum ),
3015 map "commission_$_", qw( agentnum salesnum pkgnum );
3017 $cust_credit->insert(%options);
3021 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3023 Creates a one-time charge for this customer. If there is an error, returns
3024 the error, otherwise returns false.
3026 New-style, with a hashref of options:
3028 my $error = $cust_main->charge(
3032 'start_date' => str2time('7/4/2009'),
3033 'pkg' => 'Description',
3034 'comment' => 'Comment',
3035 'additional' => [], #extra invoice detail
3036 'classnum' => 1, #pkg_class
3038 'setuptax' => '', # or 'Y' for tax exempt
3040 'locationnum'=> 1234, # optional
3043 'taxclass' => 'Tax class',
3046 'taxproduct' => 2, #part_pkg_taxproduct
3047 'override' => {}, #XXX describe
3049 #will be filled in with the new object
3050 'cust_pkg_ref' => \$cust_pkg,
3052 #generate an invoice immediately
3054 'invoice_terms' => '', #with these terms
3060 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3064 #super false laziness w/quotation::charge
3067 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3068 my ( $pkg, $comment, $additional );
3069 my ( $setuptax, $taxclass ); #internal taxes
3070 my ( $taxproduct, $override ); #vendor (CCH) taxes
3072 my $separate_bill = '';
3073 my $cust_pkg_ref = '';
3074 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3076 if ( ref( $_[0] ) ) {
3077 $amount = $_[0]->{amount};
3078 $setup_cost = $_[0]->{setup_cost};
3079 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3080 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3081 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3082 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3083 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3084 : '$'. sprintf("%.2f",$amount);
3085 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3086 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3087 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3088 $additional = $_[0]->{additional} || [];
3089 $taxproduct = $_[0]->{taxproductnum};
3090 $override = { '' => $_[0]->{tax_override} };
3091 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3092 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3093 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3094 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3095 $separate_bill = $_[0]->{separate_bill} || '';
3101 $pkg = @_ ? shift : 'One-time charge';
3102 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3104 $taxclass = @_ ? shift : '';
3108 local $SIG{HUP} = 'IGNORE';
3109 local $SIG{INT} = 'IGNORE';
3110 local $SIG{QUIT} = 'IGNORE';
3111 local $SIG{TERM} = 'IGNORE';
3112 local $SIG{TSTP} = 'IGNORE';
3113 local $SIG{PIPE} = 'IGNORE';
3115 my $oldAutoCommit = $FS::UID::AutoCommit;
3116 local $FS::UID::AutoCommit = 0;
3119 my $part_pkg = new FS::part_pkg ( {
3121 'comment' => $comment,
3125 'classnum' => ( $classnum ? $classnum : '' ),
3126 'setuptax' => $setuptax,
3127 'taxclass' => $taxclass,
3128 'taxproductnum' => $taxproduct,
3129 'setup_cost' => $setup_cost,
3132 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3133 ( 0 .. @$additional - 1 )
3135 'additional_count' => scalar(@$additional),
3136 'setup_fee' => $amount,
3139 my $error = $part_pkg->insert( options => \%options,
3140 tax_overrides => $override,
3143 $dbh->rollback if $oldAutoCommit;
3147 my $pkgpart = $part_pkg->pkgpart;
3148 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3149 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3150 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3151 $error = $type_pkgs->insert;
3153 $dbh->rollback if $oldAutoCommit;
3158 my $cust_pkg = new FS::cust_pkg ( {
3159 'custnum' => $self->custnum,
3160 'pkgpart' => $pkgpart,
3161 'quantity' => $quantity,
3162 'start_date' => $start_date,
3163 'no_auto' => $no_auto,
3164 'separate_bill' => $separate_bill,
3165 'locationnum'=> $locationnum,
3168 $error = $cust_pkg->insert;
3170 $dbh->rollback if $oldAutoCommit;
3172 } elsif ( $cust_pkg_ref ) {
3173 ${$cust_pkg_ref} = $cust_pkg;
3177 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3178 'pkg_list' => [ $cust_pkg ],
3181 $dbh->rollback if $oldAutoCommit;
3186 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3191 #=item charge_postal_fee
3193 #Applies a one time charge this customer. If there is an error,
3194 #returns the error, returns the cust_pkg charge object or false
3195 #if there was no charge.
3199 # This should be a customer event. For that to work requires that bill
3200 # also be a customer event.
3202 sub charge_postal_fee {
3205 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3206 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3208 my $cust_pkg = new FS::cust_pkg ( {
3209 'custnum' => $self->custnum,
3210 'pkgpart' => $pkgpart,
3214 my $error = $cust_pkg->insert;
3215 $error ? $error : $cust_pkg;
3218 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3220 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3222 Optionally, a list or hashref of additional arguments to the qsearch call can
3229 my $opt = ref($_[0]) ? shift : { @_ };
3231 #return $self->num_cust_bill unless wantarray || keys %$opt;
3233 $opt->{'table'} = 'cust_bill';
3234 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3235 $opt->{'hashref'}{'custnum'} = $self->custnum;
3236 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3238 map { $_ } #behavior of sort undefined in scalar context
3239 sort { $a->_date <=> $b->_date }
3243 =item open_cust_bill
3245 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3250 sub open_cust_bill {
3254 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3260 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3262 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3266 sub legacy_cust_bill {
3269 #return $self->num_legacy_cust_bill unless wantarray;
3271 map { $_ } #behavior of sort undefined in scalar context
3272 sort { $a->_date <=> $b->_date }
3273 qsearch({ 'table' => 'legacy_cust_bill',
3274 'hashref' => { 'custnum' => $self->custnum, },
3275 'order_by' => 'ORDER BY _date ASC',
3279 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3281 Returns all the statements (see L<FS::cust_statement>) for this customer.
3283 Optionally, a list or hashref of additional arguments to the qsearch call can
3288 =item cust_bill_void
3290 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3294 sub cust_bill_void {
3297 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3298 sort { $a->_date <=> $b->_date }
3299 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3302 sub cust_statement {
3304 my $opt = ref($_[0]) ? shift : { @_ };
3306 #return $self->num_cust_statement unless wantarray || keys %$opt;
3308 $opt->{'table'} = 'cust_statement';
3309 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3310 $opt->{'hashref'}{'custnum'} = $self->custnum;
3311 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3313 map { $_ } #behavior of sort undefined in scalar context
3314 sort { $a->_date <=> $b->_date }
3318 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3320 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3322 Optionally, a list or hashref of additional arguments to the qsearch call can
3323 be passed following the SVCDB.
3330 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3331 warn "$me svc_x requires a svcdb";
3334 my $opt = ref($_[0]) ? shift : { @_ };
3336 $opt->{'table'} = $svcdb;
3337 $opt->{'addl_from'} =
3338 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3339 ($opt->{'addl_from'} || '');
3341 my $custnum = $self->custnum;
3342 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3343 my $where = "cust_pkg.custnum = $custnum";
3345 my $extra_sql = $opt->{'extra_sql'} || '';
3346 if ( keys %{ $opt->{'hashref'} } ) {
3347 $extra_sql = " AND $where $extra_sql";
3350 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3351 $extra_sql = "WHERE $where AND $1";
3354 $extra_sql = "WHERE $where $extra_sql";
3357 $opt->{'extra_sql'} = $extra_sql;
3362 # required for use as an eventtable;
3365 $self->svc_x('svc_acct', @_);
3370 Returns all the credits (see L<FS::cust_credit>) for this customer.
3377 #return $self->num_cust_credit unless wantarray;
3379 map { $_ } #behavior of sort undefined in scalar context
3380 sort { $a->_date <=> $b->_date }
3381 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3384 =item cust_credit_pkgnum
3386 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3387 package when using experimental package balances.
3391 sub cust_credit_pkgnum {
3392 my( $self, $pkgnum ) = @_;
3393 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3394 sort { $a->_date <=> $b->_date }
3395 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3396 'pkgnum' => $pkgnum,
3401 =item cust_credit_void
3403 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3407 sub cust_credit_void {
3410 sort { $a->_date <=> $b->_date }
3411 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3416 Returns all the payments (see L<FS::cust_pay>) for this customer.
3422 my $opt = ref($_[0]) ? shift : { @_ };
3424 return $self->num_cust_pay unless wantarray || keys %$opt;
3426 $opt->{'table'} = 'cust_pay';
3427 $opt->{'hashref'}{'custnum'} = $self->custnum;
3429 map { $_ } #behavior of sort undefined in scalar context
3430 sort { $a->_date <=> $b->_date }
3437 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3438 called automatically when the cust_pay method is used in a scalar context.
3444 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3445 my $sth = dbh->prepare($sql) or die dbh->errstr;
3446 $sth->execute($self->custnum) or die $sth->errstr;
3447 $sth->fetchrow_arrayref->[0];
3450 =item unapplied_cust_pay
3452 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3456 sub unapplied_cust_pay {
3460 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3466 =item cust_pay_pkgnum
3468 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3469 package when using experimental package balances.
3473 sub cust_pay_pkgnum {
3474 my( $self, $pkgnum ) = @_;
3475 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3476 sort { $a->_date <=> $b->_date }
3477 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3478 'pkgnum' => $pkgnum,
3485 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3491 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3492 sort { $a->_date <=> $b->_date }
3493 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3496 =item cust_pay_pending
3498 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3499 (without status "done").
3503 sub cust_pay_pending {
3505 return $self->num_cust_pay_pending unless wantarray;
3506 sort { $a->_date <=> $b->_date }
3507 qsearch( 'cust_pay_pending', {
3508 'custnum' => $self->custnum,
3509 'status' => { op=>'!=', value=>'done' },
3514 =item cust_pay_pending_attempt
3516 Returns all payment attempts / declined payments for this customer, as pending
3517 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3518 a corresponding payment (see L<FS::cust_pay>).
3522 sub cust_pay_pending_attempt {
3524 return $self->num_cust_pay_pending_attempt unless wantarray;
3525 sort { $a->_date <=> $b->_date }
3526 qsearch( 'cust_pay_pending', {
3527 'custnum' => $self->custnum,
3534 =item num_cust_pay_pending
3536 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3537 customer (without status "done"). Also called automatically when the
3538 cust_pay_pending method is used in a scalar context.
3542 sub num_cust_pay_pending {
3545 " SELECT COUNT(*) FROM cust_pay_pending ".
3546 " WHERE custnum = ? AND status != 'done' ",
3551 =item num_cust_pay_pending_attempt
3553 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3554 customer, with status "done" but without a corresp. Also called automatically when the
3555 cust_pay_pending method is used in a scalar context.
3559 sub num_cust_pay_pending_attempt {
3562 " SELECT COUNT(*) FROM cust_pay_pending ".
3563 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3570 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3576 map { $_ } #return $self->num_cust_refund unless wantarray;
3577 sort { $a->_date <=> $b->_date }
3578 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3581 =item display_custnum
3583 Returns the displayed customer number for this customer: agent_custid if
3584 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3588 sub display_custnum {
3591 return $self->agent_custid
3592 if $default_agent_custid && $self->agent_custid;
3594 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3598 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
3599 } elsif ( $custnum_display_length ) {
3600 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
3602 return $self->custnum;
3608 Returns a name string for this customer, either "Company (Last, First)" or
3615 my $name = $self->contact;
3616 $name = $self->company. " ($name)" if $self->company;
3620 =item service_contact
3622 Returns the L<FS::contact> object for this customer that has the 'Service'
3623 contact class, or undef if there is no such contact. Deprecated; don't use
3628 sub service_contact {
3630 if ( !exists($self->{service_contact}) ) {
3631 my $classnum = $self->scalar_sql(
3632 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3633 ) || 0; #if it's zero, qsearchs will return nothing
3634 my $cust_contact = qsearchs('cust_contact', {
3635 'classnum' => $classnum,
3636 'custnum' => $self->custnum,
3638 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3640 $self->{service_contact};
3645 Returns a name string for this (service/shipping) contact, either
3646 "Company (Last, First)" or "Last, First".
3653 my $name = $self->ship_contact;
3654 $name = $self->company. " ($name)" if $self->company;
3660 Returns a name string for this customer, either "Company" or "First Last".
3666 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3669 =item ship_name_short
3671 Returns a name string for this (service/shipping) contact, either "Company"
3676 sub ship_name_short {
3678 $self->service_contact
3679 ? $self->ship_contact_firstlast
3685 Returns this customer's full (billing) contact name only, "Last, First"
3691 $self->get('last'). ', '. $self->first;
3696 Returns this customer's full (shipping) contact name only, "Last, First"
3702 my $contact = $self->service_contact || $self;
3703 $contact->get('last') . ', ' . $contact->get('first');
3706 =item contact_firstlast
3708 Returns this customers full (billing) contact name only, "First Last".
3712 sub contact_firstlast {
3714 $self->first. ' '. $self->get('last');
3717 =item ship_contact_firstlast
3719 Returns this customer's full (shipping) contact name only, "First Last".
3723 sub ship_contact_firstlast {
3725 my $contact = $self->service_contact || $self;
3726 $contact->get('first') . ' '. $contact->get('last');
3729 sub bill_country_full {
3731 $self->bill_location->country_full;
3734 sub ship_country_full {
3736 $self->ship_location->country_full;
3739 =item county_state_county [ PREFIX ]
3741 Returns a string consisting of just the county, state and country.
3745 sub county_state_country {
3748 if ( @_ && $_[0] && $self->has_ship_address ) {
3749 $locationnum = $self->ship_locationnum;
3751 $locationnum = $self->bill_locationnum;
3753 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3754 $cust_location->county_state_country;
3757 =item geocode DATA_VENDOR
3759 Returns a value for the customer location as encoded by DATA_VENDOR.
3760 Currently this only makes sense for "CCH" as DATA_VENDOR.
3768 Returns a status string for this customer, currently:
3774 No packages have ever been ordered. Displayed as "No packages".
3778 Recurring packages all are new (not yet billed).
3782 One or more recurring packages is active.
3786 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3790 All non-cancelled recurring packages are suspended.
3794 All recurring packages are cancelled.
3798 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3799 cust_main-status_module configuration option.
3803 sub status { shift->cust_status(@_); }
3807 for my $status ( FS::cust_main->statuses() ) {
3808 my $method = $status.'_sql';
3809 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3810 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3811 $sth->execute( ($self->custnum) x $numnum )
3812 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3813 return $status if $sth->fetchrow_arrayref->[0];
3817 =item is_status_delay_cancel
3819 Returns true if customer status is 'suspended'
3820 and all suspended cust_pkg return true for
3821 cust_pkg->is_status_delay_cancel.
3823 This is not a real status, this only meant for hacking display
3824 values, because otherwise treating the customer as suspended is
3825 really the whole point of the delay_cancel option.
3829 sub is_status_delay_cancel {
3831 return 0 unless $self->status eq 'suspended';
3832 foreach my $cust_pkg ($self->ncancelled_pkgs) {
3833 return 0 unless $cust_pkg->is_status_delay_cancel;
3838 =item ucfirst_cust_status
3840 =item ucfirst_status
3842 Deprecated, use the cust_status_label method instead.
3844 Returns the status with the first character capitalized.
3848 sub ucfirst_status {
3849 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3850 local($ucfirst_nowarn) = 1;
3851 shift->ucfirst_cust_status(@_);
3854 sub ucfirst_cust_status {
3855 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
3857 ucfirst($self->cust_status);
3860 =item cust_status_label
3864 Returns the display label for this status.
3868 sub status_label { shift->cust_status_label(@_); }
3870 sub cust_status_label {
3872 __PACKAGE__->statuslabels->{$self->cust_status};
3877 Returns a hex triplet color string for this customer's status.
3881 sub statuscolor { shift->cust_statuscolor(@_); }
3883 sub cust_statuscolor {
3885 __PACKAGE__->statuscolors->{$self->cust_status};
3888 =item tickets [ STATUS ]
3890 Returns an array of hashes representing the customer's RT tickets.
3892 An optional status (or arrayref or hashref of statuses) may be specified.
3898 my $status = ( @_ && $_[0] ) ? shift : '';
3900 my $num = $conf->config('cust_main-max_tickets') || 10;
3903 if ( $conf->config('ticket_system') ) {
3904 unless ( $conf->config('ticket_system-custom_priority_field') ) {
3906 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
3915 foreach my $priority (
3916 $conf->config('ticket_system-custom_priority_field-values'), ''
3918 last if scalar(@tickets) >= $num;
3920 @{ FS::TicketSystem->customer_tickets( $self->custnum,
3921 $num - scalar(@tickets),
3932 =item appointments [ STATUS ]
3934 Returns an array of hashes representing the customer's RT tickets which
3941 my $status = ( @_ && $_[0] ) ? shift : '';
3943 return () unless $conf->config('ticket_system');
3945 my $queueid = $conf->config('ticket_system-appointment-queueid');
3947 @{ FS::TicketSystem->customer_tickets( $self->custnum,
3956 # Return services representing svc_accts in customer support packages
3957 sub support_services {
3959 my %packages = map { $_ => 1 } $conf->config('support_packages');
3961 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
3962 grep { $_->part_svc->svcdb eq 'svc_acct' }
3963 map { $_->cust_svc }
3964 grep { exists $packages{ $_->pkgpart } }
3965 $self->ncancelled_pkgs;
3969 # Return a list of latitude/longitude for one of the services (if any)
3970 sub service_coordinates {
3974 grep { $_->latitude && $_->longitude }
3976 map { $_->cust_svc }
3977 $self->ncancelled_pkgs;
3979 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
3984 Returns a masked version of the named field
3989 my ($self,$field) = @_;
3993 'x'x(length($self->getfield($field))-4).
3994 substr($self->getfield($field), (length($self->getfield($field))-4));
3998 =item payment_history
4000 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4001 cust_credit and cust_refund objects. Each hashref has the following fields:
4003 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4005 I<date> - value of _date field, unix timestamp
4007 I<date_pretty> - user-friendly date
4009 I<description> - user-friendly description of item
4011 I<amount> - impact of item on user's balance
4012 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4013 Not to be confused with the native 'amount' field in cust_credit, see below.
4015 I<amount_pretty> - includes money char
4017 I<balance> - customer balance, chronologically as of this item
4019 I<balance_pretty> - includes money char
4021 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4023 I<paid> - amount paid for cust_pay records, undef for other types
4025 I<credit> - amount credited for cust_credit records, undef for other types.
4026 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4028 I<refund> - amount refunded for cust_refund records, undef for other types
4030 The four table-specific keys always have positive values, whether they reflect charges or payments.
4032 The following options may be passed to this method:
4034 I<line_items> - if true, returns charges ('Line item') rather than invoices
4036 I<start_date> - unix timestamp, only include records on or after.
4037 If specified, an item of type 'Previous' will also be included.
4038 It does not have table-specific fields.
4040 I<end_date> - unix timestamp, only include records before
4042 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4044 I<conf> - optional already-loaded FS::Conf object.
4048 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4049 # and also for sending customer statements, which should both be kept customer-friendly.
4050 # If you add anything that shouldn't be passed on through the API or exposed
4051 # to customers, add a new option to include it, don't include it by default
4052 sub payment_history {
4054 my $opt = ref($_[0]) ? $_[0] : { @_ };
4056 my $conf = $$opt{'conf'} || new FS::Conf;
4057 my $money_char = $conf->config("money_char") || '$',
4059 #first load entire history,
4060 #need previous to calculate previous balance
4061 #loading after end_date shouldn't hurt too much?
4063 if ( $$opt{'line_items'} ) {
4065 foreach my $cust_bill ( $self->cust_bill ) {
4068 'type' => 'Line item',
4069 'description' => $_->desc( $self->locale ).
4070 ( $_->sdate && $_->edate
4071 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4072 ' To '. time2str('%d-%b-%Y', $_->edate)
4075 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4076 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4077 'date' => $cust_bill->_date,
4078 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4080 foreach $cust_bill->cust_bill_pkg;
4087 'type' => 'Invoice',
4088 'description' => 'Invoice #'. $_->display_invnum,
4089 'amount' => sprintf('%.2f', $_->charged ),
4090 'charged' => sprintf('%.2f', $_->charged ),
4091 'date' => $_->_date,
4092 'date_pretty' => $self->time2str_local('short', $_->_date ),
4094 foreach $self->cust_bill;
4099 'type' => 'Payment',
4100 'description' => 'Payment', #XXX type
4101 'amount' => sprintf('%.2f', 0 - $_->paid ),
4102 'paid' => sprintf('%.2f', $_->paid ),
4103 'date' => $_->_date,
4104 'date_pretty' => $self->time2str_local('short', $_->_date ),
4106 foreach $self->cust_pay;
4110 'description' => 'Credit', #more info?
4111 'amount' => sprintf('%.2f', 0 -$_->amount ),
4112 'credit' => sprintf('%.2f', $_->amount ),
4113 'date' => $_->_date,
4114 'date_pretty' => $self->time2str_local('short', $_->_date ),
4116 foreach $self->cust_credit;
4120 'description' => 'Refund', #more info? type, like payment?
4121 'amount' => $_->refund,
4122 'refund' => $_->refund,
4123 'date' => $_->_date,
4124 'date_pretty' => $self->time2str_local('short', $_->_date ),
4126 foreach $self->cust_refund;
4128 #put it all in chronological order
4129 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4131 #calculate balance, filter items outside date range
4135 foreach my $item (@history) {
4136 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4137 $balance += $$item{'amount'};
4138 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4139 $previous += $$item{'amount'};
4142 $$item{'balance'} = sprintf("%.2f",$balance);
4143 foreach my $key ( qw(amount balance) ) {
4144 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4149 # start with previous balance, if there was one
4152 'type' => 'Previous',
4153 'description' => 'Previous balance',
4154 'amount' => sprintf("%.2f",$previous),
4155 'balance' => sprintf("%.2f",$previous),
4156 'date' => $$opt{'start_date'},
4157 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4159 #false laziness with above
4160 foreach my $key ( qw(amount balance) ) {
4161 $$item{$key.'_pretty'} = $$item{$key};
4162 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4164 unshift(@out,$item);
4167 @out = reverse @history if $$opt{'reverse_sort'};
4172 =item save_cust_payby
4174 Saves a new cust_payby for this customer, replacing an existing entry only
4175 in select circumstances. Does not validate input.
4177 If auto is specified, marks this as the customer's primary method, or the
4178 specified weight. Existing payment methods have their weight incremented as
4181 If bill_location is specified with auto, also sets location in cust_main.
4183 Will not insert complete duplicates of existing records, or records in which the
4184 only difference from an existing record is to turn off automatic payment (will
4185 return without error.) Will replace existing records in which the only difference
4186 is to add a value to a previously empty preserved field and/or turn on automatic payment.
4187 Fields marked as preserved are optional, and existing values will not be overwritten with
4188 blanks when replacing.
4190 Accepts the following named parameters:
4200 save as an automatic payment type (CARD/CHEK if true, DCRD/DCHK if false)
4204 optional, set higher than 1 for secondary, etc.
4212 optional, but should be specified for anything that might be tokenized, will be preserved when replacing
4220 optional, will be preserved when replacing
4228 CARD only, required, FS::cust_location object
4230 =item paystart_month
4232 CARD only, optional, will be preserved when replacing
4236 CARD only, optional, will be preserved when replacing
4240 CARD only, optional, will be preserved when replacing
4244 CARD only, only used if conf cvv-save is set appropriately
4258 #The code for this option is in place, but it's not currently used
4262 # existing cust_payby object to be replaced (must match custnum)
4264 # stateid/stateid_state/ss are not currently supported in cust_payby,
4265 # might not even work properly in 4.x, but will need to work here if ever added
4267 sub save_cust_payby {
4271 my $old = $opt{'replace'};
4272 my $new = new FS::cust_payby { $old ? $old->hash : () };
4273 return "Customer number does not match" if $new->custnum and $new->custnum != $self->custnum;
4274 $new->set( 'custnum' => $self->custnum );
4276 my $payby = $opt{'payment_payby'};
4277 return "Bad payby" unless grep(/^$payby$/,('CARD','CHEK'));
4279 # don't allow turning off auto when replacing
4280 $opt{'auto'} ||= 1 if $old and $old->payby !~ /^D/;
4282 my @check_existing; # payby relevant to this payment_payby
4284 # set payby based on auto
4285 if ( $payby eq 'CARD' ) {
4286 $new->set( 'payby' => ( $opt{'auto'} ? 'CARD' : 'DCRD' ) );
4287 @check_existing = qw( CARD DCRD );
4288 } elsif ( $payby eq 'CHEK' ) {
4289 $new->set( 'payby' => ( $opt{'auto'} ? 'CHEK' : 'DCHK' ) );
4290 @check_existing = qw( CHEK DCHK );
4293 $new->set( 'weight' => $opt{'auto'} ? $opt{'weight'} : '' );
4296 $new->payinfo($opt{'payinfo'}); # sets default paymask, but not if it's already tokenized
4297 $new->paymask($opt{'paymask'}) if $opt{'paymask'}; # in case it's been tokenized, override with loaded paymask
4298 $new->set( 'payname' => $opt{'payname'} );
4299 $new->set( 'payip' => $opt{'payip'} ); # will be preserved below
4301 my $conf = new FS::Conf;
4303 # compare to FS::cust_main::realtime_bop - check both to make sure working correctly
4304 if ( $payby eq 'CARD' &&
4305 grep { $_ eq cardtype($opt{'payinfo'}) } $conf->config('cvv-save') ) {
4306 $new->set( 'paycvv' => $opt{'paycvv'} );
4308 $new->set( 'paycvv' => '');
4311 local $SIG{HUP} = 'IGNORE';
4312 local $SIG{INT} = 'IGNORE';
4313 local $SIG{QUIT} = 'IGNORE';
4314 local $SIG{TERM} = 'IGNORE';
4315 local $SIG{TSTP} = 'IGNORE';
4316 local $SIG{PIPE} = 'IGNORE';
4318 my $oldAutoCommit = $FS::UID::AutoCommit;
4319 local $FS::UID::AutoCommit = 0;
4322 # set fields specific to payment_payby
4323 if ( $payby eq 'CARD' ) {
4324 if ($opt{'bill_location'}) {
4325 $opt{'bill_location'}->set('custnum' => $self->custnum);
4326 my $error = $opt{'bill_location'}->find_or_insert;
4328 $dbh->rollback if $oldAutoCommit;
4331 $new->set( 'locationnum' => $opt{'bill_location'}->locationnum );
4333 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
4334 $new->set( $field => $opt{$field} );
4337 foreach my $field ( qw(paytype paystate) ) {
4338 $new->set( $field => $opt{$field} );
4342 # other cust_payby to compare this to
4343 my @existing = $self->cust_payby(@check_existing);
4345 # fields that can overwrite blanks with values, but not values with blanks
4346 my @preserve = qw( paymask locationnum paystart_month paystart_year payissue payip );
4348 my $skip_cust_payby = 0; # true if we don't need to save or reweight cust_payby
4350 # generally, we don't want to overwrite existing cust_payby with this,
4351 # but we can replace if we're only marking it auto or adding a preserved field
4352 # and we can avoid saving a total duplicate or merely turning off auto
4354 foreach my $cust_payby (@existing) {
4355 # check fields that absolutely should not change
4356 foreach my $field ($new->fields) {
4357 next if grep(/^$field$/, qw( custpaybynum payby weight ) );
4358 next if grep(/^$field$/, @preserve );
4359 next PAYBYLOOP unless $new->get($field) eq $cust_payby->get($field);
4361 # now check fields that can replace if one value is blank
4363 foreach my $field (@preserve) {
4365 ( $new->get($field) and !$cust_payby->get($field) ) or
4366 ( $cust_payby->get($field) and !$new->get($field) )
4368 # prevention of overwriting values with blanks happens farther below
4370 } elsif ( $new->get($field) ne $cust_payby->get($field) ) {
4374 unless ( $replace ) {
4375 # nearly identical, now check weight
4376 if ($new->get('weight') eq $cust_payby->get('weight') or !$new->get('weight')) {
4377 # ignore identical cust_payby, and ignore attempts to turn off auto
4378 # no need to save or re-weight cust_payby (but still need to update/commit $self)
4379 $skip_cust_payby = 1;
4382 # otherwise, only change is to mark this as primary
4384 # if we got this far, we're definitely replacing
4391 $new->set( 'custpaybynum' => $old->custpaybynum );
4392 # don't turn off automatic payment (but allow it to be turned on)
4393 if ($new->payby =~ /^D/ and $new->payby ne $old->payby) {
4395 $new->set( 'payby' => $old->payby );
4396 $new->set( 'weight' => 1 );
4398 # make sure we're not overwriting values with blanks
4399 foreach my $field (@preserve) {
4400 if ( $old->get($field) and !$new->get($field) ) {
4401 $new->set( $field => $old->get($field) );
4406 # only overwrite cust_main bill_location if auto
4407 if ($opt{'auto'} && $opt{'bill_location'}) {
4408 $self->set('bill_location' => $opt{'bill_location'});
4409 my $error = $self->replace;
4411 $dbh->rollback if $oldAutoCommit;
4416 # done with everything except reweighting and saving cust_payby
4417 # still need to commit changes to cust_main and cust_location
4418 if ($skip_cust_payby) {
4419 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4423 # re-weight existing primary cust_pay for this payby
4425 foreach my $cust_payby (@existing) {
4426 # relies on cust_payby return order
4427 last unless $cust_payby->payby !~ /^D/;
4428 last if $cust_payby->weight > 1;
4429 next if $new->custpaybynum eq $cust_payby->custpaybynum;
4430 next if $cust_payby->weight < ($opt{'weight'} || 1);
4431 $cust_payby->weight( $cust_payby->weight + 1 );
4432 my $error = $cust_payby->replace;
4434 $dbh->rollback if $oldAutoCommit;
4435 return "Error reweighting cust_payby: $error";
4440 # finally, save cust_payby
4441 my $error = $old ? $new->replace($old) : $new->insert;
4443 $dbh->rollback if $oldAutoCommit;
4447 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4454 =head1 CLASS METHODS
4460 Class method that returns the list of possible status strings for customers
4461 (see L<the status method|/status>). For example:
4463 @statuses = FS::cust_main->statuses();
4469 keys %{ $self->statuscolors };
4472 =item cust_status_sql
4474 Returns an SQL fragment to determine the status of a cust_main record, as a
4479 sub cust_status_sql {
4481 for my $status ( FS::cust_main->statuses() ) {
4482 my $method = $status.'_sql';
4483 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4492 Returns an SQL expression identifying prospective cust_main records (customers
4493 with no packages ever ordered)
4497 use vars qw($select_count_pkgs);
4498 $select_count_pkgs =
4499 "SELECT COUNT(*) FROM cust_pkg
4500 WHERE cust_pkg.custnum = cust_main.custnum";
4502 sub select_count_pkgs_sql {
4507 " 0 = ( $select_count_pkgs ) ";
4512 Returns an SQL expression identifying ordered cust_main records (customers with
4513 no active packages, but recurring packages not yet setup or one time charges
4519 FS::cust_main->none_active_sql.
4520 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4525 Returns an SQL expression identifying active cust_main records (customers with
4526 active recurring packages).
4531 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4534 =item none_active_sql
4536 Returns an SQL expression identifying cust_main records with no active
4537 recurring packages. This includes customers of status prospect, ordered,
4538 inactive, and suspended.
4542 sub none_active_sql {
4543 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4548 Returns an SQL expression identifying inactive cust_main records (customers with
4549 no active recurring packages, but otherwise unsuspended/uncancelled).
4554 FS::cust_main->none_active_sql.
4555 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4561 Returns an SQL expression identifying suspended cust_main records.
4566 sub suspended_sql { susp_sql(@_); }
4568 FS::cust_main->none_active_sql.
4569 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4575 Returns an SQL expression identifying cancelled cust_main records.
4579 sub cancel_sql { shift->cancelled_sql(@_); }
4582 =item uncancelled_sql
4584 Returns an SQL expression identifying un-cancelled cust_main records.
4588 sub uncancelled_sql { uncancel_sql(@_); }
4589 sub uncancel_sql { "
4590 ( 0 < ( $select_count_pkgs
4591 AND ( cust_pkg.cancel IS NULL
4592 OR cust_pkg.cancel = 0
4595 OR 0 = ( $select_count_pkgs )
4601 Returns an SQL fragment to retreive the balance.
4606 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4607 WHERE cust_bill.custnum = cust_main.custnum )
4608 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4609 WHERE cust_pay.custnum = cust_main.custnum )
4610 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4611 WHERE cust_credit.custnum = cust_main.custnum )
4612 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4613 WHERE cust_refund.custnum = cust_main.custnum )
4616 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4618 Returns an SQL fragment to retreive the balance for this customer, optionally
4619 considering invoices with date earlier than START_TIME, and not
4620 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4621 total_unapplied_payments).
4623 Times are specified as SQL fragments or numeric
4624 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4625 L<Date::Parse> for conversion functions. The empty string can be passed
4626 to disable that time constraint completely.
4628 Available options are:
4632 =item unapplied_date
4634 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)
4639 set to true to remove all customer comparison clauses, for totals
4644 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4649 JOIN clause (typically used with the total option)
4653 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4654 time will be ignored. Note that START_TIME and END_TIME only limit the date
4655 range for invoices and I<unapplied> payments, credits, and refunds.
4661 sub balance_date_sql {
4662 my( $class, $start, $end, %opt ) = @_;
4664 my $cutoff = $opt{'cutoff'};
4666 my $owed = FS::cust_bill->owed_sql($cutoff);
4667 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4668 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4669 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4671 my $j = $opt{'join'} || '';
4673 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4674 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4675 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4676 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4678 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4679 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4680 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4681 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4686 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4688 Returns an SQL fragment to retreive the total unapplied payments for this
4689 customer, only considering payments with date earlier than START_TIME, and
4690 optionally not later than END_TIME.
4692 Times are specified as SQL fragments or numeric
4693 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4694 L<Date::Parse> for conversion functions. The empty string can be passed
4695 to disable that time constraint completely.
4697 Available options are:
4701 sub unapplied_payments_date_sql {
4702 my( $class, $start, $end, %opt ) = @_;
4704 my $cutoff = $opt{'cutoff'};
4706 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4708 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4709 'unapplied_date'=>1 );
4711 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4714 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4716 Helper method for balance_date_sql; name (and usage) subject to change
4717 (suggestions welcome).
4719 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4720 cust_refund, cust_credit or cust_pay).
4722 If TABLE is "cust_bill" or the unapplied_date option is true, only
4723 considers records with date earlier than START_TIME, and optionally not
4724 later than END_TIME .
4728 sub _money_table_where {
4729 my( $class, $table, $start, $end, %opt ) = @_;
4732 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4733 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4734 push @where, "$table._date <= $start" if defined($start) && length($start);
4735 push @where, "$table._date > $end" if defined($end) && length($end);
4737 push @where, @{$opt{'where'}} if $opt{'where'};
4738 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4744 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4745 use FS::cust_main::Search;
4748 FS::cust_main::Search->search(@_);
4757 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4759 Generates a templated notification to the customer (see L<Text::Template>).
4761 OPTIONS is a hash and may include
4763 I<extra_fields> - a hashref of name/value pairs which will be substituted
4764 into the template. These values may override values mentioned below
4765 and those from the customer record.
4767 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
4769 The following variables are available in the template instead of or in addition
4770 to the fields of the customer record.
4772 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4776 # a lot like cust_bill::print_latex
4777 sub generate_letter {
4778 my ($self, $template, %options) = @_;
4780 warn "Template $template does not exist" && return
4781 unless $conf->exists($template) || $options{'template_text'};
4783 my $template_source = $options{'template_text'}
4784 ? [ $options{'template_text'} ]
4785 : [ map "$_\n", $conf->config($template) ];
4787 my $letter_template = new Text::Template
4789 SOURCE => $template_source,
4790 DELIMITERS => [ '[@--', '--@]' ],
4792 or die "can't create new Text::Template object: Text::Template::ERROR";
4794 $letter_template->compile()
4795 or die "can't compile template: Text::Template::ERROR";
4797 my %letter_data = map { $_ => $self->$_ } $self->fields;
4799 for (keys %{$options{extra_fields}}){
4800 $letter_data{$_} = $options{extra_fields}->{$_};
4803 unless(exists($letter_data{returnaddress})){
4804 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4805 $self->agent_template)
4807 if ( length($retadd) ) {
4808 $letter_data{returnaddress} = $retadd;
4809 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4810 $letter_data{returnaddress} =
4811 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4815 ( $conf->config('company_name', $self->agentnum),
4816 $conf->config('company_address', $self->agentnum),
4820 $letter_data{returnaddress} = '~';
4824 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4826 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4828 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4830 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4834 ) or die "can't open temp file: $!\n";
4835 print $lh $conf->config_binary('logo.eps', $self->agentnum)
4836 or die "can't write temp file: $!\n";
4838 $letter_data{'logo_file'} = $lh->filename;
4840 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4844 ) or die "can't open temp file: $!\n";
4846 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4848 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4849 return ($1, $letter_data{'logo_file'});
4853 =item print_ps TEMPLATE
4855 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4861 my($file, $lfile) = $self->generate_letter(@_);
4862 my $ps = FS::Misc::generate_ps($file);
4863 unlink($file.'.tex');
4869 =item print TEMPLATE
4871 Prints the filled in template.
4873 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4877 sub queueable_print {
4880 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4881 or die "invalid customer number: " . $opt{custnum};
4883 #do not backport this change to 3.x
4884 # my $error = $self->print( { 'template' => $opt{template} } );
4885 my $error = $self->print( $opt{'template'} );
4886 die $error if $error;
4890 my ($self, $template) = (shift, shift);
4892 [ $self->print_ps($template) ],
4893 'agentnum' => $self->agentnum,
4897 #these three subs should just go away once agent stuff is all config overrides
4899 sub agent_template {
4901 $self->_agent_plandata('agent_templatename');
4904 sub agent_invoice_from {
4906 $self->_agent_plandata('agent_invoice_from');
4909 sub _agent_plandata {
4910 my( $self, $option ) = @_;
4912 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
4913 #agent-specific Conf
4915 use FS::part_event::Condition;
4917 my $agentnum = $self->agentnum;
4919 my $regexp = regexp_sql();
4921 my $part_event_option =
4923 'select' => 'part_event_option.*',
4924 'table' => 'part_event_option',
4926 LEFT JOIN part_event USING ( eventpart )
4927 LEFT JOIN part_event_option AS peo_agentnum
4928 ON ( part_event.eventpart = peo_agentnum.eventpart
4929 AND peo_agentnum.optionname = 'agentnum'
4930 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4932 LEFT JOIN part_event_condition
4933 ON ( part_event.eventpart = part_event_condition.eventpart
4934 AND part_event_condition.conditionname = 'cust_bill_age'
4936 LEFT JOIN part_event_condition_option
4937 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4938 AND part_event_condition_option.optionname = 'age'
4941 #'hashref' => { 'optionname' => $option },
4942 #'hashref' => { 'part_event_option.optionname' => $option },
4944 " WHERE part_event_option.optionname = ". dbh->quote($option).
4945 " AND action = 'cust_bill_send_agent' ".
4946 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4947 " AND peo_agentnum.optionname = 'agentnum' ".
4948 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4950 CASE WHEN part_event_condition_option.optionname IS NULL
4952 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4954 , part_event.weight".
4958 unless ( $part_event_option ) {
4959 return $self->agent->invoice_template || ''
4960 if $option eq 'agent_templatename';
4964 $part_event_option->optionvalue;
4968 sub process_o2m_qsearch {
4971 return qsearch($table, @_) unless $table eq 'contact';
4973 my $hashref = shift;
4974 my %hash = %$hashref;
4975 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4976 or die 'guru meditation #4343';
4978 qsearch({ 'table' => 'contact',
4979 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4980 'hashref' => \%hash,
4981 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
4982 " cust_contact.custnum = $custnum "
4986 sub process_o2m_qsearchs {
4989 return qsearchs($table, @_) unless $table eq 'contact';
4991 my $hashref = shift;
4992 my %hash = %$hashref;
4993 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
4994 or die 'guru meditation #2121';
4996 qsearchs({ 'table' => 'contact',
4997 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
4998 'hashref' => \%hash,
4999 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5000 " cust_contact.custnum = $custnum "
5004 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5006 Subroutine (not a method), designed to be called from the queue.
5008 Takes a list of options and values.
5010 Pulls up the customer record via the custnum option and calls bill_and_collect.
5015 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5017 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5018 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5020 #without this errors don't get rolled back
5021 $args{'fatal'} = 1; # runs from job queue, will be caught
5023 $cust_main->bill_and_collect( %args );
5026 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5028 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5029 C<collect> part. This is used in batch tax calculation, where invoice
5030 generation and collection events have to be completely separated.
5034 sub queued_collect {
5036 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5038 $cust_main->collect(%args);
5041 sub process_bill_and_collect {
5044 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5045 or die "custnum '$param->{custnum}' not found!\n";
5046 $param->{'job'} = $job;
5047 $param->{'fatal'} = 1; # runs from job queue, will be caught
5048 $param->{'retry'} = 1;
5050 $cust_main->bill_and_collect( %$param );
5053 #starting to take quite a while for big dbs
5054 # (JRNL: journaled so it only happens once per database)
5055 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5056 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5057 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5058 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5059 # JRNL leading/trailing spaces in first, last, company
5060 # JRNL migrate to cust_payby
5061 # - otaker upgrade? journal and call it good? (double check to make sure
5062 # we're not still setting otaker here)
5064 #only going to get worse with new location stuff...
5066 sub _upgrade_data { #class method
5067 my ($class, %opts) = @_;
5069 my @statements = ();
5071 #this seems to be the only expensive one.. why does it take so long?
5072 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5074 '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';
5075 FS::upgrade_journal->set_done('cust_main__signupdate');
5079 foreach my $sql ( @statements ) {
5080 my $sth = dbh->prepare($sql) or die dbh->errstr;
5081 $sth->execute or die $sth->errstr;
5082 #warn ( (time - $t). " seconds\n" );
5086 local($ignore_expired_card) = 1;
5087 local($ignore_banned_card) = 1;
5088 local($skip_fuzzyfiles) = 1;
5089 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5091 FS::cust_main::Location->_upgrade_data(%opts);
5093 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5095 foreach my $cust_main ( qsearch({
5096 'table' => 'cust_main',
5098 'extra_sql' => 'WHERE '.
5100 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5101 qw( first last company )
5104 my $error = $cust_main->replace;
5105 die $error if $error;
5108 FS::upgrade_journal->set_done('cust_main__trimspaces');
5112 $class->_upgrade_otaker(%opts);
5122 The delete method should possibly take an FS::cust_main object reference
5123 instead of a scalar customer number.
5125 Bill and collect options should probably be passed as references instead of a
5128 There should probably be a configuration file with a list of allowed credit
5131 No multiple currency support (probably a larger project than just this module).
5133 Birthdates rely on negative epoch values.
5135 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5139 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5140 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5141 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.