feat: Extract Brazil phone number normalization into generic service (#12492)
This PR refactors existing Brazil phone number normalization logic into a generic, extensible service while maintaining backward compatibility. Also extracts it into a dedicated service designed for expansion to support additional countries. --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
# Base class for country-specific phone number normalizers
|
||||
# Each country normalizer should inherit from this class and implement:
|
||||
# - country_code_pattern: regex to identify the country code
|
||||
# - normalize: logic to convert phone number to normalized format for contact lookup
|
||||
class Whatsapp::PhoneNormalizers::BasePhoneNormalizer
|
||||
def handles_country?(waid)
|
||||
waid.match(country_code_pattern)
|
||||
end
|
||||
|
||||
def normalize(waid)
|
||||
raise NotImplementedError, 'Subclasses must implement #normalize'
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def country_code_pattern
|
||||
raise NotImplementedError, 'Subclasses must implement #country_code_pattern'
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,26 @@
|
||||
# Handles Brazil phone number normalization
|
||||
# ref: https://github.com/chatwoot/chatwoot/issues/5840
|
||||
#
|
||||
# Brazil changed its mobile number system by adding a "9" prefix to existing numbers.
|
||||
# This normalizer adds the "9" digit if the number is 12 digits (making it 13 digits total)
|
||||
# to match the new format: 55 + DDD + 9 + number
|
||||
class Whatsapp::PhoneNormalizers::BrazilPhoneNormalizer < Whatsapp::PhoneNormalizers::BasePhoneNormalizer
|
||||
COUNTRY_CODE_LENGTH = 2
|
||||
DDD_LENGTH = 2
|
||||
|
||||
def normalize(waid)
|
||||
return waid unless handles_country?(waid)
|
||||
|
||||
ddd = waid[COUNTRY_CODE_LENGTH, DDD_LENGTH]
|
||||
number = waid[COUNTRY_CODE_LENGTH + DDD_LENGTH, waid.length - (COUNTRY_CODE_LENGTH + DDD_LENGTH)]
|
||||
normalized_number = "55#{ddd}#{number}"
|
||||
normalized_number = "55#{ddd}9#{number}" if normalized_number.length != 13
|
||||
normalized_number
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def country_code_pattern
|
||||
/^55/
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user