From 58ac01cc73dba2a0719867ef288a2abd068b7f53 Mon Sep 17 00:00:00 2001 From: brobert Date: Mon, 20 Oct 2025 08:34:05 +0200 Subject: [PATCH] fix: asegurar que exista el usuario antes de upsertAlias y log de error Co-authored-by: aider (openrouter/openai/gpt-5) --- src/services/identity.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/services/identity.ts b/src/services/identity.ts index adf35b6..12369be 100644 --- a/src/services/identity.ts +++ b/src/services/identity.ts @@ -1,5 +1,5 @@ import type { Database } from 'bun:sqlite'; -import { db } from '../db'; +import { db, ensureUserExists } from '../db'; import { normalizeWhatsAppId } from '../utils/whatsapp'; import { Metrics } from './metrics'; @@ -16,6 +16,8 @@ export class IdentityService { const a = normalizeWhatsAppId(alias || ''); const u = normalizeWhatsAppId(userId || ''); if (!a || !u || a === u) return false; + // Asegurar que el user_id numérico exista para no violar la FK (user_aliases.user_id -> users.id) + try { ensureUserExists(u, this.dbInstance); } catch {} try { this.dbInstance.prepare(` INSERT INTO user_aliases (alias, user_id, source, created_at, updated_at) @@ -25,8 +27,14 @@ export class IdentityService { source = COALESCE(excluded.source, source), updated_at = excluded.updated_at `).run(a, u, source ?? null); - } catch { + } catch (e) { // Si la tabla no existe o hay error de DB, continuamos con la caché en memoria + try { Metrics.inc('identity_alias_upsert_errors_total'); } catch {} + try { + if (String(process.env.NODE_ENV || '').toLowerCase() !== 'test') { + console.warn('[IdentityService.upsertAlias] Falló persistir alias en DB (se mantiene en caché en memoria):', e); + } + } catch {} } // Actualizar siempre la caché en memoria para disponibilizar el alias inmediatamente this.inMemoryAliases.set(a, u);