diff options
Diffstat (limited to 'app/models/customer_relations/contact.rb')
-rw-r--r-- | app/models/customer_relations/contact.rb | 18 |
1 files changed, 7 insertions, 11 deletions
diff --git a/app/models/customer_relations/contact.rb b/app/models/customer_relations/contact.rb index a981351f4a0..4fa2c3fb8cf 100644 --- a/app/models/customer_relations/contact.rb +++ b/app/models/customer_relations/contact.rb @@ -23,8 +23,9 @@ class CustomerRelations::Contact < ApplicationRecord validates :last_name, presence: true, length: { maximum: 255 } validates :email, length: { maximum: 255 } validates :description, length: { maximum: 1024 } + validates :email, uniqueness: { scope: :group_id } validate :validate_email_format - validate :unique_email_for_group_hierarchy + validate :validate_root_group def self.reference_prefix '[contact:' @@ -41,14 +42,13 @@ class CustomerRelations::Contact < ApplicationRecord def self.find_ids_by_emails(group, emails) raise ArgumentError, "Cannot lookup more than #{MAX_PLUCK} emails" if emails.length > MAX_PLUCK - where(group_id: group.self_and_ancestor_ids, email: emails) - .pluck(:id) + where(group: group, email: emails).pluck(:id) end def self.exists_for_group?(group) return false unless group - exists?(group_id: group.self_and_ancestor_ids) + exists?(group: group) end private @@ -59,13 +59,9 @@ class CustomerRelations::Contact < ApplicationRecord self.errors.add(:email, I18n.t(:invalid, scope: 'valid_email.validations.email')) unless ValidateEmail.valid?(self.email) end - def unique_email_for_group_hierarchy - return unless group - return unless email + def validate_root_group + return if group&.root? - duplicate_email_exists = CustomerRelations::Contact - .where(group_id: group.self_and_hierarchy.pluck(:id), email: email) - .where.not(id: id).exists? - self.errors.add(:email, _('contact with same email already exists in group hierarchy')) if duplicate_email_exists + self.errors.add(:base, _('contacts can only be added to root groups')) end end |