Saltar a contenido

Especificación Técnica: mae_presupuestos_cliente

Esquema: fuerza_ventas
Base de Datos: crm
Tabla Legacy Origen: i714t_presupuesto_cliente
Propósito: Presupuesto comercial y proyección mensual de ventas acordada por cada cliente específico bajo la atención de un promotor determinado.


1. Justificación y Mejoras de Arquitectura

  • Planificación Comercial Segmentada: Proporciona visibilidad granular de las metas acordadas a nivel de cada cliente y promotor asignado en períodos mensuales.
  • Aislamiento Multi-Tenant (RLS): Integra empresa_id BIGINT NOT NULL con políticas RLS obligatorias.
  • Integridad Referencial Compuesta: Clave única compuesta (empresa_id, id), constraint de unicidad temporal por cliente y promotor (empresa_id, cliente_id, promotor_id, anio, mes) y FKs compuestas hacia clientes.mae_clientes y fuerza_ventas.mae_promotores.
  • 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 fuerza_ventas.mae_presupuestos_cliente {
    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 comercial asignado']
    promotor_id         uuid          [not null, note: 'Promotor responsable de la atención']
    anio                int           [not null, note: 'Año fiscal del presupuesto']
    mes                 int           [not null, note: 'Mes del presupuesto (1-12)']
    monto_presupuesto   numeric(12,2) [not null, default: `0.00`, note: 'Monto mensual proyectado de compra']

    // 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_mae_presupuestos_cliente_empresa_id']
        (empresa_id, cliente_id, promotor_id, anio, mes) [unique, name: 'uq_mae_presupuestos_cliente_periodo']
        (empresa_id, is_activo) [name: 'ix_mae_presupuestos_cliente_empresa_activo']
        (empresa_id, anio, mes) [name: 'ix_mae_presupuestos_cliente_empresa_periodo']
        (empresa_id, cliente_id) [name: 'ix_mae_presupuestos_cliente_empresa_cliente']
        (empresa_id, promotor_id) [name: 'ix_mae_presupuestos_cliente_empresa_promotor']
    }
}

Ref: fuerza_ventas.mae_presupuestos_cliente.(empresa_id, cliente_id) > clientes.mae_clientes.(empresa_id, id) [delete: cascade]
Ref: fuerza_ventas.mae_presupuestos_cliente.(empresa_id, promotor_id) > fuerza_ventas.mae_promotores.(empresa_id, id) [delete: cascade]
CREATE TABLE IF NOT EXISTS fuerza_ventas.mae_presupuestos_cliente (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    cliente_id UUID NOT NULL,
    promotor_id UUID NOT NULL,
    anio INT NOT NULL,
    mes INT NOT NULL,
    monto_presupuesto NUMERIC(12,2) NOT NULL DEFAULT 0.00,

    -- 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_mae_presupuestos_cliente
        PRIMARY KEY (id),

    CONSTRAINT uq_mae_presupuestos_cliente_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_mae_presupuestos_cliente_periodo
        UNIQUE (empresa_id, cliente_id, promotor_id, anio, mes),

    CONSTRAINT ck_mae_presupuestos_cliente_mes
        CHECK (mes BETWEEN 1 AND 12),

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

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

CREATE INDEX IF NOT EXISTS ix_mae_presupuestos_cliente_empresa_activo
    ON fuerza_ventas.mae_presupuestos_cliente (empresa_id, is_activo);

CREATE INDEX IF NOT EXISTS ix_mae_presupuestos_cliente_empresa_periodo
    ON fuerza_ventas.mae_presupuestos_cliente (empresa_id, anio, mes);

CREATE INDEX IF NOT EXISTS ix_mae_presupuestos_cliente_empresa_cliente
    ON fuerza_ventas.mae_presupuestos_cliente (empresa_id, cliente_id);

CREATE INDEX IF NOT EXISTS ix_mae_presupuestos_cliente_empresa_promotor
    ON fuerza_ventas.mae_presupuestos_cliente (empresa_id, promotor_id);

COMMENT ON TABLE fuerza_ventas.mae_presupuestos_cliente IS
    'Presupuestos Comerciales por Cliente y Promotor: Presupuesto y proyección mensual de ventas acordado para un cliente atendido por un promotor.';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.id IS
    'Identificador único UUID';

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

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.cliente_id IS
    'Cliente comercial asignado';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.promotor_id IS
    'Promotor responsable de la atención';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.anio IS
    'Año fiscal del presupuesto';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.mes IS
    'Mes del presupuesto (1-12)';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.monto_presupuesto IS
    'Monto mensual proyectado de compra';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.is_activo IS
    'Estado lógico del registro';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.created_at IS
    'Fecha de creación';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.updated_at IS
    'Fecha de última actualización';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.deleted_at IS
    'Fecha de eliminación lógica';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.created_by IS
    'Usuario creador';

COMMENT ON COLUMN fuerza_ventas.mae_presupuestos_cliente.updated_by IS
    'Usuario modificador';

ALTER TABLE fuerza_ventas.mae_presupuestos_cliente
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_mae_presupuestos_cliente_empresa
    ON fuerza_ventas.mae_presupuestos_cliente
    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 decimal import Decimal

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

from app.db.base import Base


class MaePresupuestosCliente(Base):
    """
    Presupuestos Comerciales por Cliente y Promotor.

    Presupuesto y proyección mensual de ventas acordado para un cliente
    específico atendido por un promotor.

    Legacy:
        i714t_presupuesto_cliente
    """

    __tablename__ = "mae_presupuestos_cliente"

    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_mae_presupuestos_cliente_empresa_id",
        ),
        UniqueConstraint(
            "empresa_id",
            "cliente_id",
            "promotor_id",
            "anio",
            "mes",
            name="uq_mae_presupuestos_cliente_periodo",
        ),
        CheckConstraint(
            "mes BETWEEN 1 AND 12",
            name="ck_mae_presupuestos_cliente_mes",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "cliente_id"],
            ["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
            ondelete="CASCADE",
            name="fk_mae_presupuestos_cliente_cliente",
        ),
        ForeignKeyConstraint(
            ["empresa_id", "promotor_id"],
            ["fuerza_ventas.mae_promotores.empresa_id", "fuerza_ventas.mae_promotores.id"],
            ondelete="CASCADE",
            name="fk_mae_presupuestos_cliente_promotor",
        ),
        Index(
            "ix_mae_presupuestos_cliente_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        Index(
            "ix_mae_presupuestos_cliente_empresa_periodo",
            "empresa_id",
            "anio",
            "mes",
        ),
        Index(
            "ix_mae_presupuestos_cliente_empresa_cliente",
            "empresa_id",
            "cliente_id",
        ),
        Index(
            "ix_mae_presupuestos_cliente_empresa_promotor",
            "empresa_id",
            "promotor_id",
        ),
        {
            "schema": "fuerza_ventas",
            "comment": "Presupuestos Comerciales por Cliente y 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 comercial asignado",
    )

    promotor_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        nullable=False,
        comment="Promotor responsable de la atención",
    )

    anio: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        comment="Año fiscal del presupuesto",
    )

    mes: Mapped[int] = mapped_column(
        Integer,
        nullable=False,
        comment="Mes del presupuesto (1-12)",
    )

    monto_presupuesto: Mapped[Decimal] = mapped_column(
        Numeric(12, 2),
        nullable=False,
        server_default=text("0.00"),
        comment="Monto mensual proyectado de compra",
    )

    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 mae_presupuestos_cliente

