diff --git a/robot.js b/robot.js index be77199..c9ff7f8 100644 --- a/robot.js +++ b/robot.js @@ -122,10 +122,9 @@ async function main() { console.log("\n💤 Durmiendo 15 minutos..."); await new Promise(r => setTimeout(r, 15 * 60 * 1000)); } -} - -// ========================================== -// 🏥 MULTIASISTENCIA (ROBOT REPARADO Y BLINDADO) + + // ========================================== +// 🏥 MULTIASISTENCIA (ASPIRADORA MASIVA C/ DOBLE RECARGA) // ========================================== async function runMultiasistencia(ownerId, user, pass, gremiosDB) { const browser = await chromium.launch({ @@ -151,56 +150,66 @@ 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(3000); + await page.waitForTimeout(4000); - // --- BUCLE DE PAGINACIÓN --- - let todosExpedientes = new Set(); - let paginaActual = 1; - - while (true) { - console.log(`📄 [Multi] Escaneando página ${paginaActual}...`); - - // Esperamos un poco a que cargue la tabla para evitar que lea en blanco - await page.waitForTimeout(1000); - - 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); - }); - - console.log(` 👉 Encontrados ${expedientesPagina.length} expedientes en la página ${paginaActual}.`); - expedientesPagina.forEach(ref => todosExpedientes.add(ref)); - - // Buscamos el botón de página siguiente con el selector nativo - const nextBtn = page.locator('a.lnkheader:has-text("Página siguiente")').first(); - const hasNextPage = await nextBtn.count() > 0; - - if (hasNextPage) { - console.log(` ➡️ Botón 'Siguiente' detectado. Pulsando...`); - await nextBtn.click(); - await page.waitForTimeout(3000); - paginaActual++; - if(paginaActual > 15) { - console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad."); - break; + // 🛑 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(); }); } - } else { - console.log("🛑 [Multi] Fin de la lista. No hay botón de página siguiente."); - break; + await page.waitForTimeout(4000); // Esperamos a que la tabla se redibuje + } catch (e) { + console.log(` ⚠️ Fallo menor en recarga ${i}: ${e.message}`); } } - const expedientes = Array.from(todosExpedientes); - console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientes.length}`); + 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); + } + }); + + console.log(`🔍 [Multi] Extrayendo referencias...`); + let todosExpedientes = []; - if (expedientes.length > 5 || paginaActual === 1) { - console.log(`🧹 [Multi] Llamando a la escoba con ${expedientes.length} refs...`); - await syncAndArchive(ownerId, 'multiasistencia', expedientes); + // 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)]; + + console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientesUnicos.length}`); + + // SEGURO DE VIDA + if (expedientesUnicos.length > 5) { + console.log(`🧹 [Multi] Llamando a la escoba con ${expedientesUnicos.length} refs...`); + await syncAndArchive(ownerId, 'multiasistencia', expedientesUnicos); } else { - console.log("⚠️ [Multi] Pocos expedientes detectados. ABORTANDO ARCHIVADO DE SEGURIDAD."); + console.log("⚠️ [Multi] Menos de 5 expedientes detectados. ABORTANDO ARCHIVADO DE SEGURIDAD."); } - for (const ref of expedientes) { + // BUCLE DE GUARDADO + for (const ref of expedientesUnicos) { await gotoWithRetry(page, `https://web.multiasistencia.com/w3multi/repasos1.php?reparacion=${ref}`); await page.waitForTimeout(1500); let scrapData = null;