Actualizar robot_cobros.js
This commit is contained in:
parent
05a7ce73fe
commit
7e9e0186e2
259
robot_cobros.js
259
robot_cobros.js
|
|
@ -3,8 +3,7 @@ const { chromium } = require('playwright');
|
||||||
const admin = require('firebase-admin');
|
const admin = require('firebase-admin');
|
||||||
const cors = require('cors');
|
const cors = require('cors');
|
||||||
|
|
||||||
// --- CONFIGURACIÓN FIREBASE ---
|
// --- 1. CONFIGURACIÓN FIREBASE ---
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (process.env.FIREBASE_PRIVATE_KEY) {
|
if (process.env.FIREBASE_PRIVATE_KEY) {
|
||||||
if (!admin.apps.length) {
|
if (!admin.apps.length) {
|
||||||
|
|
@ -17,40 +16,44 @@ try {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
console.log("✅ Firebase inicializado.");
|
console.log("✅ Firebase inicializado.");
|
||||||
|
} else {
|
||||||
|
console.error("❌ FALTA CONFIGURACIÓN DE FIREBASE (Variables de entorno)");
|
||||||
}
|
}
|
||||||
} catch (e) { console.error("❌ Error Firebase:", e.message); }
|
} catch (e) { console.error("❌ Error Firebase:", e.message); }
|
||||||
|
|
||||||
const db = admin.apps.length ? admin.firestore() : null;
|
const db = admin.apps.length ? admin.firestore() : null;
|
||||||
const APPOINTMENTS_COL = "appointments";
|
const APPOINTMENTS_COL = "appointments";
|
||||||
|
|
||||||
// URL LOGIN MULTIASISTENCIA (Verifica que sea esta)
|
const URLS = {
|
||||||
const MULTI_LOGIN_URL = "https://web.multiasistencia.com/w3multi/acceso.php";
|
MULTI_LOGIN: "https://web.multiasistencia.com/w3multi/acceso.php",
|
||||||
|
MULTI_LIST: "https://web.multiasistencia.com/w3multi/cerrados.php",
|
||||||
|
HS_LOGIN: "https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS",
|
||||||
|
HS_LIQ: "https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=CONSULTALIQ_WEB"
|
||||||
|
};
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(cors({ origin: '*' }));
|
app.use(cors({ origin: '*' }));
|
||||||
app.use(express.json({ limit: '10mb' }));
|
app.use(express.json({ limit: '50mb' }));
|
||||||
|
|
||||||
// --- ENDPOINT PRINCIPAL ---
|
// --- 2. ENDPOINT PRINCIPAL ---
|
||||||
app.post('/api/robot-cobros', async (req, res) => {
|
app.post('/api/robot-cobros', async (req, res) => {
|
||||||
const { action, url, provider, dataToSave, month, year } = req.body;
|
const { action, url, provider, dataToSave, month, year } = req.body;
|
||||||
console.log(`🔔 Orden: ${action.toUpperCase()} [${provider || 'HS'}]`);
|
console.log(`🔔 Petición: ${action} [${provider}]`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// === ROBOT MULTIASISTENCIA ===
|
|
||||||
if (provider === 'MULTI') {
|
if (provider === 'MULTI') {
|
||||||
if (action === 'scan') {
|
if (action === 'scan') {
|
||||||
// Escanear lista y luego entrar en detalles
|
|
||||||
const lista = await runMultiFullScan(month, year);
|
const lista = await runMultiFullScan(month, year);
|
||||||
res.json({ success: true, data: lista });
|
res.json({ success: true, data: lista });
|
||||||
}
|
}
|
||||||
else if (action === 'save_data') {
|
else if (action === 'save_data') {
|
||||||
// Guardar
|
|
||||||
const count = await runSaver(dataToSave, 'MULTI');
|
const count = await runSaver(dataToSave, 'MULTI');
|
||||||
res.json({ success: true, count });
|
res.json({ success: true, count });
|
||||||
}
|
}
|
||||||
|
else { throw new Error("Acción MULTI inválida"); }
|
||||||
}
|
}
|
||||||
// === ROBOT HOMESERVE ===
|
|
||||||
else {
|
else {
|
||||||
|
// HOMESERVE
|
||||||
if (action === 'scan') {
|
if (action === 'scan') {
|
||||||
const lista = await runHSScanner();
|
const lista = await runHSScanner();
|
||||||
res.json({ success: true, data: lista });
|
res.json({ success: true, data: lista });
|
||||||
|
|
@ -64,183 +67,148 @@ app.post('/api/robot-cobros', async (req, res) => {
|
||||||
const count = await runSaver(dataToSave, 'HS');
|
const count = await runSaver(dataToSave, 'HS');
|
||||||
res.json({ success: true, count });
|
res.json({ success: true, count });
|
||||||
}
|
}
|
||||||
|
else { throw new Error("Acción HS inválida"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("❌ Error:", err.message);
|
console.error("❌ CRASH:", err.message);
|
||||||
res.status(500).json({ success: false, message: err.message });
|
res.status(500).json({ success: false, message: err.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ==========================================
|
// ==================================================================
|
||||||
// 🤖 LÓGICA MULTIASISTENCIA
|
// 🤖 3. LÓGICA MULTIASISTENCIA (LOGIN CORREGIDO)
|
||||||
// ==========================================
|
// ==================================================================
|
||||||
|
|
||||||
async function runMultiFullScan(mes, anio) {
|
async function runMultiFullScan(mes, anio) {
|
||||||
let browser = null;
|
let browser = null;
|
||||||
const resultados = [];
|
const resultados = [];
|
||||||
const noEncontrados = [];
|
const noEncontrados = [];
|
||||||
|
|
||||||
// Formato fecha web: "1_2025", "12_2025"
|
|
||||||
const valD1 = `${mes}_${anio}`;
|
const valD1 = `${mes}_${anio}`;
|
||||||
const valD2 = `${anio}`;
|
const valD2 = `${anio}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(`🚀 Iniciando MULTI para ${valD1}...`);
|
console.log(`🚀 (MULTI) Iniciando: ${valD1}`);
|
||||||
|
|
||||||
// 1. Login
|
// 1. LOGIN (Usando tu lógica probada)
|
||||||
const { browser: b, page } = await loginMulti();
|
const { browser: b, page } = await loginMulti();
|
||||||
browser = b;
|
browser = b;
|
||||||
|
|
||||||
// 2. Ir a Cerrados
|
// 2. IR A CERRADOS
|
||||||
console.log("📂 Yendo a Cerrados...");
|
console.log("📂 (MULTI) Yendo a Cerrados...");
|
||||||
await page.goto('https://web.multiasistencia.com/w3multi/cerrados.php');
|
await page.goto(URLS.MULTI_LIST, { waitUntil: 'domcontentloaded' });
|
||||||
|
|
||||||
// 3. Filtrar por Fecha
|
// 3. FILTRAR
|
||||||
console.log(`📅 Filtrando fecha: ${valD1}`);
|
console.log(`📅 (MULTI) Filtrando...`);
|
||||||
// Rellenar formulario de filtro si existe
|
|
||||||
if (await page.isVisible('select[name="D1"]')) {
|
if (await page.isVisible('select[name="D1"]')) {
|
||||||
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"]'); // Botón Continuar
|
await page.click('input[name="continuar"]');
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Recorrer Páginas y Extraer IDs
|
// 4. RECORRER PÁGINAS
|
||||||
let idsServicios = [];
|
let idsServicios = [];
|
||||||
let tieneSiguiente = true;
|
let tieneSiguiente = true;
|
||||||
let pagActual = 1;
|
let pagActual = 1;
|
||||||
|
|
||||||
while (tieneSiguiente && pagActual <= 5) { // Límite seguridad 5 págs
|
while (tieneSiguiente && pagActual <= 5) {
|
||||||
console.log(`📄 Leyendo página ${pagActual}...`);
|
console.log(`📄 (MULTI) Página ${pagActual}...`);
|
||||||
|
|
||||||
// Extraer filas de la tabla (Clase 'tdet')
|
|
||||||
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 = [];
|
||||||
// La estructura parece ser filas de celdas. Buscamos celdas que tengan 8 dígitos numéricos
|
|
||||||
celdas.forEach(td => {
|
celdas.forEach(td => {
|
||||||
const txt = td.innerText.trim();
|
const txt = td.innerText.trim();
|
||||||
if (/^\d{8}$/.test(txt)) {
|
if (/^\d{8}$/.test(txt)) lista.push(txt);
|
||||||
lista.push(txt);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
return lista;
|
return lista;
|
||||||
});
|
});
|
||||||
|
idsServicios.push(...nuevosIds);
|
||||||
|
|
||||||
// Eliminar duplicados en la misma página
|
// Botón Siguiente
|
||||||
const unicosPag = [...new Set(nuevosIds)];
|
const haySiguiente = await page.evaluate(() => {
|
||||||
idsServicios = [...idsServicios, ...unicosPag];
|
const img = document.querySelector('img[src*="seguir.gif"]');
|
||||||
console.log(` -> Encontrados ${unicosPag.length} servicios.`);
|
if (img && img.parentElement.tagName === 'A') {
|
||||||
|
img.parentElement.click(); return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
// Buscar botón siguiente
|
if (haySiguiente) { await page.waitForTimeout(3000); pagActual++; }
|
||||||
// En el HTML: onclick="javascript:document.visor.paginasiguiente.value=1+1"
|
else { tieneSiguiente = false; }
|
||||||
// Intentaremos detectar si hay imagen de "seguir.gif" o texto "Página siguiente"
|
|
||||||
const btnSiguiente = await page.$('img[src*="seguir.gif"]');
|
|
||||||
if (btnSiguiente) {
|
|
||||||
const padreLink = await btnSiguiente.evaluateHandle(el => el.parentElement); // El <a> o el padre
|
|
||||||
if (padreLink) {
|
|
||||||
await padreLink.click(); // Clicamos en la flecha/enlace
|
|
||||||
await page.waitForTimeout(2500);
|
|
||||||
pagActual++;
|
|
||||||
} else { tieneSiguiente = false; }
|
|
||||||
} else {
|
|
||||||
tieneSiguiente = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Eliminar duplicados totales
|
|
||||||
idsServicios = [...new Set(idsServicios)];
|
idsServicios = [...new Set(idsServicios)];
|
||||||
console.log(`🔍 Total Servicios a revisar: ${idsServicios.length}`);
|
console.log(`🔍 (MULTI) Servicios a analizar: ${idsServicios.length}`);
|
||||||
|
|
||||||
// 5. Entrar en CADA servicio para ver el dinero (Presupuesto)
|
if (idsServicios.length === 0) return { encontrados: [], noEncontrados: [] };
|
||||||
|
|
||||||
|
// 5. DETALLES (PRESUPUESTO)
|
||||||
for (const idServicio of idsServicios) {
|
for (const idServicio of idsServicios) {
|
||||||
console.log(`💰 Analizando servicio: ${idServicio}`);
|
// Ir directo al presupuesto
|
||||||
|
|
||||||
// URL Directa al presupuesto
|
|
||||||
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' });
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
// Esperar un poco a que carguen los componentes Angular/JS
|
|
||||||
await page.waitForTimeout(1000);
|
|
||||||
|
|
||||||
// Extraer Datos del Presupuesto
|
|
||||||
const info = await page.evaluate(() => {
|
const info = await page.evaluate(() => {
|
||||||
// Buscar "Nombre Cliente" y "Dirección" en los bloques de cabecera
|
const clean = (t) => t ? t.trim() : "Desconocido";
|
||||||
const buscarTexto = (label) => {
|
let cliente = "", direccion = "", totalStr = "0";
|
||||||
// Buscamos en los divs de info
|
|
||||||
const divs = Array.from(document.querySelectorAll('.policy-info-block'));
|
// Datos Cliente (Bloques modernos o Tablas antiguas)
|
||||||
for (let div of divs) {
|
const bloques = Array.from(document.querySelectorAll('.policy-info-block'));
|
||||||
if (div.innerText.includes(label)) {
|
bloques.forEach(b => {
|
||||||
const valDiv = div.querySelector('.policy-info-value');
|
const t = b.querySelector('.policy-info-title')?.innerText.toUpperCase() || "";
|
||||||
return valDiv ? valDiv.innerText.trim() : '';
|
const v = b.querySelector('.policy-info-value')?.innerText || "";
|
||||||
}
|
if (t.includes("CLIENTE")) cliente = v;
|
||||||
}
|
if (t.includes("DIRECCIÓN")) direccion = v;
|
||||||
// Fallback a tablas antiguas
|
});
|
||||||
|
|
||||||
|
if (!cliente) {
|
||||||
const tds = Array.from(document.querySelectorAll('td'));
|
const tds = Array.from(document.querySelectorAll('td'));
|
||||||
const targetTd = tds.find(td => td.innerText.includes(label));
|
for(let i=0; i<tds.length; i++) {
|
||||||
if(targetTd && targetTd.nextElementSibling) return targetTd.nextElementSibling.innerText.trim();
|
const txt = tds[i].innerText.toUpperCase();
|
||||||
return '';
|
if(txt.includes("NOMBRE CLIENTE") && tds[i+1]) cliente = tds[i+1].innerText;
|
||||||
};
|
if(txt.includes("DIRECCIÓN") && tds[i+1]) direccion = tds[i+1].innerText;
|
||||||
|
|
||||||
const cliente = buscarTexto('Nombre Cliente') || "Desconocido";
|
|
||||||
const direccion = buscarTexto('Dirección') || "Desconocido";
|
|
||||||
|
|
||||||
// Buscar el TOTAL DINERO
|
|
||||||
// Estrategia 1: Buscar celda con atributo data-label="TOTAL REPARACION:"
|
|
||||||
let totalStr = "";
|
|
||||||
const celdaTotal = document.querySelector('td[data-label*="TOTAL REPARACION"]');
|
|
||||||
if (celdaTotal) {
|
|
||||||
totalStr = celdaTotal.innerText;
|
|
||||||
} else {
|
|
||||||
// Estrategia 2: Buscar texto "TOTAL REPARACION" y coger el siguiente
|
|
||||||
const allTd = Array.from(document.querySelectorAll('td, th'));
|
|
||||||
const header = allTd.find(el => el.innerText.includes("TOTAL REPARACION"));
|
|
||||||
if (header && header.nextElementSibling) totalStr = header.nextElementSibling.innerText;
|
|
||||||
else if (header) {
|
|
||||||
// A veces está en la misma celda o fila rara
|
|
||||||
totalStr = header.innerText.replace("TOTAL REPARACION", "");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { cliente, direccion, totalStr };
|
// Total Dinero
|
||||||
|
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(":", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { cliente: clean(cliente), direccion: clean(direccion), totalStr };
|
||||||
});
|
});
|
||||||
|
|
||||||
// Limpiar importe
|
|
||||||
let importe = 0;
|
let importe = 0;
|
||||||
if (info.totalStr) {
|
if (info.totalStr) {
|
||||||
// "53,66 €" -> 53.66
|
let cleanMoney = info.totalStr.replace(/[^\d.,-]/g, '').replace(',', '.');
|
||||||
let clean = info.totalStr.replace(/[^\d.,]/g, '').replace(',', '.');
|
importe = Math.abs(parseFloat(cleanMoney) || 0);
|
||||||
importe = parseFloat(clean) || 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cruzar con Firebase
|
|
||||||
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 => {
|
q.forEach(doc => {
|
||||||
resultados.push({
|
resultados.push({ servicio: idServicio, direccion: info.direccion, importe, docId: doc.id });
|
||||||
servicio: idServicio,
|
|
||||||
direccion: info.direccion,
|
|
||||||
cliente: info.cliente,
|
|
||||||
importe: importe,
|
|
||||||
docId: doc.id
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
noEncontrados.push({
|
noEncontrados.push({ servicio: idServicio, direccion: info.direccion, importe });
|
||||||
servicio: idServicio,
|
|
||||||
direccion: info.direccion,
|
|
||||||
importe: importe
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (errDetail) {
|
} catch (errDetail) { console.error(` ⚠️ Error ${idServicio}: ${errDetail.message}`); }
|
||||||
console.error(` ⚠️ Error leyendo ${idServicio}: ${errDetail.message}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { encontrados: resultados, noEncontrados };
|
return { encontrados: resultados, noEncontrados };
|
||||||
|
|
@ -257,15 +225,20 @@ async function loginMulti() {
|
||||||
if(!user) throw new Error("Faltan credenciales Multiasistencia en Firebase");
|
if(!user) throw new Error("Faltan credenciales Multiasistencia en Firebase");
|
||||||
|
|
||||||
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 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();
|
||||||
|
|
||||||
console.log("🌍 Login Multi...");
|
console.log("🌍 (MULTI) Entrando al login...");
|
||||||
await page.goto(MULTI_LOGIN_URL, { timeout: 60000 });
|
await page.goto(URLS.MULTI_LOGIN, { waitUntil: 'networkidle', timeout: 60000 });
|
||||||
|
|
||||||
// Rellenar form (según tu código anterior)
|
// TU LÓGICA DE LOGIN QUE FUNCIONA
|
||||||
const userFilled = await page.evaluate((u) => {
|
const userFilled = await page.evaluate((u) => {
|
||||||
const el = document.querySelector('input[name="usuario"]') || document.querySelector('input[type="text"]');
|
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;
|
return false;
|
||||||
}, user);
|
}, user);
|
||||||
|
|
||||||
|
|
@ -273,20 +246,15 @@ async function loginMulti() {
|
||||||
await page.fill('input[type="password"]', pass);
|
await page.fill('input[type="password"]', pass);
|
||||||
await page.click('input[type="submit"]');
|
await page.click('input[type="submit"]');
|
||||||
await page.waitForTimeout(4000);
|
await page.waitForTimeout(4000);
|
||||||
|
|
||||||
|
console.log("✅ (MULTI) Login OK");
|
||||||
return { browser, page };
|
return { browser, page };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================================================================
|
||||||
// ==========================================
|
// 🤖 4. LÓGICA HOMESERVE (Mantenida igual)
|
||||||
// 🤖 ZONA HOMESERVE (Mantenemos intacta)
|
// ==================================================================
|
||||||
// ==========================================
|
|
||||||
async function runHSScanner() {
|
async function runHSScanner() {
|
||||||
// ... (El código de HomeServe que ya tenías, resumido aquí para ahorrar espacio) ...
|
|
||||||
// COPIA AQUÍ LA FUNCIÓN runScanner DE LA VERSIÓN ANTERIOR
|
|
||||||
// O DÍMELO SI QUIERES QUE TE PEGUE EL ARCHIVO ENTERO DE 400 LÍNEAS
|
|
||||||
// Para simplificar, asumo que mantienes las funciones HS que funcionaban.
|
|
||||||
// Voy a poner una versión mínima que llama a loginHS
|
|
||||||
let browser = null;
|
let browser = null;
|
||||||
try {
|
try {
|
||||||
const { browser: b, page } = await loginHS();
|
const { browser: b, page } = await loginHS();
|
||||||
|
|
@ -305,14 +273,12 @@ async function runHSScanner() {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runHSAnalyzer(targetUrl) {
|
async function runHSAnalyzer(targetUrl) {
|
||||||
// ... (Tu función runAnalyzer de HomeServe v6/v7) ...
|
|
||||||
let browser = null;
|
let browser = null;
|
||||||
try {
|
try {
|
||||||
const { browser: b, page } = await loginHS();
|
const { browser: b, page } = await loginHS();
|
||||||
browser = b;
|
browser = b;
|
||||||
await page.goto(targetUrl, { timeout: 60000 });
|
await page.goto(targetUrl, { timeout: 60000 });
|
||||||
await page.waitForTimeout(1500);
|
await page.waitForTimeout(1500);
|
||||||
// ... Logica buscar boton y leer tabla ...
|
|
||||||
const botonPulsado = await page.evaluate(() => {
|
const botonPulsado = await page.evaluate(() => {
|
||||||
const elementos = Array.from(document.querySelectorAll('input, button, a'));
|
const elementos = Array.from(document.querySelectorAll('input, button, a'));
|
||||||
const target = elementos.find(el => {
|
const target = elementos.find(el => {
|
||||||
|
|
@ -362,31 +328,26 @@ async function loginHS() {
|
||||||
}
|
}
|
||||||
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('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', { timeout: 60000 });
|
await page.goto(URLS.HS_LOGIN, { timeout: 60000 });
|
||||||
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);
|
||||||
await page.fill('input[type="password"]', pass);
|
await page.fill('input[type="password"]', pass);
|
||||||
await page.keyboard.press('Enter');
|
await page.keyboard.press('Enter');
|
||||||
await page.waitForTimeout(4000);
|
await page.waitForTimeout(4000);
|
||||||
}
|
}
|
||||||
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=CONSULTALIQ_WEB');
|
await page.goto(URLS.HS_LIQ);
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
return { browser, page };
|
return { browser, page };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// 💾 GUARDADOR
|
||||||
// 💾 GUARDADOR GENÉRICO
|
|
||||||
// ==========================================
|
|
||||||
async function runSaver(items, providerType) {
|
async function runSaver(items, providerType) {
|
||||||
if (!db) return 0;
|
if (!db) return 0;
|
||||||
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);
|
const ref = db.collection(APPOINTMENTS_COL).doc(item.docId);
|
||||||
|
|
||||||
// Datos comunes
|
|
||||||
const updateData = {
|
const updateData = {
|
||||||
paidAmount: item.importe,
|
paidAmount: item.importe,
|
||||||
paymentState: "Pagado",
|
paymentState: "Pagado",
|
||||||
|
|
@ -394,20 +355,12 @@ async function runSaver(items, providerType) {
|
||||||
paymentDate: nowISO,
|
paymentDate: nowISO,
|
||||||
lastUpdatedByRobot: nowISO
|
lastUpdatedByRobot: nowISO
|
||||||
};
|
};
|
||||||
|
if (providerType === 'MULTI') updateData.multiasistenciaPaymentStatus = 'paid_verified';
|
||||||
// Campos específicos para saber de dónde vino el pago
|
else updateData.homeservePaymentStatus = 'paid_saldo';
|
||||||
if (providerType === 'MULTI') {
|
|
||||||
updateData.multiasistenciaPaymentStatus = 'paid_verified';
|
|
||||||
} else {
|
|
||||||
updateData.homeservePaymentStatus = 'paid_saldo';
|
|
||||||
}
|
|
||||||
|
|
||||||
batch.update(ref, updateData);
|
batch.update(ref, updateData);
|
||||||
count++;
|
count++;
|
||||||
});
|
});
|
||||||
|
|
||||||
await batch.commit();
|
await batch.commit();
|
||||||
console.log(`💾 Guardados ${count} documentos (${providerType}).`);
|
|
||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue