Actualizar robot.js
This commit is contained in:
141
robot.js
141
robot.js
@@ -16,49 +16,35 @@ 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
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🛡️ 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 +53,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 +71,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 +79,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;
|
||||||
@@ -125,49 +107,37 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🏥 MULTIASISTENCIA (CON REINTENTOS ANTI-CAÍDAS)
|
// 🏥 MULTIASISTENCIA
|
||||||
// ==========================================
|
// ==========================================
|
||||||
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();
|
||||||
try {
|
try {
|
||||||
// INICIO DE SESIÓN CON REINTENTOS
|
|
||||||
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php');
|
await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php');
|
||||||
|
|
||||||
await page.fill('input[name="usuario"]', user);
|
await page.fill('input[name="usuario"]', user);
|
||||||
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);
|
||||||
|
|
||||||
// ENTRAR AL BUZÓN CON REINTENTOS
|
|
||||||
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(3000);
|
await page.waitForTimeout(3000);
|
||||||
|
|
||||||
console.log("🔄 [Multi] Forzando recarga segura mediante script interno...");
|
console.log("🔄 [Multi] Forzando recarga segura...");
|
||||||
try {
|
try {
|
||||||
await page.evaluate(() => {
|
await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); });
|
||||||
if (typeof refrescar === 'function') refrescar();
|
|
||||||
});
|
|
||||||
await page.waitForLoadState('networkidle');
|
await page.waitForLoadState('networkidle');
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
|
|
||||||
// --- BUCLE DE PAGINACIÓN ---
|
|
||||||
let todosExpedientes = new Set();
|
let todosExpedientes = new Set();
|
||||||
let paginaActual = 1;
|
let paginaActual = 1;
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
console.log(`📄 [Multi] Escaneando página ${paginaActual}...`);
|
console.log(`📄 [Multi] Escaneando página ${paginaActual}...`);
|
||||||
|
|
||||||
const expedientesPagina = await page.evaluate(() => {
|
const expedientesPagina = await page.evaluate(() => {
|
||||||
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
const links = Array.from(document.querySelectorAll('a[href*="reparacion="]'));
|
||||||
return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean);
|
return links.map(a => a.href.match(/reparacion=(\d+)/)?.[1]).filter(Boolean);
|
||||||
@@ -175,19 +145,17 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
|
|
||||||
expedientesPagina.forEach(ref => todosExpedientes.add(ref));
|
expedientesPagina.forEach(ref => todosExpedientes.add(ref));
|
||||||
|
|
||||||
// 🛑 NUEVO: Buscamos el botón de siguiente
|
|
||||||
const hasNextPage = await page.evaluate(() => {
|
const hasNextPage = await page.evaluate(() => {
|
||||||
const links = Array.from(document.querySelectorAll('a.lnkheader'));
|
const links = Array.from(document.querySelectorAll('a.lnkheader'));
|
||||||
return links.some(a => a.innerText.trim() === 'Página siguiente');
|
return links.some(a => a.innerText.trim() === 'Página siguiente');
|
||||||
});
|
});
|
||||||
|
|
||||||
if (hasNextPage) {
|
if (hasNextPage) {
|
||||||
// 🛑 NUEVO: Pulsamos usando el motor de Playwright, simulando click humano
|
|
||||||
await page.locator('a.lnkheader:has-text("Página siguiente")').first().click();
|
await page.locator('a.lnkheader:has-text("Página siguiente")').first().click();
|
||||||
await page.waitForTimeout(3000);
|
await page.waitForTimeout(3000);
|
||||||
paginaActual++;
|
paginaActual++;
|
||||||
if(paginaActual > 15) {
|
if(paginaActual > 15) {
|
||||||
console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad.");
|
console.log("⚠️ [Multi] Límite de páginas alcanzado.");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -226,16 +194,12 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
const descHeader = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación"));
|
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);
|
if (descHeader && descHeader.nextElementSibling) rawDesc = clean(descHeader.nextElementSibling.innerText);
|
||||||
|
|
||||||
// CORRECCIÓN: Borrado el recorte de fechas destructivo.
|
|
||||||
// Ahora le pasamos todo el bloque de texto completo a la IA para que no se pierdan palabras clave.
|
|
||||||
const cleanDesc = rawDesc;
|
const cleanDesc = rawDesc;
|
||||||
|
|
||||||
const rawCPField = findByCab("Distrito Postal") || "";
|
const rawCPField = findByCab("Distrito Postal") || "";
|
||||||
const cpMatch = rawCPField.match(/\b\d{5}\b/);
|
const cpMatch = rawCPField.match(/\b\d{5}\b/);
|
||||||
const cpOnly = cpMatch ? cpMatch[0] : "";
|
const cpOnly = cpMatch ? cpMatch[0] : "";
|
||||||
const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim();
|
const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim();
|
||||||
|
|
||||||
// 📞 EXTRAER TELÉFONO REAL (Evita coger el de la oficina)
|
|
||||||
let telefonoReal = "";
|
let telefonoReal = "";
|
||||||
const titulosDiv = Array.from(document.querySelectorAll('.subtitulo'));
|
const titulosDiv = Array.from(document.querySelectorAll('.subtitulo'));
|
||||||
const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono'));
|
const divTelefono = titulosDiv.find(div => div.innerText && div.innerText.includes('Teléfono'));
|
||||||
@@ -243,7 +207,6 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet');
|
const celdaNum = divTelefono.nextElementSibling.querySelector('.tdet');
|
||||||
if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, '');
|
if (celdaNum) telefonoReal = celdaNum.innerText.replace(/[^0-9]/g, '');
|
||||||
}
|
}
|
||||||
// Fallback por si acaso falla, usamos el que tenías antes
|
|
||||||
if (!telefonoReal || telefonoReal.length < 9) {
|
if (!telefonoReal || telefonoReal.length < 9) {
|
||||||
telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "";
|
telefonoReal = (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "";
|
||||||
}
|
}
|
||||||
@@ -257,7 +220,7 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
"Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"),
|
"Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"),
|
||||||
"Descripción": cleanDesc,
|
"Descripción": cleanDesc,
|
||||||
"Teléfono": telefonoReal,
|
"Teléfono": telefonoReal,
|
||||||
"Estado": findByCab("Estado") || "", // 🛑 AÑADIDO EL ESTADO AQUÍ
|
"Estado": findByCab("Estado") || "",
|
||||||
"Urgente": findByCab("Urgente") || "No"
|
"Urgente": findByCab("Urgente") || "No"
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -273,15 +236,12 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) {
|
|||||||
await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData);
|
await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) { console.error("❌ Error Multi:", e.message); }
|
||||||
console.error("❌ Error Multi:", e.message);
|
finally { await browser.close(); }
|
||||||
} finally {
|
|
||||||
await browser.close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 🧹 HOMESERVE (ROBOT MEJORADO + CAMUFLAJE ANTI-BOTS)
|
// 🧹 HOMESERVE (MODO CAMUFLAJE)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
||||||
const browser = await chromium.launch({
|
const browser = await chromium.launch({
|
||||||
@@ -291,11 +251,10 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
'--disable-setuid-sandbox',
|
'--disable-setuid-sandbox',
|
||||||
'--disable-dev-shm-usage',
|
'--disable-dev-shm-usage',
|
||||||
'--disable-gpu',
|
'--disable-gpu',
|
||||||
'--disable-blink-features=AutomationControlled' // 1. Oculta que es un bot automatizado
|
'--disable-blink-features=AutomationControlled'
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
// 2. Le ponemos el DNI de un Chrome normal en Windows 10
|
|
||||||
const context = await browser.newContext({
|
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',
|
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||||
viewport: { width: 1366, height: 768 },
|
viewport: { width: 1366, height: 768 },
|
||||||
@@ -304,7 +263,6 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
|
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
|
|
||||||
// 3. Borramos la variable chivata de Playwright antes de que cargue la web
|
|
||||||
await page.addInitScript(() => {
|
await page.addInitScript(() => {
|
||||||
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
|
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
|
||||||
});
|
});
|
||||||
@@ -448,17 +406,74 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) {
|
|||||||
await saveServiceToDB(ownerId, 'homeserve', ref, scrapData);
|
await saveServiceToDB(ownerId, 'homeserve', ref, scrapData);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) { console.error("❌ [HomeServe] Error:", e.message); }
|
||||||
console.error("❌ [HomeServe] Error:", e.message);
|
finally { await browser.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// 🛡️ FUNCIONES DE GUARDADO Y ARCHIVADO
|
||||||
|
// ==========================================
|
||||||
|
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);
|
||||||
|
|
||||||
|
if (refsToArchive.length > 0) {
|
||||||
|
await client.query(
|
||||||
|
`UPDATE scraped_services
|
||||||
|
SET status = 'archived'
|
||||||
|
WHERE owner_id = $1 AND provider = $2 AND service_ref = ANY($3)`,
|
||||||
|
[ownerId, provider, refsToArchive]
|
||||||
|
);
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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 cancelado/retirado el expediente. Se pasa a estado Anulado."]
|
||||||
|
);
|
||||||
|
console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`❌ Error archivando ${provider}:`, error.message);
|
||||||
} finally {
|
} finally {
|
||||||
await browser.close();
|
client.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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(`
|
||||||
@@ -466,10 +481,8 @@ 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')),
|
||||||
|
|
||||||
is_urgent = EXCLUDED.is_urgent,
|
is_urgent = EXCLUDED.is_urgent,
|
||||||
status = CASE
|
status = CASE
|
||||||
WHEN scraped_services.status = 'archived' THEN 'archived'
|
WHEN scraped_services.status = 'archived' THEN 'archived'
|
||||||
|
|||||||
Reference in New Issue
Block a user