Saltar a contenido

Especificación Técnica: rel_clientes_promotores

Esquema: clientes
Base de Datos: crm
Tabla Legacy Origen: i137t_cliente_promotor (cartera)
Propósito: Asignación de clientes a la cartera comercial de los promotores, definiendo el vendedor titular, el día de visita habitual y la secuencia en la ruta diaria.


1. Justificación y Mejoras de Arquitectura

  • Normalización de Cartera Comercial Dinámica N:M: Permite estructurar carteras compartidas donde un cliente puede tener un promotor titular (is_promotor_principal = true) y promotores de apoyo o especialistas (preventa, cobranza, merchandising), con programación de día de visita semanal (dia_visita_habitual) y secuencia en ruta (orden_secuencia_visita).
  • Aislamiento Multi-Tenant (RLS): Integra empresa_id BIGINT NOT NULL con políticas RLS obligatorias (USING y WITH CHECK).
  • Integridad Referencial Compuesta: Clave única compuesta (empresa_id, id) y claves foráneas compuestas (empresa_id, cliente_id) hacia clientes.mae_clientes(empresa_id, id) y (empresa_id, promotor_id) hacia fuerza_ventas.mae_promotores(empresa_id, id), ambas con borrado en cascada (ON DELETE CASCADE).
  • Validación de Dominio: CHECK (dia_visita_habitual BETWEEN 1 AND 7 OR dia_visita_habitual IS NULL) para validar los días canónicos (1=Lunes a 7=Domingo).
  • Unicidad de Asignación: Restricción UNIQUE (empresa_id, cliente_id, promotor_id) para prevenir duplicidad de asignaciones entre un cliente y un promotor específico.
  • Trazabilidad y Auditoría: Auditoría integral (created_at, updated_at, deleted_at, created_by, updated_by) con auditoría integral.

2. Definiciones de Implementación

Table clientes.rel_clientes_promotores {
    id                      uuid        [pk, default: `gen_random_uuid()`, note: 'Identificador único UUID']
    empresa_id                  bigint        [not null, note: 'Identificador BIGINT de la empresa en core.identidad (RLS)']
    cliente_id              uuid        [not null, note: 'Cliente asignado']
    promotor_id             uuid        [not null, note: 'Promotor asignado']
    is_promotor_principal   boolean     [not null, default: `true`, note: 'Indica si es el vendedor titular']
    dia_visita_habitual     int         [note: 'Día de la semana de atención (1=Lunes ... 7=Domingo)']
    orden_secuencia_visita  int         [not null, default: `1`, note: 'Secuencia en la ruta de visita diaria']

    // Auditoría General
    is_activo               boolean     [not null, default: `true`, note: 'Estado lógico del registro']
    created_at              timestamptz [not null, default: `now()`, note: 'Fecha de creación']
    updated_at              timestamptz [not null, default: `now()`, note: 'Fecha de última actualización']
    deleted_at              timestamptz [note: 'Fecha de eliminación lógica']
    created_by              uuid        [note: 'Usuario creador']
    updated_by              uuid        [note: 'Usuario modificador']

    Indexes {
        (empresa_id, id) [unique, name: 'uq_rel_clientes_promotores_empresa_id']
        (empresa_id, cliente_id, promotor_id) [unique, name: 'uq_rel_clientes_promotores_asignacion']
        (empresa_id, is_activo) [name: 'ix_rel_clientes_promotores_empresa_activo']
        (empresa_id, promotor_id, dia_visita_habitual) [name: 'ix_rel_clientes_promotores_empresa_promotor_dia']
        (empresa_id, cliente_id) [name: 'ix_rel_clientes_promotores_empresa_cliente']
    }
}

