Actualizar robot_cobros.js
This commit is contained in:
parent
f3aac68a4f
commit
0535c970e4
283
robot_cobros.js
283
robot_cobros.js
|
|
@ -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');
|
||||||
|
|
||||||
// --- CONFIGURACIÓN ---
|
// --- 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) {
|
||||||
|
|
@ -15,150 +15,199 @@ try {
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
console.log("✅ Firebase inicializado.");
|
||||||
}
|
}
|
||||||
} catch (e) { console.error("Firebase Error:", e.message); }
|
} catch (e) { console.error("❌ Error Firebase:", e.message); }
|
||||||
|
|
||||||
const db = admin.apps.length ? admin.firestore() : null;
|
const db = admin.apps.length ? admin.firestore() : null;
|
||||||
|
const APPOINTMENTS_COL = "appointments";
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(cors({ origin: '*' }));
|
app.use(cors({ origin: '*' }));
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
// --- ENDPOINT ---
|
// --- ENDPOINT UNIFICADO ---
|
||||||
app.post('/api/robot-cobros', async (req, res) => {
|
app.post('/api/robot-cobros', async (req, res) => {
|
||||||
console.log("🔔 DIAGNÓSTICO: Iniciando...");
|
const { action, urls } = req.body; // action: 'scan' o 'process'
|
||||||
|
|
||||||
|
console.log(`🔔 Orden recibida: ${action.toUpperCase()}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const reporte = await runDiagnostic();
|
if (action === 'scan') {
|
||||||
res.json({ success: true, message: "Diagnóstico finalizado", data: reporte });
|
const lista = await runScanner();
|
||||||
|
res.json({ success: true, mode: 'scan', data: lista });
|
||||||
|
}
|
||||||
|
else if (action === 'process') {
|
||||||
|
if (!urls || urls.length === 0) throw new Error("No has seleccionado ninguna fecha.");
|
||||||
|
const procesados = await runProcessor(urls);
|
||||||
|
res.json({ success: true, mode: 'process', count: procesados });
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new Error("Acción no válida");
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("❌ Error Fatal:", err);
|
console.error("❌ Error:", err.message);
|
||||||
res.status(500).json({ success: false, message: err.message });
|
res.status(500).json({ success: false, message: err.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/', (req, res) => res.send('🤖 Robot Sherlock ONLINE'));
|
// --- FUNCIÓN 1: ESCANEAR FECHAS DISPONIBLES ---
|
||||||
|
async function runScanner() {
|
||||||
// --- LÓGICA DE DETECTIVE ---
|
|
||||||
async function runDiagnostic() {
|
|
||||||
let browser = null;
|
let browser = null;
|
||||||
const logs = []; // Aquí guardaremos las pistas
|
try {
|
||||||
|
const { browser: b, page } = await loginAndGoToLiquidaciones();
|
||||||
function apuntar(msg) {
|
browser = b;
|
||||||
console.log(msg);
|
|
||||||
logs.push({ expediente: "INFO", direccion: msg, importeLimpio: 0 });
|
console.log("🔍 Buscando lista de liquidaciones...");
|
||||||
}
|
|
||||||
|
// Extraemos todos los enlaces de fechas
|
||||||
|
const liquidaciones = await page.evaluate(() => {
|
||||||
|
const links = Array.from(document.querySelectorAll('a'));
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
links.forEach(l => {
|
||||||
|
const txt = l.innerText.trim();
|
||||||
|
// Filtramos por formato fecha (DD/MM/YYYY) o similar
|
||||||
|
if (/\d{2}\/\d{2}\/\d{4}/.test(txt)) {
|
||||||
|
// Guardamos la URL absoluta para navegar directo luego
|
||||||
|
results.push({
|
||||||
|
fecha: txt,
|
||||||
|
url: l.href
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return results;
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`✅ Encontradas ${liquidaciones.length} fechas.`);
|
||||||
|
return liquidaciones;
|
||||||
|
|
||||||
|
} catch (e) { throw e; } finally { if(browser) await browser.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- FUNCIÓN 2: PROCESAR SELECCIONADAS ---
|
||||||
|
async function runProcessor(urlsAProcesar) {
|
||||||
|
let browser = null;
|
||||||
|
let totalActualizados = 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. CREDENCIALES
|
const { browser: b, page } = await loginAndGoToLiquidaciones(); // Login inicial
|
||||||
let user = ""; let pass = "";
|
browser = b;
|
||||||
if (db) {
|
|
||||||
const doc = await db.collection("providerCredentials").doc("homeserve").get();
|
|
||||||
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
|
||||||
}
|
|
||||||
if (!user) {
|
|
||||||
apuntar("❌ ERROR: No tengo usuario/pass en Firebase.");
|
|
||||||
return logs;
|
|
||||||
}
|
|
||||||
|
|
||||||
apuntar("🚀 Lanzando navegador...");
|
for (const targetUrl of urlsAProcesar) {
|
||||||
browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
console.log(`➡️ Procesando URL: ${targetUrl}`);
|
||||||
const page = await browser.newPage();
|
|
||||||
|
// 1. Navegar a la fecha específica
|
||||||
|
await page.goto(targetUrl, { timeout: 60000 });
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// 2. LOGIN
|
// 2. Buscar botón "Desglose" y pulsar si existe
|
||||||
apuntar("🌍 Entrando al Login...");
|
const hayDesglose = await page.evaluate(() => {
|
||||||
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', { timeout: 60000 });
|
const btn = Array.from(document.querySelectorAll('input[type="button"], button, a'))
|
||||||
|
.find(el => (el.value || el.innerText || "").toLowerCase().includes('desglose'));
|
||||||
const enLogin = await page.isVisible('input[name="CODIGO"]');
|
if(btn) { btn.click(); return true; }
|
||||||
if (enLogin) {
|
return false;
|
||||||
apuntar("🔑 Formulario detectado. Escribiendo...");
|
|
||||||
await page.fill('input[name="CODIGO"]', user);
|
|
||||||
await page.fill('input[type="password"]', pass);
|
|
||||||
await page.keyboard.press('Enter');
|
|
||||||
await page.waitForTimeout(4000);
|
|
||||||
} else {
|
|
||||||
apuntar("⚠️ No vi el formulario de login. ¿Ya estaba dentro?");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. NAVEGAR A LIQUIDACIONES
|
|
||||||
apuntar("📂 Yendo a Consultar Liquidaciones...");
|
|
||||||
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=CONSULTALIQ_WEB');
|
|
||||||
await page.waitForTimeout(2000);
|
|
||||||
|
|
||||||
apuntar(`📍 URL actual: ${page.url()}`);
|
|
||||||
|
|
||||||
// 4. INTENTAR CLICKAR FECHA
|
|
||||||
// Buscamos enlaces que parezcan una fecha YYYYMMDD o similar
|
|
||||||
const clickado = await page.evaluate(() => {
|
|
||||||
const links = Array.from(document.querySelectorAll('a'));
|
|
||||||
// Busca el primer enlace que NO sea de menú y tenga numeros
|
|
||||||
const target = links.find(l => {
|
|
||||||
const txt = l.innerText.trim();
|
|
||||||
// Heurística: Si tiene más de 4 números seguidos, probablemente es una fecha/expediente
|
|
||||||
return /\d{4}/.test(txt) && !txt.includes('FACTURACION');
|
|
||||||
});
|
});
|
||||||
if (target) {
|
|
||||||
const texto = target.innerText;
|
if(hayDesglose) {
|
||||||
target.click();
|
console.log(" 🔘 Entrando al Desglose...");
|
||||||
return texto;
|
await page.waitForTimeout(3000);
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (clickado) {
|
// 3. LEER LA TABLA (EXTRAER SALDO)
|
||||||
apuntar(`🖱️ Click realizado en enlace: "${clickado}"`);
|
const datosTabla = await page.evaluate(() => {
|
||||||
await page.waitForTimeout(3000);
|
const filas = Array.from(document.querySelectorAll('tr'));
|
||||||
} else {
|
const datos = [];
|
||||||
apuntar("⚠️ No encontré ningún enlace de fecha para hacer clic. ¿Está la lista vacía?");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. BUSCAR DESGLOSE
|
|
||||||
const hayBotonDesglose = await page.isVisible('input[value*="Desglose" i]');
|
|
||||||
if (hayBotonDesglose) {
|
|
||||||
apuntar("🔘 Botón 'Desglose' detectado. Pulsando...");
|
|
||||||
await page.click('input[value*="Desglose" i]');
|
|
||||||
await page.waitForTimeout(3000);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 6. ANÁLISIS VISUAL DE LA TABLA (EL MOMENTO DE LA VERDAD)
|
|
||||||
apuntar("👀 Analizando estructura de la página...");
|
|
||||||
|
|
||||||
const diagnosticoPagina = await page.evaluate(() => {
|
|
||||||
const resultado = [];
|
|
||||||
|
|
||||||
// A) Buscar la tabla amarilla específica de saldo.html
|
|
||||||
const tablaAmarilla = document.querySelector('table[bgcolor="#F8E8A6"]');
|
|
||||||
|
|
||||||
if (tablaAmarilla) {
|
|
||||||
resultado.push({ expediente: "EXITO", direccion: "✅ TABLA AMARILLA ENCONTRADA", importeLimpio: 1 });
|
|
||||||
|
|
||||||
// Leemos las 3 primeras filas para ver qué hay dentro
|
filas.forEach(tr => {
|
||||||
const filas = Array.from(tablaAmarilla.querySelectorAll('tr'));
|
const tds = tr.querySelectorAll('td');
|
||||||
resultado.push({ expediente: "INFO", direccion: `La tabla tiene ${filas.length} filas.`, importeLimpio: 0 });
|
// Según tu saldo.html:
|
||||||
|
// Col 0: Servicio | Col 5 (Sexta columna): Saldo
|
||||||
filas.slice(0, 5).forEach((tr, i) => {
|
if (tds.length >= 6) {
|
||||||
resultado.push({
|
const servicio = tds[0].innerText.trim();
|
||||||
expediente: `FILA ${i}`,
|
const saldoRaw = tds[5].innerText.trim(); // <--- COLUMNA SALDO
|
||||||
direccion: tr.innerText.substring(0, 50) + "...", // Primeros 50 caracteres
|
|
||||||
importeLimpio: 0
|
// Validar que sea un servicio numérico
|
||||||
});
|
if (/^\d{5,}$/.test(servicio)) {
|
||||||
|
datos.push({ servicio, saldoRaw });
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} else {
|
return datos;
|
||||||
// B) Si no hay tabla amarilla, ¿qué hay?
|
});
|
||||||
resultado.push({ expediente: "ERROR", direccion: "❌ NO VEO LA TABLA AMARILLA", importeLimpio: 0 });
|
|
||||||
const bodyText = document.body.innerText.substring(0, 100).replace(/\n/g, ' ');
|
console.log(` 💰 Leídos ${datosTabla.length} servicios. Guardando en Firebase...`);
|
||||||
resultado.push({ expediente: "DUMP", direccion: `Texto visible: ${bodyText}`, importeLimpio: 0 });
|
|
||||||
|
// 4. GUARDAR EN FIREBASE
|
||||||
|
if (db && datosTabla.length > 0) {
|
||||||
|
const batch = db.batch();
|
||||||
|
let batchCount = 0;
|
||||||
|
const nowISO = new Date().toISOString();
|
||||||
|
|
||||||
|
for (const item of datosTabla) {
|
||||||
|
// Limpieza: "-33.48" -> 33.48 (Positivo)
|
||||||
|
let cleanSaldo = item.saldoRaw.replace(/[^\d.-]/g, ''); // Deja solo numeros, punto y menos
|
||||||
|
let importe = parseFloat(cleanSaldo);
|
||||||
|
|
||||||
|
if (isNaN(importe)) continue;
|
||||||
|
|
||||||
|
// IMPORTANTE: Convertimos a positivo para paidAmount
|
||||||
|
// Si prefieres negativo, quita Math.abs()
|
||||||
|
importe = Math.abs(importe);
|
||||||
|
|
||||||
|
// Buscar el documento en appointments
|
||||||
|
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", item.servicio).get();
|
||||||
|
|
||||||
|
q.forEach(doc => {
|
||||||
|
batch.update(doc.ref, {
|
||||||
|
paidAmount: importe, // <--- GUARDAMOS EL SALDO AQUÍ
|
||||||
|
status: 'completed', // Asumimos completado
|
||||||
|
paymentDate: nowISO,
|
||||||
|
homeservePaymentStatus: 'paid_saldo',
|
||||||
|
lastUpdatedByRobot: nowISO
|
||||||
|
});
|
||||||
|
batchCount++;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (batchCount > 0) {
|
||||||
|
await batch.commit();
|
||||||
|
totalActualizados += batchCount;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return resultado;
|
|
||||||
});
|
return totalActualizados;
|
||||||
|
|
||||||
return [...logs, ...diagnosticoPagina];
|
} catch (e) { throw e; } finally { if(browser) await browser.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
} catch (e) {
|
// --- AUXILIAR LOGIN ---
|
||||||
apuntar("❌ CRASH: " + e.message);
|
async function loginAndGoToLiquidaciones() {
|
||||||
return logs;
|
let user = "SIN_USER", pass = "SIN_PASS";
|
||||||
} finally {
|
if (db) {
|
||||||
if (browser) await browser.close();
|
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();
|
||||||
|
|
||||||
|
console.log("🌍 Login...");
|
||||||
|
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', { 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("📂 Sección Liquidaciones...");
|
||||||
|
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=CONSULTALIQ_WEB');
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
return { browser, page };
|
||||||
}
|
}
|
||||||
|
|
||||||
const PORT = process.env.PORT || 3000;
|
const PORT = process.env.PORT || 3000;
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue