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 (Simplificado) 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 V13 (LECTURA MEJORADA) // ================================================================== async function runMultiStream(mes, anio, send) { let browser = null; const valD1 = `${mes}_${anio}`; const valD2 = `${anio}`; try { send('LOG', `🚀 Iniciando para: ${valD1}`); const { browser: b, page } = await loginMulti(); browser = b; send('LOG', "📂 Yendo a Servicios Cerrados..."); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); 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; }); const unicosPag = [...new Set(nuevosIds)]; idsServicios.push(...unicosPag); send('LOG', ` -> Encontrados ${unicosPag.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: 45000, waitUntil: 'domcontentloaded' }); // Espera crítica para que Angular pinte el precio try { await page.waitForSelector('td[data-label*="TOTAL"]', { timeout: 4000 }); } catch(e){} const info = await page.evaluate(() => { const clean = (t) => t ? t.trim().replace(/\s+/g, ' ') : ""; let cliente = "", direccion = "", totalStr = ""; // 1. BUSCAR DIRECCIÓN Y CLIENTE (Iterando los bloques azules) // Buscamos contenedores que tengan título y valor 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")) cliente = valor; if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccion = valor; }); // 2. BUSCAR PRECIO (Estrategia agresiva) // A) Por atributo data-label (lo más fiable según tu captura) const celdaDataLabel = document.querySelector('td[data-label*="TOTAL REPARACION"]'); if (celdaDataLabel) totalStr = celdaDataLabel.innerText; // B) Si falla, buscar texto visible en cualquier celda if (!totalStr) { const celdas = Array.from(document.querySelectorAll('td, th, div')); const celdaTexto = celdas.find(el => el.innerText && el.innerText.includes("TOTAL REPARACION") && el.innerText.includes("€")); if(celdaTexto) totalStr = celdaTexto.innerText.split("TOTAL")[1] || celdaTexto.innerText; } return { cliente: clean(cliente), direccion: clean(direccion), totalStr }; }); // LIMPIAR PRECIO let importe = 0; if (info.totalStr) { // Quitamos símbolos raros, espacios, letras... dejamos solo números y coma let cleanMoney = info.totalStr.replace(/[^\d,]/g, '').replace(',', '.'); importe = parseFloat(cleanMoney) || 0; } // CONSULTAR BASE DE DATOS (Para saber el color) let docId = null; let enBD = false; let direccionBD = ""; 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; direccionBD = doc.data().address || ""; } } // SI LA WEB NO DA DIRECCIÓN, USAR LA DE LA BD (O viceversa) const direccionFinal = info.direccion && info.direccion.length > 3 ? info.direccion : (direccionBD || "Desconocido"); // ENVIAR send('ITEM_FOUND', { servicio: idServicio, direccion: direccionFinal, cliente: info.cliente, 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 IGUALES) ... 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); // Fallback al servicio si no hay docId (caso nuevo) // Si el documento no existe, lo creamos con lo básico (opcional) // Pero tu petición es guardar importes en servicios existentes. // Si no existe, no hacemos update, o hacemos un set con merge. // Asumo update si existe. 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++; } }); // Solo hacemos commit de lo que está en BD if(count > 0) await batch.commit(); return count; } const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`🚀 Server on port ${PORT}`));