Actualizar robot_cobros.js
This commit is contained in:
parent
1cf871b2a3
commit
bcbc7a7705
114
robot_cobros.js
114
robot_cobros.js
|
|
@ -3,7 +3,7 @@ const { chromium } = require('playwright');
|
|||
const admin = require('firebase-admin');
|
||||
const cors = require('cors');
|
||||
|
||||
// --- CONFIGURACIÓN FIREBASE ---
|
||||
// --- FIREBASE INIT ---
|
||||
try {
|
||||
if (process.env.FIREBASE_PRIVATE_KEY) {
|
||||
if (!admin.apps.length) {
|
||||
|
|
@ -39,7 +39,6 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
const send = (type, payload) => res.write(JSON.stringify({ type, payload }) + "\n");
|
||||
|
||||
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||
console.log(`🔔 Orden: ${action} [${provider}]`);
|
||||
|
||||
try {
|
||||
if (provider === 'MULTI') {
|
||||
|
|
@ -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 }); }
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("❌ CRASH:", err.message);
|
||||
send('ERROR', err.message);
|
||||
} finally { res.end(); }
|
||||
});
|
||||
|
||||
// ==================================================================
|
||||
// 🤖 LÓGICA MULTIASISTENCIA V14 (LECTURA DEEP WAIT)
|
||||
// 🤖 LÓGICA MULTIASISTENCIA V15 (SOPORTE FRAMES)
|
||||
// ==================================================================
|
||||
|
||||
async function runMultiStream(mes, anio, send) {
|
||||
|
|
@ -70,19 +68,19 @@ async function runMultiStream(mes, anio, send) {
|
|||
const valD2 = `${anio}`;
|
||||
|
||||
try {
|
||||
send('LOG', `🚀 Iniciando MULTI V14 para: ${valD1}`);
|
||||
send('LOG', `🚀 (MULTI) Iniciando para: ${valD1}`);
|
||||
const { browser: b, page } = await loginMulti();
|
||||
browser = b;
|
||||
|
||||
send('LOG', "📂 Yendo a Cerrados...");
|
||||
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Filtro Fecha
|
||||
// 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(2000);
|
||||
await page.waitForTimeout(2500);
|
||||
}
|
||||
|
||||
// --- FASE 1: RECOLECTAR IDs ---
|
||||
|
|
@ -93,10 +91,11 @@ async function runMultiStream(mes, anio, send) {
|
|||
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 => { if (/^\d{8}$/.test(td.innerText.trim())) lista.push(td.innerText.trim()); });
|
||||
return lista;
|
||||
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
||||
return links.map(a => {
|
||||
const m = a.href.match(/reparacion=(\d+)/);
|
||||
return m ? m[1] : null;
|
||||
}).filter(id => id && /^\d{8}$/.test(id));
|
||||
});
|
||||
|
||||
idsServicios.push(...[...new Set(nuevosIds)]);
|
||||
|
|
@ -110,7 +109,7 @@ async function runMultiStream(mes, anio, send) {
|
|||
idsServicios = [...new Set(idsServicios)];
|
||||
send('LOG', `🔍 Total a revisar: ${idsServicios.length}`);
|
||||
|
||||
// --- FASE 2: LEER DETALLES ---
|
||||
// --- FASE 2: LEER DETALLES (CON FRAMES) ---
|
||||
for (const [index, idServicio] of idsServicios.entries()) {
|
||||
send('PROGRESS', { current: index + 1, total: idsServicios.length });
|
||||
|
||||
|
|
@ -118,60 +117,41 @@ async function runMultiStream(mes, anio, send) {
|
|||
|
||||
try {
|
||||
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 ---
|
||||
const info = await page.evaluate(() => {
|
||||
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
|
||||
// === BÚSQUEDA PROFUNDA EN FRAMES ===
|
||||
let totalStr = "";
|
||||
let importe = 0;
|
||||
if (info.totalStr) {
|
||||
// "53,66 €" -> Quitamos todo menos números y comas -> "53,66" -> replace coma por punto -> 53.66
|
||||
let cleanMoney = info.totalStr.replace(/[^\d,]/g, '').replace(',', '.');
|
||||
|
||||
// 1. Iterar sobre todos los frames (marcos) de la web
|
||||
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;
|
||||
}
|
||||
|
||||
// --- CRUCE CON BASE DE DATOS (PRIORIDAD AL CLIENTE DE LA BD) ---
|
||||
// 3. CONSULTAR BASE DE DATOS Y FORZAR NOMBRE
|
||||
let docId = null;
|
||||
let enBD = false;
|
||||
let clienteFinal = info.clienteWeb; // Por defecto el de la web
|
||||
let direccionFinal = info.direccionWeb;
|
||||
let clienteFinal = "Desconocido"; // Fallback por defecto
|
||||
let direccionFinal = "Sin dirección";
|
||||
|
||||
if (db) {
|
||||
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
|
||||
|
|
@ -180,19 +160,15 @@ async function runMultiStream(mes, anio, send) {
|
|||
docId = doc.id;
|
||||
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();
|
||||
if (datosBD.clientName && datosBD.clientName.length > 2) {
|
||||
clienteFinal = datosBD.clientName;
|
||||
}
|
||||
if (datosBD.address && datosBD.address.length > 5) {
|
||||
direccionFinal = datosBD.address;
|
||||
}
|
||||
|
||||
// PRIORIDAD ABSOLUTA A LOS DATOS DE FIREBASE
|
||||
if (datosBD.clientName) clienteFinal = datosBD.clientName;
|
||||
if (datosBD.address) direccionFinal = datosBD.address;
|
||||
}
|
||||
}
|
||||
|
||||
// ENVIAR
|
||||
// ENVIAR (Verde o Amarillo)
|
||||
send('ITEM_FOUND', {
|
||||
servicio: idServicio,
|
||||
direccion: direccionFinal,
|
||||
|
|
@ -239,7 +215,7 @@ async function loginMulti() {
|
|||
return { browser, page };
|
||||
}
|
||||
|
||||
// ... (RESTO DE FUNCIONES HS Y SAVER SE MANTIENEN IGUAL) ...
|
||||
// ... RESTO DE FUNCIONES (HS, Saver) NO CAMBIAN ...
|
||||
async function runHSScanner() {
|
||||
let browser = null;
|
||||
try {
|
||||
|
|
|
|||
Loading…
Reference in New Issue