Actualizar worker-multi-estado.js

This commit is contained in:
marsalva 2026-01-10 16:19:43 +00:00
parent 2cc2159687
commit 6368ac14be
1 changed files with 112 additions and 115 deletions

View File

@ -1,4 +1,4 @@
// worker-multi-estado.js (V11 - FINAL: TRADUCTOR + ANTI-DOBLE EJECUCIÓN)
// worker-multi-estado.js (V13 - REDONDEO DE HORA + ANTI-BLOQUEO)
'use strict';
const { chromium } = require('playwright');
@ -14,27 +14,44 @@ const CONFIG = {
RESCAN_SECONDS: 60
};
// --- DICCIONARIO DE TRADUCCIÓN (APP -> WEB) ---
// --- DICCIONARIO DE TRADUCCIÓN ---
const STATE_TRANSLATOR = {
"15": "2", // App envía "15" -> Robot marca "2" (Visita al Cliente)
"0": "34", // Rechazado
"1": "1", // Contacto
"99": "3" // Entrega presupuesto (ajustar si es necesario)
"15": "2", // App 15 -> Web 2 (Visita)
"0": "34", // Web 34 (Rechazado)
"1": "1", // Web 1 (Contacto)
"99": "3" // Web 3 (Presupuesto)
};
// --- UTILS ---
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function toServerTimestamp() { return admin.firestore.FieldValue.serverTimestamp(); }
function toServerTimestamp() {
return admin.firestore.FieldValue.serverTimestamp();
}
// Convertir HH:MM a segundos (para Multiasistencia)
function timeToMultiValue(timeStr) {
if (!timeStr) return "";
const [h, m] = timeStr.split(':').map(Number);
return String((h * 3600) + (m * 60));
}
// NUEVO: Redondear hora a intervalos de 30 min (ej: 16:45 -> 17:00, 16:10 -> 16: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; // Pasar a la siguiente hora
}
const hStr = String(h).padStart(2, '0');
const mStr = String(m).padStart(2, '0');
return `${hStr}:${mStr}`;
}
function extractTimeFromText(text) {
if (!text) return null;
const match = text.match(/(\d{1,2}:\d{2})/);
@ -80,17 +97,15 @@ function initFirebase() {
// --- LOGIN ---
async function loginMulti(page, db) {
let user = "", pass = "";
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
const { user, pass } = doc.data() || {};
if (!user) throw new Error("Faltan credenciales.");
console.log('🔐 Login en Multiasistencia...');
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"]') || document.querySelector('input[type="text"]');
const el = document.querySelector('input[name="usuario"]');
if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
return false;
}, user);
@ -101,7 +116,7 @@ async function loginMulti(page, db) {
await page.waitForTimeout(4000);
}
// --- PLAYWRIGHT SETUP ---
// --- HELPERS BROWSER ---
async function withBrowser(fn) {
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
const context = await browser.newContext();
@ -123,137 +138,154 @@ async function forceUpdate(elementHandle) {
async function processChangeState(page, db, jobData) {
const serviceNumber = jobData.serviceNumber;
// MAPPING
// 1. MAPPING DE DATOS
let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado;
const comment = jobData.comment || jobData.observaciones || jobData.nota;
const rawDate = jobData.dateStr || jobData.fecha;
const dateStr = normalizeDate(rawDate);
let timeStr = jobData.timeStr || extractTimeFromText(comment);
const dateStr = normalizeDate(jobData.dateStr || jobData.fecha);
// TRADUCCIÓN
// Extracción y Redondeo de Hora
let rawTime = jobData.timeStr || extractTimeFromText(comment);
let timeStr = roundToNearest30(rawTime); // <--- AQUÍ ESTÁ LA MAGIA (16:45 -> 17:00)
const reasonValue = STATE_TRANSLATOR[rawReason] || rawReason;
console.log(`🔧 DATOS: App envía "${rawReason}" -> Traducido a ID "${reasonValue}"`);
console.log(`🔧 DATOS: ID:${reasonValue} | Fecha:${dateStr} | Hora:${rawTime} -> Redondeada:${timeStr}`);
if (!reasonValue || reasonValue === 'undefined') throw new Error("DATOS FALTANTES: No hay estado válido.");
// NAVEGACIÓN
// 2. 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(1500);
await page.waitForTimeout(1000);
// MOTIVO
// 3. SELECCIONAR MOTIVO
const reasonSel = page.locator('select.answer-select').first();
const targetValue = String(reasonValue);
const availableOptions = await reasonSel.evaluate(s => Array.from(s.options).map(o => o.value));
// Check de seguridad
const availableOptions = await reasonSel.evaluate((select) =>
Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() }))
);
if (!availableOptions.find(o => o.value === targetValue)) {
const validList = availableOptions.map(o => `[${o.value}: ${o.text}]`).join(', ');
throw new Error(`MOTIVO INVÁLIDO: ID "${targetValue}" no existe. Opciones: ${validList}`);
if (!availableOptions.includes(String(reasonValue))) {
// Fallback inteligente: Si enviamos "2" pero no está, intentamos buscar texto
throw new Error(`MOTIVO INVÁLIDO: ID "${reasonValue}" no está disponible.`);
}
await reasonSel.selectOption(targetValue);
await reasonSel.selectOption(String(reasonValue));
await forceUpdate(await reasonSel.elementHandle());
// COMENTARIO
// 4. COMENTARIO
if (comment) {
const commentBox = page.locator('textarea[formcontrolname="comment"]');
await commentBox.fill(comment);
await forceUpdate(await commentBox.elementHandle());
}
// FECHA SIGUIENTE ACCIÓN
// 5. FECHA SIGUIENTE ACCIÓN (CON HORA REDONDEADA)
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');
await page.click('body');
if (timeStr) {
const secondsValue = timeToMultiValue(timeStr);
const timeSelect = actionBlock.locator('select.answer-select');
await timeSelect.selectOption(secondsValue).catch(() => {});
await forceUpdate(await timeSelect.elementHandle());
const seconds = timeToMultiValue(timeStr);
const timeSel = actionBlock.locator('select.answer-select');
// Intento de selección seguro
try {
await timeSel.selectOption(seconds);
await forceUpdate(await timeSel.elementHandle());
console.log(`⏰ Hora cita seleccionada: ${timeStr}`);
} catch(e) {
console.log(`⚠️ No se pudo seleccionar la hora ${timeStr}. Posiblemente no exista en el combo.`);
}
}
} else {
const genericDateInput = page.locator('input[type="date"]').first();
await genericDateInput.fill(dateStr);
await forceUpdate(await genericDateInput.elementHandle());
// Fallback genérico
const genDate = page.locator('input[type="date"]').first();
await genDate.fill(dateStr);
await forceUpdate(await genDate.elementHandle());
}
}
// FECHA CONTACTO (AUTOMÁTICA)
// 6. FECHA CONTACTO (AUTOMÁTICA)
const contactBlock = page.locator('encastrables-date-hour-field[label="TXTFCONTACTO"]');
if (await contactBlock.count() > 0 && await contactBlock.isVisible()) {
console.log('📞 Rellenando contacto con FECHA ACTUAL...');
const now = getCurrentDateTime();
const contactDateInput = contactBlock.locator('input[type="date"]');
await contactDateInput.fill(now.dateStr);
await forceUpdate(await contactDateInput.elementHandle());
console.log('📞 Rellenando contacto...');
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(() => {});
// Hora
await selects.nth(0).selectOption(now.hourStr).catch(()=>{});
await forceUpdate(await selects.nth(0).elementHandle());
await selects.nth(1).selectOption(now.minStr).catch(() => {});
// Minutos
await selects.nth(1).selectOption(now.minStr).catch(()=>{});
await forceUpdate(await selects.nth(1).elementHandle());
}
}
await page.waitForTimeout(2000);
// GUARDAR
// 7. GUARDAR (CON INTELIGENCIA DE REINTENTO)
const btn = page.locator('button.form-container-button-submit');
if (await btn.isDisabled()) {
console.log('⛔ Botón bloqueado. Reintentando activación...');
// Truco: Click en comentario -> Tab -> Click fuera
await page.click('textarea[formcontrolname="comment"]');
await page.keyboard.press('Tab');
await page.waitForTimeout(1000);
if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Bloqueado.`);
await page.click('body');
await page.waitForTimeout(1500);
if (await btn.isDisabled()) {
throw new Error(`IMPOSIBLE GUARDAR: El formulario sigue bloqueado (probablemente falta un campo obligatorio o la hora no es válida).`);
}
}
console.log('💾 Guardando...');
await btn.click();
// ALERTAS SMS
// 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()) {
await confirmBtn.click();
await page.waitForTimeout(3000);
await page.waitForTimeout(3000);
}
// RESULTADO
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
const screenshotBase64 = screenshotBuffer.toString('base64');
// 9. 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') || document.querySelector('.bg-success');
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
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) };
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 bodyText = document.body.innerText;
if (bodyText.includes('correctamente') || bodyText.includes('guardado')) return { type: 'OK', text: "Guardado correctamente." };
return { type: 'UNKNOWN', text: "No se detectó mensaje." };
});
console.log(`🏁 FINAL: ${finalResult.type}`);
return { success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')), message: finalResult.text, screenshot: screenshotBase64 };
console.log(`🏁 FINAL: ${finalResult.type} - ${finalResult.text}`);
return { success: finalResult.type === 'OK', message: finalResult.text, screenshot };
}
// --- GESTIÓN DE COLAS Y TRANSACCIONES ---
// --- GESTIÓN DE COLAS ---
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);
// VALIDACIÓN CRÍTICA: Si ya no es PENDING, devolvemos null
if (!snap.exists || snap.data().status !== 'PENDING') return null;
tx.set(ref, { status: 'RUNNING', claimedAt: toServerTimestamp() }, { merge: true });
return { id: jobId, ...snap.data() };
});
@ -263,13 +295,10 @@ 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 || '',
comment: job.observaciones || job.nota || '',
...result,
createdAt: toServerTimestamp()
jobId, ok: true, serviceNumber: job.serviceNumber || '',
reason: job.nuevoEstado || '',
comment: job.observaciones || '',
...result, createdAt: toServerTimestamp()
});
}
@ -282,12 +311,7 @@ async function markJobFailed(db, job, err) {
}
async function processJob(db, job) {
// CRÍTICO: Si el trabajo llegó nulo (porque otro proceso lo robó antes), salimos silenciosamente
if (!job) {
console.log('⚠️ Aviso: Trabajo duplicado detectado y evitado (Transacción retornó null).');
return;
}
if (!job) return;
console.log(`>>> Procesando Job: ${job.id}`);
try {
await withBrowser(async (page) => {
@ -301,46 +325,19 @@ async function processJob(db, job) {
}
}
// --- LOOP PRINCIPAL MEJORADO ---
function startWorker(db) {
const queue = [];
const processingIds = new Set(); // 🔒 EVITAR DUPLICADOS EN MEMORIA
let isRunning = false; // 🔒 SEMÁFORO DE EJECUCIÓN
const run = async () => {
if (isRunning) return; // Si ya estoy corriendo, no me interrumpas
isRunning = true;
while(queue.length) {
const jobId = queue.shift();
// 🔒 DOBLE SEGURIDAD: Si ya lo estoy procesando, salto
if (processingIds.has(jobId)) continue;
processingIds.add(jobId);
try {
const jobData = await claimJobById(db, jobId);
await processJob(db, jobData);
} finally {
processingIds.delete(jobId); // Libero el ID al terminar
}
}
isRunning = false;
while(queue.length) { await processJob(db, await claimJobById(db, queue.shift())); }
};
db.collection(CONFIG.QUEUE_COLLECTION).where('status', '==', 'PENDING').onSnapshot(s => {
let hasNews = false;
s.docChanges().forEach(c => {
// Solo añadimos si es nuevo Y no lo tenemos ya en cola ni procesando
if(c.type === 'added' && !queue.includes(c.doc.id) && !processingIds.has(c.doc.id)) {
queue.push(c.doc.id);
hasNews = true;
}
if(c.type === 'added') { queue.push(c.doc.id); run(); }
});
if (hasNews) run();
});
console.log('🚀 Worker Multiasistencia (V11 - FINAL SEGURO) LISTO.');
console.log('🚀 Worker Multiasistencia (V13 - HORA REDONDEADA) LISTO.');
}
const db = initFirebase();