346 lines
11 KiB
JavaScript
346 lines
11 KiB
JavaScript
// ARCHIVO: robot_cobros.js
|
|
const express = require('express');
|
|
const { chromium } = require('playwright');
|
|
const admin = require('firebase-admin');
|
|
const cors = require('cors');
|
|
|
|
// --- FIREBASE INIT ---
|
|
try {
|
|
if (process.env.FIREBASE_PRIVATE_KEY) {
|
|
if (!admin.apps.length) {
|
|
admin.initializeApp({
|
|
credential: admin.credential.cert({
|
|
projectId: process.env.FIREBASE_PROJECT_ID,
|
|
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
|
|
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
|
|
}),
|
|
});
|
|
}
|
|
console.log("✅ Firebase inicializado.");
|
|
}
|
|
} catch (e) {
|
|
console.error("❌ Error Firebase:", e.message);
|
|
}
|
|
|
|
const db = admin.apps.length ? admin.firestore() : null;
|
|
const APPOINTMENTS_COL = "appointments";
|
|
|
|
const URLS = {
|
|
MULTI_LOGIN: "https://web.multiasistencia.com/w3multi/acceso.php",
|
|
MULTI_LIST: "https://web.multiasistencia.com/w3multi/cerrados.php",
|
|
};
|
|
|
|
const app = express();
|
|
app.use(cors({ origin: '*' }));
|
|
app.use(express.json({ limit: '50mb' }));
|
|
|
|
/** * Endpoint streaming NDJSON
|
|
*/
|
|
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, provider, dataToSave, month, year } = req.body;
|
|
|
|
try {
|
|
if (provider !== 'MULTI') throw new Error("Provider inválido. Usa provider='MULTI'.");
|
|
|
|
if (action === 'scan') {
|
|
await runMultiStream(month, year, send);
|
|
} else if (action === 'save_data') {
|
|
const count = await runSaver(dataToSave, send);
|
|
send('DONE', { count });
|
|
} else {
|
|
throw new Error("Acción inválida. Usa action='scan' o action='save_data'.");
|
|
}
|
|
} catch (err) {
|
|
send('ERROR', err.message);
|
|
} finally {
|
|
res.end();
|
|
}
|
|
});
|
|
|
|
// ================================================================
|
|
// Helpers
|
|
// ================================================================
|
|
function parseEuro(raw) {
|
|
if (!raw) return 0;
|
|
const clean = String(raw).replace(/[^\d,]/g, '').replace(',', '.');
|
|
const val = parseFloat(clean);
|
|
return Number.isFinite(val) ? val : 0;
|
|
}
|
|
|
|
async function getTotalReparacion(page) {
|
|
const deepSel = 'css=multiasistencia-valoraciones >>> td[data-label^="TOTAL REPARACION"]';
|
|
|
|
// 1) Frames
|
|
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) ShadowRoots traverse
|
|
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);
|
|
}
|
|
|
|
// ==================================================================
|
|
// MULTI SCAN (INTELIGENTE)
|
|
// ==================================================================
|
|
async function runMultiStream(mes, anio, send) {
|
|
let browser = null;
|
|
|
|
const yyyy = String(anio || '');
|
|
const mesNum = parseInt(mes, 10);
|
|
|
|
if (isNaN(mesNum) || !/^\d{4}$/.test(yyyy)) {
|
|
throw new Error("Mes o Año inválidos. Ejemplo: month='01', year='2026'.");
|
|
}
|
|
|
|
const nombresMeses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"];
|
|
const nombreMes = nombresMeses[mesNum - 1];
|
|
|
|
try {
|
|
send('LOG', `🚀 (MULTI) Scan inteligente: ${nombreMes.toUpperCase()} ${yyyy}`);
|
|
const { browser: b, page } = await loginMulti(send);
|
|
browser = b;
|
|
|
|
send('LOG', "📂 Yendo a Cerrados...");
|
|
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
|
|
|
// --- SELECCIÓN INTELIGENTE ---
|
|
const selectorD1 = 'select[name="D1"]';
|
|
|
|
if (await page.isVisible(selectorD1)) {
|
|
const valorASeleccionar = await page.evaluate(({ sel, m, y, name }) => {
|
|
const select = document.querySelector(sel);
|
|
if (!select) return null;
|
|
for (const op of select.options) {
|
|
const txt = op.text.toLowerCase();
|
|
const val = op.value;
|
|
// Debe coincidir el año y (el mes en texto o el mes en numero)
|
|
if ((txt.includes(y) || val.includes(y)) &&
|
|
(txt.includes(name) || val.startsWith(m + '_') || val.startsWith('0' + m + '_'))) {
|
|
return op.value;
|
|
}
|
|
}
|
|
return null;
|
|
}, { sel: selectorD1, m: mesNum, y: yyyy, name: nombreMes });
|
|
|
|
if (valorASeleccionar) {
|
|
send('LOG', `✅ Opción encontrada: "${valorASeleccionar}"`);
|
|
await page.selectOption(selectorD1, valorASeleccionar);
|
|
} else {
|
|
throw new Error(`❌ No encontré opción para ${nombreMes} ${yyyy}`);
|
|
}
|
|
|
|
// Año D2
|
|
if (await page.isVisible('select[name="D2"]')) {
|
|
await page.selectOption('select[name="D2"]', yyyy).catch(() => {});
|
|
}
|
|
|
|
await page.click('input[name="continuar"]');
|
|
await page.waitForTimeout(2500);
|
|
|
|
} else {
|
|
send('LOG', "⚠️ No veo el filtro D1.");
|
|
}
|
|
|
|
// --- FASE 1: IDs ---
|
|
let idsServicios = [];
|
|
let tieneSiguiente = true;
|
|
let pagActual = 1;
|
|
|
|
while (tieneSiguiente && pagActual <= 10) {
|
|
send('LOG', `📄 Leyendo pág ${pagActual}...`);
|
|
const nuevosIds = await page.evaluate(() => {
|
|
const celdas = Array.from(document.querySelectorAll('td.tdet'));
|
|
const lista = [];
|
|
celdas.forEach(td => {
|
|
const txt = (td.innerText || '').trim();
|
|
if (/^\d{8}$/.test(txt)) lista.push(txt);
|
|
});
|
|
return lista;
|
|
});
|
|
idsServicios.push(...[...new Set(nuevosIds)]);
|
|
send('LOG', ` -> +${nuevosIds.length} servicios.`);
|
|
|
|
const haySiguiente = await page.$('a:has-text("Página siguiente")');
|
|
if (haySiguiente) {
|
|
await haySiguiente.click();
|
|
await page.waitForTimeout(3000);
|
|
pagActual++;
|
|
} else {
|
|
tieneSiguiente = false;
|
|
}
|
|
}
|
|
|
|
idsServicios = [...new Set(idsServicios)];
|
|
send('LOG', `🔍 Total único: ${idsServicios.length}`);
|
|
|
|
if (idsServicios.length === 0) {
|
|
send('FINISH_SCAN', {});
|
|
return;
|
|
}
|
|
|
|
// --- FASE 2: 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' });
|
|
await page.waitForSelector('multiasistencia-valoraciones', { timeout: 12000 }).catch(() => {});
|
|
|
|
let clienteWeb = "Desconocido";
|
|
let direccionWeb = "Sin dirección";
|
|
|
|
for (const frame of page.frames()) {
|
|
try {
|
|
const data = await frame.evaluate(() => {
|
|
let c = "", d = "";
|
|
const bloques = Array.from(document.querySelectorAll('.policy-info-block'));
|
|
bloques.forEach(b => {
|
|
const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
|
|
const v = b.querySelector('.policy-info-value')?.innerText || "";
|
|
if (t.includes("CLIENTE")) c = v;
|
|
if (t.includes("DIRECCIÓN")) d = v;
|
|
});
|
|
return { c, d };
|
|
});
|
|
if (data.c) clienteWeb = data.c.trim();
|
|
if (data.d) direccionWeb = data.d.trim();
|
|
} catch {}
|
|
}
|
|
|
|
const importe = await getTotalReparacion(page);
|
|
if (importe === 0) send('LOG', `⚠️ ${idServicio} tiene importe 0.`);
|
|
|
|
// Cruce DB
|
|
let docId = null;
|
|
let enBD = false;
|
|
let clienteFinal = clienteWeb;
|
|
let direccionFinal = direccionWeb;
|
|
|
|
if (db) {
|
|
const q = await db.collection(APPOINTMENTS_COL).where("serviceNumber", "==", idServicio).get();
|
|
if (!q.empty) {
|
|
const doc = q.docs[0];
|
|
docId = doc.id;
|
|
enBD = true;
|
|
if (doc.data().clientName) clienteFinal = doc.data().clientName;
|
|
if (doc.data().address) direccionFinal = doc.data().address;
|
|
}
|
|
}
|
|
|
|
send('ITEM_FOUND', {
|
|
servicio: idServicio,
|
|
direccion: direccionFinal,
|
|
cliente: clienteFinal,
|
|
importe,
|
|
enBD,
|
|
docId
|
|
});
|
|
} catch (errDetail) {
|
|
send('LOG', `⚠️ Error ${idServicio}: ${errDetail.message}`);
|
|
}
|
|
}
|
|
send('FINISH_SCAN', {});
|
|
|
|
} finally {
|
|
if (browser) await browser.close().catch(()=>{});
|
|
}
|
|
}
|
|
|
|
async function loginMulti(send) {
|
|
let user = "", pass = "";
|
|
if (db) {
|
|
// Busca en la colección 'providerCredentials', documento 'multiasistencia'
|
|
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. CREA EL DOC EN FIRESTORE: providerCredentials/multiasistencia");
|
|
|
|
send('LOG', '🔐 Login en Multiasistencia…');
|
|
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });
|
|
const page = await browser.newPage();
|
|
|
|
await page.goto(URLS.MULTI_LOGIN, { timeout: 60000, waitUntil: 'domcontentloaded' });
|
|
|
|
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; }
|
|
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.waitForTimeout(4000);
|
|
|
|
return { browser, page };
|
|
}
|
|
|
|
// ==================================================================
|
|
// SAVE
|
|
// ==================================================================
|
|
async function runSaver(items, send) {
|
|
if (!db) return 0;
|
|
const batch = db.batch();
|
|
const nowISO = new Date().toISOString();
|
|
let count = 0;
|
|
|
|
(items || []).forEach(item => {
|
|
if (!item || !item.docId) return;
|
|
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId);
|
|
batch.update(ref, {
|
|
paidAmount: Number(item.importe || 0),
|
|
paymentState: "Pagado",
|
|
paymentMethod: "transferencia",
|
|
paymentType: "transferencia",
|
|
status: "completed",
|
|
paymentDate: nowISO,
|
|
lastUpdatedByRobot: nowISO,
|
|
multiasistenciaPaymentStatus: "paid_transfer"
|
|
});
|
|
count++;
|
|
});
|
|
|
|
if (count > 0) {
|
|
await batch.commit();
|
|
send && send('LOG', `💾 Guardados ${count} servicios.`);
|
|
} else {
|
|
send && send('LOG', '💾 Nada que guardar.');
|
|
}
|
|
return count;
|
|
}
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
app.listen(PORT, () => console.log(`🚀 MULTI robot server on port ${PORT}`)); |