feat(whatsapp): enrutamiento inteligente para grupo central de notificaciones y aprobaciones

This commit is contained in:
AI Bot 2026-08-24 13:43:59 -05:00
parent f474fa64f0
commit 98f13621ba
2 changed files with 61 additions and 16 deletions

View File

@ -4,7 +4,7 @@ import { InputFile } from 'node-appwrite/file';
import { createAdminClient } from '@/lib/appwrite.server';
import { APPWRITE_ALMEIRA_CONFIG } from '@/lib/appwrite';
import { processWhatsAppMessage } from '@/lib/gemini';
import { sendWhatsAppMessage, getBase64FromMediaMessage, fetchRecentMediaFromSameChat } from '@/lib/evolution';
import { sendWhatsAppMessage, getBase64FromMediaMessage, fetchRecentMediaFromSameChat, getNotificationGroupJid } from '@/lib/evolution';
import { isWhatsAppChatAllowed } from '@/lib/whatsapp-filter';
// Función para obtener el último día del mes actual
@ -189,14 +189,30 @@ export async function POST(req: Request) {
return NextResponse.json({ success: true, message: 'Ignored empty message' }, { status: 200 });
}
// Descubrir si existe un grupo central de Notificaciones/Aprobaciones
const adminNotificationJid = await getNotificationGroupJid();
const destinationJid = adminNotificationJid || remoteJid;
const isCentralizedAdmin = Boolean(adminNotificationJid && adminNotificationJid !== remoteJid);
// Notificación de Progreso 1: Recepción inmediata
try {
await sendWhatsAppMessage(
remoteJid,
`📥 *Información Recibida*\n` +
`_Almeira Web • Asistente Editorial con IA_\n\n` +
`🤖 Iniciando análisis con IA y procesamiento de contenido...`
);
if (isCentralizedAdmin) {
// Acuse discreto a la fuente/cliente
await sendWhatsAppMessage(
remoteJid,
`📥 *Comunicado Recibido*\n` +
`_Almeira Web • Redacción Editorial_\n\n` +
`Tu información ha sido recibida y remitida a la mesa editorial para su revisión.`
);
} else {
// Notificación directa en el mismo chat
await sendWhatsAppMessage(
remoteJid,
`📥 *Información Recibida*\n` +
`_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);
}
@ -240,14 +256,14 @@ export async function POST(req: Request) {
? `🖼️ *Imagen:* Optimizando foto destacada (${isSquare ? 'Formato 640x640' : 'Formato 640x360'})`
: `📄 *Formato:* Publicación en texto`;
await sendWhatsAppMessage(
remoteJid,
`⚙️ *Procesando Publicación*\n\n` +
`📌 *Titular:* ${parsed.titulo}\n` +
`📂 *Categoría:* ${parsed.tipo.toUpperCase()}\n` +
`${mediaStatus}\n\n` +
`💾 Registrando en la biblioteca de medios y guardando borrador en la web...`
);
const progressMsg = `⚙️ *Procesando Publicación*\n`
+ (isCentralizedAdmin ? `📍 *Fuente:* ${filterResult.resolvedName}\n\n` : '\n')
+ `📌 *Titular:* ${parsed.titulo}\n`
+ `📂 *Categoría:* ${parsed.tipo.toUpperCase()}\n`
+ `${mediaStatus}\n\n`
+ `💾 Registrando en la biblioteca de medios y guardando borrador en la web...`;
await sendWhatsAppMessage(destinationJid, progressMsg);
} catch (err: any) {
console.warn('[WhatsApp Webhook] No se pudo enviar notificación de progreso:', err.message);
}
@ -369,6 +385,7 @@ export async function POST(req: Request) {
}
const requestText = `🔔 *PUBLICACIÓN LISTA - SOLICITUD DE APROBACIÓN*\n\n`
+ (isCentralizedAdmin ? `📍 *Fuente:* ${filterResult.resolvedName}\n\n` : '')
+ `📌 *Titular:*\n${parsed.titulo}\n\n`
+ `🖼️ *Imagen Destacada:*\n${imageNotice}\n\n`
+ `📝 *Resumen:*\n${parsed.seo_descripcion}\n\n`
@ -380,7 +397,7 @@ export async function POST(req: Request) {
+ `❌ *Rechazar* (para descartar el borrador)\n\n`
+ `(Ref: ${newPost.$id})`;
await sendWhatsAppMessage(remoteJid, requestText);
await sendWhatsAppMessage(destinationJid, requestText);
return NextResponse.json({ success: true, message: 'Mensaje procesado con notificaciones de progreso' }, { status: 200 });

View File

@ -163,3 +163,31 @@ export async function getWhatsAppGroupSubject(groupJid: string): Promise<string
return null;
}
/**
* Automatically discovers the dedicated Admin/Notification group JID if one exists
*/
export async function getNotificationGroupJid(): Promise<string | null> {
if (process.env.WHATSAPP_ADMIN_NOTIFICATION_JID) {
return process.env.WHATSAPP_ADMIN_NOTIFICATION_JID;
}
try {
const groups = await fetchAllWhatsAppGroups();
const found = groups.find(g => {
const name = (g.subject || '').toLowerCase();
return name.includes('notificaciones almeira') ||
name.includes('aprobaciones almeira') ||
name.includes('redacción almeira') ||
name.includes('redaccion almeira');
});
if (found) {
return found.id;
}
} catch (err: any) {
console.warn('Could not discover notification group:', err?.message);
}
return null;
}