Actualizar worker-multi-estado.js

This commit is contained in:
marsalva 2026-01-10 15:47:42 +00:00
parent 677012a22a
commit 2cc2159687
1 changed files with 79 additions and 80 deletions

View File

@ -1,4 +1,4 @@
// worker-multi-estado.js (V10 - TRADUCTOR AUTOMÁTICO DE ESTADOS)
// worker-multi-estado.js (V11 - FINAL: TRADUCTOR + ANTI-DOBLE EJECUCIÓN)
'use strict';
const { chromium } = require('playwright');
@ -15,12 +15,11 @@ const CONFIG = {
};
// --- 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)
"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)
};
// --- UTILS ---
@ -36,14 +35,12 @@ function timeToMultiValue(timeStr) {
return String((h * 3600) + (m * 60));
}
// 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;
}
// Normalizar fecha (DD/MM/YYYY -> YYYY-MM-DD)
function normalizeDate(dateStr) {
if (!dateStr) return "";
if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) return dateStr;
@ -54,24 +51,21 @@ function normalizeDate(dateStr) {
return dateStr;
}
// Fecha/Hora actual del 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 };
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({
@ -88,24 +82,16 @@ function initFirebase() {
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; }
if (doc.exists) {
user = doc.data().user;
pass = doc.data().pass;
}
if (!user) throw new Error("Faltan credenciales en providerCredentials/multiasistencia");
if (!user) throw new Error("Faltan credenciales.");
console.log('🔐 Login en Multiasistencia...');
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"]');
if (el) {
el.value = u;
el.dispatchEvent(new Event('input', { bubbles: true }));
return true;
}
if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
return false;
}, user);
@ -137,28 +123,22 @@ async function forceUpdate(elementHandle) {
async function processChangeState(page, db, jobData) {
const serviceNumber = jobData.serviceNumber;
// 1. OBTENER DATOS CRUDOS DE LA APP
let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado; // Viene "15"
// MAPPING
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);
// 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.
// TRADUCCIÓN
const reasonValue = STATE_TRANSLATOR[rawReason] || rawReason;
console.log(`🔧 DATOS: App envía "${rawReason}" -> Robot traduce a ID "${reasonValue}"`);
console.log(`📅 FECHA: ${dateStr} | ⏰ HORA: ${timeStr}`);
console.log(`🔧 DATOS: App envía "${rawReason}" -> Traducido a ID "${reasonValue}"`);
if (!reasonValue || reasonValue === 'undefined') {
throw new Error("DATOS FALTANTES: No hay estado válido para procesar.");
}
if (!reasonValue || reasonValue === 'undefined') throw new Error("DATOS FALTANTES: No hay estado válido.");
// 3. LOGIN
// NAVEGACIÓN
await loginMulti(page, db);
// 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 });
@ -166,35 +146,31 @@ async function processChangeState(page, db, jobData) {
await page.waitForSelector('select.answer-select', { timeout: 20000 });
await page.waitForTimeout(1500);
// 5. SELECCIONAR MOTIVO
// MOTIVO
const reasonSel = page.locator('select.answer-select').first();
const targetValue = String(reasonValue);
// Verificación de seguridad
const availableOptions = await reasonSel.evaluate((select) => {
return Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() }));
});
// Check de seguridad
const availableOptions = await reasonSel.evaluate((select) =>
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.`);
if (!availableOptions.find(o => o.value === targetValue)) {
const validList = availableOptions.map(o => `[${o.value}: ${o.text}]`).join(', ');
throw new Error(`MOTIVO INVÁLIDO: Intenté seleccionar ID "${targetValue}" pero no está. Opciones: ${validList}`);
throw new Error(`MOTIVO INVÁLIDO: ID "${targetValue}" no existe. Opciones: ${validList}`);
}
await reasonSel.selectOption(targetValue);
await forceUpdate(await reasonSel.elementHandle());
// 6. COMENTARIO
// COMENTARIO
if (comment) {
const commentBox = page.locator('textarea[formcontrolname="comment"]');
await commentBox.fill(comment);
await forceUpdate(await commentBox.elementHandle());
}
// 7. FECHA SIGUIENTE ACCIÓN (SI PROCEDE)
// FECHA SIGUIENTE ACCIÓN
if (dateStr) {
const actionBlock = page.locator('encastrables-date-hour-field[label="TXTFACCION"]');
if (await actionBlock.count() > 0) {
@ -210,19 +186,17 @@ async function processChangeState(page, db, jobData) {
await forceUpdate(await timeSelect.elementHandle());
}
} else {
// Fallback
const genericDateInput = page.locator('input[type="date"]').first();
await genericDateInput.fill(dateStr);
await forceUpdate(await genericDateInput.elementHandle());
}
}
// 8. FECHA CONTACTO (AUTOMÁTICA HOY)
// 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());
@ -238,7 +212,7 @@ async function processChangeState(page, db, jobData) {
await page.waitForTimeout(2000);
// 9. GUARDAR
// GUARDAR
const btn = page.locator('button.form-container-button-submit');
if (await btn.isDisabled()) {
await page.click('textarea[formcontrolname="comment"]');
@ -246,11 +220,10 @@ async function processChangeState(page, db, jobData) {
await page.waitForTimeout(1000);
if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Bloqueado.`);
}
console.log('💾 Guardando...');
await btn.click();
// 10. ALERTAS
// ALERTAS SMS
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()) {
@ -258,10 +231,9 @@ async function processChangeState(page, db, jobData) {
await page.waitForTimeout(3000);
}
// 11. RESULTADO
// RESULTADO
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');
@ -271,20 +243,17 @@ async function processChangeState(page, db, jobData) {
});
console.log(`🏁 FINAL: ${finalResult.type}`);
return {
success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')),
message: finalResult.text,
screenshot: screenshotBase64
};
return { success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')), message: finalResult.text, screenshot: screenshotBase64 };
}
// --- WORKER LOOP ---
// --- 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);
// 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() };
});
@ -306,20 +275,19 @@ async function markJobDone(db, job, result) {
async function markJobFailed(db, job, err) {
const jobId = job.id;
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({
status: 'FAILED',
error: { message: err.message }
}, { merge: true });
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'FAILED', error: { message: err.message } }, { merge: true });
await db.collection(CONFIG.RESULT_COLLECTION).add({
jobId,
ok: false,
serviceNumber: job.serviceNumber || '',
error: err.message,
createdAt: toServerTimestamp()
jobId, ok: false, serviceNumber: job.serviceNumber || '', error: err.message, createdAt: toServerTimestamp()
});
}
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;
}
console.log(`>>> Procesando Job: ${job.id}`);
try {
await withBrowser(async (page) => {
@ -333,15 +301,46 @@ 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 () => {
while(queue.length) { await processJob(db, await claimJobById(db, queue.shift())); }
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;
};
db.collection(CONFIG.QUEUE_COLLECTION).where('status', '==', 'PENDING').onSnapshot(s => {
s.docChanges().forEach(c => { if(c.type==='added') { queue.push(c.doc.id); run(); } });
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 (hasNews) run();
});
console.log('🚀 Worker Multiasistencia (V10 - TRADUCTOR) LISTO.');
console.log('🚀 Worker Multiasistencia (V11 - FINAL SEGURO) LISTO.');
}
const db = initFirebase();