Actualizar worker-multi-estado.js

This commit is contained in:
marsalva 2026-01-06 22:30:31 +00:00
parent 244678b69d
commit 0e35df2319
1 changed files with 15 additions and 17 deletions

View File

@ -92,7 +92,7 @@ async function processChangeState(page, db, jobData) {
// 2. IR AL SERVICIO // 2. IR AL SERVICIO
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 27867185...`); // Log limpio para depurar console.log(`📂 Abriendo servicio ${serviceNumber}...`);
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 }); await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
// Esperar formulario // Esperar formulario
@ -101,7 +101,7 @@ async function processChangeState(page, db, jobData) {
console.log('📝 Rellenando formulario (Modo Preciso)...'); console.log('📝 Rellenando formulario (Modo Preciso)...');
// 3. MOTIVO (Primer select de la página suele ser el motivo) // 3. MOTIVO (Primer select de la página)
const reasonSel = page.locator('select.answer-select').first(); const reasonSel = page.locator('select.answer-select').first();
await reasonSel.selectOption(String(reasonValue)); await reasonSel.selectOption(String(reasonValue));
await forceUpdate(await reasonSel.elementHandle()); await forceUpdate(await reasonSel.elementHandle());
@ -113,22 +113,22 @@ async function processChangeState(page, db, jobData) {
await forceUpdate(await commentBox.elementHandle()); await forceUpdate(await commentBox.elementHandle());
} }
// 5. FECHA // 5. FECHA (AQUÍ ESTABA EL ERROR: AHORA USAMOS .first())
if (dateStr) { if (dateStr) {
const dateInput = page.locator('input[type="date"]'); // Había 2 inputs de fecha, cogemos el primero que es el de "Siguiente Acción"
const dateInput = page.locator('input[type="date"]').first();
await dateInput.fill(dateStr); await dateInput.fill(dateStr);
await forceUpdate(await dateInput.elementHandle()); await forceUpdate(await dateInput.elementHandle());
// Click fuera para asegurar validación de fecha // Click fuera para asegurar validación
await page.click('body'); await page.click('body');
} }
// 6. HORA (El punto crítico) // 6. HORA
if (timeStr) { if (timeStr) {
const secondsValue = timeToMultiValue(timeStr); // ej: "28800" para 08:00 const secondsValue = timeToMultiValue(timeStr); // ej: "28800" para 08:00
console.log(`🕒 Intentando poner hora: ${timeStr} (Valor interno: ${secondsValue})`); console.log(`🕒 Intentando poner hora: ${timeStr} (Valor interno: ${secondsValue})`);
// ESTRATEGIA INFALIBLE: Buscar el select que contiene esa opción específica usando XPath // Búsqueda por XPath (Infalible)
// "Búscame un <select> que tenga dentro una <option> con value='28800'"
const timeSelectHandle = await page.$(`xpath=//select[.//option[@value="${secondsValue}"]]`); const timeSelectHandle = await page.$(`xpath=//select[.//option[@value="${secondsValue}"]]`);
if (timeSelectHandle) { if (timeSelectHandle) {
@ -136,11 +136,10 @@ async function processChangeState(page, db, jobData) {
await forceUpdate(timeSelectHandle); await forceUpdate(timeSelectHandle);
console.log('✅ Hora seleccionada correctamente.'); console.log('✅ Hora seleccionada correctamente.');
} else { } else {
console.log(`⚠️ ERROR GRAVE: No encuentro ningún desplegable que tenga la opción de valor "${secondsValue}".`); console.log(`⚠️ ERROR: No encuentro opción para hora ${timeStr}. Probando fallback...`);
// Fallback desesperado: intentar ponerlo en el segundo select que encuentre // Fallback: segundo select de la página
const allSelects = await page.$$('select'); const allSelects = await page.$$('select');
if (allSelects.length > 1) { if (allSelects.length > 1) {
console.log('⚠️ Intentando fallback en el segundo select...');
await allSelects[1].selectOption(secondsValue).catch(() => {}); await allSelects[1].selectOption(secondsValue).catch(() => {});
await forceUpdate(allSelects[1]); await forceUpdate(allSelects[1]);
} }
@ -154,14 +153,13 @@ async function processChangeState(page, db, jobData) {
// Verificación final antes de clickar // Verificación final antes de clickar
if (await btn.isDisabled()) { if (await btn.isDisabled()) {
console.log('⛔ Botón deshabilitado. Intentando reactivación final...'); console.log('⛔ Botón deshabilitado. Re-activando campo comentario...');
// A veces hacer click en el comentario ayuda a que Angular se entere
await page.click('textarea[formcontrolname="comment"]'); await page.click('textarea[formcontrolname="comment"]');
await page.keyboard.press('Tab'); await page.keyboard.press('Tab');
await page.waitForTimeout(1000); await page.waitForTimeout(1000);
if (await btn.isDisabled()) { if (await btn.isDisabled()) {
throw new Error(`IMPOSIBLE GUARDAR: Formulario incompleto. ¿La hora ${timeStr} es válida para este servicio?`); throw new Error(`IMPOSIBLE GUARDAR: El formulario sigue bloqueado.`);
} }
} }
@ -171,7 +169,7 @@ async function processChangeState(page, db, jobData) {
// 8. VERIFICAR RESULTADO // 8. VERIFICAR RESULTADO
await page.waitForTimeout(4000); await page.waitForTimeout(4000);
// Captura de mensajes de éxito/error de la web // Captura de mensajes
const message = await page.evaluate(() => { const message = await page.evaluate(() => {
const err = document.querySelector('.form-container-error'); const err = document.querySelector('.form-container-error');
const ok = document.querySelector('.form-container-success'); const ok = document.querySelector('.form-container-success');
@ -190,7 +188,7 @@ async function processChangeState(page, db, jobData) {
return { success: true, finalUrl: page.url() }; return { success: true, finalUrl: page.url() };
} }
// --- 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) => {
@ -242,7 +240,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 Estados (BÚSQUEDA XPATH) LISTO.'); console.log('🚀 Worker Multiasistencia Estados (FINAL CORREGIDO) LISTO.');
} }
const db = initFirebase(); const db = initFirebase();