Actualizar worker-multi-estado.js
This commit is contained in:
parent
2cc2159687
commit
6368ac14be
|
|
@ -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';
|
'use strict';
|
||||||
|
|
||||||
const { chromium } = require('playwright');
|
const { chromium } = require('playwright');
|
||||||
|
|
@ -14,27 +14,44 @@ const CONFIG = {
|
||||||
RESCAN_SECONDS: 60
|
RESCAN_SECONDS: 60
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- DICCIONARIO DE TRADUCCIÓN (APP -> WEB) ---
|
// --- DICCIONARIO DE TRADUCCIÓN ---
|
||||||
const STATE_TRANSLATOR = {
|
const STATE_TRANSLATOR = {
|
||||||
"15": "2", // App envía "15" -> Robot marca "2" (Visita al Cliente)
|
"15": "2", // App 15 -> Web 2 (Visita)
|
||||||
"0": "34", // Rechazado
|
"0": "34", // Web 34 (Rechazado)
|
||||||
"1": "1", // Contacto
|
"1": "1", // Web 1 (Contacto)
|
||||||
"99": "3" // Entrega presupuesto (ajustar si es necesario)
|
"99": "3" // Web 3 (Presupuesto)
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- UTILS ---
|
// --- UTILS ---
|
||||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
function toServerTimestamp() { return admin.firestore.FieldValue.serverTimestamp(); }
|
||||||
|
|
||||||
function toServerTimestamp() {
|
// Convertir HH:MM a segundos (para Multiasistencia)
|
||||||
return admin.firestore.FieldValue.serverTimestamp();
|
|
||||||
}
|
|
||||||
|
|
||||||
function timeToMultiValue(timeStr) {
|
function timeToMultiValue(timeStr) {
|
||||||
if (!timeStr) return "";
|
if (!timeStr) return "";
|
||||||
const [h, m] = timeStr.split(':').map(Number);
|
const [h, m] = timeStr.split(':').map(Number);
|
||||||
return String((h * 3600) + (m * 60));
|
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) {
|
function extractTimeFromText(text) {
|
||||||
if (!text) return null;
|
if (!text) return null;
|
||||||
const match = text.match(/(\d{1,2}:\d{2})/);
|
const match = text.match(/(\d{1,2}:\d{2})/);
|
||||||
|
|
@ -80,17 +97,15 @@ function initFirebase() {
|
||||||
|
|
||||||
// --- LOGIN ---
|
// --- LOGIN ---
|
||||||
async function loginMulti(page, db) {
|
async function loginMulti(page, db) {
|
||||||
let user = "", pass = "";
|
|
||||||
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
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.");
|
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' });
|
await page.goto(CONFIG.MULTI_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||||
|
|
||||||
const userFilled = await page.evaluate((u) => {
|
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; }
|
if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
|
||||||
return false;
|
return false;
|
||||||
}, user);
|
}, user);
|
||||||
|
|
@ -101,7 +116,7 @@ async function loginMulti(page, db) {
|
||||||
await page.waitForTimeout(4000);
|
await page.waitForTimeout(4000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- PLAYWRIGHT SETUP ---
|
// --- HELPERS BROWSER ---
|
||||||
async function withBrowser(fn) {
|
async function withBrowser(fn) {
|
||||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||||
const context = await browser.newContext();
|
const context = await browser.newContext();
|
||||||
|
|
@ -123,137 +138,154 @@ async function forceUpdate(elementHandle) {
|
||||||
async function processChangeState(page, db, jobData) {
|
async function processChangeState(page, db, jobData) {
|
||||||
const serviceNumber = jobData.serviceNumber;
|
const serviceNumber = jobData.serviceNumber;
|
||||||
|
|
||||||
// MAPPING
|
// 1. MAPPING DE DATOS
|
||||||
let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado;
|
let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado;
|
||||||
const comment = jobData.comment || jobData.observaciones || jobData.nota;
|
const comment = jobData.comment || jobData.observaciones || jobData.nota;
|
||||||
const rawDate = jobData.dateStr || jobData.fecha;
|
const dateStr = normalizeDate(jobData.dateStr || jobData.fecha);
|
||||||
const dateStr = normalizeDate(rawDate);
|
|
||||||
let timeStr = jobData.timeStr || extractTimeFromText(comment);
|
|
||||||
|
|
||||||
// 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;
|
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.");
|
if (!reasonValue || reasonValue === 'undefined') throw new Error("DATOS FALTANTES: No hay estado válido.");
|
||||||
|
|
||||||
// NAVEGACIÓN
|
// 2. NAVEGACIÓN
|
||||||
await loginMulti(page, db);
|
await loginMulti(page, db);
|
||||||
const targetUrl = `${CONFIG.MULTI_ACTION_BASE}?reparacion=${serviceNumber}&modo=0&navid=%2Fw3multi%2Ffrepasos_new.php%FDGET%FDrefresh%3D1%FC`;
|
const targetUrl = `${CONFIG.MULTI_ACTION_BASE}?reparacion=${serviceNumber}&modo=0&navid=%2Fw3multi%2Ffrepasos_new.php%FDGET%FDrefresh%3D1%FC`;
|
||||||
console.log(`📂 Abriendo servicio ${serviceNumber}...`);
|
console.log(`📂 Abriendo servicio ${serviceNumber}...`);
|
||||||
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
||||||
|
|
||||||
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
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 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
|
if (!availableOptions.includes(String(reasonValue))) {
|
||||||
const availableOptions = await reasonSel.evaluate((select) =>
|
// Fallback inteligente: Si enviamos "2" pero no está, intentamos buscar texto
|
||||||
Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() }))
|
throw new Error(`MOTIVO INVÁLIDO: ID "${reasonValue}" no está disponible.`);
|
||||||
);
|
|
||||||
|
|
||||||
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}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await reasonSel.selectOption(targetValue);
|
await reasonSel.selectOption(String(reasonValue));
|
||||||
await forceUpdate(await reasonSel.elementHandle());
|
await forceUpdate(await reasonSel.elementHandle());
|
||||||
|
|
||||||
// COMENTARIO
|
// 4. COMENTARIO
|
||||||
if (comment) {
|
if (comment) {
|
||||||
const commentBox = page.locator('textarea[formcontrolname="comment"]');
|
const commentBox = page.locator('textarea[formcontrolname="comment"]');
|
||||||
await commentBox.fill(comment);
|
await commentBox.fill(comment);
|
||||||
await forceUpdate(await commentBox.elementHandle());
|
await forceUpdate(await commentBox.elementHandle());
|
||||||
}
|
}
|
||||||
|
|
||||||
// FECHA SIGUIENTE ACCIÓN
|
// 5. FECHA SIGUIENTE ACCIÓN (CON HORA REDONDEADA)
|
||||||
if (dateStr) {
|
if (dateStr) {
|
||||||
const actionBlock = page.locator('encastrables-date-hour-field[label="TXTFACCION"]');
|
const actionBlock = page.locator('encastrables-date-hour-field[label="TXTFACCION"]');
|
||||||
if (await actionBlock.count() > 0) {
|
if (await actionBlock.count() > 0) {
|
||||||
const dateInput = actionBlock.locator('input[type="date"]');
|
const dateInput = actionBlock.locator('input[type="date"]');
|
||||||
await dateInput.fill(dateStr);
|
await dateInput.fill(dateStr);
|
||||||
await forceUpdate(await dateInput.elementHandle());
|
await forceUpdate(await dateInput.elementHandle());
|
||||||
await page.click('body');
|
await page.click('body');
|
||||||
|
|
||||||
if (timeStr) {
|
if (timeStr) {
|
||||||
const secondsValue = timeToMultiValue(timeStr);
|
const seconds = timeToMultiValue(timeStr);
|
||||||
const timeSelect = actionBlock.locator('select.answer-select');
|
const timeSel = actionBlock.locator('select.answer-select');
|
||||||
await timeSelect.selectOption(secondsValue).catch(() => {});
|
|
||||||
await forceUpdate(await timeSelect.elementHandle());
|
// 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 {
|
} else {
|
||||||
const genericDateInput = page.locator('input[type="date"]').first();
|
// Fallback genérico
|
||||||
await genericDateInput.fill(dateStr);
|
const genDate = page.locator('input[type="date"]').first();
|
||||||
await forceUpdate(await genericDateInput.elementHandle());
|
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"]');
|
const contactBlock = page.locator('encastrables-date-hour-field[label="TXTFCONTACTO"]');
|
||||||
if (await contactBlock.count() > 0 && await contactBlock.isVisible()) {
|
if (await contactBlock.count() > 0 && await contactBlock.isVisible()) {
|
||||||
console.log('📞 Rellenando contacto con FECHA ACTUAL...');
|
console.log('📞 Rellenando contacto...');
|
||||||
const now = getCurrentDateTime();
|
const now = getCurrentDateTime();
|
||||||
const contactDateInput = contactBlock.locator('input[type="date"]');
|
|
||||||
await contactDateInput.fill(now.dateStr);
|
const cDate = contactBlock.locator('input[type="date"]');
|
||||||
await forceUpdate(await contactDateInput.elementHandle());
|
await cDate.fill(now.dateStr);
|
||||||
|
await forceUpdate(await cDate.elementHandle());
|
||||||
|
|
||||||
const selects = contactBlock.locator('select.answer-select-time');
|
const selects = contactBlock.locator('select.answer-select-time');
|
||||||
if (await selects.count() >= 2) {
|
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 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 forceUpdate(await selects.nth(1).elementHandle());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// GUARDAR
|
// 7. GUARDAR (CON INTELIGENCIA DE REINTENTO)
|
||||||
const btn = page.locator('button.form-container-button-submit');
|
const btn = page.locator('button.form-container-button-submit');
|
||||||
if (await btn.isDisabled()) {
|
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.click('textarea[formcontrolname="comment"]');
|
||||||
await page.keyboard.press('Tab');
|
await page.keyboard.press('Tab');
|
||||||
await page.waitForTimeout(1000);
|
await page.click('body');
|
||||||
if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Bloqueado.`);
|
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...');
|
console.log('💾 Guardando...');
|
||||||
await btn.click();
|
await btn.click();
|
||||||
|
|
||||||
// ALERTAS SMS
|
// 8. ALERTAS
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
const confirmBtn = page.locator('button.form-container-button-submit-toast').filter({ hasText: 'Sí' });
|
const confirmBtn = page.locator('button.form-container-button-submit-toast').filter({ hasText: 'Sí' });
|
||||||
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
|
if (await confirmBtn.count() > 0 && await confirmBtn.isVisible()) {
|
||||||
await confirmBtn.click();
|
await confirmBtn.click();
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// RESULTADO
|
// 9. RESULTADO
|
||||||
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
|
const screenshot = (await page.screenshot({ fullPage: true, quality: 40, type: 'jpeg' })).toString('base64');
|
||||||
const screenshotBase64 = screenshotBuffer.toString('base64');
|
|
||||||
const finalResult = await page.evaluate(() => {
|
const finalResult = await page.evaluate(() => {
|
||||||
const successEl = document.querySelector('.form-container-success') || document.querySelector('.bg-success');
|
const successEl = document.querySelector('.form-container-success, .bg-success');
|
||||||
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
|
const errorEl = document.querySelector('.form-container-error, .bg-danger');
|
||||||
if (successEl) return { type: 'OK', text: successEl.innerText };
|
|
||||||
if (errorEl) return { type: 'ERROR', text: errorEl.innerText };
|
if (successEl) return { type: 'OK', text: successEl.innerText.trim() };
|
||||||
return { type: 'UNKNOWN', text: document.body.innerText.substring(0, 300) };
|
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}`);
|
console.log(`🏁 FINAL: ${finalResult.type} - ${finalResult.text}`);
|
||||||
return { success: (finalResult.type === 'OK' || finalResult.text.includes('correctamente')), message: finalResult.text, screenshot: screenshotBase64 };
|
return { success: finalResult.type === 'OK', message: finalResult.text, screenshot };
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- GESTIÓN DE COLAS Y TRANSACCIONES ---
|
// --- GESTIÓN DE COLAS ---
|
||||||
async function claimJobById(db, jobId) {
|
async function claimJobById(db, jobId) {
|
||||||
const ref = db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId);
|
const ref = db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId);
|
||||||
return await db.runTransaction(async (tx) => {
|
return await db.runTransaction(async (tx) => {
|
||||||
const snap = await tx.get(ref);
|
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;
|
if (!snap.exists || snap.data().status !== 'PENDING') return null;
|
||||||
|
|
||||||
tx.set(ref, { status: 'RUNNING', claimedAt: toServerTimestamp() }, { merge: true });
|
tx.set(ref, { status: 'RUNNING', claimedAt: toServerTimestamp() }, { merge: true });
|
||||||
return { id: jobId, ...snap.data() };
|
return { id: jobId, ...snap.data() };
|
||||||
});
|
});
|
||||||
|
|
@ -263,13 +295,10 @@ async function markJobDone(db, job, result) {
|
||||||
const jobId = job.id;
|
const jobId = job.id;
|
||||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'DONE', result }, { merge: true });
|
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'DONE', result }, { merge: true });
|
||||||
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
||||||
jobId,
|
jobId, ok: true, serviceNumber: job.serviceNumber || '',
|
||||||
ok: true,
|
reason: job.nuevoEstado || '',
|
||||||
serviceNumber: job.serviceNumber || '',
|
comment: job.observaciones || '',
|
||||||
reason: job.nuevoEstado || job.estado || '',
|
...result, createdAt: toServerTimestamp()
|
||||||
comment: job.observaciones || job.nota || '',
|
|
||||||
...result,
|
|
||||||
createdAt: toServerTimestamp()
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -282,12 +311,7 @@ async function markJobFailed(db, job, err) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function processJob(db, job) {
|
async function processJob(db, job) {
|
||||||
// CRÍTICO: Si el trabajo llegó nulo (porque otro proceso lo robó antes), salimos silenciosamente
|
if (!job) return;
|
||||||
if (!job) {
|
|
||||||
console.log('⚠️ Aviso: Trabajo duplicado detectado y evitado (Transacción retornó null).');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`>>> Procesando Job: ${job.id}`);
|
console.log(`>>> Procesando Job: ${job.id}`);
|
||||||
try {
|
try {
|
||||||
await withBrowser(async (page) => {
|
await withBrowser(async (page) => {
|
||||||
|
|
@ -301,46 +325,19 @@ async function processJob(db, job) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- LOOP PRINCIPAL MEJORADO ---
|
|
||||||
function startWorker(db) {
|
function startWorker(db) {
|
||||||
const queue = [];
|
const queue = [];
|
||||||
const processingIds = new Set(); // 🔒 EVITAR DUPLICADOS EN MEMORIA
|
|
||||||
let isRunning = false; // 🔒 SEMÁFORO DE EJECUCIÓN
|
|
||||||
|
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
if (isRunning) return; // Si ya estoy corriendo, no me interrumpas
|
while(queue.length) { await processJob(db, await claimJobById(db, queue.shift())); }
|
||||||
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 => {
|
db.collection(CONFIG.QUEUE_COLLECTION).where('status', '==', 'PENDING').onSnapshot(s => {
|
||||||
let hasNews = false;
|
|
||||||
s.docChanges().forEach(c => {
|
s.docChanges().forEach(c => {
|
||||||
// Solo añadimos si es nuevo Y no lo tenemos ya en cola ni procesando
|
if(c.type === 'added') { queue.push(c.doc.id); run(); }
|
||||||
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 (V13 - HORA REDONDEADA) LISTO.');
|
||||||
console.log('🚀 Worker Multiasistencia (V11 - FINAL SEGURO) LISTO.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const db = initFirebase();
|
const db = initFirebase();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue