Actualizar robot_cobros.js
This commit is contained in:
parent
194f732aa7
commit
981ed2892e
127
robot_cobros.js
127
robot_cobros.js
|
|
@ -39,6 +39,7 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||
res.setHeader('Transfer-Encoding', 'chunked');
|
||||
const send = (type, payload) => res.write(JSON.stringify({ type, payload }) + "\n");
|
||||
|
||||
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||
|
||||
try {
|
||||
|
|
@ -64,6 +65,7 @@ app.post('/api/robot-cobros', async (req, res) => {
|
|||
// ================================================================
|
||||
// Helpers MONEY + TOTAL REPARACION (Shadow DOM)
|
||||
// ================================================================
|
||||
|
||||
function parseEuro(raw) {
|
||||
if (!raw) return 0;
|
||||
// "53,66 €" -> 53.66
|
||||
|
|
@ -73,41 +75,58 @@ function parseEuro(raw) {
|
|||
}
|
||||
|
||||
async function getTotalReparacion(page) {
|
||||
// EL SELECTOR MÁGICO: ">>>" atraviesa el Shadow DOM automáticamente
|
||||
// Selector deep: atraviesa Shadow DOM
|
||||
const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]';
|
||||
|
||||
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()) {
|
||||
try {
|
||||
const locFrame = frame.locator(deepSel).first();
|
||||
await locFrame.waitFor({ state: 'attached', timeout: 2000 });
|
||||
const rawFrame = await locFrame.innerText();
|
||||
const val = parseEuro(rawFrame);
|
||||
if (val > 0) return val;
|
||||
} catch {}
|
||||
}
|
||||
return 0; // Si falla todo, es 0
|
||||
|
||||
// 1) prueba en frames por si lo meten dentro
|
||||
for (const frame of page.frames()) {
|
||||
try {
|
||||
const loc = frame.locator(deepSel).first();
|
||||
await loc.waitFor({ state: 'attached', timeout: 6000 });
|
||||
const raw = await loc.innerText();
|
||||
const val = parseEuro(raw);
|
||||
if (val > 0) return val;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 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 (OPTIMIZADA)
|
||||
// 🤖 LÓGICA MULTIASISTENCIA (sin reintentos del importe)
|
||||
// ==================================================================
|
||||
|
||||
async function runMultiStream(mes, anio, send) {
|
||||
let browser = null;
|
||||
const valD1 = `${mes}_${anio}`;
|
||||
const valD2 = `${anio}`;
|
||||
|
||||
try {
|
||||
send('LOG', `🚀 (MULTI) Iniciando rápido: ${valD1}`);
|
||||
send('LOG', `🚀 (MULTI) Iniciando scan: ${valD1}`);
|
||||
const { browser: b, page } = await loginMulti();
|
||||
browser = b;
|
||||
|
||||
|
|
@ -119,7 +138,7 @@ async function runMultiStream(mes, anio, send) {
|
|||
await page.selectOption('select[name="D1"]', valD1);
|
||||
await page.selectOption('select[name="D2"]', valD2);
|
||||
await page.click('input[name="continuar"]');
|
||||
await page.waitForTimeout(2000); // Pequeña espera técnica para que recargue la tabla
|
||||
await page.waitForTimeout(2500);
|
||||
}
|
||||
|
||||
// --- FASE 1: RECOLECTAR IDs ---
|
||||
|
|
@ -143,13 +162,8 @@ async function runMultiStream(mes, anio, send) {
|
|||
send('LOG', ` -> Encontrados ${nuevosIds.length} servicios.`);
|
||||
|
||||
const haySiguiente = await page.$('a:has-text("Página siguiente")');
|
||||
if (haySiguiente) {
|
||||
await haySiguiente.click();
|
||||
await page.waitForTimeout(2500);
|
||||
pagActual++;
|
||||
} else {
|
||||
tieneSiguiente = false;
|
||||
}
|
||||
if (haySiguiente) { await haySiguiente.click(); await page.waitForTimeout(3000); pagActual++; }
|
||||
else { tieneSiguiente = false; }
|
||||
}
|
||||
|
||||
idsServicios = [...new Set(idsServicios)];
|
||||
|
|
@ -160,19 +174,20 @@ async function runMultiStream(mes, anio, send) {
|
|||
// --- FASE 2: LEER DETALLES ---
|
||||
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: 60000, waitUntil: 'domcontentloaded' });
|
||||
|
||||
// 1. OBTENER DATOS CLIENTE (Esto suele estar disponible rápido)
|
||||
// Espera suave al componente (si existe)
|
||||
await page.waitForSelector('multiasistencia-valoraciones', { timeout: 12000 }).catch(() => {});
|
||||
|
||||
let clienteWeb = "Desconocido";
|
||||
let direccionWeb = "Sin dirección";
|
||||
|
||||
// Intentamos leer cliente de los frames (por si acaso)
|
||||
const frames = page.frames();
|
||||
for (const frame of frames) {
|
||||
// Cliente/dirección (igual que antes)
|
||||
for (const frame of page.frames()) {
|
||||
try {
|
||||
const data = await frame.evaluate(() => {
|
||||
let c = "";
|
||||
|
|
@ -191,10 +206,12 @@ async function runMultiStream(mes, anio, send) {
|
|||
} catch {}
|
||||
}
|
||||
|
||||
// 2. OBTENER IMPORTE (Sin bucles, confiando en el selector inteligente)
|
||||
// ✅ IMPORTE (una sola lectura, sin reintentos)
|
||||
const importe = await getTotalReparacion(page);
|
||||
|
||||
// 3. CRUCE BD
|
||||
if (importe === 0) send('LOG', `⚠️ Aviso: Servicio ${idServicio} en 0€ (no encontrado).`);
|
||||
|
||||
// --- CRUCE BD ---
|
||||
let docId = null;
|
||||
let enBD = false;
|
||||
let clienteFinal = clienteWeb;
|
||||
|
|
@ -206,7 +223,6 @@ async function runMultiStream(mes, anio, send) {
|
|||
const doc = q.docs[0];
|
||||
docId = doc.id;
|
||||
enBD = true;
|
||||
// Priorizamos datos de Firebase si existen
|
||||
if (doc.data().clientName) clienteFinal = doc.data().clientName;
|
||||
if (doc.data().address) direccionFinal = doc.data().address;
|
||||
}
|
||||
|
|
@ -263,8 +279,9 @@ async function loginMulti() {
|
|||
}
|
||||
|
||||
// ==================================================================
|
||||
// ... RESTO IGUAL (HOMESERVE + SAVER) ...
|
||||
// HOMESERVE (igual)
|
||||
// ==================================================================
|
||||
|
||||
async function runHSScanner() {
|
||||
let browser = null;
|
||||
try {
|
||||
|
|
@ -280,7 +297,11 @@ async function runHSScanner() {
|
|||
return results;
|
||||
});
|
||||
return liquidaciones;
|
||||
} catch (e) { throw e; } finally { if (browser) await browser.close(); }
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function runHSAnalyzer(targetUrl) {
|
||||
|
|
@ -288,15 +309,19 @@ async function runHSAnalyzer(targetUrl) {
|
|||
try {
|
||||
const { browser: b, page } = await loginHS();
|
||||
browser = b;
|
||||
await page.goto(targetUrl, { timeout: 60000 });
|
||||
|
||||
await page.goto(targetUrl, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
const botonPulsado = await page.evaluate(() => {
|
||||
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 datos = await page.evaluate(() => {
|
||||
const rows = Array.from(document.querySelectorAll('tr'));
|
||||
return rows.map(tr => {
|
||||
|
|
@ -306,17 +331,22 @@ async function runHSAnalyzer(targetUrl) {
|
|||
}
|
||||
}).filter(Boolean);
|
||||
});
|
||||
|
||||
const encontrados = [], noEncontrados = [];
|
||||
if (db) {
|
||||
for (const item of datos) {
|
||||
let importe = Math.abs(parseFloat(item.saldoRaw.replace(/[^\d.-]/g, '')) || 0);
|
||||
const 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, docId: doc.id }));
|
||||
else noEncontrados.push({ servicio: item.servicio, direccion: item.direccion, importe });
|
||||
}
|
||||
}
|
||||
return { encontrados, noEncontrados };
|
||||
} catch (e) { throw e; } finally { if (browser) await browser.close(); }
|
||||
} catch (e) {
|
||||
throw e;
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function loginHS() {
|
||||
|
|
@ -325,25 +355,32 @@ async function loginHS() {
|
|||
const doc = await db.collection("providerCredentials").doc("homeserve").get();
|
||||
if (doc.exists) { user = doc.data().user; pass = doc.data().pass; }
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
||||
const page = await browser.newPage();
|
||||
|
||||
await page.goto(URLS.HS_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
||||
|
||||
if (await page.isVisible('input[name="CODIGO"]')) {
|
||||
await page.fill('input[name="CODIGO"]', user);
|
||||
await page.fill('input[type="password"]', pass);
|
||||
await page.keyboard.press('Enter');
|
||||
await page.waitForTimeout(4000);
|
||||
}
|
||||
|
||||
await page.goto(URLS.HS_LIQ, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
return { browser, page };
|
||||
}
|
||||
|
||||
async function runSaver(items, providerType) {
|
||||
if (!db) return 0;
|
||||
|
||||
const batch = db.batch();
|
||||
const nowISO = new Date().toISOString();
|
||||
let count = 0;
|
||||
|
||||
items.forEach(item => {
|
||||
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId || item.servicio);
|
||||
if (item.enBD || item.docId) {
|
||||
|
|
@ -356,10 +393,12 @@ async function runSaver(items, providerType) {
|
|||
};
|
||||
if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified';
|
||||
else updateData.homeservePaymentStatus = 'paid_saldo';
|
||||
|
||||
batch.update(ref, updateData);
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
if (count > 0) await batch.commit();
|
||||
return count;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue