diff --git a/src/app/api/webhooks/whatsapp/route.ts b/src/app/api/webhooks/whatsapp/route.ts index 18d3068..87604c9 100644 --- a/src/app/api/webhooks/whatsapp/route.ts +++ b/src/app/api/webhooks/whatsapp/route.ts @@ -71,10 +71,14 @@ export async function POST(req: Request) { // pero permitir tests que el administrador envíe desde el mismo celular del bot. if (fromMe && ( rawText.includes('SOLICITUD DE APROBACIÓN') || + rawText.includes('PUBLICACIÓN LISTA') || + rawText.includes('Información Recibida') || + rawText.includes('Procesando Publicación') || rawText.includes('Publicación Procesada') || rawText.includes('PUBLICACIÓN APROBADA') || rawText.includes('PUBLICACIÓN RECHAZADA') || - rawText.includes('Error al publicar') + rawText.includes('Error al publicar') || + rawText.includes('Bot de Almeira') )) { return NextResponse.json({ success: true, message: 'Ignored bot self-message loop' }, { status: 200 }); } @@ -185,6 +189,18 @@ export async function POST(req: Request) { return NextResponse.json({ success: true, message: 'Ignored empty message' }, { status: 200 }); } + // 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...` + ); + } 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) const candidateMediaList: Array<{ base64: string; mimeType: string }> = []; @@ -213,6 +229,29 @@ export async function POST(req: Request) { // Llamar a Gemini para estructurar la publicación y seleccionar la mejor imagen const parsed = await processWhatsAppMessage(text, candidateMediaList); + // Determinar dimensiones según el tipo de publicación + // Noticias: 640x360 (16:9) | Clasificados y Eventos: 640x640 (1:1) + const isSquare = parsed.tipo === 'evento' || parsed.tipo === 'aviso'; + const imgHeight = isSquare ? 640 : 360; + + // Notificación de Progreso 2: Estructuración completa y registro + try { + const mediaStatus = candidateMediaList.length > 0 + ? `🖼️ *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...` + ); + } catch (err: any) { + console.warn('[WhatsApp Webhook] No se pudo enviar notificación de progreso:', err.message); + } + let storageFileId = undefined; let featuredMediaDocId = undefined; @@ -258,12 +297,7 @@ export async function POST(req: Request) { } } - // Determinar dimensiones según el tipo de publicación - // Noticias: 640x360 (16:9) | Clasificados y Eventos: 640x640 (1:1) - const isSquare = parsed.tipo === 'evento' || parsed.tipo === 'aviso'; - const imgHeight = isSquare ? 640 : 360; let ogImageUrl = undefined; - if (storageFileId) { ogImageUrl = `${APPWRITE_ALMEIRA_CONFIG.endpoint}/storage/buckets/${APPWRITE_ALMEIRA_CONFIG.mediaBucketId}/files/${storageFileId}/preview?project=${APPWRITE_ALMEIRA_CONFIG.projectId}&width=640&height=${imgHeight}&quality=85`; } @@ -334,7 +368,7 @@ export async function POST(req: Request) { imageNotice = `1 foto procesada (${isSquare ? '640x640' : '640x360'})`; } - const requestText = `🔔 *SOLICITUD DE APROBACIÓN DE PUBLICACIÓN*\n\n` + const requestText = `🔔 *PUBLICACIÓN LISTA - SOLICITUD DE APROBACIÓN*\n\n` + `📌 *Titular:*\n${parsed.titulo}\n\n` + `🖼️ *Imagen Destacada:*\n${imageNotice}\n\n` + `📝 *Resumen:*\n${parsed.seo_descripcion}\n\n` @@ -348,7 +382,7 @@ export async function POST(req: Request) { await sendWhatsAppMessage(remoteJid, requestText); - return NextResponse.json({ success: true, message: 'Mensaje procesado' }, { status: 200 }); + return NextResponse.json({ success: true, message: 'Mensaje procesado con notificaciones de progreso' }, { status: 200 }); } catch (error: any) { console.error('Error in WhatsApp Webhook:', error);