fix: normalizar ID de WhatsApp para usuarios y grupos

Co-authored-by: aider (openrouter/openai/gpt-5) <aider@aider.chat>
pull/1/head
borja 1 month ago
parent ae0a853b63
commit 7308c73a79

@ -1,43 +1,38 @@
/**
* Normalizes a WhatsApp ID by removing the domain part (@s.whatsapp.net, @g.us)
* and any participant identifier (:12).
* Handles potential variations like participant IDs in group messages.
*
* Examples:
* Normaliza un ID de WhatsApp.
* - Para usuarios (DMs o @s.whatsapp.net): devuelve solo dígitos.
* - Para grupos (@g.us): devuelve el identificador numérico con guion (ej. 12345-67890).
*
* Ejemplos:
* - '1234567890@s.whatsapp.net' -> '1234567890'
* - '+34 600 123 456' -> '34600123456'
* - '1234567890:12@s.whatsapp.net' -> '1234567890'
* - '1234567890-1234567890@g.us' -> '1234567890-1234567890'
* - '1234567890:12@s.whatsapp.net' -> '1234567890' (handles participant format)
* - 'status_me@broadcast' -> 'status_me' (handles status broadcast)
*
* @param id The raw WhatsApp ID string. Can be null or undefined.
* @returns The normalized ID string, or null if the input is null/undefined or invalid after normalization.
* - 'status_me@broadcast' -> null
*/
export function normalizeWhatsAppId(id: string | null | undefined): string | null {
if (!id) {
return null;
}
// Remove domain part (@s.whatsapp.net, @g.us, @broadcast etc.)
let normalized = id.split('@')[0];
// Handle potential participant format like '1234567890:12' by taking the part before ':'
normalized = normalized.split(':')[0];
// Basic validation: should contain alphanumeric characters, possibly hyphens for group IDs
// Allows simple numbers, group IDs with hyphens, and potentially status_me
if (!/^[a-zA-Z0-9_-]+$/.test(normalized)) {
console.warn(`[normalizeWhatsAppId] Invalid characters found in WhatsApp ID after normalization: ${id} -> ${normalized}`);
// Return null for clearly invalid IDs after normalization
return null;
}
if (!id) return null;
const raw = String(id).trim();
if (!raw) return null;
// Partes antes de @ y antes de ':' (participante)
const atIdx = raw.indexOf('@');
const beforeAt = atIdx >= 0 ? raw.slice(0, atIdx) : raw;
const core = beforeAt.split(':')[0];
// Prevent empty strings after normalization
if (normalized.length === 0) {
console.warn(`[normalizeWhatsAppId] Empty string resulted from normalization: ${id}`);
return null;
// Si es un JID de grupo (en el raw termina en @g.us), conservar dígitos y guion
if (raw.endsWith('@g.us')) {
const groupCore = core.replace(/[^0-9-]/g, '');
// Aceptar formatos tipo "123-456" o "123456" (algunas libs incluyen un único bloque)
if (!groupCore) return null;
if (!/^\d+(?:-\d+)?$/.test(groupCore)) return null;
return groupCore;
}
return normalized;
// Usuarios: conservar solo dígitos (eliminar +, espacios, etc.)
const digits = core.replace(/\D+/g, '');
if (!digits) return null;
return digits;
}
/**

Loading…
Cancel
Save