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), FK compuesta hacia fuerza_ventas.mae_promotores y correlación lógica con crm.clientes.mae_clientes (sin FK física cross-service).
  • 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 (Correlación lógica con crm.clientes.mae_clientes)']
    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, 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_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 BIGINT 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
    );