Files
robot-proveedores/robot.js
2026-02-13 09:27:00 +00:00

245 lines
10 KiB
JavaScript

import { chromium } from 'playwright';
import pg from 'pg';
// En Coolify las variables se inyectan solas
const { DATABASE_URL } = process.env;
if (!DATABASE_URL) {
console.error("❌ Error: No hay DATABASE_URL definida.");
process.exit(1);
}
const pool = new pg.Pool({ connectionString: DATABASE_URL, ssl: false });
// CONFIGURACIÓN
const HEADLESS = true; // En servidor SIEMPRE true
async function main() {
console.log("🤖 INICIANDO ROBOT UNIFICADO (MEJORADO)...");
while (true) {
const client = await pool.connect();
try {
// 1. Obtener credenciales activas
const res = await client.query("SELECT * FROM provider_credentials WHERE status = 'active'");
const credentials = res.rows;
console.log(`📋 Procesando ${credentials.length} cuentas de proveedores...`);
for (const cred of credentials) {
let password = "";
try {
password = Buffer.from(cred.password_hash, 'base64').toString('utf-8');
} catch (e) {
console.error(`Error decodificando pass para usuario ${cred.owner_id}`);
continue;
}
console.log(`\n🔄 Sincronizando ${cred.provider.toUpperCase()} para usuario ID ${cred.owner_id}...`);
if (cred.provider === 'multiasistencia') {
await runMultiasistencia(cred.owner_id, cred.username, password);
} else if (cred.provider === 'homeserve') {
await runHomeserve(cred.owner_id, cred.username, password);
}
// Actualizar timestamp
await client.query("UPDATE provider_credentials SET last_sync = NOW() WHERE id = $1", [cred.id]);
}
} catch (e) {
console.error("❌ Error en ciclo principal:", e);
} finally {
client.release();
}
// ESPERA DE 15 MINUTOS
console.log("\n💤 Durmiendo 15 minutos...");
await new Promise(r => setTimeout(r, 15 * 60 * 1000));
}
}
// ==========================================
// 🛠️ ROBOT MULTIASISTENCIA (CORREGIDO)
// ==========================================
async function runMultiasistencia(ownerId, user, pass) {
const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] });
const context = await browser.newContext();
const page = await context.newPage();
try {
console.log("🌍 [Multi] Conectando...");
await page.goto('https://web.multiasistencia.com/w3multi/acceso.php', { timeout: 60000 });
// Login
const userInput = await page.$('input[name="usuario"]') || await page.$('input[type="text"]');
if(userInput) {
await userInput.fill(user);
await page.fill('input[type="password"]', pass);
await page.click('input[type="submit"]');
await page.waitForTimeout(4000);
}
// Ir a listado
await page.goto('https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1', { waitUntil: 'domcontentloaded' });
// Sacar expedientes
const expedientes = await page.evaluate(() => {
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
return Array.from(new Set(links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean)));
});
console.log(`🔍 [Multi] ${expedientes.length} expedientes encontrados.`);
for (const ref of expedientes) {
await page.goto(`https://web.multiasistencia.com/w3multi/repasos1.php?reparacion=${ref}`, { waitUntil: 'domcontentloaded' });
// --- NUEVA LÓGICA DE EXTRACCIÓN POR CELDAS ---
const data = await page.evaluate(() => {
// Función auxiliar para buscar en celdas vecinas
const findValueByHeader = (keywords) => {
const cells = Array.from(document.querySelectorAll('td, th'));
for (const cell of cells) {
const text = (cell.innerText || "").toUpperCase().trim();
// Si la celda contiene una de las palabras clave
if (keywords.some(k => text.includes(k.toUpperCase()))) {
// Devolvemos el texto de la celda SIGUIENTE
const nextCell = cell.nextElementSibling;
if (nextCell) return nextCell.innerText.trim();
}
}
return "";
};
// Función auxiliar para descripción (busca bloques de texto grandes)
const findDescription = () => {
// Intento 1: Buscar celda "Descripción"
let desc = findValueByHeader(['Descripción', 'Daños', 'Solicitud']);
if(desc) return desc;
// Intento 2: Buscar en el cuerpo general si falla la tabla
const body = document.body.innerText;
const match = body.match(/Descripción\s*[:\-]?\s*([^\n]+)/i);
return match ? match[1].trim() : "";
}
// Extracción más precisa
let address = findValueByHeader(['Dirección', 'Domicilio', 'Riesgo']);
let pob = findValueByHeader(['Población', 'Localidad']);
let cp = findValueByHeader(['C.P.', 'Postal']);
// Limpieza de dirección (quitar "Baremo" si se cuela)
if (address.includes("Baremo")) address = address.split("Baremo")[0].trim();
// Unir dirección completa
let fullAddress = address;
if (pob) fullAddress += `, ${pob}`;
if (cp) fullAddress += ` (${cp})`;
return {
clientName: findValueByHeader(['Nombre Cliente', 'Asegurado']) || "Desconocido",
address: fullAddress || "Sin dirección detectada",
phone: (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "",
description: findDescription()
};
});
if (data.clientName) {
// Solo guardamos si tenemos al menos un nombre
await saveServiceToDB(ownerId, 'multiasistencia', ref, data);
}
}
} catch (e) {
console.error("❌ [Multi] Error:", e.message);
} finally {
await browser.close();
}
}
// ==========================================
// 🛠️ ROBOT HOMESERVE (MANTENIDO)
// ==========================================
async function runHomeserve(ownerId, user, pass) {
const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox'] });
const page = await browser.newPage();
try {
console.log("🌍 [HomeServe] Conectando...");
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS', { timeout: 60000 });
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(5000);
}
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
const refs = await page.evaluate(() => {
const filas = Array.from(document.querySelectorAll('table tr'));
return filas.map(tr => tr.querySelector('td')?.innerText.trim()).filter(t => /^\d{4,}$/.test(t));
});
console.log(`🔍 [HomeServe] ${refs.length} expedientes encontrados.`);
for (const ref of refs) {
try {
await page.goto('https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
await page.click(`text="${ref}"`, { timeout: 5000 });
await page.waitForTimeout(1000);
const data = await page.evaluate(() => {
const rows = Array.from(document.querySelectorAll('tr'));
const d = {};
rows.forEach(r => {
const cells = r.querySelectorAll('td');
if(cells.length > 1) {
const k = cells[0].innerText.toUpperCase();
const v = cells[1].innerText;
if(k.includes("CLIENTE")) d.clientName = v;
if(k.includes("DOMICILIO")) d.address = v;
if(k.includes("POBLACION")) d.address += ", " + v;
if(k.includes("TELEFONOS")) d.phone = v;
if(k.includes("COMENTARIOS") || k.includes("AVERIA")) d.description = v;
}
});
return d;
});
if (data.clientName) {
await saveServiceToDB(ownerId, 'homeserve', ref, data);
}
} catch (e) { console.error(`Error leyendo ${ref}: ${e.message}`); }
}
} catch (e) {
console.error("❌ [HomeServe] Error:", e.message);
} finally {
await browser.close();
}
}
// ==========================================
// 💾 GUARDADO EN BASE DE DATOS
// ==========================================
async function saveServiceToDB(ownerId, provider, ref, data) {
// Verificar si ya existe en servicios reales (para no duplicar trabajo)
const exists = await pool.query("SELECT id FROM services WHERE company_ref = $1 AND owner_id = $2", [ref, ownerId]);
if (exists.rowCount > 0) return;
// Verificar si ya existe en buzón, si existe ACTUALIZAMOS los datos (por si hemos mejorado el scraping)
console.log(`💾 Guardando/Actualizando: ${ref} (${data.address})`);
await pool.query(`
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, status)
VALUES ($1, $2, $3, $4, 'pending')
ON CONFLICT (owner_id, provider, service_ref)
DO UPDATE SET raw_data = EXCLUDED.raw_data, created_at = NOW()
`, [ownerId, provider, ref, JSON.stringify(data)]);
}
main();