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) { async function runMultiStream(mes, anio, send) {
@ -68,7 +68,7 @@ async function runMultiStream(mes, anio, send) {
const valD2 = `${anio}`; const valD2 = `${anio}`;
try { try {
send('LOG', `🚀 (MULTI V16) Iniciando para: ${valD1}`); send('LOG', `🚀 (MULTI V17) Iniciando Bulldog: ${valD1}`);
const { browser: b, page } = await loginMulti(); const { browser: b, page } = await loginMulti();
browser = b; browser = b;
@ -80,32 +80,28 @@ async function runMultiStream(mes, anio, send) {
await page.selectOption('select[name="D1"]', valD1); await page.selectOption('select[name="D1"]', valD1);
await page.selectOption('select[name="D2"]', valD2); await page.selectOption('select[name="D2"]', valD2);
await page.click('input[name="continuar"]'); 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 idsServicios = [];
let tieneSiguiente = true; let tieneSiguiente = true;
let pagActual = 1; let pagActual = 1;
while (tieneSiguiente && pagActual <= 10) { while (tieneSiguiente && pagActual <= 10) {
send('LOG', `📄 Leyendo página ${pagActual}...`); send('LOG', `📄 Leyendo página ${pagActual}...`);
// BUSCAR TEXTO EN CELDAS (NO SOLO ENLACES)
const nuevosIds = await page.evaluate(() => { const nuevosIds = await page.evaluate(() => {
const celdas = Array.from(document.querySelectorAll('td.tdet')); const celdas = Array.from(document.querySelectorAll('td.tdet'));
const lista = []; const lista = [];
celdas.forEach(td => { celdas.forEach(td => {
const txt = td.innerText.trim(); const txt = td.innerText.trim();
// Buscamos cualquier número de 8 cifras
if (/^\d{8}$/.test(txt)) lista.push(txt); if (/^\d{8}$/.test(txt)) lista.push(txt);
}); });
return lista; return lista;
}); });
const unicosPag = [...new Set(nuevosIds)]; idsServicios.push(...[...new Set(nuevosIds)]);
idsServicios.push(...unicosPag); send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`);
send('LOG', ` -> Encontrados ${unicosPag.length} servicios.`);
const haySiguiente = await page.$('a:has-text("Página siguiente")'); const haySiguiente = await page.$('a:has-text("Página siguiente")');
if (haySiguiente) { await haySiguiente.click(); await page.waitForTimeout(3000); pagActual++; } 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: [] }; 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()) { for (const [index, idServicio] of idsServicios.entries()) {
send('PROGRESS', { current: index + 1, total: idsServicios.length }); send('PROGRESS', { current: index + 1, total: idsServicios.length });
@ -125,49 +121,73 @@ async function runMultiStream(mes, anio, send) {
try { try {
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' }); await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
await page.waitForTimeout(1500); // Esperar renderizado
// === BÚSQUEDA PROFUNDA EN FRAMES ===
let totalStr = "";
let importe = 0;
// 1. Iterar sobre todos los frames let importe = 0;
const frames = page.frames(); let clienteWeb = "Desconocido";
for (const frame of frames) { let direccionWeb = "Sin dirección";
try {
const text = await frame.evaluate(() => { // --- MODO BULLDOG: INTENTAR HASTA 5 VECES SI EL PRECIO ES 0 ---
// Selector flexible: busca data-label que contenga "TOTAL" let intentos = 0;
const el = document.querySelector('td[data-label*="TOTAL"]'); while (intentos < 5 && importe === 0) {
return el ? el.innerText : null; intentos++;
}); if(intentos > 1) await page.waitForTimeout(1500); // Esperar entre intentos
if (text) { // 1. ESCANEAR TODOS LOS FRAMES
totalStr = text; const frames = page.frames();
break; for (const frame of frames) {
} try {
} catch(e) { } 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;
});
return { p, c, d };
});
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) {}
}
// Si ya tenemos precio, salimos del bucle
if (importe > 0) break;
} }
// 2. Si no encuentra en frames, busca en la página principal (por si acaso) if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} sigue en 0€ tras 5 intentos.`);
if (!totalStr) {
const infoPage = await page.evaluate(() => {
const el = document.querySelector('td[data-label*="TOTAL"]');
return el ? el.innerText : "";
});
totalStr = infoPage;
}
// 3. Limpieza precio // --- CRUCE BD ---
if (totalStr) {
const cleanMoney = totalStr.replace(/[^\d,]/g, '').replace(',', '.');
importe = parseFloat(cleanMoney) || 0;
}
// 4. CONSULTAR BASE DE DATOS
let docId = null; let docId = null;
let enBD = false; let enBD = false;
let clienteFinal = "Desconocido"; let clienteFinal = clienteWeb;
let direccionFinal = "Sin dirección"; let direccionFinal = direccionWeb;
if (db) { if (db) {
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get(); 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]; const doc = q.docs[0];
docId = doc.id; docId = doc.id;
enBD = true; enBD = true;
const d = doc.data(); // Prioridad BD
if (d.clientName) clienteFinal = d.clientName; if (doc.data().clientName) clienteFinal = doc.data().clientName;
if (d.address) direccionFinal = d.address; if (doc.data().address) direccionFinal = doc.data().address;
} }
} }
// ENVIAR
send('ITEM_FOUND', { send('ITEM_FOUND', {
servicio: idServicio, servicio: idServicio,
direccion: direccionFinal, direccion: direccionFinal,
@ -228,6 +247,7 @@ async function loginMulti() {
return { browser, page }; return { browser, page };
} }
// ... RESTO IGUAL ...
async function runHSScanner() { async function runHSScanner() {
let browser = null; let browser = null;
try { try {