estados-multi/worker-multi-estado.js

346 lines
13 KiB
JavaScript

// worker-multi-estado.js (V13 - REDONDEO DE HORA + ANTI-BLOQUEO)
'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
};
// --- DICCIONARIO DE TRADUCCIÓN ---
const STATE_TRANSLATOR = {
"15": "2", // App 15 -> Web 2 (Visita)
"0": "34", // Web 34 (Rechazado)
"1": "1", // Web 1 (Contacto)
"99": "3" // Web 3 (Presupuesto)
"60": "13" // Web 3 (Presupuesto)
};
// --- UTILS ---
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
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})/);
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);
}
// --- HELPERS BROWSER ---
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;
// 1. MAPPING DE DATOS
let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado;
const comment = jobData.comment || jobData.observaciones || jobData.nota;
const dateStr = normalizeDate(jobData.dateStr || jobData.fecha);
// 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: ID:${reasonValue} | Fecha:${dateStr} | Hora:${rawTime} -> Redondeada:${timeStr}`);
if (!reasonValue || reasonValue === 'undefined') throw new Error("DATOS FALTANTES: No hay estado válido.");
// 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(1000);
// 3. SELECCIONAR MOTIVO
const reasonSel = page.locator('select.answer-select').first();
const availableOptions = await reasonSel.evaluate(s => Array.from(s.options).map(o => o.value));
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(String(reasonValue));
await forceUpdate(await reasonSel.elementHandle());
// 4. COMENTARIO
if (comment) {
const commentBox = page.locator('textarea[formcontrolname="comment"]');
await commentBox.fill(comment);
await forceUpdate(await commentBox.elementHandle());
}
// 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');
if (timeStr) {
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 {
// Fallback genérico
const genDate = page.locator('input[type="date"]').first();
await genDate.fill(dateStr);
await forceUpdate(await genDate.elementHandle());
}
}
// 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...');
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) {
// Hora
await selects.nth(0).selectOption(now.hourStr).catch(()=>{});
await forceUpdate(await selects.nth(0).elementHandle());
// Minutos
await selects.nth(1).selectOption(now.minStr).catch(()=>{});
await forceUpdate(await selects.nth(1).elementHandle());
}
}
await page.waitForTimeout(2000);
// 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.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();
// 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);
}
// 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, .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} - ${finalResult.text}`);
return { success: finalResult.type === 'OK', message: finalResult.text, screenshot };
}
// --- 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);
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) {
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 || '',
comment: job.observaciones || '',
...result, createdAt: toServerTimestamp()
});
}
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.RESULT_COLLECTION).add({
jobId, ok: false, serviceNumber: job.serviceNumber || '', error: err.message, createdAt: toServerTimestamp()
});
}
async function processJob(db, job) {
if (!job) return;
console.log(`>>> Procesando Job: ${job.id}`);
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);
}
}
function startWorker(db) {
const queue = [];
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 (V13 - HORA REDONDEADA) LISTO.');
}
const db = initFirebase();
startWorker(db);