Saltar a contenido

TrxVisitas — fuerza_ventas.trx_visitas

Transacción de Visitas y Agenda en Campo.

import uuid
from datetime import date, datetime
from decimal import Decimal
from typing import Optional

from sqlalchemy import (
    BigInteger,
    Boolean,
    CheckConstraint,
    Date,
    Double,
    ForeignKeyConstraint,
    Index,
    Numeric,
    Text,
    UniqueConstraint,
    text,
)
from sqlalchemy.dialects.postgresql import TIMESTAMP, UUID
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base


class TrxVisitas(Base):
    """
    Transacción de Visitas y Agenda en Campo.

    Cabecera principal de actividades en ruta de la fuerza de ventas.
    Incorpora validación de exclusividad de destino (cliente vs prospecto)
    y trazabilidad completa de check-in / check-out georreferenciado.

    Legacy:
        c063t_agenda_actividades
    """

    __tablename__ = "trx_visitas"

    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_trx_visitas_empresa_id",
        ),
        CheckConstraint(
            "num_nonnulls(cliente_id, prospecto_id) = 1",
            name="ck_trx_visitas_destino_exclusivo",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "promotor_id"],
            ["fuerza_ventas.mae_promotores.empresa_id", "fuerza_ventas.mae_promotores.id"],
            name="fk_trx_visitas_promotor",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "tipo_actividad_id"],
            ["fuerza_ventas.cat_tipos_actividad.empresa_id", "fuerza_ventas.cat_tipos_actividad.id"],
            name="fk_trx_visitas_tipo_actividad",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "estado_visita_id"],
            ["fuerza_ventas.cat_estados_visita.empresa_id", "fuerza_ventas.cat_estados_visita.id"],
            name="fk_trx_visitas_estado",
        ),
        Index(
            "ix_trx_visitas_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        Index(
            "ix_trx_visitas_empresa_promotor_fecha",
            "empresa_id",
            "promotor_id",
            "fecha_planificada",
        ),
        Index(
            "ix_trx_visitas_empresa_cliente",
            "empresa_id",
            "cliente_id",
        ),
        Index(
            "ix_trx_visitas_empresa_prospecto",
            "empresa_id",
            "prospecto_id",
        ),
        Index(
            "ix_trx_visitas_empresa_estado",
            "empresa_id",
            "estado_visita_id",
        ),
        {
            "schema": "fuerza_ventas",
            "comment": "Transacción de Visitas y Agenda en Campo",
        },
    )

    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)",
    )

    promotor_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Promotor comercial asignado a la visita",
    )

    cliente_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Cliente formal visitado",
    )

    local_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Punto de venta o local físico específico",
    )

    prospecto_id: Mapped[Optional[uuid.UUID]] = mapped_column(
        UUID(as_uuid=True),
        nullable=True,
        comment="Prospecto lead visitado",
    )

    tipo_actividad_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Tipo de gestión comercial efectuada",
    )

    estado_visita_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Estado de ejecución de la visita",
    )

    fecha_planificada: Mapped[date] = mapped_column(
        Date,
        nullable=False,
        comment="Fecha programada en la ruta comercial",
    )

    hora_estimada_llegada: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMP(timezone=True),
        nullable=True,
        comment="Hora estimada de llegada",
    )

    fecha_checkin: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMP(timezone=True),
        nullable=True,
        comment="Timestamp real de check-in capturado por la app",
    )

    fecha_checkout: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMP(timezone=True),
        nullable=True,
        comment="Timestamp real de check-out capturado por la app",
    )

    latitud_checkin: Mapped[Optional[float]] = mapped_column(
        Double,
        nullable=True,
        comment="Coordenada GPS Latitud en check-in",
    )

    longitud_checkin: Mapped[Optional[float]] = mapped_column(
        Double,
        nullable=True,
        comment="Coordenada GPS Longitud en check-in",
    )

    latitud_checkout: Mapped[Optional[float]] = mapped_column(
        Double,
        nullable=True,
        comment="Coordenada GPS Latitud en check-out",
    )

    longitud_checkout: Mapped[Optional[float]] = mapped_column(
        Double,
        nullable=True,
        comment="Coordenada GPS Longitud en check-out",
    )

    distancia_metros_checkin: Mapped[Optional[Decimal]] = mapped_column(
        Numeric(8, 2),
        nullable=True,
        comment="Distancia calculada en metros respecto al local",
    )

    is_checkin_fuera_rango: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("false"),
        comment="Indica si el check-in excedió la geocerca configurada",
    )

    observaciones_visita: Mapped[Optional[str]] = mapped_column(
        Text,
        nullable=True,
        comment="Bitácora y comentarios comerciales del promotor",
    )

    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()"),
        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",
    )