2 use base qw( FS::Password_Mixin
6 use vars qw( $skip_fuzzyfiles );
8 use Scalar::Util qw( blessed );
9 use FS::Record qw( qsearch qsearchs dbh );
11 use FS::contact_phone;
12 use FS::contact_email;
14 use FS::phone_type; #for cgi_contact_fields
16 use FS::prospect_contact;
22 FS::contact - Object methods for contact records
28 $record = new FS::contact \%hash;
29 $record = new FS::contact { 'column' => 'value' };
31 $error = $record->insert;
33 $error = $new_record->replace($old_record);
35 $error = $record->delete;
37 $error = $record->check;
41 An FS::contact object represents an specific contact person for a prospect or
42 customer. FS::contact inherits from FS::Record. The following fields are
79 =item selfservice_access
85 =item _password_encoding
101 Creates a new contact. To add the contact to the database, see L<"insert">.
103 Note that this stores the hash reference, not a distinct copy of the hash it
104 points to. You can ask the object for a copy with the I<hash> method.
108 sub table { 'contact'; }
112 Adds this record to the database. If there is an error, returns the error,
113 otherwise returns false.
115 If the object has an C<emailaddress> field, L<FS::contact_email> records will
116 be created for each (comma-separated) email address in that field. If any of
117 these coincide with an existing email address, this contact will be merged with
118 the contact with that address.
120 Then, if the object has any fields named C<phonetypenumN> an
121 L<FS::contact_phone> record will be created for each of them. Those fields
122 should contain phone numbers of the appropriate types (where N is the key of
123 an L<FS::phone_type> record identifying the type of number: daytime, night,
126 After inserting the record, if the object has a 'custnum' or 'prospectnum'
127 field, an L<FS::cust_contact> or L<FS::prospect_contact> record will be
128 created to link the contact to the customer. The following fields will also
129 be included in that record, if they are set on the object:
140 local $SIG{INT} = 'IGNORE';
141 local $SIG{QUIT} = 'IGNORE';
142 local $SIG{TERM} = 'IGNORE';
143 local $SIG{TSTP} = 'IGNORE';
144 local $SIG{PIPE} = 'IGNORE';
146 my $oldAutoCommit = $FS::UID::AutoCommit;
147 local $FS::UID::AutoCommit = 0;
150 #save off and blank values that move to cust_contact / prospect_contact now
151 my $prospectnum = $self->prospectnum;
152 $self->prospectnum('');
153 my $custnum = $self->custnum;
157 for (qw( classnum comment selfservice_access invoice_dest )) {
158 $link_hash{$_} = $self->get($_);
162 #look for an existing contact with this email address
163 my $existing_contact = '';
164 if ( $self->get('emailaddress') =~ /\S/ ) {
166 my %existing_contact = ();
168 foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
170 my $contact_email = qsearchs('contact_email', { emailaddress=>$email } )
173 my $contact = $contact_email->contact;
174 $existing_contact{ $contact->contactnum } = $contact;
178 if ( scalar( keys %existing_contact ) > 1 ) {
179 $dbh->rollback if $oldAutoCommit;
180 return 'Multiple email addresses specified '.
181 ' that already belong to separate contacts';
182 } elsif ( scalar( keys %existing_contact ) ) {
183 ($existing_contact) = values %existing_contact;
189 if ( $existing_contact ) {
191 $self->$_($existing_contact->$_())
192 for qw( contactnum _password _password_encoding );
193 $error = $self->SUPER::replace($existing_contact);
197 $error = $self->SUPER::insert;
201 $error ||= $self->insert_password_history;
204 $dbh->rollback if $oldAutoCommit;
208 my $cust_contact = '';
210 my %hash = ( 'contactnum' => $self->contactnum,
211 'custnum' => $custnum,
213 $cust_contact = qsearchs('cust_contact', \%hash )
214 || new FS::cust_contact { %hash, %link_hash };
215 my $error = $cust_contact->custcontactnum ? $cust_contact->replace
216 : $cust_contact->insert;
218 $dbh->rollback if $oldAutoCommit;
223 if ( $prospectnum ) {
224 my %hash = ( 'contactnum' => $self->contactnum,
225 'prospectnum' => $prospectnum,
227 my $prospect_contact = qsearchs('prospect_contact', \%hash )
228 || new FS::prospect_contact { %hash, %link_hash };
230 $prospect_contact->prospectcontactnum ? $prospect_contact->replace
231 : $prospect_contact->insert;
233 $dbh->rollback if $oldAutoCommit;
238 foreach my $pf ( grep { /^phonetypenum(\d+)$/ && $self->get($_) =~ /\S/ }
239 keys %{ $self->hashref } ) {
240 $pf =~ /^phonetypenum(\d+)$/ or die "wtf (daily, the)";
241 my $phonetypenum = $1;
243 my %hash = ( 'contactnum' => $self->contactnum,
244 'phonetypenum' => $phonetypenum,
247 qsearchs('contact_phone', \%hash)
248 || new FS::contact_phone { %hash, _parse_phonestring($self->get($pf)) };
249 my $error = $contact_phone->contactphonenum ? $contact_phone->replace
250 : $contact_phone->insert;
252 $dbh->rollback if $oldAutoCommit;
257 if ( $self->get('emailaddress') =~ /\S/ ) {
259 foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
261 'contactnum' => $self->contactnum,
262 'emailaddress' => $email,
264 unless ( qsearchs('contact_email', \%hash) ) {
265 my $contact_email = new FS::contact_email \%hash;
266 my $error = $contact_email->insert;
268 $dbh->rollback if $oldAutoCommit;
276 unless ( $skip_fuzzyfiles ) { #unless ( $import || $skip_fuzzyfiles ) {
277 #warn " queueing fuzzyfiles update\n"
279 my $error = $self->queue_fuzzyfiles_update;
281 $dbh->rollback if $oldAutoCommit;
282 return "updating fuzzy search cache: $error";
286 if ( $link_hash{'selfservice_access'} eq 'R'
287 or ( $link_hash{'selfservice_access'}
289 && ! length($self->_password)
293 my $error = $self->send_reset_email( queue=>1 );
295 $dbh->rollback if $oldAutoCommit;
300 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
308 Delete this record from the database.
315 local $SIG{HUP} = 'IGNORE';
316 local $SIG{INT} = 'IGNORE';
317 local $SIG{QUIT} = 'IGNORE';
318 local $SIG{TERM} = 'IGNORE';
319 local $SIG{TSTP} = 'IGNORE';
320 local $SIG{PIPE} = 'IGNORE';
322 my $oldAutoCommit = $FS::UID::AutoCommit;
323 local $FS::UID::AutoCommit = 0;
326 #got a prospetnum or custnum? delete the prospect_contact or cust_contact link
328 if ( $self->prospectnum ) {
329 my $prospect_contact = qsearchs('prospect_contact', {
330 'contactnum' => $self->contactnum,
331 'prospectnum' => $self->prospectnum,
333 my $error = $prospect_contact->delete;
335 $dbh->rollback if $oldAutoCommit;
340 if ( $self->custnum ) {
341 my $cust_contact = qsearchs('cust_contact', {
342 'contactnum' => $self->contactnum,
343 'custnum' => $self->custnum,
345 my $error = $cust_contact->delete;
347 $dbh->rollback if $oldAutoCommit;
352 # then, proceed with deletion only if the contact isn't attached to any other
353 # prospects or customers
355 #inefficient, but how many prospects/customers can a single contact be
356 # attached too? (and is removing them from one a common operation?)
357 if ( $self->prospect_contact || $self->cust_contact ) {
358 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
362 #proceed with deletion
364 foreach my $cust_pkg ( $self->cust_pkg ) {
365 $cust_pkg->contactnum('');
366 my $error = $cust_pkg->replace;
368 $dbh->rollback if $oldAutoCommit;
373 foreach my $object ( $self->contact_phone, $self->contact_email ) {
374 my $error = $object->delete;
376 $dbh->rollback if $oldAutoCommit;
381 my $error = $self->SUPER::delete;
383 $dbh->rollback if $oldAutoCommit;
387 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
392 =item replace OLD_RECORD
394 Replaces the OLD_RECORD with this one in the database. If there is an error,
395 returns the error, otherwise returns false.
402 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
404 : $self->replace_old;
406 $self->$_( $self->$_ || $old->$_ ) for qw( _password _password_encoding );
408 local $SIG{INT} = 'IGNORE';
409 local $SIG{QUIT} = 'IGNORE';
410 local $SIG{TERM} = 'IGNORE';
411 local $SIG{TSTP} = 'IGNORE';
412 local $SIG{PIPE} = 'IGNORE';
414 my $oldAutoCommit = $FS::UID::AutoCommit;
415 local $FS::UID::AutoCommit = 0;
418 #save off and blank values that move to cust_contact / prospect_contact now
419 my $prospectnum = $self->prospectnum;
420 $self->prospectnum('');
421 my $custnum = $self->custnum;
425 for (qw( classnum comment selfservice_access invoice_dest )) {
426 $link_hash{$_} = $self->get($_);
430 my $error = $self->SUPER::replace($old);
431 if ( $old->_password ne $self->_password ) {
432 $error ||= $self->insert_password_history;
435 $dbh->rollback if $oldAutoCommit;
439 my $cust_contact = '';
441 my %hash = ( 'contactnum' => $self->contactnum,
442 'custnum' => $custnum,
445 if ( $cust_contact = qsearchs('cust_contact', \%hash ) ) {
446 $cust_contact->$_($link_hash{$_}) for keys %link_hash;
447 $error = $cust_contact->replace;
449 $cust_contact = new FS::cust_contact { %hash, %link_hash };
450 $error = $cust_contact->insert;
453 $dbh->rollback if $oldAutoCommit;
458 if ( $prospectnum ) {
459 my %hash = ( 'contactnum' => $self->contactnum,
460 'prospectnum' => $prospectnum,
463 if ( my $prospect_contact = qsearchs('prospect_contact', \%hash ) ) {
464 $prospect_contact->$_($link_hash{$_}) for keys %link_hash;
465 $error = $prospect_contact->replace;
467 my $prospect_contact = new FS::prospect_contact { %hash, %link_hash };
468 $error = $prospect_contact->insert;
471 $dbh->rollback if $oldAutoCommit;
476 foreach my $pf ( grep { /^phonetypenum(\d+)$/ }
477 keys %{ $self->hashref } ) {
478 $pf =~ /^phonetypenum(\d+)$/ or die "wtf (daily, the)";
479 my $phonetypenum = $1;
481 my %cp = ( 'contactnum' => $self->contactnum,
482 'phonetypenum' => $phonetypenum,
484 my $contact_phone = qsearchs('contact_phone', \%cp);
486 my $pv = $self->get($pf);
489 #if new value is empty, delete old entry
491 if ($contact_phone) {
492 $error = $contact_phone->delete;
494 $dbh->rollback if $oldAutoCommit;
501 $contact_phone ||= new FS::contact_phone \%cp;
503 my %cpd = _parse_phonestring( $pv );
504 $contact_phone->set( $_ => $cpd{$_} ) foreach keys %cpd;
506 my $method = $contact_phone->contactphonenum ? 'replace' : 'insert';
508 $error = $contact_phone->$method;
510 $dbh->rollback if $oldAutoCommit;
515 if ( defined($self->hashref->{'emailaddress'}) ) {
517 #ineffecient but whatever, how many email addresses can there be?
519 foreach my $contact_email ( $self->contact_email ) {
520 my $error = $contact_email->delete;
522 $dbh->rollback if $oldAutoCommit;
527 foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
529 my $contact_email = new FS::contact_email {
530 'contactnum' => $self->contactnum,
531 'emailaddress' => $email,
533 $error = $contact_email->insert;
535 $dbh->rollback if $oldAutoCommit;
543 unless ( $skip_fuzzyfiles ) { #unless ( $import || $skip_fuzzyfiles ) {
544 #warn " queueing fuzzyfiles update\n"
546 $error = $self->queue_fuzzyfiles_update;
548 $dbh->rollback if $oldAutoCommit;
549 return "updating fuzzy search cache: $error";
553 if ( $cust_contact and (
554 ( $cust_contact->selfservice_access eq ''
555 && $link_hash{selfservice_access}
556 && ! length($self->_password)
558 || $cust_contact->_resend()
562 my $error = $self->send_reset_email( queue=>1 );
564 $dbh->rollback if $oldAutoCommit;
569 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
575 =item _parse_phonestring PHONENUMBER_STRING
577 Subroutine, takes a string and returns a list (suitable for assigning to a hash)
578 with keys 'countrycode', 'phonenum' and 'extension'
580 (Should probably be moved to contact_phone.pm, hence the initial underscore.)
584 sub _parse_phonestring {
587 my($countrycode, $extension) = ('1', '');
590 if ( $value =~ s/^\s*\+\s*(\d+)// ) {
596 if ( $value =~ s/\s*(ext|x)\s*(\d+)\s*$//i ) {
600 ( 'countrycode' => $countrycode,
601 'phonenum' => $value,
602 'extension' => $extension,
606 =item queue_fuzzyfiles_update
608 Used by insert & replace to update the fuzzy search cache
612 use FS::cust_main::Search;
613 sub queue_fuzzyfiles_update {
616 local $SIG{HUP} = 'IGNORE';
617 local $SIG{INT} = 'IGNORE';
618 local $SIG{QUIT} = 'IGNORE';
619 local $SIG{TERM} = 'IGNORE';
620 local $SIG{TSTP} = 'IGNORE';
621 local $SIG{PIPE} = 'IGNORE';
623 my $oldAutoCommit = $FS::UID::AutoCommit;
624 local $FS::UID::AutoCommit = 0;
627 foreach my $field ( 'first', 'last' ) {
628 my $queue = new FS::queue {
629 'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
631 my @args = "contact.$field", $self->get($field);
632 my $error = $queue->insert( @args );
634 $dbh->rollback if $oldAutoCommit;
635 return "queueing job (transaction rolled back): $error";
639 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
646 Checks all fields to make sure this is a valid contact. If there is
647 an error, returns the error, otherwise returns false. Called by the insert
655 if ( $self->selfservice_access eq 'R' ) {
656 $self->selfservice_access('Y');
661 $self->ut_numbern('contactnum')
662 || $self->ut_foreign_keyn('prospectnum', 'prospect_main', 'prospectnum')
663 || $self->ut_foreign_keyn('custnum', 'cust_main', 'custnum')
664 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
665 || $self->ut_foreign_keyn('classnum', 'contact_class', 'classnum')
666 || $self->ut_namen('last')
667 || $self->ut_namen('first')
668 || $self->ut_textn('title')
669 || $self->ut_textn('comment')
670 || $self->ut_enum('selfservice_access', [ '', 'Y' ])
671 || $self->ut_textn('_password')
672 || $self->ut_enum('_password_encoding', [ '', 'bcrypt'])
673 || $self->ut_enum('disabled', [ '', 'Y' ])
675 return $error if $error;
677 return "Prospect and customer!" if $self->prospectnum && $self->custnum;
679 return "One of first name, last name, or title must have a value"
680 if ! grep $self->$_(), qw( first last title);
687 Returns a formatted string representing this contact, including name, title and
694 my $data = $self->first. ' '. $self->last;
695 $data .= ', '. $self->title
697 $data .= ' ('. $self->comment. ')'
704 Returns a formatted string representing this contact, with just the name.
710 $self->first . ' ' . $self->last;
713 #=item contact_classname PROSPECT_OBJ | CUST_MAIN_OBJ
715 #Returns the name of this contact's class for the specified prospect or
716 #customer (see L<FS::prospect_contact>, L<FS::cust_contact> and
717 #L<FS::contact_class>).
721 #sub contact_classname {
722 # my( $self, $prospect_or_cust ) = @_;
725 # if ( ref($prospect_or_cust) eq 'FS::prospect_main' ) {
726 # $link = qsearchs('prospect_contact', {
727 # 'contactnum' => $self->contactnum,
728 # 'prospectnum' => $prospect_or_cust->prospectnum,
730 # } elsif ( ref($prospect_or_cust) eq 'FS::cust_main' ) {
731 # $link = qsearchs('cust_contact', {
732 # 'contactnum' => $self->contactnum,
733 # 'custnum' => $prospect_or_cust->custnum,
736 # croak "$prospect_or_cust is not an FS::prospect_main or FS::cust_main object";
739 # my $contact_class = $link->contact_class or return '';
740 # $contact_class->classname;
743 =item by_selfservice_email EMAILADDRESS
745 Alternate search constructor (class method). Given an email address,
746 returns the contact for that address, or the empty string if no contact
747 has that email address.
751 sub by_selfservice_email {
752 my($class, $email) = @_;
754 my $contact_email = qsearchs({
755 'table' => 'contact_email',
756 'addl_from' => ' LEFT JOIN contact USING ( contactnum ) ',
757 'hashref' => { 'emailaddress' => $email, },
758 'extra_sql' => " AND ( disabled IS NULL OR disabled = '' )",
761 $contact_email->contact;
765 #these three functions are very much false laziness w/FS/FS/Auth/internal.pm
766 # and should maybe be libraried in some way for other password needs
768 use Crypt::Eksblowfish::Bcrypt qw( bcrypt_hash en_base64 de_base64);
770 sub authenticate_password {
771 my($self, $check_password) = @_;
773 if ( $self->_password_encoding eq 'bcrypt' ) {
775 my( $cost, $salt, $hash ) = split(',', $self->_password);
777 my $check_hash = en_base64( bcrypt_hash( { key_nul => 1,
779 salt => de_base64($salt),
785 $hash eq $check_hash;
789 return 0 if $self->_password eq '';
791 $self->_password eq $check_password;
797 =item change_password NEW_PASSWORD
799 Changes the contact's selfservice access password to NEW_PASSWORD. This does
800 not check password policy rules (see C<is_password_allowed>) and will return
801 an error only if editing the record fails for some reason.
803 If NEW_PASSWORD is the same as the existing password, this does nothing.
807 sub change_password {
808 my($self, $new_password) = @_;
810 # do nothing if the password is unchanged
811 return if $self->authenticate_password($new_password);
813 $self->change_password_fields( $new_password );
819 sub change_password_fields {
820 my($self, $new_password) = @_;
822 $self->_password_encoding('bcrypt');
826 my $salt = pack( 'C*', map int(rand(256)), 1..16 );
828 my $hash = bcrypt_hash( { key_nul => 1,
836 join(',', $cost, en_base64($salt), en_base64($hash) )
841 # end of false laziness w/FS/FS/Auth/internal.pm
844 #false laziness w/ClientAPI/MyAccount/reset_passwd
845 use Digest::SHA qw(sha512_hex);
847 use FS::ClientAPI_SessionCache;
848 sub send_reset_email {
849 my( $self, %opt ) = @_;
851 my @contact_email = $self->contact_email or return '';
853 my $reset_session = {
854 'contactnum' => $self->contactnum,
855 'svcnum' => $opt{'svcnum'},
858 my $timeout = '24 hours'; #?
860 my $reset_session_id;
862 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
863 } until ( ! defined $self->myaccount_cache->get("reset_passwd_$reset_session_id") );
866 $self->myaccount_cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
870 my $conf = new FS::Conf;
873 my @cust_contact = grep $_->selfservice_access, $self->cust_contact;
874 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
876 my $agentnum = $cust_main ? $cust_main->agentnum : '';
877 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $agentnum);
878 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
879 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
880 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
881 return { 'error' => "selfservice-password_reset_msgnum cannot be loaded" } unless $msg_template;
883 'to' => join(',', map $_->emailaddress, @contact_email ),
884 'cust_main' => $cust_main,
886 'substitutions' => { 'session_id' => $reset_session_id }
889 if ( $opt{'queue'} ) { #or should queueing just be the default?
891 my $cust_msg = $msg_template->prepare( %msg_template );
892 my $error = $cust_msg->insert;
893 return { 'error' => $error } if $error;
894 my $queue = new FS::queue {
895 'job' => 'FS::cust_msg::process_send',
896 'custnum' => $cust_main ? $cust_main->custnum : '',
898 $queue->insert( $cust_msg->custmsgnum );
902 $msg_template->send( %msg_template );
908 use vars qw( $myaccount_cache );
909 sub myaccount_cache {
911 $myaccount_cache ||= new FS::ClientAPI_SessionCache( {
912 'namespace' => 'FS::ClientAPI::MyAccount',
916 =item cgi_contact_fields
918 Returns a list reference containing the set of contact fields used in the web
919 interface for one-line editing (i.e. excluding contactnum, prospectnum, custnum
920 and locationnum, as well as password fields, but including fields for
921 contact_email and contact_phone records.)
925 sub cgi_contact_fields {
928 my @contact_fields = qw(
929 classnum first last title comment emailaddress selfservice_access
933 push @contact_fields, 'phonetypenum'. $_->phonetypenum
934 foreach qsearch({table=>'phone_type', order_by=>'weight'});
940 use FS::upgrade_journal;
941 sub _upgrade_data { #class method
942 my ($class, %opts) = @_;
944 # always migrate cust_main_invoice records over
945 local $FS::cust_main::import = 1; # override require_phone and such
946 my $search = FS::Cursor->new('cust_main_invoice', {});
947 while (my $cust_main_invoice = $search->fetch) {
948 my $custnum = $cust_main_invoice->custnum;
949 my $dest = $cust_main_invoice->dest;
950 my $cust_main = $cust_main_invoice->cust_main;
952 if ( $dest =~ /^\d+$/ ) {
953 my $svc_acct = FS::svc_acct->by_key($dest);
954 die "custnum $custnum, invoice destination svcnum $svc_acct does not exist\n"
956 $dest = $svc_acct->email;
959 my $error = $cust_main->replace( invoicing_list => [ $dest ] );
962 die "custnum $custnum, invoice destination $dest, creating contact: $error\n";
965 $error = $cust_main_invoice->delete;
966 die "custnum $custnum, cleaning up cust_main_invoice: $error\n" if $error;
968 } # while $search->fetch
970 unless ( FS::upgrade_journal->is_done('contact_invoice_dest') ) {
972 foreach my $contact (qsearch('contact', {})) {
973 my $error = $contact->replace;
974 die $error if $error;
977 FS::upgrade_journal->set_done('contact_invoice_dest');
988 L<FS::Record>, schema.html from the base documentation.