Files
robot-proveedores/robot.js
2026-03-22 22:16:06 +00:00

468 lines
22 KiB
JavaScript

import { chromium } from 'playwright';
import pg from 'pg';
const { DATABASE_URL } = process.env;
if (!DATABASE_URL) { console.error("❌ Error: No hay DATABASE_URL."); process.exit(1); }
const pool = new pg.Pool({ connectionString: DATABASE_URL, ssl: false });
const HEADLESS = true;
// ==========================================
// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (DINÁMICO)
// ==========================================
function normalizarTexto(texto) {
if (!texto) return "";
return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
// 🛠️ El "Gira-Nombres" EXCLUSIVO para HomeServe
function arreglarNombre(nombreRaw) {
if (!nombreRaw) return "";
let nombreLimpio = nombreRaw.trim();
if (nombreLimpio.includes(',')) {
let partes = nombreLimpio.split(',');
let apellidos = partes[0].trim();
let nombre = partes[1].trim();
nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' ');
}
return nombreLimpio;
}
// 🛡️ DESCODIFICADOR UNIVERSAL PARA HOMESERVE (Arregla los +, Ó, Ñ, etc.)
function arreglarCodificacion(texto) {
if (!texto) return "";
let limpio = texto.replace(/\+/g, ' ');
try {
limpio = decodeURIComponent(escape(limpio));
} catch(e) {}
return limpio.trim();
}
function clasificarGremio(descripcion, gremiosActivosDB) {
if (!descripcion || gremiosActivosDB.length === 0) return null;
const descNormalizada = normalizarTexto(descripcion);
for (const gremio of gremiosActivosDB) {
const keywords = Array.isArray(gremio.ia_keywords) ? gremio.ia_keywords : [];
if (keywords.length === 0) continue;
const coincide = keywords.some(kw => descNormalizada.includes(normalizarTexto(kw)));
if (coincide) {
console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`);
return gremio.id;
}
}
return null;
}
async function gotoWithRetry(page, url, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
return;
} catch (e) {
if (i === retries - 1) throw e;
console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`);
await page.waitForTimeout(3000);
}
}
}
async function main() {
console.log("🤖 ROBOT MODO: CIRUJANO + ASPIRADORA + CLASIFICADOR PRO");
while (true) {
const client = await pool.connect();
try {
const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds");
const gremiosDB = gremiosRes.rows;
await client.query(`
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='is_urgent') THEN
ALTER TABLE scraped_services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE;
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='ia_keywords') THEN
ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]';
END IF;
END $$;
`);
const res = await client.query("SELECT * FROM provider_credentials WHERE status = 'active'");
for (const cred of res.rows) {
let password = Buffer.from(cred.password_hash, 'base64').toString('utf-8');
console.log(`\n🔄 Procesando ${cred.provider.toUpperCase()}...`);
if (cred.provider === 'multiasistencia') {
await runMultiasistencia(cred.owner_id, cred.username, password, gremiosDB);
} else if (cred.provider === 'homeserve') {
await runHomeserve(cred.owner_id, cred.username, password, gremiosDB);
}
await client.query("UPDATE provider_credentials SET last_sync = NOW() WHERE id = $1", [cred.id]);
}
} catch (e) { console.error("❌ Error ciclo:", e.message); }
finally { client.release(); }
console.log("\n💤 Durmiendo 15 minutos...");
await new Promise(r => setTimeout(r, 15 * 60 * 1000));
}
}
// ==========================================
// 🏥 MULTIASISTENCIA (PAGINACIÓN ANTIBALAS Y DOBLE RECARGA)
// ==========================================
// --- BUCLE DE PAGINACIÓN INFALIBLE ---
let todosExpedientes = new Set();
let paginaActual = 1;
console.log(`📄 [Multi] Iniciando lectura por páginas...`);
while (true) {
console.log(`\n📄 [Multi] Escaneando página ${paginaActual}...`);
// 🛑 NUEVO: Esperamos a que los enlaces existan o damos 5 seg. de margen extra
await page.waitForSelector('a[href*="reparacion="]', { timeout: 6000 }).catch(() => {});
await page.waitForTimeout(1000);
// 1. Extraemos los enlaces de esta página
const expedientesPagina = await page.evaluate(() => {
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean);
});
const unicosPagina = [...new Set(expedientesPagina)];
console.log(` 👉 Encontrados ${unicosPagina.length} expedientes únicos en la pág. ${paginaActual}.`);
if (unicosPagina.length === 0) {
console.log(" ⚠️ Página en blanco o cargando demasiado lento. Terminamos aquí.");
break;
}
unicosPagina.forEach(ref => todosExpedientes.add(ref));
// 2. BUSCAMOS Y PULSAMOS EL BOTÓN "SIGUIENTE"
const clicked = await page.evaluate(() => {
const links = Array.from(document.querySelectorAll('a.lnkheader'));
const btn = links.find(a => a.innerText.toLowerCase().includes('siguiente'));
if (btn) {
btn.click();
return true;
}
return false;
});
if (clicked) {
console.log(` ➡️ Botón 'Siguiente' detectado. Pulsando y esperando a que cargue...`);
// 🛑 EL FRENO: Congelamos el robot 5 segundos fijos para que el servidor responda
await page.waitForTimeout(5000);
paginaActual++;
if(paginaActual > 20) {
console.log("⚠️ [Multi] Límite de 20 páginas alcanzado por seguridad.");
break;
}
} else {
console.log("🛑 [Multi] Fin de la lista. No hay enlace a página siguiente.");
break;
}
}
const expedientesUnicos = Array.from(todosExpedientes);
console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientesUnicos.length}`);
// SEGURO DE VIDA PARA MULTIASISTENCIA
if (expedientesUnicos.length > 5 || paginaActual === 1) {
console.log(`🧹 [Multi] Llamando a la escoba con ${expedientesUnicos.length} refs...`);
await syncAndArchive(ownerId, 'multiasistencia', expedientesUnicos);
} else {
console.log("⚠️ [Multi] Menos de 5 expedientes detectados. ABORTANDO ARCHIVADO DE SEGURIDAD.");
}
// BUCLE DE GUARDADO
for (const ref of expedientesUnicos) {
await gotoWithRetry(page, `https://web.multiasistencia.com/w3multi/repasos1.php?reparacion=${ref}`);
await page.waitForTimeout(1500);
let scrapData = null;
for (const frame of page.frames()) {
try {
scrapData = await frame.evaluate(() => {
const clean = (t) => t ? t.replace(/\s+/g, ' ').trim() : "";
const body = document.body?.innerText || "";
if (!body.includes("Nombre Cliente") && !body.includes("Asegurado")) return null;
const cabeceras = Array.from(document.querySelectorAll('.tcab'));
const detalles = Array.from(document.querySelectorAll('.tdet'));
const findByCab = (texto) => {
const idx = cabeceras.findIndex(el => el.innerText.includes(texto));
return idx !== -1 && detalles[idx] ? clean(detalles[idx].innerText) : null;
};
let rawDesc = "";
const descHeader = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación"));
if (descHeader && descHeader.nextElementSibling) rawDesc = clean(descHeader.nextElementSibling.innerText);
const rawCPField = findByCab("Distrito Postal") || "";
const cpMatch = rawCPField.match(/\b\d{5}\b/);
const cpOnly = cpMatch ? cpMatch[0] : "";
const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim();
let telefonoReal = "";
const titulosDiv = Array.from(document.querySelectorAll('.subtitulo'));
const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono'));
if (divTelefono && divTelefono.nextElementSibling) {
const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet');
if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, '');
}
if (!telefonoReal || telefonoReal.length < 9) {
telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "";
}
return {
"Expediente": findByCab("Número Reparación") || "",
"Nombre Cliente": findByCab("Nombre Cliente") || "",
"Dirección": findByCab("Dirección") || "",
"Población": popOnly,
"Código Postal": cpOnly,
"Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"),
"Descripción": rawDesc,
"Teléfono": telefonoReal,
"Estado": findByCab("Estado") || "",
"Urgente": findByCab("Urgente") || "No"
};
});
if (scrapData && scrapData['Nombre Cliente']) break;
} catch (e) { continue; }
}
if (scrapData && scrapData['Nombre Cliente']) {
const idGremioDetectado = clasificarGremio(scrapData['Descripción'], gremiosDB);
if (idGremioDetectado) {
scrapData['guild_id'] = idGremioDetectado;
}
await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData);
}
} catch (e) {
console.error("❌ Error Multi:", e.message);
} finally {
await browser.close();
}
}
// ==========================================
// 🧹 HOMESERVE (MEJORADO CON DECODIFICADOR, ICONOS Y URGENCIA)
// ==========================================
async function runHomeserve(ownerId, user, pass, gremiosDB) {
const browser = await chromium.launch({
headless: HEADLESS,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
});
const page = await browser.newPage();
try {
console.log("🌍 [HomeServe] Entrando...");
await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=PROF_PASS');
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 gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
await page.waitForTimeout(3000);
// 🛑 EXTRAEMOS REFS E ICONOS
const listaConIconos = await page.evaluate(() => {
const results = [];
const rows = Array.from(document.querySelectorAll('table[bgcolor="#FCF4D6"] tr'));
rows.forEach(tr => {
const firstTd = tr.querySelector('td');
if (!firstTd) return;
const textMatch = firstTd.innerText.trim().match(/^15\d{6}$/);
const aMatch = firstTd.querySelector('a') ? firstTd.querySelector('a').innerText.trim().match(/^15\d{6}$/) : null;
const ref = textMatch ? textMatch[0] : (aMatch ? aMatch[0] : null);
if (ref) {
const hasLock = firstTd.querySelector('img[src*="candado.gif"]') !== null;
const hasEyes = firstTd.querySelector('img[src*="ojos.gif"]') !== null;
results.push({ ref, hasLock, hasEyes });
}
});
return results;
});
const refs = [...new Set(listaConIconos.map(item => item.ref))];
if (refs.length > 0) {
await syncAndArchive(ownerId, 'homeserve', refs);
}
console.log(`🔍 [HomeServe] ${refs.length} expedientes detectados.`);
for (const ref of refs) {
await gotoWithRetry(page, `https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=ver_servicioencurso&Servicio=${ref}`);
await page.waitForTimeout(2000);
const scrapData = await page.evaluate(() => {
const d = {};
let isUrgent = "No";
const rows = Array.from(document.querySelectorAll('tr'));
rows.forEach(r => {
const cells = r.querySelectorAll('td');
if (cells.length >= 2) {
const k = cells[0].innerText.toUpperCase().trim().replace(':', '');
const v = cells[1].innerText.trim();
if (k.includes("COMENTARIOS")) {
const inputEl = cells[1].querySelector('textarea');
const txt = inputEl ? inputEl.value : (cells[1].innerText || "");
// 🔥 DETECTOR DE URGENCIA 🔥
const txtLower = txt.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
if (txtLower.includes("atencion presencial urgencias") || txtLower.includes("atencion de la urgencia") || txtLower.includes("urgente")) {
isUrgent = "Sí";
}
const cleanDesc = txt.split('\n').filter(line => {
const l = line.toUpperCase();
return !["ESTADO ASIGNADO", "SMS NO ENVIADO", "CONTACTO CON PROF", "0000"].some(b => l.includes(b));
}).join('\n').trim();
d['Descripción'] = cleanDesc;
} else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) {
d[k] = v;
}
}
});
const rawPop = d['POBLACION-PROVINCIA'] || "";
const cpMatch = rawPop.match(/\b\d{5}\b/);
d['Código Postal'] = cpMatch ? cpMatch[0] : "";
d['Población'] = rawPop.replace(d['Código Postal'], '').replace('-', '').trim();
d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE");
d['Nombre Cliente'] = d['CLIENTE'] || "";
d['Dirección'] = d['DOMICILIO'] || "";
d['Urgente'] = isUrgent;
return d;
});
if (scrapData && scrapData['Nombre Cliente']) {
// 🪄 Arreglamos codificación y nombres de HomeServe
scrapData['Nombre Cliente'] = arreglarNombre(arreglarCodificacion(scrapData['Nombre Cliente']));
scrapData['Dirección'] = arreglarCodificacion(scrapData['Dirección']);
scrapData['Población'] = arreglarCodificacion(scrapData['Población']);
scrapData['Descripción'] = arreglarCodificacion(scrapData['Descripción']);
// 🛑 INYECTAMOS ICONOS CAZADOS
const iconInfo = listaConIconos.find(item => item.ref === ref);
if (iconInfo) {
scrapData['has_lock'] = iconInfo.hasLock;
scrapData['has_eyes'] = iconInfo.hasEyes;
}
const idGremioDetectado = clasificarGremio(scrapData['Descripción'], gremiosDB);
if (idGremioDetectado) {
scrapData['guild_id'] = idGremioDetectado;
}
await saveServiceToDB(ownerId, 'homeserve', ref, scrapData);
}
}
} catch (e) { console.error("❌ [HomeServe] Error:", e.message); }
finally { await browser.close(); }
}
async function syncAndArchive(ownerId, provider, currentWebRefs) {
const client = await pool.connect();
try {
const { rows: dbServices } = await client.query(
`SELECT id, service_ref, assigned_to, raw_data FROM scraped_services
WHERE owner_id = $1 AND provider = $2 AND status IN ('pending', 'imported')`,
[ownerId, provider]
);
const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref));
const refsToArchive = missingServices.map(s => s.service_ref);
console.log(`\n📊 [ESCOBA ${provider.toUpperCase()}] Refs en Web: ${currentWebRefs.length} | Pendientes en BD: ${dbServices.length}`);
if (refsToArchive.length > 0) {
console.log(`🚨 ATENCIÓN: Se van a ARCHIVAR ${refsToArchive.length} expedientes porque NO están en la web:`);
console.log(`💀 LISTA:`, refsToArchive.join(', '));
await client.query(
`UPDATE scraped_services
SET status = 'archived'
WHERE owner_id = $1
AND provider = $2
AND service_ref = ANY($3)`,
[ownerId, provider, refsToArchive]
);
// ========================================================
// 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Apagado para Multiasistencia)
// ========================================================
const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id = $1 AND name ILIKE '%anulado%' LIMIT 1", [ownerId]);
const idAnulado = statusQ.rowCount > 0 ? statusQ.rows[0].id : null;
if (idAnulado && provider !== 'multiasistencia') {
for (const svc of missingServices) {
if (svc.assigned_to) {
const raw = svc.raw_data || {};
const currentStatusId = String(raw.status_operativo || "");
if (currentStatusId !== String(idAnulado)) {
let isFinal = false;
if (currentStatusId) {
const checkStatusQ = await client.query("SELECT is_final FROM service_statuses WHERE id = $1", [currentStatusId]);
isFinal = checkStatusQ.rowCount > 0 ? checkStatusQ.rows[0].is_final : false;
}
if (!isFinal) {
raw.status_operativo = idAnulado;
await client.query("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(raw), svc.id]);
await client.query(
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
[svc.id, "Sistema Robot", "Cancelación Automática", "La compañía ha retirado el expediente. Se pasa a Anulado."]
);
console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado).`);
}
}
}
}
}
console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`);
}
} catch (error) {
console.error(`❌ Error archivando ${provider}:`, error.message);
} finally {
client.release();
}
}
async function saveServiceToDB(ownerId, provider, ref, data) {
console.log(`💾 Guardando/Actualizando ${provider.toUpperCase()} ${ref}...`);
const isUrgent = (data['Urgente'] && (data['Urgente'].toLowerCase().trim() === 'sí' || data['Urgente'].toLowerCase().trim() === 'si')) ? true : false;
await pool.query(`
INSERT INTO scraped_services (owner_id, provider, service_ref, raw_data, status, is_urgent)
VALUES ($1, $2, $3, $4, 'pending', $5)
ON CONFLICT (owner_id, provider, service_ref)
DO UPDATE SET
raw_data = (scraped_services.raw_data || EXCLUDED.raw_data) ||
jsonb_build_object('guild_id', COALESCE(scraped_services.raw_data->'guild_id', EXCLUDED.raw_data->'guild_id')),
is_urgent = EXCLUDED.is_urgent,
status = CASE
WHEN scraped_services.status = 'archived' THEN 'archived'
WHEN scraped_services.status = 'imported' THEN 'imported'
ELSE 'pending'
END
`, [ownerId, provider, ref, JSON.stringify(data), isUrgent]);
}
main();