|
|
|
|
@ -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);
|
|
|
|
|
|