Actualizar server.js

This commit is contained in:
2026-03-15 13:31:08 +00:00
parent d80baf95b8
commit ea52f3afce

View File

@@ -1828,11 +1828,17 @@ app.post("/providers/scraped", authMiddleware, async (req, res) => {
"SELECT auto_dispatch FROM provider_credentials WHERE owner_id = $1 AND provider = $2",
[req.user.accountId, provider]
);
const autoDispatchEnabled = credsQ.rowCount > 0 && credsQ.rows[0].auto_dispatch === true;
// 🐛 ¡AQUÍ ESTABA EL BUG DEL INTERRUPTOR! 🐛
// La BD devuelve un 1, pero JS esperaba un 'true'. Lo hacemos flexible:
let autoDispatchEnabled = false;
if (credsQ.rowCount > 0) {
const val = credsQ.rows[0].auto_dispatch;
autoDispatchEnabled = (val === true || val === 1 || val === '1' || val === 't');
}
for (const svc of services) {
// 1. EXTRAER REFERENCIA A PRUEBA DE BOMBAS
const ref = svc['service_ref']
|| svc['SERVICIO']
|| svc['Referencia']
@@ -1842,34 +1848,22 @@ app.post("/providers/scraped", authMiddleware, async (req, res) => {
|| (svc.raw_data && (svc.raw_data['SERVICIO'] || svc.raw_data['Referencia'] || svc.raw_data['Nº Siniestro'] || svc.raw_data['Expediente'] || svc.raw_data['expediente']));
if (!ref) {
console.log("⚠️ Se omitió un servicio por no encontrar el número de referencia.");
console.log("⚠️ Se omitió un servicio por no encontrar referencia.");
continue;
}
// 🔥 2. DETECTOR DE URGENCIAS MODO DIOS 🔥
let esUrgente = false;
const todoElTexto = JSON.stringify(svc).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\n/g, " ");
// Convertimos todo a un texto gigante, minúsculas, sin acentos ni símbolos raros
const todoElTexto = JSON.stringify(svc)
.toLowerCase()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/\n/g, " "); // Quitamos saltos de línea por si acaso
// 1. Detección HomeServe: Busca la frase clave de la Bandeja de Entrada o del Interior
if (todoElTexto.includes("atencion presencial urgencias") || todoElTexto.includes("atencion de la urgencia") || todoElTexto.includes("por atencion")) {
esUrgente = true;
}
// 2. Detección Multiasistencia: Busca el combo "urgente":"si" literal en el JSON
if (todoElTexto.includes('"urgente":"si"') || todoElTexto.includes('"urgencia":"si"')) {
esUrgente = true;
}
// 3. Extracción de Gremio
const guildId = svc.guild_id || svc['guild_id'] || (svc.raw_data && svc.raw_data.guild_id);
// 4. GUARDAMOS EN LA BD (CON MEMORIA ETERNA: OR EXCLUDED.is_urgent)
const insertRes = await pool.query(`
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, is_urgent)
VALUES ($1, $2, $3, $4, $5)
@@ -1883,26 +1877,22 @@ app.post("/providers/scraped", authMiddleware, async (req, res) => {
const newSvcId = insertRes.rows[0].id;
const autoStatus = insertRes.rows[0].automation_status;
// 5. AUTO-DESPACHO
if (esUrgente && guildId && autoDispatchEnabled && (autoStatus === 'manual' || autoStatus === 'pending')) {
console.log(`⚡ [AUTO-DISPATCH] Lanzando urgencia ${ref} a la bolsa...`);
// 🕵️ CHIVATO EN CONSOLA PARA VER POR QUÉ NO SALTA
console.log(`[DEBUG-BOLSA] Ref: ${ref} | Urgente: ${esUrgente} | Gremio: ${guildId} | Auto_ON: ${autoDispatchEnabled} | Estado: ${autoStatus}`);
// 🔥 DISPARO AUTOMÁTICO REPARADO 🔥
if (esUrgente && guildId && autoDispatchEnabled && (autoStatus === 'manual' || autoStatus === 'pending')) {
console.log(`⚡ [AUTO-DISPATCH] Lanzando urgencia ${ref} a la bolsa internamente...`);
const cpMatch = todoElTexto.match(/\b\d{5}\b/);
const cpFinal = cpMatch ? cpMatch[0] : "00000";
const port = process.env.PORT || 3000;
fetch(`http://127.0.0.1:${port}/providers/automate/${newSvcId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': req.headers.authorization },
body: JSON.stringify({ guild_id: guildId, cp: cpFinal, useDelay: false })
}).catch(e => console.error("Error en auto-despacho:", e.message));
// Llamamos directamente a la función
dispatchToBolsa(newSvcId, guildId, cpFinal, req.user.accountId, req.user.sub);
}
count++;
}
res.json({ ok: true, inserted: count });
} catch (error) {
console.error("❌ Error recibiendo servicios:", error);
res.status(500).json({ ok: false, error: error.message });