Añadir worker-multi-estado.js
This commit is contained in:
commit
bf3c045bda
|
|
@ -0,0 +1,231 @@
|
|||
// worker-multi-estado.js
|
||||
'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',
|
||||
|
||||
// URLs base
|
||||
MULTI_LOGIN: "https://web.multiasistencia.com/w3multi/acceso.php",
|
||||
// La URL base para construir la dirección del servicio
|
||||
MULTI_ACTION_BASE: "https://web.multiasistencia.com/w3multi/fechaccion.php",
|
||||
|
||||
NAV_TIMEOUT: 60000,
|
||||
RESCAN_SECONDS: 60
|
||||
};
|
||||
|
||||
// --- UTILS ---
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
function toServerTimestamp() { return admin.firestore.FieldValue.serverTimestamp(); }
|
||||
|
||||
// Conversor de Hora (HH:MM) a Segundos desde media noche (formato interno Multi)
|
||||
// Ej: "08:00" -> 28800
|
||||
function timeToMultiValue(timeStr) {
|
||||
if (!timeStr) return "";
|
||||
const [h, m] = timeStr.split(':').map(Number);
|
||||
return String((h * 3600) + (m * 60));
|
||||
}
|
||||
|
||||
// --- 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 (Reutilizado de tu robot_cobros) ---
|
||||
async function loginMulti(page, db) {
|
||||
let user = "", pass = "";
|
||||
|
||||
// Buscamos credenciales en Firestore
|
||||
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
||||
if (doc.exists) {
|
||||
user = doc.data().user;
|
||||
pass = doc.data().pass;
|
||||
}
|
||||
|
||||
if (!user) throw new Error("Faltan credenciales en providerCredentials/multiasistencia");
|
||||
|
||||
console.log('🔐 Login en Multiasistencia...');
|
||||
await page.goto(CONFIG.MULTI_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Lógica de llenado robusta
|
||||
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; }
|
||||
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 HELPERS ---
|
||||
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(() => {}); }
|
||||
}
|
||||
|
||||
// --- LÓGICA PRINCIPAL DE CAMBIO DE ESTADO ---
|
||||
async function processChangeState(page, db, jobData) {
|
||||
const { serviceNumber, reasonValue, comment, dateStr, timeStr } = jobData;
|
||||
|
||||
// 1. LOGIN
|
||||
await loginMulti(page, db);
|
||||
|
||||
// 2. IR A LA URL DEL SERVICIO
|
||||
// Construimos la URL exacta que pediste con el navid incluido
|
||||
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 });
|
||||
|
||||
// Esperar a que cargue el formulario (Angular puede tardar)
|
||||
// Buscamos el selector del motivo para saber que cargó
|
||||
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
||||
|
||||
console.log('📝 Rellenando formulario...');
|
||||
|
||||
// 3. SELECCIONAR MOTIVO (Reason)
|
||||
// El HTML muestra <select class="answer-select ..."> dentro de un loop.
|
||||
// Usamos selectOption buscando por el value (ej: "26" para cliente ilocalizable)
|
||||
const reasonSelect = page.locator('select.answer-select').first();
|
||||
await reasonSelect.selectOption(String(reasonValue));
|
||||
|
||||
// 4. COMENTARIO
|
||||
// <textarea formcontrolname="comment" ...>
|
||||
if (comment) {
|
||||
await page.fill('textarea[formcontrolname="comment"]', comment);
|
||||
}
|
||||
|
||||
// 5. FECHA SIGUIENTE ACCIÓN
|
||||
// <input type="date" ...>
|
||||
if (dateStr) {
|
||||
// Aseguramos formato YYYY-MM-DD
|
||||
await page.fill('input[type="date"]', dateStr);
|
||||
}
|
||||
|
||||
// 6. HORA
|
||||
// La hora en Multi es un select con valores en segundos (ej: 08:00 = 28800)
|
||||
if (timeStr) {
|
||||
const secondsValue = timeToMultiValue(timeStr);
|
||||
// Buscamos el select que está dentro del bloque de hora
|
||||
// El HTML muestra un div class="answer-time"
|
||||
const timeSelect = page.locator('.answer-time select.answer-select').first();
|
||||
|
||||
// Si no lo encuentra por clase específica, intentamos buscar por valor
|
||||
if (await timeSelect.count() > 0) {
|
||||
await timeSelect.selectOption(secondsValue);
|
||||
} else {
|
||||
// Fallback: buscar cualquier select que tenga esa opción
|
||||
await page.evaluate((val) => {
|
||||
const selects = document.querySelectorAll('select');
|
||||
for (const s of selects) {
|
||||
if (s.querySelector(`option[value="${val}"]`)) {
|
||||
s.value = val;
|
||||
s.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, secondsValue);
|
||||
}
|
||||
}
|
||||
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// 7. GUARDAR
|
||||
// Botón: <button class="form-container-button-submit ...">
|
||||
console.log('💾 Guardando...');
|
||||
const submitBtn = page.locator('button.form-container-button-submit');
|
||||
|
||||
// Verificamos si está habilitado (el HTML inicial lo tenía disabled, pero al rellenar se habilita)
|
||||
if (await submitBtn.isDisabled()) {
|
||||
throw new Error("El botón de guardar sigue deshabilitado. ¿Falta algún campo obligatorio?");
|
||||
}
|
||||
|
||||
await submitBtn.click();
|
||||
|
||||
// Esperamos confirmación o redirección
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
return { success: true, url: targetUrl };
|
||||
}
|
||||
|
||||
// --- GESTIÓN DE COLAS (WORKER) ---
|
||||
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, jobId, result) {
|
||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'DONE', result }, { merge: true });
|
||||
await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: true, ...result, createdAt: toServerTimestamp() });
|
||||
}
|
||||
|
||||
async function markJobFailed(db, jobId, err) {
|
||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({
|
||||
status: 'FAILED',
|
||||
error: { message: err.message, stack: err.stack }
|
||||
}, { merge: true });
|
||||
await db.collection(CONFIG.RESULT_COLLECTION).add({ jobId, ok: false, error: err.message, createdAt: toServerTimestamp() });
|
||||
}
|
||||
|
||||
async function processJob(db, job) {
|
||||
console.log(`>>> Procesando Job: ${job.id} (Servicio: ${job.serviceNumber})`);
|
||||
try {
|
||||
await withBrowser(async (page) => {
|
||||
const res = await processChangeState(page, db, {
|
||||
serviceNumber: job.serviceNumber,
|
||||
reasonValue: job.reasonValue,
|
||||
comment: job.comment,
|
||||
dateStr: job.dateStr,
|
||||
timeStr: job.timeStr
|
||||
});
|
||||
await markJobDone(db, job.id, res);
|
||||
console.log(`✅ Job ${job.id} Completado.`);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`❌ Job ${job.id} Falló:`, err.message);
|
||||
await markJobFailed(db, job.id, err);
|
||||
}
|
||||
}
|
||||
|
||||
function startWorker(db) {
|
||||
const queue = [];
|
||||
const run = async () => {
|
||||
while(queue.length) { await processJob(db, await claimJobById(db, queue.shift())); }
|
||||
};
|
||||
|
||||
// Escuchar nuevos trabajos
|
||||
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 Estados LISTO.');
|
||||
}
|
||||
|
||||
// Iniciar
|
||||
const db = initFirebase();
|
||||
startWorker(db);
|
||||
Loading…
Reference in New Issue