Especificación Técnica: mae_documentos_cliente¶
Esquema: clientes
Base de Datos: crm
Tabla Legacy Origen: i287t_documentos_cliente (613 MB bytea eliminados)
Propósito: Expediente digital de documentos mercantiles y legales (RUC, Cédula Representante, Contrato de Crédito, Pagaré, Permisos) almacenados en Object Storage (S3 / MinIO).
1. Justificación y Mejoras de Arquitectura¶
- Desacoplamiento de Binarios (Blob Offloading): Elimina el almacenamiento de blobs (
bytea) dentro del motor PostgreSQL, reemplazándolo por metadatos, URLs seguras de almacenamiento en MinIO/S3 y cálculo de hash de integridad SHA-256. - Aislamiento Multi-Tenant (RLS): Integra
empresa_id BIGINT NOT NULLcon políticas RLS obligatorias. - Integridad Referencial Compuesta: FK compuesta
(empresa_id, cliente_id)haciaclientes.mae_clientes(empresa_id, id)con borrado en cascada. - 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 clientes.mae_documentos_cliente {
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)']
cliente_id uuid [not null, note: 'Cliente titular del expediente digital']
tipo_documento_id uuid [not null, note: 'Tipo de documento (FK cat_tipos_documento_cliente)']
nombre_archivo varchar(255) [not null, note: 'Nombre del archivo original']
url_almacenamiento varchar(500) [not null, note: 'URL o URI de almacenamiento en S3/MinIO']
mime_type varchar(100) [not null, note: 'Tipo de contenido MIME (ej. application/pdf)']
tamano_bytes bigint [not null, note: 'Tamaño del archivo en bytes']
hash_sha256 varchar(64) [note: 'Hash criptográfico SHA-256 para verificación de integridad']
fecha_emision date [note: 'Fecha de emisión del documento legal']
fecha_vencimiento date [note: 'Fecha de caducidad del documento']
is_verificado boolean [not null, default: `false`, note: 'Indica si fue verificado por el área legal o de créditos']
// 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_documentos_cliente_empresa_id']
(empresa_id, is_activo) [name: 'ix_mae_documentos_cliente_empresa_activo']
(empresa_id, cliente_id, tipo_documento) [name: 'ix_mae_documentos_cliente_empresa_tipo']
(empresa_id, fecha_vencimiento) [name: 'ix_mae_documentos_cliente_empresa_venc']
}
}
Ref: clientes.mae_documentos_cliente.(empresa_id, cliente_id) > clientes.mae_clientes.(empresa_id, id) [delete: cascade]
Ref: clientes.mae_documentos_cliente.(empresa_id, tipo_documento_id) > clientes.cat_tipos_documento_cliente.(empresa_id, id)
CREATE TABLE IF NOT EXISTS clientes.mae_documentos_cliente (
id UUID NOT NULL DEFAULT gen_random_uuid(),
empresa_id BIGINT NOT NULL,
cliente_id UUID NOT NULL,
tipo_documento_id UUID NOT NULL,
nombre_archivo VARCHAR(255) NOT NULL,
url_almacenamiento VARCHAR(500) NOT NULL,
mime_type VARCHAR(100) NOT NULL,
tamano_bytes BIGINT NOT NULL,
hash_sha256 VARCHAR(64),
fecha_emision DATE,
fecha_vencimiento DATE,
is_verificado BOOLEAN NOT NULL DEFAULT false,
-- 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_documentos_cliente
PRIMARY KEY (id),
CONSTRAINT uq_mae_documentos_cliente_empresa_id
UNIQUE (empresa_id, id),
CONSTRAINT fk_mae_documentos_cliente_mae_clientes
FOREIGN KEY (empresa_id, cliente_id)
REFERENCES clientes.mae_clientes (empresa_id, id)
ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS ix_mae_documentos_cliente_empresa_activo
ON clientes.mae_documentos_cliente (empresa_id, is_activo);
CREATE INDEX IF NOT EXISTS ix_mae_documentos_cliente_empresa_tipo
ON clientes.mae_documentos_cliente (empresa_id, cliente_id, tipo_documento_id);
CREATE INDEX IF NOT EXISTS ix_mae_documentos_cliente_empresa_venc
ON clientes.mae_documentos_cliente (empresa_id, fecha_vencimiento);
COMMENT ON TABLE clientes.mae_documentos_cliente IS
'Documentos Digitales del Cliente: Expediente digital de documentos mercantiles y legales almacenados en Object Storage.';
COMMENT ON COLUMN clientes.mae_documentos_cliente.id IS
'Identificador único UUID';
COMMENT ON COLUMN clientes.mae_documentos_cliente.empresa_id IS
'Identificador UUID de la empresa en core.identidad (RLS)';
COMMENT ON COLUMN clientes.mae_documentos_cliente.cliente_id IS
'Cliente titular del expediente digital';
COMMENT ON COLUMN clientes.mae_documentos_cliente.tipo_documento_id IS
'Tipo de documento legal/comercial (FK cat_tipos_documento_cliente)';
COMMENT ON COLUMN clientes.mae_documentos_cliente.nombre_archivo IS
'Nombre del archivo original';
COMMENT ON COLUMN clientes.mae_documentos_cliente.url_almacenamiento IS
'URL o URI de almacenamiento en S3/MinIO';
COMMENT ON COLUMN clientes.mae_documentos_cliente.mime_type IS
'Tipo de contenido MIME (ej. application/pdf)';
COMMENT ON COLUMN clientes.mae_documentos_cliente.tamano_bytes IS
'Tamaño del archivo en bytes';
COMMENT ON COLUMN clientes.mae_documentos_cliente.hash_sha256 IS
'Hash criptográfico SHA-256 para verificación de integridad';
COMMENT ON COLUMN clientes.mae_documentos_cliente.fecha_emision IS
'Fecha de emisión del documento legal';
COMMENT ON COLUMN clientes.mae_documentos_cliente.fecha_vencimiento IS
'Fecha de caducidad del documento';
COMMENT ON COLUMN clientes.mae_documentos_cliente.is_verificado IS
'Indica si fue verificado por el área legal o de créditos';
COMMENT ON COLUMN clientes.mae_documentos_cliente.is_activo IS
'Estado lógico del registro';
COMMENT ON COLUMN clientes.mae_documentos_cliente.created_at IS
'Fecha de creación';
COMMENT ON COLUMN clientes.mae_documentos_cliente.updated_at IS
'Fecha de última actualización';
COMMENT ON COLUMN clientes.mae_documentos_cliente.deleted_at IS
'Fecha de eliminación lógica';
COMMENT ON COLUMN clientes.mae_documentos_cliente.created_by IS
'Usuario creador';
COMMENT ON COLUMN clientes.mae_documentos_cliente.updated_by IS
'Usuario modificador';
ALTER TABLE clientes.mae_documentos_cliente
ENABLE ROW LEVEL SECURITY;
CREATE POLICY rls_mae_documentos_cliente_empresa
ON clientes.mae_documentos_cliente
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 date, datetime
from typing import Optional
from sqlalchemy import (
BigInteger,
Boolean,
Date,
ForeignKeyConstraint,
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 MaeDocumentosCliente(Base):
"""
Documentos Digitales del Cliente.
Expediente digital de documentos mercantiles y legales (RUC, Cédula Representante,
Contrato de Crédito, Pagaré) almacenados en MinIO/S3.
Legacy:
i287t_documentos_cliente
"""
__tablename__ = "mae_documentos_cliente"
__table_args__ = (
UniqueConstraint(
"empresa_id",
"id",
name="uq_mae_documentos_cliente_empresa_id",
),
ForeignKeyConstraint(
["empresa_id", "cliente_id"],
["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
ondelete="CASCADE",
name="fk_mae_documentos_cliente_mae_clientes",
),
Index(
"ix_mae_documentos_cliente_empresa_activo",
"empresa_id",
"is_activo",
),
Index(
"ix_mae_documentos_cliente_empresa_tipo",
"empresa_id",
"cliente_id",
"tipo_documento",
),
Index(
"ix_mae_documentos_cliente_empresa_venc",
"empresa_id",
"fecha_vencimiento",
),
{
"schema": "clientes",
"comment": "Documentos Digitales del Cliente",
},
)
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)",
)
cliente_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
nullable=False,
comment="Cliente titular del expediente digital",
)
tipo_documento_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
nullable=False,
comment="Tipo de documento (FK cat_tipos_documento_cliente)",
)
nombre_archivo: Mapped[str] = mapped_column(
String(255),
nullable=False,
comment="Nombre del archivo original",
)
url_almacenamiento: Mapped[str] = mapped_column(
String(500),
nullable=False,
comment="URL o URI de almacenamiento en S3/MinIO",
)
mime_type: Mapped[str] = mapped_column(
String(100),
nullable=False,
comment="Tipo de contenido MIME (ej. application/pdf)",
)
tamano_bytes: Mapped[int] = mapped_column(
BigInteger,
nullable=False,
comment="Tamaño del archivo en bytes",
)
hash_sha256: Mapped[Optional[str]] = mapped_column(
String(64),
nullable=True,
comment="Hash criptográfico SHA-256 para verificación de integridad",
)
fecha_emision: Mapped[Optional[date]] = mapped_column(
Date,
nullable=True,
comment="Fecha de emisión del documento legal",
)
fecha_vencimiento: Mapped[Optional[date]] = mapped_column(
Date,
nullable=True,
comment="Fecha de caducidad del documento",
)
is_verificado: Mapped[bool] = mapped_column(
Boolean,
nullable=False,
server_default=text("false"),
comment="Indica si fue verificado por el área legal o de créditos",
)
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 mae_documentos_cliente
Revision ID: mae_0007
Revises: mae_0006
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 = "mae_0007"
down_revision: Union[str, Sequence[str], None] = "mae_0006"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"mae_documentos_cliente",
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(
"cliente_id",
postgresql.UUID(as_uuid=True),
nullable=False,
comment="Cliente titular del expediente digital",
),
sa.Column(
"tipo_documento_id",
postgresql.UUID(as_uuid=True),
nullable=False,
comment="Tipo de documento (FK cat_tipos_documento_cliente)",
),
sa.Column(
"nombre_archivo",
sa.String(length=255),
nullable=False,
comment="Nombre del archivo original",
),
sa.Column(
"url_almacenamiento",
sa.String(length=500),
nullable=False,
comment="URL o URI de almacenamiento en S3/MinIO",
),
sa.Column(
"mime_type",
sa.String(length=100),
nullable=False,
comment="Tipo de contenido MIME (ej. application/pdf)",
),
sa.Column(
"tamano_bytes",
sa.BigInteger(),
nullable=False,
comment="Tamaño del archivo en bytes",
),
sa.Column(
"hash_sha256",
sa.String(length=64),
nullable=True,
comment="Hash criptográfico SHA-256 para verificación de integridad",
),
sa.Column(
"fecha_emision",
sa.Date(),
nullable=True,
comment="Fecha de emisión del documento legal",
),
sa.Column(
"fecha_vencimiento",
sa.Date(),
nullable=True,
comment="Fecha de caducidad del documento",
),
sa.Column(
"is_verificado",
sa.Boolean(),
nullable=False,
server_default=sa.text("false"),
comment="Indica si fue verificado por el área legal o de créditos",
),
# 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_mae_documentos_cliente",
),
sa.UniqueConstraint(
"empresa_id",
"id",
name="uq_mae_documentos_cliente_empresa_id",
),
sa.ForeignKeyConstraint(
["empresa_id", "cliente_id"],
["clientes.mae_clientes.empresa_id", "clientes.mae_clientes.id"],
ondelete="CASCADE",
name="fk_mae_documentos_cliente_mae_clientes",
),
comment="Documentos Digitales del Cliente",
schema="clientes",
)
op.create_index(
"ix_mae_documentos_cliente_empresa_activo",
"mae_documentos_cliente",
["empresa_id", "is_activo"],
unique=False,
schema="clientes",
)
op.create_index(
"ix_mae_documentos_cliente_empresa_tipo",
"mae_documentos_cliente",
["empresa_id", "cliente_id", "tipo_documento_id"],
unique=False,
schema="clientes",
)
op.create_index(
"ix_mae_documentos_cliente_empresa_venc",
"mae_documentos_cliente",
["empresa_id", "fecha_vencimiento"],
unique=False,
schema="clientes",
)
op.execute(
"""
ALTER TABLE clientes.mae_documentos_cliente
ENABLE ROW LEVEL SECURITY;
"""
)
op.execute(
"""
CREATE POLICY rls_mae_documentos_cliente_empresa
ON clientes.mae_documentos_cliente
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_mae_documentos_cliente_empresa
ON clientes.mae_documentos_cliente;
"""
)
op.execute(
"""
ALTER TABLE clientes.mae_documentos_cliente
DISABLE ROW LEVEL SECURITY;
"""
)
op.drop_index(
"ix_mae_documentos_cliente_empresa_venc",
table_name="mae_documentos_cliente",
schema="clientes",
)
op.drop_index(
"ix_mae_documentos_cliente_empresa_tipo",
table_name="mae_documentos_cliente",
schema="clientes",
)
op.drop_index(
"ix_mae_documentos_cliente_empresa_activo",
table_name="mae_documentos_cliente",
schema="clientes",
)
op.drop_table(
"mae_documentos_cliente",
schema="clientes",
)