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", HS_LOGIN: "https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS", HS_LIQ: "https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=CONSULTALIQ_WEB" }; const app = express(); app.use(cors({ origin: '*' })); app.use(express.json({ limit: '50mb' })); 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 { if (provider === 'MULTI') { if (action === 'scan') await runMultiStream(month, year, send); else if (action === 'save_data') { const count = await runSaver(dataToSave, 'MULTI'); send('DONE', { count }); } } else { // HOMESERVE if (action === 'scan') { const l = await runHSScanner(); send('HS_DATES', l); } else if (action === 'analyze') { const a = await runHSAnalyzer(url); send('HS_DATA', a); } else if (action === 'save_data') { const c = await runSaver(dataToSave, 'HS'); send('DONE', { count: c }); } } } catch (err) { send('ERROR', err.message); } finally { res.end(); } }); // ================================================================== // 🤖 LÓGICA MULTIASISTENCIA V15 (SOPORTE FRAMES) // ================================================================== async function runMultiStream(mes, anio, send) { let browser = null; const valD1 = `${mes}_${anio}`; const valD2 = `${anio}`; try { send('LOG', `🚀 (MULTI) Iniciando para: ${valD1}`); const { browser: b, page } = await loginMulti(); 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); await page.click('input[name="continuar"]'); await page.waitForTimeout(2500); } // --- FASE 1: RECOLECTAR IDs --- let idsServicios = []; let tieneSiguiente = true; let pagActual = 1; while (tieneSiguiente && pagActual <= 10) { send('LOG', `📄 Leyendo página ${pagActual}...`); const nuevosIds = await page.evaluate(() => { const links = Array.from(document.querySelectorAll('a[href*="reparacion="]')); return links.map(a => { const m = a.href.match(/reparacion=(\d+)/); return m ? m[1] : null; }).filter(id => id && /^\d{8}$/.test(id)); }); 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++; } else { tieneSiguiente = false; } } idsServicios = [...new Set(idsServicios)]; send('LOG', `🔍 Total a revisar: ${idsServicios.length}`); // --- FASE 2: LEER DETALLES (CON FRAMES) --- 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.waitForTimeout(1000); // Esperar renderizado base // === BÚSQUEDA PROFUNDA EN FRAMES === let totalStr = ""; let importe = 0; // 1. Iterar sobre todos los frames (marcos) de la web const frames = page.frames(); for (const frame of frames) { try { // Buscamos el elemento exacto que me pasaste const text = await frame.evaluate(() => { const el = document.querySelector('td[data-label="TOTAL REPARACION:"]'); // Selector exacto return el ? el.innerText : null; }); if (text) { totalStr = text; // "53,66 €" break; // ¡Encontrado! Dejamos de buscar } } catch(e) { /* Error en frame, seguimos al siguiente */ } } // 2. Limpieza del precio if (totalStr) { // "53,66 €" -> "53.66" const cleanMoney = totalStr.replace(/[^\d,]/g, '').replace(',', '.'); importe = parseFloat(cleanMoney) || 0; } // 3. CONSULTAR BASE DE DATOS Y FORZAR NOMBRE let docId = null; let enBD = false; let clienteFinal = "Desconocido"; // Fallback por defecto let direccionFinal = "Sin dirección"; if (db) { const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get(); if (!q.empty) { const doc = q.docs[0]; docId = doc.id; enBD = true; const datosBD = doc.data(); // PRIORIDAD ABSOLUTA A LOS DATOS DE FIREBASE if (datosBD.clientName) clienteFinal = datosBD.clientName; if (datosBD.address) direccionFinal = datosBD.address; } } // ENVIAR (Verde o Amarillo) send('ITEM_FOUND', { servicio: idServicio, direccion: direccionFinal, cliente: clienteFinal, importe: importe, enBD: enBD, docId: docId }); } catch (errDetail) { send('LOG', `⚠️ Error ${idServicio}: ${errDetail.message}`); } } send('FINISH_SCAN', {}); } catch (e) { throw e; } finally { if(browser) await browser.close(); } } async function loginMulti() { 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"); const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); const page = await browser.newPage(); await page.goto(URLS.MULTI_LOGIN, { timeout: 60000 }); 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 }; } // ... RESTO DE FUNCIONES (HS, Saver) NO CAMBIAN ... async function runHSScanner() { let browser = null; try { const { browser: b, page } = await loginHS(); browser = b; const liquidaciones = await page.evaluate(() => { const links = Array.from(document.querySelectorAll('a')); const results = []; links.forEach(l => { const txt = l.innerText.trim(); if (/\d{2}\/\d{2}\/\d{4}/.test(txt)) results.push({ fecha: txt, url: l.href }); }); return results; }); return liquidaciones; } catch (e) { throw e; } finally { if(browser) await browser.close(); } } async function runHSAnalyzer(targetUrl) { let browser = null; try { const { browser: b, page } = await loginHS(); 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 => { const tds = tr.querySelectorAll('td'); if (tds.length >= 6 && /^\d{5,}$/.test(tds[0].innerText.trim())) { return { servicio: tds[0].innerText.trim(), direccion: tds[1].innerText.trim(), saldoRaw: tds[5].innerText.trim() }; } }).filter(Boolean); }); const encontrados = [], noEncontrados = []; if (db) { for (const item of datos) { let importe = Math.abs(parseFloat(item.saldoRaw.replace(/[^\d.-]/g, '')) || 0); const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", item.servicio).get(); if (!q.empty) q.forEach(doc => encontrados.push({ servicio: item.servicio, direccion: item.direccion, importe, docId: doc.id })); else noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe }); } } return { encontrados, noEncontrados }; } catch (e) { throw e; } finally { if(browser) await browser.close(); } } async function loginHS() { let user = "", pass = ""; if (db) { 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 }); if (await page.isVisible('input[name="CODIGO"]')) { await page.fill('input[name="CODIGO"]', user); await page.fill('input[type="password"]', pass); await page.keyboard.press('Enter'); await page.waitForTimeout(4000); } await page.goto(URLS.HS_LIQ); await page.waitForTimeout(2000); return { browser, page }; } async function runSaver(items, providerType) { if (!db) return 0; 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) { const updateData = { paidAmount: item.importe, paymentState: "Pagado", status: 'completed', paymentDate: nowISO, lastUpdatedByRobot: nowISO }; 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; } const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`🚀 Server on port ${PORT}`));