summaryrefslogtreecommitdiff
path: root/app/models/customer_relations/contact.rb
blob: 168f1c48a6c0525218d036e3d9ca8303950989b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true

class CustomerRelations::Contact < ApplicationRecord
  include StripAttribute

  self.table_name = "customer_relations_contacts"

  belongs_to :group, -> { where(type: Group.sti_name) }, foreign_key: 'group_id'
  belongs_to :organization, optional: true
  has_many :issue_contacts, inverse_of: :contact
  has_many :issues, through: :issue_contacts, inverse_of: :customer_relations_contacts

  strip_attributes! :phone, :first_name, :last_name

  enum state: {
    inactive: 0,
    active: 1
  }

  validates :group, presence: true
  validates :phone, length: { maximum: 32 }
  validates :first_name, presence: true, length: { maximum: 255 }
  validates :last_name, presence: true, length: { maximum: 255 }
  validates :email, length: { maximum: 255 }
  validates :description, length: { maximum: 1024 }
  validate :validate_email_format
  validate :unique_email_for_group_hierarchy

  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)
  end

  private

  def validate_email_format
    return unless email

    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

    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
  end
end