cobros-multi/robot_cobros.js

368 lines
15 KiB
JavaScript

const express = require('express');
const { chromium } = require('playwright');
const admin = require('firebase-admin');
const cors = require('cors');
// --- 1. 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.");
} else {
console.error("❌ FALTA CONFIGURACIÓN DE FIREBASE (Variables de entorno)");
}
} 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' }));
// --- 2. ENDPOINT PRINCIPAL ---
app.post('/api/robot-cobros', async (req, res) => {
const { action, url, provider, dataToSave, month, year } = req.body;
console.log(`🔔 Petición: ${action} [${provider}]`);
try {
if (provider === 'MULTI') {
if (action === 'scan') {
const lista = await runMultiFullScan(month, year);
res.json({ success: true, data: lista });
}
else if (action === 'save_data') {
const count = await runSaver(dataToSave, 'MULTI');
res.json({ success: true, count });
}
else { throw new Error("Acción MULTI inválida"); }
}
else {
// HOMESERVE
if (action === 'scan') {
const lista = await runHSScanner();
res.json({ success: true, data: lista });
}
else if (action === 'analyze') {
if (!url) throw new Error("Falta URL");
const analisis = await runHSAnalyzer(url);
res.json({ success: true, ...analisis });
}
else if (action === 'save_data') {
const count = await runSaver(dataToSave, 'HS');
res.json({ success: true, count });
}
else { throw new Error("Acción HS inválida"); }
}
} catch (err) {
console.error("❌ CRASH:", err.message);
res.status(500).json({ success: false, message: err.message });
}
});
// ==================================================================
// 🤖 3. LÓGICA MULTIASISTENCIA (LOGIN CORREGIDO)
// ==================================================================
async function runMultiFullScan(mes, anio) {
let browser = null;
const resultados = [];
const noEncontrados = [];
const valD1 = `${mes}_${anio}`;
const valD2 = `${anio}`;
try {
console.log(`🚀 (MULTI) Iniciando: ${valD1}`);
// 1. LOGIN (Usando tu lógica probada)
const { browser: b, page } = await loginMulti();
browser = b;
// 2. IR A CERRADOS
console.log("📂 (MULTI) Yendo a Cerrados...");
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
// 3. FILTRAR
console.log(`📅 (MULTI) Filtrando...`);
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);
}
// 4. RECORRER PÁGINAS
let idsServicios = [];
let tieneSiguiente = true;
let pagActual = 1;
while (tieneSiguiente && pagActual <= 5) {
console.log(`📄 (MULTI) 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(...nuevosIds);
// Botón Siguiente
const haySiguiente = await page.evaluate(() => {
const img = document.querySelector('img[src*="seguir.gif"]');
if (img && img.parentElement.tagName === 'A') {
img.parentElement.click(); return true;
}
return false;
});
if (haySiguiente) { await page.waitForTimeout(3000); pagActual++; }
else { tieneSiguiente = false; }
}
idsServicios = [...new Set(idsServicios)];
console.log(`🔍 (MULTI) Servicios a analizar: ${idsServicios.length}`);
if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] };
// 5. DETALLES (PRESUPUESTO)
for (const idServicio of idsServicios) {
// Ir directo al presupuesto
const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`;
try {
await page.goto(urlPresupuesto, { timeout: 45000, waitUntil: 'domcontentloaded' });
await page.waitForTimeout(1500);
const info = await page.evaluate(() => {
const clean = (t) => t ? t.trim() : "Desconocido";
let cliente = "", direccion = "", totalStr = "0";
// Datos Cliente (Bloques modernos o Tablas antiguas)
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")) cliente = v;
if (t.includes("DIRECCIÓN")) direccion = v;
});
if (!cliente) {
const tds = Array.from(document.querySelectorAll('td'));
for(let i=0; i<tds.length; i++) {
const txt = tds[i].innerText.toUpperCase();
if(txt.includes("NOMBRE CLIENTE") && tds[i+1]) cliente = tds[i+1].innerText;
if(txt.includes("DIRECCIÓN") && tds[i+1]) direccion = tds[i+1].innerText;
}
}
// Total Dinero
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
if (celdaTotal) totalStr = celdaTotal.innerText;
else {
const allTd = Array.from(document.querySelectorAll('td, th, div'));
const header = allTd.find(el => el.innerText && el.innerText.includes("TOTAL REPARACION"));
if (header) {
if(header.tagName==='TD' || header.tagName==='TH') {
if(header.nextElementSibling) totalStr = header.nextElementSibling.innerText;
} else {
totalStr = header.innerText.replace("TOTAL REPARACION", "").replace(":", "");
}
}
}
return { cliente: clean(cliente), direccion: clean(direccion), totalStr };
});
let importe = 0;
if (info.totalStr) {
let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.');
importe = Math.abs(parseFloat(cleanMoney) || 0);
}
if (db) {
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
if (!q.empty) {
q.forEach(doc => {
resultados.push({ servicio: idServicio, direccion: info.direccion, importe, docId: doc.id });
});
} else {
noEncontrados.push({ servicio: idServicio, direccion: info.direccion, importe });
}
}
} catch (errDetail) { console.error(` ⚠️ Error ${idServicio}: ${errDetail.message}`); }
}
return { encontrados: resultados, noEncontrados };
} 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 Multiasistencia en Firebase");
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 context.newPage();
console.log("🌍 (MULTI) Entrando al login...");
await page.goto(URLS.MULTI_LOGIN, { waitUntil: 'networkidle', timeout: 60000 });
// TU LÓGICA DE LOGIN QUE FUNCIONA
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);
console.log("✅ (MULTI) Login OK");
return { browser, page };
}
// ==================================================================
// 🤖 4. LÓGICA HOMESERVE (Mantenida 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 elementos = Array.from(document.querySelectorAll('input, button, a'));
const target = elementos.find(el => {
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);
const datosRaw = await page.evaluate(() => {
const filas = Array.from(document.querySelectorAll('tr'));
const datos = [];
filas.forEach(tr => {
const tds = tr.querySelectorAll('td');
if (tds.length >= 6) {
const servicio = tds[0].innerText.trim();
const direccion = tds[1].innerText.trim();
const saldoRaw = tds[5].innerText.trim();
if (/^\d{5,}$/.test(servicio)) datos.push({ servicio, direccion, saldoRaw });
}
});
return datos;
});
const encontrados = []; const noEncontrados = [];
if (db) {
for (const item of datosRaw) {
let cleanSaldo = item.saldoRaw.replace(/[^\d.-]/g, '');
let importe = Math.abs(parseFloat(cleanSaldo) || 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: importe, docId: doc.id }));
} else {
noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe: 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 };
}
// 💾 GUARDADOR
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);
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++;
});
await batch.commit();
return count;
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`🚀 Server on port ${PORT}`));