215 lines
8.5 KiB
JavaScript
215 lines
8.5 KiB
JavaScript
// worker-homeserve.js (Versión SaaS Ultra-Eficaz con Logs Reforzados)
|
|
import { chromium } from 'playwright';
|
|
import pg from 'pg';
|
|
|
|
const { Pool } = pg;
|
|
|
|
// --- CONFIGURACIÓN ---
|
|
const CONFIG = {
|
|
DATABASE_URL: process.env.DATABASE_URL,
|
|
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
|
|
};
|
|
|
|
const pool = new Pool({ connectionString: CONFIG.DATABASE_URL, ssl: false });
|
|
|
|
// --- HELPERS ---
|
|
function checkWeekend(dateStr) {
|
|
if (!dateStr) return;
|
|
const parts = dateStr.split('/');
|
|
if (parts.length !== 3) return;
|
|
const d = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
|
|
if (d.getDay() === 0 || d.getDay() === 6) {
|
|
throw new Error(`⛔ ERROR: La fecha ${dateStr} es fin de semana.`);
|
|
}
|
|
}
|
|
|
|
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(`Sin credenciales para empresa 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;
|
|
}
|
|
|
|
// --- PROCESO PRINCIPAL REFORZADO ---
|
|
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();
|
|
});
|
|
|
|
// 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);
|
|
|
|
// 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 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);
|
|
|
|
// 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. 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 repasBtn = await findLocatorInFrames(page, 'input[name="repaso"]');
|
|
if (!repasBtn) throw new Error("No se encuentra el siniestro o no permite 'repaso'.");
|
|
await repasBtn.click();
|
|
|
|
console.log(' [3] Rellenando formulario de cambio de estado...');
|
|
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);
|
|
|
|
if (!statusOk) throw new Error(`Estado '${targetCode}' no disponible en la web.`);
|
|
|
|
// Fecha Siguiente Acción
|
|
if (jobData.appointment_date) {
|
|
const dateInp = await findLocatorInFrames(page, 'input[name="FECSIG"]');
|
|
if (dateInp) await dateInp.fill(jobData.appointment_date);
|
|
}
|
|
|
|
// Observaciones
|
|
const obsInp = await findLocatorInFrames(page, 'textarea[name="Observaciones"]');
|
|
if (!obsInp) throw new Error("Campo observaciones no encontrado.");
|
|
await obsInp.fill(jobData.observation);
|
|
|
|
// 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] Ejecutando CLIC DE GUARDADO FINAL...');
|
|
const btnGuardar = await findLocatorInFrames(page, 'input[name="BTNCAMBIAESTADO"]');
|
|
if (!btnGuardar) throw new Error("Botón GUARDAR no encontrado.");
|
|
|
|
// Clic con reintento y espera de red
|
|
await Promise.all([
|
|
page.waitForLoadState('networkidle').catch(() => {}),
|
|
btnGuardar.click()
|
|
]);
|
|
|
|
// 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 };
|
|
}
|
|
|
|
// --- 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)
|
|
RETURNING *;
|
|
`);
|
|
|
|
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();
|
|
|
|
try {
|
|
const creds = await getHomeServeCreds(job.owner_id);
|
|
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}`);
|
|
} 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);
|
|
}
|
|
} else {
|
|
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
|
}
|
|
} catch (e) {
|
|
console.error("Error en bucle:", e.message);
|
|
setTimeout(pollQueue, CONFIG.POLL_INTERVAL_MS);
|
|
}
|
|
}
|
|
|
|
console.log("📡 Robot HomeServe SaaS Online...");
|
|
pollQueue(); |