Especificación Técnica: trx_mensajes¶
Esquema: core.notificaciones
Base de Datos: core
Servicio: svc-notificaciones
Tabla Legacy Origen: c038t_correo
Propósito: Cola y registro de mensajes enviados: cada fila es un envío a un destinatario con su estado, intentos y trazabilidad.
1. Justificación y Mejoras de Arquitectura¶
- Evolución del legado
c038t_correo:tx_detalle varchar(300000)se reemplaza porcuerpo TEXT(el varchar de 300 mil no limita nada) yco_documento bytease sustituye por la referenciadocumento_idacore.identidad.mae_documentos(el binario vive en Object Storage). in_enviado character(1)(tres valores en un char) se reemplaza por el tipocore.notificaciones.estado_mensaje(pendiente,enviando,enviado,fallido,cancelado): distingue "fallido" de "pendiente" de forma tipada.plantilla_idopcional: la plantilla se "congela" en el cuerpo al momento del envío; la FK solo garantiza que la plantilla exista en la misma empresa.usuario_ides referencia lógica asvc-identidad, sin FK (el usuario no vive en este esquema).intentosconCHECK (intentos >= 0)y consistenciaCHECK ((estado='enviado') = (fecha_enviado IS NOT NULL)).- Índice parcial de cola
(fecha_programada) WHERE estado IN ('pendiente','enviando') AND deleted_at IS NULLpara el barrido eficiente de envíos pendientes.
2. Definiciones de Implementación¶
Table core.notificaciones.trx_mensajes {
id uuid [pk, default: `gen_random_uuid()`]
empresa_id bigint [not null]
canal_id uuid [not null, ref: > cat_canales.id]
plantilla_id uuid
destinatario text [not null]
usuario_id uuid [note: 'Referencia lógica a core.identidad.mae_usuarios (sin FK)']
asunto text
cuerpo text [not null]
documento_id uuid [note: 'Referencia a core.identidad.mae_documentos via FK sobre la PK (id)']
estado core.notificaciones.estado_mensaje [not null, default: `'pendiente'`, note: 'Valores enum: pendiente, enviando, enviado, fallido, cancelado']
intentos smallint [not null, default: `0`]
fecha_programada timestamptz [not null, default: `now()`]
fecha_enviado timestamptz
error_ultimo text
servicio_origen text
referencia_externa_id bigint
// Auditoría General
created_at timestamptz [not null, default: `now()`, note: 'Fecha de creación']
updated_at timestamptz [not null, default: `now()`, note: 'Fecha de última actualización']
deleted_at timestamptz [note: 'Fecha de eliminación lógica']
created_by uuid [note: 'Usuario creador']
updated_by uuid [note: 'Usuario modificador']
Indexes {
(empresa_id, id) [unique, name: 'uq_trx_mensajes_empresa_id']
(fecha_programada) [name: 'ix_trx_mensajes_cola', note: 'WHERE estado IN (pendiente, enviando) AND deleted_at IS NULL']
(empresa_id) [name: 'ix_trx_mensajes_empresa_id']
(servicio_origen, referencia_externa_id) [name: 'ix_trx_mensajes_referencia_externa']
(canal_id) [name: 'ix_trx_mensajes_canal_id']
(plantilla_id) [name: 'ix_trx_mensajes_plantilla_id']
(documento_id) [name: 'ix_trx_mensajes_documento_id']
}
Note: 'CHECK intentos >= 0; CHECK (estado = enviado) = (fecha_enviado IS NOT NULL)'
}
Ref: mae_plantillas_mensaje.(empresa_id, id) < trx_mensajes.(empresa_id, plantilla_id)
Ref: core.identidad.mae_documentos.id < trx_mensajes.documento_id
-- Tipo enum previo: CREATE TYPE core.notificaciones.estado_mensaje AS ENUM
-- ('pendiente','enviando','enviado','fallido','cancelado');
CREATE TABLE IF NOT EXISTS core.notificaciones.trx_mensajes (
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
empresa_id BIGINT NOT NULL,
canal_id UUID NOT NULL,
plantilla_id UUID,
destinatario TEXT NOT NULL,
usuario_id UUID,
asunto TEXT,
cuerpo TEXT NOT NULL,
documento_id UUID,
estado core.notificaciones.estado_mensaje NOT NULL DEFAULT 'pendiente',
intentos SMALLINT NOT NULL DEFAULT 0,
fecha_programada TIMESTAMPTZ NOT NULL DEFAULT now(),
fecha_enviado TIMESTAMPTZ,
error_ultimo TEXT,
servicio_origen TEXT,
referencia_externa_id BIGINT,
-- Auditoría General
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ,
created_by UUID,
updated_by UUID,
CONSTRAINT uq_trx_mensajes_empresa_id UNIQUE (empresa_id, id),
CONSTRAINT fk_trx_mensajes_canal FOREIGN KEY (canal_id) REFERENCES core.notificaciones.cat_canales (id),
CONSTRAINT fk_trx_mensajes_plantilla
FOREIGN KEY (empresa_id, plantilla_id)
REFERENCES core.notificaciones.mae_plantillas_mensaje (empresa_id, id),
CONSTRAINT fk_trx_mensajes_documento FOREIGN KEY (documento_id) REFERENCES core.identidad.mae_documentos (id),
CONSTRAINT ck_trx_mensajes_intentos CHECK (intentos >= 0),
CONSTRAINT ck_trx_mensajes_enviado CHECK ((estado = 'enviado') = (fecha_enviado IS NOT NULL))
);
CREATE INDEX IF NOT EXISTS ix_trx_mensajes_cola ON core.notificaciones.trx_mensajes (fecha_programada) WHERE estado IN ('pendiente','enviando') AND deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS ix_trx_mensajes_empresa_id ON core.notificaciones.trx_mensajes (empresa_id);
CREATE INDEX IF NOT EXISTS ix_trx_mensajes_referencia_externa ON core.notificaciones.trx_mensajes (servicio_origen, referencia_externa_id);
CREATE INDEX IF NOT EXISTS ix_trx_mensajes_canal_id ON core.notificaciones.trx_mensajes (canal_id);
CREATE INDEX IF NOT EXISTS ix_trx_mensajes_plantilla_id ON core.notificaciones.trx_mensajes (plantilla_id);
CREATE INDEX IF NOT EXISTS ix_trx_mensajes_documento_id ON core.notificaciones.trx_mensajes (documento_id);
-- Comentarios
COMMENT ON COLUMN core.notificaciones.trx_mensajes.empresa_id IS 'Empresa propietaria del mensaje';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.canal_id IS 'Canal de notificación (catálogo global)';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.plantilla_id IS 'Plantilla usada (opcional); el cuerpo se congela al enviar';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.destinatario IS 'Destinatario del mensaje (según canal)';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.usuario_id IS 'Usuario destinatario (referencia lógica a svc-identidad)';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.cuerpo IS 'Cuerpo del mensaje';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.documento_id IS 'Documento adjunto (referencia al maestro de documentos del núcleo, core.identidad.mae_documentos)';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.estado IS 'Estado del envío (enum estado_mensaje)';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.intentos IS 'Número de intentos de envío';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.fecha_programada IS 'Fecha programada del envío';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.fecha_enviado IS 'Fecha real de envío';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.error_ultimo IS 'Último error reportado por el proveedor';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.servicio_origen IS 'Servicio que originó el mensaje';
COMMENT ON COLUMN core.notificaciones.trx_mensajes.referencia_externa_id IS 'Identificador de referencia del sistema originador';