Actualizar worker-multi-estado.js
This commit is contained in:
parent
03501e8101
commit
0fac382d4d
|
|
@ -1,4 +1,4 @@
|
||||||
// worker-multi-estado.js (V5 - CON FOTO DE DIAGNÓSTICO)
|
// worker-multi-estado.js (V6 - LOG COMPLETO DE DATOS)
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const { chromium } = require('playwright');
|
const { chromium } = require('playwright');
|
||||||
|
|
@ -92,7 +92,6 @@ async function processChangeState(page, db, jobData) {
|
||||||
console.log(`📂 Abriendo servicio ${serviceNumber}...`);
|
console.log(`📂 Abriendo servicio ${serviceNumber}...`);
|
||||||
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
||||||
|
|
||||||
// Esperar formulario
|
|
||||||
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
||||||
await page.waitForTimeout(1500);
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
|
@ -154,8 +153,7 @@ async function processChangeState(page, db, jobData) {
|
||||||
console.log('💾 Click en Guardar...');
|
console.log('💾 Click en Guardar...');
|
||||||
await btn.click();
|
await btn.click();
|
||||||
|
|
||||||
// 8. GESTIÓN DE ALERTAS (EL MOMENTO CRÍTICO)
|
// 8. GESTIÓN DE ALERTAS
|
||||||
// Esperamos más tiempo para asegurar que el popup carga
|
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
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í' });
|
||||||
|
|
@ -164,27 +162,20 @@ async function processChangeState(page, db, jobData) {
|
||||||
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
|
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
|
||||||
await confirmBtn.click();
|
await confirmBtn.click();
|
||||||
|
|
||||||
// ¡OJO! Esperar a que el botón DESAPAREZCA (Confirmación de que el click funcionó)
|
|
||||||
try {
|
try {
|
||||||
await confirmBtn.waitFor({ state: 'hidden', timeout: 5000 });
|
await confirmBtn.waitFor({ state: 'hidden', timeout: 5000 });
|
||||||
console.log('✅ Botón "Sí" ha desaparecido (Click exitoso).');
|
console.log('✅ Botón "Sí" ha desaparecido.');
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
console.log('⚠️ El botón "Sí" sigue ahí. Forzando segundo click...');
|
console.log('⚠️ Forzando segundo click en "Sí"...');
|
||||||
await confirmBtn.click(); // Re-intentar
|
await confirmBtn.click();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Espera larga para el guardado real del servidor
|
|
||||||
await page.waitForTimeout(5000);
|
await page.waitForTimeout(5000);
|
||||||
} else {
|
|
||||||
console.log('ℹ️ No saltó la alerta de SMS (o ya se procesó).');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 9. VERIFICACIÓN FINAL + CAPTURA DE PANTALLA
|
// 9. VERIFICACIÓN FINAL + FOTO
|
||||||
// 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 screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
|
||||||
const screenshotBase64 = screenshotBuffer.toString('base64');
|
const screenshotBase64 = screenshotBuffer.toString('base64');
|
||||||
|
|
||||||
// Analizamos texto
|
|
||||||
const finalResult = await page.evaluate(() => {
|
const finalResult = await page.evaluate(() => {
|
||||||
const successEl = document.querySelector('.form-container-success') || document.querySelector('.bg-success');
|
const successEl = document.querySelector('.form-container-success') || document.querySelector('.bg-success');
|
||||||
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
|
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
|
||||||
|
|
@ -197,15 +188,14 @@ async function processChangeState(page, db, jobData) {
|
||||||
|
|
||||||
console.log(`🏁 RESULTADO: [${finalResult.type}]`);
|
console.log(`🏁 RESULTADO: [${finalResult.type}]`);
|
||||||
|
|
||||||
// Devolvemos el resultado y LA FOTO
|
|
||||||
return {
|
return {
|
||||||
success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')),
|
success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')),
|
||||||
message: finalResult.text,
|
message: finalResult.text,
|
||||||
screenshot: screenshotBase64 // <-- LA PRUEBA DEL DELITO
|
screenshot: screenshotBase64
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- WORKER LOOP ---
|
// --- WORKER LOOP (ACTUALIZADO PARA GUARDAR INFO) ---
|
||||||
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) => {
|
||||||
|
|
@ -216,23 +206,49 @@ async function claimJobById(db, jobId) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markJobDone(db, jobId, result) {
|
// ✅ MODIFICADO: Ahora recibe el objeto 'job' completo para guardar sus datos
|
||||||
// Guardamos la foto en el log
|
async function markJobDone(db, job, result) {
|
||||||
|
const jobId = job.id;
|
||||||
|
// 1. Actualizamos el estado en la cola
|
||||||
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 });
|
||||||
|
|
||||||
|
// 2. Guardamos el LOG COMPLETO con los datos de entrada
|
||||||
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
||||||
jobId,
|
jobId,
|
||||||
ok: true,
|
ok: true,
|
||||||
...result, // Aquí va la screenshot
|
// Datos del servicio enviados:
|
||||||
|
serviceNumber: job.serviceNumber || '',
|
||||||
|
reason: job.reasonValue || '',
|
||||||
|
comment: job.comment || '',
|
||||||
|
date: job.dateStr || '',
|
||||||
|
time: job.timeStr || '',
|
||||||
|
// Resultado del robot:
|
||||||
|
...result, // Incluye screenshot y message
|
||||||
createdAt: toServerTimestamp()
|
createdAt: toServerTimestamp()
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function markJobFailed(db, jobId, err) {
|
// ✅ MODIFICADO: También guardamos los datos si falla, para saber qué provocó el error
|
||||||
|
async function markJobFailed(db, job, err) {
|
||||||
|
const jobId = job.id;
|
||||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({
|
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({
|
||||||
status: 'FAILED',
|
status: 'FAILED',
|
||||||
error: { message: err.message }
|
error: { message: err.message }
|
||||||
}, { merge: true });
|
}, { merge: true });
|
||||||
await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: false, error: err.message, createdAt: toServerTimestamp() });
|
|
||||||
|
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
||||||
|
jobId,
|
||||||
|
ok: false,
|
||||||
|
// Datos del servicio:
|
||||||
|
serviceNumber: job.serviceNumber || '',
|
||||||
|
reason: job.reasonValue || '',
|
||||||
|
comment: job.comment || '',
|
||||||
|
date: job.dateStr || '',
|
||||||
|
time: job.timeStr || '',
|
||||||
|
// Error:
|
||||||
|
error: err.message,
|
||||||
|
createdAt: toServerTimestamp()
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function processJob(db, job) {
|
async function processJob(db, job) {
|
||||||
|
|
@ -246,12 +262,14 @@ async function processJob(db, job) {
|
||||||
dateStr: job.dateStr,
|
dateStr: job.dateStr,
|
||||||
timeStr: job.timeStr
|
timeStr: job.timeStr
|
||||||
});
|
});
|
||||||
await markJobDone(db, job.id, res);
|
// Pasamos el objeto 'job' entero
|
||||||
|
await markJobDone(db, job, res);
|
||||||
console.log(`✅ Job ${job.id} Completado.`);
|
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);
|
||||||
await markJobFailed(db, job.id, err);
|
// Pasamos el objeto 'job' entero
|
||||||
|
await markJobFailed(db, job, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -263,7 +281,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 (V5 - CON FOTO) LISTO.');
|
console.log('🚀 Worker Multiasistencia (V6 - LOG COMPLETO) LISTO.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const db = initFirebase();
|
const db = initFirebase();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue