From 194f732aa7e16353a9ec321ce32a1f1ee0e2103d Mon Sep 17 00:00:00 2001 From: marsalva Date: Tue, 30 Dec 2025 22:40:51 +0000 Subject: [PATCH] Actualizar robot_cobros.js --- robot_cobros.js | 112 +++++++++++++++++------------------------------- 1 file changed, 39 insertions(+), 73 deletions(-) diff --git a/robot_cobros.js b/robot_cobros.js index 58d5d74..87e28c8 100644 --- a/robot_cobros.js +++ b/robot_cobros.js @@ -39,7 +39,6 @@ app.post('/api/robot-cobros', async (req, res) => { res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.setHeader('Transfer-Encoding', 'chunked'); const send = (type, payload) => res.write(JSON.stringify({ type, payload }) + "\n"); - const { action, url, provider, dataToSave, month, year } = req.body; try { @@ -65,7 +64,6 @@ app.post('/api/robot-cobros', async (req, res) => { // ================================================================ // Helpers MONEY + TOTAL REPARACION (Shadow DOM) // ================================================================ - function parseEuro(raw) { if (!raw) return 0; // "53,66 €" -> 53.66 @@ -75,58 +73,41 @@ function parseEuro(raw) { } async function getTotalReparacion(page) { - // Selector deep: atraviesa Shadow DOM + // EL SELECTOR MÁGICO: ">>>" atraviesa el Shadow DOM automáticamente const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]'; - - // 1) prueba en frames por si lo meten dentro - for (const frame of page.frames()) { - try { - const loc = frame.locator(deepSel).first(); - await loc.waitFor({ state: 'attached', timeout: 6000 }); - const raw = await loc.innerText(); - const val = parseEuro(raw); - if (val > 0) return val; - } catch {} - } - - // 2) fallback: búsqueda manual por shadowRoots abiertos (por si cambian el componente) - const raw2 = await page.evaluate(() => { - const seen = new Set(); - - function findIn(root) { - if (!root || seen.has(root)) return null; - seen.add(root); - - const td = root.querySelector?.('td[data-label^="TOTAL REPARACION"]'); - if (td) return td.innerText; - - const els = root.querySelectorAll ? Array.from(root.querySelectorAll('*')) : []; - for (const el of els) { - if (el.shadowRoot) { - const hit = findIn(el.shadowRoot); - if (hit) return hit; - } - } - return null; + + try { + // Locator de Playwright ya espera automáticamente a que el elemento aparezca + const loc = page.locator(deepSel).first(); + // Le damos hasta 5 segundos para aparecer, si no, asumimos 0€ + await loc.waitFor({ state: 'attached', timeout: 5000 }); + const raw = await loc.innerText(); + return parseEuro(raw); + } catch (e) { + // Si falla el locator principal, intentamos buscar en frames por seguridad + for (const frame of page.frames()) { + try { + const locFrame = frame.locator(deepSel).first(); + await locFrame.waitFor({ state: 'attached', timeout: 2000 }); + const rawFrame = await locFrame.innerText(); + const val = parseEuro(rawFrame); + if (val > 0) return val; + } catch {} } - - return findIn(document); - }); - - return parseEuro(raw2); + return 0; // Si falla todo, es 0 + } } // ================================================================== -// 🤖 LÓGICA MULTIASISTENCIA V17 (MODO BULLDOG) +// 🤖 LÓGICA MULTIASISTENCIA (OPTIMIZADA) // ================================================================== - async function runMultiStream(mes, anio, send) { let browser = null; const valD1 = `${mes}_${anio}`; const valD2 = `${anio}`; try { - send('LOG', `🚀 (MULTI V17) Iniciando Bulldog: ${valD1}`); + send('LOG', `🚀 (MULTI) Iniciando rápido: ${valD1}`); const { browser: b, page } = await loginMulti(); browser = b; @@ -138,7 +119,7 @@ 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(2500); + await page.waitForTimeout(2000); // Pequeña espera técnica para que recargue la tabla } // --- FASE 1: RECOLECTAR IDs --- @@ -162,8 +143,13 @@ async function runMultiStream(mes, anio, send) { 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++; } - else { tieneSiguiente = false; } + if (haySiguiente) { + await haySiguiente.click(); + await page.waitForTimeout(2500); + pagActual++; + } else { + tieneSiguiente = false; + } } idsServicios = [...new Set(idsServicios)]; @@ -174,19 +160,17 @@ async function runMultiStream(mes, anio, send) { // --- FASE 2: LEER DETALLES --- for (const [index, idServicio] of idsServicios.entries()) { send('PROGRESS', { current: index + 1, total: idsServicios.length }); - + const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`; try { await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' }); - // espera suave al componente (si existe) - await page.waitForSelector('multiasistencia-valoraciones', { timeout: 12000 }).catch(() => {}); - + // 1. OBTENER DATOS CLIENTE (Esto suele estar disponible rápido) let clienteWeb = "Desconocido"; let direccionWeb = "Sin dirección"; - // cliente/dirección los sigues sacando igual (si algún día también cae en shadow, lo ajustamos) + // Intentamos leer cliente de los frames (por si acaso) const frames = page.frames(); for (const frame of frames) { try { @@ -207,18 +191,10 @@ async function runMultiStream(mes, anio, send) { } catch {} } - // ✅ IMPORTE: ahora sí, Shadow DOM friendly - let importe = 0; - let intentos = 0; - while (intentos < 5 && importe === 0) { - intentos++; - if (intentos > 1) await page.waitForTimeout(1200); - importe = await getTotalReparacion(page); - } + // 2. OBTENER IMPORTE (Sin bucles, confiando en el selector inteligente) + const importe = await getTotalReparacion(page); - if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} sigue en 0€ tras 5 intentos.`); - - // --- CRUCE BD --- + // 3. CRUCE BD let docId = null; let enBD = false; let clienteFinal = clienteWeb; @@ -230,6 +206,7 @@ async function runMultiStream(mes, anio, send) { const doc = q.docs[0]; docId = doc.id; enBD = true; + // Priorizamos datos de Firebase si existen if (doc.data().clientName) clienteFinal = doc.data().clientName; if (doc.data().address) direccionFinal = doc.data().address; } @@ -286,9 +263,8 @@ async function loginMulti() { } // ================================================================== -// ... RESTO IGUAL ... +// ... RESTO IGUAL (HOMESERVE + SAVER) ... // ================================================================== - async function runHSScanner() { let browser = null; try { @@ -314,16 +290,13 @@ async function runHSAnalyzer(targetUrl) { browser = b; await page.goto(targetUrl, { timeout: 60000 }); await page.waitForTimeout(1500); - const botonPulsado = await page.evaluate(() => { const el = Array.from(document.querySelectorAll('input, button, a')) .find(el => (el.value || el.innerText || "").toUpperCase().includes("DESGLOSE")); if (el) { el.click(); return true; } return false; }); - if (botonPulsado) await page.waitForTimeout(3000); - const datos = await page.evaluate(() => { const rows = Array.from(document.querySelectorAll('tr')); return rows.map(tr => { @@ -333,7 +306,6 @@ async function runHSAnalyzer(targetUrl) { } }).filter(Boolean); }); - const encontrados = [], noEncontrados = []; if (db) { for (const item of datos) { @@ -353,10 +325,8 @@ async function loginHS() { const doc = await db.collection("providerCredentials").doc("homeserve").get(); if (doc.exists) { user = doc.data().user; pass = doc.data().pass; } } - const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); const page = await browser.newPage(); - await page.goto(URLS.HS_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' }); if (await page.isVisible('input[name="CODIGO"]')) { await page.fill('input[name="CODIGO"]', user); @@ -366,7 +336,6 @@ async function loginHS() { } await page.goto(URLS.HS_LIQ, { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2000); - return { browser, page }; } @@ -375,7 +344,6 @@ async function runSaver(items, providerType) { const batch = db.batch(); const nowISO = new Date().toISOString(); let count = 0; - items.forEach(item => { const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio); if (item.enBD || item.docId) { @@ -388,12 +356,10 @@ async function runSaver(items, providerType) { }; if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified'; else updateData.homeservePaymentStatus = 'paid_saldo'; - batch.update(ref, updateData); count++; } }); - if (count > 0) await batch.commit(); return count; }