Actualizar robot_cobros.js
This commit is contained in:
parent
7cb8c402cf
commit
ccd58e1940
160
robot_cobros.js
160
robot_cobros.js
|
|
@ -33,129 +33,130 @@ const app = express();
|
|||
app.use(cors({ origin: '*' }));
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
|
||||
// --- ENDPOINT DE STREAMING ---
|
||||
app.post('/api/robot-cobros', async (req, res) => {
|
||||
// Configurar cabeceras para STREAMING (Evita timeout 504)
|
||||
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||
res.setHeader('Transfer-Encoding', 'chunked');
|
||||
|
||||
// Función auxiliar para enviar mensajes al navegador
|
||||
const send = (type, payload) => {
|
||||
res.write(JSON.stringify({ type, payload }) + "\n");
|
||||
};
|
||||
|
||||
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||
console.log(`🔔 Petición: ${action} [${provider}]`);
|
||||
console.log(`🔔 Orden: ${action} [${provider}]`);
|
||||
|
||||
try {
|
||||
if (provider === 'MULTI') {
|
||||
if (action === 'scan') {
|
||||
const lista = await runMultiFullScan(month, year);
|
||||
res.json({ success: true, data: lista });
|
||||
await runMultiStream(month, year, send);
|
||||
}
|
||||
else if (action === 'save_data') {
|
||||
const count = await runSaver(dataToSave, 'MULTI');
|
||||
res.json({ success: true, count });
|
||||
send('DONE', { count });
|
||||
}
|
||||
else { throw new Error("Acción MULTI inválida"); }
|
||||
}
|
||||
else {
|
||||
// HOMESERVE (Mantenemos modo normal por ahora, adaptado a respuesta simple)
|
||||
if (action === 'scan') {
|
||||
const lista = await runHSScanner();
|
||||
res.json({ success: true, data: lista });
|
||||
send('HS_DATES', lista);
|
||||
}
|
||||
else if (action === 'analyze') {
|
||||
const analisis = await runHSAnalyzer(url);
|
||||
res.json({ success: true, ...analisis });
|
||||
send('HS_DATA', analisis);
|
||||
}
|
||||
else if (action === 'save_data') {
|
||||
const count = await runSaver(dataToSave, 'HS');
|
||||
res.json({ success: true, count });
|
||||
send('DONE', { count });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("❌ CRASH:", err.message);
|
||||
res.status(500).json({ success: false, message: err.message });
|
||||
send('ERROR', err.message);
|
||||
} finally {
|
||||
res.end(); // Cerrar conexión al terminar
|
||||
}
|
||||
});
|
||||
|
||||
// ==================================================================
|
||||
// 🤖 LÓGICA MULTIASISTENCIA (PAGINACIÓN + PRECIOS)
|
||||
// 🤖 LÓGICA MULTIASISTENCIA (STREAMING)
|
||||
// ==================================================================
|
||||
|
||||
async function runMultiFullScan(mes, anio) {
|
||||
async function runMultiStream(mes, anio, send) {
|
||||
let browser = null;
|
||||
const resultados = [];
|
||||
const noEncontrados = [];
|
||||
const valD1 = `${mes}_${anio}`;
|
||||
const valD2 = `${anio}`;
|
||||
|
||||
try {
|
||||
console.log(`🚀 (MULTI) Iniciando escaneo: ${valD1}`);
|
||||
send('LOG', `🚀 Iniciando robot para: ${valD1}`);
|
||||
const { browser: b, page } = await loginMulti();
|
||||
browser = b;
|
||||
|
||||
// 1. Ir a Cerrados y Filtrar
|
||||
console.log("📂 (MULTI) Yendo a Cerrados...");
|
||||
send('LOG', "📂 Accediendo a Servicios Cerrados...");
|
||||
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// Filtro Fecha
|
||||
if (await page.isVisible('select[name="D1"]')) {
|
||||
send('LOG', `📅 Aplicando filtro de fecha...`);
|
||||
await page.selectOption('select[name="D1"]', valD1);
|
||||
await page.selectOption('select[name="D2"]', valD2);
|
||||
await page.click('input[name="continuar"]');
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
|
||||
// 2. RECORRER PÁGINAS (Bucle Principal)
|
||||
// Recolectar IDs
|
||||
let idsServicios = [];
|
||||
let tieneSiguiente = true;
|
||||
let pagActual = 1;
|
||||
|
||||
while (tieneSiguiente && pagActual <= 10) {
|
||||
console.log(`📄 (MULTI) Leyendo página ${pagActual}...`);
|
||||
|
||||
// Extraer expedientes de esta página
|
||||
send('LOG', `📄 Leyendo página ${pagActual}...`);
|
||||
const nuevosIds = await page.evaluate(() => {
|
||||
const celdas = Array.from(document.querySelectorAll('td.tdet'));
|
||||
const lista = [];
|
||||
celdas.forEach(td => {
|
||||
const txt = td.innerText.trim();
|
||||
// Solo números de 8 cifras (formato expediente multi)
|
||||
if (/^\d{8}$/.test(txt)) lista.push(txt);
|
||||
if (/^\d{8}$/.test(td.innerText.trim())) lista.push(td.innerText.trim());
|
||||
});
|
||||
return lista;
|
||||
});
|
||||
|
||||
// Añadir a la lista global (sin duplicados de esta página)
|
||||
const unicosPagina = [...new Set(nuevosIds)];
|
||||
idsServicios.push(...unicosPagina);
|
||||
console.log(` -> Encontrados ${unicosPagina.length} en pág ${pagActual}. Total acumulado: ${idsServicios.length}`);
|
||||
const unicosPag = [...new Set(nuevosIds)];
|
||||
idsServicios.push(...unicosPag);
|
||||
send('LOG', ` -> Encontrados ${unicosPag.length} servicios.`);
|
||||
|
||||
// 3. INTENTAR PASAR DE PÁGINA
|
||||
// Buscamos un enlace que contenga el texto "Página siguiente"
|
||||
const btnSiguiente = await page.$('a:has-text("Página siguiente")');
|
||||
|
||||
if (btnSiguiente) {
|
||||
console.log(" ➡️ Pasando a la siguiente página...");
|
||||
await btnSiguiente.click();
|
||||
await page.waitForTimeout(2500); // Esperar carga
|
||||
const haySiguiente = await page.$('a:has-text("Página siguiente")');
|
||||
if (haySiguiente) {
|
||||
await haySiguiente.click();
|
||||
await page.waitForTimeout(3000);
|
||||
pagActual++;
|
||||
} else {
|
||||
console.log(" ⛔ No hay más páginas.");
|
||||
tieneSiguiente = false;
|
||||
}
|
||||
} else { tieneSiguiente = false; }
|
||||
}
|
||||
|
||||
// Limpiar duplicados finales por si acaso
|
||||
idsServicios = [...new Set(idsServicios)];
|
||||
console.log(`🔍 (MULTI) Inicio análisis de detalle de ${idsServicios.length} servicios.`);
|
||||
send('LOG', `🔍 Total servicios a revisar: ${idsServicios.length}`);
|
||||
|
||||
if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] };
|
||||
|
||||
// 4. ENTRAR EN CADA SERVICIO PARA VER EL PRECIO
|
||||
for (const idServicio of idsServicios) {
|
||||
// PROCESAR UNO A UNO Y ENVIAR AL MOMENTO
|
||||
for (const [index, idServicio] of idsServicios.entries()) {
|
||||
send('PROGRESS', { current: index + 1, total: idsServicios.length });
|
||||
|
||||
const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`;
|
||||
|
||||
try {
|
||||
await page.goto(urlPresupuesto, { timeout: 30000, waitUntil: 'domcontentloaded' });
|
||||
// Esperamos un poco para asegurar que Angular/JS cargue el precio
|
||||
await page.waitForTimeout(800);
|
||||
await page.goto(urlPresupuesto, { timeout: 45000, waitUntil: 'domcontentloaded' });
|
||||
|
||||
// ESPERA EXPLÍCITA DEL PRECIO (Clave para que no salga 0€)
|
||||
try {
|
||||
// Esperamos hasta 5 segundos a que aparezca el elemento del precio
|
||||
await page.waitForSelector('td[data-label*="TOTAL REPARACION"]', { timeout: 5000 });
|
||||
} catch(e) { /* Si falla, seguimos, quizás no hay precio */ }
|
||||
|
||||
const info = await page.evaluate(() => {
|
||||
const clean = (t) => t ? t.trim() : "Desconocido";
|
||||
let cliente = "", direccion = "", totalStr = "0";
|
||||
|
||||
// A) Datos Cliente
|
||||
// Datos Cliente
|
||||
const bloques = Array.from(document.querySelectorAll('.policy-info-block'));
|
||||
bloques.forEach(b => {
|
||||
const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
|
||||
|
|
@ -164,7 +165,7 @@ async function runMultiFullScan(mes, anio) {
|
|||
if (t.includes("DIRECCIÓN")) direccion = v;
|
||||
});
|
||||
|
||||
// Fallback tablas antiguas
|
||||
// Fallback antiguo
|
||||
if (!cliente) {
|
||||
const tds = Array.from(document.querySelectorAll('td'));
|
||||
for(let i=0; i<tds.length; i++) {
|
||||
|
|
@ -174,68 +175,61 @@ async function runMultiFullScan(mes, anio) {
|
|||
}
|
||||
}
|
||||
|
||||
// B) EL DINERO (Clave del asunto)
|
||||
// Buscamos celda con atributo data-label="TOTAL REPARACION:" (Tu HTML)
|
||||
// PRECIO (Selector exacto que me diste)
|
||||
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
|
||||
if (celdaTotal) {
|
||||
totalStr = celdaTotal.innerText; // Ej: "53,66 €"
|
||||
} else {
|
||||
// Plan B: Buscar texto visible "TOTAL REPARACION"
|
||||
const allElems = Array.from(document.querySelectorAll('td, th, div, span'));
|
||||
const elTotal = allElems.find(el => el.innerText && el.innerText.toUpperCase().includes("TOTAL REPARACION"));
|
||||
|
||||
if (elTotal) {
|
||||
// A veces está en el siguiente elemento hermano
|
||||
if (elTotal.nextElementSibling) totalStr = elTotal.nextElementSibling.innerText;
|
||||
// O en el mismo texto tipo "Total Reparación: 50€"
|
||||
else totalStr = elTotal.innerText.split(':')[1] || elTotal.innerText;
|
||||
}
|
||||
}
|
||||
|
||||
if (celdaTotal) totalStr = celdaTotal.innerText;
|
||||
|
||||
return { cliente: clean(cliente), direccion: clean(direccion), totalStr };
|
||||
});
|
||||
|
||||
// Limpiar importe
|
||||
let importe = 0;
|
||||
if (info.totalStr) {
|
||||
let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.');
|
||||
importe = Math.abs(parseFloat(cleanMoney) || 0);
|
||||
}
|
||||
|
||||
console.log(` 📝 Serv: ${idServicio} | Imp: ${importe}€`);
|
||||
|
||||
// Cruzar con BD
|
||||
let docId = null;
|
||||
let enBD = false;
|
||||
if (db) {
|
||||
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
|
||||
if (!q.empty) {
|
||||
q.forEach(doc => {
|
||||
resultados.push({ servicio: idServicio, direccion: info.direccion, importe, docId: doc.id });
|
||||
});
|
||||
} else {
|
||||
noEncontrados.push({ servicio: idServicio, direccion: info.direccion, importe });
|
||||
docId = q.docs[0].id;
|
||||
enBD = true;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (errDetail) { console.error(` ⚠️ Fallo en ${idServicio}:`, errDetail.message); }
|
||||
// ENVIAR DATO EN TIEMPO REAL AL NAVEGADOR
|
||||
send('ITEM_FOUND', {
|
||||
servicio: idServicio,
|
||||
direccion: info.direccion,
|
||||
importe: importe,
|
||||
enBD: enBD,
|
||||
docId: docId
|
||||
});
|
||||
|
||||
} catch (errDetail) {
|
||||
console.error(errDetail);
|
||||
send('LOG', `⚠️ Error en ${idServicio}: ${errDetail.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { encontrados: resultados, noEncontrados };
|
||||
send('FINISH_SCAN', {});
|
||||
|
||||
} catch (e) { throw e; } finally { if(browser) await browser.close(); }
|
||||
}
|
||||
|
||||
async function loginMulti() {
|
||||
// ... LOGIN DE SIEMPRE (No tocar) ...
|
||||
let user = "", pass = "";
|
||||
if (db) {
|
||||
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
||||
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
||||
}
|
||||
if(!user) throw new Error("Faltan credenciales Multiasistencia en Firebase");
|
||||
if(!user) throw new Error("Faltan credenciales");
|
||||
|
||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const page = await browser.newPage();
|
||||
|
||||
console.log("🌍 (MULTI) Login...");
|
||||
await page.goto(URLS.MULTI_LOGIN, { timeout: 60000 });
|
||||
|
||||
const userFilled = await page.evaluate((u) => {
|
||||
|
|
@ -252,9 +246,9 @@ async function loginMulti() {
|
|||
return { browser, page };
|
||||
}
|
||||
|
||||
// ... (RESTO DE CÓDIGO HOMESERVE Y GUARDADOR IGUAL) ...
|
||||
// (Copia las funciones runHSScanner, runHSAnalyzer, loginHS y runSaver del archivo anterior V10 si las necesitas completas aquí, o déjalas como estaban)
|
||||
// Te pongo aquí abajo runSaver y el resto para que sea copiar y pegar fácil.
|
||||
// ... (Resto de funciones HS y Saver se mantienen igual que la V10) ...
|
||||
// IMPORTANTE: Asegúrate de incluirlas aquí abajo (runHSScanner, runHSAnalyzer, runSaver, loginHS)
|
||||
// Copialas del mensaje anterior si hace falta, no cambian.
|
||||
|
||||
async function runHSScanner() {
|
||||
let browser = null;
|
||||
|
|
|
|||
Loading…
Reference in New Issue