0003 - mae_plantillas_mensaje
"""mae_plantillas_mensaje
Revision ID: 0003
Revises: 0002
Create Date: 2026-09-21
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "0003"
down_revision: str | None = "0002"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.execute(
"""
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)';
"""
)
def downgrade() -> None:
op.execute("DROP TABLE IF EXISTS core.notificaciones.mae_plantillas_mensaje;")