Saltar a contenido

Especificación Técnica: mae_metas_promotores

Esquema: fuerza_ventas
Base de Datos: crm
Tabla Legacy Origen: i176t_meta_promotor
Propósito: Objetivos mensuales o periódicos de ventas, cobertura de clientes compradores, visitas efectivas y recaudación asignados a los promotores comerciales.


1. Justificación y Mejoras de Arquitectura

  • Estructura Periódica de Metas Comerciales: Modela los KPIs y cuotas mensuales por promotor para evaluación de desempeño y liquidación de comisiones.
  • 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 promotor (empresa_id, promotor_id, anio, mes) y FK compuesta hacia 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_metas_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)']
    promotor_id                 uuid          [not null, note: 'Promotor comercial asignado']
    anio                        int           [not null, note: 'Año de la meta (p. ej. 2026)']
    mes                         int           [not null, note: 'Mes de la meta (1-12)']
    meta_monto_ventas           numeric(12,2) [not null, default: `0.00`, note: 'Meta financiera de facturación']
    meta_cobertura_clientes     int           [not null, default: `0`, note: 'Meta de cantidad de clientes compradores únicos']
    meta_visitas_efectivas      int           [not null, default: `0`, note: 'Meta de visitas efectivas con transacción']
    meta_monto_cobranza         numeric(12,2) [not null, default: `0.00`, note: 'Meta de recuperación y cobro de cartera']

    // 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_metas_promotores_empresa_id']
        (empresa_id, promotor_id, anio, mes) [unique, name: 'uq_mae_metas_promotores_periodo']
        (empresa_id, is_activo) [name: 'ix_mae_metas_promotores_empresa_activo']
        (empresa_id, anio, mes) [name: 'ix_mae_metas_promotores_empresa_periodo']
        (empresa_id, promotor_id) [name: 'ix_mae_metas_promotores_empresa_promotor']
    }
}

Ref: fuerza_ventas.mae_metas_promotores.(empresa_id, promotor_id) > fuerza_ventas.mae_promotores.(empresa_id, id) [delete: cascade]
CREATE TABLE IF NOT EXISTS fuerza_ventas.mae_metas_promotores (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    promotor_id UUID NOT NULL,
    anio INT NOT NULL,
    mes INT NOT NULL,
    meta_monto_ventas NUMERIC(12,2) NOT NULL DEFAULT 0.00,
    meta_cobertura_clientes INT NOT NULL DEFAULT 0,
    meta_visitas_efectivas INT NOT NULL DEFAULT 0,
    meta_monto_cobranza 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_metas_promotores
        PRIMARY KEY (id),

    CONSTRAINT uq_mae_metas_promotores_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_mae_metas_promotores_periodo
        UNIQUE (empresa_id, promotor_id, anio, mes),

    CONSTRAINT ck_mae_metas_promotores_mes
        CHECK (mes BETWEEN 1 AND 12),

    CONSTRAINT fk_mae_metas_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_mae_metas_promotores_empresa_activo
    ON fuerza_ventas.mae_metas_promotores (empresa_id, is_activo);

CREATE INDEX IF NOT EXISTS ix_mae_metas_promotores_empresa_periodo
    ON fuerza_ventas.mae_metas_promotores (empresa_id, anio, mes);

CREATE INDEX IF NOT EXISTS ix_mae_metas_promotores_empresa_promotor
    ON fuerza_ventas.mae_metas_promotores (empresa_id, promotor_id);

COMMENT ON TABLE fuerza_ventas.mae_metas_promotores IS
    'Metas y Cuotas Comerciales de Promotores: Objetivos periódicos de ventas, cobertura, visitas y cobranza asignados a promotores.';

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

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

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.promotor_id IS
    'Promotor comercial asignado';

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.anio IS
    'Año de la meta (p. ej. 2026)';

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.mes IS
    'Mes de la meta (1-12)';

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.meta_monto_ventas IS
    'Meta financiera de facturación';

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.meta_cobertura_clientes IS
    'Meta de cantidad de clientes compradores únicos';

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.meta_visitas_efectivas IS
    'Meta de visitas efectivas con transacción';

COMMENT ON COLUMN fuerza_ventas.mae_metas_promotores.meta_monto_cobranza IS
    'Meta de recuperación y cobro de cartera';

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

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

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

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

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

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

ALTER TABLE fuerza_ventas.mae_metas_promotores
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_mae_metas_promotores_empresa
    ON fuerza_ventas.mae_metas_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
    );