Actualizar robot_cobros.js
This commit is contained in:
parent
899d66c93f
commit
194f732aa7
|
|
@ -39,7 +39,6 @@ app.post('/api/robot-cobros', async (req, res) => {
|
||||||
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||||
res.setHeader('Transfer-Encoding', 'chunked');
|
res.setHeader('Transfer-Encoding', 'chunked');
|
||||||
const send = (type, payload) => res.write(JSON.stringify({ type, payload }) + "\n");
|
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;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -65,7 +64,6 @@ app.post('/api/robot-cobros', async (req, res) => {
|
||||||
// ================================================================
|
// ================================================================
|
||||||
// Helpers MONEY + TOTAL REPARACION (Shadow DOM)
|
// Helpers MONEY + TOTAL REPARACION (Shadow DOM)
|
||||||
// ================================================================
|
// ================================================================
|
||||||
|
|
||||||
function parseEuro(raw) {
|
function parseEuro(raw) {
|
||||||
if (!raw) return 0;
|
if (!raw) return 0;
|
||||||
// "53,66 €" -> 53.66
|
// "53,66 €" -> 53.66
|
||||||
|
|
@ -75,58 +73,41 @@ function parseEuro(raw) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getTotalReparacion(page) {
|
async function getTotalReparacion(page) {
|
||||||
// Selector deep: atraviesa Shadow DOM
|
// EL SELECTOR MÁGICO: ">>>" atraviesa el Shadow DOM automáticamente
|
||||||
const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]';
|
const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]';
|
||||||
|
|
||||||
// 1) prueba en frames por si lo meten dentro
|
try {
|
||||||
|
// Locator de Playwright ya espera automáticamente a que el elemento aparezca
|
||||||
|
const loc = page.locator(deepSel).first();
|
||||||
|
// Le damos hasta 5 segundos para aparecer, si no, asumimos 0€
|
||||||
|
await loc.waitFor({ state: 'attached', timeout: 5000 });
|
||||||
|
const raw = await loc.innerText();
|
||||||
|
return parseEuro(raw);
|
||||||
|
} catch (e) {
|
||||||
|
// Si falla el locator principal, intentamos buscar en frames por seguridad
|
||||||
for (const frame of page.frames()) {
|
for (const frame of page.frames()) {
|
||||||
try {
|
try {
|
||||||
const loc = frame.locator(deepSel).first();
|
const locFrame = frame.locator(deepSel).first();
|
||||||
await loc.waitFor({ state: 'attached', timeout: 6000 });
|
await locFrame.waitFor({ state: 'attached', timeout: 2000 });
|
||||||
const raw = await loc.innerText();
|
const rawFrame = await locFrame.innerText();
|
||||||
const val = parseEuro(raw);
|
const val = parseEuro(rawFrame);
|
||||||
if (val > 0) return val;
|
if (val > 0) return val;
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
return 0; // Si falla todo, es 0
|
||||||
// 2) fallback: búsqueda manual por shadowRoots abiertos (por si cambian el componente)
|
|
||||||
const raw2 = await page.evaluate(() => {
|
|
||||||
const seen = new Set();
|
|
||||||
|
|
||||||
function findIn(root) {
|
|
||||||
if (!root || seen.has(root)) return null;
|
|
||||||
seen.add(root);
|
|
||||||
|
|
||||||
const td = root.querySelector?.('td[data-label^="TOTAL REPARACION"]');
|
|
||||||
if (td) return td.innerText;
|
|
||||||
|
|
||||||
const els = root.querySelectorAll ? Array.from(root.querySelectorAll('*')) : [];
|
|
||||||
for (const el of els) {
|
|
||||||
if (el.shadowRoot) {
|
|
||||||
const hit = findIn(el.shadowRoot);
|
|
||||||
if (hit) return hit;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return findIn(document);
|
|
||||||
});
|
|
||||||
|
|
||||||
return parseEuro(raw2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================================================================
|
// ==================================================================
|
||||||
// 🤖 LÓGICA MULTIASISTENCIA V17 (MODO BULLDOG)
|
// 🤖 LÓGICA MULTIASISTENCIA (OPTIMIZADA)
|
||||||
// ==================================================================
|
// ==================================================================
|
||||||
|
|
||||||
async function runMultiStream(mes, anio, send) {
|
async function runMultiStream(mes, anio, send) {
|
||||||
let browser = null;
|
let browser = null;
|
||||||
const valD1 = `${mes}_${anio}`;
|
const valD1 = `${mes}_${anio}`;
|
||||||
const valD2 = `${anio}`;
|
const valD2 = `${anio}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
send('LOG', `🚀 (MULTI V17) Iniciando Bulldog: ${valD1}`);
|
send('LOG', `🚀 (MULTI) Iniciando rápido: ${valD1}`);
|
||||||
const { browser: b, page } = await loginMulti();
|
const { browser: b, page } = await loginMulti();
|
||||||
browser = b;
|
browser = b;
|
||||||
|
|
||||||
|
|
@ -138,7 +119,7 @@ async function runMultiStream(mes, anio, send) {
|
||||||
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(2500);
|
await page.waitForTimeout(2000); // Pequeña espera técnica para que recargue la tabla
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- FASE 1: RECOLECTAR IDs ---
|
// --- FASE 1: RECOLECTAR IDs ---
|
||||||
|
|
@ -162,8 +143,13 @@ async function runMultiStream(mes, anio, send) {
|
||||||
send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`);
|
send('LOG', ` -> Encontrados ${nuevosIds.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) {
|
||||||
else { tieneSiguiente = false; }
|
await haySiguiente.click();
|
||||||
|
await page.waitForTimeout(2500);
|
||||||
|
pagActual++;
|
||||||
|
} else {
|
||||||
|
tieneSiguiente = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
idsServicios = [...new Set(idsServicios)];
|
idsServicios = [...new Set(idsServicios)];
|
||||||
|
|
@ -180,13 +166,11 @@ async function runMultiStream(mes, anio, send) {
|
||||||
try {
|
try {
|
||||||
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
await page.goto(urlPresupuesto, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||||
|
|
||||||
// espera suave al componente (si existe)
|
// 1. OBTENER DATOS CLIENTE (Esto suele estar disponible rápido)
|
||||||
await page.waitForSelector('multiasistencia-valoraciones', { timeout: 12000 }).catch(() => {});
|
|
||||||
|
|
||||||
let clienteWeb = "Desconocido";
|
let clienteWeb = "Desconocido";
|
||||||
let direccionWeb = "Sin dirección";
|
let direccionWeb = "Sin dirección";
|
||||||
|
|
||||||
// cliente/dirección los sigues sacando igual (si algún día también cae en shadow, lo ajustamos)
|
// Intentamos leer cliente de los frames (por si acaso)
|
||||||
const frames = page.frames();
|
const frames = page.frames();
|
||||||
for (const frame of frames) {
|
for (const frame of frames) {
|
||||||
try {
|
try {
|
||||||
|
|
@ -207,18 +191,10 @@ async function runMultiStream(mes, anio, send) {
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ IMPORTE: ahora sí, Shadow DOM friendly
|
// 2. OBTENER IMPORTE (Sin bucles, confiando en el selector inteligente)
|
||||||
let importe = 0;
|
const importe = await getTotalReparacion(page);
|
||||||
let intentos = 0;
|
|
||||||
while (intentos < 5 && importe === 0) {
|
|
||||||
intentos++;
|
|
||||||
if (intentos > 1) await page.waitForTimeout(1200);
|
|
||||||
importe = await getTotalReparacion(page);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} sigue en 0€ tras 5 intentos.`);
|
// 3. CRUCE BD
|
||||||
|
|
||||||
// --- CRUCE BD ---
|
|
||||||
let docId = null;
|
let docId = null;
|
||||||
let enBD = false;
|
let enBD = false;
|
||||||
let clienteFinal = clienteWeb;
|
let clienteFinal = clienteWeb;
|
||||||
|
|
@ -230,6 +206,7 @@ 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;
|
||||||
|
// Priorizamos datos de Firebase si existen
|
||||||
if (doc.data().clientName) clienteFinal = doc.data().clientName;
|
if (doc.data().clientName) clienteFinal = doc.data().clientName;
|
||||||
if (doc.data().address) direccionFinal = doc.data().address;
|
if (doc.data().address) direccionFinal = doc.data().address;
|
||||||
}
|
}
|
||||||
|
|
@ -286,9 +263,8 @@ async function loginMulti() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================================================================
|
// ==================================================================
|
||||||
// ... RESTO IGUAL ...
|
// ... RESTO IGUAL (HOMESERVE + SAVER) ...
|
||||||
// ==================================================================
|
// ==================================================================
|
||||||
|
|
||||||
async function runHSScanner() {
|
async function runHSScanner() {
|
||||||
let browser = null;
|
let browser = null;
|
||||||
try {
|
try {
|
||||||
|
|
@ -314,16 +290,13 @@ async function runHSAnalyzer(targetUrl) {
|
||||||
browser = b;
|
browser = b;
|
||||||
await page.goto(targetUrl, { timeout: 60000 });
|
await page.goto(targetUrl, { timeout: 60000 });
|
||||||
await page.waitForTimeout(1500);
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
const botonPulsado = await page.evaluate(() => {
|
const botonPulsado = await page.evaluate(() => {
|
||||||
const el = Array.from(document.querySelectorAll('input, button, a'))
|
const el = Array.from(document.querySelectorAll('input, button, a'))
|
||||||
.find(el => (el.value || el.innerText || "").toUpperCase().includes("DESGLOSE"));
|
.find(el => (el.value || el.innerText || "").toUpperCase().includes("DESGLOSE"));
|
||||||
if (el) { el.click(); return true; }
|
if (el) { el.click(); return true; }
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (botonPulsado) await page.waitForTimeout(3000);
|
if (botonPulsado) await page.waitForTimeout(3000);
|
||||||
|
|
||||||
const datos = await page.evaluate(() => {
|
const datos = await page.evaluate(() => {
|
||||||
const rows = Array.from(document.querySelectorAll('tr'));
|
const rows = Array.from(document.querySelectorAll('tr'));
|
||||||
return rows.map(tr => {
|
return rows.map(tr => {
|
||||||
|
|
@ -333,7 +306,6 @@ async function runHSAnalyzer(targetUrl) {
|
||||||
}
|
}
|
||||||
}).filter(Boolean);
|
}).filter(Boolean);
|
||||||
});
|
});
|
||||||
|
|
||||||
const encontrados = [], noEncontrados = [];
|
const encontrados = [], noEncontrados = [];
|
||||||
if (db) {
|
if (db) {
|
||||||
for (const item of datos) {
|
for (const item of datos) {
|
||||||
|
|
@ -353,10 +325,8 @@ async function loginHS() {
|
||||||
const doc = await db.collection("providerCredentials").doc("homeserve").get();
|
const doc = await db.collection("providerCredentials").doc("homeserve").get();
|
||||||
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
||||||
|
|
||||||
await page.goto(URLS.HS_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
await page.goto(URLS.HS_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||||
if (await page.isVisible('input[name="CODIGO"]')) {
|
if (await page.isVisible('input[name="CODIGO"]')) {
|
||||||
await page.fill('input[name="CODIGO"]', user);
|
await page.fill('input[name="CODIGO"]', user);
|
||||||
|
|
@ -366,7 +336,6 @@ async function loginHS() {
|
||||||
}
|
}
|
||||||
await page.goto(URLS.HS_LIQ, { waitUntil: 'domcontentloaded' });
|
await page.goto(URLS.HS_LIQ, { waitUntil: 'domcontentloaded' });
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
return { browser, page };
|
return { browser, page };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -375,7 +344,6 @@ async function runSaver(items, providerType) {
|
||||||
const batch = db.batch();
|
const batch = db.batch();
|
||||||
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);
|
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio);
|
||||||
if (item.enBD || item.docId) {
|
if (item.enBD || item.docId) {
|
||||||
|
|
@ -388,12 +356,10 @@ async function runSaver(items, providerType) {
|
||||||
};
|
};
|
||||||
if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified';
|
if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified';
|
||||||
else updateData.homeservePaymentStatus = 'paid_saldo';
|
else updateData.homeservePaymentStatus = 'paid_saldo';
|
||||||
|
|
||||||
batch.update(ref, updateData);
|
batch.update(ref, updateData);
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (count > 0) await batch.commit();
|
if (count > 0) await batch.commit();
|
||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue