Saltar a contenido

0007 - trx_mensajes

"""trx_mensajes

Revision ID: 0007
Revises: 0006
Create Date: 2026-09-21
"""
from typing import Sequence, Union

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "0007"
down_revision: str | None = "0006"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # El tipo enum core.notificaciones.estado_mensaje aparece comentado en la
    # spec (-- Tipo enum previo: CREATE TYPE ...). Siguiendo la convención del
    # repo, los ENUMs se gestionan en la capa de código y se persisten como
    # VARCHAR: aquí no se crea el tipo y la columna estado es VARCHAR.
    op.execute(
        """
        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 VARCHAR 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';
        """
    )


def downgrade() -> None:
    op.execute("DROP TABLE IF EXISTS core.notificaciones.trx_mensajes;")