Actualizar robot_cobros.js
This commit is contained in:
parent
1cf871b2a3
commit
bcbc7a7705
116
robot_cobros.js
116
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 FIREBASE ---
|
// --- FIREBASE INIT ---
|
||||||
try {
|
try {
|
||||||
if (process.env.FIREBASE_PRIVATE_KEY) {
|
if (process.env.FIREBASE_PRIVATE_KEY) {
|
||||||
if (!admin.apps.length) {
|
if (!admin.apps.length) {
|
||||||
|
|
@ -39,8 +39,7 @@ app.post('/api/robot-cobros', async (req, res) => {
|
||||||
const send = (type, payload) => res.write(JSON.stringify({ type, payload }) + "\n");
|
const send = (type, payload) => res.write(JSON.stringify({ type, payload }) + "\n");
|
||||||
|
|
||||||
const { action, url, provider, dataToSave, month, year } = req.body;
|
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||||
console.log(`🔔 Orden: ${action} [${provider}]`);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (provider === 'MULTI') {
|
if (provider === 'MULTI') {
|
||||||
if (action === 'scan') await runMultiStream(month, year, send);
|
if (action === 'scan') await runMultiStream(month, year, send);
|
||||||
|
|
@ -55,13 +54,12 @@ app.post('/api/robot-cobros', async (req, res) => {
|
||||||
else if (action === 'save_data') { const c = await runSaver(dataToSave, 'HS'); send('DONE', { count: c }); }
|
else if (action === 'save_data') { const c = await runSaver(dataToSave, 'HS'); send('DONE', { count: c }); }
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("❌ CRASH:", err.message);
|
|
||||||
send('ERROR', err.message);
|
send('ERROR', err.message);
|
||||||
} finally { res.end(); }
|
} finally { res.end(); }
|
||||||
});
|
});
|
||||||
|
|
||||||
// ==================================================================
|
// ==================================================================
|
||||||
// 🤖 LÓGICA MULTIASISTENCIA V14 (LECTURA DEEP WAIT)
|
// 🤖 LÓGICA MULTIASISTENCIA V15 (SOPORTE FRAMES)
|
||||||
// ==================================================================
|
// ==================================================================
|
||||||
|
|
||||||
async function runMultiStream(mes, anio, send) {
|
async function runMultiStream(mes, anio, send) {
|
||||||
|
|
@ -70,19 +68,19 @@ async function runMultiStream(mes, anio, send) {
|
||||||
const valD2 = `${anio}`;
|
const valD2 = `${anio}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
send('LOG', `🚀 Iniciando MULTI V14 para: ${valD1}`);
|
send('LOG', `🚀 (MULTI) Iniciando para: ${valD1}`);
|
||||||
const { browser: b, page } = await loginMulti();
|
const { browser: b, page } = await loginMulti();
|
||||||
browser = b;
|
browser = b;
|
||||||
|
|
||||||
send('LOG', "📂 Yendo a Cerrados...");
|
send('LOG', "📂 Yendo a Cerrados...");
|
||||||
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
||||||
|
|
||||||
// Filtro Fecha
|
// Filtro
|
||||||
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);
|
||||||
await page.click('input[name="continuar"]');
|
await page.click('input[name="continuar"]');
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2500);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- FASE 1: RECOLECTAR IDs ---
|
// --- FASE 1: RECOLECTAR IDs ---
|
||||||
|
|
@ -93,10 +91,11 @@ async function runMultiStream(mes, anio, send) {
|
||||||
while (tieneSiguiente && pagActual <= 10) {
|
while (tieneSiguiente && pagActual <= 10) {
|
||||||
send('LOG', `📄 Leyendo página ${pagActual}...`);
|
send('LOG', `📄 Leyendo página ${pagActual}...`);
|
||||||
const nuevosIds = await page.evaluate(() => {
|
const nuevosIds = await page.evaluate(() => {
|
||||||
const celdas = Array.from(document.querySelectorAll('td.tdet'));
|
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
||||||
const lista = [];
|
return links.map(a => {
|
||||||
celdas.forEach(td => { if (/^\d{8}$/.test(td.innerText.trim())) lista.push(td.innerText.trim()); });
|
const m = a.href.match(/reparacion=(\d+)/);
|
||||||
return lista;
|
return m ? m[1] : null;
|
||||||
|
}).filter(id => id && /^\d{8}$/.test(id));
|
||||||
});
|
});
|
||||||
|
|
||||||
idsServicios.push(...[...new Set(nuevosIds)]);
|
idsServicios.push(...[...new Set(nuevosIds)]);
|
||||||
|
|
@ -110,7 +109,7 @@ async function runMultiStream(mes, anio, send) {
|
||||||
idsServicios = [...new Set(idsServicios)];
|
idsServicios = [...new Set(idsServicios)];
|
||||||
send('LOG', `🔍 Total a revisar: ${idsServicios.length}`);
|
send('LOG', `🔍 Total a revisar: ${idsServicios.length}`);
|
||||||
|
|
||||||
// --- FASE 2: LEER DETALLES ---
|
// --- FASE 2: LEER DETALLES (CON FRAMES) ---
|
||||||
for (const [index, idServicio] of idsServicios.entries()) {
|
for (const [index, idServicio] of idsServicios.entries()) {
|
||||||
send('PROGRESS', { current: index + 1, total: idsServicios.length });
|
send('PROGRESS', { current: index + 1, total: idsServicios.length });
|
||||||
|
|
||||||
|
|
@ -118,60 +117,41 @@ async function runMultiStream(mes, anio, send) {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||||
|
await page.waitForTimeout(1000); // Esperar renderizado base
|
||||||
// --- ESPERA CRÍTICA ---
|
|
||||||
// Esperamos a que aparezca el bloque de cliente o el precio.
|
|
||||||
// Angular tarda en renderizar. Damos hasta 5 segundos extra.
|
|
||||||
try {
|
|
||||||
await page.waitForSelector('div.policy-info-block', { timeout: 6000 });
|
|
||||||
} catch(e) {}
|
|
||||||
|
|
||||||
// --- EXTRACCIÓN ROBUSTA ---
|
// === BÚSQUEDA PROFUNDA EN FRAMES ===
|
||||||
const info = await page.evaluate(() => {
|
let totalStr = "";
|
||||||
const clean = (t) => t ? t.trim().replace(/\s+/g, ' ') : "Desconocido";
|
|
||||||
let clienteWeb = "", direccionWeb = "", totalStr = "";
|
|
||||||
|
|
||||||
// 1. CLIENTE Y DIRECCIÓN (Buscamos en los bloques azules)
|
|
||||||
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")) clienteWeb = valor;
|
|
||||||
if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccionWeb = valor;
|
|
||||||
});
|
|
||||||
|
|
||||||
// 2. PRECIO (Buscamos por el atributo data-label exacto que me pasaste)
|
|
||||||
// Primero intentamos el selector preciso
|
|
||||||
const celdaDataLabel = document.querySelector('td[data-label*="TOTAL REPARACION"]');
|
|
||||||
if (celdaDataLabel) {
|
|
||||||
totalStr = celdaDataLabel.innerText;
|
|
||||||
} else {
|
|
||||||
// Si falla, buscamos cualquier celda que contenga "TOTAL REPARACION" y el símbolo "€"
|
|
||||||
const celdas = Array.from(document.querySelectorAll('td'));
|
|
||||||
const celdaTexto = celdas.find(el => el.innerText.toUpperCase().includes("TOTAL REPARACION") && el.innerText.includes("€"));
|
|
||||||
if (celdaTexto) {
|
|
||||||
// A veces viene sucio "TOTAL REPARACION: 53 €", limpiamos
|
|
||||||
totalStr = celdaTexto.innerText.replace("TOTAL REPARACION", "").replace(":", "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { clienteWeb: clean(clienteWeb), direccionWeb: clean(direccionWeb), totalStr };
|
|
||||||
});
|
|
||||||
|
|
||||||
// LIMPIEZA DE PRECIO
|
|
||||||
let importe = 0;
|
let importe = 0;
|
||||||
if (info.totalStr) {
|
|
||||||
// "53,66 €" -> Quitamos todo menos números y comas -> "53,66" -> replace coma por punto -> 53.66
|
// 1. Iterar sobre todos los frames (marcos) de la web
|
||||||
let cleanMoney = info.totalStr.replace(/[^\d,]/g, '').replace(',', '.');
|
const frames = page.frames();
|
||||||
|
for (const frame of frames) {
|
||||||
|
try {
|
||||||
|
// Buscamos el elemento exacto que me pasaste
|
||||||
|
const text = await frame.evaluate(() => {
|
||||||
|
const el = document.querySelector('td[data-label="TOTAL REPARACION:"]'); // Selector exacto
|
||||||
|
return el ? el.innerText : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (text) {
|
||||||
|
totalStr = text; // "53,66 €"
|
||||||
|
break; // ¡Encontrado! Dejamos de buscar
|
||||||
|
}
|
||||||
|
} catch(e) { /* Error en frame, seguimos al siguiente */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Limpieza del precio
|
||||||
|
if (totalStr) {
|
||||||
|
// "53,66 €" -> "53.66"
|
||||||
|
const cleanMoney = totalStr.replace(/[^\d,]/g, '').replace(',', '.');
|
||||||
importe = parseFloat(cleanMoney) || 0;
|
importe = parseFloat(cleanMoney) || 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- CRUCE CON BASE DE DATOS (PRIORIDAD AL CLIENTE DE LA BD) ---
|
// 3. CONSULTAR BASE DE DATOS Y FORZAR NOMBRE
|
||||||
let docId = null;
|
let docId = null;
|
||||||
let enBD = false;
|
let enBD = false;
|
||||||
let clienteFinal = info.clienteWeb; // Por defecto el de la web
|
let clienteFinal = "Desconocido"; // Fallback por defecto
|
||||||
let direccionFinal = info.direccionWeb;
|
let direccionFinal = "Sin dirección";
|
||||||
|
|
||||||
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();
|
||||||
|
|
@ -180,19 +160,15 @@ async function runMultiStream(mes, anio, send) {
|
||||||
docId = doc.id;
|
docId = doc.id;
|
||||||
enBD = true;
|
enBD = true;
|
||||||
|
|
||||||
// ¡AQUÍ ESTÁ EL ARREGLO!
|
|
||||||
// Si tenemos el nombre en la BD, lo usamos en lugar del "Desconocido" de la web si falló
|
|
||||||
const datosBD = doc.data();
|
const datosBD = doc.data();
|
||||||
if (datosBD.clientName && datosBD.clientName.length > 2) {
|
|
||||||
clienteFinal = datosBD.clientName;
|
// PRIORIDAD ABSOLUTA A LOS DATOS DE FIREBASE
|
||||||
}
|
if (datosBD.clientName) clienteFinal = datosBD.clientName;
|
||||||
if (datosBD.address && datosBD.address.length > 5) {
|
if (datosBD.address) direccionFinal = datosBD.address;
|
||||||
direccionFinal = datosBD.address;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ENVIAR
|
// ENVIAR (Verde o Amarillo)
|
||||||
send('ITEM_FOUND', {
|
send('ITEM_FOUND', {
|
||||||
servicio: idServicio,
|
servicio: idServicio,
|
||||||
direccion: direccionFinal,
|
direccion: direccionFinal,
|
||||||
|
|
@ -239,7 +215,7 @@ async function loginMulti() {
|
||||||
return { browser, page };
|
return { browser, page };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ... (RESTO DE FUNCIONES HS Y SAVER SE MANTIENEN IGUAL) ...
|
// ... RESTO DE FUNCIONES (HS, Saver) NO CAMBIAN ...
|
||||||
async function runHSScanner() {
|
async function runHSScanner() {
|
||||||
let browser = null;
|
let browser = null;
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue