Actualizar robot.js

This commit is contained in:
2026-04-07 06:48:45 +00:00
parent 3d4527eeb5
commit 43bd875688

166
robot.js
View File

@@ -16,35 +16,49 @@ function normalizarTexto(texto) {
return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
} }
// 🛠️ NUEVO: El "Gira-Nombres" EXCLUSIVO para HomeServe
function arreglarNombre(nombreRaw) { function arreglarNombre(nombreRaw) {
if (!nombreRaw) return ""; if (!nombreRaw) return "";
let nombreLimpio = nombreRaw.trim(); let nombreLimpio = nombreRaw.trim();
// Si detectamos que tiene una coma...
if (nombreLimpio.includes(',')) { if (nombreLimpio.includes(',')) {
let partes = nombreLimpio.split(','); let partes = nombreLimpio.split(',');
let apellidos = partes[0].trim(); let apellidos = partes[0].trim();
let nombre = partes[1].trim(); let nombre = partes[1].trim();
// Le damos la vuelta y quitamos espacios sobrantes
nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' '); nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' ');
} }
return nombreLimpio; return nombreLimpio;
} }
// 🛡️ DESCODIFICADOR UNIVERSAL PARA HOMESERVE (Arregla los +, Ó, Ñ, etc.)
function arreglarCodificacion(texto) { function arreglarCodificacion(texto) {
if (!texto) return ""; if (!texto) return "";
let limpio = texto.replace(/\+/g, ' '); let limpio = texto.replace(/\+/g, ' '); // Primero cambiamos los + por espacios
try { try {
// Truco clásico de Javascript para transformar ISO a UTF-8
limpio = decodeURIComponent(escape(limpio)); limpio = decodeURIComponent(escape(limpio));
} catch(e) {} } catch(e) {
// Si no se puede, lo dejamos con los espacios arreglados
}
return limpio.trim(); return limpio.trim();
} }
// NUEVO: La función ahora lee las keywords directamente del JSON de la base de datos
function clasificarGremio(descripcion, gremiosActivosDB) { function clasificarGremio(descripcion, gremiosActivosDB) {
if (!descripcion || gremiosActivosDB.length === 0) return null; if (!descripcion || gremiosActivosDB.length === 0) return null;
const descNormalizada = normalizarTexto(descripcion); const descNormalizada = normalizarTexto(descripcion);
for (const gremio of gremiosActivosDB) { for (const gremio of gremiosActivosDB) {
// Obtenemos las palabras clave guardadas desde el panel de configuración
const keywords = Array.isArray(gremio.ia_keywords) ? gremio.ia_keywords : []; const keywords = Array.isArray(gremio.ia_keywords) ? gremio.ia_keywords : [];
if (keywords.length === 0) continue;
if (keywords.length === 0) continue; // Si no tiene reglas, pasamos al siguiente
// Comprobamos si alguna palabra clave coincide con la descripción
const coincide = keywords.some(kw => descNormalizada.includes(normalizarTexto(kw))); const coincide = keywords.some(kw => descNormalizada.includes(normalizarTexto(kw)));
if (coincide) { if (coincide) {
console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`); console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`);
return gremio.id; return gremio.id;
@@ -53,15 +67,17 @@ function clasificarGremio(descripcion, gremiosActivosDB) {
return null; return null;
} }
// Función auxiliar para reintentar la navegación si hay fallo de red
async function gotoWithRetry(page, url, retries = 3) { async function gotoWithRetry(page, url, retries = 3) {
for (let i = 0; i < retries; i++) { for (let i = 0; i < retries; i++) {
try { try {
// Usamos domcontentloaded para que no se quede colgado esperando imágenes o scripts pesados
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 }); await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
return; return; // Si funciona, salimos de la función
} catch (e) { } catch (e) {
if (i === retries - 1) throw e; if (i === retries - 1) throw e; // Si es el último intento, lanza el error
console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`); console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`);
await page.waitForTimeout(3000); await page.waitForTimeout(3000); // Esperamos 3 segundos antes de volver a intentar
} }
} }
} }
@@ -71,6 +87,7 @@ async function main() {
while (true) { while (true) {
const client = await pool.connect(); const client = await pool.connect();
try { try {
// 1. CARGAMOS LOS GREMIOS ACTUALES (AHORA INCLUYE LAS PALABRAS CLAVE)
const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds"); const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds");
const gremiosDB = gremiosRes.rows; const gremiosDB = gremiosRes.rows;
@@ -79,6 +96,7 @@ async function main() {
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='is_urgent') THEN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='is_urgent') THEN
ALTER TABLE scraped_services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE; ALTER TABLE scraped_services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE;
END IF; END IF;
-- AÑADIDO: Aseguramos que exista la columna ia_keywords en los gremios
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='ia_keywords') THEN IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='ia_keywords') THEN
ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]'; ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]';
END IF; END IF;
@@ -107,37 +125,49 @@ async function main() {
} }
// ========================================== // ==========================================
// 🏥 MULTIASISTENCIA // 🏥 MULTIASISTENCIA (CON REINTENTOS ANTI-CAÍDAS)
// ========================================== // ==========================================
async function runMultiasistencia(ownerId, user, pass, gremiosDB) { async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
const browser = await chromium.launch({ const browser = await chromium.launch({
headless: HEADLESS, headless: HEADLESS,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'] args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu'
]
}); });
const context = await browser.newContext(); const context = await browser.newContext();
const page = await context.newPage(); const page = await context.newPage();
try { try {
// INICIO DE SESIÓN CON REINTENTOS
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php'); await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php');
await page.fill('input[name="usuario"]', user); await page.fill('input[name="usuario"]', user);
await page.fill('input[type="password"]', pass); await page.fill('input[type="password"]', pass);
await page.click('input[type="submit"]'); await page.click('input[type="submit"]');
await page.waitForTimeout(4000); await page.waitForTimeout(4000);
// ENTRAR AL BUZÓN CON REINTENTOS
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1'); await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1');
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
console.log("🔄 [Multi] Forzando recarga segura..."); console.log("🔄 [Multi] Forzando recarga segura mediante script interno...");
try { try {
await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); }); await page.evaluate(() => {
if (typeof refrescar === 'function') refrescar();
});
await page.waitForLoadState('networkidle'); await page.waitForLoadState('networkidle');
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
} catch (e) {} } catch (e) {}
// --- BUCLE DE PAGINACIÓN ---
let todosExpedientes = new Set(); let todosExpedientes = new Set();
let paginaActual = 1; let paginaActual = 1;
while (true) { while (true) {
console.log(`📄 [Multi] Escaneando página ${paginaActual}...`); console.log(`📄 [Multi] Escaneando página ${paginaActual}...`);
const expedientesPagina = await page.evaluate(() => { const expedientesPagina = await page.evaluate(() => {
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]')); const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean); return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean);
@@ -145,17 +175,19 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
expedientesPagina.forEach(ref => todosExpedientes.add(ref)); expedientesPagina.forEach(ref => todosExpedientes.add(ref));
// 🛑 NUEVO: Buscamos el botón de siguiente
const hasNextPage = await page.evaluate(() => { const hasNextPage = await page.evaluate(() => {
const links = Array.from(document.querySelectorAll('a.lnkheader')); const links = Array.from(document.querySelectorAll('a.lnkheader'));
return links.some(a => a.innerText.trim() === 'Página siguiente'); return links.some(a => a.innerText.trim() === 'Página siguiente');
}); });
if (hasNextPage) { if (hasNextPage) {
// 🛑 NUEVO: Pulsamos usando el motor de Playwright, simulando click humano
await page.locator('a.lnkheader:has-text("Página siguiente")').first().click(); await page.locator('a.lnkheader:has-text("Página siguiente")').first().click();
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
paginaActual++; paginaActual++;
if(paginaActual > 15) { if(paginaActual > 15) {
console.log("⚠️ [Multi] Límite de páginas alcanzado."); console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad.");
break; break;
} }
} else { } else {
@@ -194,12 +226,16 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
const descHeader = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación")); const descHeader = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación"));
if (descHeader && descHeader.nextElementSibling) rawDesc = clean(descHeader.nextElementSibling.innerText); if (descHeader && descHeader.nextElementSibling) rawDesc = clean(descHeader.nextElementSibling.innerText);
// CORRECCIÓN: Borrado el recorte de fechas destructivo.
// Ahora le pasamos todo el bloque de texto completo a la IA para que no se pierdan palabras clave.
const cleanDesc = rawDesc; const cleanDesc = rawDesc;
const rawCPField = findByCab("Distrito Postal") || ""; const rawCPField = findByCab("Distrito Postal") || "";
const cpMatch = rawCPField.match(/\b\d{5}\b/); const cpMatch = rawCPField.match(/\b\d{5}\b/);
const cpOnly = cpMatch ? cpMatch[0] : ""; const cpOnly = cpMatch ? cpMatch[0] : "";
const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim(); const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim();
// 📞 EXTRAER TELÉFONO REAL (Evita coger el de la oficina)
let telefonoReal = ""; let telefonoReal = "";
const titulosDiv = Array.from(document.querySelectorAll('.subtitulo')); const titulosDiv = Array.from(document.querySelectorAll('.subtitulo'));
const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono')); const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono'));
@@ -207,6 +243,7 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet'); const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet');
if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, ''); if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, '');
} }
// Fallback por si acaso falla, usamos el que tenías antes
if (!telefonoReal || telefonoReal.length < 9) { if (!telefonoReal || telefonoReal.length < 9) {
telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || ""; telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "";
} }
@@ -220,7 +257,7 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
"Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"), "Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"),
"Descripción": cleanDesc, "Descripción": cleanDesc,
"Teléfono": telefonoReal, "Teléfono": telefonoReal,
"Estado": findByCab("Estado") || "", "Estado": findByCab("Estado") || "", // 🛑 AÑADIDO EL ESTADO AQUÍ
"Urgente": findByCab("Urgente") || "No" "Urgente": findByCab("Urgente") || "No"
}; };
}); });
@@ -236,12 +273,15 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData); await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData);
} }
} }
} catch (e) { console.error("❌ Error Multi:", e.message); } } catch (e) {
finally { await browser.close(); } console.error("❌ Error Multi:", e.message);
} finally {
await browser.close();
}
} }
// ========================================== // ==========================================
// 🧹 HOMESERVE (MODO CAMUFLAJE) // 🧹 HOMESERVE (ROBOT MEJORADO Y DETECTOR DE URGENCIAS)
// ========================================== // ==========================================
async function runHomeserve(ownerId, user, pass, gremiosDB) { async function runHomeserve(ownerId, user, pass, gremiosDB) {
const browser = await chromium.launch({ const browser = await chromium.launch({
@@ -250,64 +290,25 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
'--no-sandbox', '--no-sandbox',
'--disable-setuid-sandbox', '--disable-setuid-sandbox',
'--disable-dev-shm-usage', '--disable-dev-shm-usage',
'--disable-gpu', '--disable-gpu'
'--disable-blink-features=AutomationControlled'
] ]
}); });
const page = await browser.newPage();
const context = await browser.newContext({
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
viewport: { width: 1366, height: 768 },
hasTouch: false
});
const page = await context.newPage();
await page.addInitScript(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
});
try { try {
console.log("🌍 [HomeServe] Entrando a la web (Modo Sigilo Activado)..."); console.log("🌍 [HomeServe] Entrando...");
await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS'); await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS');
console.log(`🔎 [HomeServe] URL actual: ${page.url()}`);
if (await page.isVisible('input[name="CODIGO"]')) { if (await page.isVisible('input[name="CODIGO"]')) {
console.log("🔑 [HomeServe] Formulario detectado. Rellenando datos...");
await page.fill('input[name="CODIGO"]', user); await page.fill('input[name="CODIGO"]', user);
await page.fill('input[type="password"]', pass); await page.fill('input[type="password"]', pass);
const botonEntrar = await page.$('input[type="submit"], input[type="button"], button');
if (botonEntrar) {
console.log("🖱️ [HomeServe] Haciendo clic en el botón de Entrar...");
await botonEntrar.click();
} else {
console.log("⌨️ [HomeServe] No vi el botón, pulsando Enter...");
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
}
await page.waitForTimeout(5000); await page.waitForTimeout(5000);
console.log(`👀 [HomeServe] URL tras intentar login: ${page.url()}`);
if (page.url().includes('PROF_PASS')) {
console.log("⚠️ [HomeServe] El login falló. Leyendo el texto visible de la web...");
const textoPantalla = await page.evaluate(() => {
return document.body.innerText.replace(/\n+/g, '\n').trim();
});
console.log("\n🚨 ESTO ES LO QUE ESTÁ VIENDO EL ROBOT EN LA PANTALLA:");
console.log("--------------------------------------------------");
console.log(textoPantalla.substring(0, 800));
console.log("--------------------------------------------------\n");
}
} else {
console.log("⚠️ [HomeServe] NO se detectó el formulario de login.");
} }
console.log("📋 [HomeServe] Yendo a la lista de servicios...");
await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total'); await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
console.log(`📍 [HomeServe] URL de la lista cargada: ${page.url()}`);
// 🛑 NUEVO: Ahora extraemos la referencia Y LOS ICONOS de la misma pasada
const listaConIconos = await page.evaluate(() => { const listaConIconos = await page.evaluate(() => {
const results = []; const results = [];
const rows = Array.from(document.querySelectorAll('table[bgcolor="#FCF4D6"] tr')); const rows = Array.from(document.querySelectorAll('table[bgcolor="#FCF4D6"] tr'));
@@ -329,8 +330,7 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
return results; return results;
}); });
console.log(`📊 [HomeServe] Total de filas válidas extraídas de la tabla: ${listaConIconos.length}`); // Sacamos solo los números para la escoba (syncAndArchive)
const refs = [...new Set(listaConIconos.map(item => item.ref))]; const refs = [...new Set(listaConIconos.map(item => item.ref))];
if (refs.length > 0) { if (refs.length > 0) {
@@ -345,7 +345,7 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
const scrapData = await page.evaluate(() => { const scrapData = await page.evaluate(() => {
const d = {}; const d = {};
let isUrgent = "No"; let isUrgent = "No"; // <-- EMPEZAMOS ASUMIENDO QUE NO ES URGENTE
const rows = Array.from(document.querySelectorAll('tr')); const rows = Array.from(document.querySelectorAll('tr'));
rows.forEach(r => { rows.forEach(r => {
@@ -358,16 +358,19 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
const inputEl = cells[1].querySelector('textarea'); const inputEl = cells[1].querySelector('textarea');
const txt = inputEl ? inputEl.value : (cells[1].innerText || ""); const txt = inputEl ? inputEl.value : (cells[1].innerText || "");
// 🔥 DETECTOR DE URGENCIA ANTES DE LIMPIAR 🔥
const txtLower = txt.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); const txtLower = txt.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
if (txtLower.includes("atencion presencial urgencias") || txtLower.includes("atencion de la urgencia") || txtLower.includes("urgente")) { if (txtLower.includes("atencion presencial urgencias") || txtLower.includes("atencion de la urgencia") || txtLower.includes("urgente")) {
isUrgent = "Sí"; isUrgent = "Sí"; // Si pilla la urgencia, la guarda.
} }
const cleanDesc = txt.split('\n').filter(line => { const cleanDesc = txt.split('\n').filter(line => {
const l = line.toUpperCase(); const l = line.toUpperCase();
// Quitamos los filtros destructivos que borraban el "Cambio de estado"
return !["ESTADO ASIGNADO", "SMS NO ENVIADO", "CONTACTO CON PROF", "0000"].some(b => l.includes(b)); return !["ESTADO ASIGNADO", "SMS NO ENVIADO", "CONTACTO CON PROF", "0000"].some(b => l.includes(b));
}).join('\n').trim(); }).join('\n').trim();
d['Descripción'] = cleanDesc; // Aplicamos el descodificador a la avería
d['Descripción'] = cleanDesc; // Se limpiará luego abajo
} else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) { } else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) {
d[k] = v; d[k] = v;
} }
@@ -381,18 +384,24 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE"); d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE");
d['Nombre Cliente'] = d['CLIENTE'] || ""; d['Nombre Cliente'] = d['CLIENTE'] || "";
d['Dirección'] = d['DOMICILIO'] || ""; d['Dirección'] = d['DOMICILIO'] || "";
// INYECTAMOS LA URGENCIA AL ESTILO MULTIASISTENCIA
d['Urgente'] = isUrgent; d['Urgente'] = isUrgent;
return d; return d;
}); });
if (scrapData && scrapData['Nombre Cliente']) { if (scrapData && scrapData['Nombre Cliente']) {
// 🪄 Arreglamos la codificación alienígena de HomeServe EN TODOS LOS CAMPOS IMPORTANTES
scrapData['Nombre Cliente'] = arreglarCodificacion(scrapData['Nombre Cliente']); scrapData['Nombre Cliente'] = arreglarCodificacion(scrapData['Nombre Cliente']);
scrapData['Dirección'] = arreglarCodificacion(scrapData['Dirección']); scrapData['Dirección'] = arreglarCodificacion(scrapData['Dirección']);
scrapData['Población'] = arreglarCodificacion(scrapData['Población']); scrapData['Población'] = arreglarCodificacion(scrapData['Población']);
scrapData['Descripción'] = arreglarCodificacion(scrapData['Descripción']); scrapData['Descripción'] = arreglarCodificacion(scrapData['Descripción']);
// 🪄 Arreglamos el formato de "Apellidos, Nombre" (Solo en HomeServe)
scrapData['Nombre Cliente'] = arreglarNombre(scrapData['Nombre Cliente']); scrapData['Nombre Cliente'] = arreglarNombre(scrapData['Nombre Cliente']);
// 🛑 NUEVO: Le inyectamos los iconos que cazamos antes en la lista
const iconInfo = listaConIconos.find(item => item.ref === ref); const iconInfo = listaConIconos.find(item => item.ref === ref);
if (iconInfo) { if (iconInfo) {
scrapData['has_lock'] = iconInfo.hasLock; scrapData['has_lock'] = iconInfo.hasLock;
@@ -410,58 +419,74 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
finally { await browser.close(); } finally { await browser.close(); }
} }
// ==========================================
// 🛡️ FUNCIONES DE GUARDADO Y ARCHIVADO
// ==========================================
async function syncAndArchive(ownerId, provider, currentWebRefs) { async function syncAndArchive(ownerId, provider, currentWebRefs) {
const client = await pool.connect(); const client = await pool.connect();
try { try {
// 1. Buscamos TODOS los expedientes que están vivos (en el buzón o en el panel)
const { rows: dbServices } = await client.query( const { rows: dbServices } = await client.query(
`SELECT id, service_ref, assigned_to, raw_data FROM scraped_services `SELECT id, service_ref, assigned_to, raw_data FROM scraped_services
WHERE owner_id = $1 AND provider = $2 AND status IN ('pending', 'imported')`, WHERE owner_id = $1 AND provider = $2 AND status IN ('pending', 'imported')`,
[ownerId, provider] [ownerId, provider]
); );
// 2. Filtramos cuáles han desaparecido de la web oficial
const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref)); const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref));
const refsToArchive = missingServices.map(s => s.service_ref); const refsToArchive = missingServices.map(s => s.service_ref);
if (refsToArchive.length > 0) { if (refsToArchive.length > 0) {
// 3. Los archivamos (los quitamos del buzón)
await client.query( await client.query(
`UPDATE scraped_services `UPDATE scraped_services
SET status = 'archived' SET status = 'archived'
WHERE owner_id = $1 AND provider = $2 AND service_ref = ANY($3)`, WHERE owner_id = $1
AND provider = $2
AND service_ref = ANY($3)`,
[ownerId, provider, refsToArchive] [ownerId, provider, refsToArchive]
); );
// ========================================================
// 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Para la App del Técnico)
// ========================================================
// Buscamos el ID del estado "Anulado" de este propietario
const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id = $1 AND name ILIKE '%anulado%' LIMIT 1", [ownerId]); const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id = $1 AND name ILIKE '%anulado%' LIMIT 1", [ownerId]);
const idAnulado = statusQ.rowCount > 0 ? statusQ.rows[0].id : null; const idAnulado = statusQ.rowCount > 0 ? statusQ.rows[0].id : null;
if (idAnulado) { if (idAnulado) {
for (const svc of missingServices) { for (const svc of missingServices) {
// Si el expediente estaba asignado a un técnico...
if (svc.assigned_to) { if (svc.assigned_to) {
const raw = svc.raw_data || {}; const raw = svc.raw_data || {};
const currentStatusId = String(raw.status_operativo || ""); const currentStatusId = String(raw.status_operativo || "");
// ...y su estado actual no era ya "Anulado"
if (currentStatusId !== String(idAnulado)) { if (currentStatusId !== String(idAnulado)) {
// Comprobamos si el técnico ya lo había "Finalizado" (para no pisarle el trabajo hecho)
let isFinal = false; let isFinal = false;
if (currentStatusId) { if (currentStatusId) {
const checkStatusQ = await client.query("SELECT is_final FROM service_statuses WHERE id = $1", [currentStatusId]); const checkStatusQ = await client.query("SELECT is_final FROM service_statuses WHERE id = $1", [currentStatusId]);
isFinal = checkStatusQ.rowCount > 0 ? checkStatusQ.rows[0].is_final : false; isFinal = checkStatusQ.rowCount > 0 ? checkStatusQ.rows[0].is_final : false;
} }
// Si NO estaba finalizado, procedemos a ANULARLO automáticamente
if (!isFinal) { if (!isFinal) {
raw.status_operativo = idAnulado; raw.status_operativo = idAnulado;
await client.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(raw), svc.id]); await client.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(raw), svc.id]);
// Dejamos huella en la trazabilidad para que sepas por qué se anuló
await client.query( await client.query(
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)", "INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[svc.id, "Sistema Robot", "Cancelación Automática", "La compañía ha cancelado/retirado el expediente. Se pasa a estado Anulado."] [svc.id, "Sistema Robot", "Cancelación Automática", "La compañía ha cancelado/retirado el expediente. Se pasa a estado Anulado para avisar al técnico."]
); );
console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente.`); console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado de viajar en balde).`);
} }
} }
} }
} }
} }
// ========================================================
console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`); console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`);
} }
} catch (error) { } catch (error) {
@@ -474,6 +499,7 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) {
async function saveServiceToDB(ownerId, provider, ref, data) { async function saveServiceToDB(ownerId, provider, ref, data) {
console.log(`💾 Guardando/Actualizando ${provider.toUpperCase()} ${ref}...`); console.log(`💾 Guardando/Actualizando ${provider.toUpperCase()} ${ref}...`);
// Aquí está la solución al problema del tilde ("sí" vs "si") que te comenté antes
const isUrgent = (data['Urgente'] && (data['Urgente'].toLowerCase().trim() === 'sí' || data['Urgente'].toLowerCase().trim() === 'si')) ? true : false; const isUrgent = (data['Urgente'] && (data['Urgente'].toLowerCase().trim() === 'sí' || data['Urgente'].toLowerCase().trim() === 'si')) ? true : false;
await pool.query(` await pool.query(`
@@ -481,8 +507,10 @@ async function saveServiceToDB(ownerId, provider, ref, data) {
VALUES ($1, $2, $3, $4, 'pending', $5) VALUES ($1, $2, $3, $4, 'pending', $5)
ON CONFLICT (owner_id, provider, service_ref) ON CONFLICT (owner_id, provider, service_ref)
DO UPDATE SET DO UPDATE SET
-- 🛡️ EL ESCUDO: Fusiona todo, pero si ya había un gremio guardado, lo blinda para que el robot no lo pise
raw_data = (scraped_services.raw_data || EXCLUDED.raw_data) || raw_data = (scraped_services.raw_data || EXCLUDED.raw_data) ||
jsonb_build_object('guild_id', COALESCE(scraped_services.raw_data->'guild_id', EXCLUDED.raw_data->'guild_id')), jsonb_build_object('guild_id', COALESCE(scraped_services.raw_data->'guild_id', EXCLUDED.raw_data->'guild_id')),
is_urgent = EXCLUDED.is_urgent, is_urgent = EXCLUDED.is_urgent,
status = CASE status = CASE
WHEN scraped_services.status = 'archived' THEN 'archived' WHEN scraped_services.status = 'archived' THEN 'archived'