2019-12-24 07:57:25 +00:00
|
|
|
class ContactMergeAction
|
|
|
|
pattr_initialize [:account!, :base_contact!, :mergee_contact!]
|
|
|
|
|
|
|
|
def perform
|
2021-06-22 10:27:48 +00:00
|
|
|
# This case happens when an agent updates a contact email in dashboard,
|
|
|
|
# while the contact also update his email via email collect box
|
|
|
|
return @base_contact if base_contact.id == mergee_contact.id
|
|
|
|
|
2019-12-24 07:57:25 +00:00
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
validate_contacts
|
|
|
|
merge_conversations
|
2020-03-18 20:22:38 +00:00
|
|
|
merge_messages
|
2019-12-24 07:57:25 +00:00
|
|
|
merge_contact_inboxes
|
|
|
|
remove_mergee_contact
|
|
|
|
end
|
2020-04-03 07:34:58 +00:00
|
|
|
@base_contact
|
2019-12-24 07:57:25 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def validate_contacts
|
|
|
|
return if belongs_to_account?(@base_contact) && belongs_to_account?(@mergee_contact)
|
|
|
|
|
2020-04-07 04:49:19 +00:00
|
|
|
raise StandardError, 'contact does not belong to the account'
|
2019-12-24 07:57:25 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def belongs_to_account?(contact)
|
|
|
|
@account.id == contact.account_id
|
|
|
|
end
|
|
|
|
|
|
|
|
def merge_conversations
|
|
|
|
Conversation.where(contact_id: @mergee_contact.id).update(contact_id: @base_contact.id)
|
|
|
|
end
|
|
|
|
|
2020-03-18 20:22:38 +00:00
|
|
|
def merge_messages
|
2020-06-27 16:04:53 +00:00
|
|
|
Message.where(sender: @mergee_contact).update(sender: @base_contact)
|
2020-03-18 20:22:38 +00:00
|
|
|
end
|
|
|
|
|
2019-12-24 07:57:25 +00:00
|
|
|
def merge_contact_inboxes
|
|
|
|
ContactInbox.where(contact_id: @mergee_contact.id).update(contact_id: @base_contact.id)
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_mergee_contact
|
|
|
|
@mergee_contact.destroy!
|
|
|
|
end
|
|
|
|
end
|