iachat/app/services/whatsapp/phone_number_normalization_service.rb
Muhsin Keloth f44e47a624
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>
2025-09-25 11:23:43 +05:30

40 lines
1.2 KiB
Ruby

# Service to handle phone number normalization for WhatsApp messages
# Currently supports Brazil phone number format variations
# Designed to be extensible for additional countries in future PRs
#
# Usage: Whatsapp::PhoneNumberNormalizationService.new(inbox).normalize_and_find_contact(waid)
class Whatsapp::PhoneNumberNormalizationService
def initialize(inbox)
@inbox = inbox
end
# Main entry point for phone number normalization
# Returns the source_id of an existing contact if found, otherwise returns original waid
def normalize_and_find_contact(waid)
normalizer = find_normalizer_for_country(waid)
return waid unless normalizer
normalized_waid = normalizer.normalize(waid)
existing_contact_inbox = find_existing_contact_inbox(normalized_waid)
existing_contact_inbox&.source_id || waid
end
private
attr_reader :inbox
def find_normalizer_for_country(waid)
NORMALIZERS.map(&:new)
.find { |normalizer| normalizer.handles_country?(waid) }
end
def find_existing_contact_inbox(normalized_waid)
inbox.contact_inboxes.find_by(source_id: normalized_waid)
end
NORMALIZERS = [
Whatsapp::PhoneNormalizers::BrazilPhoneNormalizer
].freeze
end