Actualizar worker-multi-estado.js
This commit is contained in:
parent
43a5b2c3a2
commit
03501e8101
|
|
@ -1,4 +1,4 @@
|
||||||
// worker-multi-estado.js
|
// worker-multi-estado.js (V5 - CON FOTO DE DIAGNÓSTICO)
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const { chromium } = require('playwright');
|
const { chromium } = require('playwright');
|
||||||
|
|
@ -18,7 +18,6 @@ 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
|
|
||||||
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);
|
||||||
|
|
@ -71,7 +70,6 @@ async function withBrowser(fn) {
|
||||||
try { return await fn(page); } finally { await browser.close().catch(() => {}); }
|
try { return await fn(page); } finally { await browser.close().catch(() => {}); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- HELPERS DE EVENTOS ---
|
|
||||||
async function forceUpdate(elementHandle) {
|
async function forceUpdate(elementHandle) {
|
||||||
if (elementHandle) {
|
if (elementHandle) {
|
||||||
await elementHandle.evaluate(el => {
|
await elementHandle.evaluate(el => {
|
||||||
|
|
@ -149,68 +147,62 @@ async function processChangeState(page, db, jobData) {
|
||||||
await page.waitForTimeout(1000);
|
await page.waitForTimeout(1000);
|
||||||
|
|
||||||
if (await btn.isDisabled()) {
|
if (await btn.isDisabled()) {
|
||||||
throw new Error(`IMPOSIBLE GUARDAR: Formulario bloqueado.`);
|
throw new Error(`IMPOSIBLE GUARDAR: El formulario bloqueado.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('💾 Click en Guardar...');
|
console.log('💾 Click en Guardar...');
|
||||||
await btn.click();
|
await btn.click();
|
||||||
|
|
||||||
// 8. GESTIÓN DE ALERTAS Y CONFIRMACIÓN
|
// 8. GESTIÓN DE ALERTAS (EL MOMENTO CRÍTICO)
|
||||||
console.log('👀 Esperando mensajes o confirmaciones...');
|
// Esperamos más tiempo para asegurar que el popup carga
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
// Esperamos un poco para que salga el Popup si tiene que salir
|
|
||||||
await page.waitForTimeout(2000);
|
|
||||||
|
|
||||||
// Buscamos el botón "Sí"
|
|
||||||
const confirmBtn = page.locator('button.form-container-button-submit-toast').filter({ hasText: 'Sí' });
|
const confirmBtn = page.locator('button.form-container-button-submit-toast').filter({ hasText: 'Sí' });
|
||||||
|
|
||||||
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
|
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
|
||||||
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
|
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
|
||||||
await confirmBtn.click();
|
await confirmBtn.click();
|
||||||
// Esperamos a que la acción se procese tras el "Sí"
|
|
||||||
await page.waitForTimeout(3000);
|
// ¡OJO! Esperar a que el botón DESAPAREZCA (Confirmación de que el click funcionó)
|
||||||
|
try {
|
||||||
|
await confirmBtn.waitFor({ state: 'hidden', timeout: 5000 });
|
||||||
|
console.log('✅ Botón "Sí" ha desaparecido (Click exitoso).');
|
||||||
|
} catch(e) {
|
||||||
|
console.log('⚠️ El botón "Sí" sigue ahí. Forzando segundo click...');
|
||||||
|
await confirmBtn.click(); // Re-intentar
|
||||||
|
}
|
||||||
|
|
||||||
|
// Espera larga para el guardado real del servidor
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
} else {
|
} else {
|
||||||
console.log('ℹ️ No hubo alerta de SMS (o se procesó rápido).');
|
console.log('ℹ️ No saltó la alerta de SMS (o ya se procesó).');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 9. VERIFICACIÓN FINAL (LO QUE PEDISTE)
|
// 9. VERIFICACIÓN FINAL + CAPTURA DE PANTALLA
|
||||||
// Esperamos explícitamente a que aparezca un mensaje de éxito o error
|
// Hacemos una captura ahora mismo para ver qué demonios hay en la pantalla
|
||||||
try {
|
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
|
||||||
await page.waitForSelector('.form-container-success, .form-container-error, encastrables-success-error-message', { timeout: 10000 });
|
const screenshotBase64 = screenshotBuffer.toString('base64');
|
||||||
} catch (e) {
|
|
||||||
console.log("⏳ Tiempo de espera agotado buscando mensaje. Analizando pantalla...");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Leemos el texto exacto
|
// Analizamos texto
|
||||||
const finalResult = await page.evaluate(() => {
|
const finalResult = await page.evaluate(() => {
|
||||||
// Selector verde (Exito)
|
|
||||||
const successEl = document.querySelector('.form-container-success') || document.querySelector('.bg-success');
|
const successEl = document.querySelector('.form-container-success') || document.querySelector('.bg-success');
|
||||||
// Selector rojo (Error)
|
|
||||||
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
|
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
|
||||||
// Selector genérico
|
|
||||||
const msgEl = document.querySelector('encastrables-success-error-message');
|
|
||||||
const infoMsg = document.querySelector('.form-container-message-info');
|
|
||||||
|
|
||||||
if (successEl && successEl.innerText.length > 2) return { type: 'OK', text: successEl.innerText };
|
if (successEl && successEl.innerText.length > 2) return { type: 'OK', text: successEl.innerText };
|
||||||
if (errorEl && errorEl.innerText.length > 2) return { type: 'ERROR', text: errorEl.innerText };
|
if (errorEl && errorEl.innerText.length > 2) return { type: 'ERROR', text: errorEl.innerText };
|
||||||
if (msgEl && msgEl.innerText.length > 2) return { type: 'INFO', text: msgEl.innerText };
|
|
||||||
if (infoMsg && infoMsg.innerText.length > 2) return { type: 'INFO', text: infoMsg.innerText };
|
|
||||||
|
|
||||||
return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 200) }; // Fallback
|
return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 300) };
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`🏁 RESULTADO FINAL: [${finalResult.type}] "${finalResult.text.replace(/\n/g, ' ')}"`);
|
console.log(`🏁 RESULTADO: [${finalResult.type}]`);
|
||||||
|
|
||||||
// Validamos según tu petición
|
// Devolvemos el resultado y LA FOTO
|
||||||
if (finalResult.type === 'OK' || finalResult.text.includes('correctamente')) {
|
return {
|
||||||
return { success: true, message: finalResult.text };
|
success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')),
|
||||||
} else if (finalResult.type === 'ERROR') {
|
message: finalResult.text,
|
||||||
throw new Error(`WEB ERROR: ${finalResult.text}`);
|
screenshot: screenshotBase64 // <-- LA PRUEBA DEL DELITO
|
||||||
} else {
|
};
|
||||||
// Si no es ni verde ni rojo claro, devolvemos lo que vemos para que tú juzgues
|
|
||||||
return { success: true, warning: `No vi mensaje verde, pero tampoco rojo. Pantalla dice: ${finalResult.text.substring(0,100)}...` };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- WORKER LOOP ---
|
// --- WORKER LOOP ---
|
||||||
|
|
@ -225,8 +217,14 @@ async function claimJobById(db, jobId) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markJobDone(db, jobId, result) {
|
async function markJobDone(db, jobId, result) {
|
||||||
|
// Guardamos la foto en el log
|
||||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'DONE', result }, { merge: true });
|
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'DONE', result }, { merge: true });
|
||||||
await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: true, ...result, createdAt: toServerTimestamp() });
|
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
||||||
|
jobId,
|
||||||
|
ok: true,
|
||||||
|
...result, // Aquí va la screenshot
|
||||||
|
createdAt: toServerTimestamp()
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markJobFailed(db, jobId, err) {
|
async function markJobFailed(db, jobId, err) {
|
||||||
|
|
@ -249,7 +247,7 @@ async function processJob(db, job) {
|
||||||
timeStr: job.timeStr
|
timeStr: job.timeStr
|
||||||
});
|
});
|
||||||
await markJobDone(db, job.id, res);
|
await markJobDone(db, job.id, res);
|
||||||
console.log(`✅ Job ${job.id} Completado: ${res.message || 'OK'}`);
|
console.log(`✅ Job ${job.id} Completado.`);
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`❌ Job ${job.id} Falló:`, err.message);
|
console.error(`❌ Job ${job.id} Falló:`, err.message);
|
||||||
|
|
@ -265,7 +263,7 @@ function startWorker(db) {
|
||||||
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 (V4 - VERIFICACION ESTRICTA) LISTO.');
|
console.log('🚀 Worker Multiasistencia (V5 - CON FOTO) LISTO.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const db = initFirebase();
|
const db = initFirebase();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue