const express = require('express'); const { chromium } = require('playwright'); const admin = require('firebase-admin'); const cors = require('cors'); // --- CONFIGURACIÓN FIREBASE --- 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; console.log(`🔔 Orden: ${action} [${provider}]`); 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) { console.error("❌ CRASH:", err.message); send('ERROR', err.message); } finally { res.end(); } }); // ================================================================== // 🤖 LÓGICA MULTIASISTENCIA V14 (LECTURA DEEP WAIT) // ================================================================== async function runMultiStream(mes, anio, send) { let browser = null; const valD1 = `${mes}_${anio}`; const valD2 = `${anio}`; try { send('LOG', `🚀 Iniciando MULTI V14 para: ${valD1}`); const { browser: b, page } = await loginMulti(); browser = b; send('LOG', "📂 Yendo a Cerrados..."); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); // Filtro Fecha 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); } // --- 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 => { if (/^\d{8}$/.test(td.innerText.trim())) lista.push(td.innerText.trim()); }); 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(3000); pagActual++; } else { tieneSiguiente = false; } } idsServicios = [...new Set(idsServicios)]; send('LOG', `🔍 Total a revisar: ${idsServicios.length}`); // --- 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 CRÍTICA --- // Esperamos a que aparezca el bloque de cliente o el precio. // Angular tarda en renderizar. Damos hasta 5 segundos extra. try { await page.waitForSelector('div.policy-info-block', { timeout: 6000 }); } catch(e) {} // --- EXTRACCIÓN ROBUSTA --- const info = await page.evaluate(() => { const clean = (t) => t ? t.trim().replace(/\s+/g, ' ') : "Desconocido"; let clienteWeb = "", direccionWeb = "", totalStr = ""; // 1. CLIENTE Y DIRECCIÓN (Buscamos en los bloques azules) const bloques = Array.from(document.querySelectorAll('.policy-info-block')); bloques.forEach(b => { const titulo = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || ""; const valor = b.querySelector('.policy-info-value')?.innerText || ""; if (titulo.includes("CLIENTE")) clienteWeb = valor; if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccionWeb = valor; }); // 2. PRECIO (Buscamos por el atributo data-label exacto que me pasaste) // Primero intentamos el selector preciso const celdaDataLabel = document.querySelector('td[data-label*="TOTAL REPARACION"]'); if (celdaDataLabel) { totalStr = celdaDataLabel.innerText; } else { // Si falla, buscamos cualquier celda que contenga "TOTAL REPARACION" y el símbolo "€" const celdas = Array.from(document.querySelectorAll('td')); const celdaTexto = celdas.find(el => el.innerText.toUpperCase().includes("TOTAL REPARACION") && el.innerText.includes("€")); if (celdaTexto) { // A veces viene sucio "TOTAL REPARACION: 53 €", limpiamos totalStr = celdaTexto.innerText.replace("TOTAL REPARACION", "").replace(":", ""); } } return { clienteWeb: clean(clienteWeb), direccionWeb: clean(direccionWeb), totalStr }; }); // LIMPIEZA DE PRECIO let importe = 0; if (info.totalStr) { // "53,66 €" -> Quitamos todo menos números y comas -> "53,66" -> replace coma por punto -> 53.66 let cleanMoney = info.totalStr.replace(/[^\d,]/g, '').replace(',', '.'); importe = parseFloat(cleanMoney) || 0; } // --- CRUCE CON BASE DE DATOS (PRIORIDAD AL CLIENTE DE LA BD) --- let docId = null; let enBD = false; let clienteFinal = info.clienteWeb; // Por defecto el de la web let direccionFinal = info.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; // ¡AQUÍ ESTÁ EL ARREGLO! // Si tenemos el nombre en la BD, lo usamos en lugar del "Desconocido" de la web si falló const datosBD = doc.data(); if (datosBD.clientName && datosBD.clientName.length > 2) { clienteFinal = datosBD.clientName; } if (datosBD.address && datosBD.address.length > 5) { direccionFinal = datosBD.address; } } } // ENVIAR 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 Y SAVER SE MANTIENEN IGUAL) ... 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}`));