Actualizar worker-multi-estado.js

This commit is contained in:
marsalva 2026-01-10 15:17:42 +00:00
parent 36073d8b3b
commit 02b7ea9daa
1 changed files with 114 additions and 98 deletions

View File

@ -1,4 +1,4 @@
// worker-multi-estado.js (V7 - CON DEBUG DE SELECTOR Y FECHA CONTACTO) // worker-multi-estado.js (V9 - ADAPTADOR PARA TU APP + FECHA CONTACTO AUTO)
'use strict'; 'use strict';
const { chromium } = require('playwright'); const { chromium } = require('playwright');
@ -28,6 +28,41 @@ function timeToMultiValue(timeStr) {
return String((h * 3600) + (m * 60)); return String((h * 3600) + (m * 60));
} }
// Helper: Extraer hora de un texto (Ej: "cita a las 13:00") -> "13:00"
function extractTimeFromText(text) {
if (!text) return null;
const match = text.match(/(\d{1,2}:\d{2})/);
return match ? match[1] : null;
}
// Helper: Convertir DD/MM/YYYY a YYYY-MM-DD
function normalizeDate(dateStr) {
if (!dateStr) return "";
// Si ya viene como YYYY-MM-DD, devolver tal cual
if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) return dateStr;
// Si viene como DD/MM/YYYY
if (dateStr.includes('/')) {
const [day, month, year] = dateStr.split('/');
return `${year}-${month}-${day}`;
}
return dateStr;
}
// Obtener fecha y hora actuales desglosadas (Sistema)
function getCurrentDateTime() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const dateStr = `${year}-${month}-${day}`;
const hourStr = String(now.getHours());
const minStr = String(now.getMinutes()).padStart(2, '0');
return { dateStr, hourStr, minStr };
}
// --- FIREBASE INIT --- // --- FIREBASE INIT ---
function initFirebase() { function initFirebase() {
if (!process.env.FIREBASE_PRIVATE_KEY) throw new Error('Missing FIREBASE_PRIVATE_KEY'); if (!process.env.FIREBASE_PRIVATE_KEY) throw new Error('Missing FIREBASE_PRIVATE_KEY');
@ -95,7 +130,32 @@ async function forceUpdate(elementHandle) {
// --- LÓGICA PRINCIPAL --- // --- LÓGICA PRINCIPAL ---
async function processChangeState(page, db, jobData) { async function processChangeState(page, db, jobData) {
const { serviceNumber, reasonValue, comment, dateStr, timeStr } = jobData; // --- ADAPTADOR DE DATOS (MAPPING) ---
// Tu App envía 'nuevoEstado', 'observaciones', 'fecha' (DD/MM/YYYY)
const serviceNumber = jobData.serviceNumber;
// 1. Mapear Motivo
const reasonValue = jobData.reasonValue || jobData.nuevoEstado || jobData.estado;
// 2. Mapear Comentario
const comment = jobData.comment || jobData.observaciones || jobData.nota;
// 3. Mapear y Normalizar Fecha (DD/MM/YYYY -> YYYY-MM-DD)
const rawDate = jobData.dateStr || jobData.fecha;
const dateStr = normalizeDate(rawDate);
// 4. Mapear Hora (Intentar buscar en timeStr, o extraer de la nota)
let timeStr = jobData.timeStr || extractTimeFromText(comment);
console.log(`🔧 DATOS PROCESADOS: ID:${reasonValue} | Fecha:${dateStr} | Hora:${timeStr}`);
// VALIDACIÓN
if (!reasonValue || reasonValue === 'undefined') {
throw new Error("DATOS FALTANTES: No se encontró 'nuevoEstado' ni 'reasonValue' en Firebase.");
}
// -----------------------------------------------------------
// 1. LOGIN // 1. LOGIN
await loginMulti(page, db); await loginMulti(page, db);
@ -109,27 +169,20 @@ async function processChangeState(page, db, jobData) {
await page.waitForTimeout(1500); await page.waitForTimeout(1500);
console.log('📝 Rellenando formulario...'); console.log('📝 Rellenando formulario...');
// 3. MOTIVO (CON DIAGNÓSTICO DE ERROR) // 3. MOTIVO
const reasonSel = page.locator('select.answer-select').first(); const reasonSel = page.locator('select.answer-select').first();
const targetValue = String(reasonValue); const targetValue = String(reasonValue);
// --- BLOQUE DE DIAGNÓSTICO --- // Diagnóstico rápido
const availableOptions = await reasonSel.evaluate((select) => { const availableOptions = await reasonSel.evaluate((select) => {
return Array.from(select.options).map(o => ({ return Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() }));
value: o.value,
text: o.innerText.trim()
}));
}); });
console.log(`🔍 Intentando seleccionar motivo ID: "${targetValue}"`);
const optionExists = availableOptions.find(o => o.value === targetValue); const optionExists = availableOptions.find(o => o.value === targetValue);
if (!optionExists) { if (!optionExists) {
const validList = availableOptions.map(o => `[${o.value}: ${o.text}]`).join(', '); const validList = availableOptions.map(o => `[${o.value}: ${o.text}]`).join(', ');
console.error(`❌ ERROR: El motivo "${targetValue}" no existe.`); throw new Error(`MOTIVO INVÁLIDO: El ID "${targetValue}" no existe. Opciones: ${validList}`);
throw new Error(`MOTIVO INVÁLIDO: El ID "${targetValue}" no está disponible en este estado. Opciones válidas: ${validList}`);
} }
// -----------------------------
await reasonSel.selectOption(targetValue); await reasonSel.selectOption(targetValue);
await forceUpdate(await reasonSel.elementHandle()); await forceUpdate(await reasonSel.elementHandle());
@ -141,66 +194,55 @@ async function processChangeState(page, db, jobData) {
await forceUpdate(await commentBox.elementHandle()); await forceUpdate(await commentBox.elementHandle());
} }
// 5. FECHA (Siguiente Acción) // 5. FECHA SIGUIENTE ACCIÓN (Solo si hay fecha futura)
if (dateStr) { if (dateStr) {
const dateInput = page.locator('input[type="date"]').first(); // Bloque TXTFACCION (preferido)
await dateInput.fill(dateStr); const actionBlock = page.locator('encastrables-date-hour-field[label="TXTFACCION"]');
await forceUpdate(await dateInput.elementHandle());
await page.click('body');
}
// 6. HORA (Siguiente Acción) if (await actionBlock.count() > 0) {
if (timeStr) { const dateInput = actionBlock.locator('input[type="date"]');
const secondsValue = timeToMultiValue(timeStr); await dateInput.fill(dateStr);
const timeSelectHandle = await page.$(`xpath=//select[.//option[@value="${secondsValue}"]]`); await forceUpdate(await dateInput.elementHandle());
await page.click('body');
if (timeSelectHandle) { // Hora (Solo si la hemos detectado)
await timeSelectHandle.selectOption(secondsValue); if (timeStr) {
await forceUpdate(timeSelectHandle); const secondsValue = timeToMultiValue(timeStr);
} else { const timeSelect = actionBlock.locator('select.answer-select');
const allSelects = await page.$$('select'); // Intentamos seleccionar, si falla (ej: hora no válida) no rompemos el flujo
if (allSelects.length > 1) { await timeSelect.selectOption(secondsValue).catch(() => console.log(`⚠️ Hora ${timeStr} no válida en desplegable`));
await allSelects[1].selectOption(secondsValue).catch(() => {}); await forceUpdate(await timeSelect.elementHandle());
await forceUpdate(allSelects[1]);
} }
} else {
// Fallback genérico
const genericDateInput = page.locator('input[type="date"]').first();
await genericDateInput.fill(dateStr);
await forceUpdate(await genericDateInput.elementHandle());
} }
} }
// --- NUEVO BLOQUE: FECHA DE CONTACTO (CONDICIONAL) --- // 6. HISTÓRICO / FECHA CONTACTO (AUTOMÁTICO - SIEMPRE HOY)
// Buscamos si existe el campo "Fecha en la que contactó con el cliente" const contactBlock = page.locator('encastrables-date-hour-field[label="TXTFCONTACTO"]');
const contactBlock = page.locator('encastrables-date-hour-field').filter({ hasText: 'Fecha en la que contactó con el cliente' });
if (await contactBlock.count() > 0 && await contactBlock.isVisible()) { if (await contactBlock.count() > 0 && await contactBlock.isVisible()) {
console.log('📞 Detectado campo obligatorio "Fecha contacto cliente". Rellenando...'); console.log('📞 Rellenando "Fecha contacto cliente" con FECHA ACTUAL...');
const now = getCurrentDateTime();
// Rellenar Fecha // Fecha
if (dateStr) { const contactDateInput = contactBlock.locator('input[type="date"]');
const contactDateInput = contactBlock.locator('input[type="date"]'); await contactDateInput.fill(now.dateStr);
await contactDateInput.fill(dateStr); await forceUpdate(await contactDateInput.elementHandle());
await forceUpdate(await contactDateInput.elementHandle());
}
// Rellenar Hora (Este campo es especial, tiene 2 desplegables: Hora y Minutos por separado) // Hora y Minutos
if (timeStr) { const selects = contactBlock.locator('select.answer-select-time');
const [hRaw, mRaw] = timeStr.split(':'); if (await selects.count() >= 2) {
// La web usa "8", "9" para horas de un dígito, no "08" await selects.nth(0).selectOption(now.hourStr).catch(() => {});
const hVal = String(Number(hRaw)); await forceUpdate(await selects.nth(0).elementHandle());
const mVal = mRaw; // Los minutos sí suelen tener el "00"
const selects = contactBlock.locator('select'); await selects.nth(1).selectOption(now.minStr).catch(() => {});
await forceUpdate(await selects.nth(1).elementHandle());
// Asumimos que el primer select es Hora y el segundo Minutos dentro de este bloque
if (await selects.count() >= 1) {
await selects.nth(0).selectOption(hVal).catch(() => {});
await forceUpdate(await selects.nth(0).elementHandle());
}
if (await selects.count() >= 2) {
await selects.nth(1).selectOption(mVal).catch(() => {});
await forceUpdate(await selects.nth(1).elementHandle());
}
} }
} }
// -----------------------------------------------------
await page.waitForTimeout(2000); await page.waitForTimeout(2000);
@ -208,48 +250,34 @@ async function processChangeState(page, db, jobData) {
const btn = page.locator('button.form-container-button-submit'); const btn = page.locator('button.form-container-button-submit');
if (await btn.isDisabled()) { if (await btn.isDisabled()) {
console.log('⛔ Botón deshabilitado. Intentando reactivar...'); console.log('⛔ Botón deshabilitado. Reintentando...');
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()) throw new Error(`IMPOSIBLE GUARDAR: Formulario bloqueado.`);
if (await btn.isDisabled()) {
throw new Error(`IMPOSIBLE GUARDAR: El formulario bloqueado.`);
}
} }
console.log('💾 Click en Guardar...'); console.log('💾 Click en Guardar...');
await btn.click(); await btn.click();
// 8. GESTIÓN DE ALERTAS (POPUP "SÍ") // 8. ALERTAS
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í' });
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) { if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...'); console.log('🚨 ALERTA SMS. Confirmando...');
await confirmBtn.click(); await confirmBtn.click();
await page.waitForTimeout(3000);
try {
await confirmBtn.waitFor({ state: 'hidden', timeout: 5000 });
console.log('✅ Botón "Sí" ha desaparecido.');
} catch(e) {
console.log('⚠️ Forzando segundo click en "Sí"...');
await confirmBtn.click();
}
await page.waitForTimeout(5000);
} }
// 9. VERIFICACIÓN FINAL + FOTO // 9. VERIFICACIÓN
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');
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');
if (successEl) return { type: 'OK', text: successEl.innerText };
if (successEl && successEl.innerText.length > 2) return { type: 'OK', text: successEl.innerText }; if (errorEl) return { type: 'ERROR', text: errorEl.innerText };
if (errorEl && errorEl.innerText.length > 2) return { type: 'ERROR', text: errorEl.innerText };
return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 300) }; return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 300) };
}); });
@ -281,10 +309,8 @@ async function markJobDone(db, job, result) {
jobId, jobId,
ok: true, ok: true,
serviceNumber: job.serviceNumber || '', serviceNumber: job.serviceNumber || '',
reason: job.reasonValue || '', reason: job.nuevoEstado || job.estado || '', // Adaptado al log
comment: job.comment || '', comment: job.observaciones || job.nota || '', // Adaptado al log
date: job.dateStr || '',
time: job.timeStr || '',
...result, ...result,
createdAt: toServerTimestamp() createdAt: toServerTimestamp()
}); });
@ -301,10 +327,6 @@ async function markJobFailed(db, job, err) {
jobId, jobId,
ok: false, ok: false,
serviceNumber: job.serviceNumber || '', serviceNumber: job.serviceNumber || '',
reason: job.reasonValue || '',
comment: job.comment || '',
date: job.dateStr || '',
time: job.timeStr || '',
error: err.message, error: err.message,
createdAt: toServerTimestamp() createdAt: toServerTimestamp()
}); });
@ -314,13 +336,7 @@ async function processJob(db, job) {
console.log(`>>> Procesando Job: ${job.id}`); console.log(`>>> Procesando Job: ${job.id}`);
try { try {
await withBrowser(async (page) => { await withBrowser(async (page) => {
const res = await processChangeState(page, db, { const res = await processChangeState(page, db, job); // Pasamos todo el objeto 'job'
serviceNumber: job.serviceNumber,
reasonValue: job.reasonValue,
comment: job.comment,
dateStr: job.dateStr,
timeStr: job.timeStr
});
await markJobDone(db, job, res); await markJobDone(db, job, res);
console.log(`✅ Job ${job.id} Completado.`); console.log(`✅ Job ${job.id} Completado.`);
}); });
@ -340,7 +356,7 @@ function startWorker(db) {
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 (V7 - CON DEBUG) LISTO.'); console.log('🚀 Worker Multiasistencia (V9 - ADAPTADOR APP) LISTO.');
} }
const db = initFirebase(); const db = initFirebase();