Actualizar server.js
This commit is contained in:
46
server.js
46
server.js
@@ -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",
|
"SELECT auto_dispatch FROM provider_credentials WHERE owner_id = $1 AND provider = $2",
|
||||||
[req.user.accountId, provider]
|
[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) {
|
for (const svc of services) {
|
||||||
|
|
||||||
// 1. EXTRAER REFERENCIA A PRUEBA DE BOMBAS
|
|
||||||
const ref = svc['service_ref']
|
const ref = svc['service_ref']
|
||||||
|| svc['SERVICIO']
|
|| svc['SERVICIO']
|
||||||
|| svc['Referencia']
|
|| 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']));
|
|| (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) {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔥 2. DETECTOR DE URGENCIAS MODO DIOS 🔥
|
|
||||||
let esUrgente = false;
|
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")) {
|
if (todoElTexto.includes("atencion presencial urgencias") || todoElTexto.includes("atencion de la urgencia") || todoElTexto.includes("por atencion")) {
|
||||||
esUrgente = true;
|
esUrgente = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Detección Multiasistencia: Busca el combo "urgente":"si" literal en el JSON
|
|
||||||
if (todoElTexto.includes('"urgente":"si"') || todoElTexto.includes('"urgencia":"si"')) {
|
if (todoElTexto.includes('"urgente":"si"') || todoElTexto.includes('"urgencia":"si"')) {
|
||||||
esUrgente = true;
|
esUrgente = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Extracción de Gremio
|
|
||||||
const guildId = svc.guild_id || svc['guild_id'] || (svc.raw_data && svc.raw_data.guild_id);
|
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(`
|
const insertRes = await pool.query(`
|
||||||
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, is_urgent)
|
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, is_urgent)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
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 newSvcId = insertRes.rows[0].id;
|
||||||
const autoStatus = insertRes.rows[0].automation_status;
|
const autoStatus = insertRes.rows[0].automation_status;
|
||||||
|
|
||||||
// 5. AUTO-DESPACHO
|
// 🕵️ 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')) {
|
if (esUrgente && guildId && autoDispatchEnabled && (autoStatus === 'manual' || autoStatus === 'pending')) {
|
||||||
console.log(`⚡ [AUTO-DISPATCH] Lanzando urgencia ${ref} a la bolsa...`);
|
console.log(`⚡ [AUTO-DISPATCH] Lanzando urgencia ${ref} a la bolsa internamente...`);
|
||||||
|
|
||||||
const cpMatch = todoElTexto.match(/\b\d{5}\b/);
|
const cpMatch = todoElTexto.match(/\b\d{5}\b/);
|
||||||
const cpFinal = cpMatch ? cpMatch[0] : "00000";
|
const cpFinal = cpMatch ? cpMatch[0] : "00000";
|
||||||
|
|
||||||
const port = process.env.PORT || 3000;
|
// Llamamos directamente a la función
|
||||||
fetch(`http://127.0.0.1:${port}/providers/automate/${newSvcId}`, {
|
dispatchToBolsa(newSvcId, guildId, cpFinal, req.user.accountId, req.user.sub);
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json({ ok: true, inserted: count });
|
res.json({ ok: true, inserted: count });
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("❌ Error recibiendo servicios:", error);
|
console.error("❌ Error recibiendo servicios:", error);
|
||||||
res.status(500).json({ ok: false, error: error.message });
|
res.status(500).json({ ok: false, error: error.message });
|
||||||
|
|||||||
Reference in New Issue
Block a user