Saltar a contenido

Especificación Técnica: trx_pedidos_detalle

Esquema: fuerza_ventas
Base de Datos: crm
Tabla Legacy Origen: c066t_detalle_pedido
Propósito: Desglose ítem por ítem de los productos solicitados en el pedido, con alta precisión decimal en precio unitario (NUMERIC(14,4)), cantidades fraccionables (NUMERIC(12,4)) y cálculo tributario de descuentos e impuestos.


1. Justificación y Mejoras de Arquitectura

  • Precisión Numérica Extendida: Incorpora precio_unitario NUMERIC(14,4) y cantidades NUMERIC(12,4) para evitar errores de redondeo en operaciones de mayoreo y conversión de unidades comerciales.
  • Integridad Referencial Compuesta Multi-Tenant: Clave única compuesta (empresa_id, id) y clave foránea compuesta (empresa_id, pedido_id) hacia fuerza_ventas.trx_pedidos(empresa_id, id) con eliminación en cascada (ON DELETE CASCADE).
  • Integración Desacoplada de Inventario: Los campos producto_id y almacen_id correlacionan lógicamente con el módulo de inventarios/operaciones del ERP mediante identificadores UUID sin claves foráneas físicas entre microservicios.
  • Aislamiento Multi-Tenant (RLS): Integra empresa_id BIGINT NOT NULL con políticas RLS obligatorias (USING y WITH CHECK).
  • Unicidad de Líneas de Pedido: Restricción UNIQUE (empresa_id, pedido_id, numero_linea) para garantizar la correlación secuencial ordenada de cada renglón comercial.
  • 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.trx_pedidos_detalle {
    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)']
    pedido_id             uuid          [not null, note: 'Cabecera de la orden de pedido asociada']
    numero_linea          int           [not null, note: 'Número secuencial de renglón (1, 2, 3...)']
    producto_id           uuid          [not null, note: 'Correlación lógica con operaciones.mae_productos (sin FK física)']
    almacen_id            uuid          [not null, note: 'Correlación lógica con operaciones.mae_almacenes (sin FK física)']
    cantidad_pedida       numeric(12,4) [not null, note: 'Cantidad ordenada en unidad base']
    cantidad_aprobada     numeric(12,4) [not null, note: 'Cantidad autorizada por crédito e inventario']
    cantidad_despachada   numeric(12,4) [not null, default: `0.0000`, note: 'Cantidad despachada real acumulada']
    precio_unitario       numeric(14,4) [not null, note: 'Precio unitario pactado con 4 decimales de precisión']
    porcentaje_descuento  numeric(5,2)  [not null, default: `0.00`, note: 'Porcentaje de descuento otorgado']
    monto_descuento_linea numeric(12,2) [not null, default: `0.00`, note: 'Monto monetario de descuento en la línea']
    monto_impuesto_linea  numeric(12,2) [not null, default: `0.00`, note: 'Monto de tributos aplicables a la línea']
    monto_total_linea     numeric(12,2) [not null, note: 'Importe neto final de la línea']

    // 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_trx_pedidos_det_empresa_id']
        (empresa_id, pedido_id, numero_linea) [unique, name: 'uq_trx_pedidos_det_empresa_pedido_linea']
        (empresa_id, is_activo) [name: 'ix_trx_pedidos_det_empresa_activo']
        (empresa_id, pedido_id) [name: 'ix_trx_pedidos_det_empresa_pedido']
        (empresa_id, producto_id) [name: 'ix_trx_pedidos_det_empresa_producto']
        (empresa_id, almacen_id) [name: 'ix_trx_pedidos_det_empresa_almacen']
    }
}

Ref: fuerza_ventas.trx_pedidos_detalle.(empresa_id, pedido_id) > fuerza_ventas.trx_pedidos.(empresa_id, id) [delete: cascade]
CREATE TABLE IF NOT EXISTS fuerza_ventas.trx_pedidos_detalle (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    pedido_id UUID NOT NULL,
    numero_linea INT NOT NULL,
    producto_id UUID NOT NULL,
    almacen_id UUID NOT NULL,
    cantidad_pedida NUMERIC(12,4) NOT NULL,
    cantidad_aprobada NUMERIC(12,4) NOT NULL,
    cantidad_despachada NUMERIC(12,4) NOT NULL DEFAULT 0.0000,
    precio_unitario NUMERIC(14,4) NOT NULL,
    porcentaje_descuento NUMERIC(5,2) NOT NULL DEFAULT 0.00,
    monto_descuento_linea NUMERIC(12,2) NOT NULL DEFAULT 0.00,
    monto_impuesto_linea NUMERIC(12,2) NOT NULL DEFAULT 0.00,
    monto_total_linea NUMERIC(12,2) 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_trx_pedidos_detalle
        PRIMARY KEY (id),

    CONSTRAINT uq_trx_pedidos_det_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_trx_pedidos_det_empresa_pedido_linea
        UNIQUE (empresa_id, pedido_id, numero_linea),

    CONSTRAINT fk_trx_pedidos_det_pedido
        FOREIGN KEY (empresa_id, pedido_id)
        REFERENCES fuerza_ventas.trx_pedidos (empresa_id, id)
        ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS ix_trx_pedidos_det_empresa_activo
    ON fuerza_ventas.trx_pedidos_detalle (empresa_id, is_activo);

CREATE INDEX IF NOT EXISTS ix_trx_pedidos_det_empresa_pedido
    ON fuerza_ventas.trx_pedidos_detalle (empresa_id, pedido_id);

CREATE INDEX IF NOT EXISTS ix_trx_pedidos_det_empresa_producto
    ON fuerza_ventas.trx_pedidos_detalle (empresa_id, producto_id);

CREATE INDEX IF NOT EXISTS ix_trx_pedidos_det_empresa_almacen
    ON fuerza_ventas.trx_pedidos_detalle (empresa_id, almacen_id);

COMMENT ON TABLE fuerza_ventas.trx_pedidos_detalle IS
    'Líneas de Detalle de Órdenes de Pedido: Desglose ítem por ítem de los productos solicitados en el pedido, con alta precisión en precio unitario (NUMERIC(14,4)) y descuentos.';

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

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

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.pedido_id IS
    'Cabecera de la orden de pedido asociada';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.numero_linea IS
    'Número secuencial de renglón (1, 2, 3...)';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.producto_id IS
    'Correlación lógica con operaciones.mae_productos (sin FK física)';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.almacen_id IS
    'Correlación lógica con operaciones.mae_almacenes (sin FK física)';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.cantidad_pedida IS
    'Cantidad ordenada en unidad base';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.cantidad_aprobada IS
    'Cantidad autorizada por crédito e inventario';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.cantidad_despachada IS
    'Cantidad despachada real acumulada';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.precio_unitario IS
    'Precio unitario pactado con 4 decimales de precisión';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.porcentaje_descuento IS
    'Porcentaje de descuento otorgado';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.monto_descuento_linea IS
    'Monto monetario de descuento en la línea';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.monto_impuesto_linea IS
    'Monto de tributos aplicables a la línea';

COMMENT ON COLUMN fuerza_ventas.trx_pedidos_detalle.monto_total_linea IS
    'Importe neto final de la línea';

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

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

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

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

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

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

ALTER TABLE fuerza_ventas.trx_pedidos_detalle
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_trx_pedidos_det_empresa
    ON fuerza_ventas.trx_pedidos_detalle
    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
    );