Actualizar server.js

This commit is contained in:
2026-03-15 10:38:14 +00:00
parent 76e193ef22
commit 07881c7ce5

View File

@@ -1812,7 +1812,7 @@ app.post("/providers/credentials", authMiddleware, async (req, res) => {
});
// ==========================================
// 📥 RECEPCIÓN DE SERVICIOS (EMBUDO INTELIGENTE CON AUTO-DESPACHO Y TODOTERRENO)
// 📥 RECEPCIÓN DE SERVICIOS (EMBUDO INTELIGENTE CON AUTO-DESPACHO Y TODOTERRENO FINAL)
// ==========================================
app.post("/providers/scraped", authMiddleware, async (req, res) => {
try {
@@ -1833,37 +1833,29 @@ app.post("/providers/scraped", authMiddleware, async (req, res) => {
for (const svc of services) {
// 2. Extraer la referencia
const ref = svc['Referencia'] || svc['Nº Siniestro'] || svc['Expediente'] || svc['service_ref'];
// 2. Extraer la referencia (revisamos la raíz y el raw_data por si viene anidado)
const ref = svc['Referencia'] || svc['Nº Siniestro'] || svc['Expediente'] || svc['service_ref'] || (svc.raw_data && svc.raw_data['Referencia']);
if (!ref) continue;
// 🔥 3. DETECTOR DE URGENCIAS ANTI-FALLOS (TODOTERRENO) 🔥
// 🔥 3. DETECTOR DE URGENCIAS ANTI-FALLOS (APLASTAMIENTO TOTAL) 🔥
let esUrgente = false;
// Recorremos TODOS los campos que mande el proveedor
for (const key in svc) {
const valor = String(svc[key]).toLowerCase();
if (
valor.includes('atencion presencial urgencias') ||
valor.includes('urgencia') ||
valor.includes('urgente')
) {
esUrgente = true;
break;
}
if (key.toLowerCase().includes('urgent') && (valor === 'sí' || valor === 'si' || valor === 'true')) {
esUrgente = true;
break;
}
// Convertimos TODO el expediente (con todas sus subcapas) a un texto gigante,
// en minúsculas y sin acentos para que no se escape nada.
const todoElTexto = JSON.stringify(svc).toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
if (
todoElTexto.includes('atencion presencial urgencias') ||
todoElTexto.includes('urgencia') ||
todoElTexto.includes('urgente')
) {
esUrgente = true;
}
// 🕵️ 4. EXTRAER GREMIO (Ya viene en el objeto enviado)
const guildId = svc.guild_id || svc['guild_id'];
const guildId = svc.guild_id || svc['guild_id'] || (svc.raw_data && svc.raw_data.guild_id);
// 5. Guardamos en la Base de Datos
// Usamos RETURNING para saber el ID generado y el estado de automatización actual
const insertRes = await pool.query(`
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, is_urgent)
VALUES ($1, $2, $3, $4, $5)
@@ -1878,22 +1870,18 @@ app.post("/providers/scraped", authMiddleware, async (req, res) => {
const autoStatus = insertRes.rows[0].automation_status;
// 🚀 6. ¡DISPARADOR AUTOMÁTICO DE URGENCIAS!
// Solo si: Es urgente + Tiene Gremio + Botón ON + No se ha enviado ya (status manual/pending)
if (esUrgente && guildId && autoDispatchEnabled && (autoStatus === 'manual' || autoStatus === 'pending')) {
console.log(`⚡ [AUTO-DISPATCH] Lanzando urgencia ${ref} de ${provider} a la bolsa...`);
// Extraemos CP para afinar la búsqueda si es posible
const cpMatch = String(svc['Código Postal'] || svc['C.P.'] || "").match(/\b\d{5}\b/);
const cpMatch = todoElTexto.match(/\b\d{5}\b/);
const cpFinal = cpMatch ? cpMatch[0] : "00000";
// Llamamos a tu lógica de automatización interna
// Usamos fetch local para reutilizar la lógica de asignación aleatoria y pings
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 // Reutilizamos el token del scraper
'Authorization': req.headers.authorization
},
body: JSON.stringify({
guild_id: guildId,