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