Actualizar worker-homeserve.js
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
// worker-homeserve.js (Versión Definitiva PostgreSQL - MULTI-EMPRESA SAAS)
|
// worker-homeserve.js (Versión SaaS Ultra-Eficaz con Logs Reforzados)
|
||||||
import { chromium } from 'playwright';
|
import { chromium } from 'playwright';
|
||||||
import pg from 'pg';
|
import pg from 'pg';
|
||||||
|
|
||||||
@@ -10,241 +10,193 @@ const CONFIG = {
|
|||||||
LOGIN_URL: 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS',
|
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',
|
BASE_CGI: 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe',
|
||||||
NAV_TIMEOUT: 60000,
|
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) {
|
|
||||||
console.error("❌ ERROR FATAL: Falta la variable de entorno DATABASE_URL");
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Conexión a la Base de Datos
|
|
||||||
const pool = new Pool({ connectionString: CONFIG.DATABASE_URL, ssl: false });
|
const pool = new Pool({ connectionString: CONFIG.DATABASE_URL, ssl: false });
|
||||||
|
|
||||||
// --- UTILS ---
|
// --- HELPERS ---
|
||||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
||||||
|
|
||||||
function checkWeekend(dateStr) {
|
function checkWeekend(dateStr) {
|
||||||
if (!dateStr) return;
|
if (!dateStr) return;
|
||||||
const parts = dateStr.split('/');
|
const parts = dateStr.split('/');
|
||||||
if (parts.length !== 3) return;
|
if (parts.length !== 3) return;
|
||||||
const day = parseInt(parts[0], 10);
|
const d = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
|
||||||
const month = parseInt(parts[1], 10) - 1;
|
if (d.getDay() === 0 || d.getDay() === 6) {
|
||||||
const year = parseInt(parts[2], 10);
|
throw new Error(`⛔ ERROR: La fecha ${dateStr} es fin de semana.`);
|
||||||
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.`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- DESENCRIPTAR CREDENCIALES (MULTI-EMPRESA) ---
|
|
||||||
async function getHomeServeCreds(ownerId) {
|
async function getHomeServeCreds(ownerId) {
|
||||||
const q = await pool.query(
|
const q = await pool.query(
|
||||||
"SELECT username, password_hash FROM provider_credentials WHERE provider = 'homeserve' AND status = 'active' AND owner_id = $1 LIMIT 1",
|
"SELECT username, password_hash FROM provider_credentials WHERE provider = 'homeserve' AND status = 'active' AND owner_id = $1 LIMIT 1",
|
||||||
[ownerId]
|
[ownerId]
|
||||||
);
|
);
|
||||||
|
if (q.rowCount === 0) throw new Error(`Sin credenciales para empresa ID: ${ownerId}`);
|
||||||
if (q.rowCount === 0) {
|
return {
|
||||||
throw new Error(`No hay credenciales activas de HomeServe para la empresa/dueño ID: ${ownerId}.`);
|
user: q.rows[0].username,
|
||||||
}
|
pass: Buffer.from(q.rows[0].password_hash, 'base64').toString('utf-8')
|
||||||
|
};
|
||||||
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 };
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 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(() => {}); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function findLocatorInFrames(page, selector) {
|
async function findLocatorInFrames(page, selector) {
|
||||||
for (const fr of page.frames()) {
|
// Primero buscamos en la página principal
|
||||||
const loc = fr.locator(selector);
|
const mainLoc = page.locator(selector);
|
||||||
try { if (await loc.count()) return { frame: fr, locator: loc }; } catch (_) {}
|
if (await mainLoc.count() > 0) return mainLoc.first();
|
||||||
}
|
|
||||||
return null;
|
// 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function clickFirstThatExists(page, selectors) {
|
// --- PROCESO PRINCIPAL ---
|
||||||
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) {
|
async function loginAndProcess(page, creds, jobData) {
|
||||||
console.log(`>>> 1. Login en HomeServe con usuario: ${creds.user}`);
|
console.log(` [1] Intentando Login (${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) {
|
// Manejo de diálogos (Alertas de la web que bloquean el proceso)
|
||||||
throw new Error('⛔ ERROR: El campo Observaciones es obligatorio para HomeServe.');
|
page.on('dialog', async dialog => {
|
||||||
}
|
console.log(` [DIALOG] Mensaje detectado: ${dialog.message()}`);
|
||||||
|
await dialog.accept();
|
||||||
|
});
|
||||||
|
|
||||||
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
|
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'networkidle', timeout: CONFIG.NAV_TIMEOUT });
|
||||||
await page.waitForTimeout(1000);
|
|
||||||
|
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.");
|
||||||
|
|
||||||
await fillFirstThatExists(page, ['input[name="w3user"]', 'input[type="text"]'], creds.user);
|
await userInp.fill(creds.user);
|
||||||
await fillFirstThatExists(page, ['input[name="w3clau"]', 'input[type="password"]'], creds.pass);
|
await passInp.fill(creds.pass);
|
||||||
|
await page.keyboard.press('Enter');
|
||||||
await page.keyboard.press('Enter');
|
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
const loginFail = await findLocatorInFrames(page, 'input[type="password"]');
|
// Verificar si seguimos en login
|
||||||
if (loginFail) throw new Error(`Login fallido en HomeServe para el usuario ${creds.user}. Revise las credenciales.`);
|
if (await page.locator('input[type="password"]').count() > 0) {
|
||||||
|
throw new Error("Credenciales rechazadas por HomeServe.");
|
||||||
|
}
|
||||||
|
|
||||||
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`;
|
const repasBtn = await findLocatorInFrames(page, 'input[name="repaso"]');
|
||||||
await page.goto(serviceUrl, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
|
if (!repasBtn) throw new Error("No se encuentra el siniestro o no permite 'repaso'.");
|
||||||
await page.waitForTimeout(1500);
|
await repasBtn.click();
|
||||||
|
|
||||||
const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']);
|
console.log(' [3] Rellenando formulario de cambio de estado...');
|
||||||
if (!changeBtn) {
|
await page.waitForTimeout(2000);
|
||||||
throw new Error(`No veo el botón 'repaso'. ¿El siniestro ${jobData.service_number} existe y está abierto?`);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('>>> 3. Accediendo al formulario. Rellenando datos...');
|
// Selección de Estado
|
||||||
await page.waitForLoadState('domcontentloaded');
|
const targetCode = jobData.new_status;
|
||||||
await page.waitForTimeout(1000);
|
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);
|
||||||
|
|
||||||
// 🔴 MAGIA: DICCIONARIO TRADUCTOR DE ESTADOS
|
if (!statusOk) throw new Error(`Estado '${targetCode}' no disponible en la web.`);
|
||||||
const HOMESERVE_MAP = {
|
|
||||||
'CITADO': '307',
|
|
||||||
'ESPERA': '303',
|
|
||||||
'TERMINADO': '345',
|
|
||||||
'ANULADO': '352'
|
|
||||||
};
|
|
||||||
|
|
||||||
let targetCode = jobData.new_status.toUpperCase();
|
// Fecha Siguiente Acción
|
||||||
if (HOMESERVE_MAP[targetCode]) {
|
if (jobData.appointment_date) {
|
||||||
targetCode = HOMESERVE_MAP[targetCode];
|
const dateInp = await findLocatorInFrames(page, 'input[name="FECSIG"]');
|
||||||
}
|
if (dateInp) await dateInp.fill(jobData.appointment_date);
|
||||||
|
}
|
||||||
|
|
||||||
const statusOk = await page.evaluate((code) => {
|
// Observaciones
|
||||||
const select = document.querySelector('select[name="ESTADO"]');
|
const obsInp = await findLocatorInFrames(page, 'textarea[name="Observaciones"]');
|
||||||
if (!select) return false;
|
if (!obsInp) throw new Error("Campo observaciones no encontrado.");
|
||||||
for (const opt of select.options) {
|
await obsInp.fill(jobData.observation);
|
||||||
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}' (Buscando código interno: ${targetCode}) en el desplegable de HomeServe.`);
|
// Informar Cliente
|
||||||
|
if (jobData.inform_client) {
|
||||||
|
const check = await findLocatorInFrames(page, 'input[name="INFORMO"]');
|
||||||
|
if (check && !(await check.isChecked())) await check.check();
|
||||||
|
}
|
||||||
|
|
||||||
if (jobData.appointment_date) {
|
console.log(' [4] Ejecutando CLIC DE GUARDADO FINAL...');
|
||||||
const dateFilled = await fillFirstThatExists(page, ['input[name="FECSIG"]'], jobData.appointment_date);
|
const btnGuardar = await findLocatorInFrames(page, 'input[name="BTNCAMBIAESTADO"]');
|
||||||
if (!dateFilled) console.warn('⚠️ No encontré el recuadro para la fecha.');
|
if (!btnGuardar) throw new Error("Botón GUARDAR no encontrado.");
|
||||||
}
|
|
||||||
|
|
||||||
const obsFilled = await fillFirstThatExists(page, ['textarea[name="Observaciones"]'], jobData.observation);
|
// Clic con reintento y espera de red
|
||||||
if (!obsFilled) throw new Error('No encontré el recuadro de Observaciones en la web de HomeServe.');
|
await Promise.all([
|
||||||
|
page.waitForLoadState('networkidle').catch(() => {}),
|
||||||
|
btnGuardar.click()
|
||||||
|
]);
|
||||||
|
|
||||||
if (jobData.inform_client) {
|
// Verificación de éxito
|
||||||
const informCheck = await findLocatorInFrames(page, 'input[name="INFORMO"]');
|
await page.waitForTimeout(3000);
|
||||||
if (informCheck && !(await informCheck.locator.first().isChecked())) {
|
const feedback = await page.evaluate(() => {
|
||||||
await informCheck.locator.first().check();
|
// 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('>>> 4. Guardando cambios en HomeServe...');
|
console.log(` [RESULTADO] Web dice: "${feedback.trim() || 'Sin mensaje visible'}"`);
|
||||||
|
|
||||||
const saveBtnLocator = page.locator('input[name="BTNCAMBIAESTADO"]');
|
const esExito = feedback.toUpperCase().includes('EXITO') ||
|
||||||
|
feedback.toUpperCase().includes('ÉXITO') ||
|
||||||
if (await saveBtnLocator.count() === 0) {
|
feedback.toUpperCase().includes('MODIFICADO') ||
|
||||||
throw new Error('No encuentro el botón para guardar los cambios en HomeServe.');
|
feedback.toUpperCase().includes('ACTUALIZADO');
|
||||||
}
|
|
||||||
|
|
||||||
// Esperamos a que la página navegue DESPUÉS de hacer clic (El Clic Seguro)
|
if (!esExito && feedback.length > 0) {
|
||||||
await Promise.all([
|
throw new Error(`HomeServe denegó el cambio: ${feedback}`);
|
||||||
page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT }),
|
}
|
||||||
saveBtnLocator.first().click()
|
|
||||||
]);
|
|
||||||
|
|
||||||
// 🔴 LECTURA INTELIGENTE DEL RESULTADO (Evita los falsos errores rojos)
|
return { success: true };
|
||||||
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() {
|
async function pollQueue() {
|
||||||
try {
|
try {
|
||||||
const res = await pool.query(`
|
const res = await pool.query(`
|
||||||
UPDATE robot_queue
|
UPDATE robot_queue SET status = 'RUNNING', updated_at = NOW()
|
||||||
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)
|
||||||
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 *;
|
RETURNING *;
|
||||||
`);
|
`);
|
||||||
|
|
||||||
if (res.rowCount > 0) {
|
if (res.rowCount > 0) {
|
||||||
const job = res.rows[0];
|
const job = res.rows[0];
|
||||||
console.log(`\n========================================`);
|
console.log(`\n🚀 TRABAJO #${job.id} | Exp: ${job.service_number} | Accion: ${job.new_status}`);
|
||||||
console.log(`🤖 TRABAJO #${job.id} | Empresa ID: ${job.owner_id}`);
|
|
||||||
console.log(`📋 Siniestro: ${job.service_number} -> Cambiar a: ${job.new_status}`);
|
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||||
console.log(`========================================`);
|
const page = await browser.newPage();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const creds = await getHomeServeCreds(job.owner_id);
|
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]);
|
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`);
|
console.log(`✅ COMPLETADO #${job.id}`);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`❌ ERROR EN TRABAJO #${job.id}:`, err.message);
|
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]);
|
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 {
|
} else {
|
||||||
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error crítico en el bucle del robot:", e.message);
|
console.error("Error en bucle:", e.message);
|
||||||
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- INICIO ---
|
console.log("📡 Robot HomeServe SaaS Online...");
|
||||||
console.log("🚀 Robot HomeServe (Multi-Empresa SaaS) Iniciado.");
|
|
||||||
console.log("📡 Conectado a PostgreSQL. Esperando peticiones en la cola...");
|
|
||||||
pollQueue();
|
pollQueue();
|
||||||
Reference in New Issue
Block a user