diff --git a/worker-homeserve.js b/worker-homeserve.js index 956fd45..b3629fc 100644 --- a/worker-homeserve.js +++ b/worker-homeserve.js @@ -1,4 +1,4 @@ -// worker-homeserve.js (Versión SaaS Ultra-Eficaz con Logs Reforzados) +// worker-homeserve.js (Versión SaaS - Limpia y Eficaz) import { chromium } from 'playwright'; import pg from 'pg'; @@ -15,7 +15,7 @@ const CONFIG = { const pool = new Pool({ connectionString: CONFIG.DATABASE_URL, ssl: false }); -// --- HELPERS --- +// --- UTILS --- function checkWeekend(dateStr) { if (!dateStr) return; const parts = dateStr.split('/'); @@ -31,147 +31,130 @@ async function getHomeServeCreds(ownerId) { "SELECT username, password_hash FROM provider_credentials WHERE provider = 'homeserve' AND status = 'active' AND owner_id = $1 LIMIT 1", [ownerId] ); - if (q.rowCount === 0) throw new Error(`Sin credenciales para empresa ID: ${ownerId}`); + if (q.rowCount === 0) throw new Error(`Sin credenciales para ID: ${ownerId}`); return { user: q.rows[0].username, pass: Buffer.from(q.rows[0].password_hash, 'base64').toString('utf-8') }; } -async function findLocatorInFrames(page, selector) { - // Primero buscamos en la página principal - const mainLoc = page.locator(selector); - if (await mainLoc.count() > 0) return mainLoc.first(); - - // Si no está, buscamos dentro de cada frame (HomeServe usa muchos frames) - for (const frame of page.frames()) { - const frameLoc = frame.locator(selector); - try { - if (await frameLoc.count() > 0) return frameLoc.first(); - } catch (e) {} - } - return null; +// --- PLAYWRIGHT HELPERS --- +async function withBrowser(fn) { + const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); + const context = await browser.newContext(); + const page = await context.newPage(); + try { return await fn(page); } finally { await browser.close().catch(() => {}); } } -// --- PROCESO PRINCIPAL REFORZADO --- +async function findLocatorInFrames(page, selector) { + for (const fr of page.frames()) { + const loc = fr.locator(selector); + try { if (await loc.count()) return { frame: fr, locator: loc }; } catch (_) {} + } + return null; +} + +async function clickFirstThatExists(page, selectors) { + for (const sel of selectors) { + const hit = await findLocatorInFrames(page, sel); + if (hit) { await hit.locator.first().click(); return sel; } + } + return null; +} + +async function fillFirstThatExists(page, selectors, value) { + for (const sel of selectors) { + const hit = await findLocatorInFrames(page, sel); + if (hit) { await hit.locator.first().fill(String(value)); return sel; } + } + return null; +} + +// --- INYECCIÓN EN HOMESERVE --- async function loginAndProcess(page, creds, jobData) { - console.log(` [1] Navegando a HomeServe (${creds.user})...`); - - if (jobData.appointment_date) checkWeekend(jobData.appointment_date); - - page.on('dialog', async dialog => { - console.log(` [DIALOG] Mensaje detectado: ${dialog.message()}`); - await dialog.accept(); - }); + console.log(`>>> 1. Login en HomeServe con usuario: ${creds.user}`); + + if (jobData.appointment_date) checkWeekend(jobData.appointment_date); + if (!jobData.observation || jobData.observation.trim().length === 0) { + throw new Error('⛔ ERROR: El campo Observaciones es obligatorio.'); + } - // 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 }); - - // 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); + await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT }); + await page.waitForTimeout(1000); - // 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 fillFirstThatExists(page, ['input[name="w3user"]', 'input[type="text"]'], creds.user); + await fillFirstThatExists(page, ['input[name="w3clau"]', 'input[type="password"]'], creds.pass); + + await page.keyboard.press('Enter'); + await page.waitForTimeout(3000); - await page.keyboard.press('Enter'); - console.log(" [DEBUG] Enter pulsado, esperando navegación..."); - - // Esperamos a que la página cambie tras el login - await page.waitForTimeout(4000); + const loginFail = await findLocatorInFrames(page, 'input[type="password"]'); + if (loginFail) throw new Error(`Login fallido en 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. Navegando al expediente ${jobData.service_number}...`); - console.log(` [2] Login OK. Buscando expediente: ${jobData.service_number}...`); - const serviceUrl = `${CONFIG.BASE_CGI}?w3exec=ver_servicioencurso&Servicio=${jobData.service_number}&Pag=1`; - await page.goto(serviceUrl, { waitUntil: 'domcontentloaded' }); + const serviceUrl = `${CONFIG.BASE_CGI}?w3exec=ver_servicioencurso&Servicio=${jobData.service_number}&Pag=1`; + await page.goto(serviceUrl, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT }); + await page.waitForTimeout(1500); - const repasBtn = await findLocatorInFrames(page, 'input[name="repaso"]'); - if (!repasBtn) throw new Error("No se encuentra el siniestro o no permite 'repaso'."); - await repasBtn.click(); + const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']); + if (!changeBtn) throw new Error(`No veo el botón 'repaso'.`); - console.log(' [3] Rellenando formulario de cambio de estado...'); - await page.waitForTimeout(2000); + console.log('>>> 3. Accediendo al formulario. Rellenando datos...'); + await page.waitForTimeout(2000); - // Selección de Estado - const targetCode = jobData.new_status; - const statusOk = await page.evaluate((code) => { - const sel = document.querySelector('select[name="ESTADO"]'); - if (!sel) return false; - // Buscamos por valor (código 307, 348...) o por texto parcial - for (let opt of sel.options) { - if (opt.value == code || opt.text.includes(code)) { - sel.value = opt.value; - sel.dispatchEvent(new Event('change', { bubbles: true })); - return true; - } - } - return false; - }, targetCode); + // Traducción y selección de estado + let targetCode = jobData.new_status; + const statusOk = await page.evaluate((code) => { + const select = document.querySelector('select[name="ESTADO"]'); + if (!select) return false; + for (const opt of select.options) { + if (opt.value == code || opt.text.toUpperCase().includes(code.toUpperCase())) { + select.value = opt.value; + return true; + } + } + return false; + }, targetCode); - if (!statusOk) throw new Error(`Estado '${targetCode}' no disponible en la web.`); + if (!statusOk) throw new Error(`Estado '${jobData.new_status}' no encontrado.`); - // Fecha Siguiente Acción - if (jobData.appointment_date) { - const dateInp = await findLocatorInFrames(page, 'input[name="FECSIG"]'); - if (dateInp) await dateInp.fill(jobData.appointment_date); - } + if (jobData.appointment_date) await fillFirstThatExists(page, ['input[name="FECSIG"]'], jobData.appointment_date); + await fillFirstThatExists(page, ['textarea[name="Observaciones"]'], jobData.observation); - // Observaciones - const obsInp = await findLocatorInFrames(page, 'textarea[name="Observaciones"]'); - if (!obsInp) throw new Error("Campo observaciones no encontrado."); - await obsInp.fill(jobData.observation); + if (jobData.inform_client) { + const informCheck = await findLocatorInFrames(page, 'input[name="INFORMO"]'); + if (informCheck && !(await informCheck.locator.first().isChecked())) { + await informCheck.locator.first().check(); + } + } - // Informar Cliente - if (jobData.inform_client) { - const check = await findLocatorInFrames(page, 'input[name="INFORMO"]'); - if (check && !(await check.isChecked())) await check.check(); - } + console.log('>>> 4. Guardando cambios en HomeServe...'); + + // CORRECCIÓN PARA EL GUARDADO: Buscamos el botón de guardar también en los frames + const saveBtnHit = await findLocatorInFrames(page, 'input[name="BTNCAMBIAESTADO"]'); + if (!saveBtnHit) throw new Error('No encuentro el botón para guardar los cambios.'); - console.log(' [4] Ejecutando CLIC DE GUARDADO FINAL...'); - const btnGuardar = await findLocatorInFrames(page, 'input[name="BTNCAMBIAESTADO"]'); - if (!btnGuardar) throw new Error("Botón GUARDAR no encontrado."); + // Clic y esperar que la web procese + await saveBtnHit.locator.first().click(); + console.log(' -> Clic realizado, esperando confirmación...'); + await page.waitForTimeout(4000); - // Clic con reintento y espera de red - await Promise.all([ - page.waitForLoadState('networkidle').catch(() => {}), - btnGuardar.click() - ]); + // Verificación del texto de confirmación + const resultText = await page.evaluate(() => { + const el = document.querySelector('font[color="#FF0000"], .Estilo4, b'); + return el ? el.innerText : ""; + }); - // Verificación de éxito - await page.waitForTimeout(3000); - const feedback = await page.evaluate(() => { - // Buscamos textos rojos o negritas que indiquen el resultado - const el = document.querySelector('font[color="#FF0000"], .Estilo4, b, .mensaje'); - return el ? el.innerText : ""; - }); - - console.log(` [RESULTADO] Web dice: "${feedback.trim() || 'Sin mensaje visible'}"`); - - const esExito = feedback.toUpperCase().includes('EXITO') || - feedback.toUpperCase().includes('ÉXITO') || - feedback.toUpperCase().includes('MODIFICADO') || - feedback.toUpperCase().includes('ACTUALIZADO'); - - if (!esExito && feedback.length > 0) { - throw new Error(`HomeServe denegó el cambio: ${feedback}`); - } - - return { success: true }; + if (resultText && resultText.trim().length > 0) { + console.log(`>>> Web dice: ${resultText.trim()}`); + const textUpper = resultText.toUpperCase(); + if (!textUpper.includes('EXITO') && !textUpper.includes('ÉXITO') && !textUpper.includes('MODIFICADO')) { + throw new Error(`Error en HomeServe: ${resultText.trim()}`); + } + } + + return { success: true }; } // --- BUCLE DE COLA --- @@ -185,31 +168,28 @@ async function pollQueue() { if (res.rowCount > 0) { const job = res.rows[0]; - console.log(`\n🚀 TRABAJO #${job.id} | Exp: ${job.service_number} | Accion: ${job.new_status}`); - - const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); - const page = await browser.newPage(); + console.log(`\n🤖 TRABAJO #${job.id} | Empresa ID: ${job.owner_id} | Siniestro: ${job.service_number}`); try { const creds = await getHomeServeCreds(job.owner_id); - await loginAndProcess(page, creds, job); + await withBrowser(async (page) => { + await loginAndProcess(page, creds, job); + }); await pool.query("UPDATE robot_queue SET status = 'DONE', updated_at = NOW() WHERE id = $1", [job.id]); - console.log(`✅ COMPLETADO #${job.id}`); + console.log(`✅ COMPLETADO #${job.id}\n`); } catch (err) { console.error(`❌ ERROR #${job.id}:`, err.message); await pool.query("UPDATE robot_queue SET status = 'FAILED', error_msg = $1, updated_at = NOW() WHERE id = $2", [err.message, job.id]); - } finally { - await browser.close(); - setTimeout(pollQueue, 1000); } + setTimeout(pollQueue, 1000); } else { setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS); } } catch (e) { - console.error("Error en bucle:", e.message); + console.error("Error crítico:", e.message); setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS); } } -console.log("📡 Robot HomeServe SaaS Online..."); +console.log("🚀 Robot HomeServe SaaS Online."); pollQueue(); \ No newline at end of file