From f9282b457b6f93264f522ba023437befe17f9985 Mon Sep 17 00:00:00 2001 From: marsalva Date: Tue, 10 Mar 2026 22:03:56 +0000 Subject: [PATCH] Actualizar worker-homeserve.js --- worker-homeserve.js | 125 +++++++++++++++++--------------------------- 1 file changed, 48 insertions(+), 77 deletions(-) diff --git a/worker-homeserve.js b/worker-homeserve.js index aa7cf7b..caa8c17 100644 --- a/worker-homeserve.js +++ b/worker-homeserve.js @@ -1,4 +1,4 @@ -// worker-homeserve.js (Versión Definitiva PostgreSQL - MULTI-EMPRESA SAAS) +// worker-homeserve.js (Tu código exacto + Chivato de Popups) import { chromium } from 'playwright'; import pg from 'pg'; @@ -10,7 +10,7 @@ const CONFIG = { LOGIN_URL: 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', BASE_CGI: 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe', NAV_TIMEOUT: 60000, - POLL_INTERVAL_MS: 5000 // Cada 5 segundos mira si hay trabajo en la pizarra + POLL_INTERVAL_MS: 5000 }; if (!CONFIG.DATABASE_URL) { @@ -18,10 +18,8 @@ if (!CONFIG.DATABASE_URL) { process.exit(1); } -// Conexión a la Base de Datos const pool = new Pool({ connectionString: CONFIG.DATABASE_URL, ssl: false }); -// --- UTILS --- const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function checkWeekend(dateStr) { @@ -32,31 +30,23 @@ function checkWeekend(dateStr) { const month = parseInt(parts[1], 10) - 1; const year = parseInt(parts[2], 10); const d = new Date(year, month, day); - const dayOfWeek = d.getDay(); - if (dayOfWeek === 0 || dayOfWeek === 6) { - throw new Error(`⛔ ERROR: La fecha ${dateStr} es fin de semana (Sáb/Dom). No permitido por HomeServe.`); + if (d.getDay() === 0 || d.getDay() === 6) { + throw new Error(`⛔ ERROR: La fecha ${dateStr} es fin de semana.`); } } -// --- DESENCRIPTAR CREDENCIALES (MULTI-EMPRESA) --- async function getHomeServeCreds(ownerId) { const q = await pool.query( "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(`No hay credenciales activas de HomeServe para la empresa/dueño ID: ${ownerId}.`); - } - - const user = q.rows[0].username; - // Convierte el Base64 a texto normal - const pass = Buffer.from(q.rows[0].password_hash, 'base64').toString('utf-8'); - - return { user, pass }; + 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') + }; } -// --- PLAYWRIGHT HELPERS --- async function withBrowser(fn) { const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const context = await browser.newContext(); @@ -93,11 +83,18 @@ async function loginAndProcess(page, creds, jobData) { 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 para HomeServe.'); + throw new Error('⛔ ERROR: Observaciones es obligatorio.'); } + // 🚨 EL CHIVATO: Guardamos el mensaje del popup si HomeServe se queja + let mensajeAlerta = null; + page.on('dialog', async dialog => { + mensajeAlerta = dialog.message(); + console.log(` [CHIVATO] HomeServe lanzó un popup: "${mensajeAlerta}"`); + await dialog.accept(); + }); + await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT }); await page.waitForTimeout(1000); @@ -108,51 +105,43 @@ async function loginAndProcess(page, creds, jobData) { await page.waitForTimeout(3000); const loginFail = await findLocatorInFrames(page, 'input[type="password"]'); - if (loginFail) throw new Error(`Login fallido en HomeServe para el usuario ${creds.user}. Revise las credenciales.`); + if (loginFail) throw new Error(`Login fallido en HomeServe.`); console.log(`>>> 2. Login OK. Navegando al expediente ${jobData.service_number}...`); - 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 changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']); - if (!changeBtn) { - throw new Error(`No veo el botón 'repaso'. ¿El siniestro ${jobData.service_number} existe y está abierto?`); - } + if (!changeBtn) throw new Error(`No veo el botón 'repaso'.`); console.log('>>> 3. Accediendo al formulario. Rellenando datos...'); await page.waitForLoadState('domcontentloaded'); await page.waitForTimeout(1000); - // 🔴 MAGIA: DICCIONARIO TRADUCTOR DE ESTADOS - const HOMESERVE_MAP = { - 'CITADO': '307', - 'ESPERA': '303', - 'TERMINADO': '345', - 'ANULADO': '352' - }; - + const HOMESERVE_MAP = { 'CITADO': '307', 'ESPERA': '303', 'TERMINADO': '345', 'ANULADO': '352' }; let targetCode = jobData.new_status.toUpperCase(); - if (HOMESERVE_MAP[targetCode]) { - targetCode = HOMESERVE_MAP[targetCode]; - } + if (HOMESERVE_MAP[targetCode]) targetCode = HOMESERVE_MAP[targetCode]; - // 👇 CORRECCIÓN CLAVE 1: Usar selectOption nativo para que el estado cambie de verdad - const selectBox = await findLocatorInFrames(page, 'select[name="ESTADO"]'); - if (selectBox) { - await selectBox.locator.first().selectOption({ value: targetCode }); - } else { - throw new Error(`No encontré el desplegable de estados en HomeServe.`); - } + 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(`No encontré el estado '${jobData.new_status}'.`); if (jobData.appointment_date) { - const dateFilled = await fillFirstThatExists(page, ['input[name="FECSIG"]'], jobData.appointment_date); - if (!dateFilled) console.warn('⚠️ No encontré el recuadro para la fecha.'); + await fillFirstThatExists(page, ['input[name="FECSIG"]'], jobData.appointment_date); } - const obsFilled = await fillFirstThatExists(page, ['textarea[name="Observaciones"]'], jobData.observation); - if (!obsFilled) throw new Error('No encontré el recuadro de Observaciones en la web de HomeServe.'); + await fillFirstThatExists(page, ['textarea[name="Observaciones"]'], jobData.observation); if (jobData.inform_client) { const informCheck = await findLocatorInFrames(page, 'input[name="INFORMO"]'); @@ -161,51 +150,38 @@ async function loginAndProcess(page, creds, jobData) { } } - // 👇 CORRECCIÓN CLAVE 2: Una pausa de 1 segundo antes de guardar - await page.waitForTimeout(1000); - console.log('>>> 4. Guardando cambios en HomeServe...'); - const saveBtnLocator = page.locator('input[name="BTNCAMBIAESTADO"]'); - - if (await saveBtnLocator.count() === 0) { - throw new Error('No encuentro el botón para guardar los cambios en HomeServe.'); - } + if (await saveBtnLocator.count() === 0) throw new Error('No encuentro el botón guardar.'); - // Esperamos a que la página navegue DESPUÉS de hacer clic (El Clic Seguro) + // Reducimos el tiempo de espera máximo de 60s a 15s para que no se quede colgado eternamente await Promise.all([ - page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT }), + page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => console.log(' -> Terminado el tiempo de espera de red.')), saveBtnLocator.first().click() ]); - // 👇 CORRECCIÓN CLAVE 3: Ignorar la etiqueta que daba el falso error + // 🚨 SI HUBO ALERTA, LANZAMOS EL ERROR REAL + if (mensajeAlerta) { + throw new Error(`HomeServe bloqueó el guardado con este mensaje: "${mensajeAlerta}"`); + } + const alertText = await page.locator('font[color="#FF0000"], .Estilo4').first().textContent().catch(() => null); if (alertText && alertText.trim().length > 0) { const textUpper = alertText.toUpperCase(); if (!textUpper.includes('EXITO') && !textUpper.includes('ÉXITO')) { throw new Error(`HomeServe devolvió un error: ${alertText.trim()}`); - } else { - console.log(`>>> Confirmación positiva de HomeServe: ${alertText.trim()}`); } } - await page.waitForTimeout(2000); return { success: true }; } -// --- EL CEREBRO: LECTURA DE LA COLA EN POSTGRESQL --- +// --- BUCLE DE COLA --- async function pollQueue() { try { const res = await pool.query(` - UPDATE robot_queue - SET status = 'RUNNING', updated_at = NOW() - WHERE id = ( - SELECT id FROM robot_queue - WHERE status = 'PENDING' AND provider = 'homeserve' - ORDER BY created_at ASC - FOR UPDATE SKIP LOCKED - LIMIT 1 - ) + UPDATE robot_queue SET status = 'RUNNING', updated_at = NOW() + WHERE id = (SELECT id FROM robot_queue WHERE status = 'PENDING' AND provider = 'homeserve' ORDER BY created_at ASC FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING *; `); @@ -218,19 +194,15 @@ async function pollQueue() { try { const creds = await getHomeServeCreds(job.owner_id); - 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(`✅ TRABAJO #${job.id} COMPLETADO CON ÉXITO.\n`); - } catch (err) { console.error(`❌ ERROR EN TRABAJO #${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]); } - setTimeout(pollQueue, 1000); } else { setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS); @@ -241,7 +213,6 @@ async function pollQueue() { } } -// --- INICIO --- console.log("🚀 Robot HomeServe (Multi-Empresa SaaS) Iniciado."); console.log("📡 Conectado a PostgreSQL. Esperando peticiones en la cola..."); pollQueue(); \ No newline at end of file