Saltar a contenido

Especificación Técnica: log_ubicaciones_promotores

Esquema: fuerza_ventas
Base de Datos: crm
Servicio: svc-fuerza-ventas
Tabla Legacy Origen: c550t (14,2 M filas — particionada por fecha)
Propósito: telemetría GPS en ruta


1. Justificación y Mejoras de Arquitectura

  • Normalización Relacional Rigurosa: Aplica diseño normalizado (1FN a BCNF), eliminando grupos repetidos de booleanos, desnormalizaciones innecesarias y redundancias del sistema legacy.
  • Aislamiento Multi-Tenant (RLS): Integra empresa_id BIGINT NOT NULL indexado, gobernado por políticas PostgreSQL Row-Level Security (USING y WITH CHECK) para garantizar la total separación de datos por tenant.
  • Integridad Referencial Compuesta: Todas las claves foráneas internas hacia tablas con tenencia son compuestas (empresa_id, <fk_id>), asegurando la integridad física en PostgreSQL.
  • Trazabilidad y Auditoría: Auditoría estándar (created_at, updated_at, deleted_at, created_by, updated_by) con auditoría integral.

2. Definiciones de Implementación

Table fuerza_ventas.log_ubicaciones_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 o asesor comercial']
    latitud                 numeric(10,7) [not null, note: 'Campo latitud']
    longitud                numeric(10,7) [not null, note: 'Campo longitud']
    precision_gps_metros    numeric(6,2)  [, note: 'Campo precision_gps_metros']
    bateria_porcentaje      int           [, note: 'Campo bateria_porcentaje']
    is_en_movimiento        boolean       [, note: 'Campo is_en_movimiento']
    fecha_hora_dispositivo  timestamptz   [not null, note: 'Campo fecha_hora_dispositivo']

    // 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_log_ubicaciones_promotores_empresa_id']
        (empresa_id, promotor_id) [name: 'ix_log_ubicaciones_promotores_empresa_promotor']
        (empresa_id, is_activo) [name: 'ix_log_ubicaciones_promotores_empresa_activo']
    }
}

Ref: fuerza_ventas.log_ubicaciones_promotores.(empresa_id, promotor_id) > fuerza_ventas.mae_promotores.(empresa_id, id) [delete: restrict]
CREATE TABLE IF NOT EXISTS fuerza_ventas.log_ubicaciones_promotores (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    promotor_id UUID NOT NULL,
    latitud NUMERIC(10, 7) NOT NULL,
    longitud NUMERIC(10, 7) NOT NULL,
    precision_gps_metros NUMERIC(6,2),
    bateria_porcentaje INT,
    is_en_movimiento BOOLEAN,
    fecha_hora_dispositivo TIMESTAMPTZ NOT NULL,

    -- 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_log_ubicaciones_promotores PRIMARY KEY (id),
    CONSTRAINT uq_log_ubicaciones_promotores_empresa_id UNIQUE (empresa_id, id),
    CONSTRAINT fk_log_ubicaciones_promotores_promotor_id FOREIGN KEY (empresa_id, promotor_id) REFERENCES fuerza_ventas.mae_promotores (empresa_id, id) ON DELETE RESTRICT
);

CREATE INDEX IF NOT EXISTS ix_log_ubicaciones_promotores_empresa_promotor ON fuerza_ventas.log_ubicaciones_promotores (empresa_id, promotor_id);
CREATE INDEX IF NOT EXISTS ix_log_ubicaciones_promotores_empresa_activo ON fuerza_ventas.log_ubicaciones_promotores (empresa_id, is_activo);

ALTER TABLE fuerza_ventas.log_ubicaciones_promotores ENABLE ROW LEVEL SECURITY;
CREATE POLICY rls_log_ubicaciones_promotores_tenant_isolation ON fuerza_ventas.log_ubicaciones_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);