diff --git a/robot_cobros.js b/robot_cobros.js index 0365938..3e9a9cb 100644 --- a/robot_cobros.js +++ b/robot_cobros.js @@ -1,97 +1,181 @@ +// ARCHIVO: robot_cobros.js +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 + */ +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 +// ================================================================ +function parseEuro(raw) { + if (!raw) return 0; + const clean = String(raw).replace(/[^\d,]/g, '').replace(',', '.'); + const val = parseFloat(clean); + return Number.isFinite(val) ? val : 0; +} + +async function getTotalReparacion(page) { + const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]'; + + // 1) 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) ShadowRoots traverse + 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 (SELECTOR INTELIGENTE) +// MULTI SCAN (INTELIGENTE) // ================================================================== async function runMultiStream(mes, anio, send) { let browser = null; - - // Limpieza básica const yyyy = String(anio || ''); - const mesNum = parseInt(mes, 10); // Ejemplo: convierte "01" a 1 + const mesNum = parseInt(mes, 10); if (isNaN(mesNum) || !/^\d{4}$/.test(yyyy)) { - throw new Error("Mes o Año inválidos. Ejemplo correcto: month='01', year='2026'."); + throw new Error("Mes o Año inválidos. Ejemplo: month='01', year='2026'."); } - // 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" + const nombresMeses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]; + const nombreMes = nombresMeses[mesNum - 1]; try { - send('LOG', `🚀 (MULTI) Iniciando scan: ${nombreMes.toUpperCase()} ${yyyy}`); - - // Login + send('LOG', `🚀 (MULTI) Scan inteligente: ${nombreMes.toUpperCase()} ${yyyy}`); const { browser: b, page } = await loginMulti(send); browser = b; send('LOG', "📂 Yendo a Cerrados..."); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); - // --- LÓGICA INTELIGENTE PARA EL DESPLEGABLE D1 --- + // --- SELECCIÓN INTELIGENTE --- 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 + const txt = op.text.toLowerCase(); + const val = op.value; + // Debe coincidir el año y (el mes en texto o el mes en numero) + if ((txt.includes(y) || val.includes(y)) && + (txt.includes(name) || val.startsWith(m + '_') || val.startsWith('0' + m + '_'))) { + return op.value; } } return null; }, { sel: selectorD1, m: mesNum, y: yyyy, name: nombreMes }); if (valorASeleccionar) { - send('LOG', `✅ Opción encontrada: "${valorASeleccionar}". Seleccionando...`); + send('LOG', `✅ Opción encontrada: "${valorASeleccionar}"`); await page.selectOption(selectorD1, valorASeleccionar); } else { - throw new Error(`❌ No encontré ninguna opción en el desplegable para ${nombreMes} del ${yyyy}`); + throw new Error(`❌ No encontré opción para ${nombreMes} ${yyyy}`); } - // Seleccionar D2 (Año) si existe, por seguridad + // Año D2 if (await page.isVisible('select[name="D2"]')) { await page.selectOption('select[name="D2"]', yyyy).catch(() => {}); } await page.click('input[name="continuar"]'); - await page.waitForTimeout(3000); + await page.waitForTimeout(2500); } else { - send('LOG', "⚠️ No veo el filtro D1 (¿cambió la página?)."); + send('LOG', "⚠️ No veo el filtro D1."); } - // --- (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 --- - + // --- FASE 1: IDs --- let idsServicios = []; let tieneSiguiente = true; let pagActual = 1; + while (tieneSiguiente && pagActual <= 10) { - send('LOG', `📄 Leyendo página ${pagActual}...`); + send('LOG', `📄 Leyendo pág ${pagActual}...`); const nuevosIds = await page.evaluate(() => { const celdas = Array.from(document.querySelectorAll('td.tdet')); const lista = []; @@ -102,7 +186,8 @@ async function runMultiStream(mes, anio, send) { return lista; }); idsServicios.push(...[...new Set(nuevosIds)]); - send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`); + send('LOG', ` -> +${nuevosIds.length} servicios.`); + const haySiguiente = await page.$('a:has-text("Página siguiente")'); if (haySiguiente) { await haySiguiente.click(); @@ -112,25 +197,31 @@ async function runMultiStream(mes, anio, send) { tieneSiguiente = false; } } + idsServicios = [...new Set(idsServicios)]; - send('LOG', `🔍 Total a revisar: ${idsServicios.length}`); + send('LOG', `🔍 Total único: ${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' }); await page.waitForSelector('multiasistencia-valoraciones', { timeout: 12000 }).catch(() => {}); + let clienteWeb = "Desconocido"; let direccionWeb = "Sin dirección"; + for (const frame of page.frames()) { try { const data = await frame.evaluate(() => { - let c = ""; - let d = ""; + let c = "", d = ""; const bloques = Array.from(document.querySelectorAll('.policy-info-block')); bloques.forEach(b => { const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || ""; @@ -144,14 +235,18 @@ async function runMultiStream(mes, anio, send) { if (data.d) direccionWeb = data.d.trim(); } catch {} } + const importe = await getTotalReparacion(page); - if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} en 0€ (no encontrado).`); + if (importe === 0) send('LOG', `⚠️ ${idServicio} tiene importe 0.`); + + // Cruce DB let docId = null; let enBD = false; let clienteFinal = clienteWeb; let direccionFinal = direccionWeb; + if (db) { - const q = await db.collection("appointments").where("serviceNumber", "==", idServicio).get(); + const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get(); if (!q.empty) { const doc = q.docs[0]; docId = doc.id; @@ -160,6 +255,7 @@ async function runMultiStream(mes, anio, send) { if (doc.data().address) direccionFinal = doc.data().address; } } + send('ITEM_FOUND', { servicio: idServicio, direccion: direccionFinal, @@ -177,4 +273,74 @@ async function runMultiStream(mes, anio, send) { } finally { if (browser) await browser.close().catch(()=>{}); } -} \ No newline at end of file +} + +async function loginMulti(send) { + let user = "", pass = ""; + if (db) { + // Busca en la colección 'providerCredentials', documento 'multiasistencia' + 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. CREA EL DOC EN FIRESTORE: 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 +// ================================================================== +async function runSaver(items, send) { + if (!db) return 0; + const batch = db.batch(); + const nowISO = new Date().toISOString(); + let count = 0; + + (items || []).forEach(item => { + 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.`); + } else { + send && send('LOG', '💾 Nada que guardar.'); + } + 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