feat(whatsapp): enrutamiento inteligente para grupo central de notificaciones y aprobaciones
This commit is contained in:
parent
f474fa64f0
commit
98f13621ba
@ -4,7 +4,7 @@ import { InputFile } from 'node-appwrite/file';
|
|||||||
import { createAdminClient } from '@/lib/appwrite.server';
|
import { createAdminClient } from '@/lib/appwrite.server';
|
||||||
import { APPWRITE_ALMEIRA_CONFIG } from '@/lib/appwrite';
|
import { APPWRITE_ALMEIRA_CONFIG } from '@/lib/appwrite';
|
||||||
import { processWhatsAppMessage } from '@/lib/gemini';
|
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';
|
import { isWhatsAppChatAllowed } from '@/lib/whatsapp-filter';
|
||||||
|
|
||||||
// Función para obtener el último día del mes actual
|
// 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 });
|
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
|
// Notificación de Progreso 1: Recepción inmediata
|
||||||
try {
|
try {
|
||||||
|
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(
|
await sendWhatsAppMessage(
|
||||||
remoteJid,
|
remoteJid,
|
||||||
`📥 *Información Recibida*\n` +
|
`📥 *Información Recibida*\n` +
|
||||||
`_Almeira Web • Asistente Editorial con IA_\n\n` +
|
`_Almeira Web • Asistente Editorial con IA_\n\n` +
|
||||||
`🤖 Iniciando análisis con IA y procesamiento de contenido...`
|
`🤖 Iniciando análisis con IA y procesamiento de contenido...`
|
||||||
);
|
);
|
||||||
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.warn('[WhatsApp Webhook] No se pudo enviar notificación de inicio:', err.message);
|
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'})`
|
? `🖼️ *Imagen:* Optimizando foto destacada (${isSquare ? 'Formato 640x640' : 'Formato 640x360'})`
|
||||||
: `📄 *Formato:* Publicación en texto`;
|
: `📄 *Formato:* Publicación en texto`;
|
||||||
|
|
||||||
await sendWhatsAppMessage(
|
const progressMsg = `⚙️ *Procesando Publicación*\n`
|
||||||
remoteJid,
|
+ (isCentralizedAdmin ? `📍 *Fuente:* ${filterResult.resolvedName}\n\n` : '\n')
|
||||||
`⚙️ *Procesando Publicació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);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.warn('[WhatsApp Webhook] No se pudo enviar notificación de progreso:', err.message);
|
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`
|
const requestText = `🔔 *PUBLICACIÓN LISTA - SOLICITUD DE APROBACIÓN*\n\n`
|
||||||
|
+ (isCentralizedAdmin ? `📍 *Fuente:* ${filterResult.resolvedName}\n\n` : '')
|
||||||
+ `📌 *Titular:*\n${parsed.titulo}\n\n`
|
+ `📌 *Titular:*\n${parsed.titulo}\n\n`
|
||||||
+ `🖼️ *Imagen Destacada:*\n${imageNotice}\n\n`
|
+ `🖼️ *Imagen Destacada:*\n${imageNotice}\n\n`
|
||||||
+ `📝 *Resumen:*\n${parsed.seo_descripcion}\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`
|
+ `❌ *Rechazar* (para descartar el borrador)\n\n`
|
||||||
+ `(Ref: ${newPost.$id})`;
|
+ `(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 });
|
return NextResponse.json({ success: true, message: 'Mensaje procesado con notificaciones de progreso' }, { status: 200 });
|
||||||
|
|
||||||
|
|||||||
@ -163,3 +163,31 @@ export async function getWhatsAppGroupSubject(groupJid: string): Promise<string
|
|||||||
|
|
||||||
return null;
|
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;
|
||||||
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user