From c9c5f5891a58a9b35eda74b2ce0d42ca8b1dd037 Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 22 Mar 2026 22:53:03 +0000 Subject: [PATCH] Actualizar robot.js --- robot.js | 234 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 160 insertions(+), 74 deletions(-) diff --git a/robot.js b/robot.js index e36a340..b6b8bf8 100644 --- a/robot.js +++ b/robot.js @@ -8,7 +8,7 @@ const pool = new pg.Pool({ connectionString: DATABASE_URL, ssl: false }); const HEADLESS = true; // ========================================== -// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (DINÁMICO) +// 🧠 MOTOR DE CLASIFICACIÓN DE GREMIOS PRO (AHORA DINÁMICO) // ========================================== function normalizarTexto(texto) { @@ -16,14 +16,16 @@ function normalizarTexto(texto) { return texto.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, ""); } -// 🛠️ El "Gira-Nombres" EXCLUSIVO para HomeServe +// 🛠️ NUEVO: El "Gira-Nombres" EXCLUSIVO para HomeServe function arreglarNombre(nombreRaw) { if (!nombreRaw) return ""; let nombreLimpio = nombreRaw.trim(); + // Si detectamos que tiene una coma... if (nombreLimpio.includes(',')) { let partes = nombreLimpio.split(','); let apellidos = partes[0].trim(); let nombre = partes[1].trim(); + // Le damos la vuelta y quitamos espacios sobrantes nombreLimpio = `${nombre} ${apellidos}`.replace(/\s+/g, ' '); } return nombreLimpio; @@ -32,23 +34,31 @@ function arreglarNombre(nombreRaw) { // 🛡️ DESCODIFICADOR UNIVERSAL PARA HOMESERVE (Arregla los +, Ó, Ñ, etc.) function arreglarCodificacion(texto) { if (!texto) return ""; - let limpio = texto.replace(/\+/g, ' '); + let limpio = texto.replace(/\+/g, ' '); // Primero cambiamos los + por espacios try { + // Truco clásico de Javascript para transformar ISO a UTF-8 limpio = decodeURIComponent(escape(limpio)); - } catch(e) {} + } catch(e) { + // Si no se puede, lo dejamos con los espacios arreglados + } return limpio.trim(); } +// NUEVO: La función ahora lee las keywords directamente del JSON de la base de datos function clasificarGremio(descripcion, gremiosActivosDB) { if (!descripcion || gremiosActivosDB.length === 0) return null; const descNormalizada = normalizarTexto(descripcion); 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 : []; - 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))); + if (coincide) { console.log(` 🧠 Gremio detectado automáticamente: ${gremio.name} (ID: ${gremio.id})`); return gremio.id; @@ -57,15 +67,17 @@ function clasificarGremio(descripcion, gremiosActivosDB) { return null; } +// Función auxiliar para reintentar la navegación si hay fallo de red async function gotoWithRetry(page, url, retries = 3) { for (let i = 0; i < retries; i++) { try { + // Usamos domcontentloaded para que no se quede colgado esperando imágenes o scripts pesados await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 }); - return; + return; // Si funciona, salimos de la función } catch (e) { - if (i === retries - 1) throw e; + if (i === retries - 1) throw e; // Si es el último intento, lanza el error console.log(`⚠️ Fallo de red detectado al ir a ${url}. Reintentando (${i + 1}/${retries})...`); - await page.waitForTimeout(3000); + await page.waitForTimeout(3000); // Esperamos 3 segundos antes de volver a intentar } } } @@ -75,6 +87,7 @@ async function main() { while (true) { const client = await pool.connect(); try { + // 1. CARGAMOS LOS GREMIOS ACTUALES (AHORA INCLUYE LAS PALABRAS CLAVE) const gremiosRes = await client.query("SELECT id, name, ia_keywords FROM guilds"); const gremiosDB = gremiosRes.rows; @@ -83,6 +96,7 @@ async function main() { 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; + -- 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 ALTER TABLE guilds ADD COLUMN ia_keywords JSONB DEFAULT '[]'; END IF; @@ -111,104 +125,151 @@ async function main() { } // ========================================== -// 🏥 MULTIASISTENCIA (PAGINACIÓN Y DOBLE RECARGA) +// 🏥 MULTIASISTENCIA (CON REINTENTOS ANTI-CAÍDAS) // ========================================== async function runMultiasistencia(ownerId, user, pass, gremiosDB) { - const browser = await chromium.launch({ headless: HEADLESS, args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu'] }); + const browser = await chromium.launch({ + headless: HEADLESS, + args: [ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] + }); const context = await browser.newContext(); const page = await context.newPage(); try { - console.log("🌍 [Multi] Iniciando sesión..."); + // INICIO DE SESIÓN CON REINTENTOS await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/acceso.php'); + await page.fill('input[name="usuario"]', user); await page.fill('input[type="password"]', pass); await page.click('input[type="submit"]'); await page.waitForTimeout(4000); + + // ENTRAR AL BUZÓN CON REINTENTOS await gotoWithRetry(page, 'https://web.multiasistencia.com/w3multi/frepasos_new.php?refresh=1'); + await page.waitForTimeout(3000); - // 🔄 TU TRUCO MANUAL: Recarga -> Espera 3s -> Recarga -> Espera 5s - console.log("🔄 [Multi] Aplicando tu doble recarga manual..."); - await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); }); - await page.waitForTimeout(3000); // Primera espera de 3 seg. - await page.evaluate(() => { if (typeof refrescar === 'function') refrescar(); }); - await page.waitForTimeout(5000); // Segunda espera de 5 seg. para ver la tabla + console.log("🔄 [Multi] Forzando recarga segura mediante script interno..."); + try { + await page.evaluate(() => { + if (typeof refrescar === 'function') refrescar(); + }); + await page.waitForLoadState('networkidle'); + await page.waitForTimeout(3000); + } catch (e) {} + // --- BUCLE DE PAGINACIÓN --- 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}...`); - await page.waitForSelector('a[href*="reparacion="]', { timeout: 8000 }).catch(() => {}); - await page.waitForTimeout(1000); + console.log(`📄 [Multi] Escaneando página ${paginaActual}...`); - const refs = await page.evaluate(() => { + 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 unicos = [...new Set(refs)]; - console.log(` 👉 Encontrados ${unicos.length} expedientes únicos.`); - unicos.forEach(r => todosExpedientes.add(r)); + expedientesPagina.forEach(ref => todosExpedientes.add(ref)); - // CLICK EN SIGUIENTE - const hasNext = await page.evaluate(() => { - const btn = Array.from(document.querySelectorAll('a.lnkheader')).find(a => a.innerText.toLowerCase().includes('siguiente')); - if (btn) { btn.click(); return true; } - return false; + // 🛑 NUEVO: Buscamos el botón de siguiente + const hasNextPage = await page.evaluate(() => { + const links = Array.from(document.querySelectorAll('a.lnkheader')); + return links.some(a => a.innerText.trim() === 'Página siguiente'); }); - if (hasNext && unicos.length > 0) { - console.log(" ➡️ Pulsado 'Siguiente'. Esperando 6 segundos a que cargue..."); - await page.waitForTimeout(6000); + 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.waitForTimeout(3000); paginaActual++; - if(paginaActual > 20) break; + if(paginaActual > 15) { + console.log("⚠️ [Multi] Límite de 15 páginas alcanzado por seguridad."); + break; + } } else { - console.log("🛑 [Multi] Fin de lista."); - break; + console.log("🛑 [Multi] No hay más páginas."); + break; } } - const listaFinal = Array.from(todosExpedientes); - console.log(`✅ [Multi] TOTAL: ${listaFinal.length}`); + const expedientes = Array.from(todosExpedientes); + console.log(`✅ [Multi] Total expedientes detectados: ${expedientes.length}`); - if (listaFinal.length > 5 || paginaActual === 1) { - await syncAndArchive(ownerId, 'multiasistencia', listaFinal); + if (expedientes.length > 0) { + await syncAndArchive(ownerId, 'multiasistencia', expedientes); } - for (const ref of listaFinal) { + for (const ref of expedientes) { 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 findByCab = (t) => { - const tds = Array.from(document.querySelectorAll('.tcab')); - const idx = tds.findIndex(el => el.innerText.includes(t)); - return idx !== -1 ? clean(tds[idx].nextElementSibling.innerText) : null; + 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; }; - const desc = Array.from(document.querySelectorAll('td.tcab')).find(td => td.innerText.includes("Descripción de la Reparación")); - if (!document.body.innerText.includes("Nombre Cliente")) return 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); + + // 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 rawCPField = findByCab("Distrito Postal") || ""; + const cpMatch = rawCPField.match(/\b\d{5}\b/); + const cpOnly = cpMatch ? cpMatch[0] : ""; + const popOnly = rawCPField.replace(cpOnly, '').replace('-', '').trim(); + + // 📞 EXTRAER TELÉFONO REAL (Evita coger el de la oficina) + 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, ''); + } + // Fallback por si acaso falla, usamos el que tenías antes + 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": (findByCab("Distrito Postal") || "").replace(/\d{5}/, '').trim(), - "Código Postal": (findByCab("Distrito Postal") || "").match(/\d{5}/)?.[0] || "", + "Población": popOnly, + "Código Postal": cpOnly, "Compañía": "MULTI - " + (findByCab("Procedencia") || "MULTIASISTENCIA"), - "Descripción": desc ? clean(desc.nextElementSibling.innerText) : "", - "Teléfono": (document.body.innerText.match(/[6789]\d{8}/) || [])[0] || "", - "Estado": findByCab("Estado") || "", + "Descripción": cleanDesc, + "Teléfono": telefonoReal, + "Estado": findByCab("Estado") || "", // 🛑 AÑADIDO EL ESTADO AQUÍ "Urgente": findByCab("Urgente") || "No" }; }); - if (scrapData && scrapData['Nombre Cliente']) break; - } catch(e) {} + if (scrapData && scrapData['Nombre Cliente']) break; + } catch (e) { continue; } } + if (scrapData && scrapData['Nombre Cliente']) { - scrapData['guild_id'] = clasificarGremio(scrapData['Descripción'], gremiosDB); + const idGremioDetectado = clasificarGremio(scrapData['Descripción'], gremiosDB); + if (idGremioDetectado) { + scrapData['guild_id'] = idGremioDetectado; + } await saveServiceToDB(ownerId, 'multiasistencia', ref, scrapData); } } @@ -220,12 +281,17 @@ async function runMultiasistencia(ownerId, user, pass, gremiosDB) { } // ========================================== -// 🧹 HOMESERVE (MEJORADO CON DECODIFICADOR, ICONOS Y URGENCIA) +// 🧹 HOMESERVE (ROBOT MEJORADO Y DETECTOR DE URGENCIAS) // ========================================== 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'] + args: [ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-dev-shm-usage', + '--disable-gpu' + ] }); const page = await browser.newPage(); try { @@ -242,16 +308,19 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { await gotoWithRetry(page, 'https://www.clientes.homeserve.es/cgi-bin/fccgi.exe?w3exec=lista_servicios_total'); await page.waitForTimeout(3000); - // 🛑 EXTRAEMOS REFS E ICONOS + // 🛑 NUEVO: Ahora extraemos la referencia Y LOS ICONOS de la misma pasada 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; @@ -261,6 +330,7 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { return results; }); + // Sacamos solo los números para la escoba (syncAndArchive) const refs = [...new Set(listaConIconos.map(item => item.ref))]; if (refs.length > 0) { @@ -275,7 +345,7 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { const scrapData = await page.evaluate(() => { const d = {}; - let isUrgent = "No"; + let isUrgent = "No"; // <-- EMPEZAMOS ASUMIENDO QUE NO ES URGENTE const rows = Array.from(document.querySelectorAll('tr')); rows.forEach(r => { @@ -288,17 +358,19 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { const inputEl = cells[1].querySelector('textarea'); const txt = inputEl ? inputEl.value : (cells[1].innerText || ""); - // 🔥 DETECTOR DE URGENCIA 🔥 + // 🔥 DETECTOR DE URGENCIA ANTES DE LIMPIAR 🔥 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í"; + isUrgent = "Sí"; // Si pilla la urgencia, la guarda. } const cleanDesc = txt.split('\n').filter(line => { 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)); }).join('\n').trim(); - d['Descripción'] = cleanDesc; + // Aplicamos el descodificador a la avería + d['Descripción'] = cleanDesc; // Se limpiará luego abajo } else if (k.length > 1 && v.length > 0 && !k.includes("MENU")) { d[k] = v; } @@ -312,19 +384,24 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { d['Compañía'] = "HOME - " + (d['COMPAÑIA'] || "HOMESERVE"); d['Nombre Cliente'] = d['CLIENTE'] || ""; d['Dirección'] = d['DOMICILIO'] || ""; + + // INYECTAMOS LA URGENCIA AL ESTILO MULTIASISTENCIA 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'])); + // 🪄 Arreglamos la codificación alienígena de HomeServe EN TODOS LOS CAMPOS IMPORTANTES + scrapData['Nombre Cliente'] = 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 + // 🪄 Arreglamos el formato de "Apellidos, Nombre" (Solo en HomeServe) + 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); if (iconInfo) { scrapData['has_lock'] = iconInfo.hasLock; @@ -345,21 +422,19 @@ async function runHomeserve(ownerId, user, pass, gremiosDB) { async function syncAndArchive(ownerId, provider, currentWebRefs) { const client = await pool.connect(); try { + // 1. Buscamos TODOS los expedientes que están vivos (en el buzón o en el panel) 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] ); + // 2. Filtramos cuáles han desaparecido de la web oficial 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(', ')); - + // 3. Los archivamos (los quitamos del buzón) await client.query( `UPDATE scraped_services SET status = 'archived' @@ -370,38 +445,47 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) { ); // ======================================================== - // 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Apagado para Multiasistencia) + // 🛡️ EL ESCUDO ANTI-VIAJES EN BALDE (Para la App del Técnico) // ======================================================== + // 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 idAnulado = statusQ.rowCount > 0 ? statusQ.rows[0].id : null; - if (idAnulado && provider !== 'multiasistencia') { + if (idAnulado) { for (const svc of missingServices) { + // Si el expediente estaba asignado a un técnico... if (svc.assigned_to) { const raw = svc.raw_data || {}; const currentStatusId = String(raw.status_operativo || ""); + // ...y su estado actual no era ya "Anulado" if (currentStatusId !== String(idAnulado)) { + + // Comprobamos si el técnico ya lo había "Finalizado" (para no pisarle el trabajo hecho) 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; } + // Si NO estaba finalizado, procedemos a ANULARLO automáticamente if (!isFinal) { raw.status_operativo = idAnulado; + 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( "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."] + [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."] ); - console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado).`); + console.log(`🛡️ [ESCUDO] Expediente ${svc.service_ref} anulado automáticamente (Técnico salvado de viajar en balde).`); } } } } } + // ======================================================== console.log(`📦 [${provider.toUpperCase()}] Archivados ${refsToArchive.length} expedientes desaparecidos.`); } @@ -415,6 +499,7 @@ async function syncAndArchive(ownerId, provider, currentWebRefs) { async function saveServiceToDB(ownerId, provider, ref, data) { 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; await pool.query(` @@ -422,6 +507,7 @@ async function saveServiceToDB(ownerId, provider, ref, data) { VALUES ($1, $2, $3, $4, 'pending', $5) ON CONFLICT (owner_id, provider, service_ref) 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) || jsonb_build_object('guild_id', COALESCE(scraped_services.raw_data->'guild_id', EXCLUDED.raw_data->'guild_id')),