diff --git a/enterprise/app/models/enterprise/concerns/contact.rb b/enterprise/app/models/enterprise/concerns/contact.rb index 4362a915d..910af6e45 100644 --- a/enterprise/app/models/enterprise/concerns/contact.rb +++ b/enterprise/app/models/enterprise/concerns/contact.rb @@ -15,13 +15,17 @@ module Enterprise::Concerns::Contact def should_associate_company? # Only trigger if: # 1. Contact has an email - # 2. Contact doesn't have a compan yet + # 2. Contact doesn't have a company yet # 3. Email was just set/changed # 4. Email was previously nil (first time getting email) + # 5. The account has the Companies feature enabled + # Feature check is last so unrelated contact updates short-circuit on the + # cheap in-memory guards before touching the account (hot message-ingest path). email.present? && company_id.nil? && saved_change_to_email? && - saved_change_to_email.first.nil? + saved_change_to_email.first.nil? && + account.feature_enabled?('companies') end def associate_company_from_email diff --git a/spec/enterprise/models/contact_company_association_spec.rb b/spec/enterprise/models/contact_company_association_spec.rb index 6ed8af4f6..0930eefb9 100644 --- a/spec/enterprise/models/contact_company_association_spec.rb +++ b/spec/enterprise/models/contact_company_association_spec.rb @@ -4,6 +4,26 @@ RSpec.describe Contact, type: :model do describe 'company auto-association' do let(:account) { create(:account) } + before { account.enable_features!(:companies) } + + context 'when the companies feature is disabled' do + before { account.disable_features!(:companies) } + + it 'does not create or associate a company' do + expect do + create(:contact, email: 'john@acme.com', account: account) + end.not_to change(Company, :count) + expect(described_class.last.company).to be_nil + end + + it 'preserves a contact-supplied company_name' do + contact = create(:contact, email: 'john@acme.com', account: account, + additional_attributes: { 'company_name' => 'John Personal Co' }) + + expect(contact.reload.additional_attributes['company_name']).to eq('John Personal Co') + end + end + context 'when creating a new contact with business email' do it 'automatically creates and associates a company' do expect do