diff --git a/worker-homeserve.js b/worker-homeserve.js index f8538aa..956fd45 100644 --- a/worker-homeserve.js +++ b/worker-homeserve.js @@ -53,34 +53,47 @@ async function findLocatorInFrames(page, selector) { return null; } -// --- PROCESO PRINCIPAL --- +// --- PROCESO PRINCIPAL REFORZADO --- async function loginAndProcess(page, creds, jobData) { - console.log(` [1] Intentando Login (${creds.user})...`); + console.log(` [1] Navegando a HomeServe (${creds.user})...`); if (jobData.appointment_date) checkWeekend(jobData.appointment_date); - // Manejo de diálogos (Alertas de la web que bloquean el proceso) page.on('dialog', async dialog => { console.log(` [DIALOG] Mensaje detectado: ${dialog.message()}`); await dialog.accept(); }); + // 1. Ir a la URL y esperar a que la red esté quieta await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'networkidle', timeout: CONFIG.NAV_TIMEOUT }); - const userInp = await findLocatorInFrames(page, 'input[name="w3user"]'); - const passInp = await findLocatorInFrames(page, 'input[name="w3clau"]'); - - if (!userInp || !passInp) throw new Error("No se cargó el formulario de login."); + // 2. ESPERA EXTRA: A veces la web tarda en renderizar los inputs + console.log(" [DEBUG] Esperando a que aparezcan los campos de usuario..."); + await page.waitForTimeout(2000); + + // 3. Login directo (Sin buscar en frames primero para el login, suele ser más eficaz en la principal) + try { + await page.locator('input[name="w3user"]').first().fill(creds.user, { timeout: 5000 }); + await page.locator('input[name="w3clau"]').first().fill(creds.pass, { timeout: 5000 }); + } catch (e) { + console.log(" [!] No los vi en la principal, buscando en frames..."); + const u = await findLocatorInFrames(page, 'input[name="w3user"]'); + const p = await findLocatorInFrames(page, 'input[name="w3clau"]'); + if (!u || !p) throw new Error("No se cargó el formulario de login ni en principal ni en frames."); + await u.fill(creds.user); + await p.fill(creds.pass); + } - await userInp.fill(creds.user); - await passInp.fill(creds.pass); await page.keyboard.press('Enter'); + console.log(" [DEBUG] Enter pulsado, esperando navegación..."); - await page.waitForTimeout(3000); + // Esperamos a que la página cambie tras el login + await page.waitForTimeout(4000); - // Verificar si seguimos en login - if (await page.locator('input[type="password"]').count() > 0) { - throw new Error("Credenciales rechazadas por HomeServe."); + // Verificar si seguimos en login (si el campo password sigue ahí, es que falló) + const isStillAtLogin = await page.locator('input[type="password"]').count(); + if (isStillAtLogin > 0) { + throw new Error("Credenciales rechazadas o la web no avanzó tras el login."); } console.log(` [2] Login OK. Buscando expediente: ${jobData.service_number}...`);