Actualizar worker-homeserve.js
This commit is contained in:
@@ -18,12 +18,9 @@ if (!CONFIG.DATABASE_URL) {
|
|||||||
process.exit(1);
|
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 ---
|
// --- UTILS ---
|
||||||
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('/');
|
||||||
@@ -32,30 +29,23 @@ function checkWeekend(dateStr) {
|
|||||||
const month = parseInt(parts[1], 10) - 1;
|
const month = parseInt(parts[1], 10) - 1;
|
||||||
const year = parseInt(parts[2], 10);
|
const year = parseInt(parts[2], 10);
|
||||||
const d = new Date(year, month, day);
|
const d = new Date(year, month, day);
|
||||||
const dayOfWeek = d.getDay();
|
if (d.getDay() === 0 || d.getDay() === 6) {
|
||||||
if (dayOfWeek === 0 || dayOfWeek === 6) {
|
|
||||||
throw new Error(`⛔ ERROR: La fecha ${dateStr} es fin de semana (Sáb/Dom). No permitido por HomeServe.`);
|
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 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;
|
|
||||||
const pass = Buffer.from(q.rows[0].password_hash, 'base64').toString('utf-8');
|
|
||||||
|
|
||||||
return { user, pass };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- PLAYWRIGHT HELPERS ---
|
|
||||||
async function withBrowser(fn) {
|
async function withBrowser(fn) {
|
||||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
|
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
|
||||||
const context = await browser.newContext();
|
const context = await browser.newContext();
|
||||||
@@ -92,11 +82,13 @@ async function loginAndProcess(page, creds, jobData) {
|
|||||||
console.log(`>>> 1. Login en HomeServe con usuario: ${creds.user}`);
|
console.log(`>>> 1. Login en HomeServe con usuario: ${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 para HomeServe.');
|
throw new Error('⛔ ERROR: El campo Observaciones es obligatorio.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auto-aceptar popups de HomeServe si saltan
|
||||||
|
page.on('dialog', async dialog => await dialog.accept());
|
||||||
|
|
||||||
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
|
await page.goto(CONFIG.LOGIN_URL, { waitUntil: 'domcontentloaded', timeout: CONFIG.NAV_TIMEOUT });
|
||||||
await page.waitForTimeout(1000);
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
@@ -107,60 +99,35 @@ async function loginAndProcess(page, creds, jobData) {
|
|||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
const loginFail = await findLocatorInFrames(page, 'input[type="password"]');
|
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}...`);
|
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(1500);
|
||||||
|
|
||||||
const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']);
|
const changeBtn = await clickFirstThatExists(page, ['input[name="repaso"]']);
|
||||||
if (!changeBtn) {
|
if (!changeBtn) throw new Error(`No veo el botón 'repaso' en el siniestro.`);
|
||||||
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...');
|
console.log('>>> 3. Accediendo al formulario. Rellenando datos...');
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForTimeout(1500);
|
||||||
await page.waitForTimeout(1000);
|
|
||||||
|
|
||||||
const HOMESERVE_MAP = {
|
const HOMESERVE_MAP = { 'CITADO': '307', 'ESPERA': '303', 'TERMINADO': '345', 'ANULADO': '352' };
|
||||||
'CITADO': '307',
|
let targetCode = String(jobData.new_status).toUpperCase();
|
||||||
'ESPERA': '303',
|
if (HOMESERVE_MAP[targetCode]) targetCode = HOMESERVE_MAP[targetCode];
|
||||||
'TERMINADO': '345',
|
|
||||||
'ANULADO': '352'
|
|
||||||
};
|
|
||||||
|
|
||||||
let targetCode = jobData.new_status.toUpperCase();
|
// SELECCIÓN NATIVA DE PLAYWRIGHT (Mucho más fiable)
|
||||||
if (HOMESERVE_MAP[targetCode]) {
|
const selectEstado = await findLocatorInFrames(page, 'select[name="ESTADO"]');
|
||||||
targetCode = HOMESERVE_MAP[targetCode];
|
if (!selectEstado) throw new Error('No encontré el desplegable de estados.');
|
||||||
}
|
await selectEstado.locator.first().selectOption({ value: targetCode }).catch(() => {
|
||||||
|
throw new Error(`El código de estado '${targetCode}' no existe en HomeServe.`);
|
||||||
// 👇 AQUÍ ESTÁ EL ARREGLO 1: FORZAR QUE LA WEB RECONOZCA EL DESPLEGABLE
|
});
|
||||||
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;
|
|
||||||
// Disparar eventos para que el servidor de HS registre el cambio
|
|
||||||
select.dispatchEvent(new Event('change', { bubbles: true }));
|
|
||||||
select.dispatchEvent(new Event('blur', { bubbles: true }));
|
|
||||||
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.`);
|
|
||||||
|
|
||||||
if (jobData.appointment_date) {
|
if (jobData.appointment_date) {
|
||||||
const dateFilled = await fillFirstThatExists(page, ['input[name="FECSIG"]'], jobData.appointment_date);
|
await fillFirstThatExists(page, ['input[name="FECSIG"]'], jobData.appointment_date);
|
||||||
if (!dateFilled) console.warn('⚠️ No encontré el recuadro para la fecha.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const obsFilled = await fillFirstThatExists(page, ['textarea[name="Observaciones"]'], jobData.observation);
|
await fillFirstThatExists(page, ['textarea[name="Observaciones"]'], jobData.observation);
|
||||||
if (!obsFilled) throw new Error('No encontré el recuadro de Observaciones en la web de HomeServe.');
|
|
||||||
|
|
||||||
if (jobData.inform_client) {
|
if (jobData.inform_client) {
|
||||||
const informCheck = await findLocatorInFrames(page, 'input[name="INFORMO"]');
|
const informCheck = await findLocatorInFrames(page, 'input[name="INFORMO"]');
|
||||||
@@ -169,48 +136,38 @@ async function loginAndProcess(page, creds, jobData) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 👇 AQUÍ ESTÁ EL ARREGLO 2: UN RESPIRO ANTES DEL CLIC
|
console.log('>>> 4. Ejecutando clic en Aceptar el Cambio...');
|
||||||
await page.waitForTimeout(1500);
|
|
||||||
|
|
||||||
console.log('>>> 4. Guardando cambios en HomeServe...');
|
|
||||||
|
|
||||||
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 en HomeServe.');
|
if (!saveBtnHit) throw new Error('No encuentro el botón para guardar los cambios.');
|
||||||
|
|
||||||
await saveBtnHit.locator.first().click();
|
// Hacemos el clic y esperamos a que la página reaccione
|
||||||
console.log(' -> Clic realizado, esperando confirmación...');
|
await Promise.all([
|
||||||
|
page.waitForNavigation({ timeout: 10000 }).catch(() => {}),
|
||||||
await page.waitForTimeout(4000);
|
saveBtnHit.locator.first().click()
|
||||||
|
]);
|
||||||
|
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// LEEMOS SOLO LOS ERRORES ROJOS (Ignoramos etiquetas <b>)
|
||||||
const resultText = await page.evaluate(() => {
|
const resultText = await page.evaluate(() => {
|
||||||
const el = document.querySelector('font[color="#FF0000"], .Estilo4, b');
|
const errEl = document.querySelector('font[color="#FF0000"], .Estilo4');
|
||||||
return el ? el.innerText : "";
|
return errEl ? errEl.innerText : "";
|
||||||
});
|
});
|
||||||
|
|
||||||
if (resultText && resultText.trim().length > 0) {
|
if (resultText && resultText.trim().length > 0) {
|
||||||
console.log(`>>> Web dice: ${resultText.trim()}`);
|
throw new Error(`HomeServe devolvió un error rojo: ${resultText.trim()}`);
|
||||||
const textUpper = resultText.toUpperCase();
|
|
||||||
if (!textUpper.includes('EXITO') && !textUpper.includes('ÉXITO') && !textUpper.includes('MODIFICADO')) {
|
|
||||||
throw new Error(`Error en HomeServe: ${resultText.trim()}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('>>> 5. Formulario enviado sin errores aparentes.');
|
||||||
return { success: true };
|
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 *;
|
||||||
`);
|
`);
|
||||||
|
|
||||||
@@ -223,19 +180,15 @@ async function pollQueue() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const creds = await getHomeServeCreds(job.owner_id);
|
const creds = await getHomeServeCreds(job.owner_id);
|
||||||
|
|
||||||
await withBrowser(async (page) => {
|
await withBrowser(async (page) => {
|
||||||
await loginAndProcess(page, creds, job);
|
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(`✅ TRABAJO #${job.id} COMPLETADO CON ÉXITO.\n`);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`❌ ERROR EN TRABAJO #${job.id}:`, err.message);
|
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]);
|
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);
|
setTimeout(pollQueue, 1000);
|
||||||
} else {
|
} else {
|
||||||
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
||||||
@@ -246,7 +199,6 @@ async function pollQueue() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- INICIO ---
|
|
||||||
console.log("🚀 Robot HomeServe (Multi-Empresa SaaS) Iniciado.");
|
console.log("🚀 Robot HomeServe (Multi-Empresa SaaS) Iniciado.");
|
||||||
console.log("📡 Conectado a PostgreSQL. Esperando peticiones en la cola...");
|
console.log("📡 Conectado a PostgreSQL. Esperando peticiones en la cola...");
|
||||||
pollQueue();
|
pollQueue();
|
||||||
Reference in New Issue
Block a user