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';
const { chromium } = require('playwright');
@ -28,6 +28,41 @@ function timeToMultiValue(timeStr) {
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 ---
function initFirebase() {
if (!process.env.FIREBASE_PRIVATE_KEY) throw new Error('Missing FIREBASE_PRIVATE_KEY');
@ -95,7 +130,32 @@ async function forceUpdate(elementHandle) {
// --- LÓGICA PRINCIPAL ---
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
await loginMulti(page, db);
@ -109,27 +169,20 @@ async function processChangeState(page, db, jobData) {
await page.waitForTimeout(1500);
console.log('📝 Rellenando formulario...');
// 3. MOTIVO (CON DIAGNÓSTICO DE ERROR)
// 3. MOTIVO
const reasonSel = page.locator('select.answer-select').first();
const targetValue = String(reasonValue);
// --- BLOQUE DE DIAGNÓSTICO ---
// Diagnóstico rápido
const availableOptions = await reasonSel.evaluate((select) => {
return Array.from(select.options).map(o => ({
value: o.value,
text: o.innerText.trim()
}));
return Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() }));
});
console.log(`🔍 Intentando seleccionar motivo ID: "${targetValue}"`);
const optionExists = availableOptions.find(o => o.value === targetValue);
if (!optionExists) {
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 está disponible en este estado. Opciones válidas: ${validList}`);
throw new Error(`MOTIVO INVÁLIDO: El ID "${targetValue}" no existe. Opciones: ${validList}`);
}
// -----------------------------
await reasonSel.selectOption(targetValue);
await forceUpdate(await reasonSel.elementHandle());
@ -141,66 +194,55 @@ async function processChangeState(page, db, jobData) {
await forceUpdate(await commentBox.elementHandle());
}
// 5. FECHA (Siguiente Acción)
// 5. FECHA SIGUIENTE ACCIÓN (Solo si hay fecha futura)
if (dateStr) {
const dateInput = page.locator('input[type="date"]').first();
await dateInput.fill(dateStr);
await forceUpdate(await dateInput.elementHandle());
await page.click('body');
}
// Bloque TXTFACCION (preferido)
const actionBlock = page.locator('encastrables-date-hour-field[label="TXTFACCION"]');
// 6. HORA (Siguiente Acción)
if (timeStr) {
const secondsValue = timeToMultiValue(timeStr);
const timeSelectHandle = await page.$(`xpath=//select[.//option[@value="${secondsValue}"]]`);
if (await actionBlock.count() > 0) {
const dateInput = actionBlock.locator('input[type="date"]');
await dateInput.fill(dateStr);
await forceUpdate(await dateInput.elementHandle());
await page.click('body');
if (timeSelectHandle) {
await timeSelectHandle.selectOption(secondsValue);
await forceUpdate(timeSelectHandle);
} else {
const allSelects = await page.$$('select');
if (allSelects.length > 1) {
await allSelects[1].selectOption(secondsValue).catch(() => {});
await forceUpdate(allSelects[1]);
// Hora (Solo si la hemos detectado)
if (timeStr) {
const secondsValue = timeToMultiValue(timeStr);
const timeSelect = actionBlock.locator('select.answer-select');
// Intentamos seleccionar, si falla (ej: hora no válida) no rompemos el flujo
await timeSelect.selectOption(secondsValue).catch(() => console.log(`⚠️ Hora ${timeStr} no válida en desplegable`));
await forceUpdate(await timeSelect.elementHandle());
}
} 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) ---
// Buscamos si existe el campo "Fecha en la que contactó con el cliente"
const contactBlock = page.locator('encastrables-date-hour-field').filter({ hasText: 'Fecha en la que contactó con el cliente' });
// 6. HISTÓRICO / FECHA CONTACTO (AUTOMÁTICO - SIEMPRE HOY)
const contactBlock = page.locator('encastrables-date-hour-field[label="TXTFCONTACTO"]');
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
if (dateStr) {
const contactDateInput = contactBlock.locator('input[type="date"]');
await contactDateInput.fill(dateStr);
await forceUpdate(await contactDateInput.elementHandle());
}
// Fecha
const contactDateInput = contactBlock.locator('input[type="date"]');
await contactDateInput.fill(now.dateStr);
await forceUpdate(await contactDateInput.elementHandle());
// Rellenar Hora (Este campo es especial, tiene 2 desplegables: Hora y Minutos por separado)
if (timeStr) {
const [hRaw, mRaw] = timeStr.split(':');
// La web usa "8", "9" para horas de un dígito, no "08"
const hVal = String(Number(hRaw));
const mVal = mRaw; // Los minutos sí suelen tener el "00"
// Hora y Minutos
const selects = contactBlock.locator('select.answer-select-time');
if (await selects.count() >= 2) {
await selects.nth(0).selectOption(now.hourStr).catch(() => {});
await forceUpdate(await selects.nth(0).elementHandle());
const selects = contactBlock.locator('select');
// 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 selects.nth(1).selectOption(now.minStr).catch(() => {});
await forceUpdate(await selects.nth(1).elementHandle());
}
}
// -----------------------------------------------------
await page.waitForTimeout(2000);
@ -208,48 +250,34 @@ async function processChangeState(page, db, jobData) {
const btn = page.locator('button.form-container-button-submit');
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.keyboard.press('Tab');
await page.waitForTimeout(1000);
if (await btn.isDisabled()) {
throw new Error(`IMPOSIBLE GUARDAR: El formulario bloqueado.`);
}
if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Formulario bloqueado.`);
}
console.log('💾 Click en Guardar...');
await btn.click();
// 8. GESTIÓN DE ALERTAS (POPUP "SÍ")
// 8. ALERTAS
await page.waitForTimeout(3000);
const confirmBtn = page.locator('button.form-container-button-submit-toast').filter({ hasText: 'Sí' });
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
console.log('🚨 ALERTA SMS DETECTADA. Pulsando "Sí"...');
console.log('🚨 ALERTA SMS. Confirmando...');
await confirmBtn.click();
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);
await page.waitForTimeout(3000);
}
// 9. VERIFICACIÓN FINAL + FOTO
// 9. VERIFICACIÓN
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
const screenshotBase64 = screenshotBuffer.toString('base64');
const finalResult = await page.evaluate(() => {
const successEl = document.querySelector('.form-container-success') || document.querySelector('.bg-success');
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
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 (successEl) return { type: 'OK', text: successEl.innerText };
if (errorEl) return { type: 'ERROR', text: errorEl.innerText };
return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 300) };
});
@ -281,10 +309,8 @@ async function markJobDone(db, job, result) {
jobId,
ok: true,
serviceNumber: job.serviceNumber || '',
reason: job.reasonValue || '',
comment: job.comment || '',
date: job.dateStr || '',
time: job.timeStr || '',
reason: job.nuevoEstado || job.estado || '', // Adaptado al log
comment: job.observaciones || job.nota || '', // Adaptado al log
...result,
createdAt: toServerTimestamp()
});
@ -301,10 +327,6 @@ async function markJobFailed(db, job, err) {
jobId,
ok: false,
serviceNumber: job.serviceNumber || '',
reason: job.reasonValue || '',
comment: job.comment || '',
date: job.dateStr || '',
time: job.timeStr || '',
error: err.message,
createdAt: toServerTimestamp()
});
@ -314,13 +336,7 @@ async function processJob(db, job) {
console.log(`>>> Procesando Job: ${job.id}`);
try {
await withBrowser(async (page) => {
const res = await processChangeState(page, db, {
serviceNumber: job.serviceNumber,
reasonValue: job.reasonValue,
comment: job.comment,
dateStr: job.dateStr,
timeStr: job.timeStr
});
const res = await processChangeState(page, db, job); // Pasamos todo el objeto 'job'
await markJobDone(db, job, res);
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(); } });
});
console.log('🚀 Worker Multiasistencia (V7 - CON DEBUG) LISTO.');
console.log('🚀 Worker Multiasistencia (V9 - ADAPTADOR APP) LISTO.');
}
const db = initFirebase();