+ #save off and blank values that move to cust_contact / prospect_contact now
+ my $prospectnum = $self->prospectnum;
+ $self->prospectnum('');
+ my $custnum = $self->custnum;
+ $self->custnum('');
+
+ my %link_hash = ();
+ for (qw( classnum comment selfservice_access )) {
+ $link_hash{$_} = $self->get($_);
+ $self->$_('');
+ }
+
+ #look for an existing contact with this email address
+ my $existing_contact = '';
+ if ( $self->get('emailaddress') =~ /\S/ ) {
+
+ my %existing_contact = ();
+
+ foreach my $email ( split(/\s*,\s*/, $self->get('emailaddress') ) ) {
+
+ my $contact_email = qsearchs('contact_email', { emailaddress=>$email } )
+ or next;
+
+ my $contact = $contact_email->contact;
+ $existing_contact{ $contact->contactnum } = $contact;
+
+ }
+
+ if ( scalar( keys %existing_contact ) > 1 ) {
+ $dbh->rollback if $oldAutoCommit;
+ return 'Multiple email addresses specified '.
+ ' that already belong to separate contacts';
+ } elsif ( scalar( keys %existing_contact ) ) {
+ ($existing_contact) = values %existing_contact;
+ }
+
+ }
+
+ if ( $existing_contact ) {
+
+ $self->$_($existing_contact->$_())
+ for qw( contactnum _password _password_encoding );
+ $self->SUPER::replace($existing_contact);
+
+ } else {
+
+ my $error = $self->SUPER::insert;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+
+ }
+
+ my $cust_contact = '';
+ if ( $custnum ) {
+ my %hash = ( 'contactnum' => $self->contactnum,
+ 'custnum' => $custnum,
+ );
+ $cust_contact = qsearchs('cust_contact', \%hash )
+ || new FS::cust_contact { %hash, %link_hash };
+ my $error = $cust_contact->custcontactnum ? $cust_contact->replace
+ : $cust_contact->insert;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }
+ }
+
+ if ( $prospectnum ) {
+ my %hash = ( 'contactnum' => $self->contactnum,
+ 'prospectnum' => $prospectnum,
+ );
+ my $prospect_contact = qsearchs('prospect_contact', \%hash )
+ || new FS::prospect_contact { %hash, %link_hash };
+ my $error =
+ $prospect_contact->prospectcontactnum ? $prospect_contact->replace
+ : $prospect_contact->insert;
+ if ( $error ) {
+ $dbh->rollback if $oldAutoCommit;
+ return $error;
+ }