Actualizar worker-multi-estado.js

This commit is contained in:
marsalva 2026-01-06 22:55:07 +00:00
parent c551bcde8b
commit 43a5b2c3a2
1 changed files with 48 additions and 30 deletions

View File

@ -112,7 +112,7 @@ async function processChangeState(page, db, jobData) {
await forceUpdate(await commentBox.elementHandle());
}
// 5. FECHA (Usamos .first() para evitar error de doble fecha)
// 5. FECHA
if (dateStr) {
const dateInput = page.locator('input[type="date"]').first();
await dateInput.fill(dateStr);
@ -120,7 +120,7 @@ async function processChangeState(page, db, jobData) {
await page.click('body');
}
// 6. HORA (Usamos XPath para buscar por valor)
// 6. HORA
if (timeStr) {
const secondsValue = timeToMultiValue(timeStr);
const timeSelectHandle = await page.$(`xpath=//select[.//option[@value="${secondsValue}"]]`);
@ -129,7 +129,6 @@ async function processChangeState(page, db, jobData) {
await timeSelectHandle.selectOption(secondsValue);
await forceUpdate(timeSelectHandle);
} else {
// Fallback
const allSelects = await page.$$('select');
if (allSelects.length > 1) {
await allSelects[1].selectOption(secondsValue).catch(() => {});
@ -150,49 +149,68 @@ async function processChangeState(page, db, jobData) {
await page.waitForTimeout(1000);
if (await btn.isDisabled()) {
throw new Error(`IMPOSIBLE GUARDAR: El formulario sigue bloqueado.`);
throw new Error(`IMPOSIBLE GUARDAR: Formulario bloqueado.`);
}
}
console.log('💾 Click en Guardar...');
await btn.click();
// --- 8. DETECCIÓN DE POPUP "SÍ" (NUEVO CÓDIGO) ---
// Esperamos 2.5s para ver si salta la alerta roja
await page.waitForTimeout(2500);
// 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);
// Buscamos el botón usando la clase específica que me diste y el texto "Sí"
// 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 DETECTADA! (Mensaje informativo de SMS).');
console.log('👉 Pulsando botón "Sí"...');
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
await confirmBtn.click();
await page.waitForTimeout(3000); // Esperar guardado real
// Esperamos a que la acción se procese tras el "Sí"
await page.waitForTimeout(3000);
} else {
console.log(' No apareció alerta de SMS (o ya se guardó).');
console.log(' No hubo alerta de SMS (o se procesó rápido).');
}
// ----------------------------------------------------
// 9. VERIFICAR RESULTADO FINAL
await page.waitForTimeout(2000);
const message = await page.evaluate(() => {
const err = document.querySelector('.form-container-error');
const ok = document.querySelector('.form-container-success');
const toast = document.querySelector('encastrables-success-error-message');
// 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...");
}
// Leemos el texto exacto
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 };
if (err && err.innerText) return `ERROR WEB: ${err.innerText}`;
if (ok && ok.innerText) return `EXITO WEB: ${ok.innerText}`;
if (toast && toast.innerText) return `MSG: ${toast.innerText}`;
return null;
return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 200) }; // Fallback
});
console.log(` Estado final: ${message || 'Sin mensaje (Redirección correcta)'}`);
if (message && message.includes('ERROR')) throw new Error(message);
console.log(`🏁 RESULTADO FINAL: [${finalResult.type}] "${finalResult.text.replace(/\n/g, ' ')}"`);
return { success: true, finalUrl: page.url() };
// 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)}...` };
}
}
// --- WORKER LOOP ---
@ -231,7 +249,7 @@ async function processJob(db, job) {
timeStr: job.timeStr
});
await markJobDone(db, job.id, res);
console.log(`✅ Job ${job.id} Completado.`);
console.log(`✅ Job ${job.id} Completado: ${res.message || 'OK'}`);
});
} catch (err) {
console.error(`❌ Job ${job.id} Falló:`, err.message);
@ -247,7 +265,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 (V3 - CONFIRMACIÓN SÍ) LISTO.');
console.log('🚀 Worker Multiasistencia (V4 - VERIFICACION ESTRICTA) LISTO.');
}
const db = initFirebase();