Revision ID: mae_0010
Revises: mae_0009
Create Date: 2026-09-09
"""

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 = "mae_0010"
down_revision: Union[str, Sequence[str], None] = "mae_0009"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:

    op.create_table(
        "mae_presupuestos_cliente",

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

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

        sa.Column(
            "anio",
            sa.Integer(),
            nullable=False,
            comment="Año fiscal del presupuesto",
        ),

        sa.Column(
            "mes",
            sa.Integer(),
            nullable=False,
            comment="Mes del presupuesto (1-12)",
        ),

        sa.Column(
            "monto_presupuesto",
            sa.Numeric(precision=12, scale=2),
            nullable=False,
            server_default=sa.text("0.00"),
            comment="Monto mensual proyectado de compra",
        ),

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

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

        sa.UniqueConstraint(
            "empresa_id",
            "cliente_id",
            "promotor_id",
            "anio",
            "mes",
            name="uq_mae_presupuestos_cliente_periodo",
        ),

        sa.CheckConstraint(
            "mes BETWEEN 1 AND 12",
            name="ck_mae_presupuestos_cliente_mes",
        ),

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

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

        comment="Presupuestos Comerciales por Cliente y Promotor",
        schema="fuerza_ventas",
    )

    op.create_index(
        "ix_mae_presupuestos_cliente_empresa_activo",
        "mae_presupuestos_cliente",
        ["empresa_id", "is_activo"],
        unique=False,
        schema="fuerza_ventas",
    )

    op.create_index(
        "ix_mae_presupuestos_cliente_empresa_periodo",
        "mae_presupuestos_cliente",
        ["empresa_id", "anio", "mes"],
        unique=False,
        schema="fuerza_ventas",
    )

    op.create_index(
        "ix_mae_presupuestos_cliente_empresa_cliente",
        "mae_presupuestos_cliente",
        ["empresa_id", "cliente_id"],
        unique=False,
        schema="fuerza_ventas",
    )

    op.create_index(
        "ix_mae_presupuestos_cliente_empresa_promotor",
        "mae_presupuestos_cliente",
        ["empresa_id", "promotor_id"],
        unique=False,
        schema="fuerza_ventas",
    )

    op.execute(
        """
        ALTER TABLE fuerza_ventas.mae_presupuestos_cliente
        ENABLE ROW LEVEL SECURITY;
        """
    )

    op.execute(
        """
        CREATE POLICY rls_mae_presupuestos_cliente_empresa
        ON fuerza_ventas.mae_presupuestos_cliente
        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_mae_presupuestos_cliente_empresa
        ON fuerza_ventas.mae_presupuestos_cliente;
        """
    )

    op.execute(
        """
        ALTER TABLE fuerza_ventas.mae_presupuestos_cliente
        DISABLE ROW LEVEL SECURITY;
        """
    )

    op.drop_index(
        "ix_mae_presupuestos_cliente_empresa_promotor",
        table_name="mae_presupuestos_cliente",
        schema="fuerza_ventas",
    )

    op.drop_index(
        "ix_mae_presupuestos_cliente_empresa_cliente",
        table_name="mae_presupuestos_cliente",
        schema="fuerza_ventas",
    )

    op.drop_index(
        "ix_mae_presupuestos_cliente_empresa_periodo",
        table_name="mae_presupuestos_cliente",
        schema="fuerza_ventas",
    )

    op.drop_index(
        "ix_mae_presupuestos_cliente_empresa_activo",
        table_name="mae_presupuestos_cliente",
        schema="fuerza_ventas",
    )

    op.drop_table(
        "mae_presupuestos_cliente",
        schema="fuerza_ventas",
    )