Actualizar robot_cobros.js

This commit is contained in:
marsalva 2025-12-30 10:24:55 +00:00
parent 60f3b5228b
commit efa47f360f
1 changed files with 71 additions and 51 deletions

View File

@ -59,7 +59,7 @@ app.post('/api/robot-cobros', async (req, res) => {
});
// ==================================================================
// 🤖 LÓGICA MULTIASISTENCIA V16 (HÍBRIDO LISTA TEXTO + PRECIO FRAMES)
// 🤖 LÓGICA MULTIASISTENCIA V17 (MODO BULLDOG)
// ==================================================================
async function runMultiStream(mes, anio, send) {
@ -68,7 +68,7 @@ async function runMultiStream(mes, anio, send) {
const valD2 = `${anio}`;
try {
send('LOG', `🚀 (MULTI V16) Iniciando para: ${valD1}`);
send('LOG', `🚀 (MULTI V17) Iniciando Bulldog: ${valD1}`);
const { browser: b, page } = await loginMulti();
browser = b;
@ -80,32 +80,28 @@ async function runMultiStream(mes, anio, send) {
await page.selectOption('select[name="D1"]', valD1);
await page.selectOption('select[name="D2"]', valD2);
await page.click('input[name="continuar"]');
await page.waitForTimeout(2000);
await page.waitForTimeout(2500);
}
// --- FASE 1: RECOLECTAR IDs (LÓGICA V13 QUE SÍ FUNCIONABA) ---
// --- FASE 1: RECOLECTAR IDs ---
let idsServicios = [];
let tieneSiguiente = true;
let pagActual = 1;
while (tieneSiguiente && pagActual <= 10) {
send('LOG', `📄 Leyendo página ${pagActual}...`);
// BUSCAR TEXTO EN CELDAS (NO SOLO ENLACES)
const nuevosIds = await page.evaluate(() => {
const celdas = Array.from(document.querySelectorAll('td.tdet'));
const lista = [];
celdas.forEach(td => {
const txt = td.innerText.trim();
// Buscamos cualquier número de 8 cifras
if (/^\d{8}$/.test(txt)) lista.push(txt);
});
return lista;
});
const unicosPag = [...new Set(nuevosIds)];
idsServicios.push(...unicosPag);
send('LOG', ` -> Encontrados ${unicosPag.length} servicios.`);
idsServicios.push(...[...new Set(nuevosIds)]);
send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`);
const haySiguiente = await page.$('a:has-text("Página siguiente")');
if (haySiguiente) { await haySiguiente.click(); await page.waitForTimeout(3000); pagActual++; }
@ -117,7 +113,7 @@ async function runMultiStream(mes, anio, send) {
if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] };
// --- FASE 2: LEER DETALLES (CON FRAMES V15) ---
// --- FASE 2: LEER DETALLES (BUCLE DE REINTENTOS) ---
for (const [index, idServicio] of idsServicios.entries()) {
send('PROGRESS', { current: index + 1, total: idsServicios.length });
@ -125,49 +121,73 @@ async function runMultiStream(mes, anio, send) {
try {
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
await page.waitForTimeout(1500); // Esperar renderizado
// === BÚSQUEDA PROFUNDA EN FRAMES ===
let totalStr = "";
let importe = 0;
let clienteWeb = "Desconocido";
let direccionWeb = "Sin dirección";
// 1. Iterar sobre todos los frames
// --- MODO BULLDOG: INTENTAR HASTA 5 VECES SI EL PRECIO ES 0 ---
let intentos = 0;
while (intentos < 5 && importe === 0) {
intentos++;
if(intentos > 1) await page.waitForTimeout(1500); // Esperar entre intentos
// 1. ESCANEAR TODOS LOS FRAMES
const frames = page.frames();
for (const frame of frames) {
try {
const text = await frame.evaluate(() => {
// Selector flexible: busca data-label que contenga "TOTAL"
const el = document.querySelector('td[data-label*="TOTAL"]');
return el ? el.innerText : null;
const data = await frame.evaluate(() => {
let p = "0";
let c = "";
let d = "";
// BUSCAR PRECIO (Prioridad data-label exacto)
const elPrecio = document.querySelector('td[data-label="TOTAL REPARACION:"]') ||
document.querySelector('td[data-label*="TOTAL"]');
if (elPrecio) p = elPrecio.innerText;
// Si no, buscar texto bruto
if (p === "0") {
const all = Array.from(document.querySelectorAll('td, div, span'));
const found = all.find(e => e.innerText && e.innerText.includes("TOTAL REPARACION") && e.innerText.includes("€"));
if(found) p = found.innerText;
}
// BUSCAR CLIENTE/DIRECCION (Para los amarillos)
const bloques = Array.from(document.querySelectorAll('.policy-info-block'));
bloques.forEach(b => {
const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
const v = b.querySelector('.policy-info-value')?.innerText || "";
if (t.includes("CLIENTE")) c = v;
if (t.includes("DIRECCIÓN")) d = v;
});
if (text) {
totalStr = text;
break;
}
} catch(e) { }
}
// 2. Si no encuentra en frames, busca en la página principal (por si acaso)
if (!totalStr) {
const infoPage = await page.evaluate(() => {
const el = document.querySelector('td[data-label*="TOTAL"]');
return el ? el.innerText : "";
return { p, c, d };
});
totalStr = infoPage;
if (data.p && data.p !== "0") {
// Limpieza precio
const cleanMoney = data.p.replace(/[^\d,]/g, '').replace(',', '.');
const val = parseFloat(cleanMoney);
if (val > 0) importe = val;
}
if (data.c) clienteWeb = data.c.trim();
if (data.d) direccionWeb = data.d.trim();
} catch(e) {}
}
// 3. Limpieza precio
if (totalStr) {
const cleanMoney = totalStr.replace(/[^\d,]/g, '').replace(',', '.');
importe = parseFloat(cleanMoney) || 0;
// Si ya tenemos precio, salimos del bucle
if (importe > 0) break;
}
// 4. CONSULTAR BASE DE DATOS
if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} sigue en 0€ tras 5 intentos.`);
// --- CRUCE BD ---
let docId = null;
let enBD = false;
let clienteFinal = "Desconocido";
let direccionFinal = "Sin dirección";
let clienteFinal = clienteWeb;
let direccionFinal = direccionWeb;
if (db) {
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
@ -175,13 +195,12 @@ async function runMultiStream(mes, anio, send) {
const doc = q.docs[0];
docId = doc.id;
enBD = true;
const d = doc.data();
if (d.clientName) clienteFinal = d.clientName;
if (d.address) direccionFinal = d.address;
// Prioridad BD
if (doc.data().clientName) clienteFinal = doc.data().clientName;
if (doc.data().address) direccionFinal = doc.data().address;
}
}
// ENVIAR
send('ITEM_FOUND', {
servicio: idServicio,
direccion: direccionFinal,
@ -228,6 +247,7 @@ async function loginMulti() {
return { browser, page };
}
// ... RESTO IGUAL ...
async function runHSScanner() {
let browser = null;
try {