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);
33 use FS::UID qw( dbh driver_name );
34 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
36 use FS::Misc qw( generate_ps do_print money_pretty card_types );
37 use FS::Msgcat qw(gettext);
44 use FS::cust_bill_void;
45 use FS::legacy_cust_bill;
47 use FS::cust_pay_pending;
48 use FS::cust_pay_void;
49 use FS::cust_pay_batch;
52 use FS::part_referral;
53 use FS::cust_main_county;
54 use FS::cust_location;
57 use FS::cust_main_exemption;
58 use FS::cust_tax_adjustment;
59 use FS::cust_tax_location;
60 use FS::agent_currency;
61 use FS::cust_main_invoice;
63 use FS::prepay_credit;
69 use FS::payment_gateway;
70 use FS::agent_payment_gateway;
72 use FS::cust_main_note;
73 use FS::cust_attachment;
76 use FS::upgrade_journal;
82 # 1 is mostly method/subroutine entry and options
83 # 2 traces progress of some operations
84 # 3 is even more information including possibly sensitive data
86 our $me = '[FS::cust_main]';
89 our $ignore_expired_card = 0;
90 our $ignore_banned_card = 0;
91 our $ignore_invalid_card = 0;
93 our $skip_fuzzyfiles = 0;
95 our $ucfirst_nowarn = 0;
97 #this info is in cust_payby as of 4.x
98 #this and the fields themselves can be removed in 5.x
99 our @encrypted_fields = ('payinfo', 'paycvv');
100 sub nohistory_fields { ('payinfo', 'paycvv'); }
103 our $default_agent_custid;
104 our $custnum_display_length;
105 #ask FS::UID to run this stuff for us later
106 #$FS::UID::callback{'FS::cust_main'} = sub {
107 install_callback FS::UID sub {
108 $conf = new FS::Conf;
109 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
110 $default_agent_custid = $conf->exists('cust_main-default_agent_custid');
111 $custnum_display_length = $conf->config('cust_main-custnum-display_length');
116 my ( $hashref, $cache ) = @_;
117 if ( exists $hashref->{'pkgnum'} ) {
118 #@{ $self->{'_pkgnum'} } = ();
119 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
120 $self->{'_pkgnum'} = $subcache;
121 #push @{ $self->{'_pkgnum'} },
122 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
128 FS::cust_main - Object methods for cust_main records
134 $record = new FS::cust_main \%hash;
135 $record = new FS::cust_main { 'column' => 'value' };
137 $error = $record->insert;
139 $error = $new_record->replace($old_record);
141 $error = $record->delete;
143 $error = $record->check;
145 @cust_pkg = $record->all_pkgs;
147 @cust_pkg = $record->ncancelled_pkgs;
149 @cust_pkg = $record->suspended_pkgs;
151 $error = $record->bill;
152 $error = $record->bill %options;
153 $error = $record->bill 'time' => $time;
155 $error = $record->collect;
156 $error = $record->collect %options;
157 $error = $record->collect 'invoice_time' => $time,
162 An FS::cust_main object represents a customer. FS::cust_main inherits from
163 FS::Record. The following fields are currently supported:
169 Primary key (assigned automatically for new customers)
173 Agent (see L<FS::agent>)
177 Advertising source (see L<FS::part_referral>)
189 Cocial security number (optional)
213 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
217 Payment Information (See L<FS::payinfo_Mixin> for data format)
221 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
225 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
229 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
233 Start date month (maestro/solo cards only)
237 Start date year (maestro/solo cards only)
241 Issue number (maestro/solo cards only)
245 Name on card or billing name
249 IP address from which payment information was received
253 Tax exempt, empty or `Y'
257 Order taker (see L<FS::access_user>)
263 =item referral_custnum
265 Referring customer number
269 Enable individual CDR spooling, empty or `Y'
273 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
277 Discourage individual CDR printing, empty or `Y'
281 Allow self-service editing of ticket subjects, empty or 'Y'
283 =item calling_list_exempt
285 Do not call, empty or 'Y'
287 =item invoice_ship_address
289 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
299 Creates a new customer. To add the customer to the database, see L<"insert">.
301 Note that this stores the hash reference, not a distinct copy of the hash it
302 points to. You can ask the object for a copy with the I<hash> method.
306 sub table { 'cust_main'; }
308 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
310 Adds this customer to the database. If there is an error, returns the error,
311 otherwise returns false.
313 Usually the customer's location will not yet exist in the database, and
314 the C<bill_location> and C<ship_location> pseudo-fields must be set to
315 uninserted L<FS::cust_location> objects. These will be inserted and linked
316 (in both directions) to the new customer record. If they're references
317 to the same object, they will become the same location.
319 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
320 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
321 are inserted atomicly, or the transaction is rolled back. Passing an empty
322 hash reference is equivalent to not supplying this parameter. There should be
323 a better explanation of this, but until then, here's an example:
326 tie %hash, 'Tie::RefHash'; #this part is important
328 $cust_pkg => [ $svc_acct ],
331 $cust_main->insert( \%hash );
333 INVOICING_LIST_ARYREF: No longer supported.
335 Currently available options are: I<depend_jobnum>, I<noexport>,
336 I<tax_exemption>, I<prospectnum>, I<contact> and I<contact_params>.
338 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
339 on the supplied jobnum (they will not run until the specific job completes).
340 This can be used to defer provisioning until some action completes (such
341 as running the customer's credit card successfully).
343 The I<noexport> option is deprecated. If I<noexport> is set true, no
344 provisioning jobs (exports) are scheduled. (You can schedule them later with
345 the B<reexport> method.)
347 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
348 of tax names and exemption numbers. FS::cust_main_exemption records will be
349 created and inserted.
351 If I<prospectnum> is set, moves contacts and locations from that prospect.
353 If I<contact> is set to an arrayref of FS::contact objects, those will be
356 If I<contact_params> is set to a hashref of CGI parameters (and I<contact> is
357 unset), inserts those new contacts with this new customer. Handles CGI
358 paramaters for an "m2" multiple entry field as passed by edit/cust_main.cgi
360 If I<cust_payby_params> is set to a hashref o fCGI parameters, inserts those
361 new stored payment records with this new customer. Handles CGI parameters
362 for an "m2" multiple entry field as passed by edit/cust_main.cgi
368 my $cust_pkgs = @_ ? shift : {};
370 if ( $_[0] and ref($_[0]) eq 'ARRAY' ) {
371 warn "cust_main::insert using deprecated invoicing list argument";
372 $invoicing_list = shift;
375 warn "$me insert called with options ".
376 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
379 local $SIG{HUP} = 'IGNORE';
380 local $SIG{INT} = 'IGNORE';
381 local $SIG{QUIT} = 'IGNORE';
382 local $SIG{TERM} = 'IGNORE';
383 local $SIG{TSTP} = 'IGNORE';
384 local $SIG{PIPE} = 'IGNORE';
386 my $oldAutoCommit = $FS::UID::AutoCommit;
387 local $FS::UID::AutoCommit = 0;
390 my $prepay_identifier = '';
391 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
393 if ( $self->payby eq 'PREPAY' ) {
395 $self->payby(''); #'BILL');
396 $prepay_identifier = $self->payinfo;
399 warn " looking up prepaid card $prepay_identifier\n"
402 my $error = $self->get_prepay( $prepay_identifier,
403 'amount_ref' => \$amount,
404 'seconds_ref' => \$seconds,
405 'upbytes_ref' => \$upbytes,
406 'downbytes_ref' => \$downbytes,
407 'totalbytes_ref' => \$totalbytes,
410 $dbh->rollback if $oldAutoCommit;
411 #return "error applying prepaid card (transaction rolled back): $error";
415 $payby = 'PREP' if $amount;
417 } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
420 $self->payby(''); #'BILL');
421 $amount = $self->paid;
426 foreach my $l (qw(bill_location ship_location)) {
428 my $loc = delete $self->hashref->{$l} or next;
430 if ( !$loc->locationnum ) {
431 # warn the location that we're going to insert it with no custnum
432 $loc->set(custnum_pending => 1);
433 warn " inserting $l\n"
435 my $error = $loc->insert;
437 $dbh->rollback if $oldAutoCommit;
438 my $label = $l eq 'ship_location' ? 'service' : 'billing';
439 return "$error (in $label location)";
442 } elsif ( $loc->prospectnum ) {
444 $loc->prospectnum('');
445 $loc->set(custnum_pending => 1);
446 my $error = $loc->replace;
448 $dbh->rollback if $oldAutoCommit;
449 my $label = $l eq 'ship_location' ? 'service' : 'billing';
450 return "$error (moving $label location)";
453 } elsif ( ($loc->custnum || 0) > 0 ) {
454 # then it somehow belongs to another customer--shouldn't happen
455 $dbh->rollback if $oldAutoCommit;
456 return "$l belongs to customer ".$loc->custnum;
458 # else it already belongs to this customer
459 # (happens when ship_location is identical to bill_location)
461 $self->set($l.'num', $loc->locationnum);
463 if ( $self->get($l.'num') eq '' ) {
464 $dbh->rollback if $oldAutoCommit;
469 warn " inserting $self\n"
472 $self->signupdate(time) unless $self->signupdate;
474 $self->auto_agent_custid()
475 if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
477 my $error = $self->check_payinfo_cardtype
478 || $self->SUPER::insert;
480 $dbh->rollback if $oldAutoCommit;
481 #return "inserting cust_main record (transaction rolled back): $error";
485 # now set cust_location.custnum
486 foreach my $l (qw(bill_location ship_location)) {
487 warn " setting $l.custnum\n"
489 my $loc = $self->$l or next;
490 unless ( $loc->custnum ) {
491 $loc->set(custnum => $self->custnum);
492 $error ||= $loc->replace;
496 $dbh->rollback if $oldAutoCommit;
497 return "error setting $l custnum: $error";
501 warn " setting customer tags\n"
504 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
505 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
506 'custnum' => $self->custnum };
507 my $error = $cust_tag->insert;
509 $dbh->rollback if $oldAutoCommit;
514 my $prospectnum = delete $options{'prospectnum'};
515 if ( $prospectnum ) {
517 warn " moving contacts and locations from prospect $prospectnum\n"
521 qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
522 unless ( $prospect_main ) {
523 $dbh->rollback if $oldAutoCommit;
524 return "Unknown prospectnum $prospectnum";
526 $prospect_main->custnum($self->custnum);
527 $prospect_main->disabled('Y');
528 my $error = $prospect_main->replace;
530 $dbh->rollback if $oldAutoCommit;
534 foreach my $prospect_contact ( $prospect_main->prospect_contact ) {
535 my $cust_contact = new FS::cust_contact {
536 'custnum' => $self->custnum,
537 'invoice_dest' => 'Y', # invoice_dest currently not set for prospect contacts
538 map { $_ => $prospect_contact->$_() } qw( contactnum classnum comment )
540 my $error = $cust_contact->insert
541 || $prospect_contact->delete;
543 $dbh->rollback if $oldAutoCommit;
548 my @cust_location = $prospect_main->cust_location;
549 my @qual = $prospect_main->qual;
551 foreach my $r ( @cust_location, @qual ) {
553 $r->custnum($self->custnum);
554 my $error = $r->replace;
556 $dbh->rollback if $oldAutoCommit;
560 # since we set invoice_dest on all migrated prospect contacts (for now),
561 # don't process invoicing_list.
562 delete $options{'invoicing_list'};
563 $invoicing_list = undef;
566 warn " setting contacts\n"
569 $invoicing_list ||= $options{'invoicing_list'};
570 if ( $invoicing_list ) {
572 $invoicing_list = [ $invoicing_list ] if !ref($invoicing_list);
575 foreach my $dest (@$invoicing_list ) {
576 if ($dest eq 'POST') {
577 $self->set('postal_invoice', 'Y');
580 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
581 if ( $contact_email ) {
582 my $cust_contact = FS::cust_contact->new({
583 contactnum => $contact_email->contactnum,
584 custnum => $self->custnum,
586 $cust_contact->set('invoice_dest', 'Y');
587 my $error = $cust_contact->insert;
589 $dbh->rollback if $oldAutoCommit;
590 return "$error (linking to email address $dest)";
594 # this email address is not yet linked to any contact
595 $email .= ',' if length($email);
601 my $contact = FS::contact->new({
602 'custnum' => $self->get('custnum'),
603 'last' => $self->get('last'),
604 'first' => $self->get('first'),
605 'emailaddress' => $email,
606 'invoice_dest' => 'Y', # yes, you can set this via the contact
608 my $error = $contact->insert;
610 $dbh->rollback if $oldAutoCommit;
616 if ( my $contact = delete $options{'contact'} ) {
618 foreach my $c ( @$contact ) {
619 $c->custnum($self->custnum);
620 my $error = $c->insert;
622 $dbh->rollback if $oldAutoCommit;
628 } elsif ( my $contact_params = delete $options{'contact_params'} ) {
630 my $error = $self->process_o2m( 'table' => 'contact',
631 'fields' => FS::contact->cgi_contact_fields,
632 'params' => $contact_params,
635 $dbh->rollback if $oldAutoCommit;
640 warn " setting cust_payby\n"
643 if ( $options{cust_payby} ) {
645 foreach my $cust_payby ( @{ $options{cust_payby} } ) {
646 $cust_payby->custnum($self->custnum);
647 my $error = $cust_payby->insert;
649 $dbh->rollback if $oldAutoCommit;
654 } elsif ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
656 my $error = $self->process_o2m(
657 'table' => 'cust_payby',
658 'fields' => FS::cust_payby->cgi_cust_payby_fields,
659 'params' => $cust_payby_params,
660 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
663 $dbh->rollback if $oldAutoCommit;
669 warn " setting cust_main_exemption\n"
672 my $tax_exemption = delete $options{'tax_exemption'};
673 if ( $tax_exemption ) {
675 $tax_exemption = { map { $_ => '' } @$tax_exemption }
676 if ref($tax_exemption) eq 'ARRAY';
678 foreach my $taxname ( keys %$tax_exemption ) {
679 my $cust_main_exemption = new FS::cust_main_exemption {
680 'custnum' => $self->custnum,
681 'taxname' => $taxname,
682 'exempt_number' => $tax_exemption->{$taxname},
684 my $error = $cust_main_exemption->insert;
686 $dbh->rollback if $oldAutoCommit;
687 return "inserting cust_main_exemption (transaction rolled back): $error";
692 warn " ordering packages\n"
695 $error = $self->order_pkgs( $cust_pkgs,
697 'seconds_ref' => \$seconds,
698 'upbytes_ref' => \$upbytes,
699 'downbytes_ref' => \$downbytes,
700 'totalbytes_ref' => \$totalbytes,
703 $dbh->rollback if $oldAutoCommit;
708 $dbh->rollback if $oldAutoCommit;
709 return "No svc_acct record to apply pre-paid time";
711 if ( $upbytes || $downbytes || $totalbytes ) {
712 $dbh->rollback if $oldAutoCommit;
713 return "No svc_acct record to apply pre-paid data";
717 warn " inserting initial $payby payment of $amount\n"
719 $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
721 $dbh->rollback if $oldAutoCommit;
722 return "inserting payment (transaction rolled back): $error";
726 unless ( $import || $skip_fuzzyfiles ) {
727 warn " queueing fuzzyfiles update\n"
729 $error = $self->queue_fuzzyfiles_update;
731 $dbh->rollback if $oldAutoCommit;
732 return "updating fuzzy search cache: $error";
736 # FS::geocode_Mixin::after_insert or something?
737 if ( $conf->config('tax_district_method') and !$import ) {
738 # if anything non-empty, try to look it up
739 my $queue = new FS::queue {
740 'job' => 'FS::geocode_Mixin::process_district_update',
741 'custnum' => $self->custnum,
743 my $error = $queue->insert( ref($self), $self->custnum );
745 $dbh->rollback if $oldAutoCommit;
746 return "queueing tax district update: $error";
751 warn " exporting\n" if $DEBUG > 1;
753 my $export_args = $options{'export_args'} || [];
756 map qsearch( 'part_export', {exportnum=>$_} ),
757 $conf->config('cust_main-exports'); #, $agentnum
759 foreach my $part_export ( @part_export ) {
760 my $error = $part_export->export_insert($self, @$export_args);
762 $dbh->rollback if $oldAutoCommit;
763 return "exporting to ". $part_export->exporttype.
764 " (transaction rolled back): $error";
768 #foreach my $depend_jobnum ( @$depend_jobnums ) {
769 # warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
771 # foreach my $jobnum ( @jobnums ) {
772 # my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
773 # warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
775 # my $error = $queue->depend_insert($depend_jobnum);
777 # $dbh->rollback if $oldAutoCommit;
778 # return "error queuing job dependancy: $error";
785 #if ( exists $options{'jobnums'} ) {
786 # push @{ $options{'jobnums'} }, @jobnums;
789 warn " insert complete; committing transaction\n"
792 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
797 use File::CounterFile;
798 sub auto_agent_custid {
801 my $format = $conf->config('cust_main-auto_agent_custid');
803 if ( $format eq '1YMMXXXXXXXX' ) {
805 my $counter = new File::CounterFile 'cust_main.agent_custid';
808 my $ym = 100000000000 + time2str('%y%m00000000', time);
809 if ( $ym > $counter->value ) {
810 $counter->{'value'} = $agent_custid = $ym;
811 $counter->{'updated'} = 1;
813 $agent_custid = $counter->inc;
819 die "Unknown cust_main-auto_agent_custid format: $format";
822 $self->agent_custid($agent_custid);
826 =item PACKAGE METHODS
828 Documentation on customer package methods has been moved to
829 L<FS::cust_main::Packages>.
831 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
833 Recharges this (existing) customer with the specified prepaid card (see
834 L<FS::prepay_credit>), specified either by I<identifier> or as an
835 FS::prepay_credit object. If there is an error, returns the error, otherwise
838 Optionally, five scalar references can be passed as well. They will have their
839 values filled in with the amount, number of seconds, and number of upload,
840 download, and total bytes applied by this prepaid card.
844 #the ref bullshit here should be refactored like get_prepay. MyAccount.pm is
845 #the only place that uses these args
846 sub recharge_prepay {
847 my( $self, $prepay_credit, $amountref, $secondsref,
848 $upbytesref, $downbytesref, $totalbytesref ) = @_;
850 local $SIG{HUP} = 'IGNORE';
851 local $SIG{INT} = 'IGNORE';
852 local $SIG{QUIT} = 'IGNORE';
853 local $SIG{TERM} = 'IGNORE';
854 local $SIG{TSTP} = 'IGNORE';
855 local $SIG{PIPE} = 'IGNORE';
857 my $oldAutoCommit = $FS::UID::AutoCommit;
858 local $FS::UID::AutoCommit = 0;
861 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
863 my $error = $self->get_prepay( $prepay_credit,
864 'amount_ref' => \$amount,
865 'seconds_ref' => \$seconds,
866 'upbytes_ref' => \$upbytes,
867 'downbytes_ref' => \$downbytes,
868 'totalbytes_ref' => \$totalbytes,
870 || $self->increment_seconds($seconds)
871 || $self->increment_upbytes($upbytes)
872 || $self->increment_downbytes($downbytes)
873 || $self->increment_totalbytes($totalbytes)
874 || $self->insert_cust_pay_prepay( $amount,
876 ? $prepay_credit->identifier
881 $dbh->rollback if $oldAutoCommit;
885 if ( defined($amountref) ) { $$amountref = $amount; }
886 if ( defined($secondsref) ) { $$secondsref = $seconds; }
887 if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
888 if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
889 if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
891 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
896 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
898 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
899 specified either by I<identifier> or as an FS::prepay_credit object.
901 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
902 incremented by the values of the prepaid card.
904 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
905 check or set this customer's I<agentnum>.
907 If there is an error, returns the error, otherwise returns false.
913 my( $self, $prepay_credit, %opt ) = @_;
915 local $SIG{HUP} = 'IGNORE';
916 local $SIG{INT} = 'IGNORE';
917 local $SIG{QUIT} = 'IGNORE';
918 local $SIG{TERM} = 'IGNORE';
919 local $SIG{TSTP} = 'IGNORE';
920 local $SIG{PIPE} = 'IGNORE';
922 my $oldAutoCommit = $FS::UID::AutoCommit;
923 local $FS::UID::AutoCommit = 0;
926 unless ( ref($prepay_credit) ) {
928 my $identifier = $prepay_credit;
930 $prepay_credit = qsearchs(
932 { 'identifier' => $identifier },
937 unless ( $prepay_credit ) {
938 $dbh->rollback if $oldAutoCommit;
939 return "Invalid prepaid card: ". $identifier;
944 if ( $prepay_credit->agentnum ) {
945 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
946 $dbh->rollback if $oldAutoCommit;
947 return "prepaid card not valid for agent ". $self->agentnum;
949 $self->agentnum($prepay_credit->agentnum);
952 my $error = $prepay_credit->delete;
954 $dbh->rollback if $oldAutoCommit;
955 return "removing prepay_credit (transaction rolled back): $error";
958 ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
959 for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
961 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
966 =item increment_upbytes SECONDS
968 Updates this customer's single or primary account (see L<FS::svc_acct>) by
969 the specified number of upbytes. If there is an error, returns the error,
970 otherwise returns false.
974 sub increment_upbytes {
975 _increment_column( shift, 'upbytes', @_);
978 =item increment_downbytes SECONDS
980 Updates this customer's single or primary account (see L<FS::svc_acct>) by
981 the specified number of downbytes. If there is an error, returns the error,
982 otherwise returns false.
986 sub increment_downbytes {
987 _increment_column( shift, 'downbytes', @_);
990 =item increment_totalbytes SECONDS
992 Updates this customer's single or primary account (see L<FS::svc_acct>) by
993 the specified number of totalbytes. If there is an error, returns the error,
994 otherwise returns false.
998 sub increment_totalbytes {
999 _increment_column( shift, 'totalbytes', @_);
1002 =item increment_seconds SECONDS
1004 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1005 the specified number of seconds. If there is an error, returns the error,
1006 otherwise returns false.
1010 sub increment_seconds {
1011 _increment_column( shift, 'seconds', @_);
1014 =item _increment_column AMOUNT
1016 Updates this customer's single or primary account (see L<FS::svc_acct>) by
1017 the specified number of seconds or bytes. If there is an error, returns
1018 the error, otherwise returns false.
1022 sub _increment_column {
1023 my( $self, $column, $amount ) = @_;
1024 warn "$me increment_column called: $column, $amount\n"
1027 return '' unless $amount;
1029 my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
1030 $self->ncancelled_pkgs;
1032 if ( ! @cust_pkg ) {
1033 return 'No packages with primary or single services found'.
1034 ' to apply pre-paid time';
1035 } elsif ( scalar(@cust_pkg) > 1 ) {
1036 #maybe have a way to specify the package/account?
1037 return 'Multiple packages found to apply pre-paid time';
1040 my $cust_pkg = $cust_pkg[0];
1041 warn " found package pkgnum ". $cust_pkg->pkgnum. "\n"
1045 $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
1047 if ( ! @cust_svc ) {
1048 return 'No account found to apply pre-paid time';
1049 } elsif ( scalar(@cust_svc) > 1 ) {
1050 return 'Multiple accounts found to apply pre-paid time';
1053 my $svc_acct = $cust_svc[0]->svc_x;
1054 warn " found service svcnum ". $svc_acct->pkgnum.
1055 ' ('. $svc_acct->email. ")\n"
1058 $column = "increment_$column";
1059 $svc_acct->$column($amount);
1063 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
1065 Inserts a prepayment in the specified amount for this customer. An optional
1066 second argument can specify the prepayment identifier for tracking purposes.
1067 If there is an error, returns the error, otherwise returns false.
1071 sub insert_cust_pay_prepay {
1072 shift->insert_cust_pay('PREP', @_);
1075 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
1077 Inserts a cash payment in the specified amount for this customer. An optional
1078 second argument can specify the payment identifier for tracking purposes.
1079 If there is an error, returns the error, otherwise returns false.
1083 sub insert_cust_pay_cash {
1084 shift->insert_cust_pay('CASH', @_);
1087 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
1089 Inserts a Western Union payment in the specified amount for this customer. An
1090 optional second argument can specify the prepayment identifier for tracking
1091 purposes. If there is an error, returns the error, otherwise returns false.
1095 sub insert_cust_pay_west {
1096 shift->insert_cust_pay('WEST', @_);
1099 sub insert_cust_pay {
1100 my( $self, $payby, $amount ) = splice(@_, 0, 3);
1101 my $payinfo = scalar(@_) ? shift : '';
1103 my $cust_pay = new FS::cust_pay {
1104 'custnum' => $self->custnum,
1105 'paid' => sprintf('%.2f', $amount),
1106 #'_date' => #date the prepaid card was purchased???
1108 'payinfo' => $payinfo,
1114 =item delete [ OPTION => VALUE ... ]
1116 This deletes the customer. If there is an error, returns the error, otherwise
1119 This will completely remove all traces of the customer record. This is not
1120 what you want when a customer cancels service; for that, cancel all of the
1121 customer's packages (see L</cancel>).
1123 If the customer has any uncancelled packages, you need to pass a new (valid)
1124 customer number for those packages to be transferred to, as the "new_customer"
1125 option. Cancelled packages will be deleted. Did I mention that this is NOT
1126 what you want when a customer cancels service and that you really should be
1127 looking at L<FS::cust_pkg/cancel>?
1129 You can't delete a customer with invoices (see L<FS::cust_bill>),
1130 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1131 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1132 set the "delete_financials" option to a true value.
1137 my( $self, %opt ) = @_;
1139 local $SIG{HUP} = 'IGNORE';
1140 local $SIG{INT} = 'IGNORE';
1141 local $SIG{QUIT} = 'IGNORE';
1142 local $SIG{TERM} = 'IGNORE';
1143 local $SIG{TSTP} = 'IGNORE';
1144 local $SIG{PIPE} = 'IGNORE';
1146 my $oldAutoCommit = $FS::UID::AutoCommit;
1147 local $FS::UID::AutoCommit = 0;
1150 if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1151 $dbh->rollback if $oldAutoCommit;
1152 return "Can't delete a master agent customer";
1155 #use FS::access_user
1156 if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1157 $dbh->rollback if $oldAutoCommit;
1158 return "Can't delete a master employee customer";
1161 tie my %financial_tables, 'Tie::IxHash',
1162 'cust_bill' => 'invoices',
1163 'cust_statement' => 'statements',
1164 'cust_credit' => 'credits',
1165 'cust_pay' => 'payments',
1166 'cust_refund' => 'refunds',
1169 foreach my $table ( keys %financial_tables ) {
1171 my @records = $self->$table();
1173 if ( @records && ! $opt{'delete_financials'} ) {
1174 $dbh->rollback if $oldAutoCommit;
1175 return "Can't delete a customer with ". $financial_tables{$table};
1178 foreach my $record ( @records ) {
1179 my $error = $record->delete;
1181 $dbh->rollback if $oldAutoCommit;
1182 return "Error deleting ". $financial_tables{$table}. ": $error\n";
1188 my @cust_pkg = $self->ncancelled_pkgs;
1190 my $new_custnum = $opt{'new_custnum'};
1191 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1192 $dbh->rollback if $oldAutoCommit;
1193 return "Invalid new customer number: $new_custnum";
1195 foreach my $cust_pkg ( @cust_pkg ) {
1196 my %hash = $cust_pkg->hash;
1197 $hash{'custnum'} = $new_custnum;
1198 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1199 my $error = $new_cust_pkg->replace($cust_pkg,
1200 options => { $cust_pkg->options },
1203 $dbh->rollback if $oldAutoCommit;
1208 my @cancelled_cust_pkg = $self->all_pkgs;
1209 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1210 my $error = $cust_pkg->delete;
1212 $dbh->rollback if $oldAutoCommit;
1217 #cust_tax_adjustment in financials?
1218 #cust_pay_pending? ouch
1219 foreach my $table (qw(
1220 cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1221 cust_payby cust_location cust_main_note cust_tax_adjustment
1222 cust_pay_void cust_pay_batch queue cust_tax_exempt
1224 foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1225 my $error = $record->delete;
1227 $dbh->rollback if $oldAutoCommit;
1233 my $sth = $dbh->prepare(
1234 'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1236 my $errstr = $dbh->errstr;
1237 $dbh->rollback if $oldAutoCommit;
1240 $sth->execute($self->custnum) or do {
1241 my $errstr = $sth->errstr;
1242 $dbh->rollback if $oldAutoCommit;
1248 my $ticket_dbh = '';
1249 if ($conf->config('ticket_system') eq 'RT_Internal') {
1251 } elsif ($conf->config('ticket_system') eq 'RT_External') {
1252 my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1253 $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1254 #or die "RT_External DBI->connect error: $DBI::errstr\n";
1257 if ( $ticket_dbh ) {
1259 my $ticket_sth = $ticket_dbh->prepare(
1260 'DELETE FROM Links WHERE Target = ?'
1262 my $errstr = $ticket_dbh->errstr;
1263 $dbh->rollback if $oldAutoCommit;
1266 $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1268 my $errstr = $ticket_sth->errstr;
1269 $dbh->rollback if $oldAutoCommit;
1273 #check and see if the customer is the only link on the ticket, and
1274 #if so, set the ticket to deleted status in RT?
1275 #maybe someday, for now this will at least fix tickets not displaying
1279 #delete the customer record
1281 my $error = $self->SUPER::delete;
1283 $dbh->rollback if $oldAutoCommit;
1287 # cust_main exports!
1289 #my $export_args = $options{'export_args'} || [];
1292 map qsearch( 'part_export', {exportnum=>$_} ),
1293 $conf->config('cust_main-exports'); #, $agentnum
1295 foreach my $part_export ( @part_export ) {
1296 my $error = $part_export->export_delete( $self ); #, @$export_args);
1298 $dbh->rollback if $oldAutoCommit;
1299 return "exporting to ". $part_export->exporttype.
1300 " (transaction rolled back): $error";
1304 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1309 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1311 Replaces the OLD_RECORD with this one in the database. If there is an error,
1312 returns the error, otherwise returns false.
1314 To change the customer's address, set the pseudo-fields C<bill_location> and
1315 C<ship_location>. The address will still only change if at least one of the
1316 address fields differs from the existing values.
1318 INVOICING_LIST_ARYREF: If you pass an arrayref to this method, it will be
1319 set as the contact email address for a default contact with the same name as
1322 Currently available options are: I<tax_exemption>, I<cust_payby_params>,
1323 I<contact_params>, I<invoicing_list>.
1325 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1326 of tax names and exemption numbers. FS::cust_main_exemption records will be
1327 deleted and inserted as appropriate.
1329 I<cust_payby_params> and I<contact_params> can be hashrefs of named parameter
1330 groups (describing the customer's payment methods and contacts, respectively)
1331 in the style supported by L<FS::o2m_Common/process_o2m>. See L<FS::cust_payby>
1332 and L<FS::contact> for the fields these can contain.
1334 I<invoicing_list> is a synonym for the INVOICING_LIST_ARYREF parameter, and
1335 should be used instead if possible.
1342 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1344 : $self->replace_old;
1348 warn "$me replace called\n"
1351 my $curuser = $FS::CurrentUser::CurrentUser;
1352 return "You are not permitted to create complimentary accounts."
1353 if $self->complimentary eq 'Y'
1354 && $self->complimentary ne $old->complimentary
1355 && ! $curuser->access_right('Complimentary customer');
1357 local($ignore_expired_card) = 1
1358 if $old->payby =~ /^(CARD|DCRD)$/
1359 && $self->payby =~ /^(CARD|DCRD)$/
1360 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1362 local($ignore_banned_card) = 1
1363 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1364 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1365 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1367 if ( $self->payby =~ /^(CARD|DCRD)$/
1368 && $old->payinfo ne $self->payinfo
1369 && $old->paymask ne $self->paymask )
1371 my $error = $self->check_payinfo_cardtype;
1372 return $error if $error;
1375 return "Invoicing locale is required"
1378 && $conf->exists('cust_main-require_locale');
1380 local $SIG{HUP} = 'IGNORE';
1381 local $SIG{INT} = 'IGNORE';
1382 local $SIG{QUIT} = 'IGNORE';
1383 local $SIG{TERM} = 'IGNORE';
1384 local $SIG{TSTP} = 'IGNORE';
1385 local $SIG{PIPE} = 'IGNORE';
1387 my $oldAutoCommit = $FS::UID::AutoCommit;
1388 local $FS::UID::AutoCommit = 0;
1391 for my $l (qw(bill_location ship_location)) {
1392 #my $old_loc = $old->$l;
1393 my $new_loc = $self->$l or next;
1395 # find the existing location if there is one
1396 $new_loc->set('custnum' => $self->custnum);
1397 my $error = $new_loc->find_or_insert;
1399 $dbh->rollback if $oldAutoCommit;
1402 $self->set($l.'num', $new_loc->locationnum);
1406 if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1407 warn "cust_main::replace: using deprecated invoicing list argument";
1408 $invoicing_list = shift @param;
1411 my %options = @param;
1413 $invoicing_list ||= $options{invoicing_list};
1415 my @contacts = map { $_->contact } $self->cust_contact;
1416 # find a contact that matches the customer's name
1417 my ($implicit_contact) = grep { $_->first eq $old->get('first')
1418 and $_->last eq $old->get('last') }
1420 $implicit_contact ||= FS::contact->new({
1421 'custnum' => $self->custnum,
1422 'locationnum' => $self->get('bill_locationnum'),
1425 # for any of these that are already contact emails, link to the existing
1427 if ( $invoicing_list ) {
1430 # kind of like process_m2m on these, except:
1431 # - the other side is two tables in a join
1432 # - and we might have to create new contact_emails
1433 # - and possibly a new contact
1435 # Find existing invoice emails that aren't on the implicit contact.
1436 # Any of these that are not on the new invoicing list will be removed.
1437 my %old_email_cust_contact;
1438 foreach my $cust_contact ($self->cust_contact) {
1439 next if !$cust_contact->invoice_dest;
1440 next if $cust_contact->contactnum == ($implicit_contact->contactnum || 0);
1442 foreach my $contact_email ($cust_contact->contact->contact_email) {
1443 $old_email_cust_contact{ $contact_email->emailaddress } = $cust_contact;
1447 foreach my $dest (@$invoicing_list) {
1449 if ($dest eq 'POST') {
1451 $self->set('postal_invoice', 'Y');
1453 } elsif ( exists($old_email_cust_contact{$dest}) ) {
1455 delete $old_email_cust_contact{$dest}; # don't need to remove it, then
1459 # See if it belongs to some other contact; if so, link it.
1460 my $contact_email = qsearchs('contact_email', { emailaddress => $dest });
1462 and $contact_email->contactnum != ($implicit_contact->contactnum || 0) ) {
1463 my $cust_contact = qsearchs('cust_contact', {
1464 contactnum => $contact_email->contactnum,
1465 custnum => $self->custnum,
1466 }) || FS::cust_contact->new({
1467 contactnum => $contact_email->contactnum,
1468 custnum => $self->custnum,
1470 $cust_contact->set('invoice_dest', 'Y');
1471 my $error = $cust_contact->custcontactnum ?
1472 $cust_contact->replace : $cust_contact->insert;
1474 $dbh->rollback if $oldAutoCommit;
1475 return "$error (linking to email address $dest)";
1479 # This email address is not yet linked to any contact, so it will
1480 # be added to the implicit contact.
1481 $email .= ',' if length($email);
1487 foreach my $remove_dest (keys %old_email_cust_contact) {
1488 my $cust_contact = $old_email_cust_contact{$remove_dest};
1489 # These were not in the list of requested destinations, so take them off.
1490 $cust_contact->set('invoice_dest', '');
1491 my $error = $cust_contact->replace;
1493 $dbh->rollback if $oldAutoCommit;
1494 return "$error (unlinking email address $remove_dest)";
1498 # make sure it keeps up with the changed customer name, if any
1499 $implicit_contact->set('last', $self->get('last'));
1500 $implicit_contact->set('first', $self->get('first'));
1501 $implicit_contact->set('emailaddress', $email);
1502 $implicit_contact->set('invoice_dest', 'Y');
1503 $implicit_contact->set('custnum', $self->custnum);
1506 if ( $implicit_contact->contactnum ) {
1507 $error = $implicit_contact->replace;
1508 } elsif ( length($email) ) { # don't create a new contact if not needed
1509 $error = $implicit_contact->insert;
1513 $dbh->rollback if $oldAutoCommit;
1514 return "$error (adding email address $email)";
1519 # replace the customer record
1520 my $error = $self->SUPER::replace($old);
1523 $dbh->rollback if $oldAutoCommit;
1527 # now move packages to the new service location
1528 $self->set('ship_location', ''); #flush cache
1529 if ( $old->ship_locationnum and # should only be null during upgrade...
1530 $old->ship_locationnum != $self->ship_locationnum ) {
1531 $error = $old->ship_location->move_to($self->ship_location);
1533 $dbh->rollback if $oldAutoCommit;
1537 # don't move packages based on the billing location, but
1538 # disable it if it's no longer in use
1539 if ( $old->bill_locationnum and
1540 $old->bill_locationnum != $self->bill_locationnum ) {
1541 $error = $old->bill_location->disable_if_unused;
1543 $dbh->rollback if $oldAutoCommit;
1548 if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1550 #this could be more efficient than deleting and re-inserting, if it matters
1551 foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1552 my $error = $cust_tag->delete;
1554 $dbh->rollback if $oldAutoCommit;
1558 foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1559 my $cust_tag = new FS::cust_tag { 'tagnum' => $tagnum,
1560 'custnum' => $self->custnum };
1561 my $error = $cust_tag->insert;
1563 $dbh->rollback if $oldAutoCommit;
1570 my $tax_exemption = delete $options{'tax_exemption'};
1571 if ( $tax_exemption ) {
1573 $tax_exemption = { map { $_ => '' } @$tax_exemption }
1574 if ref($tax_exemption) eq 'ARRAY';
1576 my %cust_main_exemption =
1577 map { $_->taxname => $_ }
1578 qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1580 foreach my $taxname ( keys %$tax_exemption ) {
1582 if ( $cust_main_exemption{$taxname} &&
1583 $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1586 delete $cust_main_exemption{$taxname};
1590 my $cust_main_exemption = new FS::cust_main_exemption {
1591 'custnum' => $self->custnum,
1592 'taxname' => $taxname,
1593 'exempt_number' => $tax_exemption->{$taxname},
1595 my $error = $cust_main_exemption->insert;
1597 $dbh->rollback if $oldAutoCommit;
1598 return "inserting cust_main_exemption (transaction rolled back): $error";
1602 foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1603 my $error = $cust_main_exemption->delete;
1605 $dbh->rollback if $oldAutoCommit;
1606 return "deleting cust_main_exemption (transaction rolled back): $error";
1612 if ( my $cust_payby_params = delete $options{'cust_payby_params'} ) {
1614 my $error = $self->process_o2m(
1615 'table' => 'cust_payby',
1616 'fields' => FS::cust_payby->cgi_cust_payby_fields,
1617 'params' => $cust_payby_params,
1618 'hash_callback' => \&FS::cust_payby::cgi_hash_callback,
1621 $dbh->rollback if $oldAutoCommit;
1627 if ( my $contact_params = delete $options{'contact_params'} ) {
1629 # this can potentially replace contacts that were created by the
1630 # invoicing list argument, but the UI shouldn't allow both of them
1633 my $error = $self->process_o2m(
1634 'table' => 'contact',
1635 'fields' => FS::contact->cgi_contact_fields,
1636 'params' => $contact_params,
1639 $dbh->rollback if $oldAutoCommit;
1645 unless ( $import || $skip_fuzzyfiles ) {
1646 $error = $self->queue_fuzzyfiles_update;
1648 $dbh->rollback if $oldAutoCommit;
1649 return "updating fuzzy search cache: $error";
1653 # tax district update in cust_location
1655 # cust_main exports!
1657 my $export_args = $options{'export_args'} || [];
1660 map qsearch( 'part_export', {exportnum=>$_} ),
1661 $conf->config('cust_main-exports'); #, $agentnum
1663 foreach my $part_export ( @part_export ) {
1664 my $error = $part_export->export_replace( $self, $old, @$export_args);
1666 $dbh->rollback if $oldAutoCommit;
1667 return "exporting to ". $part_export->exporttype.
1668 " (transaction rolled back): $error";
1672 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1677 =item queue_fuzzyfiles_update
1679 Used by insert & replace to update the fuzzy search cache
1683 use FS::cust_main::Search;
1684 sub queue_fuzzyfiles_update {
1687 local $SIG{HUP} = 'IGNORE';
1688 local $SIG{INT} = 'IGNORE';
1689 local $SIG{QUIT} = 'IGNORE';
1690 local $SIG{TERM} = 'IGNORE';
1691 local $SIG{TSTP} = 'IGNORE';
1692 local $SIG{PIPE} = 'IGNORE';
1694 my $oldAutoCommit = $FS::UID::AutoCommit;
1695 local $FS::UID::AutoCommit = 0;
1698 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1699 my $queue = new FS::queue {
1700 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1702 my @args = "cust_main.$field", $self->get($field);
1703 my $error = $queue->insert( @args );
1705 $dbh->rollback if $oldAutoCommit;
1706 return "queueing job (transaction rolled back): $error";
1711 push @locations, $self->bill_location if $self->bill_locationnum;
1712 push @locations, $self->ship_location if @locations && $self->has_ship_address;
1713 foreach my $location (@locations) {
1714 my $queue = new FS::queue {
1715 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1717 my @args = 'cust_location.address1', $location->address1;
1718 my $error = $queue->insert( @args );
1720 $dbh->rollback if $oldAutoCommit;
1721 return "queueing job (transaction rolled back): $error";
1725 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1732 Checks all fields to make sure this is a valid customer record. If there is
1733 an error, returns the error, otherwise returns false. Called by the insert
1734 and replace methods.
1741 warn "$me check BEFORE: \n". $self->_dump
1745 $self->ut_numbern('custnum')
1746 || $self->ut_number('agentnum')
1747 || $self->ut_textn('agent_custid')
1748 || $self->ut_number('refnum')
1749 || $self->ut_foreign_keyn('bill_locationnum', 'cust_location','locationnum')
1750 || $self->ut_foreign_keyn('ship_locationnum', 'cust_location','locationnum')
1751 || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1752 || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1753 || $self->ut_foreign_keyn('taxstatusnum', 'tax_status', 'taxstatusnum')
1754 || $self->ut_textn('custbatch')
1755 || $self->ut_name('last')
1756 || $self->ut_name('first')
1757 || $self->ut_snumbern('signupdate')
1758 || $self->ut_snumbern('birthdate')
1759 || $self->ut_namen('spouse_last')
1760 || $self->ut_namen('spouse_first')
1761 || $self->ut_snumbern('spouse_birthdate')
1762 || $self->ut_snumbern('anniversary_date')
1763 || $self->ut_textn('company')
1764 || $self->ut_textn('ship_company')
1765 || $self->ut_anything('comments')
1766 || $self->ut_numbern('referral_custnum')
1767 || $self->ut_textn('stateid')
1768 || $self->ut_textn('stateid_state')
1769 || $self->ut_textn('invoice_terms')
1770 || $self->ut_floatn('cdr_termination_percentage')
1771 || $self->ut_floatn('credit_limit')
1772 || $self->ut_numbern('billday')
1773 || $self->ut_numbern('prorate_day')
1774 || $self->ut_flag('edit_subject')
1775 || $self->ut_flag('calling_list_exempt')
1776 || $self->ut_flag('invoice_noemail')
1777 || $self->ut_flag('message_noemail')
1778 || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1779 || $self->ut_currencyn('currency')
1780 || $self->ut_textn('po_number')
1781 || $self->ut_enum('complimentary', [ '', 'Y' ])
1782 || $self->ut_flag('invoice_ship_address')
1783 || $self->ut_flag('invoice_dest')
1786 foreach (qw(company ship_company)) {
1787 my $company = $self->get($_);
1788 $company =~ s/^\s+//;
1789 $company =~ s/\s+$//;
1790 $company =~ s/\s+/ /g;
1791 $self->set($_, $company);
1794 #barf. need message catalogs. i18n. etc.
1795 $error .= "Please select an advertising source."
1796 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1797 return $error if $error;
1799 my $agent = qsearchs( 'agent', { 'agentnum' => $self->agentnum } )
1800 or return "Unknown agent";
1802 if ( $self->currency ) {
1803 my $agent_currency = qsearchs( 'agent_currency', {
1804 'agentnum' => $agent->agentnum,
1805 'currency' => $self->currency,
1807 or return "Agent ". $agent->agent.
1808 " not permitted to offer ". $self->currency. " invoicing";
1811 return "Unknown refnum"
1812 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1814 return "Unknown referring custnum: ". $self->referral_custnum
1815 unless ! $self->referral_custnum
1816 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1818 if ( $self->ss eq '' ) {
1823 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1824 or return "Illegal social security number: ". $self->ss;
1825 $self->ss("$1-$2-$3");
1828 #turn off invoice_ship_address if ship & bill are the same
1829 if ($self->bill_locationnum eq $self->ship_locationnum) {
1830 $self->invoice_ship_address('');
1833 # cust_main_county verification now handled by cust_location check
1836 $self->ut_phonen('daytime', $self->country)
1837 || $self->ut_phonen('night', $self->country)
1838 || $self->ut_phonen('fax', $self->country)
1839 || $self->ut_phonen('mobile', $self->country)
1841 return $error if $error;
1843 if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1845 && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1848 my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1850 : FS::Msgcat::_gettext('daytime');
1851 my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1853 : FS::Msgcat::_gettext('night');
1855 my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1857 : FS::Msgcat::_gettext('mobile');
1859 return "$daytime_label, $night_label or $mobile_label is required"
1863 return "Please select an invoicing locale"
1866 && $conf->exists('cust_main-require_locale');
1868 foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1869 $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1873 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
1875 warn "$me check AFTER: \n". $self->_dump
1878 $self->SUPER::check;
1881 sub check_payinfo_cardtype {
1884 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
1886 my $payinfo = $self->payinfo;
1887 $payinfo =~ s/\D//g;
1889 return '' if $payinfo =~ /^99\d{14}$/; #token
1891 my %bop_card_types = map { $_=>1 } values %{ card_types() };
1892 my $cardtype = cardtype($payinfo);
1894 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
1902 Additional checks for replace only.
1907 my ($new,$old) = @_;
1908 #preserve old value if global config is set
1909 if ($old && $conf->exists('invoice-ship_address')) {
1910 $new->invoice_ship_address($old->invoice_ship_address);
1917 Returns a list of fields which have ship_ duplicates.
1922 qw( last first company
1924 address1 address2 city county state zip country
1926 daytime night fax mobile
1930 =item has_ship_address
1932 Returns true if this customer record has a separate shipping address.
1936 sub has_ship_address {
1938 $self->bill_locationnum != $self->ship_locationnum;
1943 Returns a list of key/value pairs, with the following keys: address1,
1944 adddress2, city, county, state, zip, country, district, and geocode. The
1945 shipping address is used if present.
1951 $self->ship_location->location_hash;
1956 Returns all locations (see L<FS::cust_location>) for this customer.
1963 'table' => 'cust_location',
1964 'hashref' => { 'custnum' => $self->custnum,
1965 'prospectnum' => '',
1967 'order_by' => 'ORDER BY country, LOWER(state), LOWER(city), LOWER(county), LOWER(address1), LOWER(address2)',
1973 Returns all contact associations (see L<FS::cust_contact>) for this customer.
1979 qsearch('cust_contact', { 'custnum' => $self->custnum } );
1982 =item cust_payby PAYBY
1984 Returns all payment methods (see L<FS::cust_payby>) for this customer.
1986 If one or more PAYBY are specified, returns only payment methods for specified PAYBY.
1987 Does not validate PAYBY.
1995 'table' => 'cust_payby',
1996 'hashref' => { 'custnum' => $self->custnum },
1997 'order_by' => "ORDER BY payby IN ('CARD','CHEK') DESC, weight ASC",
1999 $search->{'extra_sql'} = ' AND payby IN ( '.
2000 join(',', map dbh->quote($_), @payby).
2007 =item has_cust_payby_auto
2009 Returns true if customer has an automatic payment method ('CARD' or 'CHEK')
2013 sub has_cust_payby_auto {
2016 'table' => 'cust_payby',
2017 'hashref' => { 'custnum' => $self->custnum, },
2018 'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
2019 'order_by' => 'LIMIT 1',
2026 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2027 and L<FS::cust_pkg>) for this customer, except those on hold.
2029 Returns a list: an empty list on success or a list of errors.
2035 grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2040 Unsuspends all suspended packages in the on-hold state (those without setup
2041 dates) for this customer.
2047 grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2052 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2054 Returns a list: an empty list on success or a list of errors.
2060 grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2063 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2065 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2066 PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref instead
2067 of a list of pkgparts; the hashref has the following keys:
2071 =item pkgparts - listref of pkgparts
2073 =item (other options are passed to the suspend method)
2078 Returns a list: an empty list on success or a list of errors.
2082 sub suspend_if_pkgpart {
2084 my (@pkgparts, %opt);
2085 if (ref($_[0]) eq 'HASH'){
2086 @pkgparts = @{$_[0]{pkgparts}};
2091 grep { $_->suspend(%opt) }
2092 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2093 $self->unsuspended_pkgs;
2096 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2098 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2099 given PKGPARTs (see L<FS::part_pkg>). Preferred usage is to pass a hashref
2100 instead of a list of pkgparts; the hashref has the following keys:
2104 =item pkgparts - listref of pkgparts
2106 =item (other options are passed to the suspend method)
2110 Returns a list: an empty list on success or a list of errors.
2114 sub suspend_unless_pkgpart {
2116 my (@pkgparts, %opt);
2117 if (ref($_[0]) eq 'HASH'){
2118 @pkgparts = @{$_[0]{pkgparts}};
2123 grep { $_->suspend(%opt) }
2124 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2125 $self->unsuspended_pkgs;
2128 =item cancel [ OPTION => VALUE ... ]
2130 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2131 The cancellation time will be now.
2135 Always returns a list: an empty list on success or a list of errors.
2142 warn "$me cancel called on customer ". $self->custnum. " with options ".
2143 join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2145 my @pkgs = $self->ncancelled_pkgs;
2147 $self->cancel_pkgs( %opt, 'cust_pkg' => \@pkgs );
2150 =item cancel_pkgs OPTIONS
2152 Cancels a specified list of packages. OPTIONS can include:
2156 =item cust_pkg - an arrayref of the packages. Required.
2158 =item time - the cancellation time, used to calculate final bills and
2159 unused-time credits if any. Will be passed through to the bill() and
2160 FS::cust_pkg::cancel() methods.
2162 =item quiet - can be set true to supress email cancellation notices.
2164 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a
2165 reasonnum of an existing reason, or passing a hashref will create a new reason.
2166 The hashref should have the following keys:
2167 typenum - Reason type (see L<FS::reason_type>)
2168 reason - Text of the new reason.
2170 =item cust_pkg_reason - can be an arrayref of L<FS::cust_pkg_reason> objects
2171 for the individual packages, parallel to the C<cust_pkg> argument. The
2172 reason and reason_otaker arguments will be taken from those objects.
2174 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2176 =item nobill - can be set true to skip billing if it might otherwise be done.
2181 my( $self, %opt ) = @_;
2183 # we're going to cancel services, which is not reversible
2184 die "cancel_pkgs cannot be run inside a transaction"
2185 if $FS::UID::AutoCommit == 0;
2187 local $FS::UID::AutoCommit = 0;
2189 return ( 'access denied' )
2190 unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2192 if ( $opt{'ban'} ) {
2194 foreach my $cust_payby ( $self->cust_payby ) {
2196 #well, if they didn't get decrypted on search, then we don't have to
2197 # try again... queue a job for the server that does have decryption
2198 # capability if we're in a paranoid multi-server implementation?
2199 return ( "Can't (yet) ban encrypted credit cards" )
2200 if $cust_payby->is_encrypted($cust_payby->payinfo);
2202 my $ban = new FS::banned_pay $cust_payby->_new_banned_pay_hashref;
2203 my $error = $ban->insert;
2213 my @pkgs = @{ delete $opt{'cust_pkg'} };
2214 my $cancel_time = $opt{'time'} || time;
2216 # bill all packages first, so we don't lose usage, service counts for
2217 # bulk billing, etc.
2218 if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2220 my $error = $self->bill( 'pkg_list' => [ @pkgs ],
2222 'time' => $cancel_time );
2224 warn "Error billing during cancel, custnum ". $self->custnum. ": $error";
2226 return ( "Error billing during cancellation: $error" );
2232 # try to cancel each service, the same way we would for individual packages,
2233 # but in cancel weight order.
2234 my @cust_svc = map { $_->cust_svc } @pkgs;
2235 my @sorted_cust_svc =
2237 sort { $a->[1] <=> $b->[1] }
2238 map { [ $_, $_->svc_x ? $_->svc_x->table_info->{'cancel_weight'} : -1 ]; } @cust_svc
2240 warn "$me removing ".scalar(@sorted_cust_svc)." service(s) for customer ".
2243 foreach my $cust_svc (@sorted_cust_svc) {
2244 my $part_svc = $cust_svc->part_svc;
2245 next if ( defined($part_svc) and $part_svc->preserve );
2246 # immediate cancel, no date option
2247 # transactionize individually
2248 my $error = try { $cust_svc->cancel } catch { $_ };
2251 push @errors, $error;
2260 warn "$me cancelling ". scalar(@pkgs) ." package(s) for customer ".
2261 $self->custnum. "\n"
2265 if ($opt{'cust_pkg_reason'}) {
2266 @cprs = @{ delete $opt{'cust_pkg_reason'} };
2272 my $cpr = shift @cprs;
2274 $lopt{'reason'} = $cpr->reasonnum;
2275 $lopt{'reason_otaker'} = $cpr->otaker;
2277 warn "no reason found when canceling package ".$_->pkgnum."\n";
2278 # we're not actually required to pass a reason to cust_pkg::cancel,
2279 # but if we're getting to this point, something has gone awry.
2280 $null_reason ||= FS::reason->new_or_existing(
2281 reason => 'unknown reason',
2282 type => 'Cancel Reason',
2285 $lopt{'reason'} = $null_reason->reasonnum;
2286 $lopt{'reason_otaker'} = $FS::CurrentUser::CurrentUser->username;
2289 my $error = $_->cancel(%lopt);
2292 push @errors, 'pkgnum '.$_->pkgnum.': '.$error;
2301 sub _banned_pay_hashref {
2302 die 'cust_main->_banned_pay_hashref deprecated';
2314 'payby' => $payby2ban{$self->payby},
2315 'payinfo' => $self->payinfo,
2316 #don't ever *search* on reason! #'reason' =>
2322 Returns all notes (see L<FS::cust_main_note>) for this customer.
2327 my($self,$orderby_classnum) = (shift,shift);
2328 my $orderby = "sticky DESC, _date DESC";
2329 $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2330 qsearch( 'cust_main_note',
2331 { 'custnum' => $self->custnum },
2333 "ORDER BY $orderby",
2339 Returns the agent (see L<FS::agent>) for this customer.
2343 Returns the agent name (see L<FS::agent>) for this customer.
2349 $self->agent->agent;
2354 Returns any tags associated with this customer, as FS::cust_tag objects,
2355 or an empty list if there are no tags.
2359 Returns any tags associated with this customer, as FS::part_tag objects,
2360 or an empty list if there are no tags.
2366 map $_->part_tag, $self->cust_tag;
2372 Returns the customer class, as an FS::cust_class object, or the empty string
2373 if there is no customer class.
2377 Returns the customer category name, or the empty string if there is no customer
2384 my $cust_class = $self->cust_class;
2386 ? $cust_class->categoryname
2392 Returns the customer class name, or the empty string if there is no customer
2399 my $cust_class = $self->cust_class;
2401 ? $cust_class->classname
2407 Returns the external tax status, as an FS::tax_status object, or the empty
2408 string if there is no tax status.
2414 if ( $self->taxstatusnum ) {
2415 qsearchs('tax_status', { 'taxstatusnum' => $self->taxstatusnum } );
2423 Returns the tax status code if there is one.
2429 my $tax_status = $self->tax_status;
2431 ? $tax_status->taxstatus
2435 =item BILLING METHODS
2437 Documentation on billing methods has been moved to
2438 L<FS::cust_main::Billing>.
2440 =item REALTIME BILLING METHODS
2442 Documentation on realtime billing methods has been moved to
2443 L<FS::cust_main::Billing_Realtime>.
2447 Removes the I<paycvv> field from the database directly.
2449 If there is an error, returns the error, otherwise returns false.
2451 DEPRECATED. Use L</remove_cvv_from_cust_payby> instead.
2456 die 'cust_main->remove_cvv deprecated';
2458 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2459 or return dbh->errstr;
2460 $sth->execute($self->custnum)
2461 or return $sth->errstr;
2468 Returns the total owed for this customer on all invoices
2469 (see L<FS::cust_bill/owed>).
2475 $self->total_owed_date(2145859200); #12/31/2037
2478 =item total_owed_date TIME
2480 Returns the total owed for this customer on all invoices with date earlier than
2481 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2482 see L<Time::Local> and L<Date::Parse> for conversion functions.
2486 sub total_owed_date {
2490 my $custnum = $self->custnum;
2492 my $owed_sql = FS::cust_bill->owed_sql;
2495 SELECT SUM($owed_sql) FROM cust_bill
2496 WHERE custnum = $custnum
2500 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2504 =item total_owed_pkgnum PKGNUM
2506 Returns the total owed on all invoices for this customer's specific package
2507 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2511 sub total_owed_pkgnum {
2512 my( $self, $pkgnum ) = @_;
2513 $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2516 =item total_owed_date_pkgnum TIME PKGNUM
2518 Returns the total owed for this customer's specific package when using
2519 experimental package balances on all invoices with date earlier than
2520 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2521 see L<Time::Local> and L<Date::Parse> for conversion functions.
2525 sub total_owed_date_pkgnum {
2526 my( $self, $time, $pkgnum ) = @_;
2529 foreach my $cust_bill (
2530 grep { $_->_date <= $time }
2531 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2533 $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2535 sprintf( "%.2f", $total_bill );
2541 Returns the total amount of all payments.
2548 $total += $_->paid foreach $self->cust_pay;
2549 sprintf( "%.2f", $total );
2552 =item total_unapplied_credits
2554 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2555 customer. See L<FS::cust_credit/credited>.
2557 =item total_credited
2559 Old name for total_unapplied_credits. Don't use.
2563 sub total_credited {
2564 #carp "total_credited deprecated, use total_unapplied_credits";
2565 shift->total_unapplied_credits(@_);
2568 sub total_unapplied_credits {
2571 my $custnum = $self->custnum;
2573 my $unapplied_sql = FS::cust_credit->unapplied_sql;
2576 SELECT SUM($unapplied_sql) FROM cust_credit
2577 WHERE custnum = $custnum
2580 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2584 =item total_unapplied_credits_pkgnum PKGNUM
2586 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2587 customer. See L<FS::cust_credit/credited>.
2591 sub total_unapplied_credits_pkgnum {
2592 my( $self, $pkgnum ) = @_;
2593 my $total_credit = 0;
2594 $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2595 sprintf( "%.2f", $total_credit );
2599 =item total_unapplied_payments
2601 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2602 See L<FS::cust_pay/unapplied>.
2606 sub total_unapplied_payments {
2609 my $custnum = $self->custnum;
2611 my $unapplied_sql = FS::cust_pay->unapplied_sql;
2614 SELECT SUM($unapplied_sql) FROM cust_pay
2615 WHERE custnum = $custnum
2618 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2622 =item total_unapplied_payments_pkgnum PKGNUM
2624 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2625 specific package when using experimental package balances. See
2626 L<FS::cust_pay/unapplied>.
2630 sub total_unapplied_payments_pkgnum {
2631 my( $self, $pkgnum ) = @_;
2632 my $total_unapplied = 0;
2633 $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2634 sprintf( "%.2f", $total_unapplied );
2638 =item total_unapplied_refunds
2640 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2641 customer. See L<FS::cust_refund/unapplied>.
2645 sub total_unapplied_refunds {
2647 my $custnum = $self->custnum;
2649 my $unapplied_sql = FS::cust_refund->unapplied_sql;
2652 SELECT SUM($unapplied_sql) FROM cust_refund
2653 WHERE custnum = $custnum
2656 sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2662 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2663 total_unapplied_credits minus total_unapplied_payments).
2669 $self->balance_date_range;
2672 =item balance_date TIME
2674 Returns the balance for this customer, only considering invoices with date
2675 earlier than TIME (total_owed_date minus total_credited minus
2676 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2677 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2684 $self->balance_date_range(shift);
2687 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2689 Returns the balance for this customer, optionally considering invoices with
2690 date earlier than START_TIME, and not later than END_TIME
2691 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2693 Times are specified as SQL fragments or numeric
2694 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
2695 L<Date::Parse> for conversion functions. The empty string can be passed
2696 to disable that time constraint completely.
2698 Accepts the same options as L<balance_date_sql>:
2702 =item unapplied_date
2704 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)
2708 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
2709 time will be ignored. Note that START_TIME and END_TIME only limit the date
2710 range for invoices and I<unapplied> payments, credits, and refunds.
2716 sub balance_date_range {
2718 my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2719 ') FROM cust_main WHERE custnum='. $self->custnum;
2720 sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2723 =item balance_pkgnum PKGNUM
2725 Returns the balance for this customer's specific package when using
2726 experimental package balances (total_owed plus total_unrefunded, minus
2727 total_unapplied_credits minus total_unapplied_payments)
2731 sub balance_pkgnum {
2732 my( $self, $pkgnum ) = @_;
2735 $self->total_owed_pkgnum($pkgnum)
2736 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2737 # + $self->total_unapplied_refunds_pkgnum($pkgnum)
2738 - $self->total_unapplied_credits_pkgnum($pkgnum)
2739 - $self->total_unapplied_payments_pkgnum($pkgnum)
2745 Returns a hash of useful information for making a payment.
2755 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2756 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2757 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2761 For credit card transactions:
2773 For electronic check transactions:
2783 #XXX i need to be updated for 4.x+
2789 $return{balance} = $self->balance;
2791 $return{payname} = $self->payname
2792 || ( $self->first. ' '. $self->get('last') );
2794 $return{$_} = $self->bill_location->$_
2795 for qw(address1 address2 city state zip);
2797 $return{payby} = $self->payby;
2798 $return{stateid_state} = $self->stateid_state;
2800 if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2801 $return{card_type} = cardtype($self->payinfo);
2802 $return{payinfo} = $self->paymask;
2804 @return{'month', 'year'} = $self->paydate_monthyear;
2808 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2809 my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2810 $return{payinfo1} = $payinfo1;
2811 $return{payinfo2} = $payinfo2;
2812 $return{paytype} = $self->paytype;
2813 $return{paystate} = $self->paystate;
2817 #doubleclick protection
2819 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2827 Returns the next payment expiration date for this customer. If they have no
2828 payment methods that will expire, returns 0.
2834 # filter out the ones that individually return 0, but then return 0 if
2835 # there are no results
2836 my @epochs = grep { $_ > 0 } map { $_->paydate_epoch } $self->cust_payby;
2837 min( @epochs ) || 0;
2840 =item paydate_epoch_sql
2842 Returns an SQL expression to get the next payment expiration date for a
2843 customer. Returns 2143260000 (2037-12-01) if there are no payment expiration
2844 dates, so that it's safe to test for "will it expire before date X" for any
2849 sub paydate_epoch_sql {
2851 my $paydate = FS::cust_payby->paydate_epoch_sql;
2852 "(SELECT COALESCE(MIN($paydate), 2143260000) FROM cust_payby WHERE cust_payby.custnum = cust_main.custnum)";
2856 my( $self, $taxname ) = @_;
2858 qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2859 'taxname' => $taxname,
2864 =item cust_main_exemption
2866 =item invoicing_list
2868 Returns a list of email addresses (with svcnum entries expanded), and the word
2869 'POST' if the customer receives postal invoices.
2873 sub invoicing_list {
2874 my( $self, $arrayref ) = @_;
2877 warn "FS::cust_main::invoicing_list(ARRAY) is no longer supported.";
2880 my @emails = $self->invoicing_list_emailonly;
2881 push @emails, 'POST' if $self->get('postal_invoice');
2886 =item check_invoicing_list ARRAYREF
2888 Checks these arguements as valid input for the invoicing_list method. If there
2889 is an error, returns the error, otherwise returns false.
2893 sub check_invoicing_list {
2894 my( $self, $arrayref ) = @_;
2896 foreach my $address ( @$arrayref ) {
2898 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2899 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2902 my $cust_main_invoice = new FS::cust_main_invoice ( {
2903 'custnum' => $self->custnum,
2906 my $error = $self->custnum
2907 ? $cust_main_invoice->check
2908 : $cust_main_invoice->checkdest
2910 return $error if $error;
2914 return "Email address required"
2915 if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
2916 && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
2923 Returns the email addresses of all accounts provisioned for this customer.
2930 foreach my $cust_pkg ( $self->all_pkgs ) {
2931 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2933 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2934 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2936 $list{$_}=1 foreach map { $_->email } @svc_acct;
2941 =item invoicing_list_addpost
2943 Adds postal invoicing to this customer. If this customer is already configured
2944 to receive postal invoices, does nothing.
2948 sub invoicing_list_addpost {
2950 if ( $self->get('postal_invoice') eq '' ) {
2951 $self->set('postal_invoice', 'Y');
2952 my $error = $self->replace;
2953 warn $error if $error; # should fail harder, but this is traditional
2957 =item invoicing_list_emailonly
2959 Returns the list of email invoice recipients (invoicing_list without non-email
2960 destinations such as POST and FAX).
2964 sub invoicing_list_emailonly {
2966 warn "$me invoicing_list_emailonly called"
2968 return () if !$self->custnum; # not yet inserted
2969 return map { $_->emailaddress }
2971 table => 'cust_contact',
2972 select => 'emailaddress',
2973 addl_from => ' JOIN contact USING (contactnum) '.
2974 ' JOIN contact_email USING (contactnum)',
2975 hashref => { 'custnum' => $self->custnum, },
2976 extra_sql => q( AND cust_contact.invoice_dest = 'Y'),
2980 =item invoicing_list_emailonly_scalar
2982 Returns the list of email invoice recipients (invoicing_list without non-email
2983 destinations such as POST and FAX) as a comma-separated scalar.
2987 sub invoicing_list_emailonly_scalar {
2989 warn "$me invoicing_list_emailonly_scalar called"
2991 join(', ', $self->invoicing_list_emailonly);
2994 =item contact_list [ CLASSNUM, ... ]
2996 Returns a list of contacts (L<FS::contact> objects) for the customer. If
2997 a list of contact classnums is given, returns only contacts in those
2998 classes. If the pseudo-classnum 'invoice' is given, returns contacts that
2999 are marked as invoice destinations. If '0' is given, also returns contacts
3002 If no arguments are given, returns all contacts for the customer.
3010 select => 'contact.*, cust_contact.invoice_dest',
3011 addl_from => ' JOIN cust_contact USING (contactnum)',
3012 extra_sql => ' WHERE cust_contact.custnum = '.$self->custnum,
3018 if ( $_ eq 'invoice' ) {
3019 push @orwhere, 'cust_contact.invoice_dest = \'Y\'';
3020 } elsif ( $_ eq '0' ) {
3021 push @orwhere, 'cust_contact.classnum is null';
3022 } elsif ( /^\d+$/ ) {
3023 push @classnums, $_;
3025 die "bad classnum argument '$_'";
3030 push @orwhere, 'cust_contact.classnum IN ('.join(',', @classnums).')';
3033 $search->{extra_sql} .= ' AND (' .
3034 join(' OR ', map "( $_ )", @orwhere) .
3041 =item contact_list_email [ CLASSNUM, ... ]
3043 Same as L</contact_list>, but returns email destinations instead of contact
3048 sub contact_list_email {
3050 my @contacts = $self->contact_list(@_);
3052 foreach my $contact (@contacts) {
3053 foreach my $contact_email ($contact->contact_email) {
3055 $contact->firstlast . ' <' . $contact_email->emailaddress . '>';
3061 =item referral_custnum_cust_main
3063 Returns the customer who referred this customer (or the empty string, if
3064 this customer was not referred).
3066 Note the difference with referral_cust_main method: This method,
3067 referral_custnum_cust_main returns the single customer (if any) who referred
3068 this customer, while referral_cust_main returns an array of customers referred
3073 sub referral_custnum_cust_main {
3075 return '' unless $self->referral_custnum;
3076 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3079 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3081 Returns an array of customers referred by this customer (referral_custnum set
3082 to this custnum). If DEPTH is given, recurses up to the given depth, returning
3083 customers referred by customers referred by this customer and so on, inclusive.
3084 The default behavior is DEPTH 1 (no recursion).
3086 Note the difference with referral_custnum_cust_main method: This method,
3087 referral_cust_main, returns an array of customers referred BY this customer,
3088 while referral_custnum_cust_main returns the single customer (if any) who
3089 referred this customer.
3093 sub referral_cust_main {
3095 my $depth = @_ ? shift : 1;
3096 my $exclude = @_ ? shift : {};
3099 map { $exclude->{$_->custnum}++; $_; }
3100 grep { ! $exclude->{ $_->custnum } }
3101 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3105 map { $_->referral_cust_main($depth-1, $exclude) }
3112 =item referral_cust_main_ncancelled
3114 Same as referral_cust_main, except only returns customers with uncancelled
3119 sub referral_cust_main_ncancelled {
3121 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3124 =item referral_cust_pkg [ DEPTH ]
3126 Like referral_cust_main, except returns a flat list of all unsuspended (and
3127 uncancelled) packages for each customer. The number of items in this list may
3128 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3132 sub referral_cust_pkg {
3134 my $depth = @_ ? shift : 1;
3136 map { $_->unsuspended_pkgs }
3137 grep { $_->unsuspended_pkgs }
3138 $self->referral_cust_main($depth);
3141 =item referring_cust_main
3143 Returns the single cust_main record for the customer who referred this customer
3144 (referral_custnum), or false.
3148 sub referring_cust_main {
3150 return '' unless $self->referral_custnum;
3151 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3154 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3156 Applies a credit to this customer. If there is an error, returns the error,
3157 otherwise returns false.
3159 REASON can be a text string, an FS::reason object, or a scalar reference to
3160 a reasonnum. If a text string, it will be automatically inserted as a new
3161 reason, and a 'reason_type' option must be passed to indicate the
3162 FS::reason_type for the new reason.
3164 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3165 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3166 I<commission_pkgnum>.
3168 Any other options are passed to FS::cust_credit::insert.
3173 my( $self, $amount, $reason, %options ) = @_;
3175 my $cust_credit = new FS::cust_credit {
3176 'custnum' => $self->custnum,
3177 'amount' => $amount,
3180 if ( ref($reason) ) {
3182 if ( ref($reason) eq 'SCALAR' ) {
3183 $cust_credit->reasonnum( $$reason );
3185 $cust_credit->reasonnum( $reason->reasonnum );
3189 $cust_credit->set('reason', $reason)
3192 $cust_credit->$_( delete $options{$_} )
3193 foreach grep exists($options{$_}),
3194 qw( addlinfo eventnum ),
3195 map "commission_$_", qw( agentnum salesnum pkgnum );
3197 $cust_credit->insert(%options);
3201 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3203 Creates a one-time charge for this customer. If there is an error, returns
3204 the error, otherwise returns false.
3206 New-style, with a hashref of options:
3208 my $error = $cust_main->charge(
3212 'start_date' => str2time('7/4/2009'),
3213 'pkg' => 'Description',
3214 'comment' => 'Comment',
3215 'additional' => [], #extra invoice detail
3216 'classnum' => 1, #pkg_class
3218 'setuptax' => '', # or 'Y' for tax exempt
3220 'locationnum'=> 1234, # optional
3223 'taxclass' => 'Tax class',
3226 'taxproduct' => 2, #part_pkg_taxproduct
3227 'override' => {}, #XXX describe
3229 #will be filled in with the new object
3230 'cust_pkg_ref' => \$cust_pkg,
3232 #generate an invoice immediately
3234 'invoice_terms' => '', #with these terms
3240 my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3244 #super false laziness w/quotation::charge
3247 my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3248 my ( $pkg, $comment, $additional );
3249 my ( $setuptax, $taxclass ); #internal taxes
3250 my ( $taxproduct, $override ); #vendor (CCH) taxes
3252 my $separate_bill = '';
3253 my $cust_pkg_ref = '';
3254 my ( $bill_now, $invoice_terms ) = ( 0, '' );
3256 if ( ref( $_[0] ) ) {
3257 $amount = $_[0]->{amount};
3258 $setup_cost = $_[0]->{setup_cost};
3259 $quantity = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3260 $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3261 $no_auto = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3262 $pkg = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3263 $comment = exists($_[0]->{comment}) ? $_[0]->{comment}
3264 : '$'. sprintf("%.2f",$amount);
3265 $setuptax = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3266 $taxclass = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3267 $classnum = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3268 $additional = $_[0]->{additional} || [];
3269 $taxproduct = $_[0]->{taxproductnum};
3270 $override = { '' => $_[0]->{tax_override} };
3271 $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3272 $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3273 $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3274 $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3275 $separate_bill = $_[0]->{separate_bill} || '';
3281 $pkg = @_ ? shift : 'One-time charge';
3282 $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
3284 $taxclass = @_ ? shift : '';
3288 local $SIG{HUP} = 'IGNORE';
3289 local $SIG{INT} = 'IGNORE';
3290 local $SIG{QUIT} = 'IGNORE';
3291 local $SIG{TERM} = 'IGNORE';
3292 local $SIG{TSTP} = 'IGNORE';
3293 local $SIG{PIPE} = 'IGNORE';
3295 my $oldAutoCommit = $FS::UID::AutoCommit;
3296 local $FS::UID::AutoCommit = 0;
3299 my $part_pkg = new FS::part_pkg ( {
3301 'comment' => $comment,
3305 'classnum' => ( $classnum ? $classnum : '' ),
3306 'setuptax' => $setuptax,
3307 'taxclass' => $taxclass,
3308 'taxproductnum' => $taxproduct,
3309 'setup_cost' => $setup_cost,
3312 my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3313 ( 0 .. @$additional - 1 )
3315 'additional_count' => scalar(@$additional),
3316 'setup_fee' => $amount,
3319 my $error = $part_pkg->insert( options => \%options,
3320 tax_overrides => $override,
3323 $dbh->rollback if $oldAutoCommit;
3327 my $pkgpart = $part_pkg->pkgpart;
3328 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3329 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3330 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3331 $error = $type_pkgs->insert;
3333 $dbh->rollback if $oldAutoCommit;
3338 my $cust_pkg = new FS::cust_pkg ( {
3339 'custnum' => $self->custnum,
3340 'pkgpart' => $pkgpart,
3341 'quantity' => $quantity,
3342 'start_date' => $start_date,
3343 'no_auto' => $no_auto,
3344 'separate_bill' => $separate_bill,
3345 'locationnum'=> $locationnum,
3348 $error = $cust_pkg->insert;
3350 $dbh->rollback if $oldAutoCommit;
3352 } elsif ( $cust_pkg_ref ) {
3353 ${$cust_pkg_ref} = $cust_pkg;
3357 my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3358 'pkg_list' => [ $cust_pkg ],
3361 $dbh->rollback if $oldAutoCommit;
3366 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3371 #=item charge_postal_fee
3373 #Applies a one time charge this customer. If there is an error,
3374 #returns the error, returns the cust_pkg charge object or false
3375 #if there was no charge.
3379 # This should be a customer event. For that to work requires that bill
3380 # also be a customer event.
3382 sub charge_postal_fee {
3385 my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3386 return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3388 my $cust_pkg = new FS::cust_pkg ( {
3389 'custnum' => $self->custnum,
3390 'pkgpart' => $pkgpart,
3394 my $error = $cust_pkg->insert;
3395 $error ? $error : $cust_pkg;
3398 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3400 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3402 Optionally, a list or hashref of additional arguments to the qsearch call can
3409 my $opt = ref($_[0]) ? shift : { @_ };
3411 #return $self->num_cust_bill unless wantarray || keys %$opt;
3413 $opt->{'table'} = 'cust_bill';
3414 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3415 $opt->{'hashref'}{'custnum'} = $self->custnum;
3416 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3418 map { $_ } #behavior of sort undefined in scalar context
3419 sort { $a->_date <=> $b->_date }
3423 =item open_cust_bill
3425 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3430 sub open_cust_bill {
3434 'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3440 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3442 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3446 sub legacy_cust_bill {
3449 #return $self->num_legacy_cust_bill unless wantarray;
3451 map { $_ } #behavior of sort undefined in scalar context
3452 sort { $a->_date <=> $b->_date }
3453 qsearch({ 'table' => 'legacy_cust_bill',
3454 'hashref' => { 'custnum' => $self->custnum, },
3455 'order_by' => 'ORDER BY _date ASC',
3459 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3461 Returns all the statements (see L<FS::cust_statement>) for this customer.
3463 Optionally, a list or hashref of additional arguments to the qsearch call can
3468 =item cust_bill_void
3470 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3474 sub cust_bill_void {
3477 map { $_ } #return $self->num_cust_bill_void unless wantarray;
3478 sort { $a->_date <=> $b->_date }
3479 qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3482 sub cust_statement {
3484 my $opt = ref($_[0]) ? shift : { @_ };
3486 #return $self->num_cust_statement unless wantarray || keys %$opt;
3488 $opt->{'table'} = 'cust_statement';
3489 $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3490 $opt->{'hashref'}{'custnum'} = $self->custnum;
3491 $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3493 map { $_ } #behavior of sort undefined in scalar context
3494 sort { $a->_date <=> $b->_date }
3498 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3500 Returns all services of type SVCDB (such as 'svc_acct') for this customer.
3502 Optionally, a list or hashref of additional arguments to the qsearch call can
3503 be passed following the SVCDB.
3510 if ( ! $svcdb =~ /^svc_\w+$/ ) {
3511 warn "$me svc_x requires a svcdb";
3514 my $opt = ref($_[0]) ? shift : { @_ };
3516 $opt->{'table'} = $svcdb;
3517 $opt->{'addl_from'} =
3518 'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3519 ($opt->{'addl_from'} || '');
3521 my $custnum = $self->custnum;
3522 $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3523 my $where = "cust_pkg.custnum = $custnum";
3525 my $extra_sql = $opt->{'extra_sql'} || '';
3526 if ( keys %{ $opt->{'hashref'} } ) {
3527 $extra_sql = " AND $where $extra_sql";
3530 if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3531 $extra_sql = "WHERE $where AND $1";
3534 $extra_sql = "WHERE $where $extra_sql";
3537 $opt->{'extra_sql'} = $extra_sql;
3542 # required for use as an eventtable;
3545 $self->svc_x('svc_acct', @_);
3550 Returns all the credits (see L<FS::cust_credit>) for this customer.
3557 #return $self->num_cust_credit unless wantarray;
3559 map { $_ } #behavior of sort undefined in scalar context
3560 sort { $a->_date <=> $b->_date }
3561 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3564 =item cust_credit_pkgnum
3566 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3567 package when using experimental package balances.
3571 sub cust_credit_pkgnum {
3572 my( $self, $pkgnum ) = @_;
3573 map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3574 sort { $a->_date <=> $b->_date }
3575 qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3576 'pkgnum' => $pkgnum,
3581 =item cust_credit_void
3583 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3587 sub cust_credit_void {
3590 sort { $a->_date <=> $b->_date }
3591 qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3596 Returns all the payments (see L<FS::cust_pay>) for this customer.
3602 my $opt = ref($_[0]) ? shift : { @_ };
3604 return $self->num_cust_pay unless wantarray || keys %$opt;
3606 $opt->{'table'} = 'cust_pay';
3607 $opt->{'hashref'}{'custnum'} = $self->custnum;
3609 map { $_ } #behavior of sort undefined in scalar context
3610 sort { $a->_date <=> $b->_date }
3617 Returns the number of payments (see L<FS::cust_pay>) for this customer. Also
3618 called automatically when the cust_pay method is used in a scalar context.
3624 my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3625 my $sth = dbh->prepare($sql) or die dbh->errstr;
3626 $sth->execute($self->custnum) or die $sth->errstr;
3627 $sth->fetchrow_arrayref->[0];
3630 =item unapplied_cust_pay
3632 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3636 sub unapplied_cust_pay {
3640 'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3646 =item cust_pay_pkgnum
3648 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3649 package when using experimental package balances.
3653 sub cust_pay_pkgnum {
3654 my( $self, $pkgnum ) = @_;
3655 map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3656 sort { $a->_date <=> $b->_date }
3657 qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3658 'pkgnum' => $pkgnum,
3665 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3671 map { $_ } #return $self->num_cust_pay_void unless wantarray;
3672 sort { $a->_date <=> $b->_date }
3673 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3676 =item cust_pay_pending
3678 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3679 (without status "done").
3683 sub cust_pay_pending {
3685 return $self->num_cust_pay_pending unless wantarray;
3686 sort { $a->_date <=> $b->_date }
3687 qsearch( 'cust_pay_pending', {
3688 'custnum' => $self->custnum,
3689 'status' => { op=>'!=', value=>'done' },
3694 =item cust_pay_pending_attempt
3696 Returns all payment attempts / declined payments for this customer, as pending
3697 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3698 a corresponding payment (see L<FS::cust_pay>).
3702 sub cust_pay_pending_attempt {
3704 return $self->num_cust_pay_pending_attempt unless wantarray;
3705 sort { $a->_date <=> $b->_date }
3706 qsearch( 'cust_pay_pending', {
3707 'custnum' => $self->custnum,
3714 =item num_cust_pay_pending
3716 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3717 customer (without status "done"). Also called automatically when the
3718 cust_pay_pending method is used in a scalar context.
3722 sub num_cust_pay_pending {
3725 " SELECT COUNT(*) FROM cust_pay_pending ".
3726 " WHERE custnum = ? AND status != 'done' ",
3731 =item num_cust_pay_pending_attempt
3733 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3734 customer, with status "done" but without a corresp. Also called automatically when the
3735 cust_pay_pending method is used in a scalar context.
3739 sub num_cust_pay_pending_attempt {
3742 " SELECT COUNT(*) FROM cust_pay_pending ".
3743 " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3750 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3756 map { $_ } #return $self->num_cust_refund unless wantarray;
3757 sort { $a->_date <=> $b->_date }
3758 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3761 =item display_custnum
3763 Returns the displayed customer number for this customer: agent_custid if
3764 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3768 sub display_custnum {
3771 return $self->agent_custid
3772 if $default_agent_custid && $self->agent_custid;
3774 my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
3778 sprintf('%0'.($custnum_display_length||8).'d', $self->custnum)
3779 } elsif ( $custnum_display_length ) {
3780 return sprintf('%0'.$custnum_display_length.'d', $self->custnum);
3782 return $self->custnum;
3788 Returns a name string for this customer, either "Company (Last, First)" or
3795 my $name = $self->contact;
3796 $name = $self->company. " ($name)" if $self->company;
3800 =item service_contact
3802 Returns the L<FS::contact> object for this customer that has the 'Service'
3803 contact class, or undef if there is no such contact. Deprecated; don't use
3808 sub service_contact {
3810 if ( !exists($self->{service_contact}) ) {
3811 my $classnum = $self->scalar_sql(
3812 'SELECT classnum FROM contact_class WHERE classname = \'Service\''
3813 ) || 0; #if it's zero, qsearchs will return nothing
3814 my $cust_contact = qsearchs('cust_contact', {
3815 'classnum' => $classnum,
3816 'custnum' => $self->custnum,
3818 $self->{service_contact} = $cust_contact->contact if $cust_contact;
3820 $self->{service_contact};
3825 Returns a name string for this (service/shipping) contact, either
3826 "Company (Last, First)" or "Last, First".
3833 my $name = $self->ship_contact;
3834 $name = $self->company. " ($name)" if $self->company;
3840 Returns a name string for this customer, either "Company" or "First Last".
3846 $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3849 =item ship_name_short
3851 Returns a name string for this (service/shipping) contact, either "Company"
3856 sub ship_name_short {
3858 $self->service_contact
3859 ? $self->ship_contact_firstlast
3865 Returns this customer's full (billing) contact name only, "Last, First"
3871 $self->get('last'). ', '. $self->first;
3876 Returns this customer's full (shipping) contact name only, "Last, First"
3882 my $contact = $self->service_contact || $self;
3883 $contact->get('last') . ', ' . $contact->get('first');
3886 =item contact_firstlast
3888 Returns this customers full (billing) contact name only, "First Last".
3892 sub contact_firstlast {
3894 $self->first. ' '. $self->get('last');
3897 =item ship_contact_firstlast
3899 Returns this customer's full (shipping) contact name only, "First Last".
3903 sub ship_contact_firstlast {
3905 my $contact = $self->service_contact || $self;
3906 $contact->get('first') . ' '. $contact->get('last');
3909 sub bill_country_full {
3911 $self->bill_location->country_full;
3914 sub ship_country_full {
3916 $self->ship_location->country_full;
3919 =item county_state_county [ PREFIX ]
3921 Returns a string consisting of just the county, state and country.
3925 sub county_state_country {
3928 if ( @_ && $_[0] && $self->has_ship_address ) {
3929 $locationnum = $self->ship_locationnum;
3931 $locationnum = $self->bill_locationnum;
3933 my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
3934 $cust_location->county_state_country;
3937 =item geocode DATA_VENDOR
3939 Returns a value for the customer location as encoded by DATA_VENDOR.
3940 Currently this only makes sense for "CCH" as DATA_VENDOR.
3948 Returns a status string for this customer, currently:
3954 No packages have ever been ordered. Displayed as "No packages".
3958 Recurring packages all are new (not yet billed).
3962 One or more recurring packages is active.
3966 No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled).
3970 All non-cancelled recurring packages are suspended.
3974 All recurring packages are cancelled.
3978 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3979 cust_main-status_module configuration option.
3983 sub status { shift->cust_status(@_); }
3987 return $self->hashref->{cust_status} if $self->hashref->{cust_status};
3988 for my $status ( FS::cust_main->statuses() ) {
3989 my $method = $status.'_sql';
3990 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3991 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3992 $sth->execute( ($self->custnum) x $numnum )
3993 or die "Error executing 'SELECT $sql': ". $sth->errstr;
3994 if ( $sth->fetchrow_arrayref->[0] ) {
3995 $self->hashref->{cust_status} = $status;
4001 =item is_status_delay_cancel
4003 Returns true if customer status is 'suspended'
4004 and all suspended cust_pkg return true for
4005 cust_pkg->is_status_delay_cancel.
4007 This is not a real status, this only meant for hacking display
4008 values, because otherwise treating the customer as suspended is
4009 really the whole point of the delay_cancel option.
4013 sub is_status_delay_cancel {
4015 return 0 unless $self->status eq 'suspended';
4016 foreach my $cust_pkg ($self->ncancelled_pkgs) {
4017 return 0 unless $cust_pkg->is_status_delay_cancel;
4022 =item ucfirst_cust_status
4024 =item ucfirst_status
4026 Deprecated, use the cust_status_label method instead.
4028 Returns the status with the first character capitalized.
4032 sub ucfirst_status {
4033 carp "ucfirst_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4034 local($ucfirst_nowarn) = 1;
4035 shift->ucfirst_cust_status(@_);
4038 sub ucfirst_cust_status {
4039 carp "ucfirst_cust_status deprecated, use cust_status_label" unless $ucfirst_nowarn;
4041 ucfirst($self->cust_status);
4044 =item cust_status_label
4048 Returns the display label for this status.
4052 sub status_label { shift->cust_status_label(@_); }
4054 sub cust_status_label {
4056 __PACKAGE__->statuslabels->{$self->cust_status};
4061 Returns a hex triplet color string for this customer's status.
4065 sub statuscolor { shift->cust_statuscolor(@_); }
4067 sub cust_statuscolor {
4069 __PACKAGE__->statuscolors->{$self->cust_status};
4072 =item tickets [ STATUS ]
4074 Returns an array of hashes representing the customer's RT tickets.
4076 An optional status (or arrayref or hashref of statuses) may be specified.
4082 my $status = ( @_ && $_[0] ) ? shift : '';
4084 my $num = $conf->config('cust_main-max_tickets') || 10;
4087 if ( $conf->config('ticket_system') ) {
4088 unless ( $conf->config('ticket_system-custom_priority_field') ) {
4090 @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4099 foreach my $priority (
4100 $conf->config('ticket_system-custom_priority_field-values'), ''
4102 last if scalar(@tickets) >= $num;
4104 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4105 $num - scalar(@tickets),
4116 =item appointments [ STATUS ]
4118 Returns an array of hashes representing the customer's RT tickets which
4125 my $status = ( @_ && $_[0] ) ? shift : '';
4127 return () unless $conf->config('ticket_system');
4129 my $queueid = $conf->config('ticket_system-appointment-queueid');
4131 @{ FS::TicketSystem->customer_tickets( $self->custnum,
4140 # Return services representing svc_accts in customer support packages
4141 sub support_services {
4143 my %packages = map { $_ => 1 } $conf->config('support_packages');
4145 grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4146 grep { $_->part_svc->svcdb eq 'svc_acct' }
4147 map { $_->cust_svc }
4148 grep { exists $packages{ $_->pkgpart } }
4149 $self->ncancelled_pkgs;
4153 # Return a list of latitude/longitude for one of the services (if any)
4154 sub service_coordinates {
4158 grep { $_->latitude && $_->longitude }
4160 map { $_->cust_svc }
4161 $self->ncancelled_pkgs;
4163 scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4168 Returns a masked version of the named field
4173 my ($self,$field) = @_;
4177 'x'x(length($self->getfield($field))-4).
4178 substr($self->getfield($field), (length($self->getfield($field))-4));
4182 =item payment_history
4184 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4185 cust_credit and cust_refund objects. Each hashref has the following fields:
4187 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4189 I<date> - value of _date field, unix timestamp
4191 I<date_pretty> - user-friendly date
4193 I<description> - user-friendly description of item
4195 I<amount> - impact of item on user's balance
4196 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4197 Not to be confused with the native 'amount' field in cust_credit, see below.
4199 I<amount_pretty> - includes money char
4201 I<balance> - customer balance, chronologically as of this item
4203 I<balance_pretty> - includes money char
4205 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4207 I<paid> - amount paid for cust_pay records, undef for other types
4209 I<credit> - amount credited for cust_credit records, undef for other types.
4210 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4212 I<refund> - amount refunded for cust_refund records, undef for other types
4214 The four table-specific keys always have positive values, whether they reflect charges or payments.
4216 The following options may be passed to this method:
4218 I<line_items> - if true, returns charges ('Line item') rather than invoices
4220 I<start_date> - unix timestamp, only include records on or after.
4221 If specified, an item of type 'Previous' will also be included.
4222 It does not have table-specific fields.
4224 I<end_date> - unix timestamp, only include records before
4226 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4228 I<conf> - optional already-loaded FS::Conf object.
4232 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4233 # and also for sending customer statements, which should both be kept customer-friendly.
4234 # If you add anything that shouldn't be passed on through the API or exposed
4235 # to customers, add a new option to include it, don't include it by default
4236 sub payment_history {
4238 my $opt = ref($_[0]) ? $_[0] : { @_ };
4240 my $conf = $$opt{'conf'} || new FS::Conf;
4241 my $money_char = $conf->config("money_char") || '$',
4243 #first load entire history,
4244 #need previous to calculate previous balance
4245 #loading after end_date shouldn't hurt too much?
4247 if ( $$opt{'line_items'} ) {
4249 foreach my $cust_bill ( $self->cust_bill ) {
4252 'type' => 'Line item',
4253 'description' => $_->desc( $self->locale ).
4254 ( $_->sdate && $_->edate
4255 ? ' '. time2str('%d-%b-%Y', $_->sdate).
4256 ' To '. time2str('%d-%b-%Y', $_->edate)
4259 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
4260 'charged' => sprintf('%.2f', $_->setup + $_->recur ),
4261 'date' => $cust_bill->_date,
4262 'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4264 foreach $cust_bill->cust_bill_pkg;
4271 'type' => 'Invoice',
4272 'description' => 'Invoice #'. $_->display_invnum,
4273 'amount' => sprintf('%.2f', $_->charged ),
4274 'charged' => sprintf('%.2f', $_->charged ),
4275 'date' => $_->_date,
4276 'date_pretty' => $self->time2str_local('short', $_->_date ),
4278 foreach $self->cust_bill;
4283 'type' => 'Payment',
4284 'description' => 'Payment', #XXX type
4285 'amount' => sprintf('%.2f', 0 - $_->paid ),
4286 'paid' => sprintf('%.2f', $_->paid ),
4287 'date' => $_->_date,
4288 'date_pretty' => $self->time2str_local('short', $_->_date ),
4290 foreach $self->cust_pay;
4294 'description' => 'Credit', #more info?
4295 'amount' => sprintf('%.2f', 0 -$_->amount ),
4296 'credit' => sprintf('%.2f', $_->amount ),
4297 'date' => $_->_date,
4298 'date_pretty' => $self->time2str_local('short', $_->_date ),
4300 foreach $self->cust_credit;
4304 'description' => 'Refund', #more info? type, like payment?
4305 'amount' => $_->refund,
4306 'refund' => $_->refund,
4307 'date' => $_->_date,
4308 'date_pretty' => $self->time2str_local('short', $_->_date ),
4310 foreach $self->cust_refund;
4312 #put it all in chronological order
4313 @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4315 #calculate balance, filter items outside date range
4319 foreach my $item (@history) {
4320 last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4321 $balance += $$item{'amount'};
4322 if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4323 $previous += $$item{'amount'};
4326 $$item{'balance'} = sprintf("%.2f",$balance);
4327 foreach my $key ( qw(amount balance) ) {
4328 $$item{$key.'_pretty'} = money_pretty($$item{$key});
4333 # start with previous balance, if there was one
4336 'type' => 'Previous',
4337 'description' => 'Previous balance',
4338 'amount' => sprintf("%.2f",$previous),
4339 'balance' => sprintf("%.2f",$previous),
4340 'date' => $$opt{'start_date'},
4341 'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4343 #false laziness with above
4344 foreach my $key ( qw(amount balance) ) {
4345 $$item{$key.'_pretty'} = $$item{$key};
4346 $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4348 unshift(@out,$item);
4351 @out = reverse @history if $$opt{'reverse_sort'};
4356 =item save_cust_payby
4358 Saves a new cust_payby for this customer, replacing an existing entry only
4359 in select circumstances. Does not validate input.
4361 If auto is specified, marks this as the customer's primary method, or the
4362 specified weight. Existing payment methods have their weight incremented as
4365 If bill_location is specified with auto, also sets location in cust_main.
4367 Will not insert complete duplicates of existing records, or records in which the
4368 only difference from an existing record is to turn off automatic payment (will
4369 return without error.) Will replace existing records in which the only difference
4370 is to add a value to a previously empty preserved field and/or turn on automatic payment.
4371 Fields marked as preserved are optional, and existing values will not be overwritten with
4372 blanks when replacing.
4374 Accepts the following named parameters:
4384 save as an automatic payment type (CARD/CHEK if true, DCRD/DCHK if false)
4388 optional, set higher than 1 for secondary, etc.
4396 optional, but should be specified for anything that might be tokenized, will be preserved when replacing
4404 optional, will be preserved when replacing
4412 CARD only, required, FS::cust_location object
4414 =item paystart_month
4416 CARD only, optional, will be preserved when replacing
4420 CARD only, optional, will be preserved when replacing
4424 CARD only, optional, will be preserved when replacing
4428 CARD only, only used if conf cvv-save is set appropriately
4442 #The code for this option is in place, but it's not currently used
4446 # existing cust_payby object to be replaced (must match custnum)
4448 # stateid/stateid_state/ss are not currently supported in cust_payby,
4449 # might not even work properly in 4.x, but will need to work here if ever added
4451 sub save_cust_payby {
4455 my $old = $opt{'replace'};
4456 my $new = new FS::cust_payby { $old ? $old->hash : () };
4457 return "Customer number does not match" if $new->custnum and $new->custnum != $self->custnum;
4458 $new->set( 'custnum' => $self->custnum );
4460 my $payby = $opt{'payment_payby'};
4461 return "Bad payby" unless grep(/^$payby$/,('CARD','CHEK'));
4463 # don't allow turning off auto when replacing
4464 $opt{'auto'} ||= 1 if $old and $old->payby !~ /^D/;
4466 my @check_existing; # payby relevant to this payment_payby
4468 # set payby based on auto
4469 if ( $payby eq 'CARD' ) {
4470 $new->set( 'payby' => ( $opt{'auto'} ? 'CARD' : 'DCRD' ) );
4471 @check_existing = qw( CARD DCRD );
4472 } elsif ( $payby eq 'CHEK' ) {
4473 $new->set( 'payby' => ( $opt{'auto'} ? 'CHEK' : 'DCHK' ) );
4474 @check_existing = qw( CHEK DCHK );
4477 $new->set( 'weight' => $opt{'auto'} ? $opt{'weight'} : '' );
4480 $new->payinfo($opt{'payinfo'}); # sets default paymask, but not if it's already tokenized
4481 $new->paymask($opt{'paymask'}) if $opt{'paymask'}; # in case it's been tokenized, override with loaded paymask
4482 $new->set( 'payname' => $opt{'payname'} );
4483 $new->set( 'payip' => $opt{'payip'} ); # will be preserved below
4485 my $conf = new FS::Conf;
4487 # compare to FS::cust_main::realtime_bop - check both to make sure working correctly
4488 if ( $payby eq 'CARD' &&
4489 ( (grep { $_ eq cardtype($opt{'payinfo'}) } $conf->config('cvv-save'))
4490 || $conf->exists('business-onlinepayment-verification')
4493 $new->set( 'paycvv' => $opt{'paycvv'} );
4495 $new->set( 'paycvv' => '');
4498 local $SIG{HUP} = 'IGNORE';
4499 local $SIG{INT} = 'IGNORE';
4500 local $SIG{QUIT} = 'IGNORE';
4501 local $SIG{TERM} = 'IGNORE';
4502 local $SIG{TSTP} = 'IGNORE';
4503 local $SIG{PIPE} = 'IGNORE';
4505 my $oldAutoCommit = $FS::UID::AutoCommit;
4506 local $FS::UID::AutoCommit = 0;
4509 # set fields specific to payment_payby
4510 if ( $payby eq 'CARD' ) {
4511 if ($opt{'bill_location'}) {
4512 $opt{'bill_location'}->set('custnum' => $self->custnum);
4513 my $error = $opt{'bill_location'}->find_or_insert;
4515 $dbh->rollback if $oldAutoCommit;
4518 $new->set( 'locationnum' => $opt{'bill_location'}->locationnum );
4520 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
4521 $new->set( $field => $opt{$field} );
4524 foreach my $field ( qw(paytype paystate) ) {
4525 $new->set( $field => $opt{$field} );
4529 # other cust_payby to compare this to
4530 my @existing = $self->cust_payby(@check_existing);
4532 # fields that can overwrite blanks with values, but not values with blanks
4533 my @preserve = qw( paymask locationnum paystart_month paystart_year payissue payip );
4535 my $skip_cust_payby = 0; # true if we don't need to save or reweight cust_payby
4537 # generally, we don't want to overwrite existing cust_payby with this,
4538 # but we can replace if we're only marking it auto or adding a preserved field
4539 # and we can avoid saving a total duplicate or merely turning off auto
4541 foreach my $cust_payby (@existing) {
4542 # check fields that absolutely should not change
4543 foreach my $field ($new->fields) {
4544 next if grep(/^$field$/, qw( custpaybynum payby weight ) );
4545 next if grep(/^$field$/, @preserve );
4546 next PAYBYLOOP unless $new->get($field) eq $cust_payby->get($field);
4548 # now check fields that can replace if one value is blank
4550 foreach my $field (@preserve) {
4552 ( $new->get($field) and !$cust_payby->get($field) ) or
4553 ( $cust_payby->get($field) and !$new->get($field) )
4555 # prevention of overwriting values with blanks happens farther below
4557 } elsif ( $new->get($field) ne $cust_payby->get($field) ) {
4561 unless ( $replace ) {
4562 # nearly identical, now check weight
4563 if ($new->get('weight') eq $cust_payby->get('weight') or !$new->get('weight')) {
4564 # ignore identical cust_payby, and ignore attempts to turn off auto
4565 # no need to save or re-weight cust_payby (but still need to update/commit $self)
4566 $skip_cust_payby = 1;
4569 # otherwise, only change is to mark this as primary
4571 # if we got this far, we're definitely replacing
4578 $new->set( 'custpaybynum' => $old->custpaybynum );
4579 # don't turn off automatic payment (but allow it to be turned on)
4580 if ($new->payby =~ /^D/ and $new->payby ne $old->payby) {
4582 $new->set( 'payby' => $old->payby );
4583 $new->set( 'weight' => 1 );
4585 # make sure we're not overwriting values with blanks
4586 foreach my $field (@preserve) {
4587 if ( $old->get($field) and !$new->get($field) ) {
4588 $new->set( $field => $old->get($field) );
4593 # only overwrite cust_main bill_location if auto
4594 if ($opt{'auto'} && $opt{'bill_location'}) {
4595 $self->set('bill_location' => $opt{'bill_location'});
4596 my $error = $self->replace;
4598 $dbh->rollback if $oldAutoCommit;
4603 # done with everything except reweighting and saving cust_payby
4604 # still need to commit changes to cust_main and cust_location
4605 if ($skip_cust_payby) {
4606 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4610 # re-weight existing primary cust_pay for this payby
4612 foreach my $cust_payby (@existing) {
4613 # relies on cust_payby return order
4614 last unless $cust_payby->payby !~ /^D/;
4615 last if $cust_payby->weight > 1;
4616 next if $new->custpaybynum eq $cust_payby->custpaybynum;
4617 next if $cust_payby->weight < ($opt{'weight'} || 1);
4618 $cust_payby->weight( $cust_payby->weight + 1 );
4619 my $error = $cust_payby->replace;
4621 $dbh->rollback if $oldAutoCommit;
4622 return "Error reweighting cust_payby: $error";
4627 # finally, save cust_payby
4628 my $error = $old ? $new->replace($old) : $new->insert;
4630 $dbh->rollback if $oldAutoCommit;
4634 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4639 =item remove_cvv_from_cust_payby PAYINFO
4641 Removes paycvv from associated cust_payby with matching PAYINFO.
4645 sub remove_cvv_from_cust_payby {
4646 my ($self,$payinfo) = @_;
4648 my $oldAutoCommit = $FS::UID::AutoCommit;
4649 local $FS::UID::AutoCommit = 0;
4652 foreach my $cust_payby ( qsearch('cust_payby',{ custnum => $self->custnum }) ) {
4653 next unless $cust_payby->payinfo eq $payinfo; # can't qsearch on payinfo
4654 $cust_payby->paycvv('');
4655 my $error = $cust_payby->replace;
4657 $dbh->rollback if $oldAutoCommit;
4662 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4668 =head1 CLASS METHODS
4674 Class method that returns the list of possible status strings for customers
4675 (see L<the status method|/status>). For example:
4677 @statuses = FS::cust_main->statuses();
4683 keys %{ $self->statuscolors };
4686 =item cust_status_sql
4688 Returns an SQL fragment to determine the status of a cust_main record, as a
4693 sub cust_status_sql {
4695 for my $status ( FS::cust_main->statuses() ) {
4696 my $method = $status.'_sql';
4697 $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4706 Returns an SQL expression identifying prospective cust_main records (customers
4707 with no packages ever ordered)
4711 use vars qw($select_count_pkgs);
4712 $select_count_pkgs =
4713 "SELECT COUNT(*) FROM cust_pkg
4714 WHERE cust_pkg.custnum = cust_main.custnum";
4716 sub select_count_pkgs_sql {
4721 " 0 = ( $select_count_pkgs ) ";
4726 Returns an SQL expression identifying ordered cust_main records (customers with
4727 no active packages, but recurring packages not yet setup or one time charges
4733 FS::cust_main->none_active_sql.
4734 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4739 Returns an SQL expression identifying active cust_main records (customers with
4740 active recurring packages).
4745 " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4748 =item none_active_sql
4750 Returns an SQL expression identifying cust_main records with no active
4751 recurring packages. This includes customers of status prospect, ordered,
4752 inactive, and suspended.
4756 sub none_active_sql {
4757 " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4762 Returns an SQL expression identifying inactive cust_main records (customers with
4763 no active recurring packages, but otherwise unsuspended/uncancelled).
4768 FS::cust_main->none_active_sql.
4769 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4775 Returns an SQL expression identifying suspended cust_main records.
4780 sub suspended_sql { susp_sql(@_); }
4782 FS::cust_main->none_active_sql.
4783 " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4789 Returns an SQL expression identifying cancelled cust_main records.
4793 sub cancel_sql { shift->cancelled_sql(@_); }
4796 =item uncancelled_sql
4798 Returns an SQL expression identifying un-cancelled cust_main records.
4802 sub uncancelled_sql { uncancel_sql(@_); }
4805 "( NOT (".$self->cancelled_sql.") )"; #sensitive to cust_main-status_module
4810 Returns an SQL fragment to retreive the balance.
4815 ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4816 WHERE cust_bill.custnum = cust_main.custnum )
4817 - ( SELECT COALESCE( SUM(paid), 0 ) FROM cust_pay
4818 WHERE cust_pay.custnum = cust_main.custnum )
4819 - ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_credit
4820 WHERE cust_credit.custnum = cust_main.custnum )
4821 + ( SELECT COALESCE( SUM(refund), 0 ) FROM cust_refund
4822 WHERE cust_refund.custnum = cust_main.custnum )
4825 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4827 Returns an SQL fragment to retreive the balance for this customer, optionally
4828 considering invoices with date earlier than START_TIME, and not
4829 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4830 total_unapplied_payments).
4832 Times are specified as SQL fragments or numeric
4833 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4834 L<Date::Parse> for conversion functions. The empty string can be passed
4835 to disable that time constraint completely.
4837 Available options are:
4841 =item unapplied_date
4843 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)
4848 set to true to remove all customer comparison clauses, for totals
4853 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4858 JOIN clause (typically used with the total option)
4862 An absolute cutoff time. Payments, credits, and refunds I<applied> after this
4863 time will be ignored. Note that START_TIME and END_TIME only limit the date
4864 range for invoices and I<unapplied> payments, credits, and refunds.
4870 sub balance_date_sql {
4871 my( $class, $start, $end, %opt ) = @_;
4873 my $cutoff = $opt{'cutoff'};
4875 my $owed = FS::cust_bill->owed_sql($cutoff);
4876 my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4877 my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4878 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4880 my $j = $opt{'join'} || '';
4882 my $owed_wh = $class->_money_table_where( 'cust_bill', $start,$end,%opt );
4883 my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4884 my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4885 my $pay_wh = $class->_money_table_where( 'cust_pay', $start,$end,%opt );
4887 " ( SELECT COALESCE(SUM($owed), 0) FROM cust_bill $j $owed_wh )
4888 + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4889 - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4890 - ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $j $pay_wh )
4895 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4897 Returns an SQL fragment to retreive the total unapplied payments for this
4898 customer, only considering payments with date earlier than START_TIME, and
4899 optionally not later than END_TIME.
4901 Times are specified as SQL fragments or numeric
4902 UNIX timestamps; see L<perlfunc/"time">). Also see L<Time::Local> and
4903 L<Date::Parse> for conversion functions. The empty string can be passed
4904 to disable that time constraint completely.
4906 Available options are:
4910 sub unapplied_payments_date_sql {
4911 my( $class, $start, $end, %opt ) = @_;
4913 my $cutoff = $opt{'cutoff'};
4915 my $unapp_pay = FS::cust_pay->unapplied_sql($cutoff);
4917 my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4918 'unapplied_date'=>1 );
4920 " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4923 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4925 Helper method for balance_date_sql; name (and usage) subject to change
4926 (suggestions welcome).
4928 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4929 cust_refund, cust_credit or cust_pay).
4931 If TABLE is "cust_bill" or the unapplied_date option is true, only
4932 considers records with date earlier than START_TIME, and optionally not
4933 later than END_TIME .
4937 sub _money_table_where {
4938 my( $class, $table, $start, $end, %opt ) = @_;
4941 push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4942 if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4943 push @where, "$table._date <= $start" if defined($start) && length($start);
4944 push @where, "$table._date > $end" if defined($end) && length($end);
4946 push @where, @{$opt{'where'}} if $opt{'where'};
4947 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4953 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4954 use FS::cust_main::Search;
4957 FS::cust_main::Search->search(@_);
4966 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4968 Generates a templated notification to the customer (see L<Text::Template>).
4970 OPTIONS is a hash and may include
4972 I<extra_fields> - a hashref of name/value pairs which will be substituted
4973 into the template. These values may override values mentioned below
4974 and those from the customer record.
4976 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
4978 The following variables are available in the template instead of or in addition
4979 to the fields of the customer record.
4981 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4985 # a lot like cust_bill::print_latex
4986 sub generate_letter {
4987 my ($self, $template, %options) = @_;
4989 warn "Template $template does not exist" && return
4990 unless $conf->exists($template) || $options{'template_text'};
4992 my $template_source = $options{'template_text'}
4993 ? [ $options{'template_text'} ]
4994 : [ map "$_\n", $conf->config($template) ];
4996 my $letter_template = new Text::Template
4998 SOURCE => $template_source,
4999 DELIMITERS => [ '[@--', '--@]' ],
5001 or die "can't create new Text::Template object: Text::Template::ERROR";
5003 $letter_template->compile()
5004 or die "can't compile template: Text::Template::ERROR";
5006 my %letter_data = map { $_ => $self->$_ } $self->fields;
5008 for (keys %{$options{extra_fields}}){
5009 $letter_data{$_} = $options{extra_fields}->{$_};
5012 unless(exists($letter_data{returnaddress})){
5013 my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5014 $self->agent_template)
5016 if ( length($retadd) ) {
5017 $letter_data{returnaddress} = $retadd;
5018 } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5019 $letter_data{returnaddress} =
5020 join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5024 ( $conf->config('company_name', $self->agentnum),
5025 $conf->config('company_address', $self->agentnum),
5029 $letter_data{returnaddress} = '~';
5033 $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5035 $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5037 my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5039 my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5043 ) or die "can't open temp file: $!\n";
5044 print $lh $conf->config_binary('logo.eps', $self->agentnum)
5045 or die "can't write temp file: $!\n";
5047 $letter_data{'logo_file'} = $lh->filename;
5049 my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5053 ) or die "can't open temp file: $!\n";
5055 $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5057 $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5058 return ($1, $letter_data{'logo_file'});
5062 =item print_ps TEMPLATE
5064 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5070 my($file, $lfile) = $self->generate_letter(@_);
5071 my $ps = FS::Misc::generate_ps($file);
5072 unlink($file.'.tex');
5078 =item print TEMPLATE
5080 Prints the filled in template.
5082 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5086 sub queueable_print {
5089 my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5090 or die "invalid customer number: " . $opt{custnum};
5092 #do not backport this change to 3.x
5093 # my $error = $self->print( { 'template' => $opt{template} } );
5094 my $error = $self->print( $opt{'template'} );
5095 die $error if $error;
5099 my ($self, $template) = (shift, shift);
5101 [ $self->print_ps($template) ],
5102 'agentnum' => $self->agentnum,
5106 #these three subs should just go away once agent stuff is all config overrides
5108 sub agent_template {
5110 $self->_agent_plandata('agent_templatename');
5113 sub agent_invoice_from {
5115 $self->_agent_plandata('agent_invoice_from');
5118 sub _agent_plandata {
5119 my( $self, $option ) = @_;
5121 #yuck. this whole thing needs to be reconciled better with 1.9's idea of
5122 #agent-specific Conf
5124 use FS::part_event::Condition;
5126 my $agentnum = $self->agentnum;
5128 my $regexp = regexp_sql();
5130 my $part_event_option =
5132 'select' => 'part_event_option.*',
5133 'table' => 'part_event_option',
5135 LEFT JOIN part_event USING ( eventpart )
5136 LEFT JOIN part_event_option AS peo_agentnum
5137 ON ( part_event.eventpart = peo_agentnum.eventpart
5138 AND peo_agentnum.optionname = 'agentnum'
5139 AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5141 LEFT JOIN part_event_condition
5142 ON ( part_event.eventpart = part_event_condition.eventpart
5143 AND part_event_condition.conditionname = 'cust_bill_age'
5145 LEFT JOIN part_event_condition_option
5146 ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5147 AND part_event_condition_option.optionname = 'age'
5150 #'hashref' => { 'optionname' => $option },
5151 #'hashref' => { 'part_event_option.optionname' => $option },
5153 " WHERE part_event_option.optionname = ". dbh->quote($option).
5154 " AND action = 'cust_bill_send_agent' ".
5155 " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5156 " AND peo_agentnum.optionname = 'agentnum' ".
5157 " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5159 CASE WHEN part_event_condition_option.optionname IS NULL
5161 ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5163 , part_event.weight".
5167 unless ( $part_event_option ) {
5168 return $self->agent->invoice_template || ''
5169 if $option eq 'agent_templatename';
5173 $part_event_option->optionvalue;
5177 sub process_o2m_qsearch {
5180 return qsearch($table, @_) unless $table eq 'contact';
5182 my $hashref = shift;
5183 my %hash = %$hashref;
5184 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5185 or die 'guru meditation #4343';
5187 qsearch({ 'table' => 'contact',
5188 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5189 'hashref' => \%hash,
5190 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5191 " cust_contact.custnum = $custnum "
5195 sub process_o2m_qsearchs {
5198 return qsearchs($table, @_) unless $table eq 'contact';
5200 my $hashref = shift;
5201 my %hash = %$hashref;
5202 ( my $custnum = delete $hash{'custnum'} ) =~ /^(\d+)$/
5203 or die 'guru meditation #2121';
5205 qsearchs({ 'table' => 'contact',
5206 'addl_from' => 'LEFT JOIN cust_contact USING ( contactnum )',
5207 'hashref' => \%hash,
5208 'extra_sql' => ( keys %hash ? ' AND ' : ' WHERE ' ).
5209 " cust_contact.custnum = $custnum "
5213 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5215 Subroutine (not a method), designed to be called from the queue.
5217 Takes a list of options and values.
5219 Pulls up the customer record via the custnum option and calls bill_and_collect.
5224 my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5226 my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5227 warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5229 #without this errors don't get rolled back
5230 $args{'fatal'} = 1; # runs from job queue, will be caught
5232 $cust_main->bill_and_collect( %args );
5235 =item queued_collect 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5237 Like queued_bill, but instead of C<bill_and_collect>, just runs the
5238 C<collect> part. This is used in batch tax calculation, where invoice
5239 generation and collection events have to be completely separated.
5243 sub queued_collect {
5245 my $cust_main = FS::cust_main->by_key($args{'custnum'});
5247 $cust_main->collect(%args);
5250 sub process_bill_and_collect {
5253 my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5254 or die "custnum '$param->{custnum}' not found!\n";
5255 $param->{'job'} = $job;
5256 $param->{'fatal'} = 1; # runs from job queue, will be caught
5257 $param->{'retry'} = 1;
5259 $cust_main->bill_and_collect( %$param );
5262 #starting to take quite a while for big dbs
5263 # (JRNL: journaled so it only happens once per database)
5264 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5265 # JRNL seq scan of cust_main on signupdate... index signupdate? will that help?
5266 # JRNL seq scan of cust_main on paydate... index on substrings? maybe set an
5267 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5268 # JRNL leading/trailing spaces in first, last, company
5269 # JRNL migrate to cust_payby
5270 # - otaker upgrade? journal and call it good? (double check to make sure
5271 # we're not still setting otaker here)
5273 #only going to get worse with new location stuff...
5275 sub _upgrade_data { #class method
5276 my ($class, %opts) = @_;
5278 my @statements = ();
5280 #this seems to be the only expensive one.. why does it take so long?
5281 unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5283 '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';
5284 FS::upgrade_journal->set_done('cust_main__signupdate');
5288 foreach my $sql ( @statements ) {
5289 my $sth = dbh->prepare($sql) or die dbh->errstr;
5290 $sth->execute or die $sth->errstr;
5291 #warn ( (time - $t). " seconds\n" );
5295 local($ignore_expired_card) = 1;
5296 local($ignore_banned_card) = 1;
5297 local($skip_fuzzyfiles) = 1;
5298 local($import) = 1; #prevent automatic geocoding (need its own variable?)
5300 FS::cust_main::Location->_upgrade_data(%opts);
5302 unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5304 foreach my $cust_main ( qsearch({
5305 'table' => 'cust_main',
5307 'extra_sql' => 'WHERE '.
5309 map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '% %'",
5310 qw( first last company )
5313 my $error = $cust_main->replace;
5314 die $error if $error;
5317 FS::upgrade_journal->set_done('cust_main__trimspaces');
5321 $class->_upgrade_otaker(%opts);
5331 The delete method should possibly take an FS::cust_main object reference
5332 instead of a scalar customer number.
5334 Bill and collect options should probably be passed as references instead of a
5337 There should probably be a configuration file with a list of allowed credit
5340 No multiple currency support (probably a larger project than just this module).
5342 Birthdates rely on negative epoch values.
5344 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5348 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5349 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5350 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.