UNPKG

@ria-sys/mcp

Version:

MCP Server para integração com WhatsApp

117 lines (105 loc) 4.22 kB
export class PhoneFormatter { /** * Formata números de celular brasileiros para o formato E.164 * Remove caracteres especiais e adiciona o código do país (55) se necessário * Adiciona o dígito 9 automaticamente se o número tiver 10 dígitos * @param phones Array de números de celular para formatar * @param removeNinthDigit Se true, remove o nono dígito após a formatação * @returns Array de números formatados no padrão E.164 (ex: 5511999999999 ou 5511999999999) * @throws Error se o número for inválido */ static formatBrazilianPhones(phones: string[], removeNinthDigit: boolean = false): string[] { return phones.map(phone => { try { let cleaned = phone.replace(/[^\d+]/g, ''); if (cleaned.startsWith('+')) { cleaned = cleaned.substring(1); } let countryCode = ''; if (cleaned.startsWith('55')) { countryCode = cleaned.substring(0, 2); cleaned = cleaned.substring(2); } const ddd = cleaned.substring(0, 2); if (!PhoneFormatter.isValidDDD(parseInt(ddd))) { console.error('[PhoneFormatter] DDD inválido:', { phone, ddd }); throw new Error(`DDD inválido: ${ddd}`); } if (cleaned.length === 10) { cleaned = `${cleaned.substring(0, 2)}9${cleaned.substring(2)}`; } else if (cleaned.length !== 11) { console.error('[PhoneFormatter] Número com quantidade de dígitos inválida:', { phone, length: cleaned.length }); throw new Error(`Número inválido: ${phone}. Celular deve ter 10 ou 11 dígitos (DDD + número).`); } let formattedNumber = countryCode ? `${countryCode}${cleaned}` : `55${cleaned}`; if (removeNinthDigit) { formattedNumber = PhoneFormatter.removeNinthDigit(formattedNumber); } return formattedNumber; } catch (error) { console.error('[PhoneFormatter] Erro ao formatar número:', { phone, error: error instanceof Error ? error.message : 'Erro desconhecido' }); throw error; } }); } /** * Remove o nono dígito (9) de um número de celular brasileiro * @param phone Número no formato E.164 (5511999999999) * @returns Número sem o nono dígito (551199999999) */ static removeNinthDigit(phone: string): string { if (phone.length !== 13) { console.error('[PhoneFormatter] Tentativa de remover 9º dígito de número inválido:', { phone, length: phone.length }); throw new Error('Número deve estar no formato E.164 (13 dígitos começando com 55)'); } return `${phone.substring(0, 4)}${phone.substring(5)}`; } /** * Verifica se um DDD é válido * @param ddd Número do DDD para validar * @returns boolean indicando se o DDD é válido */ private static isValidDDD(ddd: number): boolean { const validDDDs = [ 11, 12, 13, 14, 15, 16, 17, 18, 19, // SP 21, 22, 24, 27, 28, // RJ, ES 31, 32, 33, 34, 35, 37, 38, // MG 41, 42, 43, 44, 45, 46, 47, 48, 49, // PR, SC 51, 53, 54, 55, // RS 61, 62, 63, 64, 65, 66, 67, 68, 69, // DF, GO, TO, MT, MS, AC, RO 71, 73, 74, 75, 77, 79, // BA, SE 81, 82, 83, 84, 85, 86, 87, 88, 89, // PE, AL, PB, RN, CE, PI 91, 92, 93, 94, 95, 96, 97, 98, 99 // PA, AM, RR, AP, MA ]; return validDDDs.includes(ddd); } /** * Formata um número de celular para exibição * @param phone Número no formato E.164 (5511999999999) * @returns Número formatado para exibição ((11) 99999-9999) */ static formatForDisplay(phone: string): string { if (!phone.startsWith('55') || phone.length !== 13) { console.error('[PhoneFormatter] Tentativa de formatar número inválido para exibição:', { phone, length: phone.length }); throw new Error('Número deve estar no formato E.164 (13 dígitos começando com 55)'); } const ddd = phone.substring(2, 4); const number = phone.substring(4); return `(${ddd}) ${number.substring(0, 5)}-${number.substring(5)}`; } }