Chatwoot/app/models/inbox.rb
Pranav Raj Sreepuram 2a34255e0b Initial Commit
Co-authored-by: Subin <subinthattaparambil@gmail.com>
Co-authored-by: Manoj <manojmj92@gmail.com>
Co-authored-by: Nithin <webofnithin@gmail.com>
2019-08-14 15:18:44 +05:30

55 lines
1.4 KiB
Ruby

class Inbox < ApplicationRecord
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
after_commit :subscribe_webhook, on: [:create], if: :facebook?
after_commit :delete_round_robin_agents, on: [:destroy]
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?
channel.class.name.to_s == "FacebookPage"
end
def next_available_agent
user_id = Redis::Alfred.rpoplpush(round_robin_key,round_robin_key)
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
Constants::RedisKeys::ROUND_ROBIN_AGENTS % { :inbox_id => self.id }
end
def subscribe_webhook
Facebook::Messenger::Subscriptions.subscribe(access_token: self.channel.page_access_token)
begin
#async this asap
Phantomjs.run('m.js', self.channel.page_id) if account.inboxes.count == 1 #only for first inbox of the account
rescue => e
true
end
end
end