From 74a0fc1dd354a753fbeb8ab43677be9097efe60d Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 15 Mar 2026 17:30:40 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 851ae9d..9065d4b 100644 --- a/server.js +++ b/server.js @@ -3726,7 +3726,8 @@ app.post("/webhook/evolution", async (req, res) => { setInterval(async () => { const client = await pool.connect(); // <-- Conectamos de forma segura try { - const expiredPings = await client.query(` + // --- 1. CADUCIDAD DE PINGS (Reasignación si el operario no contesta) --- + const expiredPings = await client.query(` SELECT ap.id, ap.scraped_id, ap.user_id, s.owner_id, s.raw_data FROM assignment_pings ap JOIN scraped_services s ON ap.scraped_id = s.id @@ -3758,12 +3759,43 @@ setInterval(async () => { await client.query("UPDATE scraped_services SET automation_status = 'failed' WHERE id = $1", [ping.scraped_id]); } } + + // --- 2. 🚨 NUEVO: CAZADOR DE URGENCIAS QUE "ENTRAN SOLAS" 🚨 --- + // Buscamos servicios que sean urgentes y que sigan atascados en 'manual' o 'pending' + const pendingUrgent = await client.query(` + SELECT s.id, s.owner_id, s.guild_id, s.raw_data, s.provider, s.service_ref, pc.auto_dispatch + FROM scraped_services s + LEFT JOIN provider_credentials pc ON s.owner_id = pc.owner_id AND s.provider = pc.provider + WHERE s.is_urgent = true + AND s.automation_status IN ('manual', 'pending') + `); + + for (const svc of pendingUrgent.rows) { + // Comprobamos si el interruptor de ese proveedor está encendido (1, '1', 't' o true) + const isAutoOn = svc.auto_dispatch === true || svc.auto_dispatch === 1 || svc.auto_dispatch === '1' || svc.auto_dispatch === 't'; + + // Sacamos el gremio + const finalGuildId = svc.guild_id || (svc.raw_data && svc.raw_data.guild_id); + + if (isAutoOn && finalGuildId) { + console.log(`⚡ [RELOJ] Cazador automático ha encontrado la urgencia #${svc.service_ref}. ¡Lanzando a bolsa!`); + + // Extraemos el código postal si existe en el raw_data + const todoElTexto = JSON.stringify(svc.raw_data || {}).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); + const cpMatch = todoElTexto.match(/\b\d{5}\b/); + const cpFinal = cpMatch ? cpMatch[0] : "00000"; + + // 🔥 Disparamos la función mágica que reparte los WhatsApps + await dispatchToBolsa(svc.id, finalGuildId, cpFinal, svc.owner_id, null); + } + } + } catch (e) { console.error("Reloj:", e); } finally { client.release(); // <-- Liberamos la conexión SIEMPRE } -}, 60000); +}, 60000); // Se ejecuta en bucle cada 60.000 milisegundos (1 minuto) const port = process.env.PORT || 3000; autoUpdateDB().then(() => { app.listen(port, "0.0.0.0", () => console.log(`🚀 Server OK en puerto ${port}`)); }); \ No newline at end of file