Saltar a contenido

Especificación Técnica: mae_plantillas_mensaje

Esquema: core.notificaciones
Base de Datos: core
Servicio: svc-notificaciones
Tabla Legacy Origen: c038t_correo
Propósito: Plantillas de mensaje parametrizables por canal (asunto, cuerpo y variables) para reutilizar en los envíos de trx_mensajes.


1. Justificación y Mejoras de Arquitectura

  • Evolución del legado c038t_correo: el asunto y el cuerpo dejan de ser campos del envío y pasan a ser una plantilla reutilizable por canal y por empresa.
  • variables JSONB tipada con CHECK (jsonb_typeof(variables) = 'array') para declarar la lista de variables esperadas por la plantilla.
  • Tenencia por empresa con clave alterna uq_mae_plantillas_mensaje_empresa_id UNIQUE (empresa_id, id): las FKs hijas arrastran el empresa_id y el motor impide apuntar a la plantilla de otra empresa (RLS no protege las FKs).
  • Unique parcial UNIQUE (empresa_id, codigo) WHERE deleted_at IS NULL: un código de plantilla por empresa; reutilizable tras borrado lógico.

2. Definiciones de Implementación

Table core.notificaciones.mae_plantillas_mensaje {
    id         uuid      [pk, default: `gen_random_uuid()`]
    empresa_id bigint    [not null]
    canal_id   uuid      [not null, ref: > cat_canales.id]
    codigo     text      [not null]
    asunto     text
    cuerpo     text      [not null]
    variables  jsonb     [not null, default: `'[]'`, note: 'Lista de variables esperadas (JSON array)']

    // Auditoría General
    is_activo  boolean   [not null, default: `true`, note: 'Estado lógico del registro']
    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_mae_plantillas_mensaje_empresa_id']
        (empresa_id, codigo) [unique, name: 'uq_mae_plantillas_mensaje_empresa_codigo', note: 'WHERE deleted_at IS NULL']
        (empresa_id) [name: 'ix_mae_plantillas_mensaje_empresa_id']
        (canal_id) [name: 'ix_mae_plantillas_mensaje_canal_id']
    }

    Note: 'CHECK: jsonb_typeof(variables) = array'
}
CREATE TABLE IF NOT EXISTS core.notificaciones.mae_plantillas_mensaje (
    id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
    empresa_id BIGINT NOT NULL,
    canal_id UUID NOT NULL,
    codigo TEXT NOT NULL,
    asunto TEXT,
    cuerpo TEXT NOT NULL,
    variables JSONB NOT NULL DEFAULT '[]'::jsonb,

    -- Auditoría General
    is_activo BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    deleted_at TIMESTAMPTZ,
    created_by UUID,
    updated_by UUID,

    -- Llave alterna: las FK hijas arrastran el empresa_id y el motor impide
    -- apuntar a la plantilla de otra empresa (RLS no protege las FK).
    CONSTRAINT uq_mae_plantillas_mensaje_empresa_id UNIQUE (empresa_id, id),
    CONSTRAINT fk_mae_plantillas_mensaje_canal FOREIGN KEY (canal_id) REFERENCES core.notificaciones.cat_canales (id),
    CONSTRAINT ck_mae_plantillas_mensaje_variables CHECK (jsonb_typeof(variables) = 'array')
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_mae_plantillas_mensaje_empresa_codigo ON core.notificaciones.mae_plantillas_mensaje (empresa_id, codigo) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS ix_mae_plantillas_mensaje_empresa_id ON core.notificaciones.mae_plantillas_mensaje (empresa_id);
CREATE INDEX IF NOT EXISTS ix_mae_plantillas_mensaje_canal_id ON core.notificaciones.mae_plantillas_mensaje (canal_id);

-- Comentarios
COMMENT ON COLUMN core.notificaciones.mae_plantillas_mensaje.empresa_id IS 'Empresa propietaria de la plantilla';
COMMENT ON COLUMN core.notificaciones.mae_plantillas_mensaje.canal_id IS 'Canal de notificación (catálogo global)';
COMMENT ON COLUMN core.notificaciones.mae_plantillas_mensaje.codigo IS 'Código único de la plantilla por empresa';
COMMENT ON COLUMN core.notificaciones.mae_plantillas_mensaje.asunto IS 'Asunto del mensaje (opcional según canal)';
COMMENT ON COLUMN core.notificaciones.mae_plantillas_mensaje.cuerpo IS 'Cuerpo del mensaje';
COMMENT ON COLUMN core.notificaciones.mae_plantillas_mensaje.variables IS 'Lista de variables esperadas por la plantilla (JSON array)';