diff --git a/robot.js b/robot.js index d9a9656..55b756f 100644 --- a/robot.js +++ b/robot.js @@ -8,7 +8,7 @@ const pool = new pg.Pool({ connectionString: DATABASE_URL, ssl: false }); const HEADLESS = true; // ========================================== -// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (AHORA DINÁMICO) +// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (DINÁMICO) // ========================================== function normalizarTexto(texto) { @@ -16,16 +16,14 @@ function normalizarTexto(texto) { return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); } -// 🛠️ NUEVO: El "Gira-Nombres" EXCLUSIVO para HomeServe +// 🛠️ 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; @@ -34,31 +32,23 @@ function arreglarNombre(nombreRaw) { // 🛡️ 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 + if (keywords.length === 0) continue; - // Comprobamos si alguna palabra clave coincide con la descripción 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 +57,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 +75,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 +83,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; @@ -122,20 +108,15 @@ async function main() { console.log("\n💤 Durmiendo 15 minutos..."); await new Promise(r => setTimeout(r, 15 * 60 * 1000)); } -} +} // ========================================== -// 🏥 MULTIASISTENCIA (ASPIRADORA MASIVA C/ DOBLE RECARGA) +// 🏥 MULTIASISTENCIA (PAGINACIÓN ANTIBALAS Y DOBLE RECARGA) // ========================================== 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(); @@ -151,58 +132,69 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { console.log("📥 [Multi] Entrando al buzón..."); await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1'); - await page.waitForTimeout(4000); + await page.waitForTimeout(3000); - // 🛑 DOBLE RECARGA FORZADA PARA DESPERTAR AL SERVIDOR + // 🔄 DOBLE RECARGA FORZADA PARA DESPERTAR AL SERVIDOR console.log("🔄 [Multi] Forzando doble recarga del buzón..."); for (let i = 1; i <= 2; i++) { try { - // Buscamos la imagen del botón de recargar y le hacemos click - const btnRecargar = page.locator('img[name="recarga"], img#recargar, img[src*="btn_recargar"]').first(); - if (await btnRecargar.count() > 0) { - console.log(` 👉 Pulsando botón físico de recargar ${i}/2...`); - await btnRecargar.click(); - } else { - console.log(` 👉 Forzando función javascript refrescar() ${i}/2...`); - await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); }); - } - await page.waitForTimeout(4000); // Esperamos a que la tabla se redibuje + console.log(` 👉 Forzando recarga ${i}/2...`); + await page.evaluate(() => { + if (typeof refrescar === 'function') refrescar(); + else if (document.getElementById('recargar')) document.getElementById('recargar').click(); + }); + await page.waitForTimeout(3500); } catch (e) { console.log(` ⚠️ Fallo menor en recarga ${i}: ${e.message}`); } } - console.log(`📄 [Multi] Haciendo scroll infinito para cargar todos los expedientes...`); - // Hacemos scroll hasta abajo varias veces - await page.evaluate(async () => { - const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); - for (let i = 0; i < 5; i++) { - window.scrollTo(0, document.body.scrollHeight); - await delay(1000); + // --- BUCLE DE PAGINACIÓN INFALIBLE --- + let todosExpedientes = new Set(); + let paginaActual = 1; + + console.log(`📄 [Multi] Iniciando lectura por páginas...`); + while (true) { + console.log(`\n📄 [Multi] Escaneando página ${paginaActual}...`); + await page.waitForTimeout(1500); + + // 1. Extraemos los enlaces de esta página + 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); + }); + + const unicosPagina = [...new Set(expedientesPagina)]; + console.log(` 👉 Encontrados ${unicosPagina.length} expedientes únicos en la pág. ${paginaActual}.`); + unicosPagina.forEach(ref => todosExpedientes.add(ref)); + + // 2. BUSCAMOS LA URL DEL BOTÓN "SIGUIENTE" + const nextPageUrl = await page.evaluate(() => { + const links = Array.from(document.querySelectorAll('a.lnkheader')); + const nextBtn = links.find(a => a.innerText.toLowerCase().includes('siguiente')); + return nextBtn ? nextBtn.href : null; + }); + + if (nextPageUrl) { + console.log(` ➡️ Botón 'Siguiente' detectado. Navegando a la url...`); + await gotoWithRetry(page, nextPageUrl); + await page.waitForTimeout(3000); + paginaActual++; + if(paginaActual > 20) { + console.log("⚠️ [Multi] Límite de 20 páginas alcanzado por seguridad."); + break; + } + } else { + console.log("🛑 [Multi] Fin de la lista. No hay enlace a página siguiente."); + break; } - }); - - console.log(`🔍 [Multi] Extrayendo referencias...`); - let todosExpedientes = []; - - // Buscamos en el documento principal y en todos los frames por si acaso - for (const frame of [page.mainFrame(), ...page.frames()]) { - try { - const refsInFrame = await frame.evaluate(() => { - const links = Array.from(document.querySelectorAll('a[href*="reparacion="]')); - return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean); - }); - todosExpedientes = todosExpedientes.concat(refsInFrame); - } catch(e) {} } - - // Limpiamos los duplicados usando un Set - const expedientesUnicos = [...new Set(todosExpedientes)]; + const expedientesUnicos = Array.from(todosExpedientes); console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientesUnicos.length}`); - // SEGURO DE VIDA - if (expedientesUnicos.length > 5) { + // SEGURO DE VIDA PARA MULTIASISTENCIA + if (expedientesUnicos.length > 5 || paginaActual === 1) { console.log(`🧹 [Multi] Llamando a la escoba con ${expedientesUnicos.length} refs...`); await syncAndArchive(ownerId, 'multiasistencia', expedientesUnicos); } else { @@ -282,17 +274,12 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { } // ========================================== -// 🧹 HOMESERVE (ROBOT MEJORADO Y DETECTOR DE URGENCIAS) +// 🧹 HOMESERVE (MEJORADO CON DECODIFICADOR, ICONOS Y URGENCIA) // ========================================== async function runHomeserve(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 page = await browser.newPage(); try { @@ -309,19 +296,16 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total'); await page.waitForTimeout(3000); - // 🛑 NUEVO: Ahora extraemos la referencia Y LOS ICONOS de la misma pasada + // 🛑 EXTRAEMOS REFS E ICONOS const listaConIconos = await page.evaluate(() => { const results = []; const rows = Array.from(document.querySelectorAll('table[bgcolor="#FCF4D6"] tr')); - rows.forEach(tr => { const firstTd = tr.querySelector('td'); if (!firstTd) return; - const textMatch = firstTd.innerText.trim().match(/^15\d{6}$/); const aMatch = firstTd.querySelector('a') ? firstTd.querySelector('a').innerText.trim().match(/^15\d{6}$/) : null; const ref = textMatch ? textMatch[0] : (aMatch ? aMatch[0] : null); - if (ref) { const hasLock = firstTd.querySelector('img[src*="candado.gif"]') !== null; const hasEyes = firstTd.querySelector('img[src*="ojos.gif"]') !== null; @@ -331,7 +315,6 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { return results; }); - // Sacamos solo los números para la escoba (syncAndArchive) const refs = [...new Set(listaConIconos.map(item => item.ref))]; if (refs.length > 0) { @@ -346,7 +329,7 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { const scrapData = await page.evaluate(() => { const d = {}; - let isUrgent = "No"; // <-- EMPEZAMOS ASUMIENDO QUE NO ES URGENTE + let isUrgent = "No"; const rows = Array.from(document.querySelectorAll('tr')); rows.forEach(r => { @@ -359,19 +342,17 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { const inputEl = cells[1].querySelector('textarea'); const txt = inputEl ? inputEl.value : (cells[1].innerText || ""); - // 🔥 DETECTOR DE URGENCIA ANTES DE LIMPIAR 🔥 + // 🔥 DETECTOR DE URGENCIA 🔥 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")) { - isUrgent = "Sí"; // Si pilla la urgencia, la guarda. + isUrgent = "Sí"; } const cleanDesc = txt.split('\n').filter(line => { 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)); }).join('\n').trim(); - // Aplicamos el descodificador a la avería - d['Descripción'] = cleanDesc; // Se limpiará luego abajo + d['Descripción'] = cleanDesc; } else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) { d[k] = v; } @@ -385,24 +366,19 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE"); d['Nombre Cliente'] = d['CLIENTE'] || ""; d['Dirección'] = d['DOMICILIO'] || ""; - - // INYECTAMOS LA URGENCIA AL ESTILO MULTIASISTENCIA d['Urgente'] = isUrgent; return d; }); 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']); + // 🪄 Arreglamos codificación y nombres de HomeServe + scrapData['Nombre Cliente'] = arreglarNombre(arreglarCodificacion(scrapData['Nombre Cliente'])); scrapData['Dirección'] = arreglarCodificacion(scrapData['Dirección']); scrapData['Población'] = arreglarCodificacion(scrapData['Población']); scrapData['Descripción'] = arreglarCodificacion(scrapData['Descripción']); - // 🪄 Arreglamos el formato de "Apellidos, Nombre" (Solo en HomeServe) - scrapData['Nombre Cliente'] = arreglarNombre(scrapData['Nombre Cliente']); - - // 🛑 NUEVO: Le inyectamos los iconos que cazamos antes en la lista + // 🛑 INYECTAMOS ICONOS CAZADOS const iconInfo = listaConIconos.find(item => item.ref === ref); if (iconInfo) { scrapData['has_lock'] = iconInfo.hasLock; @@ -423,14 +399,12 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { async function syncAndArchive(ownerId, provider, currentWebRefs) { const client = await pool.connect(); try { - // 1. Buscamos TODOS los expedientes que están vivos (en el buzón o en el panel) 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] ); - // 2. Filtramos cuáles han desaparecido de la web oficial const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref)); const refsToArchive = missingServices.map(s => s.service_ref); @@ -438,9 +412,8 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) { if (refsToArchive.length > 0) { console.log(`🚨 ATENCIÓN: Se van a ARCHIVAR ${refsToArchive.length} expedientes porque NO están en la web:`); - console.log(`💀 LISTA DE CONDENADOS:`, refsToArchive.join(', ')); + console.log(`💀 LISTA:`, refsToArchive.join(', ')); - // 3. Los archivamos (los quitamos del buzón) await client.query( `UPDATE scraped_services SET status = 'archived' @@ -451,48 +424,38 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) { ); // ======================================================== - // 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Para la App del Técnico) + // 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Apagado para Multiasistencia) // ======================================================== - // 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 idAnulado = statusQ.rowCount > 0 ? statusQ.rows[0].id : null; - // 🛑 PARCHE: Desactivamos el escudo anti-viajes para Multiasistencia hasta que mapeemos bien sus 200 estados raros. if (idAnulado && provider !== 'multiasistencia') { for (const svc of missingServices) { - // Si el expediente estaba asignado a un técnico... if (svc.assigned_to) { const raw = svc.raw_data || {}; const currentStatusId = String(raw.status_operativo || ""); - // ...y su estado actual no era ya "Anulado" if (currentStatusId !== String(idAnulado)) { - - // Comprobamos si el técnico ya lo había "Finalizado" (para no pisarle el trabajo hecho) 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; } - // Si NO estaba finalizado, procedemos a ANULARLO automáticamente if (!isFinal) { raw.status_operativo = idAnulado; - 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( "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 para avisar al técnico."] + [svc.id, "Sistema Robot", "Cancelación Automática", "La compañía ha retirado el expediente. Se pasa a Anulado."] ); - console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado de viajar en balde).`); + console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado).`); } } } } } - // ======================================================== console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`); } @@ -506,7 +469,6 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) { 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(` @@ -514,7 +476,6 @@ 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')),