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(cors({ origin: '*' }));
|
||||||
app.use(express.json({ limit: '50mb' }));
|
app.use(express.json({ limit: '50mb' }));
|
||||||
|
|
||||||
|
// --- ENDPOINT DE STREAMING ---
|
||||||
app.post('/api/robot-cobros', async (req, res) => {
|
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;
|
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||||
console.log(`🔔 Petición: ${action} [${provider}]`);
|
console.log(`🔔 Orden: ${action} [${provider}]`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (provider === 'MULTI') {
|
if (provider === 'MULTI') {
|
||||||
if (action === 'scan') {
|
if (action === 'scan') {
|
||||||
const lista = await runMultiFullScan(month, year);
|
await runMultiStream(month, year, send);
|
||||||
res.json({ success: true, data: lista });
|
|
||||||
}
|
}
|
||||||
else if (action === 'save_data') {
|
else if (action === 'save_data') {
|
||||||
const count = await runSaver(dataToSave, 'MULTI');
|
const count = await runSaver(dataToSave, 'MULTI');
|
||||||
res.json({ success: true, count });
|
send('DONE', { count });
|
||||||
}
|
}
|
||||||
else { throw new Error("Acción MULTI inválida"); }
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
// HOMESERVE (Mantenemos modo normal por ahora, adaptado a respuesta simple)
|
||||||
if (action === 'scan') {
|
if (action === 'scan') {
|
||||||
const lista = await runHSScanner();
|
const lista = await runHSScanner();
|
||||||
res.json({ success: true, data: lista });
|
send('HS_DATES', lista);
|
||||||
}
|
}
|
||||||
else if (action === 'analyze') {
|
else if (action === 'analyze') {
|
||||||
const analisis = await runHSAnalyzer(url);
|
const analisis = await runHSAnalyzer(url);
|
||||||
res.json({ success: true, ...analisis });
|
send('HS_DATA', analisis);
|
||||||
}
|
}
|
||||||
else if (action === 'save_data') {
|
else if (action === 'save_data') {
|
||||||
const count = await runSaver(dataToSave, 'HS');
|
const count = await runSaver(dataToSave, 'HS');
|
||||||
res.json({ success: true, count });
|
send('DONE', { count });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("❌ CRASH:", err.message);
|
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;
|
let browser = null;
|
||||||
const resultados = [];
|
|
||||||
const noEncontrados = [];
|
|
||||||
const valD1 = `${mes}_${anio}`;
|
const valD1 = `${mes}_${anio}`;
|
||||||
const valD2 = `${anio}`;
|
const valD2 = `${anio}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(`🚀 (MULTI) Iniciando escaneo: ${valD1}`);
|
send('LOG', `🚀 Iniciando robot para: ${valD1}`);
|
||||||
const { browser: b, page } = await loginMulti();
|
const { browser: b, page } = await loginMulti();
|
||||||
browser = b;
|
browser = b;
|
||||||
|
|
||||||
// 1. Ir a Cerrados y Filtrar
|
send('LOG', "📂 Accediendo a Servicios Cerrados...");
|
||||||
console.log("📂 (MULTI) 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"]')) {
|
||||||
|
send('LOG', `📅 Aplicando filtro de fecha...`);
|
||||||
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(2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. RECORRER PÁGINAS (Bucle Principal)
|
// Recolectar IDs
|
||||||
let idsServicios = [];
|
let idsServicios = [];
|
||||||
let tieneSiguiente = true;
|
let tieneSiguiente = true;
|
||||||
let pagActual = 1;
|
let pagActual = 1;
|
||||||
|
|
||||||
while (tieneSiguiente && pagActual <= 10) {
|
while (tieneSiguiente && pagActual <= 10) {
|
||||||
console.log(`📄 (MULTI) Leyendo página ${pagActual}...`);
|
send('LOG', `📄 Leyendo página ${pagActual}...`);
|
||||||
|
|
||||||
// Extraer expedientes de esta página
|
|
||||||
const nuevosIds = await page.evaluate(() => {
|
const nuevosIds = await page.evaluate(() => {
|
||||||
const celdas = Array.from(document.querySelectorAll('td.tdet'));
|
const celdas = Array.from(document.querySelectorAll('td.tdet'));
|
||||||
const lista = [];
|
const lista = [];
|
||||||
celdas.forEach(td => {
|
celdas.forEach(td => {
|
||||||
const txt = td.innerText.trim();
|
if (/^\d{8}$/.test(td.innerText.trim())) lista.push(td.innerText.trim());
|
||||||
// Solo números de 8 cifras (formato expediente multi)
|
|
||||||
if (/^\d{8}$/.test(txt)) lista.push(txt);
|
|
||||||
});
|
});
|
||||||
return lista;
|
return lista;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Añadir a la lista global (sin duplicados de esta página)
|
const unicosPag = [...new Set(nuevosIds)];
|
||||||
const unicosPagina = [...new Set(nuevosIds)];
|
idsServicios.push(...unicosPag);
|
||||||
idsServicios.push(...unicosPagina);
|
send('LOG', ` -> Encontrados ${unicosPag.length} servicios.`);
|
||||||
console.log(` -> Encontrados ${unicosPagina.length} en pág ${pagActual}. Total acumulado: ${idsServicios.length}`);
|
|
||||||
|
|
||||||
// 3. INTENTAR PASAR DE PÁGINA
|
const haySiguiente = await page.$('a:has-text("Página siguiente")');
|
||||||
// Buscamos un enlace que contenga el texto "Página siguiente"
|
if (haySiguiente) {
|
||||||
const btnSiguiente = await page.$('a:has-text("Página siguiente")');
|
await haySiguiente.click();
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
if (btnSiguiente) {
|
|
||||||
console.log(" ➡️ Pasando a la siguiente página...");
|
|
||||||
await btnSiguiente.click();
|
|
||||||
await page.waitForTimeout(2500); // Esperar carga
|
|
||||||
pagActual++;
|
pagActual++;
|
||||||
} else {
|
} else { tieneSiguiente = false; }
|
||||||
console.log(" ⛔ No hay más páginas.");
|
|
||||||
tieneSiguiente = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Limpiar duplicados finales por si acaso
|
|
||||||
idsServicios = [...new Set(idsServicios)];
|
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: [] };
|
// PROCESAR UNO A UNO Y ENVIAR AL MOMENTO
|
||||||
|
for (const [index, idServicio] of idsServicios.entries()) {
|
||||||
// 4. ENTRAR EN CADA SERVICIO PARA VER EL PRECIO
|
send('PROGRESS', { current: index + 1, total: idsServicios.length });
|
||||||
for (const idServicio of idsServicios) {
|
|
||||||
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: 30000, waitUntil: 'domcontentloaded' });
|
await page.goto(urlPresupuesto, { timeout: 45000, waitUntil: 'domcontentloaded' });
|
||||||
// Esperamos un poco para asegurar que Angular/JS cargue el precio
|
|
||||||
await page.waitForTimeout(800);
|
// 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 info = await page.evaluate(() => {
|
||||||
const clean = (t) => t ? t.trim() : "Desconocido";
|
const clean = (t) => t ? t.trim() : "Desconocido";
|
||||||
let cliente = "", direccion = "", totalStr = "0";
|
let cliente = "", direccion = "", totalStr = "0";
|
||||||
|
|
||||||
// A) Datos Cliente
|
// Datos Cliente
|
||||||
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 t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
|
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;
|
if (t.includes("DIRECCIÓN")) direccion = v;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Fallback tablas antiguas
|
// Fallback antiguo
|
||||||
if (!cliente) {
|
if (!cliente) {
|
||||||
const tds = Array.from(document.querySelectorAll('td'));
|
const tds = Array.from(document.querySelectorAll('td'));
|
||||||
for(let i=0; i<tds.length; i++) {
|
for(let i=0; i<tds.length; i++) {
|
||||||
|
|
@ -174,68 +175,61 @@ async function runMultiFullScan(mes, anio) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// B) EL DINERO (Clave del asunto)
|
// PRECIO (Selector exacto que me diste)
|
||||||
// Buscamos celda con atributo data-label="TOTAL REPARACION:" (Tu HTML)
|
|
||||||
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
|
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
|
||||||
if (celdaTotal) {
|
if (celdaTotal) totalStr = celdaTotal.innerText;
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { cliente: clean(cliente), direccion: clean(direccion), totalStr };
|
return { cliente: clean(cliente), direccion: clean(direccion), totalStr };
|
||||||
});
|
});
|
||||||
|
|
||||||
// Limpiar importe
|
|
||||||
let importe = 0;
|
let importe = 0;
|
||||||
if (info.totalStr) {
|
if (info.totalStr) {
|
||||||
let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.');
|
let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.');
|
||||||
importe = Math.abs(parseFloat(cleanMoney) || 0);
|
importe = Math.abs(parseFloat(cleanMoney) || 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(` 📝 Serv: ${idServicio} | Imp: ${importe}€`);
|
// Cruzar con BD
|
||||||
|
let docId = null;
|
||||||
|
let enBD = false;
|
||||||
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();
|
||||||
if (!q.empty) {
|
if (!q.empty) {
|
||||||
q.forEach(doc => {
|
docId = q.docs[0].id;
|
||||||
resultados.push({ servicio: idServicio, direccion: info.direccion, importe, docId: doc.id });
|
enBD = true;
|
||||||
});
|
|
||||||
} else {
|
|
||||||
noEncontrados.push({ servicio: idServicio, direccion: info.direccion, importe });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} 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(); }
|
} catch (e) { throw e; } finally { if(browser) await browser.close(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loginMulti() {
|
async function loginMulti() {
|
||||||
// ... LOGIN DE SIEMPRE (No tocar) ...
|
|
||||||
let user = "", pass = "";
|
let user = "", pass = "";
|
||||||
if (db) {
|
if (db) {
|
||||||
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
||||||
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
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 browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||||
const page = await browser.newPage();
|
const page = await browser.newPage();
|
||||||
|
|
||||||
console.log("🌍 (MULTI) Login...");
|
|
||||||
await page.goto(URLS.MULTI_LOGIN, { timeout: 60000 });
|
await page.goto(URLS.MULTI_LOGIN, { timeout: 60000 });
|
||||||
|
|
||||||
const userFilled = await page.evaluate((u) => {
|
const userFilled = await page.evaluate((u) => {
|
||||||
|
|
@ -252,9 +246,9 @@ async function loginMulti() {
|
||||||
return { browser, page };
|
return { browser, page };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ... (RESTO DE CÓDIGO HOMESERVE Y GUARDADOR IGUAL) ...
|
// ... (Resto de funciones HS y Saver se mantienen igual que la V10) ...
|
||||||
// (Copia las funciones runHSScanner, runHSAnalyzer, loginHS y runSaver del archivo anterior V10 si las necesitas completas aquí, o déjalas como estaban)
|
// IMPORTANTE: Asegúrate de incluirlas aquí abajo (runHSScanner, runHSAnalyzer, runSaver, loginHS)
|
||||||
// Te pongo aquí abajo runSaver y el resto para que sea copiar y pegar fácil.
|
// Copialas del mensaje anterior si hace falta, no cambian.
|
||||||
|
|
||||||
async function runHSScanner() {
|
async function runHSScanner() {
|
||||||
let browser = null;
|
let browser = null;
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue