Saltar a contenido

Especificación Técnica: cat_metodos_pago

Esquema: clientes
Base de Datos: crm
Tabla Legacy Origen: i135t_metodo_pago (co_metodo_pago, tx_metodo_pago)
Propósito: Instrumentos monetarios válidos para transacciones y recaudación en campo (Efectivo, Cheque al Día, Cheque Posfechado, Transferencia Bancaria, Tarjeta de Débito/Crédito, Depósito).


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 remueve codigo_legacy, desacoplando la estructura relacional de identificadores históricos.

2. Definiciones de Implementación

Table clientes.cat_metodos_pago {
    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(30)   [not null, note: 'Código único de negocio del método de pago']
    nombre                  varchar(100)  [not null, note: 'Nombre del método de pago']
    is_requiere_referencia  boolean       [not null, default: `false`, note: 'Indica si exige número de comprobante o cheque']
    is_requiere_banco       boolean       [not null, default: `false`, note: 'Indica si exige selección de banco origen']
    descripcion             varchar(255)  [note: 'Descripción operativa del método']

    // 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_metodos_pago_empresa_id']
        (empresa_id, codigo) [unique, name: 'uq_cat_metodos_pago_empresa_codigo']
        (empresa_id, is_activo) [name: 'ix_cat_metodos_pago_empresa_activo']
    }
}
CREATE TABLE IF NOT EXISTS clientes.cat_metodos_pago (
    id UUID NOT NULL DEFAULT gen_random_uuid(),
    empresa_id BIGINT NOT NULL,
    codigo VARCHAR(30) NOT NULL,
    nombre VARCHAR(100) NOT NULL,
    is_requiere_referencia BOOLEAN NOT NULL DEFAULT false,
    is_requiere_banco BOOLEAN NOT NULL DEFAULT false,
    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_metodos_pago
        PRIMARY KEY (id),

    CONSTRAINT uq_cat_metodos_pago_empresa_id
        UNIQUE (empresa_id, id),

    CONSTRAINT uq_cat_metodos_pago_empresa_codigo
        UNIQUE (empresa_id, codigo)
);

CREATE INDEX IF NOT EXISTS ix_cat_metodos_pago_empresa_activo
    ON clientes.cat_metodos_pago (empresa_id, is_activo);

COMMENT ON TABLE clientes.cat_metodos_pago IS
    'Métodos de Pago: Instrumentos monetarios válidos para transacciones y recaudación en campo (Efectivo, Cheque al Día, Cheque Posfechado, Transferencia Bancaria, Tarjeta de Débito/Crédito, Depósito).';

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

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

COMMENT ON COLUMN clientes.cat_metodos_pago.codigo IS
    'Código único de negocio del método de pago';

COMMENT ON COLUMN clientes.cat_metodos_pago.nombre IS
    'Nombre del método de pago';

COMMENT ON COLUMN clientes.cat_metodos_pago.is_requiere_referencia IS
    'Indica si exige número de comprobante o cheque';

COMMENT ON COLUMN clientes.cat_metodos_pago.is_requiere_banco IS
    'Indica si exige selección de banco origen';

COMMENT ON COLUMN clientes.cat_metodos_pago.descripcion IS
    'Descripción operativa del método';

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

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

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

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

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

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

ALTER TABLE clientes.cat_metodos_pago
    ENABLE ROW LEVEL SECURITY;

CREATE POLICY rls_cat_metodos_pago_empresa
    ON clientes.cat_metodos_pago
    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 CatMetodosPago(Base):
    """
    Métodos de Pago.

    Instrumentos monetarios válidos para transacciones y recaudación en campo
    (Efectivo, Cheque al Día, Cheque Posfechado, Transferencia Bancaria,
    Tarjeta de Débito/Crédito, Depósito).

    Legacy:
        i135t_metodo_pago (co_metodo_pago, tx_metodo_pago)
    """

    __tablename__ = "cat_metodos_pago"

    __table_args__ = (
        UniqueConstraint(
            "empresa_id",
            "id",
            name="uq_cat_metodos_pago_empresa_id",
        ),
        UniqueConstraint(
            "empresa_id",
            "codigo",
            name="uq_cat_metodos_pago_empresa_codigo",
        ),
        Index(
            "ix_cat_metodos_pago_empresa_activo",
            "empresa_id",
            "is_activo",
        ),
        {
            "schema": "clientes",
            "comment": "Métodos de Pago",
        },
    )

    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(30),
        nullable=False,
        comment="Código único de negocio del método de pago",
    )

    nombre: Mapped[str] = mapped_column(
        String(100),
        nullable=False,
        comment="Nombre del método de pago",
    )

    is_requiere_referencia: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("false"),
        comment="Indica si exige número de comprobante o cheque",
    )

    is_requiere_banco: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default=text("false"),
        comment="Indica si exige selección de banco origen",
    )

    descripcion: Mapped[Optional[str]] = mapped_column(
        String(255),
        nullable=True,
        comment="Descripción operativa del método",
    )

    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_metodos_pago

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


def upgrade() -> None:

    op.create_table(
        "cat_metodos_pago",

        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=30),
            nullable=False,
            comment="Código único de negocio del método de pago",
        ),

        sa.Column(
            "nombre",
            sa.String(length=100),
            nullable=False,
            comment="Nombre del método de pago",
        ),

        sa.Column(
            "is_requiere_referencia",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("false"),
            comment="Indica si exige número de comprobante o cheque",
        ),

        sa.Column(
            "is_requiere_banco",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("false"),
            comment="Indica si exige selección de banco origen",
        ),

        sa.Column(
            "descripcion",
            sa.String(length=255),
            nullable=True,
            comment="Descripción operativa del método",
        ),

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

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

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

        comment="Métodos de Pago",
        schema="clientes",
    )

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

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

    op.execute(
        """
        CREATE POLICY rls_cat_metodos_pago_empresa
        ON clientes.cat_metodos_pago
        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_metodos_pago_empresa
        ON clientes.cat_metodos_pago;
        """
    )

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

    op.drop_index(
        "ix_cat_metodos_pago_empresa_activo",
        table_name="cat_metodos_pago",
        schema="clientes",
    )

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