Actualizar worker-homeserve.js
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
// worker-homeserve.js (Versión SaaS - Limpia y Eficaz)
|
// worker-homeserve.js (Versión SaaS - Ultra Estable con Reintentos y Logs)
|
||||||
import { chromium } from 'playwright';
|
import { chromium } from 'playwright';
|
||||||
import pg from 'pg';
|
import pg from 'pg';
|
||||||
|
|
||||||
@@ -72,30 +72,50 @@ async function fillFirstThatExists(page, selectors, value) {
|
|||||||
|
|
||||||
// --- INYECCIÓN EN HOMESERVE ---
|
// --- INYECCIÓN EN HOMESERVE ---
|
||||||
async function loginAndProcess(page, creds, jobData) {
|
async function loginAndProcess(page, creds, jobData) {
|
||||||
console.log(`>>> 1. Login en HomeServe con usuario: ${creds.user}`);
|
console.log(`>>> 1. Navegando a HomeServe (${creds.user})...`);
|
||||||
|
|
||||||
if (jobData.appointment_date) checkWeekend(jobData.appointment_date);
|
if (jobData.appointment_date) checkWeekend(jobData.appointment_date);
|
||||||
if (!jobData.observation || jobData.observation.trim().length === 0) {
|
if (!jobData.observation || jobData.observation.trim().length === 0) {
|
||||||
throw new Error('⛔ ERROR: El campo Observaciones es obligatorio.');
|
throw new Error('⛔ ERROR: El campo Observaciones es obligatorio.');
|
||||||
}
|
}
|
||||||
|
|
||||||
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
|
// Aceptar diálogos molestos
|
||||||
await page.waitForTimeout(1000);
|
page.on('dialog', async dialog => {
|
||||||
|
console.log(` [DIALOG] Mensaje detectado: ${dialog.message()}`);
|
||||||
|
await dialog.accept();
|
||||||
|
});
|
||||||
|
|
||||||
await fillFirstThatExists(page, ['input[name="w3user"]', 'input[type="text"]'], creds.user);
|
// Login a prueba de fallos (Espera a que cargue todo)
|
||||||
await fillFirstThatExists(page, ['input[name="w3clau"]', 'input[type="password"]'], creds.pass);
|
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'load', timeout: CONFIG.NAV_TIMEOUT });
|
||||||
|
console.log(" [DEBUG] Buscando campos de login...");
|
||||||
|
|
||||||
|
let loginExitoso = false;
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
const u = await findLocatorInFrames(page, 'input[name="w3user"]');
|
||||||
|
const p = await findLocatorInFrames(page, 'input[name="w3clau"]');
|
||||||
|
|
||||||
|
if (u && p) {
|
||||||
|
await u.locator.first().fill(creds.user);
|
||||||
|
await p.locator.first().fill(creds.pass);
|
||||||
|
loginExitoso = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await page.waitForTimeout(1000); // Reintento si los frames tardan en cargar
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loginExitoso) throw new Error("No se cargaron los campos de login de HomeServe.");
|
||||||
|
|
||||||
await page.keyboard.press('Enter');
|
await page.keyboard.press('Enter');
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(4000); // Esperar que procese el login
|
||||||
|
|
||||||
const loginFail = await findLocatorInFrames(page, 'input[type="password"]');
|
const isStillAtLogin = await findLocatorInFrames(page, 'input[type="password"]');
|
||||||
if (loginFail) throw new Error(`Login fallido en HomeServe.`);
|
if (isStillAtLogin) throw new Error(`Login fallido en HomeServe.`);
|
||||||
|
|
||||||
console.log(`>>> 2. Login OK. Navegando al expediente ${jobData.service_number}...`);
|
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`;
|
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.goto(serviceUrl, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
|
||||||
await page.waitForTimeout(1500);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']);
|
const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']);
|
||||||
if (!changeBtn) throw new Error(`No veo el botón 'repaso'.`);
|
if (!changeBtn) throw new Error(`No veo el botón 'repaso'.`);
|
||||||
@@ -103,7 +123,7 @@ async function loginAndProcess(page, creds, jobData) {
|
|||||||
console.log('>>> 3. Accediendo al formulario. Rellenando datos...');
|
console.log('>>> 3. Accediendo al formulario. Rellenando datos...');
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Traducción y selección de estado
|
// Traducción y selección de estado (CON REFRESCO FORZADO PARA LA WEB)
|
||||||
let targetCode = jobData.new_status;
|
let targetCode = jobData.new_status;
|
||||||
const statusOk = await page.evaluate((code) => {
|
const statusOk = await page.evaluate((code) => {
|
||||||
const select = document.querySelector('select[name="ESTADO"]');
|
const select = document.querySelector('select[name="ESTADO"]');
|
||||||
@@ -111,6 +131,9 @@ async function loginAndProcess(page, creds, jobData) {
|
|||||||
for (const opt of select.options) {
|
for (const opt of select.options) {
|
||||||
if (opt.value == code || opt.text.toUpperCase().includes(code.toUpperCase())) {
|
if (opt.value == code || opt.text.toUpperCase().includes(code.toUpperCase())) {
|
||||||
select.value = opt.value;
|
select.value = opt.value;
|
||||||
|
// Disparamos los eventos para engañar a HomeServe y que crea que fue un humano
|
||||||
|
select.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
|
select.dispatchEvent(new Event('blur', { bubbles: true }));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,27 +152,33 @@ async function loginAndProcess(page, creds, jobData) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Retraso clave para que los scripts de HomeServe asienten los datos
|
||||||
|
await page.waitForTimeout(1000);
|
||||||
console.log('>>> 4. Guardando cambios en HomeServe...');
|
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"]');
|
const saveBtnHit = await findLocatorInFrames(page, 'input[name="BTNCAMBIAESTADO"]');
|
||||||
if (!saveBtnHit) throw new Error('No encuentro el botón para guardar los cambios.');
|
if (!saveBtnHit) throw new Error('No encuentro el botón para guardar los cambios.');
|
||||||
|
|
||||||
// Clic y esperar que la web procese
|
|
||||||
await saveBtnHit.locator.first().click();
|
await saveBtnHit.locator.first().click();
|
||||||
console.log(' -> Clic realizado, esperando confirmación...');
|
console.log(' -> Clic realizado, esperando confirmación del servidor (4s)...');
|
||||||
await page.waitForTimeout(4000);
|
await page.waitForTimeout(4000);
|
||||||
|
|
||||||
// Verificación del texto de confirmación
|
// Verificación del texto en pantalla (Buscando en todos los frames)
|
||||||
const resultText = await page.evaluate(() => {
|
const resultText = await page.evaluate(() => {
|
||||||
const el = document.querySelector('font[color="#FF0000"], .Estilo4, b');
|
// HomeServe suele meter el resultado en rojo o negrita
|
||||||
return el ? el.innerText : "";
|
const frameConTexto = Array.from(window.frames).map(f => {
|
||||||
|
try { return f.document.querySelector('font[color="#FF0000"], .Estilo4, b, .mensaje'); } catch(e){ return null;}
|
||||||
|
}).find(el => el != null);
|
||||||
|
|
||||||
|
const elPrincipal = document.querySelector('font[color="#FF0000"], .Estilo4, b, .mensaje');
|
||||||
|
const nodoFinal = elPrincipal || frameConTexto;
|
||||||
|
return nodoFinal ? nodoFinal.innerText : "";
|
||||||
});
|
});
|
||||||
|
|
||||||
if (resultText && resultText.trim().length > 0) {
|
if (resultText && resultText.trim().length > 0) {
|
||||||
console.log(`>>> Web dice: ${resultText.trim()}`);
|
console.log(`>>> Web dice: ${resultText.trim()}`);
|
||||||
const textUpper = resultText.toUpperCase();
|
const textUpper = resultText.toUpperCase();
|
||||||
if (!textUpper.includes('EXITO') && !textUpper.includes('ÉXITO') && !textUpper.includes('MODIFICADO')) {
|
if (!textUpper.includes('EXITO') && !textUpper.includes('ÉXITO') && !textUpper.includes('MODIFICADO') && !textUpper.includes('ACTUALIZADO')) {
|
||||||
throw new Error(`Error en HomeServe: ${resultText.trim()}`);
|
throw new Error(`Error en HomeServe: ${resultText.trim()}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user