Actualizar robot_cobros.js
This commit is contained in:
parent
9e957a8498
commit
1cf871b2a3
|
|
@ -49,7 +49,7 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
send('DONE', { count });
|
||||
}
|
||||
} else {
|
||||
// HOMESERVE (Simplificado)
|
||||
// HOMESERVE
|
||||
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 === '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) {
|
||||
|
|
@ -70,13 +70,14 @@ async function runMultiStream(mes, anio, send) {
|
|||
const valD2 = `${anio}`;
|
||||
|
||||
try {
|
||||
send('LOG', `🚀 Iniciando para: ${valD1}`);
|
||||
send('LOG', `🚀 Iniciando MULTI V14 para: ${valD1}`);
|
||||
const { browser: b, page } = await loginMulti();
|
||||
browser = b;
|
||||
|
||||
send('LOG', "📂 Yendo a Servicios Cerrados...");
|
||||
send('LOG', "📂 Yendo a Cerrados...");
|
||||
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Filtro Fecha
|
||||
if (await page.isVisible('select[name="D1"]')) {
|
||||
await page.selectOption('select[name="D1"]', valD1);
|
||||
await page.selectOption('select[name="D2"]', valD2);
|
||||
|
|
@ -98,9 +99,8 @@ async function runMultiStream(mes, anio, send) {
|
|||
return lista;
|
||||
});
|
||||
|
||||
const unicosPag = [...new Set(nuevosIds)];
|
||||
idsServicios.push(...unicosPag);
|
||||
send('LOG', ` -> Encontrados ${unicosPag.length} servicios.`);
|
||||
idsServicios.push(...[...new Set(nuevosIds)]);
|
||||
send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`);
|
||||
|
||||
const haySiguiente = await page.$('a:has-text("Página siguiente")');
|
||||
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`;
|
||||
|
||||
try {
|
||||
await page.goto(urlPresupuesto, { timeout: 45000, waitUntil: 'domcontentloaded' });
|
||||
// Espera crítica para que Angular pinte el precio
|
||||
try { await page.waitForSelector('td[data-label*="TOTAL"]', { timeout: 4000 }); } catch(e){}
|
||||
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||
|
||||
// --- 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, ' ') : "";
|
||||
let cliente = "", direccion = "", totalStr = "";
|
||||
const clean = (t) => t ? t.trim().replace(/\s+/g, ' ') : "Desconocido";
|
||||
let clienteWeb = "", direccionWeb = "", totalStr = "";
|
||||
|
||||
// 1. BUSCAR DIRECCIÓN Y CLIENTE (Iterando los bloques azules)
|
||||
// Buscamos contenedores que tengan título y valor
|
||||
// 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")) cliente = valor;
|
||||
if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccion = valor;
|
||||
if (titulo.includes("CLIENTE")) clienteWeb = valor;
|
||||
if (titulo.includes("DIRECCIÓN") || titulo.includes("DIRECCION")) direccionWeb = valor;
|
||||
});
|
||||
|
||||
// 2. BUSCAR PRECIO (Estrategia agresiva)
|
||||
// A) Por atributo data-label (lo más fiable según tu captura)
|
||||
// 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;
|
||||
|
||||
// B) Si falla, buscar texto visible en cualquier celda
|
||||
if (!totalStr) {
|
||||
const celdas = Array.from(document.querySelectorAll('td, th, div'));
|
||||
const celdaTexto = celdas.find(el => el.innerText && el.innerText.includes("TOTAL REPARACION") && el.innerText.includes("€"));
|
||||
if(celdaTexto) totalStr = celdaTexto.innerText.split("TOTAL")[1] || celdaTexto.innerText;
|
||||
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 { cliente: clean(cliente), direccion: clean(direccion), totalStr };
|
||||
return { clienteWeb: clean(clienteWeb), direccionWeb: clean(direccionWeb), totalStr };
|
||||
});
|
||||
|
||||
// LIMPIAR PRECIO
|
||||
// LIMPIEZA DE PRECIO
|
||||
let importe = 0;
|
||||
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(',', '.');
|
||||
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 enBD = false;
|
||||
let direccionBD = "";
|
||||
let clienteFinal = info.clienteWeb; // Por defecto el de la web
|
||||
let direccionFinal = info.direccionWeb;
|
||||
|
||||
if (db) {
|
||||
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];
|
||||
docId = doc.id;
|
||||
enBD = true;
|
||||
direccionBD = doc.data().address || "";
|
||||
|
||||
// ¡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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SI LA WEB NO DA DIRECCIÓN, USAR LA DE LA BD (O viceversa)
|
||||
const direccionFinal = info.direccion && info.direccion.length > 3 ? info.direccion : (direccionBD || "Desconocido");
|
||||
|
||||
// ENVIAR
|
||||
send('ITEM_FOUND', {
|
||||
servicio: idServicio,
|
||||
direccion: direccionFinal,
|
||||
cliente: info.cliente,
|
||||
cliente: clienteFinal,
|
||||
importe: importe,
|
||||
enBD: enBD,
|
||||
docId: docId
|
||||
|
|
@ -224,7 +239,7 @@ async function loginMulti() {
|
|||
return { browser, page };
|
||||
}
|
||||
|
||||
// ... (RESTO DE FUNCIONES HS Y SAVER IGUALES) ...
|
||||
// ... (RESTO DE FUNCIONES HS Y SAVER SE MANTIENEN IGUAL) ...
|
||||
async function runHSScanner() {
|
||||
let browser = null;
|
||||
try {
|
||||
|
|
@ -303,13 +318,7 @@ async function runSaver(items, providerType) {
|
|||
const nowISO = new Date().toISOString();
|
||||
let count = 0;
|
||||
items.forEach(item => {
|
||||
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio); // Fallback al servicio si no hay docId (caso nuevo)
|
||||
|
||||
// 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.
|
||||
|
||||
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio);
|
||||
if (item.enBD || item.docId) {
|
||||
const updateData = { paidAmount: item.importe, paymentState: "Pagado", status: 'completed', paymentDate: nowISO, lastUpdatedByRobot: nowISO };
|
||||
if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified';
|
||||
|
|
@ -318,7 +327,6 @@ async function runSaver(items, providerType) {
|
|||
count++;
|
||||
}
|
||||
});
|
||||
// Solo hacemos commit de lo que está en BD
|
||||
if(count > 0) await batch.commit();
|
||||
return count;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue