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';
|
||||
|
||||
const { chromium } = require('playwright');
|
||||
|
|
@ -18,7 +18,6 @@ const CONFIG = {
|
|||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
function toServerTimestamp() { return admin.firestore.FieldValue.serverTimestamp(); }
|
||||
|
||||
// Conversor de Hora
|
||||
function timeToMultiValue(timeStr) {
|
||||
if (!timeStr) return "";
|
||||
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(() => {}); }
|
||||
}
|
||||
|
||||
// --- HELPERS DE EVENTOS ---
|
||||
async function forceUpdate(elementHandle) {
|
||||
if (elementHandle) {
|
||||
await elementHandle.evaluate(el => {
|
||||
|
|
@ -149,68 +147,62 @@ async function processChangeState(page, db, jobData) {
|
|||
await page.waitForTimeout(1000);
|
||||
|
||||
if (await btn.isDisabled()) {
|
||||
throw new Error(`IMPOSIBLE GUARDAR: Formulario bloqueado.`);
|
||||
throw new Error(`IMPOSIBLE GUARDAR: El formulario bloqueado.`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('💾 Click en Guardar...');
|
||||
await btn.click();
|
||||
|
||||
// 8. GESTIÓN DE ALERTAS Y CONFIRMACIÓN
|
||||
console.log('👀 Esperando mensajes o confirmaciones...');
|
||||
|
||||
// Esperamos un poco para que salga el Popup si tiene que salir
|
||||
await page.waitForTimeout(2000);
|
||||
// 8. GESTIÓN DE ALERTAS (EL MOMENTO CRÍTICO)
|
||||
// Esperamos más tiempo para asegurar que el popup carga
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
// Buscamos el botón "Sí"
|
||||
const confirmBtn = page.locator('button.form-container-button-submit-toast').filter({ hasText: 'Sí' });
|
||||
|
||||
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
|
||||
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
|
||||
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 {
|
||||
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)
|
||||
// Esperamos explícitamente a que aparezca un mensaje de éxito o error
|
||||
try {
|
||||
await page.waitForSelector('.form-container-success, .form-container-error, encastrables-success-error-message', { timeout: 10000 });
|
||||
} catch (e) {
|
||||
console.log("⏳ Tiempo de espera agotado buscando mensaje. Analizando pantalla...");
|
||||
}
|
||||
// 9. VERIFICACIÓN FINAL + CAPTURA DE PANTALLA
|
||||
// Hacemos una captura ahora mismo para ver qué demonios hay en la pantalla
|
||||
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
|
||||
const screenshotBase64 = screenshotBuffer.toString('base64');
|
||||
|
||||
// Leemos el texto exacto
|
||||
// Analizamos texto
|
||||
const finalResult = await page.evaluate(() => {
|
||||
// Selector verde (Exito)
|
||||
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');
|
||||
// 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 (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
|
||||
if (finalResult.type === 'OK' || finalResult.text.includes('correctamente')) {
|
||||
return { success: true, message: finalResult.text };
|
||||
} else if (finalResult.type === 'ERROR') {
|
||||
throw new Error(`WEB ERROR: ${finalResult.text}`);
|
||||
} 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)}...` };
|
||||
}
|
||||
// Devolvemos el resultado y LA FOTO
|
||||
return {
|
||||
success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')),
|
||||
message: finalResult.text,
|
||||
screenshot: screenshotBase64 // <-- LA PRUEBA DEL DELITO
|
||||
};
|
||||
}
|
||||
|
||||
// --- WORKER LOOP ---
|
||||
|
|
@ -225,8 +217,14 @@ async function claimJobById(db, jobId) {
|
|||
}
|
||||
|
||||
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.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) {
|
||||
|
|
@ -249,7 +247,7 @@ async function processJob(db, job) {
|
|||
timeStr: job.timeStr
|
||||
});
|
||||
await markJobDone(db, job.id, res);
|
||||
console.log(`✅ Job ${job.id} Completado: ${res.message || 'OK'}`);
|
||||
console.log(`✅ Job ${job.id} Completado.`);
|
||||
});
|
||||
} catch (err) {
|
||||
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 => {
|
||||
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();
|
||||
|
|
|
|||
Loading…
Reference in New Issue