Añadir robot.js

This commit is contained in:
2026-02-12 22:54:11 +00:00
commit d9ea74016e

202
robot.js Normal file
View File

@@ -0,0 +1,202 @@
import { chromium } from 'playwright';
import pg from 'pg';
// En Coolify las variables se inyectan solas, pero mantenemos esto por si pruebas en local
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 (MULTI + HOMESERVE)...");
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) {
// Desencriptar password (asumiendo base64 simple por ahora)
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
// ==========================================
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
await page.fill('input[name="usuario"]', 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' });
const data = await page.evaluate(() => {
const body = document.body.innerText;
const getVal = (k) => {
const regex = new RegExp(`${k}\\s*[:\\-]?\\s*([^\\n]+)`, 'i');
return body.match(regex)?.[1]?.trim() || "";
};
return {
clientName: getVal("Nombre Cliente") || getVal("Asegurado"),
address: getVal("Dirección") || getVal("Domicilio"),
phone: (body.match(/[6789]\d{8}/) || [])[0] || "",
description: getVal("Descripción")
};
});
if (data.clientName) {
await saveServiceToDB(ownerId, 'multiasistencia', ref, data);
}
}
} catch (e) {
console.error("❌ [Multi] Error:", e.message);
} finally {
await browser.close();
}
}
// ==========================================
// 🛠️ ROBOT HOMESERVE
// ==========================================
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("TELEFONOS")) d.phone = v;
if(k.includes("COMENTARIOS")) 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;
console.log(`💾 Guardando en buzón: ${ref}`);
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();