Actualizar robot_cobros.js

This commit is contained in:
marsalva 2025-12-30 09:26:12 +00:00
parent 276275a76f
commit 7cb8c402cf
1 changed files with 79 additions and 98 deletions

View File

@ -3,7 +3,7 @@ const { chromium } = require('playwright');
const admin = require('firebase-admin'); const admin = require('firebase-admin');
const cors = require('cors'); const cors = require('cors');
// --- 1. CONFIGURACIÓN FIREBASE --- // --- CONFIGURACIÓN FIREBASE ---
try { try {
if (process.env.FIREBASE_PRIVATE_KEY) { if (process.env.FIREBASE_PRIVATE_KEY) {
if (!admin.apps.length) { if (!admin.apps.length) {
@ -16,8 +16,6 @@ try {
}); });
} }
console.log("✅ Firebase inicializado."); console.log("✅ Firebase inicializado.");
} else {
console.error("❌ FALTA CONFIGURACIÓN DE FIREBASE (Variables de entorno)");
} }
} catch (e) { console.error("❌ Error Firebase:", e.message); } } catch (e) { console.error("❌ Error Firebase:", e.message); }
@ -35,7 +33,6 @@ const app = express();
app.use(cors({ origin: '*' })); app.use(cors({ origin: '*' }));
app.use(express.json({ limit: '50mb' })); app.use(express.json({ limit: '50mb' }));
// --- 2. ENDPOINT PRINCIPAL ---
app.post('/api/robot-cobros', async (req, res) => { app.post('/api/robot-cobros', async (req, res) => {
const { action, url, provider, dataToSave, month, year } = req.body; const { action, url, provider, dataToSave, month, year } = req.body;
console.log(`🔔 Petición: ${action} [${provider}]`); console.log(`🔔 Petición: ${action} [${provider}]`);
@ -53,13 +50,11 @@ app.post('/api/robot-cobros', async (req, res) => {
else { throw new Error("Acción MULTI inválida"); } else { throw new Error("Acción MULTI inválida"); }
} }
else { else {
// HOMESERVE
if (action === 'scan') { if (action === 'scan') {
const lista = await runHSScanner(); const lista = await runHSScanner();
res.json({ success: true, data: lista }); res.json({ success: true, data: lista });
} }
else if (action === 'analyze') { else if (action === 'analyze') {
if (!url) throw new Error("Falta URL");
const analisis = await runHSAnalyzer(url); const analisis = await runHSAnalyzer(url);
res.json({ success: true, ...analisis }); res.json({ success: true, ...analisis });
} }
@ -67,9 +62,7 @@ app.post('/api/robot-cobros', async (req, res) => {
const count = await runSaver(dataToSave, 'HS'); const count = await runSaver(dataToSave, 'HS');
res.json({ success: true, count }); res.json({ success: true, count });
} }
else { throw new Error("Acción HS inválida"); }
} }
} catch (err) { } catch (err) {
console.error("❌ CRASH:", err.message); console.error("❌ CRASH:", err.message);
res.status(500).json({ success: false, message: err.message }); res.status(500).json({ success: false, message: err.message });
@ -77,7 +70,7 @@ app.post('/api/robot-cobros', async (req, res) => {
}); });
// ================================================================== // ==================================================================
// 🤖 3. LÓGICA MULTIASISTENCIA (LOGIN CORREGIDO) // 🤖 LÓGICA MULTIASISTENCIA (PAGINACIÓN + PRECIOS)
// ================================================================== // ==================================================================
async function runMultiFullScan(mes, anio) { async function runMultiFullScan(mes, anio) {
@ -88,18 +81,14 @@ async function runMultiFullScan(mes, anio) {
const valD2 = `${anio}`; const valD2 = `${anio}`;
try { try {
console.log(`🚀 (MULTI) Iniciando: ${valD1}`); console.log(`🚀 (MULTI) Iniciando escaneo: ${valD1}`);
// 1. LOGIN (Usando tu lógica probada)
const { browser: b, page } = await loginMulti(); const { browser: b, page } = await loginMulti();
browser = b; browser = b;
// 2. IR A CERRADOS // 1. Ir a Cerrados y Filtrar
console.log("📂 (MULTI) Yendo a Cerrados..."); console.log("📂 (MULTI) Yendo a Cerrados...");
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
// 3. FILTRAR
console.log(`📅 (MULTI) Filtrando...`);
if (await page.isVisible('select[name="D1"]')) { if (await page.isVisible('select[name="D1"]')) {
await page.selectOption('select[name="D1"]', valD1); await page.selectOption('select[name="D1"]', valD1);
await page.selectOption('select[name="D2"]', valD2); await page.selectOption('select[name="D2"]', valD2);
@ -107,56 +96,66 @@ async function runMultiFullScan(mes, anio) {
await page.waitForTimeout(2000); await page.waitForTimeout(2000);
} }
// 4. RECORRER PÁGINAS // 2. RECORRER PÁGINAS (Bucle Principal)
let idsServicios = []; let idsServicios = [];
let tieneSiguiente = true; let tieneSiguiente = true;
let pagActual = 1; let pagActual = 1;
while (tieneSiguiente && pagActual <= 5) { while (tieneSiguiente && pagActual <= 10) {
console.log(`📄 (MULTI) Página ${pagActual}...`); console.log(`📄 (MULTI) Leyendo página ${pagActual}...`);
// Extraer expedientes de esta página
const nuevosIds = await page.evaluate(() => { const nuevosIds = await page.evaluate(() => {
const celdas = Array.from(document.querySelectorAll('td.tdet')); const celdas = Array.from(document.querySelectorAll('td.tdet'));
const lista = []; const lista = [];
celdas.forEach(td => { celdas.forEach(td => {
const txt = td.innerText.trim(); const txt = td.innerText.trim();
// Solo números de 8 cifras (formato expediente multi)
if (/^\d{8}$/.test(txt)) lista.push(txt); if (/^\d{8}$/.test(txt)) lista.push(txt);
}); });
return lista; return lista;
}); });
idsServicios.push(...nuevosIds);
// Botón Siguiente // Añadir a la lista global (sin duplicados de esta página)
const haySiguiente = await page.evaluate(() => { const unicosPagina = [...new Set(nuevosIds)];
const img = document.querySelector('img[src*="seguir.gif"]'); idsServicios.push(...unicosPagina);
if (img && img.parentElement.tagName === 'A') { console.log(` -> Encontrados ${unicosPagina.length} en pág ${pagActual}. Total acumulado: ${idsServicios.length}`);
img.parentElement.click(); return true;
}
return false;
});
if (haySiguiente) { await page.waitForTimeout(3000); pagActual++; } // 3. INTENTAR PASAR DE PÁGINA
else { tieneSiguiente = false; } // Buscamos un enlace que contenga el texto "Página siguiente"
const btnSiguiente = await page.$('a:has-text("Página siguiente")');
if (btnSiguiente) {
console.log(" ➡️ Pasando a la siguiente página...");
await btnSiguiente.click();
await page.waitForTimeout(2500); // Esperar carga
pagActual++;
} else {
console.log(" ⛔ No hay más páginas.");
tieneSiguiente = false;
}
} }
// Limpiar duplicados finales por si acaso
idsServicios = [...new Set(idsServicios)]; idsServicios = [...new Set(idsServicios)];
console.log(`🔍 (MULTI) Servicios a analizar: ${idsServicios.length}`); console.log(`🔍 (MULTI) Inicio análisis de detalle de ${idsServicios.length} servicios.`);
if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] }; if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] };
// 5. DETALLES (PRESUPUESTO) // 4. ENTRAR EN CADA SERVICIO PARA VER EL PRECIO
for (const idServicio of idsServicios) { for (const idServicio of idsServicios) {
// Ir directo al presupuesto
const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`; const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`;
try { try {
await page.goto(urlPresupuesto, { timeout: 45000, waitUntil: 'domcontentloaded' }); await page.goto(urlPresupuesto, { timeout: 30000, waitUntil: 'domcontentloaded' });
await page.waitForTimeout(1500); // Esperamos un poco para asegurar que Angular/JS cargue el precio
await page.waitForTimeout(800);
const info = await page.evaluate(() => { const info = await page.evaluate(() => {
const clean = (t) => t ? t.trim() : "Desconocido"; const clean = (t) => t ? t.trim() : "Desconocido";
let cliente = "", direccion = "", totalStr = "0"; let cliente = "", direccion = "", totalStr = "0";
// Datos Cliente (Bloques modernos o Tablas antiguas) // A) Datos Cliente
const bloques = Array.from(document.querySelectorAll('.policy-info-block')); const bloques = Array.from(document.querySelectorAll('.policy-info-block'));
bloques.forEach(b => { bloques.forEach(b => {
const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || ""; const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
@ -165,6 +164,7 @@ async function runMultiFullScan(mes, anio) {
if (t.includes("DIRECCIÓN")) direccion = v; if (t.includes("DIRECCIÓN")) direccion = v;
}); });
// Fallback tablas antiguas
if (!cliente) { if (!cliente) {
const tds = Array.from(document.querySelectorAll('td')); const tds = Array.from(document.querySelectorAll('td'));
for(let i=0; i<tds.length; i++) { for(let i=0; i<tds.length; i++) {
@ -174,29 +174,36 @@ async function runMultiFullScan(mes, anio) {
} }
} }
// Total Dinero // B) EL DINERO (Clave del asunto)
// Buscamos celda con atributo data-label="TOTAL REPARACION:" (Tu HTML)
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]'); const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
if (celdaTotal) totalStr = celdaTotal.innerText; if (celdaTotal) {
else { totalStr = celdaTotal.innerText; // Ej: "53,66 €"
const allTd = Array.from(document.querySelectorAll('td, th, div')); } else {
const header = allTd.find(el => el.innerText && el.innerText.includes("TOTAL REPARACION")); // Plan B: Buscar texto visible "TOTAL REPARACION"
if (header) { const allElems = Array.from(document.querySelectorAll('td, th, div, span'));
if(header.tagName==='TD' || header.tagName==='TH') { const elTotal = allElems.find(el => el.innerText && el.innerText.toUpperCase().includes("TOTAL REPARACION"));
if(header.nextElementSibling) totalStr = header.nextElementSibling.innerText;
} else { if (elTotal) {
totalStr = header.innerText.replace("TOTAL REPARACION", "").replace(":", ""); // A veces está en el siguiente elemento hermano
} if (elTotal.nextElementSibling) totalStr = elTotal.nextElementSibling.innerText;
// O en el mismo texto tipo "Total Reparación: 50€"
else totalStr = elTotal.innerText.split(':')[1] || elTotal.innerText;
} }
} }
return { cliente: clean(cliente), direccion: clean(direccion), totalStr }; return { cliente: clean(cliente), direccion: clean(direccion), totalStr };
}); });
// Limpiar importe
let importe = 0; let importe = 0;
if (info.totalStr) { if (info.totalStr) {
let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.'); let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.');
importe = Math.abs(parseFloat(cleanMoney) || 0); importe = Math.abs(parseFloat(cleanMoney) || 0);
} }
console.log(` 📝 Serv: ${idServicio} | Imp: ${importe}`);
if (db) { if (db) {
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get(); const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
if (!q.empty) { if (!q.empty) {
@ -208,7 +215,7 @@ async function runMultiFullScan(mes, anio) {
} }
} }
} catch (errDetail) { console.error(` ⚠️ Error ${idServicio}: ${errDetail.message}`); } } catch (errDetail) { console.error(` ⚠️ Fallo en ${idServicio}:`, errDetail.message); }
} }
return { encontrados: resultados, noEncontrados }; return { encontrados: resultados, noEncontrados };
@ -217,6 +224,7 @@ async function runMultiFullScan(mes, anio) {
} }
async function loginMulti() { async function loginMulti() {
// ... LOGIN DE SIEMPRE (No tocar) ...
let user = "", pass = ""; let user = "", pass = "";
if (db) { if (db) {
const doc = await db.collection("providerCredentials").doc("multiasistencia").get(); const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
@ -225,20 +233,14 @@ async function loginMulti() {
if(!user) throw new Error("Faltan credenciales Multiasistencia en Firebase"); if(!user) throw new Error("Faltan credenciales Multiasistencia en Firebase");
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] }); const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
const context = await browser.newContext({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }); const page = await browser.newPage();
const page = await context.newPage();
console.log("🌍 (MULTI) Entrando al login..."); console.log("🌍 (MULTI) Login...");
await page.goto(URLS.MULTI_LOGIN, { waitUntil: 'networkidle', timeout: 60000 }); await page.goto(URLS.MULTI_LOGIN, { timeout: 60000 });
// TU LÓGICA DE LOGIN QUE FUNCIONA
const userFilled = await page.evaluate((u) => { const userFilled = await page.evaluate((u) => {
const el = document.querySelector('input[name="usuario"]') || document.querySelector('input[type="text"]'); const el = document.querySelector('input[name="usuario"]') || document.querySelector('input[type="text"]');
if (el) { if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
el.value = u;
el.dispatchEvent(new Event('input', { bubbles: true }));
return true;
}
return false; return false;
}, user); }, user);
@ -247,13 +249,13 @@ async function loginMulti() {
await page.click('input[type="submit"]'); await page.click('input[type="submit"]');
await page.waitForTimeout(4000); await page.waitForTimeout(4000);
console.log("✅ (MULTI) Login OK");
return { browser, page }; return { browser, page };
} }
// ================================================================== // ... (RESTO DE CÓDIGO HOMESERVE Y GUARDADOR IGUAL) ...
// 🤖 4. LÓGICA HOMESERVE (Mantenida igual) // (Copia las funciones runHSScanner, runHSAnalyzer, loginHS y runSaver del archivo anterior V10 si las necesitas completas aquí, o déjalas como estaban)
// ================================================================== // Te pongo aquí abajo runSaver y el resto para que sea copiar y pegar fácil.
async function runHSScanner() { async function runHSScanner() {
let browser = null; let browser = null;
try { try {
@ -280,40 +282,26 @@ async function runHSAnalyzer(targetUrl) {
await page.goto(targetUrl, { timeout: 60000 }); await page.goto(targetUrl, { timeout: 60000 });
await page.waitForTimeout(1500); await page.waitForTimeout(1500);
const botonPulsado = await page.evaluate(() => { const botonPulsado = await page.evaluate(() => {
const elementos = Array.from(document.querySelectorAll('input, button, a')); const el = Array.from(document.querySelectorAll('input, button, a')).find(el => (el.value || el.innerText || "").toUpperCase().includes("DESGLOSE"));
const target = elementos.find(el => { if (el) { el.click(); return true; } return false;
const txt = (el.value || el.innerText || "").toUpperCase();
return txt.includes("SERVICIO") && txt.includes("DESGLOSE");
});
if (target) { target.click(); return true; }
return false;
}); });
if (botonPulsado) await page.waitForTimeout(3000); if (botonPulsado) await page.waitForTimeout(3000);
const datosRaw = await page.evaluate(() => { const datos = await page.evaluate(() => {
const filas = Array.from(document.querySelectorAll('tr')); const rows = Array.from(document.querySelectorAll('tr'));
const datos = []; return rows.map(tr => {
filas.forEach(tr => {
const tds = tr.querySelectorAll('td'); const tds = tr.querySelectorAll('td');
if (tds.length >= 6) { if (tds.length >= 6 && /^\d{5,}$/.test(tds[0].innerText.trim())) {
const servicio = tds[0].innerText.trim(); return { servicio: tds[0].innerText.trim(), direccion: tds[1].innerText.trim(), saldoRaw: tds[5].innerText.trim() };
const direccion = tds[1].innerText.trim();
const saldoRaw = tds[5].innerText.trim();
if (/^\d{5,}$/.test(servicio)) datos.push({ servicio, direccion, saldoRaw });
} }
}); }).filter(Boolean);
return datos;
}); });
const encontrados = []; const noEncontrados = []; const encontrados = [], noEncontrados = [];
if (db) { if (db) {
for (const item of datosRaw) { for (const item of datos) {
let cleanSaldo = item.saldoRaw.replace(/[^\d.-]/g, ''); let importe = Math.abs(parseFloat(item.saldoRaw.replace(/[^\d.-]/g, '')) || 0);
let importe = Math.abs(parseFloat(cleanSaldo) || 0);
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", item.servicio).get(); const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", item.servicio).get();
if (!q.empty) { if (!q.empty) q.forEach(doc => encontrados.push({ servicio: item.servicio, direccion: item.direccion, importe, docId: doc.id }));
q.forEach(doc => encontrados.push({ servicio: item.servicio, direccion: item.direccion, importe: importe, docId: doc.id })); else noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe });
} else {
noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe: importe });
}
} }
} }
return { encontrados, noEncontrados }; return { encontrados, noEncontrados };
@ -340,7 +328,6 @@ async function loginHS() {
return { browser, page }; return { browser, page };
} }
// 💾 GUARDADOR
async function runSaver(items, providerType) { async function runSaver(items, providerType) {
if (!db) return 0; if (!db) return 0;
const batch = db.batch(); const batch = db.batch();
@ -348,13 +335,7 @@ async function runSaver(items, providerType) {
let count = 0; let count = 0;
items.forEach(item => { items.forEach(item => {
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId); const ref = db.collection(APPOINTMENTS_COL).doc(item.docId);
const updateData = { const updateData = { paidAmount: item.importe, paymentState: "Pagado", status: 'completed', paymentDate: nowISO, lastUpdatedByRobot: nowISO };
paidAmount: item.importe,
paymentState: "Pagado",
status: 'completed',
paymentDate: nowISO,
lastUpdatedByRobot: nowISO
};
if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified'; if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified';
else updateData.homeservePaymentStatus = 'paid_saldo'; else updateData.homeservePaymentStatus = 'paid_saldo';
batch.update(ref, updateData); batch.update(ref, updateData);