Saltar a contenido

Mensaje — core.notificaciones.trx_mensajes

Cola y registro de mensajes enviados: cada fila es un envío a un destinatario con su estado, intentos y trazabilidad.

"""``core.notificaciones.trx_mensajes``: cola y registro de mensajes enviados."""

import uuid
from datetime import datetime

from sqlalchemy import (
    BigInteger,
    CheckConstraint,
    ForeignKeyConstraint,
    Index,
    SmallInteger,
    String,
    Text,
    UniqueConstraint,
    text,
)
from sqlalchemy.dialects.postgresql import TIMESTAMPTZ, UUID
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base
from app.models.mixins import AuditMixin


class TrxMensaje(AuditMixin, Base):
    __tablename__ = "trx_mensajes"
    __table_args__ = (
        UniqueConstraint("empresa_id", "id", name="uq_trx_mensajes_empresa_id"),
        ForeignKeyConstraint(
            ["canal_id"],
            ["core.notificaciones.cat_canales.id"],
            name="fk_trx_mensajes_canal",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "plantilla_id"],
            [
                "core.notificaciones.mae_plantillas_mensaje.empresa_id",
                "core.notificaciones.mae_plantillas_mensaje.id",
            ],
            name="fk_trx_mensajes_plantilla",
        ),
        # FK simple sobre la PK de core.identidad.mae_documentos (esquema
        # externo del núcleo; la spec no expone unique compuesto).
        ForeignKeyConstraint(
            ["documento_id"],
            ["core.identidad.mae_documentos.id"],
            name="fk_trx_mensajes_documento",
        ),
        CheckConstraint("intentos >= 0", name="ck_trx_mensajes_intentos"),
        CheckConstraint(
            "(estado = 'enviado') = (fecha_enviado IS NOT NULL)",
            name="ck_trx_mensajes_enviado",
        ),
        # Índice parcial de cola: barrido eficiente de envíos pendientes.
        Index(
            "ix_trx_mensajes_cola",
            "fecha_programada",
            postgresql_where=text(
                "estado IN ('pendiente','enviando') AND deleted_at IS NULL"
            ),
        ),
        Index("ix_trx_mensajes_empresa_id", "empresa_id"),
        Index(
            "ix_trx_mensajes_referencia_externa",
            "servicio_origen",
            "referencia_externa_id",
        ),
        Index("ix_trx_mensajes_canal_id", "canal_id"),
        Index("ix_trx_mensajes_plantilla_id", "plantilla_id"),
        Index("ix_trx_mensajes_documento_id", "documento_id"),
        {"schema": "core.notificaciones"},
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        server_default=text("gen_random_uuid()"),
    )
    empresa_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
    canal_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
    plantilla_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), nullable=True
    )
    destinatario: Mapped[str] = mapped_column(Text, nullable=False)
    # Referencia lógica a core.identidad.mae_usuarios (sin FK), igual que en la spec.
    usuario_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), nullable=True
    )
    asunto: Mapped[str | None] = mapped_column(Text, nullable=True)
    cuerpo: Mapped[str] = mapped_column(Text, nullable=False)
    documento_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), nullable=True
    )
    # El enum estado_mensaje se gestiona en la capa de código y se persiste
    # como VARCHAR (convención del repo; la spec no crea el tipo).
    estado: Mapped[str] = mapped_column(
        String(50), nullable=False, server_default=text("'pendiente'")
    )
    intentos: Mapped[int] = mapped_column(
        SmallInteger, nullable=False, server_default=text("0")
    )
    fecha_programada: Mapped[datetime] = mapped_column(
        TIMESTAMPTZ, nullable=False, server_default=text("now()")
    )
    fecha_enviado: Mapped[datetime | None] = mapped_column(
        TIMESTAMPTZ, nullable=True
    )
    error_ultimo: Mapped[str | None] = mapped_column(Text, nullable=True)
    servicio_origen: Mapped[str | None] = mapped_column(Text, nullable=True)
    referencia_externa_id: Mapped[int | None] = mapped_column(
        BigInteger, nullable=True
    )