Saltar a contenido

Especificación Técnica: cat_incoterms

Esquema: clientes
Base de Datos: crm
Tabla Legacy Origen: i746t_incoterm (co_incoterm, tx_incoterm)
Propósito: Términos estándar internacionales para operaciones de exportación y despacho comercial (EXW, FOB, CIF, CFR, DDP, DAP).


1. Justificación y Mejoras de Arquitectura

  • Estandariza catálogos tipados con UUID, multitenancy RLS por empresa y claves únicas de código de negocio, eliminando cadenas sueltas y tablas desnormalizadas.
  • Multi-tenancy RLS y Auditoría Estándar: Cada tabla incluye empresa_id BIGINT NOT NULL, utilizado para el aislamiento multiempresa mediante políticas RLS y como identificador de la empresa en core.identidad. Además, incorpora trazabilidad mediante created_at, updated_at, deleted_at, created_by, updated_by y version.
  • Eliminación de campos legacy: Se elimina codigo_legacy, delegando su manejo al mapeo de migración.

2. Definiciones de Implementación

Table clientes.cat_incoterms {
    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)']
    codigo          varchar(10)   [not null, note: 'Código estándar Incoterm (p. ej. FOB, CIF)']
    nombre          varchar(100)  [not null, note: 'Nombre completo del término']
    descripcion     varchar(255)  [note: 'Alcance de responsabilidades y flete']

    // 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_cat_incoterms_empresa_id']
        (empresa_id, codigo) [unique, name: 'uq_cat_incoterms_empresa_codigo']
        (empresa_id, is_activo) [name: 'ix_cat_incoterms_empresa_activo']
    }
}
CREATE TABLE IF NOT EXISTS clientes.cat_incoterms (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    codigo VARCHAR(10) NOT NULL,
    nombre VARCHAR(100) NOT NULL,
    descripcion VARCHAR(255),

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

    CONSTRAINT uq_cat_incoterms_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_cat_incoterms_empresa_codigo
        UNIQUE (empresa_id, codigo)
);

CREATE INDEX IF NOT EXISTS ix_cat_incoterms_empresa_activo
    ON clientes.cat_incoterms (empresa_id, is_activo);

COMMENT ON TABLE clientes.cat_incoterms IS
    'Términos Internacionales de Comercio (Incoterms): Términos estándar internacionales para operaciones de exportación y despacho comercial (EXW, FOB, CIF, CFR, DDP, DAP).';

COMMENT ON COLUMN clientes.cat_incoterms.id IS
    'Identificador único UUID';

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

COMMENT ON COLUMN clientes.cat_incoterms.codigo IS
    'Código estándar Incoterm (p. ej. FOB, CIF)';

COMMENT ON COLUMN clientes.cat_incoterms.nombre IS
    'Nombre completo del término';

COMMENT ON COLUMN clientes.cat_incoterms.descripcion IS
    'Alcance de responsabilidades y flete';

COMMENT ON COLUMN clientes.cat_incoterms.is_activo IS
    'Estado lógico del registro';

COMMENT ON COLUMN clientes.cat_incoterms.created_at IS
    'Fecha de creación';

COMMENT ON COLUMN clientes.cat_incoterms.updated_at IS
    'Fecha de última actualización';

COMMENT ON COLUMN clientes.cat_incoterms.deleted_at IS
    'Fecha de eliminación lógica';

COMMENT ON COLUMN clientes.cat_incoterms.created_by IS
    'Usuario creador';

COMMENT ON COLUMN clientes.cat_incoterms.updated_by IS
    'Usuario modificador';

ALTER TABLE clientes.cat_incoterms
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_cat_incoterms_empresa
    ON clientes.cat_incoterms
    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 typing import Optional

from sqlalchemy import (
    BigInteger,
    Boolean,
    Index,
    String,
    UniqueConstraint,
    text,
)
from sqlalchemy.dialects.postgresql import TIMESTAMPTZ, UUID
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base


class CatIncoterms(Base):
    """
    Términos Internacionales de Comercio (Incoterms).

    Términos estándar internacionales para operaciones de exportación
    y despacho comercial (EXW, FOB, CIF, CFR, DDP, DAP).

    Legacy:
        i746t_incoterm (co_incoterm, tx_incoterm)
    """

    __tablename__ = "cat_incoterms"

    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_cat_incoterms_empresa_id",
        ),
        UniqueConstraint(
            "empresa_id",
            "codigo",
            name="uq_cat_incoterms_empresa_codigo",
        ),
        Index(
            "ix_cat_incoterms_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        {
            "schema": "clientes",
            "comment": "Términos Internacionales de Comercio (Incoterms)",
        },
    )

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

    codigo: Mapped[str] = mapped_column(
        String(10),
        nullable=False,
        comment="Código estándar Incoterm (p. ej. FOB, CIF)",
    )

    nombre: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        comment="Nombre completo del término",
    )

    descripcion: Mapped[Optional[str]] = mapped_column(
        String(255),
        nullable=True,
        comment="Alcance de responsabilidades y flete",
    )

    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 cat_incoterms

Revision ID: 0010
Revises: 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 = "0010"
down_revision: Union[str, Sequence[str], None] = "0009"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:

    op.create_table(
        "cat_incoterms",

        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(
            "codigo",
            sa.String(length=10),
            nullable=False,
            comment="Código estándar Incoterm (p. ej. FOB, CIF)",
        ),

        sa.Column(
            "nombre",
            sa.String(length=100),
            nullable=False,
            comment="Nombre completo del término",
        ),

        sa.Column(
            "descripcion",
            sa.String(length=255),
            nullable=True,
            comment="Alcance de responsabilidades y flete",
        ),

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

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

        sa.UniqueConstraint(
            "empresa_id",
            "codigo",
            name="uq_cat_incoterms_empresa_codigo",
        ),

        comment="Términos Internacionales de Comercio (Incoterms)",
        schema="clientes",
    )

    op.create_index(
        "ix_cat_incoterms_empresa_activo",
        "cat_incoterms",
        ["empresa_id", "is_activo"],
        unique=False,
        schema="clientes",
    )

    op.execute(
        """
        ALTER TABLE clientes.cat_incoterms
        ENABLE ROW LEVEL SECURITY;
        """
    )

    op.execute(
        """
        CREATE POLICY rls_cat_incoterms_empresa
        ON clientes.cat_incoterms
        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_cat_incoterms_empresa
        ON clientes.cat_incoterms;
        """
    )

    op.execute(
        """
        ALTER TABLE clientes.cat_incoterms
        DISABLE ROW LEVEL SECURITY;
        """
    )

    op.drop_index(
        "ix_cat_incoterms_empresa_activo",
        table_name="cat_incoterms",
        schema="clientes",
    )

    op.drop_table(
        "cat_incoterms",
        schema="clientes",
    )