Ref: clientes.rel_clientes_promotores.(empresa_id, cliente_id) > clientes.mae_clientes.(empresa_id, id) [delete: cascade]
Ref: clientes.rel_clientes_promotores.(empresa_id, promotor_id) > fuerza_ventas.mae_promotores.(empresa_id, id) [delete: cascade]
CREATE TABLE IF NOT EXISTS clientes.rel_clientes_promotores (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    cliente_id UUID NOT NULL,
    promotor_id UUID NOT NULL,
    is_promotor_principal BOOLEAN NOT NULL DEFAULT true,
    dia_visita_habitual INT,
    orden_secuencia_visita INT NOT NULL DEFAULT 1,

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

    CONSTRAINT pk_rel_clientes_promotores
        PRIMARY KEY (id),

    CONSTRAINT uq_rel_clientes_promotores_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_rel_clientes_promotores_asignacion
        UNIQUE (empresa_id, cliente_id, promotor_id),

    CONSTRAINT ck_rel_clientes_promotores_dia
        CHECK (dia_visita_habitual BETWEEN 1 AND 7 OR dia_visita_habitual IS NULL),

    CONSTRAINT fk_rel_clientes_promotores_cliente
        FOREIGN KEY (empresa_id, cliente_id)
        REFERENCES clientes.mae_clientes (empresa_id, id)
        ON DELETE CASCADE,

    CONSTRAINT fk_rel_clientes_promotores_promotor
        FOREIGN KEY (empresa_id, promotor_id)
        REFERENCES fuerza_ventas.mae_promotores (empresa_id, id)
        ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS ix_rel_clientes_promotores_empresa_activo
    ON clientes.rel_clientes_promotores (empresa_id, is_activo);

CREATE INDEX IF NOT EXISTS ix_rel_clientes_promotores_empresa_promotor_dia
    ON clientes.rel_clientes_promotores (empresa_id, promotor_id, dia_visita_habitual);

CREATE INDEX IF NOT EXISTS ix_rel_clientes_promotores_empresa_cliente
    ON clientes.rel_clientes_promotores (empresa_id, cliente_id);

COMMENT ON TABLE clientes.rel_clientes_promotores IS
    'Cartera de Clientes por Promotor: Asignación de clientes a la cartera comercial de los promotores, definiendo el día y orden de visita en ruta.';

COMMENT ON COLUMN clientes.rel_clientes_promotores.id IS
    'Identificador único UUID';

COMMENT ON COLUMN clientes.rel_clientes_promotores.empresa_id IS
    'Identificador UUID de la empresa en core.identidad (RLS)';

COMMENT ON COLUMN clientes.rel_clientes_promotores.cliente_id IS
    'Cliente asignado';

COMMENT ON COLUMN clientes.rel_clientes_promotores.promotor_id IS
    'Promotor asignado';

COMMENT ON COLUMN clientes.rel_clientes_promotores.is_promotor_principal IS
    'Indica si es el vendedor titular';

COMMENT ON COLUMN clientes.rel_clientes_promotores.dia_visita_habitual IS
    'Día de la semana de atención (1=Lunes ... 7=Domingo)';

COMMENT ON COLUMN clientes.rel_clientes_promotores.orden_secuencia_visita IS
    'Secuencia en la ruta de visita diaria';

COMMENT ON COLUMN clientes.rel_clientes_promotores.is_activo IS
    'Estado lógico del registro';

COMMENT ON COLUMN clientes.rel_clientes_promotores.created_at IS
    'Fecha de creación';

COMMENT ON COLUMN clientes.rel_clientes_promotores.updated_at IS
    'Fecha de última actualización';

COMMENT ON COLUMN clientes.rel_clientes_promotores.deleted_at IS
    'Fecha de eliminación lógica';

COMMENT ON COLUMN clientes.rel_clientes_promotores.created_by IS
    'Usuario creador';

COMMENT ON COLUMN clientes.rel_clientes_promotores.updated_by IS
    'Usuario modificador';

ALTER TABLE clientes.rel_clientes_promotores
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_rel_clientes_promotores_empresa
    ON clientes.rel_clientes_promotores
    FOR ALL
    USING (
        empresa_id = current_setting(
            'app.current_empresa_id',
            true
        )::BIGINT
    )
    WITH CHECK (
        empresa_id = current_setting(
            'app.current_empresa_id',
            true
        )::BIGINT
    );
import uuid
from datetime import datetime
from typing import Optional

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

from app.db.base import Base


class RelClientesPromotores(Base):
    """
    Cartera de Clientes por Promotor.

    Asignación de clientes a la cartera comercial de los promotores,
    definiendo el día y orden de visita en ruta.

    Legacy:
        i137t_cliente_promotor (cartera)
    """

    __tablename__ = "rel_clientes_promotores"

    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_rel_clientes_promotores_empresa_id",
        ),
        UniqueConstraint(
            "empresa_id",
            "cliente_id",
            "promotor_id",
            name="uq_rel_clientes_promotores_asignacion",
        ),
        CheckConstraint(
            "dia_visita_habitual BETWEEN 1 AND 7 OR dia_visita_habitual IS NULL",
            name="ck_rel_clientes_promotores_dia",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "cliente_id"],
            ["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
            ondelete="CASCADE",
            name="fk_rel_clientes_promotores_cliente",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "promotor_id"],
            ["fuerza_ventas.mae_promotores.empresa_id", "fuerza_ventas.mae_promotores.id"],
            ondelete="CASCADE",
            name="fk_rel_clientes_promotores_promotor",
        ),
        Index(
            "ix_rel_clientes_promotores_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        Index(
            "ix_rel_clientes_promotores_empresa_promotor_dia",
            "empresa_id",
            "promotor_id",
            "dia_visita_habitual",
        ),
        Index(
            "ix_rel_clientes_promotores_empresa_cliente",
            "empresa_id",
            "cliente_id",
        ),
        {
            "schema": "clientes",
            "comment": "Cartera de Clientes por Promotor",
        },
    )

    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 UUID de la empresa en core.identidad (RLS)",
    )

    cliente_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Cliente asignado",
    )

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

    is_promotor_principal: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("true"),
        comment="Indica si es el vendedor titular",
    )

    dia_visita_habitual: Mapped[Optional[int]] = mapped_column(
        Integer,
        nullable=True,
        comment="Día de la semana de atención (1=Lunes ... 7=Domingo)",
    )

    orden_secuencia_visita: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        server_default=text("1"),
        comment="Secuencia en la ruta de visita diaria",
    )

    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(
        TIMESTAMPTZ,
        nullable=False,
        server_default=text("now()"),
        comment="Fecha de creación",
    )

    updated_at: Mapped[datetime] = mapped_column(
        TIMESTAMPTZ,
        nullable=False,
        server_default=text("now()"),
        comment="Fecha de última actualización",
    )

    deleted_at: Mapped[Optional[datetime]] = mapped_column(
        TIMESTAMPTZ,
        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",
    )
