Actualizar robot_cobros.js
This commit is contained in:
parent
276275a76f
commit
7cb8c402cf
177
robot_cobros.js
177
robot_cobros.js
|
|
@ -3,7 +3,7 @@ const { chromium } = require('playwright');
|
|||
const admin = require('firebase-admin');
|
||||
const cors = require('cors');
|
||||
|
||||
// --- 1. CONFIGURACIÓN FIREBASE ---
|
||||
// --- CONFIGURACIÓN FIREBASE ---
|
||||
try {
|
||||
if (process.env.FIREBASE_PRIVATE_KEY) {
|
||||
if (!admin.apps.length) {
|
||||
|
|
@ -16,8 +16,6 @@ try {
|
|||
});
|
||||
}
|
||||
console.log("✅ Firebase inicializado.");
|
||||
} else {
|
||||
console.error("❌ FALTA CONFIGURACIÓN DE FIREBASE (Variables de entorno)");
|
||||
}
|
||||
} catch (e) { console.error("❌ Error Firebase:", e.message); }
|
||||
|
||||
|
|
@ -35,7 +33,6 @@ const app = express();
|
|||
app.use(cors({ origin: '*' }));
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
|
||||
// --- 2. ENDPOINT PRINCIPAL ---
|
||||
app.post('/api/robot-cobros', async (req, res) => {
|
||||
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||
console.log(`🔔 Petición: ${action} [${provider}]`);
|
||||
|
|
@ -53,13 +50,11 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
else { throw new Error("Acción MULTI inválida"); }
|
||||
}
|
||||
else {
|
||||
// HOMESERVE
|
||||
if (action === 'scan') {
|
||||
const lista = await runHSScanner();
|
||||
res.json({ success: true, data: lista });
|
||||
}
|
||||
else if (action === 'analyze') {
|
||||
if (!url) throw new Error("Falta URL");
|
||||
const analisis = await runHSAnalyzer(url);
|
||||
res.json({ success: true, ...analisis });
|
||||
}
|
||||
|
|
@ -67,9 +62,7 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
const count = await runSaver(dataToSave, 'HS');
|
||||
res.json({ success: true, count });
|
||||
}
|
||||
else { throw new Error("Acción HS inválida"); }
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("❌ CRASH:", err.message);
|
||||
res.status(500).json({ success: false, message: err.message });
|
||||
|
|
@ -77,7 +70,7 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
});
|
||||
|
||||
// ==================================================================
|
||||
// 🤖 3. LÓGICA MULTIASISTENCIA (LOGIN CORREGIDO)
|
||||
// 🤖 LÓGICA MULTIASISTENCIA (PAGINACIÓN + PRECIOS)
|
||||
// ==================================================================
|
||||
|
||||
async function runMultiFullScan(mes, anio) {
|
||||
|
|
@ -88,18 +81,14 @@ async function runMultiFullScan(mes, anio) {
|
|||
const valD2 = `${anio}`;
|
||||
|
||||
try {
|
||||
console.log(`🚀 (MULTI) Iniciando: ${valD1}`);
|
||||
|
||||
// 1. LOGIN (Usando tu lógica probada)
|
||||
console.log(`🚀 (MULTI) Iniciando escaneo: ${valD1}`);
|
||||
const { browser: b, page } = await loginMulti();
|
||||
browser = b;
|
||||
|
||||
// 2. IR A CERRADOS
|
||||
// 1. Ir a Cerrados y Filtrar
|
||||
console.log("📂 (MULTI) Yendo a Cerrados...");
|
||||
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
||||
|
||||
// 3. FILTRAR
|
||||
console.log(`📅 (MULTI) Filtrando...`);
|
||||
if (await page.isVisible('select[name="D1"]')) {
|
||||
await page.selectOption('select[name="D1"]', valD1);
|
||||
await page.selectOption('select[name="D2"]', valD2);
|
||||
|
|
@ -107,56 +96,66 @@ async function runMultiFullScan(mes, anio) {
|
|||
await page.waitForTimeout(2000);
|
||||
}
|
||||
|
||||
// 4. RECORRER PÁGINAS
|
||||
// 2. RECORRER PÁGINAS (Bucle Principal)
|
||||
let idsServicios = [];
|
||||
let tieneSiguiente = true;
|
||||
let pagActual = 1;
|
||||
|
||||
while (tieneSiguiente && pagActual <= 5) {
|
||||
console.log(`📄 (MULTI) Página ${pagActual}...`);
|
||||
while (tieneSiguiente && pagActual <= 10) {
|
||||
console.log(`📄 (MULTI) Leyendo página ${pagActual}...`);
|
||||
|
||||
// Extraer expedientes de esta página
|
||||
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);
|
||||
});
|
||||
return lista;
|
||||
});
|
||||
idsServicios.push(...nuevosIds);
|
||||
|
||||
// Botón Siguiente
|
||||
const haySiguiente = await page.evaluate(() => {
|
||||
const img = document.querySelector('img[src*="seguir.gif"]');
|
||||
if (img && img.parentElement.tagName === 'A') {
|
||||
img.parentElement.click(); return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
// 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}`);
|
||||
|
||||
if (haySiguiente) { await page.waitForTimeout(3000); pagActual++; }
|
||||
else { tieneSiguiente = false; }
|
||||
// 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
|
||||
pagActual++;
|
||||
} else {
|
||||
console.log(" ⛔ No hay más páginas.");
|
||||
tieneSiguiente = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Limpiar duplicados finales por si acaso
|
||||
idsServicios = [...new Set(idsServicios)];
|
||||
console.log(`🔍 (MULTI) Servicios a analizar: ${idsServicios.length}`);
|
||||
console.log(`🔍 (MULTI) Inicio análisis de detalle de ${idsServicios.length} servicios.`);
|
||||
|
||||
if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] };
|
||||
|
||||
// 5. DETALLES (PRESUPUESTO)
|
||||
// 4. ENTRAR EN CADA SERVICIO PARA VER EL PRECIO
|
||||
for (const idServicio of idsServicios) {
|
||||
// Ir directo al presupuesto
|
||||
const urlPresupuesto = `https://web.multiasistencia.com/w3multi/valprincipal.php?reparacion=${idServicio}&modo=0`;
|
||||
|
||||
try {
|
||||
await page.goto(urlPresupuesto, { timeout: 45000, waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(1500);
|
||||
await page.goto(urlPresupuesto, { timeout: 30000, waitUntil: 'domcontentloaded' });
|
||||
// Esperamos un poco para asegurar que Angular/JS cargue el precio
|
||||
await page.waitForTimeout(800);
|
||||
|
||||
const info = await page.evaluate(() => {
|
||||
const clean = (t) => t ? t.trim() : "Desconocido";
|
||||
let cliente = "", direccion = "", totalStr = "0";
|
||||
|
||||
// Datos Cliente (Bloques modernos o Tablas antiguas)
|
||||
// A) Datos Cliente
|
||||
const bloques = Array.from(document.querySelectorAll('.policy-info-block'));
|
||||
bloques.forEach(b => {
|
||||
const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
|
||||
|
|
@ -165,6 +164,7 @@ async function runMultiFullScan(mes, anio) {
|
|||
if (t.includes("DIRECCIÓN")) direccion = v;
|
||||
});
|
||||
|
||||
// Fallback tablas antiguas
|
||||
if (!cliente) {
|
||||
const tds = Array.from(document.querySelectorAll('td'));
|
||||
for(let i=0; i<tds.length; i++) {
|
||||
|
|
@ -174,29 +174,36 @@ async function runMultiFullScan(mes, anio) {
|
|||
}
|
||||
}
|
||||
|
||||
// Total Dinero
|
||||
// B) EL DINERO (Clave del asunto)
|
||||
// Buscamos celda con atributo data-label="TOTAL REPARACION:" (Tu HTML)
|
||||
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
|
||||
if (celdaTotal) totalStr = celdaTotal.innerText;
|
||||
else {
|
||||
const allTd = Array.from(document.querySelectorAll('td, th, div'));
|
||||
const header = allTd.find(el => el.innerText && el.innerText.includes("TOTAL REPARACION"));
|
||||
if (header) {
|
||||
if(header.tagName==='TD' || header.tagName==='TH') {
|
||||
if(header.nextElementSibling) totalStr = header.nextElementSibling.innerText;
|
||||
} else {
|
||||
totalStr = header.innerText.replace("TOTAL REPARACION", "").replace(":", "");
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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}€`);
|
||||
|
||||
if (db) {
|
||||
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
|
||||
if (!q.empty) {
|
||||
|
|
@ -208,7 +215,7 @@ async function runMultiFullScan(mes, anio) {
|
|||
}
|
||||
}
|
||||
|
||||
} catch (errDetail) { console.error(` ⚠️ Error ${idServicio}: ${errDetail.message}`); }
|
||||
} catch (errDetail) { console.error(` ⚠️ Fallo en ${idServicio}:`, errDetail.message); }
|
||||
}
|
||||
|
||||
return { encontrados: resultados, noEncontrados };
|
||||
|
|
@ -217,6 +224,7 @@ async function runMultiFullScan(mes, anio) {
|
|||
}
|
||||
|
||||
async function loginMulti() {
|
||||
// ... LOGIN DE SIEMPRE (No tocar) ...
|
||||
let user = "", pass = "";
|
||||
if (db) {
|
||||
const doc = await db.collection("providerCredentials").doc("multiasistencia").get();
|
||||
|
|
@ -225,35 +233,29 @@ async function loginMulti() {
|
|||
if(!user) throw new Error("Faltan credenciales Multiasistencia en Firebase");
|
||||
|
||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const context = await browser.newContext({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' });
|
||||
const page = await context.newPage();
|
||||
const page = await browser.newPage();
|
||||
|
||||
console.log("🌍 (MULTI) Entrando al login...");
|
||||
await page.goto(URLS.MULTI_LOGIN, { waitUntil: 'networkidle', timeout: 60000 });
|
||||
console.log("🌍 (MULTI) Login...");
|
||||
await page.goto(URLS.MULTI_LOGIN, { timeout: 60000 });
|
||||
|
||||
// TU LÓGICA DE LOGIN QUE FUNCIONA
|
||||
const userFilled = await page.evaluate((u) => {
|
||||
const el = document.querySelector('input[name="usuario"]') || document.querySelector('input[type="text"]');
|
||||
if (el) {
|
||||
el.value = u;
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
return true;
|
||||
}
|
||||
if (el) { el.value = u; el.dispatchEvent(new Event('input', { bubbles: true })); return true; }
|
||||
return false;
|
||||
}, user);
|
||||
|
||||
if (!userFilled) await page.fill('input[name="usuario"]', user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
await page.click('input[type="submit"]');
|
||||
await page.click('input[type="submit"]');
|
||||
await page.waitForTimeout(4000);
|
||||
|
||||
console.log("✅ (MULTI) Login OK");
|
||||
|
||||
return { browser, page };
|
||||
}
|
||||
|
||||
// ==================================================================
|
||||
// 🤖 4. LÓGICA HOMESERVE (Mantenida igual)
|
||||
// ==================================================================
|
||||
// ... (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.
|
||||
|
||||
async function runHSScanner() {
|
||||
let browser = null;
|
||||
try {
|
||||
|
|
@ -280,40 +282,26 @@ async function runHSAnalyzer(targetUrl) {
|
|||
await page.goto(targetUrl, { timeout: 60000 });
|
||||
await page.waitForTimeout(1500);
|
||||
const botonPulsado = await page.evaluate(() => {
|
||||
const elementos = Array.from(document.querySelectorAll('input, button, a'));
|
||||
const target = elementos.find(el => {
|
||||
const txt = (el.value || el.innerText || "").toUpperCase();
|
||||
return txt.includes("SERVICIO") && txt.includes("DESGLOSE");
|
||||
});
|
||||
if (target) { target.click(); return true; }
|
||||
return false;
|
||||
const el = Array.from(document.querySelectorAll('input, button, a')).find(el => (el.value || el.innerText || "").toUpperCase().includes("DESGLOSE"));
|
||||
if (el) { el.click(); return true; } return false;
|
||||
});
|
||||
if (botonPulsado) await page.waitForTimeout(3000);
|
||||
const datosRaw = await page.evaluate(() => {
|
||||
const filas = Array.from(document.querySelectorAll('tr'));
|
||||
const datos = [];
|
||||
filas.forEach(tr => {
|
||||
const datos = await page.evaluate(() => {
|
||||
const rows = Array.from(document.querySelectorAll('tr'));
|
||||
return rows.map(tr => {
|
||||
const tds = tr.querySelectorAll('td');
|
||||
if (tds.length >= 6) {
|
||||
const servicio = tds[0].innerText.trim();
|
||||
const direccion = tds[1].innerText.trim();
|
||||
const saldoRaw = tds[5].innerText.trim();
|
||||
if (/^\d{5,}$/.test(servicio)) datos.push({ servicio, direccion, saldoRaw });
|
||||
if (tds.length >= 6 && /^\d{5,}$/.test(tds[0].innerText.trim())) {
|
||||
return { servicio: tds[0].innerText.trim(), direccion: tds[1].innerText.trim(), saldoRaw: tds[5].innerText.trim() };
|
||||
}
|
||||
});
|
||||
return datos;
|
||||
}).filter(Boolean);
|
||||
});
|
||||
const encontrados = []; const noEncontrados = [];
|
||||
const encontrados = [], noEncontrados = [];
|
||||
if (db) {
|
||||
for (const item of datosRaw) {
|
||||
let cleanSaldo = item.saldoRaw.replace(/[^\d.-]/g, '');
|
||||
let importe = Math.abs(parseFloat(cleanSaldo) || 0);
|
||||
for (const item of datos) {
|
||||
let importe = Math.abs(parseFloat(item.saldoRaw.replace(/[^\d.-]/g, '')) || 0);
|
||||
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", item.servicio).get();
|
||||
if (!q.empty) {
|
||||
q.forEach(doc => encontrados.push({ servicio: item.servicio, direccion: item.direccion, importe: importe, docId: doc.id }));
|
||||
} else {
|
||||
noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe: importe });
|
||||
}
|
||||
if (!q.empty) q.forEach(doc => encontrados.push({ servicio: item.servicio, direccion: item.direccion, importe, docId: doc.id }));
|
||||
else noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe });
|
||||
}
|
||||
}
|
||||
return { encontrados, noEncontrados };
|
||||
|
|
@ -340,7 +328,6 @@ async function loginHS() {
|
|||
return { browser, page };
|
||||
}
|
||||
|
||||
// 💾 GUARDADOR
|
||||
async function runSaver(items, providerType) {
|
||||
if (!db) return 0;
|
||||
const batch = db.batch();
|
||||
|
|
@ -348,13 +335,7 @@ async function runSaver(items, providerType) {
|
|||
let count = 0;
|
||||
items.forEach(item => {
|
||||
const ref = db.collection(APPOINTMENTS_COL).doc(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';
|
||||
else updateData.homeservePaymentStatus = 'paid_saldo';
|
||||
batch.update(ref, updateData);
|
||||
|
|
|
|||
Loading…
Reference in New Issue