// worker-multi-estado.js (V14 - FINAL: SINTAXIS + IDs + ANTI-DUPLICADOS + REDONDEO) 'use strict'; const { chromium } = require('playwright'); const admin = require('firebase-admin'); // --- CONFIGURACIÓN --- const CONFIG = { QUEUE_COLLECTION: 'multiasistencia_cambios_estado', RESULT_COLLECTION: 'multiasistencia_cambios_estado_log', MULTI_LOGIN: "https://web.multiasistencia.com/w3multi/acceso.php", MULTI_ACTION_BASE: "https://web.multiasistencia.com/w3multi/fechaccion.php", NAV_TIMEOUT: 60000, RESCAN_SECONDS: 60, DUPLICATE_TIME_MS: 3 * 60 * 1000 // 3 Minutos de memoria para ignorar duplicados }; // --- MEMORIA ANTI-DUPLICADOS --- const processedServicesCache = new Map(); // --- DICCIONARIO DE TRADUCCIÓN CORREGIDO --- const STATE_TRANSLATOR = { "15": "2", // App: 15 -> Web: 2 (Visita) "0": "34", // App: 0 -> Web: 34 (Rechazado) "1": "1", // App: 1 -> Web: 1 (Contacto) "99": "3", // App: 99 -> Web: 3 (Presupuesto) "60": "37" // App: 60 -> Web: 37 (Pendiente Instrucciones [60]) - CORREGIDO }; // --- UTILS --- const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function toServerTimestamp() { return admin.firestore.FieldValue.serverTimestamp(); } function timeToMultiValue(timeStr) { if (!timeStr) return ""; const [h, m] = timeStr.split(':').map(Number); return String((h * 3600) + (m * 60)); } // Redondeo inteligente (16:45 -> 17:00) function roundToNearest30(timeStr) { if (!timeStr) return null; let [h, m] = timeStr.split(':').map(Number); if (m < 15) { m = 0; } else if (m < 45) { m = 30; } else { m = 0; h = (h + 1) % 24; } return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}`; } function extractTimeFromText(text) { if (!text) return null; const match = text.match(/(\d{1,2}:\d{2})/); return match ? match[1] : null; } function normalizeDate(dateStr) { if (!dateStr) return ""; if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) return dateStr; if (dateStr.includes('/')) { const [day, month, year] = dateStr.split('/'); return `${year}-${month}-${day}`; } return dateStr; } 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'); return { dateStr: `${year}-${month}-${day}`, hourStr: String(now.getHours()), minStr: String(now.getMinutes()).padStart(2, '0') }; } // --- FIREBASE INIT --- function initFirebase() { if (!process.env.FIREBASE_PRIVATE_KEY) throw new Error('Missing FIREBASE_PRIVATE_KEY'); if (!admin.apps.length) { admin.initializeApp({ credential: admin.credential.cert({ projectId: process.env.FIREBASE_PROJECT_ID, clientEmail: process.env.FIREBASE_CLIENT_EMAIL, privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'), }), }); } return admin.firestore(); } // --- LOGIN --- async function loginMulti(page, db) { const doc = await db.collection("providerCredentials").doc("multiasistencia").get(); const { user, pass } = doc.data() || {}; if (!user) throw new Error("Faltan credenciales."); console.log('🔐 Login...'); await page.goto(CONFIG.MULTI_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' }); const userFilled = await page.evaluate((u) => { const el = document.querySelector('input[name="usuario"]'); if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; } return false; }, user); if (!userFilled) await page.fill('input[name="usuario"]', user); await page.fill('input[type="password"]', pass); await page.click('input[type="submit"]'); await page.waitForTimeout(4000); } // --- PLAYWRIGHT SETUP --- async function withBrowser(fn) { const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); const context = await browser.newContext(); const page = await context.newPage(); try { return await fn(page); } finally { await browser.close().catch(() => {}); } } async function forceUpdate(elementHandle) { if (elementHandle) { await elementHandle.evaluate(el => { el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); el.dispatchEvent(new Event('blur', { bubbles: true })); }); } } // --- LÓGICA PRINCIPAL --- async function processChangeState(page, db, jobData) { const serviceNumber = jobData.serviceNumber; // MAPPING let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado; const comment = jobData.comment || jobData.observaciones || jobData.nota; const dateStr = normalizeDate(jobData.dateStr || jobData.fecha); // HORA: Extraer y Redondear let rawTime = jobData.timeStr || extractTimeFromText(comment); let timeStr = roundToNearest30(rawTime); // ID TRADUCIDO const reasonValue = STATE_TRANSLATOR[rawReason] || rawReason; console.log(`🔧 PROCESANDO: App Estado "${rawReason}" -> Web ID "${reasonValue}"`); console.log(`⏰ HORA: Original "${rawTime}" -> Redondeada "${timeStr}"`); if (!reasonValue || reasonValue === 'undefined') throw new Error("DATOS FALTANTES: No hay estado válido."); // NAVEGACIÓN await loginMulti(page, db); 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(1000); // SELECCIONAR MOTIVO const reasonSel = page.locator('select.answer-select').first(); const options = await reasonSel.evaluate(s => Array.from(s.options).map(o => o.value)); if (!options.includes(String(reasonValue))) { throw new Error(`MOTIVO INVÁLIDO: El ID "${reasonValue}" no existe en el desplegable.`); } await reasonSel.selectOption(String(reasonValue)); await forceUpdate(await reasonSel.elementHandle()); // COMENTARIO if (comment) { const commentBox = page.locator('textarea[formcontrolname="comment"]'); await commentBox.fill(comment); await forceUpdate(await commentBox.elementHandle()); } // FECHA SIGUIENTE ACCIÓN (Solo si existe fecha y es válida) if (dateStr) { 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'); if (timeStr) { const seconds = timeToMultiValue(timeStr); const timeSel = actionBlock.locator('select.answer-select'); await timeSel.selectOption(seconds).catch(()=>{ console.log('⚠️ No se pudo poner la hora exacta') }); await forceUpdate(await timeSel.elementHandle()); } } else { // Fallback const genDate = page.locator('input[type="date"]').first(); await genDate.fill(dateStr); await forceUpdate(await genDate.elementHandle()); } } // 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 contacto (Auto Hoy)...'); const now = getCurrentDateTime(); const cDate = contactBlock.locator('input[type="date"]'); await cDate.fill(now.dateStr); await forceUpdate(await cDate.elementHandle()); 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()); } } await page.waitForTimeout(2000); // GUARDAR (CON INTELIGENCIA) const btn = page.locator('button.form-container-button-submit'); if (await btn.isDisabled()) { console.log('⛔ Botón bloqueado. Reintentando inputs...'); 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 sigue bloqueado.`); } console.log('💾 Guardando...'); await btn.click(); // 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()) { await confirmBtn.click(); await page.waitForTimeout(3000); } // RESULTADO const screenshot = (await page.screenshot({ fullPage: true, quality: 40, type: 'jpeg' })).toString('base64'); const finalResult = await page.evaluate(() => { const successEl = document.querySelector('.form-container-success, .bg-success'); const errorEl = document.querySelector('.form-container-error, .bg-danger'); if (successEl) return { type: 'OK', text: successEl.innerText.trim() }; if (errorEl) return { type: 'ERROR', text: errorEl.innerText.trim() }; const body = document.body.innerText; if (body.includes('correctamente') || body.includes('guardado')) return { type: 'OK', text: "Guardado correctamente." }; return { type: 'UNKNOWN', text: "No se detectó mensaje explícito." }; }); console.log(`🏁 FINAL: ${finalResult.type} - ${finalResult.text}`); return { success: finalResult.type === 'OK', message: finalResult.text, screenshot }; } // --- GESTIÓN DE COLAS Y TRANSACCIONES --- async function claimJobById(db, jobId) { const ref = db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId); return await db.runTransaction(async (tx) => { const snap = await tx.get(ref); if (!snap.exists || snap.data().status !== 'PENDING') return null; tx.set(ref, { status: 'RUNNING', claimedAt: toServerTimestamp() }, { merge: true }); return { id: jobId, ...snap.data() }; }); } async function markJobDone(db, job, result, status = 'DONE') { await db.collection(CONFIG.QUEUE_COLLECTION).doc(job.id).set({ status, result }, { merge: true }); await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId: job.id, serviceNumber: job.serviceNumber || '', reason: job.nuevoEstado || '', comment: job.observaciones || '', ...result, createdAt: toServerTimestamp() }); } async function markJobFailed(db, job, err) { await db.collection(CONFIG.QUEUE_COLLECTION).doc(job.id).set({ status: 'FAILED', error: { message: err.message } }, { merge: true }); await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId: job.id, ok: false, serviceNumber: job.serviceNumber || '', error: err.message, createdAt: toServerTimestamp() }); } async function processJob(db, job) { if (!job) return; try { await withBrowser(async (page) => { const res = await processChangeState(page, db, job); await markJobDone(db, job, res); console.log(`✅ Job ${job.id} Completado.`); }); } catch (err) { console.error(`❌ Job ${job.id} Falló:`, err.message); await markJobFailed(db, job, err); } } // --- LOOP PRINCIPAL (CON ANTI-DUPLICADOS) --- function startWorker(db) { const queue = []; const processing = new Set(); const run = async () => { while(queue.length) { const jobId = queue.shift(); if (processing.has(jobId)) continue; processing.add(jobId); try { const jobData = await claimJobById(db, jobId); if (!jobData) { processing.delete(jobId); continue; } // FILTRO MEMORIA (3 MINUTOS) const serviceNum = jobData.serviceNumber; const lastTime = processedServicesCache.get(serviceNum); const now = Date.now(); if (lastTime && (now - lastTime < CONFIG.DUPLICATE_TIME_MS)) { console.log(`🚫 DUPLICADO: Servicio ${serviceNum} reciente. Ignorando.`); await markJobDone(db, jobData, { success: true, message: "Ignorado por duplicado" }, 'SKIPPED'); continue; } processedServicesCache.set(serviceNum, now); // Actualizar memoria console.log(`>>> Procesando Job: ${jobId}`); await processJob(db, jobData); } catch (err) { console.error(`Error loop: ${err.message}`); } finally { processing.delete(jobId); } } }; db.collection(CONFIG.QUEUE_COLLECTION).where('status', '==', 'PENDING').onSnapshot(s => { s.docChanges().forEach(c => { if(c.type === 'added' && !queue.includes(c.doc.id)) { queue.push(c.doc.id); run(); } }); }); console.log('🚀 Worker Multiasistencia (V14 - MASTER) LISTO.'); } const db = initFirebase(); startWorker(db);