From 677012a22a55aff2bc359c005c61e51efde08a0a Mon Sep 17 00:00:00 2001 From: marsalva Date: Sat, 10 Jan 2026 15:35:27 +0000 Subject: [PATCH] Actualizar worker-multi-estado.js --- worker-multi-estado.js | 107 ++++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 61 deletions(-) diff --git a/worker-multi-estado.js b/worker-multi-estado.js index a34fce8..5b88422 100644 --- a/worker-multi-estado.js +++ b/worker-multi-estado.js @@ -1,4 +1,4 @@ -// worker-multi-estado.js (V9 - ADAPTADOR PARA TU APP + FECHA CONTACTO AUTO) +// worker-multi-estado.js (V10 - TRADUCTOR AUTOMÁTICO DE ESTADOS) 'use strict'; const { chromium } = require('playwright'); @@ -14,6 +14,15 @@ const CONFIG = { RESCAN_SECONDS: 60 }; +// --- DICCIONARIO DE TRADUCCIÓN (APP -> WEB) --- +// La izquierda es lo que envía tu App. La derecha es el ID del Select de la web. +const STATE_TRANSLATOR = { + "15": "2", // App envía "15" -> Robot marca "2" (Visita al Cliente [15]) + "0": "34", // App envía "0" -> Robot marca "34" (Rechazado [0]) + "1": "1", // App envía "1" -> Robot marca "1" (Contacto [1]) + "99": "3" // App envía "99" -> Robot marca "3" (Entrega presupuesto [99]) - (Ajustar según necesidad) +}; + // --- UTILS --- const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -24,24 +33,20 @@ function toServerTimestamp() { function timeToMultiValue(timeStr) { if (!timeStr) return ""; const [h, m] = timeStr.split(':').map(Number); - // Para el desplegable principal (segundos desde medianoche) return String((h * 3600) + (m * 60)); } -// Helper: Extraer hora de un texto (Ej: "cita a las 13:00") -> "13:00" +// Extraer hora del 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 +// Normalizar fecha (DD/MM/YYYY -> 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}`; @@ -49,7 +54,7 @@ function normalizeDate(dateStr) { return dateStr; } -// Obtener fecha y hora actuales desglosadas (Sistema) +// Fecha/Hora actual del sistema function getCurrentDateTime() { const now = new Date(); const year = now.getFullYear(); @@ -130,115 +135,102 @@ async function forceUpdate(elementHandle) { // --- LÓGICA PRINCIPAL --- async function processChangeState(page, db, 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 + // 1. OBTENER DATOS CRUDOS DE LA APP + let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado; // Viene "15" 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}`); + // 2. TRADUCCIÓN MÁGICA (AQUÍ ESTÁ EL FIX) + // Si rawReason es "15", reasonValue se convierte en "2". Si no está en la lista, se queda igual. + const reasonValue = STATE_TRANSLATOR[rawReason] || rawReason; + + console.log(`🔧 DATOS: App envía "${rawReason}" -> Robot traduce a ID "${reasonValue}"`); + console.log(`📅 FECHA: ${dateStr} | ⏰ HORA: ${timeStr}`); - // VALIDACIÓN if (!reasonValue || reasonValue === 'undefined') { - throw new Error("DATOS FALTANTES: No se encontró 'nuevoEstado' ni 'reasonValue' en Firebase."); + throw new Error("DATOS FALTANTES: No hay estado válido para procesar."); } - // ----------------------------------------------------------- - - // 1. LOGIN + // 3. LOGIN await loginMulti(page, db); - // 2. IR AL SERVICIO + // 4. NAVEGACIÓN const targetUrl = `${CONFIG.MULTI_ACTION_BASE}?reparacion=${serviceNumber}&modo=0&navid=%2Fw3multi%2Ffrepasos_new.php%FDGET%FDrefresh%3D1%FC`; console.log(`📂 Abriendo servicio ${serviceNumber}...`); await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 }); await page.waitForSelector('select.answer-select', { timeout: 20000 }); await page.waitForTimeout(1500); - console.log('📝 Rellenando formulario...'); - // 3. MOTIVO + // 5. SELECCIONAR MOTIVO const reasonSel = page.locator('select.answer-select').first(); const targetValue = String(reasonValue); - // Diagnóstico rápido + // Verificación de seguridad const availableOptions = await reasonSel.evaluate((select) => { return Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() })); }); + const optionExists = availableOptions.find(o => o.value === targetValue); if (!optionExists) { + // Log detallado para depuración futura + console.error(`❌ El ID traducido "${targetValue}" (original: "${rawReason}") no existe.`); const validList = availableOptions.map(o => `[${o.value}: ${o.text}]`).join(', '); - throw new Error(`MOTIVO INVÁLIDO: El ID "${targetValue}" no existe. Opciones: ${validList}`); + throw new Error(`MOTIVO INVÁLIDO: Intenté seleccionar ID "${targetValue}" pero no está. Opciones: ${validList}`); } await reasonSel.selectOption(targetValue); await forceUpdate(await reasonSel.elementHandle()); - // 4. COMENTARIO + // 6. COMENTARIO if (comment) { const commentBox = page.locator('textarea[formcontrolname="comment"]'); await commentBox.fill(comment); await forceUpdate(await commentBox.elementHandle()); } - // 5. FECHA SIGUIENTE ACCIÓN (Solo si hay fecha futura) + // 7. FECHA SIGUIENTE ACCIÓN (SI PROCEDE) if (dateStr) { - // Bloque TXTFACCION (preferido) const actionBlock = page.locator('encastrables-date-hour-field[label="TXTFACCION"]'); - 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'); - // 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 timeSelect.selectOption(secondsValue).catch(() => {}); await forceUpdate(await timeSelect.elementHandle()); } } else { - // Fallback genérico + // Fallback const genericDateInput = page.locator('input[type="date"]').first(); await genericDateInput.fill(dateStr); await forceUpdate(await genericDateInput.elementHandle()); } } - // 6. HISTÓRICO / FECHA CONTACTO (AUTOMÁTICO - SIEMPRE HOY) + // 8. FECHA CONTACTO (AUTOMÁTICA HOY) const contactBlock = page.locator('encastrables-date-hour-field[label="TXTFCONTACTO"]'); - if (await contactBlock.count() > 0 && await contactBlock.isVisible()) { - console.log('📞 Rellenando "Fecha contacto cliente" con FECHA ACTUAL...'); + console.log('📞 Rellenando contacto con FECHA ACTUAL...'); const now = getCurrentDateTime(); - // Fecha const contactDateInput = contactBlock.locator('input[type="date"]'); await contactDateInput.fill(now.dateStr); await forceUpdate(await contactDateInput.elementHandle()); - // 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()); - await selects.nth(1).selectOption(now.minStr).catch(() => {}); await forceUpdate(await selects.nth(1).elementHandle()); } @@ -246,30 +238,27 @@ async function processChangeState(page, db, jobData) { await page.waitForTimeout(2000); - // 7. GUARDAR + // 9. GUARDAR const btn = page.locator('button.form-container-button-submit'); - if (await btn.isDisabled()) { - 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: Formulario bloqueado.`); + if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Bloqueado.`); } - console.log('💾 Click en Guardar...'); + console.log('💾 Guardando...'); await btn.click(); - // 8. ALERTAS + // 10. 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. Confirmando...'); await confirmBtn.click(); await page.waitForTimeout(3000); } - // 9. VERIFICACIÓN + // 11. RESULTADO const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' }); const screenshotBase64 = screenshotBuffer.toString('base64'); @@ -281,7 +270,7 @@ async function processChangeState(page, db, jobData) { return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 300) }; }); - console.log(`🏁 RESULTADO: [${finalResult.type}]`); + console.log(`🏁 FINAL: ${finalResult.type}`); return { success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')), @@ -304,13 +293,12 @@ async function claimJobById(db, jobId) { async function markJobDone(db, job, result) { const jobId = job.id; await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'DONE', result }, { merge: true }); - await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: true, serviceNumber: job.serviceNumber || '', - reason: job.nuevoEstado || job.estado || '', // Adaptado al log - comment: job.observaciones || job.nota || '', // Adaptado al log + reason: job.nuevoEstado || job.estado || '', + comment: job.observaciones || job.nota || '', ...result, createdAt: toServerTimestamp() }); @@ -322,7 +310,6 @@ async function markJobFailed(db, job, err) { status: 'FAILED', error: { message: err.message } }, { merge: true }); - await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: false, @@ -336,7 +323,7 @@ async function processJob(db, job) { console.log(`>>> Procesando Job: ${job.id}`); try { await withBrowser(async (page) => { - const res = await processChangeState(page, db, job); // Pasamos todo el objeto 'job' + const res = await processChangeState(page, db, job); await markJobDone(db, job, res); console.log(`✅ Job ${job.id} Completado.`); }); @@ -351,12 +338,10 @@ function startWorker(db) { const run = async () => { while(queue.length) { await processJob(db, await claimJobById(db, queue.shift())); } }; - db.collection(CONFIG.QUEUE_COLLECTION).where('status', '==', 'PENDING').onSnapshot(s => { s.docChanges().forEach(c => { if(c.type==='added') { queue.push(c.doc.id); run(); } }); }); - - console.log('🚀 Worker Multiasistencia (V9 - ADAPTADOR APP) LISTO.'); + console.log('🚀 Worker Multiasistencia (V10 - TRADUCTOR) LISTO.'); } const db = initFirebase();