Actualizar robot_cobros.js

This commit is contained in:
marsalva 2025-12-30 10:03:15 +00:00
parent 9e957a8498
commit 1cf871b2a3
1 changed files with 52 additions and 44 deletions

View File

@ -49,7 +49,7 @@ app.post('/api/robot-cobros', async (req, res) => {
send('DONE', { count }); send('DONE', { count });
} }
} else { } else {
// HOMESERVE (Simplificado) // HOMESERVE
if (action === 'scan') { const l = await runHSScanner(); send('HS_DATES', l); } if (action === 'scan') { const l = await runHSScanner(); send('HS_DATES', l); }
else if (action === 'analyze') { const a = await runHSAnalyzer(url); send('HS_DATA', a); } else if (action === 'analyze') { const a = await runHSAnalyzer(url); send('HS_DATA', a); }
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 }); }
@ -61,7 +61,7 @@ app.post('/api/robot-cobros', async (req, res) => {
}); });
// ================================================================== // ==================================================================
// 🤖 LÓGICA MULTIASISTENCIA V13 (LECTURA MEJORADA) // 🤖 LÓGICA MULTIASISTENCIA V14 (LECTURA DEEP WAIT)
// ================================================================== // ==================================================================
async function runMultiStream(mes, anio, send) { async function runMultiStream(mes, anio, send) {
@ -70,13 +70,14 @@ async function runMultiStream(mes, anio, send) {
const valD2 = `${anio}`; const valD2 = `${anio}`;
try { try {
send('LOG', `🚀 Iniciando para: ${valD1}`); send('LOG', `🚀 Iniciando MULTI V14 para: ${valD1}`);
const { browser: b, page } = await loginMulti(); const { browser: b, page } = await loginMulti();
browser = b; browser = b;
send('LOG', "📂 Yendo a Servicios Cerrados..."); send('LOG', "📂 Yendo a Cerrados...");
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' }); await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
// Filtro Fecha
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);
@ -98,9 +99,8 @@ async function runMultiStream(mes, anio, send) {
return lista; return lista;
}); });
const unicosPag = [...new Set(nuevosIds)]; idsServicios.push(...[...new Set(nuevosIds)]);
idsServicios.push(...unicosPag); send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`);
send('LOG', ` -> Encontrados ${unicosPag.length} servicios.`);
const haySiguiente = await page.$('a:has-text("Página siguiente")'); const haySiguiente = await page.$('a:has-text("Página siguiente")');
if (haySiguiente) { await haySiguiente.click(); await page.waitForTimeout(3000); pagActual++; } if (haySiguiente) { await haySiguiente.click(); await page.waitForTimeout(3000); pagActual++; }
@ -117,52 +117,61 @@ async function runMultiStream(mes, anio, send) {
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: 60000, waitUntil: 'domcontentloaded' });
// Espera crítica para que Angular pinte el precio
try { await page.waitForSelector('td[data-label*="TOTAL"]', { timeout: 4000 }); } catch(e){}
// --- 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 info = await page.evaluate(() => {
const clean = (t) => t ? t.trim().replace(/\s+/g, ' ') : ""; const clean = (t) => t ? t.trim().replace(/\s+/g, ' ') : "Desconocido";
let cliente = "", direccion = "", totalStr = ""; let clienteWeb = "", direccionWeb = "", totalStr = "";
// 1. BUSCAR DIRECCIÓN Y CLIENTE (Iterando los bloques azules) // 1. CLIENTE Y DIRECCIÓN (Buscamos en los bloques azules)
// Buscamos contenedores que tengan título y valor
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 titulo = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || ""; const titulo = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
const valor = b.querySelector('.policy-info-value')?.innerText || ""; const valor = b.querySelector('.policy-info-value')?.innerText || "";
if (titulo.includes("CLIENTE")) cliente = valor; if (titulo.includes("CLIENTE")) clienteWeb = valor;
if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccion = valor; if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccionWeb = valor;
}); });
// 2. BUSCAR PRECIO (Estrategia agresiva) // 2. PRECIO (Buscamos por el atributo data-label exacto que me pasaste)
// A) Por atributo data-label (lo más fiable según tu captura) // Primero intentamos el selector preciso
const celdaDataLabel = document.querySelector('td[data-label*="TOTAL REPARACION"]'); const celdaDataLabel = document.querySelector('td[data-label*="TOTAL REPARACION"]');
if (celdaDataLabel) totalStr = celdaDataLabel.innerText; if (celdaDataLabel) {
totalStr = celdaDataLabel.innerText;
// B) Si falla, buscar texto visible en cualquier celda } else {
if (!totalStr) { // Si falla, buscamos cualquier celda que contenga "TOTAL REPARACION" y el símbolo "€"
const celdas = Array.from(document.querySelectorAll('td, th, div')); const celdas = Array.from(document.querySelectorAll('td'));
const celdaTexto = celdas.find(el => el.innerText && el.innerText.includes("TOTAL REPARACION") && el.innerText.includes("€")); const celdaTexto = celdas.find(el => el.innerText.toUpperCase().includes("TOTAL REPARACION") && el.innerText.includes("€"));
if(celdaTexto) totalStr = celdaTexto.innerText.split("TOTAL")[1] || celdaTexto.innerText; if (celdaTexto) {
// A veces viene sucio "TOTAL REPARACION: 53 €", limpiamos
totalStr = celdaTexto.innerText.replace("TOTAL REPARACION", "").replace(":", "");
}
} }
return { cliente: clean(cliente), direccion: clean(direccion), totalStr }; return { clienteWeb: clean(clienteWeb), direccionWeb: clean(direccionWeb), totalStr };
}); });
// LIMPIAR PRECIO // LIMPIEZA DE PRECIO
let importe = 0; let importe = 0;
if (info.totalStr) { if (info.totalStr) {
// Quitamos símbolos raros, espacios, letras... dejamos solo números y coma // "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(',', '.'); let cleanMoney = info.totalStr.replace(/[^\d,]/g, '').replace(',', '.');
importe = parseFloat(cleanMoney) || 0; importe = parseFloat(cleanMoney) || 0;
} }
// CONSULTAR BASE DE DATOS (Para saber el color) // --- CRUCE CON BASE DE DATOS (PRIORIDAD AL CLIENTE DE LA BD) ---
let docId = null; let docId = null;
let enBD = false; let enBD = false;
let direccionBD = ""; let clienteFinal = info.clienteWeb; // Por defecto el de la web
let direccionFinal = info.direccionWeb;
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();
@ -170,18 +179,24 @@ async function runMultiStream(mes, anio, send) {
const doc = q.docs[0]; const doc = q.docs[0];
docId = doc.id; docId = doc.id;
enBD = true; enBD = true;
direccionBD = doc.data().address || "";
}
}
// SI LA WEB NO DA DIRECCIÓN, USAR LA DE LA BD (O viceversa) // ¡AQUÍ ESTÁ EL ARREGLO!
const direccionFinal = info.direccion && info.direccion.length > 3 ? info.direccion : (direccionBD || "Desconocido"); // 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;
}
}
}
// ENVIAR // ENVIAR
send('ITEM_FOUND', { send('ITEM_FOUND', {
servicio: idServicio, servicio: idServicio,
direccion: direccionFinal, direccion: direccionFinal,
cliente: info.cliente, cliente: clienteFinal,
importe: importe, importe: importe,
enBD: enBD, enBD: enBD,
docId: docId docId: docId
@ -224,7 +239,7 @@ async function loginMulti() {
return { browser, page }; return { browser, page };
} }
// ... (RESTO DE FUNCIONES HS Y SAVER IGUALES) ... // ... (RESTO DE FUNCIONES HS Y SAVER SE MANTIENEN IGUAL) ...
async function runHSScanner() { async function runHSScanner() {
let browser = null; let browser = null;
try { try {
@ -303,13 +318,7 @@ async function runSaver(items, providerType) {
const nowISO = new Date().toISOString(); const nowISO = new Date().toISOString();
let count = 0; let count = 0;
items.forEach(item => { items.forEach(item => {
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio); // Fallback al servicio si no hay docId (caso nuevo) const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio);
// Si el documento no existe, lo creamos con lo básico (opcional)
// Pero tu petición es guardar importes en servicios existentes.
// Si no existe, no hacemos update, o hacemos un set con merge.
// Asumo update si existe.
if (item.enBD || item.docId) { if (item.enBD || item.docId) {
const updateData = { paidAmount: item.importe, paymentState: "Pagado", status: 'completed', paymentDate: nowISO, lastUpdatedByRobot: nowISO }; const updateData = { 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';
@ -318,7 +327,6 @@ async function runSaver(items, providerType) {
count++; count++;
} }
}); });
// Solo hacemos commit de lo que está en BD
if(count > 0) await batch.commit(); if(count > 0) await batch.commit();
return count; return count;
} }