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(); } }); // ================================================================ // Helpers MONEY + TOTAL REPARACION (Shadow DOM) // ================================================================ function parseEuro(raw) { if (!raw) return 0; // "53,66 €" -> 53.66 const clean = raw.replace(/[^\d,]/g, '').replace(',', '.'); const val = parseFloat(clean); return Number.isFinite(val) ? val : 0; } async function getTotalReparacion(page) { // EL SELECTOR MÁGICO: ">>>" atraviesa el Shadow DOM automáticamente const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]'; 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 0; // Si falla todo, es 0 } } // ================================================================== // 🤖 LÓGICA MULTIASISTENCIA (OPTIMIZADA) // ================================================================== async function runMultiStream(mes, anio, send) { let browser = null; const valD1 = `${mes}_${anio}`; const valD2 = `${anio}`; try { send('LOG', `🚀 (MULTI) Iniciando rápido: ${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(2000); // Pequeña espera técnica para que recargue la tabla } // --- 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 celdas = Array.from(document.querySelectorAll('td.tdet')); const lista = []; celdas.forEach(td => { const txt = td.innerText.trim(); if (/^\d{8}$/.test(txt)) lista.push(txt); }); 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(); await page.waitForTimeout(2500); pagActual++; } else { tieneSiguiente = false; } } idsServicios = [...new Set(idsServicios)]; send('LOG', `🔍 Total a revisar: ${idsServicios.length}`); if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] }; // --- 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' }); // 1. OBTENER DATOS CLIENTE (Esto suele estar disponible rápido) let clienteWeb = "Desconocido"; let direccionWeb = "Sin dirección"; // Intentamos leer cliente de los frames (por si acaso) const frames = page.frames(); for (const frame of frames) { try { const data = await frame.evaluate(() => { let c = ""; let d = ""; 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 { c, d }; }); if (data.c) clienteWeb = data.c.trim(); if (data.d) direccionWeb = data.d.trim(); } catch {} } // 2. OBTENER IMPORTE (Sin bucles, confiando en el selector inteligente) const importe = await getTotalReparacion(page); // 3. CRUCE BD 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(); if (!q.empty) { 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; } } 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, 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 }; } // ================================================================== // ... RESTO IGUAL (HOMESERVE + SAVER) ... // ================================================================== 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, waitUntil: 'domcontentloaded' }); 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, { waitUntil: 'domcontentloaded' }); 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}`));