Actualizar robot.js
This commit is contained in:
187
robot.js
187
robot.js
@@ -8,7 +8,7 @@ const pool = new pg.Pool({ connectionString: DATABASE_URL, ssl: false });
|
|||||||
const HEADLESS = true;
|
const HEADLESS = true;
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (AHORA DINÁMICO)
|
// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (DINÁMICO)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|
||||||
function normalizarTexto(texto) {
|
function normalizarTexto(texto) {
|
||||||
@@ -16,16 +16,14 @@ function normalizarTexto(texto) {
|
|||||||
return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🛠️ NUEVO: El "Gira-Nombres" EXCLUSIVO para HomeServe
|
// 🛠️ El "Gira-Nombres" EXCLUSIVO para HomeServe
|
||||||
function arreglarNombre(nombreRaw) {
|
function arreglarNombre(nombreRaw) {
|
||||||
if (!nombreRaw) return "";
|
if (!nombreRaw) return "";
|
||||||
let nombreLimpio = nombreRaw.trim();
|
let nombreLimpio = nombreRaw.trim();
|
||||||
// Si detectamos que tiene una coma...
|
|
||||||
if (nombreLimpio.includes(',')) {
|
if (nombreLimpio.includes(',')) {
|
||||||
let partes = nombreLimpio.split(',');
|
let partes = nombreLimpio.split(',');
|
||||||
let apellidos = partes[0].trim();
|
let apellidos = partes[0].trim();
|
||||||
let nombre = partes[1].trim();
|
let nombre = partes[1].trim();
|
||||||
// Le damos la vuelta y quitamos espacios sobrantes
|
|
||||||
nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' ');
|
nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' ');
|
||||||
}
|
}
|
||||||
return nombreLimpio;
|
return nombreLimpio;
|
||||||
@@ -34,31 +32,23 @@ function arreglarNombre(nombreRaw) {
|
|||||||
// 🛡️ DESCODIFICADOR UNIVERSAL PARA HOMESERVE (Arregla los +, Ó, Ñ, etc.)
|
// 🛡️ DESCODIFICADOR UNIVERSAL PARA HOMESERVE (Arregla los +, Ó, Ñ, etc.)
|
||||||
function arreglarCodificacion(texto) {
|
function arreglarCodificacion(texto) {
|
||||||
if (!texto) return "";
|
if (!texto) return "";
|
||||||
let limpio = texto.replace(/\+/g, ' '); // Primero cambiamos los + por espacios
|
let limpio = texto.replace(/\+/g, ' ');
|
||||||
try {
|
try {
|
||||||
// Truco clásico de Javascript para transformar ISO a UTF-8
|
|
||||||
limpio = decodeURIComponent(escape(limpio));
|
limpio = decodeURIComponent(escape(limpio));
|
||||||
} catch(e) {
|
} catch(e) {}
|
||||||
// Si no se puede, lo dejamos con los espacios arreglados
|
|
||||||
}
|
|
||||||
return limpio.trim();
|
return limpio.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
// NUEVO: La función ahora lee las keywords directamente del JSON de la base de datos
|
|
||||||
function clasificarGremio(descripcion, gremiosActivosDB) {
|
function clasificarGremio(descripcion, gremiosActivosDB) {
|
||||||
if (!descripcion || gremiosActivosDB.length === 0) return null;
|
if (!descripcion || gremiosActivosDB.length === 0) return null;
|
||||||
|
|
||||||
const descNormalizada = normalizarTexto(descripcion);
|
const descNormalizada = normalizarTexto(descripcion);
|
||||||
|
|
||||||
for (const gremio of gremiosActivosDB) {
|
for (const gremio of gremiosActivosDB) {
|
||||||
// Obtenemos las palabras clave guardadas desde el panel de configuración
|
|
||||||
const keywords = Array.isArray(gremio.ia_keywords) ? gremio.ia_keywords : [];
|
const keywords = Array.isArray(gremio.ia_keywords) ? gremio.ia_keywords : [];
|
||||||
|
if (keywords.length === 0) continue;
|
||||||
if (keywords.length === 0) continue; // Si no tiene reglas, pasamos al siguiente
|
|
||||||
|
|
||||||
// Comprobamos si alguna palabra clave coincide con la descripción
|
|
||||||
const coincide = keywords.some(kw => descNormalizada.includes(normalizarTexto(kw)));
|
const coincide = keywords.some(kw => descNormalizada.includes(normalizarTexto(kw)));
|
||||||
|
|
||||||
if (coincide) {
|
if (coincide) {
|
||||||
console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`);
|
console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`);
|
||||||
return gremio.id;
|
return gremio.id;
|
||||||
@@ -67,17 +57,15 @@ function clasificarGremio(descripcion, gremiosActivosDB) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Función auxiliar para reintentar la navegación si hay fallo de red
|
|
||||||
async function gotoWithRetry(page, url, retries = 3) {
|
async function gotoWithRetry(page, url, retries = 3) {
|
||||||
for (let i = 0; i < retries; i++) {
|
for (let i = 0; i < retries; i++) {
|
||||||
try {
|
try {
|
||||||
// Usamos domcontentloaded para que no se quede colgado esperando imágenes o scripts pesados
|
|
||||||
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
|
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
|
||||||
return; // Si funciona, salimos de la función
|
return;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (i === retries - 1) throw e; // Si es el último intento, lanza el error
|
if (i === retries - 1) throw e;
|
||||||
console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`);
|
console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`);
|
||||||
await page.waitForTimeout(3000); // Esperamos 3 segundos antes de volver a intentar
|
await page.waitForTimeout(3000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,7 +75,6 @@ async function main() {
|
|||||||
while (true) {
|
while (true) {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
// 1. CARGAMOS LOS GREMIOS ACTUALES (AHORA INCLUYE LAS PALABRAS CLAVE)
|
|
||||||
const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds");
|
const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds");
|
||||||
const gremiosDB = gremiosRes.rows;
|
const gremiosDB = gremiosRes.rows;
|
||||||
|
|
||||||
@@ -96,7 +83,6 @@ async function main() {
|
|||||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='scraped_services' AND column_name='is_urgent') THEN
|
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;
|
ALTER TABLE scraped_services ADD COLUMN is_urgent BOOLEAN DEFAULT FALSE;
|
||||||
END IF;
|
END IF;
|
||||||
-- AÑADIDO: Aseguramos que exista la columna ia_keywords en los gremios
|
|
||||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='guilds' AND column_name='ia_keywords') THEN
|
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 '[]';
|
ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]';
|
||||||
END IF;
|
END IF;
|
||||||
@@ -122,20 +108,15 @@ async function main() {
|
|||||||
console.log("\n💤 Durmiendo 15 minutos...");
|
console.log("\n💤 Durmiendo 15 minutos...");
|
||||||
await new Promise(r => setTimeout(r, 15 * 60 * 1000));
|
await new Promise(r => setTimeout(r, 15 * 60 * 1000));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🏥 MULTIASISTENCIA (ASPIRADORA MASIVA C/ DOBLE RECARGA)
|
// 🏥 MULTIASISTENCIA (PAGINACIÓN ANTIBALAS Y DOBLE RECARGA)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
||||||
const browser = await chromium.launch({
|
const browser = await chromium.launch({
|
||||||
headless: HEADLESS,
|
headless: HEADLESS,
|
||||||
args: [
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
|
||||||
'--no-sandbox',
|
|
||||||
'--disable-setuid-sandbox',
|
|
||||||
'--disable-dev-shm-usage',
|
|
||||||
'--disable-gpu'
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
const context = await browser.newContext();
|
const context = await browser.newContext();
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
@@ -151,58 +132,69 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
|
|
||||||
console.log("📥 [Multi] Entrando al buzón...");
|
console.log("📥 [Multi] Entrando al buzón...");
|
||||||
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1');
|
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1');
|
||||||
await page.waitForTimeout(4000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
// 🛑 DOBLE RECARGA FORZADA PARA DESPERTAR AL SERVIDOR
|
// 🔄 DOBLE RECARGA FORZADA PARA DESPERTAR AL SERVIDOR
|
||||||
console.log("🔄 [Multi] Forzando doble recarga del buzón...");
|
console.log("🔄 [Multi] Forzando doble recarga del buzón...");
|
||||||
for (let i = 1; i <= 2; i++) {
|
for (let i = 1; i <= 2; i++) {
|
||||||
try {
|
try {
|
||||||
// Buscamos la imagen del botón de recargar y le hacemos click
|
console.log(` 👉 Forzando recarga ${i}/2...`);
|
||||||
const btnRecargar = page.locator('img[name="recarga"], img#recargar, img[src*="btn_recargar"]').first();
|
await page.evaluate(() => {
|
||||||
if (await btnRecargar.count() > 0) {
|
if (typeof refrescar === 'function') refrescar();
|
||||||
console.log(` 👉 Pulsando botón físico de recargar ${i}/2...`);
|
else if (document.getElementById('recargar')) document.getElementById('recargar').click();
|
||||||
await btnRecargar.click();
|
});
|
||||||
} else {
|
await page.waitForTimeout(3500);
|
||||||
console.log(` 👉 Forzando función javascript refrescar() ${i}/2...`);
|
|
||||||
await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); });
|
|
||||||
}
|
|
||||||
await page.waitForTimeout(4000); // Esperamos a que la tabla se redibuje
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(` ⚠️ Fallo menor en recarga ${i}: ${e.message}`);
|
console.log(` ⚠️ Fallo menor en recarga ${i}: ${e.message}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`📄 [Multi] Haciendo scroll infinito para cargar todos los expedientes...`);
|
// --- BUCLE DE PAGINACIÓN INFALIBLE ---
|
||||||
// Hacemos scroll hasta abajo varias veces
|
let todosExpedientes = new Set();
|
||||||
await page.evaluate(async () => {
|
let paginaActual = 1;
|
||||||
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
||||||
for (let i = 0; i < 5; i++) {
|
console.log(`📄 [Multi] Iniciando lectura por páginas...`);
|
||||||
window.scrollTo(0, document.body.scrollHeight);
|
while (true) {
|
||||||
await delay(1000);
|
console.log(`\n📄 [Multi] Escaneando página ${paginaActual}...`);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
// 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}.`);
|
||||||
|
unicosPagina.forEach(ref => todosExpedientes.add(ref));
|
||||||
|
|
||||||
|
// 2. BUSCAMOS LA URL DEL BOTÓN "SIGUIENTE"
|
||||||
|
const nextPageUrl = await page.evaluate(() => {
|
||||||
|
const links = Array.from(document.querySelectorAll('a.lnkheader'));
|
||||||
|
const nextBtn = links.find(a => a.innerText.toLowerCase().includes('siguiente'));
|
||||||
|
return nextBtn ? nextBtn.href : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (nextPageUrl) {
|
||||||
|
console.log(` ➡️ Botón 'Siguiente' detectado. Navegando a la url...`);
|
||||||
|
await gotoWithRetry(page, nextPageUrl);
|
||||||
|
await page.waitForTimeout(3000);
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`🔍 [Multi] Extrayendo referencias...`);
|
|
||||||
let todosExpedientes = [];
|
|
||||||
|
|
||||||
// Buscamos en el documento principal y en todos los frames por si acaso
|
|
||||||
for (const frame of [page.mainFrame(), ...page.frames()]) {
|
|
||||||
try {
|
|
||||||
const refsInFrame = await frame.evaluate(() => {
|
|
||||||
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
|
||||||
return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean);
|
|
||||||
});
|
|
||||||
todosExpedientes = todosExpedientes.concat(refsInFrame);
|
|
||||||
} catch(e) {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Limpiamos los duplicados usando un Set
|
|
||||||
const expedientesUnicos = [...new Set(todosExpedientes)];
|
|
||||||
|
|
||||||
|
const expedientesUnicos = Array.from(todosExpedientes);
|
||||||
console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientesUnicos.length}`);
|
console.log(`\n✅ [Multi] TOTAL EXPEDIENTES LEÍDOS EN WEB: ${expedientesUnicos.length}`);
|
||||||
|
|
||||||
// SEGURO DE VIDA
|
// SEGURO DE VIDA PARA MULTIASISTENCIA
|
||||||
if (expedientesUnicos.length > 5) {
|
if (expedientesUnicos.length > 5 || paginaActual === 1) {
|
||||||
console.log(`🧹 [Multi] Llamando a la escoba con ${expedientesUnicos.length} refs...`);
|
console.log(`🧹 [Multi] Llamando a la escoba con ${expedientesUnicos.length} refs...`);
|
||||||
await syncAndArchive(ownerId, 'multiasistencia', expedientesUnicos);
|
await syncAndArchive(ownerId, 'multiasistencia', expedientesUnicos);
|
||||||
} else {
|
} else {
|
||||||
@@ -282,17 +274,12 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🧹 HOMESERVE (ROBOT MEJORADO Y DETECTOR DE URGENCIAS)
|
// 🧹 HOMESERVE (MEJORADO CON DECODIFICADOR, ICONOS Y URGENCIA)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
||||||
const browser = await chromium.launch({
|
const browser = await chromium.launch({
|
||||||
headless: HEADLESS,
|
headless: HEADLESS,
|
||||||
args: [
|
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu']
|
||||||
'--no-sandbox',
|
|
||||||
'--disable-setuid-sandbox',
|
|
||||||
'--disable-dev-shm-usage',
|
|
||||||
'--disable-gpu'
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
const page = await browser.newPage();
|
const page = await browser.newPage();
|
||||||
try {
|
try {
|
||||||
@@ -309,19 +296,16 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
|
await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total');
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
// 🛑 NUEVO: Ahora extraemos la referencia Y LOS ICONOS de la misma pasada
|
// 🛑 EXTRAEMOS REFS E ICONOS
|
||||||
const listaConIconos = await page.evaluate(() => {
|
const listaConIconos = await page.evaluate(() => {
|
||||||
const results = [];
|
const results = [];
|
||||||
const rows = Array.from(document.querySelectorAll('table[bgcolor="#FCF4D6"] tr'));
|
const rows = Array.from(document.querySelectorAll('table[bgcolor="#FCF4D6"] tr'));
|
||||||
|
|
||||||
rows.forEach(tr => {
|
rows.forEach(tr => {
|
||||||
const firstTd = tr.querySelector('td');
|
const firstTd = tr.querySelector('td');
|
||||||
if (!firstTd) return;
|
if (!firstTd) return;
|
||||||
|
|
||||||
const textMatch = firstTd.innerText.trim().match(/^15\d{6}$/);
|
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 aMatch = firstTd.querySelector('a') ? firstTd.querySelector('a').innerText.trim().match(/^15\d{6}$/) : null;
|
||||||
const ref = textMatch ? textMatch[0] : (aMatch ? aMatch[0] : null);
|
const ref = textMatch ? textMatch[0] : (aMatch ? aMatch[0] : null);
|
||||||
|
|
||||||
if (ref) {
|
if (ref) {
|
||||||
const hasLock = firstTd.querySelector('img[src*="candado.gif"]') !== null;
|
const hasLock = firstTd.querySelector('img[src*="candado.gif"]') !== null;
|
||||||
const hasEyes = firstTd.querySelector('img[src*="ojos.gif"]') !== null;
|
const hasEyes = firstTd.querySelector('img[src*="ojos.gif"]') !== null;
|
||||||
@@ -331,7 +315,6 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
return results;
|
return results;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Sacamos solo los números para la escoba (syncAndArchive)
|
|
||||||
const refs = [...new Set(listaConIconos.map(item => item.ref))];
|
const refs = [...new Set(listaConIconos.map(item => item.ref))];
|
||||||
|
|
||||||
if (refs.length > 0) {
|
if (refs.length > 0) {
|
||||||
@@ -346,7 +329,7 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
|
|
||||||
const scrapData = await page.evaluate(() => {
|
const scrapData = await page.evaluate(() => {
|
||||||
const d = {};
|
const d = {};
|
||||||
let isUrgent = "No"; // <-- EMPEZAMOS ASUMIENDO QUE NO ES URGENTE
|
let isUrgent = "No";
|
||||||
|
|
||||||
const rows = Array.from(document.querySelectorAll('tr'));
|
const rows = Array.from(document.querySelectorAll('tr'));
|
||||||
rows.forEach(r => {
|
rows.forEach(r => {
|
||||||
@@ -359,19 +342,17 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
const inputEl = cells[1].querySelector('textarea');
|
const inputEl = cells[1].querySelector('textarea');
|
||||||
const txt = inputEl ? inputEl.value : (cells[1].innerText || "");
|
const txt = inputEl ? inputEl.value : (cells[1].innerText || "");
|
||||||
|
|
||||||
// 🔥 DETECTOR DE URGENCIA ANTES DE LIMPIAR 🔥
|
// 🔥 DETECTOR DE URGENCIA 🔥
|
||||||
const txtLower = txt.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
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")) {
|
if (txtLower.includes("atencion presencial urgencias") || txtLower.includes("atencion de la urgencia") || txtLower.includes("urgente")) {
|
||||||
isUrgent = "Sí"; // Si pilla la urgencia, la guarda.
|
isUrgent = "Sí";
|
||||||
}
|
}
|
||||||
|
|
||||||
const cleanDesc = txt.split('\n').filter(line => {
|
const cleanDesc = txt.split('\n').filter(line => {
|
||||||
const l = line.toUpperCase();
|
const l = line.toUpperCase();
|
||||||
// Quitamos los filtros destructivos que borraban el "Cambio de estado"
|
|
||||||
return !["ESTADO ASIGNADO", "SMS NO ENVIADO", "CONTACTO CON PROF", "0000"].some(b => l.includes(b));
|
return !["ESTADO ASIGNADO", "SMS NO ENVIADO", "CONTACTO CON PROF", "0000"].some(b => l.includes(b));
|
||||||
}).join('\n').trim();
|
}).join('\n').trim();
|
||||||
// Aplicamos el descodificador a la avería
|
d['Descripción'] = cleanDesc;
|
||||||
d['Descripción'] = cleanDesc; // Se limpiará luego abajo
|
|
||||||
} else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) {
|
} else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) {
|
||||||
d[k] = v;
|
d[k] = v;
|
||||||
}
|
}
|
||||||
@@ -385,24 +366,19 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE");
|
d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE");
|
||||||
d['Nombre Cliente'] = d['CLIENTE'] || "";
|
d['Nombre Cliente'] = d['CLIENTE'] || "";
|
||||||
d['Dirección'] = d['DOMICILIO'] || "";
|
d['Dirección'] = d['DOMICILIO'] || "";
|
||||||
|
|
||||||
// INYECTAMOS LA URGENCIA AL ESTILO MULTIASISTENCIA
|
|
||||||
d['Urgente'] = isUrgent;
|
d['Urgente'] = isUrgent;
|
||||||
|
|
||||||
return d;
|
return d;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (scrapData && scrapData['Nombre Cliente']) {
|
if (scrapData && scrapData['Nombre Cliente']) {
|
||||||
// 🪄 Arreglamos la codificación alienígena de HomeServe EN TODOS LOS CAMPOS IMPORTANTES
|
// 🪄 Arreglamos codificación y nombres de HomeServe
|
||||||
scrapData['Nombre Cliente'] = arreglarCodificacion(scrapData['Nombre Cliente']);
|
scrapData['Nombre Cliente'] = arreglarNombre(arreglarCodificacion(scrapData['Nombre Cliente']));
|
||||||
scrapData['Dirección'] = arreglarCodificacion(scrapData['Dirección']);
|
scrapData['Dirección'] = arreglarCodificacion(scrapData['Dirección']);
|
||||||
scrapData['Población'] = arreglarCodificacion(scrapData['Población']);
|
scrapData['Población'] = arreglarCodificacion(scrapData['Población']);
|
||||||
scrapData['Descripción'] = arreglarCodificacion(scrapData['Descripción']);
|
scrapData['Descripción'] = arreglarCodificacion(scrapData['Descripción']);
|
||||||
|
|
||||||
// 🪄 Arreglamos el formato de "Apellidos, Nombre" (Solo en HomeServe)
|
// 🛑 INYECTAMOS ICONOS CAZADOS
|
||||||
scrapData['Nombre Cliente'] = arreglarNombre(scrapData['Nombre Cliente']);
|
|
||||||
|
|
||||||
// 🛑 NUEVO: Le inyectamos los iconos que cazamos antes en la lista
|
|
||||||
const iconInfo = listaConIconos.find(item => item.ref === ref);
|
const iconInfo = listaConIconos.find(item => item.ref === ref);
|
||||||
if (iconInfo) {
|
if (iconInfo) {
|
||||||
scrapData['has_lock'] = iconInfo.hasLock;
|
scrapData['has_lock'] = iconInfo.hasLock;
|
||||||
@@ -423,14 +399,12 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
// 1. Buscamos TODOS los expedientes que están vivos (en el buzón o en el panel)
|
|
||||||
const { rows: dbServices } = await client.query(
|
const { rows: dbServices } = await client.query(
|
||||||
`SELECT id, service_ref, assigned_to, raw_data FROM scraped_services
|
`SELECT id, service_ref, assigned_to, raw_data FROM scraped_services
|
||||||
WHERE owner_id = $1 AND provider = $2 AND status IN ('pending', 'imported')`,
|
WHERE owner_id = $1 AND provider = $2 AND status IN ('pending', 'imported')`,
|
||||||
[ownerId, provider]
|
[ownerId, provider]
|
||||||
);
|
);
|
||||||
|
|
||||||
// 2. Filtramos cuáles han desaparecido de la web oficial
|
|
||||||
const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref));
|
const missingServices = dbServices.filter(s => !currentWebRefs.includes(s.service_ref));
|
||||||
const refsToArchive = missingServices.map(s => s.service_ref);
|
const refsToArchive = missingServices.map(s => s.service_ref);
|
||||||
|
|
||||||
@@ -438,9 +412,8 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
|||||||
|
|
||||||
if (refsToArchive.length > 0) {
|
if (refsToArchive.length > 0) {
|
||||||
console.log(`🚨 ATENCIÓN: Se van a ARCHIVAR ${refsToArchive.length} expedientes porque NO están en la web:`);
|
console.log(`🚨 ATENCIÓN: Se van a ARCHIVAR ${refsToArchive.length} expedientes porque NO están en la web:`);
|
||||||
console.log(`💀 LISTA DE CONDENADOS:`, refsToArchive.join(', '));
|
console.log(`💀 LISTA:`, refsToArchive.join(', '));
|
||||||
|
|
||||||
// 3. Los archivamos (los quitamos del buzón)
|
|
||||||
await client.query(
|
await client.query(
|
||||||
`UPDATE scraped_services
|
`UPDATE scraped_services
|
||||||
SET status = 'archived'
|
SET status = 'archived'
|
||||||
@@ -451,48 +424,38 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// ========================================================
|
// ========================================================
|
||||||
// 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Para la App del Técnico)
|
// 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Apagado para Multiasistencia)
|
||||||
// ========================================================
|
// ========================================================
|
||||||
// Buscamos el ID del estado "Anulado" de este propietario
|
|
||||||
const statusQ = await client.query("SELECT id FROM service_statuses WHERE owner_id = $1 AND name ILIKE '%anulado%' LIMIT 1", [ownerId]);
|
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;
|
const idAnulado = statusQ.rowCount > 0 ? statusQ.rows[0].id : null;
|
||||||
|
|
||||||
// 🛑 PARCHE: Desactivamos el escudo anti-viajes para Multiasistencia hasta que mapeemos bien sus 200 estados raros.
|
|
||||||
if (idAnulado && provider !== 'multiasistencia') {
|
if (idAnulado && provider !== 'multiasistencia') {
|
||||||
for (const svc of missingServices) {
|
for (const svc of missingServices) {
|
||||||
// Si el expediente estaba asignado a un técnico...
|
|
||||||
if (svc.assigned_to) {
|
if (svc.assigned_to) {
|
||||||
const raw = svc.raw_data || {};
|
const raw = svc.raw_data || {};
|
||||||
const currentStatusId = String(raw.status_operativo || "");
|
const currentStatusId = String(raw.status_operativo || "");
|
||||||
|
|
||||||
// ...y su estado actual no era ya "Anulado"
|
|
||||||
if (currentStatusId !== String(idAnulado)) {
|
if (currentStatusId !== String(idAnulado)) {
|
||||||
|
|
||||||
// Comprobamos si el técnico ya lo había "Finalizado" (para no pisarle el trabajo hecho)
|
|
||||||
let isFinal = false;
|
let isFinal = false;
|
||||||
if (currentStatusId) {
|
if (currentStatusId) {
|
||||||
const checkStatusQ = await client.query("SELECT is_final FROM service_statuses WHERE id = $1", [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;
|
isFinal = checkStatusQ.rowCount > 0 ? checkStatusQ.rows[0].is_final : false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si NO estaba finalizado, procedemos a ANULARLO automáticamente
|
|
||||||
if (!isFinal) {
|
if (!isFinal) {
|
||||||
raw.status_operativo = idAnulado;
|
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("UPDATE scraped_services SET raw_data = $1 WHERE id = $2", [JSON.stringify(raw), svc.id]);
|
||||||
|
|
||||||
// Dejamos huella en la trazabilidad para que sepas por qué se anuló
|
|
||||||
await client.query(
|
await client.query(
|
||||||
"INSERT INTO scraped_service_logs (scraped_id, user_name, action, details) VALUES ($1, $2, $3, $4)",
|
"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 cancelado/retirado el expediente. Se pasa a estado Anulado para avisar al técnico."]
|
[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 de viajar en balde).`);
|
console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado).`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// ========================================================
|
|
||||||
|
|
||||||
console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`);
|
console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`);
|
||||||
}
|
}
|
||||||
@@ -506,7 +469,6 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) {
|
|||||||
async function saveServiceToDB(ownerId, provider, ref, data) {
|
async function saveServiceToDB(ownerId, provider, ref, data) {
|
||||||
console.log(`💾 Guardando/Actualizando ${provider.toUpperCase()} ${ref}...`);
|
console.log(`💾 Guardando/Actualizando ${provider.toUpperCase()} ${ref}...`);
|
||||||
|
|
||||||
// Aquí está la solución al problema del tilde ("sí" vs "si") que te comenté antes
|
|
||||||
const isUrgent = (data['Urgente'] && (data['Urgente'].toLowerCase().trim() === 'sí' || data['Urgente'].toLowerCase().trim() === 'si')) ? true : false;
|
const isUrgent = (data['Urgente'] && (data['Urgente'].toLowerCase().trim() === 'sí' || data['Urgente'].toLowerCase().trim() === 'si')) ? true : false;
|
||||||
|
|
||||||
await pool.query(`
|
await pool.query(`
|
||||||
@@ -514,7 +476,6 @@ async function saveServiceToDB(ownerId, provider, ref, data) {
|
|||||||
VALUES ($1, $2, $3, $4, 'pending', $5)
|
VALUES ($1, $2, $3, $4, 'pending', $5)
|
||||||
ON CONFLICT (owner_id, provider, service_ref)
|
ON CONFLICT (owner_id, provider, service_ref)
|
||||||
DO UPDATE SET
|
DO UPDATE SET
|
||||||
-- 🛡️ EL ESCUDO: Fusiona todo, pero si ya había un gremio guardado, lo blinda para que el robot no lo pise
|
|
||||||
raw_data = (scraped_services.raw_data || EXCLUDED.raw_data) ||
|
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')),
|
jsonb_build_object('guild_id', COALESCE(scraped_services.raw_data->'guild_id', EXCLUDED.raw_data->'guild_id')),
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user