Saltar a contenido

MaePromotor — fuerza_ventas.mae_promotores

Perfil comercial del promotor de ventas. Aísla la identidad de usuario y credenciales (delegadas a core.identidad) y se enfoca en parámetros comerciales, metas, comisiones y cupos de crédito comercial.

from datetime import datetime
from typing import Optional
import uuid

from sqlalchemy import (
    BigInteger,
    Boolean,
    ForeignKeyConstraint,
    Index,
    Numeric,
    String,
    UniqueConstraint,
    text,
)
from sqlalchemy.dialects.postgresql import TIMESTAMP, UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class MaePromotor(Base):
    __tablename__ = "mae_promotores"
    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_mae_promotores_empresa_id",
        ),
        UniqueConstraint(
            "empresa_id",
            "codigo_promotor",
            name="uq_mae_promotores_empresa_codigo",
        ),
        UniqueConstraint(
            "empresa_id",
            "usuario_id",
            name="uq_mae_promotores_empresa_usuario",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "modalidad_pago_comision_id"],
            ["fuerza_ventas.cat_modalidades_pago_comision.empresa_id", "fuerza_ventas.cat_modalidades_pago_comision.id"],
            ondelete="RESTRICT",
            name="fk_mae_promotores_modalidad_comision",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "tipo_promotor_id"],
            ["fuerza_ventas.cat_tipos_promotor.empresa_id", "fuerza_ventas.cat_tipos_promotor.id"],
            ondelete="RESTRICT",
            name="fk_mae_promotores_tipo_promotor",
        ),
        Index(
            "ix_mae_promotores_empresa_persona",
            "empresa_id",
            "persona_id",
        ),
        Index(
            "ix_mae_promotores_empresa_modalidad",
            "empresa_id",
            "modalidad_pago_comision_id",
        ),
        Index(
            "ix_mae_promotores_empresa_tipo",
            "empresa_id",
            "tipo_promotor_id",
        ),
        Index(
            "ix_mae_promotores_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        {"schema": "fuerza_ventas"},
    )

    # Identificadores y Claves
    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        server_default=text("gen_random_uuid()"),
        comment="Identificador único UUID",
    )

    empresa_id: Mapped[int] = mapped_column(
        BigInteger,
        nullable=False,
        comment="Identificador BIGINT de la empresa en core.identidad (RLS)",
    )

    usuario_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Correlación con core.identidad.mae_usuarios (sin FK cross-DB)",
    )

    persona_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Correlación con core.identidad.mae_personas (sin FK cross-DB)",
    )

    codigo_promotor: Mapped[str] = mapped_column(
        String(30),
        nullable=False,
        comment="Código interno comercial",
    )

    tipo_promotor_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Tipo o rol de promotor comercial (FK cat_tipos_promotor)",
    )

    modalidad_pago_comision_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Identificador de la modalidad de pago de comisión (FK cat_modalidades_pago_comision)",
    )

    is_coordinador: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("false"),
        comment="Indica si tiene rol de coordinación/supervisión",
    )

    is_casa_matriz: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("false"),
        comment="Indica si opera desde sede principal",
    )

    porcentaje_comision: Mapped[float] = mapped_column(
        Numeric(5, 2),
        nullable=False,
        server_default=text("0.00"),
        comment="Porcentaje base de comisión",
    )

    monto_cupo_maximo_credito: Mapped[float] = mapped_column(
        Numeric(12, 2),
        nullable=False,
        server_default=text("0.00"),
        comment="Cupo máximo acumulado otorgable a su cartera",
    )

    dispositivo_imei: Mapped[Optional[str]] = mapped_column(
        String(50),
        nullable=True,
        comment="Identificador del dispositivo móvil autorizado",
    )

    telefono_corporativo: Mapped[Optional[str]] = mapped_column(
        String(50),
        nullable=True,
        comment="Número móvil institucional",
    )

    # Auditoría General
    is_activo: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("true"),
        comment="Estado lógico del registro",
    )

    created_at: Mapped[datetime] = mapped_column(
        TIMESTAMP(timezone=True),
        nullable=False,
        server_default=text("now()"),
        comment="Fecha de creación",
    )

    updated_at: Mapped[datetime] = mapped_column(
        TIMESTAMP(timezone=True),
        nullable=False,
        server_default=text("now()"),
        onupdate=datetime.utcnow,
        comment="Fecha de última actualización",
    )

    deleted_at: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMP(timezone=True),
        nullable=True,
        comment="Fecha de eliminación lógica",
    )

    created_by: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Usuario creador",
    )

    updated_by: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Usuario modificador",
    )