Actualizar worker-multi-estado.js
This commit is contained in:
parent
677012a22a
commit
2cc2159687
|
|
@ -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';
|
'use strict';
|
||||||
|
|
||||||
const { chromium } = require('playwright');
|
const { chromium } = require('playwright');
|
||||||
|
|
@ -15,12 +15,11 @@ const CONFIG = {
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- DICCIONARIO DE TRADUCCIÓN (APP -> WEB) ---
|
// --- 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 = {
|
const STATE_TRANSLATOR = {
|
||||||
"15": "2", // App envía "15" -> Robot marca "2" (Visita al Cliente [15])
|
"15": "2", // App envía "15" -> Robot marca "2" (Visita al Cliente)
|
||||||
"0": "34", // App envía "0" -> Robot marca "34" (Rechazado [0])
|
"0": "34", // Rechazado
|
||||||
"1": "1", // App envía "1" -> Robot marca "1" (Contacto [1])
|
"1": "1", // Contacto
|
||||||
"99": "3" // App envía "99" -> Robot marca "3" (Entrega presupuesto [99]) - (Ajustar según necesidad)
|
"99": "3" // Entrega presupuesto (ajustar si es necesario)
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- UTILS ---
|
// --- UTILS ---
|
||||||
|
|
@ -36,14 +35,12 @@ function timeToMultiValue(timeStr) {
|
||||||
return String((h * 3600) + (m * 60));
|
return String((h * 3600) + (m * 60));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extraer hora del texto (Ej: "cita a las 13:00" -> "13:00")
|
|
||||||
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})/);
|
||||||
return match ? match[1] : null;
|
return match ? match[1] : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normalizar fecha (DD/MM/YYYY -> YYYY-MM-DD)
|
|
||||||
function normalizeDate(dateStr) {
|
function normalizeDate(dateStr) {
|
||||||
if (!dateStr) return "";
|
if (!dateStr) return "";
|
||||||
if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) return dateStr;
|
if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) return dateStr;
|
||||||
|
|
@ -54,24 +51,21 @@ function normalizeDate(dateStr) {
|
||||||
return dateStr;
|
return dateStr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fecha/Hora actual del sistema
|
|
||||||
function getCurrentDateTime() {
|
function getCurrentDateTime() {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const year = now.getFullYear();
|
const year = now.getFullYear();
|
||||||
const month = String(now.getMonth() + 1).padStart(2, '0');
|
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||||||
const day = String(now.getDate()).padStart(2, '0');
|
const day = String(now.getDate()).padStart(2, '0');
|
||||||
|
return {
|
||||||
const dateStr = `${year}-${month}-${day}`;
|
dateStr: `${year}-${month}-${day}`,
|
||||||
const hourStr = String(now.getHours());
|
hourStr: String(now.getHours()),
|
||||||
const minStr = String(now.getMinutes()).padStart(2, '0');
|
minStr: String(now.getMinutes()).padStart(2, '0')
|
||||||
|
};
|
||||||
return { dateStr, hourStr, minStr };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- FIREBASE INIT ---
|
// --- FIREBASE INIT ---
|
||||||
function initFirebase() {
|
function initFirebase() {
|
||||||
if (!process.env.FIREBASE_PRIVATE_KEY) throw new Error('Missing FIREBASE_PRIVATE_KEY');
|
if (!process.env.FIREBASE_PRIVATE_KEY) throw new Error('Missing FIREBASE_PRIVATE_KEY');
|
||||||
|
|
||||||
if (!admin.apps.length) {
|
if (!admin.apps.length) {
|
||||||
admin.initializeApp({
|
admin.initializeApp({
|
||||||
credential: admin.credential.cert({
|
credential: admin.credential.cert({
|
||||||
|
|
@ -88,24 +82,16 @@ function initFirebase() {
|
||||||
async function loginMulti(page, db) {
|
async function loginMulti(page, db) {
|
||||||
let user = "", pass = "";
|
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; }
|
||||||
|
|
||||||
if (doc.exists) {
|
if (!user) throw new Error("Faltan credenciales.");
|
||||||
user = doc.data().user;
|
|
||||||
pass = doc.data().pass;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!user) throw new Error("Faltan credenciales en providerCredentials/multiasistencia");
|
|
||||||
|
|
||||||
console.log('🔐 Login en Multiasistencia...');
|
console.log('🔐 Login en Multiasistencia...');
|
||||||
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"]') || document.querySelector('input[type="text"]');
|
||||||
if (el) {
|
if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
|
||||||
el.value = u;
|
|
||||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
return false;
|
||||||
}, user);
|
}, user);
|
||||||
|
|
||||||
|
|
@ -137,28 +123,22 @@ async function forceUpdate(elementHandle) {
|
||||||
async function processChangeState(page, db, jobData) {
|
async function processChangeState(page, db, jobData) {
|
||||||
const serviceNumber = jobData.serviceNumber;
|
const serviceNumber = jobData.serviceNumber;
|
||||||
|
|
||||||
// 1. OBTENER DATOS CRUDOS DE LA APP
|
// MAPPING
|
||||||
let rawReason = jobData.reasonValue || jobData.nuevoEstado || jobData.estado; // Viene "15"
|
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 rawDate = jobData.dateStr || jobData.fecha;
|
||||||
const dateStr = normalizeDate(rawDate);
|
const dateStr = normalizeDate(rawDate);
|
||||||
let timeStr = jobData.timeStr || extractTimeFromText(comment);
|
let timeStr = jobData.timeStr || extractTimeFromText(comment);
|
||||||
|
|
||||||
// 2. TRADUCCIÓN MÁGICA (AQUÍ ESTÁ EL FIX)
|
// TRADUCCIÓN
|
||||||
// Si rawReason es "15", reasonValue se convierte en "2". Si no está en la lista, se queda igual.
|
|
||||||
const reasonValue = STATE_TRANSLATOR[rawReason] || rawReason;
|
const reasonValue = STATE_TRANSLATOR[rawReason] || rawReason;
|
||||||
|
|
||||||
console.log(`🔧 DATOS: App envía "${rawReason}" -> Robot traduce a ID "${reasonValue}"`);
|
console.log(`🔧 DATOS: App envía "${rawReason}" -> Traducido a ID "${reasonValue}"`);
|
||||||
console.log(`📅 FECHA: ${dateStr} | ⏰ HORA: ${timeStr}`);
|
|
||||||
|
|
||||||
if (!reasonValue || reasonValue === 'undefined') {
|
if (!reasonValue || reasonValue === 'undefined') throw new Error("DATOS FALTANTES: No hay estado válido.");
|
||||||
throw new Error("DATOS FALTANTES: No hay estado válido para procesar.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. LOGIN
|
// NAVEGACIÓN
|
||||||
await loginMulti(page, db);
|
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`;
|
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 });
|
||||||
|
|
@ -166,35 +146,31 @@ async function processChangeState(page, db, jobData) {
|
||||||
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
await page.waitForSelector('select.answer-select', { timeout: 20000 });
|
||||||
await page.waitForTimeout(1500);
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
// 5. SELECCIONAR MOTIVO
|
// MOTIVO
|
||||||
const reasonSel = page.locator('select.answer-select').first();
|
const reasonSel = page.locator('select.answer-select').first();
|
||||||
const targetValue = String(reasonValue);
|
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() }));
|
|
||||||
});
|
|
||||||
|
|
||||||
const optionExists = availableOptions.find(o => o.value === targetValue);
|
// Check de seguridad
|
||||||
|
const availableOptions = await reasonSel.evaluate((select) =>
|
||||||
if (!optionExists) {
|
Array.from(select.options).map(o => ({ value: o.value, text: o.innerText.trim() }))
|
||||||
// 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(', ');
|
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 reasonSel.selectOption(targetValue);
|
||||||
await forceUpdate(await reasonSel.elementHandle());
|
await forceUpdate(await reasonSel.elementHandle());
|
||||||
|
|
||||||
// 6. COMENTARIO
|
// 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());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7. FECHA SIGUIENTE ACCIÓN (SI PROCEDE)
|
// FECHA SIGUIENTE ACCIÓN
|
||||||
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) {
|
||||||
|
|
@ -210,19 +186,17 @@ async function processChangeState(page, db, jobData) {
|
||||||
await forceUpdate(await timeSelect.elementHandle());
|
await forceUpdate(await timeSelect.elementHandle());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Fallback
|
|
||||||
const genericDateInput = page.locator('input[type="date"]').first();
|
const genericDateInput = page.locator('input[type="date"]').first();
|
||||||
await genericDateInput.fill(dateStr);
|
await genericDateInput.fill(dateStr);
|
||||||
await forceUpdate(await genericDateInput.elementHandle());
|
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"]');
|
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 con FECHA ACTUAL...');
|
||||||
const now = getCurrentDateTime();
|
const now = getCurrentDateTime();
|
||||||
|
|
||||||
const contactDateInput = contactBlock.locator('input[type="date"]');
|
const contactDateInput = contactBlock.locator('input[type="date"]');
|
||||||
await contactDateInput.fill(now.dateStr);
|
await contactDateInput.fill(now.dateStr);
|
||||||
await forceUpdate(await contactDateInput.elementHandle());
|
await forceUpdate(await contactDateInput.elementHandle());
|
||||||
|
|
@ -238,7 +212,7 @@ async function processChangeState(page, db, jobData) {
|
||||||
|
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// 9. GUARDAR
|
// GUARDAR
|
||||||
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()) {
|
||||||
await page.click('textarea[formcontrolname="comment"]');
|
await page.click('textarea[formcontrolname="comment"]');
|
||||||
|
|
@ -246,11 +220,10 @@ async function processChangeState(page, db, jobData) {
|
||||||
await page.waitForTimeout(1000);
|
await page.waitForTimeout(1000);
|
||||||
if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Bloqueado.`);
|
if (await btn.isDisabled()) throw new Error(`IMPOSIBLE GUARDAR: Bloqueado.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('💾 Guardando...');
|
console.log('💾 Guardando...');
|
||||||
await btn.click();
|
await btn.click();
|
||||||
|
|
||||||
// 10. ALERTAS
|
// ALERTAS SMS
|
||||||
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()) {
|
||||||
|
|
@ -258,10 +231,9 @@ async function processChangeState(page, db, jobData) {
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 11. RESULTADO
|
// RESULTADO
|
||||||
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
|
const screenshotBuffer = await page.screenshot({ fullPage: true, quality: 50, type: 'jpeg' });
|
||||||
const screenshotBase64 = screenshotBuffer.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') || document.querySelector('.bg-success');
|
||||||
const errorEl = document.querySelector('.form-container-error') || document.querySelector('.bg-danger');
|
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}`);
|
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) {
|
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() };
|
||||||
});
|
});
|
||||||
|
|
@ -306,20 +275,19 @@ async function markJobDone(db, job, result) {
|
||||||
|
|
||||||
async function markJobFailed(db, job, err) {
|
async function markJobFailed(db, job, err) {
|
||||||
const jobId = job.id;
|
const jobId = job.id;
|
||||||
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({
|
await db.collection(CONFIG.QUEUE_COLLECTION).doc(jobId).set({ status: 'FAILED', error: { message: err.message } }, { merge: true });
|
||||||
status: 'FAILED',
|
|
||||||
error: { message: err.message }
|
|
||||||
}, { merge: true });
|
|
||||||
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
await db.collection(CONFIG.RESULT_COLLECTION).add({
|
||||||
jobId,
|
jobId, ok: false, serviceNumber: job.serviceNumber || '', error: err.message, createdAt: toServerTimestamp()
|
||||||
ok: false,
|
|
||||||
serviceNumber: job.serviceNumber || '',
|
|
||||||
error: err.message,
|
|
||||||
createdAt: toServerTimestamp()
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
|
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) => {
|
||||||
|
|
@ -333,15 +301,46 @@ 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 () => {
|
||||||
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 => {
|
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();
|
const db = initFirebase();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue