Actualizar worker-multi-estado.js
This commit is contained in:
parent
9272cdd8a0
commit
dda9dd1a1b
|
|
@ -1,7 +1,6 @@
|
|||
// worker-multi-estado.js
|
||||
'use strict';
|
||||
|
||||
|
||||
const { chromium } = require('playwright');
|
||||
const admin = require('firebase-admin');
|
||||
|
||||
|
|
@ -9,12 +8,8 @@ const admin = require('firebase-admin');
|
|||
const CONFIG = {
|
||||
QUEUE_COLLECTION: 'multiasistencia_cambios_estado',
|
||||
RESULT_COLLECTION: 'multiasistencia_cambios_estado_log',
|
||||
|
||||
// URLs base
|
||||
MULTI_LOGIN: "https://web.multiasistencia.com/w3multi/acceso.php",
|
||||
// La URL base para construir la dirección del servicio
|
||||
MULTI_ACTION_BASE: "https://web.multiasistencia.com/w3multi/fechaccion.php",
|
||||
|
||||
NAV_TIMEOUT: 60000,
|
||||
RESCAN_SECONDS: 60
|
||||
};
|
||||
|
|
@ -23,8 +18,7 @@ const CONFIG = {
|
|||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
function toServerTimestamp() { return admin.firestore.FieldValue.serverTimestamp(); }
|
||||
|
||||
// Conversor de Hora (HH:MM) a Segundos desde media noche (formato interno Multi)
|
||||
// Ej: "08:00" -> 28800
|
||||
// Conversor de Hora
|
||||
function timeToMultiValue(timeStr) {
|
||||
if (!timeStr) return "";
|
||||
const [h, m] = timeStr.split(':').map(Number);
|
||||
|
|
@ -46,23 +40,30 @@ function initFirebase() {
|
|||
return admin.firestore();
|
||||
}
|
||||
|
||||
// --- LOGIN (Reutilizado de tu robot_cobros) ---
|
||||
// --- HELPERS AVANZADOS ---
|
||||
// Esta función es la clave: obliga a la web a reconocer el cambio
|
||||
async function triggerEvents(page, selector) {
|
||||
await page.evaluate((sel) => {
|
||||
const el = document.querySelector(sel);
|
||||
if (el) {
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
el.dispatchEvent(new Event('blur', { bubbles: true }));
|
||||
}
|
||||
}, selector);
|
||||
}
|
||||
|
||||
// --- LOGIN ---
|
||||
async function loginMulti(page, db) {
|
||||
let user = "", pass = "";
|
||||
|
||||
// Buscamos credenciales en Firestore
|
||||
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
||||
if (doc.exists) {
|
||||
user = doc.data().user;
|
||||
pass = doc.data().pass;
|
||||
}
|
||||
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
||||
|
||||
if (!user) throw new Error("Faltan credenciales en providerCredentials/multiasistencia");
|
||||
|
||||
console.log('🔐 Login en Multiasistencia...');
|
||||
await page.goto(CONFIG.MULTI_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Lógica de llenado robusta
|
||||
const userFilled = await page.evaluate((u) => {
|
||||
const el = document.querySelector('input[name="usuario"]') || document.querySelector('input[type="text"]');
|
||||
if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
|
||||
|
|
@ -71,12 +72,11 @@ async function loginMulti(page, db) {
|
|||
|
||||
if (!userFilled) await page.fill('input[name="usuario"]', user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
|
||||
await page.click('input[type="submit"]');
|
||||
await page.waitForTimeout(4000);
|
||||
}
|
||||
|
||||
// --- PLAYWRIGHT HELPERS ---
|
||||
// --- PLAYWRIGHT SETUP ---
|
||||
async function withBrowser(fn) {
|
||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const context = await browser.newContext();
|
||||
|
|
@ -84,92 +84,120 @@ async function withBrowser(fn) {
|
|||
try { return await fn(page); } finally { await browser.close().catch(() => {}); }
|
||||
}
|
||||
|
||||
// --- LÓGICA PRINCIPAL DE CAMBIO DE ESTADO ---
|
||||
// --- LÓGICA PRINCIPAL ---
|
||||
async function processChangeState(page, db, jobData) {
|
||||
const { serviceNumber, reasonValue, comment, dateStr, timeStr } = jobData;
|
||||
|
||||
// 1. LOGIN
|
||||
await loginMulti(page, db);
|
||||
|
||||
// 2. IR A LA URL DEL SERVICIO
|
||||
// Construimos la URL exacta que pediste con el navid incluido
|
||||
// 2. IR AL SERVICIO
|
||||
const targetUrl = `${CONFIG.MULTI_ACTION_BASE}?reparacion=${serviceNumber}&modo=0&navid=%2Fw3multi%2Ffrepasos_new.php%FDGET%FDrefresh%3D1%FC`;
|
||||
|
||||
console.log(`📂 Abriendo servicio ${serviceNumber}...`);
|
||||
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
||||
|
||||
// Esperar a que cargue el formulario (Angular puede tardar)
|
||||
// Buscamos el selector del motivo para saber que cargó
|
||||
// Esperar formulario
|
||||
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
||||
await page.waitForTimeout(2000); // Esperar a que Angular "se asiente"
|
||||
|
||||
console.log('📝 Rellenando formulario...');
|
||||
console.log('📝 Rellenando formulario (Modo Fuerza Bruta)...');
|
||||
|
||||
// 3. SELECCIONAR MOTIVO (Reason)
|
||||
// El HTML muestra <select class="answer-select ..."> dentro de un loop.
|
||||
// Usamos selectOption buscando por el value (ej: "26" para cliente ilocalizable)
|
||||
const reasonSelect = page.locator('select.answer-select').first();
|
||||
await reasonSelect.selectOption(String(reasonValue));
|
||||
// 3. MOTIVO (SELECT)
|
||||
// Seleccionamos y forzamos el evento 'change'
|
||||
const reasonSel = 'select.answer-select';
|
||||
await page.selectOption(reasonSel, String(reasonValue));
|
||||
await triggerEvents(page, reasonSel);
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// 4. COMENTARIO
|
||||
// <textarea formcontrolname="comment" ...>
|
||||
if (comment) {
|
||||
await page.fill('textarea[formcontrolname="comment"]', comment);
|
||||
const commentSel = 'textarea[formcontrolname="comment"]';
|
||||
await page.fill(commentSel, comment);
|
||||
await triggerEvents(page, commentSel);
|
||||
}
|
||||
|
||||
// 5. FECHA SIGUIENTE ACCIÓN
|
||||
// <input type="date" ...>
|
||||
// 5. FECHA
|
||||
if (dateStr) {
|
||||
// Aseguramos formato YYYY-MM-DD
|
||||
await page.fill('input[type="date"]', dateStr);
|
||||
const dateSel = 'input[type="date"]';
|
||||
await page.fill(dateSel, dateStr);
|
||||
await triggerEvents(page, dateSel);
|
||||
// Truco: hacer click fuera para validar
|
||||
await page.click('body');
|
||||
}
|
||||
|
||||
// 6. HORA
|
||||
// La hora en Multi es un select con valores en segundos (ej: 08:00 = 28800)
|
||||
if (timeStr) {
|
||||
const secondsValue = timeToMultiValue(timeStr);
|
||||
// Buscamos el select que está dentro del bloque de hora
|
||||
// El HTML muestra un div class="answer-time"
|
||||
const timeSelect = page.locator('.answer-time select.answer-select').first();
|
||||
|
||||
// Si no lo encuentra por clase específica, intentamos buscar por valor
|
||||
if (await timeSelect.count() > 0) {
|
||||
await timeSelect.selectOption(secondsValue);
|
||||
} else {
|
||||
// Fallback: buscar cualquier select que tenga esa opción
|
||||
await page.evaluate((val) => {
|
||||
const selects = document.querySelectorAll('select');
|
||||
for (const s of selects) {
|
||||
if (s.querySelector(`option[value="${val}"]`)) {
|
||||
s.value = val;
|
||||
s.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return;
|
||||
}
|
||||
// Buscamos el select de hora. Puede ser el segundo select de la página.
|
||||
// Usamos una estrategia de búsqueda por valor para ser precisos.
|
||||
const foundTime = await page.evaluate((val) => {
|
||||
const selects = Array.from(document.querySelectorAll('select'));
|
||||
for (const s of selects) {
|
||||
// Si tiene la opción con ese valor (ej: 28800)
|
||||
if (s.querySelector(`option[value="${val}"]`)) {
|
||||
s.value = val;
|
||||
s.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
s.dispatchEvent(new Event('blur', { bubbles: true }));
|
||||
return true;
|
||||
}
|
||||
}, secondsValue);
|
||||
}
|
||||
return false;
|
||||
}, secondsValue);
|
||||
|
||||
if (!foundTime) console.log(`⚠️ Advertencia: No encontré donde poner la hora ${timeStr}`);
|
||||
}
|
||||
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// 7. GUARDAR - VERIFICACIÓN DE ESTADO DEL BOTÓN
|
||||
const btnSelector = 'button.form-container-button-submit';
|
||||
const btn = page.locator(btnSelector);
|
||||
|
||||
// Comprobar si está habilitado
|
||||
if (await btn.isDisabled()) {
|
||||
console.log('⛔ El botón Guardar sigue deshabilitado. Intentando "despertar" el formulario...');
|
||||
// Intentar hacer focus/blur en el comentario otra vez
|
||||
await page.focus('textarea[formcontrolname="comment"]');
|
||||
await page.keyboard.press('Tab');
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
if (await btn.isDisabled()) {
|
||||
throw new Error("IMPOSIBLE GUARDAR: El formulario no valida los datos (botón gris). Revisa si la fecha/hora son correctas.");
|
||||
}
|
||||
}
|
||||
|
||||
await page.waitForTimeout(1000);
|
||||
console.log('💾 Click en Guardar...');
|
||||
await btn.click();
|
||||
|
||||
// 8. VERIFICAR RESULTADO
|
||||
// Esperamos a ver si sale mensaje de éxito o error
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
// Buscamos mensajes en la pantalla
|
||||
const message = await page.evaluate(() => {
|
||||
// En tu HTML vi esta etiqueta: <encastrables-success-error-message>
|
||||
const msgEl = document.querySelector('encastrables-success-error-message');
|
||||
const errorEl = document.querySelector('.form-container-error');
|
||||
const successEl = document.querySelector('.form-container-success');
|
||||
|
||||
if (errorEl) return `ERROR WEB: ${errorEl.innerText}`;
|
||||
if (successEl) return `EXITO WEB: ${successEl.innerText}`;
|
||||
if (msgEl && msgEl.innerText.trim().length > 0) return `MSG: ${msgEl.innerText}`;
|
||||
return null;
|
||||
});
|
||||
|
||||
// 7. GUARDAR
|
||||
// Botón: <button class="form-container-button-submit ...">
|
||||
console.log('💾 Guardando...');
|
||||
const submitBtn = page.locator('button.form-container-button-submit');
|
||||
|
||||
// Verificamos si está habilitado (el HTML inicial lo tenía disabled, pero al rellenar se habilita)
|
||||
if (await submitBtn.isDisabled()) {
|
||||
throw new Error("El botón de guardar sigue deshabilitado. ¿Falta algún campo obligatorio?");
|
||||
if (message && message.includes('ERROR')) {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
console.log(`ℹ️ Resultado pantalla: ${message || 'Sin mensaje explícito (probablemente OK)'}`);
|
||||
|
||||
await submitBtn.click();
|
||||
|
||||
// Esperamos confirmación o redirección
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
return { success: true, url: targetUrl };
|
||||
// Si la URL cambió, es buena señal
|
||||
const currentUrl = page.url();
|
||||
return { success: true, finalUrl: currentUrl, webMessage: message };
|
||||
}
|
||||
|
||||
// --- GESTIÓN DE COLAS (WORKER) ---
|
||||
// --- WORKER LOOP ---
|
||||
async function claimJobById(db, jobId) {
|
||||
const ref = db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId);
|
||||
return await db.runTransaction(async (tx) => {
|
||||
|
|
@ -188,13 +216,13 @@ async function markJobDone(db, jobId, result) {
|
|||
async function markJobFailed(db, jobId, err) {
|
||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({
|
||||
status: 'FAILED',
|
||||
error: { message: err.message, stack: err.stack }
|
||||
error: { message: err.message }
|
||||
}, { merge: true });
|
||||
await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: false, error: err.message, createdAt: toServerTimestamp() });
|
||||
}
|
||||
|
||||
async function processJob(db, job) {
|
||||
console.log(`>>> Procesando Job: ${job.id} (Servicio: ${job.serviceNumber})`);
|
||||
console.log(`>>> Procesando Job: ${job.id}`);
|
||||
try {
|
||||
await withBrowser(async (page) => {
|
||||
const res = await processChangeState(page, db, {
|
||||
|
|
@ -218,15 +246,11 @@ function startWorker(db) {
|
|||
const run = async () => {
|
||||
while(queue.length) { await processJob(db, await claimJobById(db, queue.shift())); }
|
||||
};
|
||||
|
||||
// Escuchar nuevos trabajos
|
||||
db.collection(CONFIG.QUEUE_COLLECTION).where('status', '==', 'PENDING').onSnapshot(s => {
|
||||
s.docChanges().forEach(c => { if(c.type==='added') { queue.push(c.doc.id); run(); } });
|
||||
});
|
||||
|
||||
console.log('🚀 Worker Multiasistencia Estados LISTO.');
|
||||
console.log('🚀 Worker Multiasistencia Estados (FUERZA BRUTA) LISTO.');
|
||||
}
|
||||
|
||||
// Iniciar
|
||||
const db = initFirebase();
|
||||
startWorker(db);
|
||||
Loading…
Reference in New Issue