fix: Duplicate conversations and contacts WA and Brazil numbers (#6222)

Resolves issue when receiving a message from Brazil  Whatsapp number.
Fixes: #5840


Co-authored-by: Sojan <sojan@pepalo.com>
This commit is contained in:
Jacson Santos
2023-03-13 04:50:53 -03:00
committed by GitHub
parent c9b63ae8eb
commit 2e95d3a173
3 changed files with 99 additions and 3 deletions

View File

@@ -84,8 +84,10 @@ class Whatsapp::IncomingMessageBaseService
contact_params = @processed_params[:contacts]&.first
return if contact_params.blank?
waid = processed_waid(contact_params[:wa_id])
contact_inbox = ::ContactInboxWithContactBuilder.new(
source_id: contact_params[:wa_id],
source_id: waid,
inbox: inbox,
contact_attributes: { name: contact_params.dig(:profile, :name), phone_number: "+#{@processed_params[:messages].first[:from]}" }
).perform

View File

@@ -47,6 +47,38 @@ module Whatsapp::IncomingMessageServiceHelpers
%w[reaction ephemeral unsupported].include?(message_type)
end
def brazil_phone_number?(phone_number)
phone_number.match(/^55/)
end
# ref: https://github.com/chatwoot/chatwoot/issues/5840
def normalised_brazil_mobile_number(phone_number)
# DDD : Area codes in Brazil are popularly known as "DDD codes" (códigos DDD) or simply "DDD", from the initials of "direct distance dialing"
# https://en.wikipedia.org/wiki/Telephone_numbers_in_Brazil
ddd = phone_number[2, 2]
# Remove country code and DDD to obtain the number
number = phone_number[4, phone_number.length - 4]
normalised_number = "55#{ddd}#{number}"
# insert 9 to convert the number to the new mobile number format
normalised_number = "55#{ddd}9#{number}" if normalised_number.length != 13
normalised_number
end
def processed_waid(waid)
# in case of Brazil, we need to do additional processing
# https://github.com/chatwoot/chatwoot/issues/5840
if brazil_phone_number?(waid)
# check if there is an existing contact inbox with the normalised waid
# We will create conversation against it
contact_inbox = inbox.contact_inboxes.find_by(source_id: normalised_brazil_mobile_number(waid))
# if there is no contact inbox with the waid without 9,
# We will create contact inboxes and contacts with the number 9 added
waid = contact_inbox.source_id if contact_inbox.present?
end
waid
end
def error_webhook_event?(message)
message.key?('errors')
end