2022-10-13 22:12:04 +00:00
|
|
|
# This Builder will create a contact inbox with specified attributes. If the contact inbox already exists, it will be returned.
|
|
|
|
# For Specific Channels like whatsapp, email etc . it smartly generated appropriate the source id when none is provided.
|
|
|
|
|
2021-04-15 09:43:01 +00:00
|
|
|
class ContactInboxBuilder
|
2022-10-13 22:12:04 +00:00
|
|
|
pattr_initialize [:contact, :inbox, :source_id, { hmac_verified: false }]
|
2021-04-15 09:43:01 +00:00
|
|
|
|
|
|
|
def perform
|
2022-10-13 22:12:04 +00:00
|
|
|
@source_id ||= generate_source_id
|
|
|
|
create_contact_inbox if source_id.present?
|
2021-04-15 09:43:01 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def generate_source_id
|
2022-02-03 23:22:13 +00:00
|
|
|
case @inbox.channel_type
|
|
|
|
when 'Channel::TwilioSms'
|
|
|
|
twilio_source_id
|
|
|
|
when 'Channel::Whatsapp'
|
|
|
|
wa_source_id
|
|
|
|
when 'Channel::Email'
|
2022-10-13 22:12:04 +00:00
|
|
|
email_source_id
|
2022-02-03 23:22:13 +00:00
|
|
|
when 'Channel::Sms'
|
2022-10-13 22:12:04 +00:00
|
|
|
phone_source_id
|
|
|
|
when 'Channel::Api', 'Channel::WebWidget'
|
2022-02-03 23:22:13 +00:00
|
|
|
SecureRandom.uuid
|
2022-10-13 22:12:04 +00:00
|
|
|
else
|
|
|
|
raise "Unsupported operation for this channel: #{@inbox.channel_type}"
|
2022-02-03 23:22:13 +00:00
|
|
|
end
|
2021-04-15 09:43:01 +00:00
|
|
|
end
|
|
|
|
|
2022-10-13 22:12:04 +00:00
|
|
|
def email_source_id
|
|
|
|
raise ActionController::ParameterMissing, 'contact email' unless @contact.email
|
|
|
|
|
|
|
|
@contact.email
|
|
|
|
end
|
|
|
|
|
|
|
|
def phone_source_id
|
|
|
|
raise ActionController::ParameterMissing, 'contact phone number' unless @contact.phone_number
|
|
|
|
|
|
|
|
@contact.phone_number
|
|
|
|
end
|
|
|
|
|
2021-11-30 15:20:35 +00:00
|
|
|
def wa_source_id
|
2022-10-13 22:12:04 +00:00
|
|
|
raise ActionController::ParameterMissing, 'contact phone number' unless @contact.phone_number
|
2021-11-30 15:20:35 +00:00
|
|
|
|
|
|
|
# whatsapp doesn't want the + in e164 format
|
2022-09-29 17:34:55 +00:00
|
|
|
@contact.phone_number.delete('+').to_s
|
2021-11-30 15:20:35 +00:00
|
|
|
end
|
|
|
|
|
2021-04-15 09:43:01 +00:00
|
|
|
def twilio_source_id
|
2022-10-13 22:12:04 +00:00
|
|
|
raise ActionController::ParameterMissing, 'contact phone number' unless @contact.phone_number
|
2021-04-15 09:43:01 +00:00
|
|
|
|
|
|
|
case @inbox.channel.medium
|
|
|
|
when 'sms'
|
|
|
|
@contact.phone_number
|
|
|
|
when 'whatsapp'
|
|
|
|
"whatsapp:#{@contact.phone_number}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2022-10-13 22:12:04 +00:00
|
|
|
def create_contact_inbox
|
|
|
|
::ContactInbox.create_with(hmac_verified: hmac_verified || false).find_or_create_by!(
|
2021-04-15 09:43:01 +00:00
|
|
|
contact_id: @contact.id,
|
|
|
|
inbox_id: @inbox.id,
|
2022-10-13 22:12:04 +00:00
|
|
|
source_id: @source_id
|
2021-04-15 09:43:01 +00:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|