diff --git a/robot_cobros.js b/robot_cobros.js index cb5a487..1cccf2f 100644 --- a/robot_cobros.js +++ b/robot_cobros.js @@ -1,165 +1,94 @@ -const express = require('express'); -const { chromium } = require('playwright'); -const admin = require('firebase-admin'); -const cors = require('cors'); - -// --- FIREBASE INIT --- -try { - if (process.env.FIREBASE_PRIVATE_KEY) { - if (!admin.apps.length) { - admin.initializeApp({ - credential: admin.credential.cert({ - projectId: process.env.FIREBASE_PROJECT_ID, - clientEmail: process.env.FIREBASE_CLIENT_EMAIL, - privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'), - }), - }); - } - console.log("✅ Firebase inicializado."); - } -} catch (e) { - console.error("❌ Error Firebase:", e.message); -} - -const db = admin.apps.length ? admin.firestore() : null; -const APPOINTMENTS_COL = "appointments"; - -const URLS = { - MULTI_LOGIN: "https://web.multiasistencia.com/w3multi/acceso.php", - MULTI_LIST: "https://web.multiasistencia.com/w3multi/cerrados.php", -}; - -const app = express(); -app.use(cors({ origin: '*' })); -app.use(express.json({ limit: '50mb' })); - -/** - * Endpoint streaming NDJSON: - * - provider: "MULTI" - * - action: "scan" | "save_data" - * - * Respuestas por línea: - * {type:"LOG", payload:"..."} - * {type:"PROGRESS", payload:{current,total}} - * {type:"ITEM_FOUND", payload:{servicio,direccion,cliente,importe,enBD,docId}} - * {type:"FINISH_SCAN", payload:{}} - * {type:"DONE", payload:{count}} - * {type:"ERROR", payload:"mensaje"} - */ -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, provider, dataToSave, month, year } = req.body; - - try { - if (provider !== 'MULTI') throw new Error("Provider inválido. Usa provider='MULTI'."); - - if (action === 'scan') { - await runMultiStream(month, year, send); - } else if (action === 'save_data') { - const count = await runSaver(dataToSave, send); - send('DONE', { count }); - } else { - throw new Error("Acción inválida. Usa action='scan' o action='save_data'."); - } - } catch (err) { - send('ERROR', err.message); - } finally { - res.end(); - } -}); - -// ================================================================ -// Helpers MONEY + TOTAL REPARACION (Shadow DOM) -// ================================================================ - -function parseEuro(raw) { - if (!raw) return 0; - // "53,66 €" -> 53.66 - const clean = String(raw).replace(/[^\d,]/g, '').replace(',', '.'); - const val = parseFloat(clean); - return Number.isFinite(val) ? val : 0; -} - -async function getTotalReparacion(page) { - // Selector "deep" (Shadow DOM) con Playwright - const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]'; - - // 1) prueba en frames - 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: traversal shadowRoots abiertos - 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; - } - return findIn(document); - }); - - return parseEuro(raw2); -} - // ================================================================== -// MULTI SCAN +// MULTI SCAN (SELECTOR INTELIGENTE) // ================================================================== - async function runMultiStream(mes, anio, send) { let browser = null; - const mm = String(mes || '').padStart(2, '0'); + + // Limpieza básica const yyyy = String(anio || ''); - if (!/^\d{2}$/.test(mm) || !/^\d{4}$/.test(yyyy)) throw new Error("month/year inválidos. Ej: month='01', year='2025'."); + const mesNum = parseInt(mes, 10); // Ejemplo: convierte "01" a 1 + + if (isNaN(mesNum) || !/^\d{4}$/.test(yyyy)) { + throw new Error("Mes o Año inválidos. Ejemplo correcto: month='01', year='2026'."); + } - const valD1 = `${mm}_${yyyy}`; - const valD2 = `${yyyy}`; + // Mapa de meses para buscar por texto si falla el número + const nombresMeses = [ + "enero", "febrero", "marzo", "abril", "mayo", "junio", + "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" + ]; + const nombreMes = nombresMeses[mesNum - 1]; // "enero" try { - send('LOG', `🚀 (MULTI) Iniciando scan: ${valD1}`); - + send('LOG', `🚀 (MULTI) Iniciando scan: ${nombreMes.toUpperCase()} ${yyyy}`); + + // Login const { browser: b, page } = await loginMulti(send); browser = b; send('LOG', "📂 Yendo a Cerrados..."); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); - // Filtro - if (await page.isVisible('select[name="D1"]')) { - await page.selectOption('select[name="D1"]', valD1); - await page.selectOption('select[name="D2"]', valD2); + // --- LÓGICA INTELIGENTE PARA EL DESPLEGABLE D1 --- + const selectorD1 = 'select[name="D1"]'; + + if (await page.isVisible(selectorD1)) { + + // Ejecutamos código DENTRO del navegador para encontrar la opción correcta + const valorASeleccionar = await page.evaluate(({ sel, m, y, name }) => { + const select = document.querySelector(sel); + if (!select) return null; + + // Buscamos entre todas las opciones + for (const op of select.options) { + const txt = op.text.toLowerCase(); // Lo que ve el usuario (ej: "Enero 2026") + const val = op.value; // El valor interno (ej: "1_2026") + + // Criterio 1: Que contenga el año + if (!txt.includes(y) && !val.includes(y)) continue; + + // Criterio 2: Que coincida el mes (por número 1, 01 o por nombre "enero") + // Verificamos si el texto contiene "enero" O si el valor empieza por "1_" o "01_" + const mesMatchTexto = txt.includes(name); + const mesMatchValor = val.startsWith(m + '_') || val.startsWith('0' + m + '_'); + + if (mesMatchTexto || mesMatchValor) { + return op.value; // ¡Encontrado! Devolvemos el valor exacto que necesita la web + } + } + return null; + }, { sel: selectorD1, m: mesNum, y: yyyy, name: nombreMes }); + + if (valorASeleccionar) { + send('LOG', `✅ Opción encontrada: "${valorASeleccionar}". Seleccionando...`); + await page.selectOption(selectorD1, valorASeleccionar); + } else { + throw new Error(`❌ No encontré ninguna opción en el desplegable para ${nombreMes} del ${yyyy}`); + } + + // Seleccionar D2 (Año) si existe, por seguridad + if (await page.isVisible('select[name="D2"]')) { + await page.selectOption('select[name="D2"]', yyyy).catch(() => {}); + } + await page.click('input[name="continuar"]'); - await page.waitForTimeout(2500); + await page.waitForTimeout(3000); + } else { - send('LOG', "⚠️ No veo el filtro D1/D2 (¿cambió la página?)."); + send('LOG', "⚠️ No veo el filtro D1 (¿cambió la página?)."); } - // --- FASE 1: IDS --- + // --- (EL RESTO DEL CÓDIGO SIGUE IGUAL: FASE 1 IDs y FASE 2 DETALLES) --- + // Copia aquí el bloque "FASE 1: IDS" y "FASE 2: DETALLES" de tu código anterior + // ... + // ... + // (Para no hacer el mensaje eterno, asumo que mantienes el resto igual) + + // --- PEGA ESTO JUSTO DESPUÉS DEL IF DEL SELECTOR --- + let idsServicios = []; let tieneSiguiente = true; let pagActual = 1; - while (tieneSiguiente && pagActual <= 10) { send('LOG', `📄 Leyendo página ${pagActual}...`); const nuevosIds = await page.evaluate(() => { @@ -171,10 +100,8 @@ async function runMultiStream(mes, anio, send) { }); return lista; }); - 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(); @@ -184,31 +111,20 @@ async function runMultiStream(mes, anio, send) { tieneSiguiente = false; } } - idsServicios = [...new Set(idsServicios)]; send('LOG', `🔍 Total a revisar: ${idsServicios.length}`); - if (idsServicios.length === 0) { send('FINISH_SCAN', {}); return; } - - // --- FASE 2: 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(() => {}); - let clienteWeb = "Desconocido"; let direccionWeb = "Sin dirección"; - - // Cliente/dirección (policy-info-block) for (const frame of page.frames()) { try { const data = await frame.evaluate(() => { @@ -227,30 +143,22 @@ async function runMultiStream(mes, anio, send) { if (data.d) direccionWeb = data.d.trim(); } catch {} } - - // ✅ IMPORTE (una sola lectura) const importe = await getTotalReparacion(page); if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} en 0€ (no encontrado).`); - - // --- CRUCE Firestore --- let docId = null; let enBD = false; let clienteFinal = clienteWeb; let direccionFinal = direccionWeb; - if (db) { - const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get(); + const q = await db.collection("appointments").where("serviceNumber", "==", idServicio).get(); if (!q.empty) { const doc = q.docs[0]; docId = doc.id; enBD = true; - - // Prioridad Firestore if (doc.data().clientName) clienteFinal = doc.data().clientName; if (doc.data().address) direccionFinal = doc.data().address; } } - send('ITEM_FOUND', { servicio: idServicio, direccion: direccionFinal, @@ -259,88 +167,13 @@ async function runMultiStream(mes, anio, send) { enBD, docId }); - } catch (errDetail) { send('LOG', `⚠️ Error ${idServicio}: ${errDetail.message}`); } } - send('FINISH_SCAN', {}); + } finally { if (browser) await browser.close().catch(()=>{}); } -} - -async function loginMulti(send) { - let user = "", pass = ""; - - if (db) { - const doc = await db.collection("providerCredentials").doc("multiasistencia").get(); - if (doc.exists) { user = doc.data().user; pass = doc.data().pass; } - } - if (!user) throw new Error("Faltan credenciales (providerCredentials/multiasistencia)"); - - send('LOG', '🔐 Login en Multiasistencia…'); - - const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); - const page = await browser.newPage(); - - await page.goto(URLS.MULTI_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' }); - - const userFilled = await page.evaluate((u) => { - const el = document.querySelector('input[name="usuario"]') || document.querySelector('input[type="text"]'); - if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; } - return false; - }, user); - - if (!userFilled) await page.fill('input[name="usuario"]', user); - await page.fill('input[type="password"]', pass); - await page.click('input[type="submit"]'); - await page.waitForTimeout(4000); - - return { browser, page }; -} - -// ================================================================== -// SAVE: marca pagado por transferencia + importe (SOLO si existe docId) -// ================================================================== - -async function runSaver(items, send) { - if (!db) return 0; - - const batch = db.batch(); - const nowISO = new Date().toISOString(); - let count = 0; - - (items || []).forEach(item => { - // Ultra-seguro: si no hay docId, NO guardamos (no existe en Marsalva) - if (!item || !item.docId) return; - - const ref = db.collection(APPOINTMENTS_COL).doc(item.docId); - - batch.update(ref, { - paidAmount: Number(item.importe || 0), - paymentState: "Pagado", - paymentMethod: "transferencia", - paymentType: "transferencia", - status: "completed", - paymentDate: nowISO, - lastUpdatedByRobot: nowISO, - multiasistenciaPaymentStatus: "paid_transfer" - }); - - count++; - }); - - if (count > 0) { - await batch.commit(); - send && send('LOG', `💾 Guardados ${count} servicios (transferencia).`); - } else { - send && send('LOG', '💾 Nada que guardar (0 servicios con docId).'); - } - - return count; -} - -const PORT = process.env.PORT || 3000; -app.listen(PORT, () => console.log(`🚀 MULTI robot server on port ${PORT}`)); \ No newline at end of file +} \ No newline at end of file