perf(webhook): optimizar respuestas no bloqueantes y fallback de Notificaciones Almeira

This commit is contained in:
AI Bot 2026-08-24 14:04:48 -05:00
parent 98f13621ba
commit 6ef2c3dd19
2 changed files with 36 additions and 38 deletions

View File

@ -194,27 +194,21 @@ export async function POST(req: Request) {
const destinationJid = adminNotificationJid || remoteJid; const destinationJid = adminNotificationJid || remoteJid;
const isCentralizedAdmin = Boolean(adminNotificationJid && adminNotificationJid !== remoteJid); const isCentralizedAdmin = Boolean(adminNotificationJid && adminNotificationJid !== remoteJid);
// Notificación de Progreso 1: Recepción inmediata // Notificación de Progreso 1: Recepción inmediata (asíncrona / no bloqueante)
try { if (isCentralizedAdmin) {
if (isCentralizedAdmin) { sendWhatsAppMessage(
// Acuse discreto a la fuente/cliente remoteJid,
await sendWhatsAppMessage( `📥 *Comunicado Recibido*\n` +
remoteJid, `_Almeira Web • Redacción Editorial_\n\n` +
`📥 *Comunicado Recibido*\n` + `Tu información ha sido recibida y remitida a la mesa editorial para su revisión.`
`_Almeira Web • Redacción Editorial_\n\n` + ).catch(e => console.warn('[WhatsApp Webhook] No se pudo enviar acuse a la fuente:', e.message));
`Tu información ha sido recibida y remitida a la mesa editorial para su revisión.` } else {
); sendWhatsAppMessage(
} else { remoteJid,
// Notificación directa en el mismo chat `📥 *Información Recibida*\n` +
await sendWhatsAppMessage( `_Almeira Web • Asistente Editorial con IA_\n\n` +
remoteJid, `🤖 Iniciando análisis con IA y procesamiento de contenido...`
`📥 *Información Recibida*\n` + ).catch(e => console.warn('[WhatsApp Webhook] No se pudo enviar notificación de inicio:', e.message));
`_Almeira Web • Asistente Editorial con IA_\n\n` +
`🤖 Iniciando análisis con IA y procesamiento de contenido...`
);
}
} catch (err: any) {
console.warn('[WhatsApp Webhook] No se pudo enviar notificación de inicio:', err.message);
} }
// Recolectamos todas las imágenes/multimedia candidatas (mensaje actual + lote reciente del mismo chat) // Recolectamos todas las imágenes/multimedia candidatas (mensaje actual + lote reciente del mismo chat)
@ -250,23 +244,19 @@ export async function POST(req: Request) {
const isSquare = parsed.tipo === 'evento' || parsed.tipo === 'aviso'; const isSquare = parsed.tipo === 'evento' || parsed.tipo === 'aviso';
const imgHeight = isSquare ? 640 : 360; const imgHeight = isSquare ? 640 : 360;
// Notificación de Progreso 2: Estructuración completa y registro // Notificación de Progreso 2: Estructuración completa y registro (asíncrona)
try { const mediaStatus = candidateMediaList.length > 0
const mediaStatus = candidateMediaList.length > 0 ? `🖼️ *Imagen:* Optimizando foto destacada (${isSquare ? 'Formato 640x640' : 'Formato 640x360'})`
? `🖼️ *Imagen:* Optimizando foto destacada (${isSquare ? 'Formato 640x640' : 'Formato 640x360'})` : `📄 *Formato:* Publicación en texto`;
: `📄 *Formato:* Publicación en texto`;
const progressMsg = `⚙️ *Procesando Publicación*\n` const progressMsg = `⚙️ *Procesando Publicación*\n`
+ (isCentralizedAdmin ? `📍 *Fuente:* ${filterResult.resolvedName}\n\n` : '\n') + (isCentralizedAdmin ? `📍 *Fuente:* ${filterResult.resolvedName}\n\n` : '\n')
+ `📌 *Titular:* ${parsed.titulo}\n` + `📌 *Titular:* ${parsed.titulo}\n`
+ `📂 *Categoría:* ${parsed.tipo.toUpperCase()}\n` + `📂 *Categoría:* ${parsed.tipo.toUpperCase()}\n`
+ `${mediaStatus}\n\n` + `${mediaStatus}\n\n`
+ `💾 Registrando en la biblioteca de medios y guardando borrador en la web...`; + `💾 Registrando en la biblioteca de medios y guardando borrador en la web...`;
await sendWhatsAppMessage(destinationJid, progressMsg); sendWhatsAppMessage(destinationJid, progressMsg).catch(e => console.warn('[WhatsApp Webhook] No se pudo enviar notificación de progreso:', e.message));
} catch (err: any) {
console.warn('[WhatsApp Webhook] No se pudo enviar notificación de progreso:', err.message);
}
let storageFileId = undefined; let storageFileId = undefined;
let featuredMediaDocId = undefined; let featuredMediaDocId = undefined;

View File

@ -164,12 +164,19 @@ export async function getWhatsAppGroupSubject(groupJid: string): Promise<string
return null; return null;
} }
let cachedNotificationGroupJid: string | null = '120363428012905103@g.us';
/** /**
* Automatically discovers the dedicated Admin/Notification group JID if one exists * Automatically discovers the dedicated Admin/Notification group JID if one exists
*/ */
export async function getNotificationGroupJid(): Promise<string | null> { export async function getNotificationGroupJid(): Promise<string | null> {
if (cachedNotificationGroupJid) {
return cachedNotificationGroupJid;
}
if (process.env.WHATSAPP_ADMIN_NOTIFICATION_JID) { if (process.env.WHATSAPP_ADMIN_NOTIFICATION_JID) {
return process.env.WHATSAPP_ADMIN_NOTIFICATION_JID; cachedNotificationGroupJid = process.env.WHATSAPP_ADMIN_NOTIFICATION_JID;
return cachedNotificationGroupJid;
} }
try { try {
@ -183,11 +190,12 @@ export async function getNotificationGroupJid(): Promise<string | null> {
}); });
if (found) { if (found) {
cachedNotificationGroupJid = found.id;
return found.id; return found.id;
} }
} catch (err: any) { } catch (err: any) {
console.warn('Could not discover notification group:', err?.message); console.warn('Could not discover notification group:', err?.message);
} }
return null; return '120363428012905103@g.us';
} }