Actualizar robot_cobros.js

This commit is contained in:
marsalva 2025-12-30 21:40:05 +00:00
parent efa47f360f
commit d6a9efa2bd
1 changed files with 43 additions and 336 deletions

View File

@ -1,343 +1,50 @@
const express = require('express'); function parseEuro(raw) {
const { chromium } = require('playwright'); if (!raw) return 0;
const admin = require('firebase-admin'); const clean = raw.replace(/[^\d,]/g, "").replace(",", ".");
const cors = require('cors'); const val = parseFloat(clean);
return Number.isFinite(val) ? val : 0;
}
// --- FIREBASE INIT --- async function getTotalReparacion(page) {
// Selector “deep” que atraviesa Shadow DOM
const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]';
// 1) Intenta en todos los frames (por si la web lo mete en alguno)
for (const frame of page.frames()) {
try { try {
if (process.env.FIREBASE_PRIVATE_KEY) { const loc = frame.locator(deepSel).first();
if (!admin.apps.length) { await loc.waitFor({ state: "attached", timeout: 8000 });
admin.initializeApp({ const raw = await loc.innerText();
credential: admin.credential.cert({ const val = parseEuro(raw);
projectId: process.env.FIREBASE_PROJECT_ID, if (val > 0) return val;
clientEmail: process.env.FIREBASE_CLIENT_EMAIL, } catch {}
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
}),
});
} }
console.log("✅ Firebase inicializado.");
// 2) Fallback: búsqueda profunda recorriendo shadowRoots abiertos (por si cambia el HTML)
const raw2 = await page.evaluate(() => {
const seen = new Set();
function findIn(root) {
if (!root || seen.has(root)) return null;
seen.add(root);
// busca el td por data-label
const td = root.querySelector?.('td[data-label^="TOTAL REPARACION"]');
if (td) return td.innerText;
// recorre hijos y sus shadowRoots
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;
} }
} 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 { return null;
// 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); return findIn(document);
} finally { res.end(); }
}); });
// ================================================================== return parseEuro(raw2);
// 🤖 LÓGICA MULTIASISTENCIA V17 (MODO BULLDOG)
// ==================================================================
async function runMultiStream(mes, anio, send) {
let browser = null;
const valD1 = `${mes}_${anio}`;
const valD2 = `${anio}`;
try {
send('LOG', `🚀 (MULTI V17) Iniciando Bulldog: ${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 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(3000); 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 (BUCLE DE REINTENTOS) ---
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' });
let importe = 0;
let clienteWeb = "Desconocido";
let direccionWeb = "Sin dirección";
// --- MODO BULLDOG: INTENTAR HASTA 5 VECES SI EL PRECIO ES 0 ---
let intentos = 0;
while (intentos < 5 && importe === 0) {
intentos++;
if(intentos > 1) await page.waitForTimeout(1500); // Esperar entre intentos
// 1. ESCANEAR TODOS LOS FRAMES
const frames = page.frames();
for (const frame of frames) {
try {
const data = await frame.evaluate(() => {
let p = "0";
let c = "";
let d = "";
// BUSCAR PRECIO (Prioridad data-label exacto)
const elPrecio = document.querySelector('td[data-label="TOTAL REPARACION:"]') ||
document.querySelector('td[data-label*="TOTAL"]');
if (elPrecio) p = elPrecio.innerText;
// Si no, buscar texto bruto
if (p === "0") {
const all = Array.from(document.querySelectorAll('td, div, span'));
const found = all.find(e => e.innerText && e.innerText.includes("TOTAL REPARACION") && e.innerText.includes("€"));
if(found) p = found.innerText;
}
// BUSCAR CLIENTE/DIRECCION (Para los amarillos)
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 { p, c, d };
});
if (data.p && data.p !== "0") {
// Limpieza precio
const cleanMoney = data.p.replace(/[^\d,]/g, '').replace(',', '.');
const val = parseFloat(cleanMoney);
if (val > 0) importe = val;
}
if (data.c) clienteWeb = data.c.trim();
if (data.d) direccionWeb = data.d.trim();
} catch(e) {}
}
// Si ya tenemos precio, salimos del bucle
if (importe > 0) break;
}
if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} sigue en 0€ tras 5 intentos.`);
// --- 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;
// Prioridad BD
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 });
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 ...
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}`));