diff --git a/robot.js b/robot.js index 521e14b..a18ae8e 100644 --- a/robot.js +++ b/robot.js @@ -16,49 +16,35 @@ function normalizarTexto(texto) { return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); } -// 🛠️ NUEVO: El "Gira-Nombres" EXCLUSIVO para HomeServe function arreglarNombre(nombreRaw) { if (!nombreRaw) return ""; let nombreLimpio = nombreRaw.trim(); - // Si detectamos que tiene una coma... if (nombreLimpio.includes(',')) { let partes = nombreLimpio.split(','); let apellidos = partes[0].trim(); let nombre = partes[1].trim(); - // Le damos la vuelta y quitamos espacios sobrantes nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' '); } return nombreLimpio; } -// 🛡️ DESCODIFICADOR UNIVERSAL PARA HOMESERVE (Arregla los +, Ó, Ñ, etc.) function arreglarCodificacion(texto) { if (!texto) return ""; - let limpio = texto.replace(/\+/g, ' '); // Primero cambiamos los + por espacios + let limpio = texto.replace(/\+/g, ' '); try { - // Truco clásico de Javascript para transformar ISO a UTF-8 limpio = decodeURIComponent(escape(limpio)); - } catch(e) { - // Si no se puede, lo dejamos con los espacios arreglados - } + } catch(e) {} return limpio.trim(); } -// NUEVO: La función ahora lee las keywords directamente del JSON de la base de datos function clasificarGremio(descripcion, gremiosActivosDB) { if (!descripcion || gremiosActivosDB.length === 0) return null; - const descNormalizada = normalizarTexto(descripcion); 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 : []; - - if (keywords.length === 0) continue; // Si no tiene reglas, pasamos al siguiente - - // Comprobamos si alguna palabra clave coincide con la descripción + if (keywords.length === 0) continue; const coincide = keywords.some(kw => descNormalizada.includes(normalizarTexto(kw))); - if (coincide) { console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`); return gremio.id; @@ -67,17 +53,15 @@ function clasificarGremio(descripcion, gremiosActivosDB) { return null; } -// Función auxiliar para reintentar la navegación si hay fallo de red async function gotoWithRetry(page, url, retries = 3) { for (let i = 0; i < retries; i++) { try { - // Usamos domcontentloaded para que no se quede colgado esperando imágenes o scripts pesados await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 }); - return; // Si funciona, salimos de la función + return; } catch (e) { - if (i === retries - 1) throw e; // Si es el último intento, lanza el error + if (i === retries - 1) throw e; console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`); - await page.waitForTimeout(3000); // Esperamos 3 segundos antes de volver a intentar + await page.waitForTimeout(3000); } } } @@ -87,7 +71,6 @@ async function main() { while (true) { const client = await pool.connect(); try { - // 1. CARGAMOS LOS GREMIOS ACTUALES (AHORA INCLUYE LAS PALABRAS CLAVE) const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds"); const gremiosDB = gremiosRes.rows; @@ -96,7 +79,6 @@ async function main() { 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; 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 ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]'; END IF; @@ -125,49 +107,37 @@ async function main() { } // ========================================== -// 🏥 MULTIASISTENCIA (CON REINTENTOS ANTI-CAÍDAS) +// 🏥 MULTIASISTENCIA // ========================================== async function runMultiasistencia(ownerId, user, pass, gremiosDB) { const browser = await chromium.launch({ 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 page = await context.newPage(); try { - // INICIO DE SESIÓN CON REINTENTOS await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php'); - await page.fill('input[name="usuario"]', user); await page.fill('input[type="password"]', pass); await page.click('input[type="submit"]'); await page.waitForTimeout(4000); - // ENTRAR AL BUZÓN CON REINTENTOS await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1'); await page.waitForTimeout(3000); - console.log("🔄 [Multi] Forzando recarga segura mediante script interno..."); + console.log("🔄 [Multi] Forzando recarga segura..."); try { - await page.evaluate(() => { - if (typeof refrescar === 'function') refrescar(); - }); + await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); }); await page.waitForLoadState('networkidle'); await page.waitForTimeout(3000); } catch (e) {} - // --- BUCLE DE PAGINACIÓN --- let todosExpedientes = new Set(); let paginaActual = 1; while (true) { console.log(`📄 [Multi] Escaneando página ${paginaActual}...`); - const expedientesPagina = await page.evaluate(() => { const links = Array.from(document.querySelectorAll('a[href*="reparacion="]')); return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean); @@ -175,19 +145,17 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { expedientesPagina.forEach(ref => todosExpedientes.add(ref)); - // 🛑 NUEVO: Buscamos el botón de siguiente const hasNextPage = await page.evaluate(() => { const links = Array.from(document.querySelectorAll('a.lnkheader')); return links.some(a => a.innerText.trim() === 'Página siguiente'); }); 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.waitForTimeout(3000); paginaActual++; if(paginaActual > 15) { - console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad."); + console.log("⚠️ [Multi] Límite de páginas alcanzado."); break; } } else { @@ -226,16 +194,12 @@ 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")); 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 rawCPField = findByCab("Distrito Postal") || ""; const cpMatch = rawCPField.match(/\b\d{5}\b/); const cpOnly = cpMatch ? cpMatch[0] : ""; const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim(); - // 📞 EXTRAER TELÉFONO REAL (Evita coger el de la oficina) let telefonoReal = ""; const titulosDiv = Array.from(document.querySelectorAll('.subtitulo')); const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono')); @@ -243,7 +207,6 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet'); 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) { telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || ""; } @@ -257,7 +220,7 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { "Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"), "Descripción": cleanDesc, "Teléfono": telefonoReal, - "Estado": findByCab("Estado") || "", // 🛑 AÑADIDO EL ESTADO AQUÍ + "Estado": findByCab("Estado") || "", "Urgente": findByCab("Urgente") || "No" }; }); @@ -273,15 +236,12 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData); } } - } catch (e) { - console.error("❌ Error Multi:", e.message); - } finally { - await browser.close(); - } + } catch (e) { console.error("❌ Error Multi:", e.message); } + finally { await browser.close(); } } // ========================================== -// 🧹 HOMESERVE (ROBOT MEJORADO + CAMUFLAJE ANTI-BOTS) +// 🧹 HOMESERVE (MODO CAMUFLAJE) // ========================================== async function runHomeserve(ownerId, user, pass, gremiosDB) { const browser = await chromium.launch({ @@ -291,11 +251,10 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu', - '--disable-blink-features=AutomationControlled' // 1. Oculta que es un bot automatizado + '--disable-blink-features=AutomationControlled' ] }); - // 2. Le ponemos el DNI de un Chrome normal en Windows 10 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 }, @@ -304,7 +263,6 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { const page = await context.newPage(); - // 3. Borramos la variable chivata de Playwright antes de que cargue la web await page.addInitScript(() => { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); }); @@ -448,17 +406,74 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { await saveServiceToDB(ownerId, 'homeserve', ref, scrapData); } } - } catch (e) { - console.error("❌ [HomeServe] Error:", e.message); - } finally { - await browser.close(); + } catch (e) { console.error("❌ [HomeServe] Error:", e.message); } + finally { await browser.close(); } +} + +// ========================================== +// 🛡️ FUNCIONES DE GUARDADO Y ARCHIVADO +// ========================================== +async function syncAndArchive(ownerId, provider, currentWebRefs) { + const client = await pool.connect(); + try { + const { rows: dbServices } = await client.query( + `SELECT id, service_ref, assigned_to, raw_data FROM scraped_services + WHERE owner_id = $1 AND provider = $2 AND status IN ('pending', 'imported')`, + [ownerId, provider] + ); + + const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref)); + const refsToArchive = missingServices.map(s => s.service_ref); + + if (refsToArchive.length > 0) { + await client.query( + `UPDATE scraped_services + SET status = 'archived' + WHERE owner_id = $1 AND provider = $2 AND service_ref = ANY($3)`, + [ownerId, provider, refsToArchive] + ); + + 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; + + if (idAnulado) { + for (const svc of missingServices) { + if (svc.assigned_to) { + const raw = svc.raw_data || {}; + const currentStatusId = String(raw.status_operativo || ""); + + if (currentStatusId !== String(idAnulado)) { + let isFinal = false; + if (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; + } + + if (!isFinal) { + 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( + "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."] + ); + console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente.`); + } + } + } + } + } + console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`); + } + } catch (error) { + console.error(`❌ Error archivando ${provider}:`, error.message); + } finally { + client.release(); } } async function saveServiceToDB(ownerId, provider, ref, data) { 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; await pool.query(` @@ -466,10 +481,8 @@ async function saveServiceToDB(ownerId, provider, ref, data) { VALUES ($1, $2, $3, $4, 'pending', $5) ON CONFLICT (owner_id, provider, service_ref) 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) || jsonb_build_object('guild_id', COALESCE(scraped_services.raw_data->'guild_id', EXCLUDED.raw_data->'guild_id')), - is_urgent = EXCLUDED.is_urgent, status = CASE WHEN scraped_services.status = 'archived' THEN 'archived'