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