2019-08-30 22:38:00 +00:00
|
|
|
module Facebook
|
|
|
|
class SendReplyService
|
|
|
|
pattr_initialize [:message!]
|
|
|
|
|
|
|
|
def perform
|
|
|
|
return if message.private
|
2019-10-20 10:49:12 +00:00
|
|
|
return if inbox.channel.class.to_s != 'Channel::FacebookPage'
|
2019-10-20 08:47:26 +00:00
|
|
|
return unless outgoing_message_from_chatwoot?
|
2019-08-30 22:38:00 +00:00
|
|
|
|
|
|
|
Bot.deliver(delivery_params, access_token: message.channel_token)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-10-20 19:10:18 +00:00
|
|
|
delegate :contact, to: :conversation
|
|
|
|
|
2019-08-30 22:38:00 +00:00
|
|
|
def inbox
|
|
|
|
@inbox ||= message.inbox
|
|
|
|
end
|
|
|
|
|
|
|
|
def conversation
|
|
|
|
@conversation ||= message.conversation
|
|
|
|
end
|
|
|
|
|
|
|
|
def outgoing_message_from_chatwoot?
|
2019-10-20 08:47:26 +00:00
|
|
|
# messages sent directly from chatwoot won't have fb_id.
|
2019-08-30 22:38:00 +00:00
|
|
|
message.outgoing? && !message.fb_id
|
|
|
|
end
|
|
|
|
|
|
|
|
# def reopen_lock
|
|
|
|
# if message.incoming? && conversation.locked?
|
|
|
|
# conversation.unlock!
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
|
|
|
|
def fb_message_params
|
|
|
|
{
|
2019-10-27 07:44:36 +00:00
|
|
|
recipient: { id: contact.get_source_id(inbox.id) },
|
2019-10-20 08:47:26 +00:00
|
|
|
message: { text: message.content }
|
2019-08-30 22:38:00 +00:00
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def delivery_params
|
|
|
|
if twenty_four_hour_window_over?
|
2019-10-20 08:47:26 +00:00
|
|
|
fb_message_params.merge(tag: 'ISSUE_RESOLUTION')
|
2019-08-30 22:38:00 +00:00
|
|
|
else
|
|
|
|
fb_message_params
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def twenty_four_hour_window_over?
|
|
|
|
last_incoming_message = conversation.messages.incoming.last
|
|
|
|
|
|
|
|
is_after_24_hours = (Time.current - last_incoming_message.created_at) / 3600 >= 24
|
|
|
|
|
2019-10-20 10:49:12 +00:00
|
|
|
return false unless is_after_24_hours
|
2019-08-30 22:38:00 +00:00
|
|
|
|
2019-10-20 10:49:12 +00:00
|
|
|
return false if last_incoming_message && sent_first_outgoing_message_after_24_hours?(last_incoming_message.id)
|
2019-08-30 22:38:00 +00:00
|
|
|
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2019-10-20 10:49:12 +00:00
|
|
|
def sent_first_outgoing_message_after_24_hours?(last_incoming_message_id)
|
2019-10-20 08:47:26 +00:00
|
|
|
# we can send max 1 message after 24 hour window
|
|
|
|
conversation.messages.outgoing.where('id > ?', last_incoming_message_id).count == 1
|
2019-08-30 22:38:00 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|