2019-09-02 10:52:54 +00:00
|
|
|
# frozen_string_literal: true
|
2019-08-14 09:48:44 +00:00
|
|
|
|
2019-09-02 10:52:54 +00:00
|
|
|
class Inbox < ApplicationRecord
|
2019-08-14 09:48:44 +00:00
|
|
|
validates :account_id, presence: true
|
|
|
|
|
|
|
|
belongs_to :account
|
|
|
|
belongs_to :channel, polymorphic: true, dependent: :destroy
|
|
|
|
|
|
|
|
has_many :inbox_members, dependent: :destroy
|
|
|
|
has_many :members, through: :inbox_members, source: :user
|
|
|
|
has_many :conversations, dependent: :destroy
|
|
|
|
has_many :messages, through: :conversations
|
|
|
|
has_many :contacts, dependent: :destroy
|
2019-08-19 08:19:57 +00:00
|
|
|
after_create :subscribe_webhook, if: :facebook?
|
|
|
|
after_destroy :delete_round_robin_agents
|
2019-08-14 09:48:44 +00:00
|
|
|
|
|
|
|
def add_member(user_id)
|
|
|
|
member = inbox_members.new(user_id: user_id)
|
|
|
|
member.save!
|
|
|
|
end
|
|
|
|
|
|
|
|
def remove_member(user_id)
|
|
|
|
member = inbox_members.find_by(user_id: user_id)
|
|
|
|
member.try(:destroy)
|
|
|
|
end
|
|
|
|
|
|
|
|
def facebook?
|
2019-09-02 10:52:54 +00:00
|
|
|
channel.class.name.to_s == 'FacebookPage'
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def next_available_agent
|
2019-09-02 10:52:54 +00:00
|
|
|
user_id = Redis::Alfred.rpoplpush(round_robin_key, round_robin_key)
|
2019-08-14 09:48:44 +00:00
|
|
|
account.users.find_by(id: user_id)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def delete_round_robin_agents
|
|
|
|
Redis::Alfred.delete(round_robin_key)
|
|
|
|
end
|
|
|
|
|
|
|
|
def round_robin_key
|
2019-09-02 10:52:54 +00:00
|
|
|
Constants::RedisKeys::ROUND_ROBIN_AGENTS % { inbox_id: id }
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def subscribe_webhook
|
2019-09-02 10:52:54 +00:00
|
|
|
Facebook::Messenger::Subscriptions.subscribe(access_token: channel.page_access_token)
|
2019-08-14 09:48:44 +00:00
|
|
|
end
|
|
|
|
end
|