"""create rel_clientes_promotores

Revision ID: rel_0004
Revises: rel_0003
Create Date: 2026-09-10
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


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


def upgrade() -> None:

    op.create_table(
        "rel_clientes_promotores",

        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            server_default=sa.text("gen_random_uuid()"),
            comment="Identificador único UUID",
        ),

        sa.Column(
            "empresa_id",
            sa.BigInteger(),
            nullable=False,
            comment="Identificador UUID de la empresa en core.identidad (RLS)",
        ),

        sa.Column(
            "cliente_id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            comment="Cliente asignado",
        ),

        sa.Column(
            "promotor_id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            comment="Promotor asignado",
        ),

        sa.Column(
            "is_promotor_principal",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("true"),
            comment="Indica si es el vendedor titular",
        ),

        sa.Column(
            "dia_visita_habitual",
            sa.Integer(),
            nullable=True,
            comment="Día de la semana de atención (1=Lunes ... 7=Domingo)",
        ),

        sa.Column(
            "orden_secuencia_visita",
            sa.Integer(),
            nullable=False,
            server_default=sa.text("1"),
            comment="Secuencia en la ruta de visita diaria",
        ),

        # Auditoría General
        sa.Column(
            "is_activo",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("true"),
            comment="Estado lógico del registro",
        ),

        sa.Column(
            "created_at",
            sa.TIMESTAMP(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
            comment="Fecha de creación",
        ),

        sa.Column(
            "updated_at",
            sa.TIMESTAMP(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
            comment="Fecha de última actualización",
        ),

        sa.Column(
            "deleted_at",
            sa.TIMESTAMP(timezone=True),
            nullable=True,
            comment="Fecha de eliminación lógica",
        ),

        sa.Column(
            "created_by",
            postgresql.UUID(as_uuid=True),
            nullable=True,
            comment="Usuario creador",
        ),

        sa.Column(
            "updated_by",
            postgresql.UUID(as_uuid=True),
            nullable=True,
            comment="Usuario modificador",
        ),

        sa.PrimaryKeyConstraint(
            "id",
            name="pk_rel_clientes_promotores",
        ),

        sa.UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_rel_clientes_promotores_empresa_id",
        ),

        sa.UniqueConstraint(
            "empresa_id",
            "cliente_id",
            "promotor_id",
            name="uq_rel_clientes_promotores_asignacion",
        ),

        sa.CheckConstraint(
            "dia_visita_habitual BETWEEN 1 AND 7 OR dia_visita_habitual IS NULL",
            name="ck_rel_clientes_promotores_dia",
        ),

        sa.ForeignKeyConstraint(
            ["empresa_id", "cliente_id"],
            ["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
            ondelete="CASCADE",
            name="fk_rel_clientes_promotores_cliente",
        ),

        sa.ForeignKeyConstraint(
            ["empresa_id", "promotor_id"],
            ["fuerza_ventas.mae_promotores.empresa_id", "fuerza_ventas.mae_promotores.id"],
            ondelete="CASCADE",
            name="fk_rel_clientes_promotores_promotor",
        ),

        comment="Cartera de Clientes por Promotor",
        schema="clientes",
    )

    op.create_index(
        "ix_rel_clientes_promotores_empresa_activo",
        "rel_clientes_promotores",
        ["empresa_id", "is_activo"],
        unique=False,
        schema="clientes",
    )

    op.create_index(
        "ix_rel_clientes_promotores_empresa_promotor_dia",
        "rel_clientes_promotores",
        ["empresa_id", "promotor_id", "dia_visita_habitual"],
        unique=False,
        schema="clientes",
    )

    op.create_index(
        "ix_rel_clientes_promotores_empresa_cliente",
        "rel_clientes_promotores",
        ["empresa_id", "cliente_id"],
        unique=False,
        schema="clientes",
    )

    op.execute(
        """
        ALTER TABLE clientes.rel_clientes_promotores
        ENABLE ROW LEVEL SECURITY;
        """
    )

    op.execute(
        """
        CREATE POLICY rls_rel_clientes_promotores_empresa
        ON clientes.rel_clientes_promotores
        FOR ALL
        USING (
            empresa_id = current_setting(
                'app.current_empresa_id',
                true
            )::BIGINT
        )
        WITH CHECK (
            empresa_id = current_setting(
                'app.current_empresa_id',
                true
            )::BIGINT
        );
        """
    )


def downgrade() -> None:

    op.execute(
        """
        DROP POLICY IF EXISTS rls_rel_clientes_promotores_empresa
        ON clientes.rel_clientes_promotores;
        """
    )

    op.execute(
        """
        ALTER TABLE clientes.rel_clientes_promotores
        DISABLE ROW LEVEL SECURITY;
        """
    )

    op.drop_index(
        "ix_rel_clientes_promotores_empresa_cliente",
        table_name="rel_clientes_promotores",
        schema="clientes",
    )

    op.drop_index(
        "ix_rel_clientes_promotores_empresa_promotor_dia",
        table_name="rel_clientes_promotores",
        schema="clientes",
    )

    op.drop_index(
        "ix_rel_clientes_promotores_empresa_activo",
        table_name="rel_clientes_promotores",
        schema="clientes",
    )

    op.drop_table(
        "rel_clientes_promotores",
        schema="clientes",
    )