feat(expediente): migración 0006 con tabla identificacion y metadatos de documento
Tabla histórica `identificacion` (JSON validado por tipo de persona, nombre de búsqueda, fuente captura o sintética) y en `documento`: sha256, nombre original, tamaño, tipo de contenido, fecha de emisión y subtipo. `cliente` no cambia.
This commit is contained in:
1 parent
fd743e960b
commit
1caceb0e4f
5 files changed
+266
-6
No files matched your search
@@ -0,0 +1,91 @@
|
||||
"""expediente: tabla `identificacion` y metadatos de archivo en `documento`
|
||||
|
||||
Revision ID: 0006
|
||||
Revises: 0005
|
||||
Create Date: 2026-10-07
|
||||
|
||||
Fase 4, PR 1 (expediente):
|
||||
|
||||
- `identificacion`: datos de identificación del Caso de Estudio como JSON validado por Pydantic
|
||||
según el tipo de persona, **histórica** (`valid_from`/`valid_to`): un cambio cierra la fila
|
||||
vigente y abre otra, para que la reconstrucción a una fecha devuelva lo que estaba vigente.
|
||||
`nombre_busqueda` (nombre completo o denominación) sirve a la ficha y al screening.
|
||||
`cliente` no cambia: `fecha_nacimiento`, `estado` y `pais` siguen siendo lo que lee el motor y
|
||||
el servicio de expediente los sincroniza desde la identificación.
|
||||
- `documento`: metadatos del archivo subido (`sha256`, `nombre_original`, `tamano_bytes`,
|
||||
`tipo_contenido`), `fecha_emision` (antigüedad de un comprobante de domicilio) y `subtipo`
|
||||
(subtipo del catálogo `seed/catalogos/tipos_documento.json`). Todas nullable: la tabla no
|
||||
tenía filas antes de esta fase.
|
||||
|
||||
El downgrade elimina las columnas (recreando `documento`, como exige SQLite) y la tabla.
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0006"
|
||||
down_revision: str | None = "0005"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
COLUMNAS_DOCUMENTO = (
|
||||
sa.Column("sha256", sa.String(length=64), nullable=True),
|
||||
sa.Column("nombre_original", sa.String(length=255), nullable=True),
|
||||
sa.Column("tamano_bytes", sa.Integer(), nullable=True),
|
||||
sa.Column("tipo_contenido", sa.String(length=32), nullable=True),
|
||||
sa.Column("fecha_emision", sa.Date(), nullable=True),
|
||||
sa.Column("subtipo", sa.String(length=64), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"identificacion",
|
||||
sa.Column("cliente_id", sa.Integer(), nullable=False),
|
||||
sa.Column("version", sa.Integer(), nullable=False),
|
||||
sa.Column("fuente", sa.String(length=32), nullable=False),
|
||||
sa.Column("nombre_busqueda", sa.String(length=300), nullable=False),
|
||||
sa.Column("datos", sa.JSON(), nullable=False),
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("created_by", sa.String(length=64), nullable=False),
|
||||
sa.Column("tenant_id", sa.Integer(), nullable=False),
|
||||
sa.Column("valid_from", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("valid_to", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.CheckConstraint(
|
||||
"fuente IN ('captura', 'sintetico_anonimizacion')",
|
||||
name=op.f("ck_identificacion_fuente"),
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["cliente_id"], ["cliente.id"], name=op.f("fk_identificacion_cliente_id_cliente")
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id"], ["tenant.id"], name=op.f("fk_identificacion_tenant_id_tenant")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_identificacion")),
|
||||
)
|
||||
with op.batch_alter_table("identificacion", schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_identificacion_cliente_id"), ["cliente_id"], unique=False
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_identificacion_nombre_busqueda"), ["nombre_busqueda"], unique=False
|
||||
)
|
||||
batch_op.create_index(batch_op.f("ix_identificacion_tenant_id"), ["tenant_id"], unique=False)
|
||||
|
||||
# Columnas nullable: SQLite las añade con ALTER TABLE sin recrear la tabla.
|
||||
for columna in COLUMNAS_DOCUMENTO:
|
||||
op.add_column("documento", columna)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("documento", schema=None) as batch_op:
|
||||
for columna in COLUMNAS_DOCUMENTO:
|
||||
batch_op.drop_column(columna.name)
|
||||
with op.batch_alter_table("identificacion", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_identificacion_tenant_id"))
|
||||
batch_op.drop_index(batch_op.f("ix_identificacion_nombre_busqueda"))
|
||||
batch_op.drop_index(batch_op.f("ix_identificacion_cliente_id"))
|
||||
op.drop_table("identificacion")
|
||||
@@ -70,6 +70,7 @@ from app.models.cliente import ( # noqa: E402
|
||||
Cliente,
|
||||
Declaracion,
|
||||
Documento,
|
||||
Identificacion,
|
||||
Participacion,
|
||||
)
|
||||
from app.models.credito import Credito, LoteCarga, Transaccion # noqa: E402
|
||||
@@ -102,6 +103,7 @@ __all__ = [
|
||||
"EvaluacionRiesgo",
|
||||
"EventoCaso",
|
||||
"HistoricoMixin",
|
||||
"Identificacion",
|
||||
"Indicador",
|
||||
"Lista",
|
||||
"LoteCarga",
|
||||
|
||||
+48
-5
@@ -1,4 +1,4 @@
|
||||
"""Expediente único: `cliente`, `documento`, `declaracion`, `participacion`,
|
||||
"""Expediente único: `cliente`, `identificacion`, `documento`, `declaracion`, `participacion`,
|
||||
`beneficiario_controlador`.
|
||||
|
||||
Nombres según la sección 6 del brief, en `snake_case` ASCII (sin acentos ni ñ: `pais`,
|
||||
@@ -6,9 +6,16 @@ Nombres según la sección 6 del brief, en `snake_case` ASCII (sin acentos ni ñ
|
||||
`cliente` (`tipo_persona`); por eso `tercero_id`, `persona_moral_id`, `socio_id` y
|
||||
`persona_fisica_id` apuntan a `cliente.id`.
|
||||
|
||||
Históricas (`valid_from`/`valid_to`): `documento`, `declaracion`, `participacion`,
|
||||
`beneficiario_controlador`. El grado de riesgo vigente NO es columna de `cliente`: es la última
|
||||
`evaluacion_riesgo`.
|
||||
Históricas (`valid_from`/`valid_to`): `identificacion`, `documento`, `declaracion`,
|
||||
`participacion`, `beneficiario_controlador`. El grado de riesgo vigente NO es columna de `cliente`:
|
||||
es la última `evaluacion_riesgo`.
|
||||
|
||||
`identificacion` (migración `0006`) guarda los datos de identificación del Caso de Estudio como
|
||||
JSON validado por Pydantic según el tipo de persona (`app.schemas.expediente`). Es histórica: un
|
||||
cambio cierra la fila vigente y abre otra. Los clientes importados del esquema de CHM no traen
|
||||
identificación; `seed/identidades_sinteticas.py` les da un nombre sintético (`fuente =
|
||||
"sintetico_anonimizacion"`). `fecha_nacimiento`, `estado` y `pais` de `cliente` siguen siendo lo
|
||||
que lee el motor: el servicio de expediente los sincroniza desde la identificación.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
@@ -33,6 +40,7 @@ TIPOS_PERSONA = ("fisica", "moral")
|
||||
PERFILES_ACTIVIDAD = ("A", "B", "C", "D", "E", "F")
|
||||
TIPOS_PARTICIPACION = ("capital", "voto")
|
||||
CRITERIOS_BENEFICIARIO = ("PARTICIPACION_25", "CONTROL", "ADMINISTRADOR")
|
||||
FUENTES_IDENTIFICACION = ("captura", "sintetico_anonimizacion")
|
||||
|
||||
|
||||
class Cliente(ColumnasBaseMixin, TenantMixin, Base):
|
||||
@@ -75,15 +83,50 @@ class Cliente(ColumnasBaseMixin, TenantMixin, Base):
|
||||
estado_relacion: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
|
||||
|
||||
class Identificacion(ColumnasBaseMixin, TenantMixin, HistoricoMixin, Base):
|
||||
"""Datos de identificación (KYC/KYB) del cliente, versionados. Migración `0006`."""
|
||||
|
||||
__tablename__ = "identificacion"
|
||||
__table_args__ = (CheckConstraint(check_in("fuente", FUENTES_IDENTIFICACION), name="fuente"),)
|
||||
|
||||
cliente_id: Mapped[int] = mapped_column(ForeignKey("cliente.id"), nullable=False, index=True)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
|
||||
fuente: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default="captura", comment="captura | sintetico_anonimizacion"
|
||||
)
|
||||
nombre_busqueda: Mapped[str] = mapped_column(
|
||||
String(300),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Nombre completo o denominación; para la ficha y el screening",
|
||||
)
|
||||
datos: Mapped[dict] = mapped_column(
|
||||
JSON, nullable=False, comment="Validado por app.schemas.expediente según tipo_persona"
|
||||
)
|
||||
|
||||
|
||||
class Documento(ColumnasBaseMixin, TenantMixin, HistoricoMixin, Base):
|
||||
__tablename__ = "documento"
|
||||
|
||||
cliente_id: Mapped[int] = mapped_column(ForeignKey("cliente.id"), nullable=False, index=True)
|
||||
tipo: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
vigencia: Mapped[date | None] = mapped_column(Date, nullable=True)
|
||||
ruta: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
ruta: Mapped[str | None] = mapped_column(
|
||||
String(512), nullable=True, comment="Relativa a DATA_DIR: documentos/<cliente_id>/<sha>.ext"
|
||||
)
|
||||
cotejado_por: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
|
||||
# Migración 0006
|
||||
sha256: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
nombre_original: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
tamano_bytes: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
tipo_contenido: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
fecha_emision: Mapped[date | None] = mapped_column(
|
||||
Date, nullable=True, comment="Fecha del documento; mide la antigüedad de un comprobante"
|
||||
)
|
||||
subtipo: Mapped[str | None] = mapped_column(
|
||||
String(64), nullable=True, comment="Subtipo del catálogo (p. ej. credencial_votar)"
|
||||
)
|
||||
|
||||
|
||||
class Declaracion(ColumnasBaseMixin, TenantMixin, HistoricoMixin, Base):
|
||||
|
||||
@@ -12,6 +12,7 @@ from app.models import Base
|
||||
|
||||
RAIZ = Path(__file__).resolve().parents[1]
|
||||
TABLAS_0001 = {"tenant", "usuario", "audit_trail"}
|
||||
TABLAS_0006 = {"identificacion"} # Fase 4: el head ya la incluye
|
||||
TABLAS_0002 = {
|
||||
"cliente",
|
||||
"documento",
|
||||
@@ -64,7 +65,7 @@ def test_upgrade_head_crea_las_25_tablas_y_coincide_con_los_modelos(tmp_path: Pa
|
||||
command.upgrade(_config(url), "head")
|
||||
|
||||
with sa.create_engine(url).connect() as conn:
|
||||
assert _tablas(conn) == TABLAS_0001 | TABLAS_0002
|
||||
assert _tablas(conn) == TABLAS_0001 | TABLAS_0002 | TABLAS_0006
|
||||
assert len(TABLAS_0002) == 22
|
||||
inspector = sa.inspect(conn)
|
||||
for tabla in TABLAS_0002:
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Migración 0006: tabla `identificacion` y metadatos de archivo en `documento`."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
from app.models import Base
|
||||
|
||||
RAIZ = Path(__file__).resolve().parents[1]
|
||||
COLUMNAS_NUEVAS = {
|
||||
"sha256",
|
||||
"nombre_original",
|
||||
"tamano_bytes",
|
||||
"tipo_contenido",
|
||||
"fecha_emision",
|
||||
"subtipo",
|
||||
}
|
||||
|
||||
|
||||
def _config(url: str) -> Config:
|
||||
cfg = Config(str(RAIZ / "alembic.ini"))
|
||||
cfg.set_main_option("sqlalchemy.url", url)
|
||||
return cfg
|
||||
|
||||
|
||||
def _columnas(engine: sa.Engine, tabla: str) -> set[str]:
|
||||
return {c["name"] for c in sa.inspect(engine).get_columns(tabla)}
|
||||
|
||||
|
||||
def test_upgrade_crea_identificacion_y_las_columnas_y_downgrade_las_quita(tmp_path) -> None:
|
||||
url = f"sqlite:///{tmp_path / 'pld.db'}"
|
||||
cfg = _config(url)
|
||||
command.upgrade(cfg, "0005")
|
||||
engine = sa.create_engine(url)
|
||||
assert "identificacion" not in sa.inspect(engine).get_table_names()
|
||||
assert not COLUMNAS_NUEVAS & _columnas(engine, "documento")
|
||||
|
||||
command.upgrade(cfg, "0006")
|
||||
engine.dispose()
|
||||
engine = sa.create_engine(url)
|
||||
inspector = sa.inspect(engine)
|
||||
assert "identificacion" in inspector.get_table_names()
|
||||
assert COLUMNAS_NUEVAS <= _columnas(engine, "documento")
|
||||
columnas = _columnas(engine, "identificacion")
|
||||
assert {
|
||||
"id",
|
||||
"tenant_id",
|
||||
"created_at",
|
||||
"created_by",
|
||||
"valid_from",
|
||||
"valid_to",
|
||||
"cliente_id",
|
||||
"version",
|
||||
"fuente",
|
||||
"nombre_busqueda",
|
||||
"datos",
|
||||
} <= columnas
|
||||
indices = {i["name"] for i in inspector.get_indexes("identificacion")}
|
||||
assert {
|
||||
"ix_identificacion_cliente_id",
|
||||
"ix_identificacion_nombre_busqueda",
|
||||
"ix_identificacion_tenant_id",
|
||||
} <= indices
|
||||
|
||||
# La migración deja la base igual que los modelos (sin diferencias para autogenerate).
|
||||
with engine.connect() as conn:
|
||||
tablas_modelo = set(Base.metadata.tables)
|
||||
tablas_base = set(sa.inspect(conn).get_table_names()) - {"alembic_version"}
|
||||
assert tablas_modelo == tablas_base
|
||||
|
||||
command.downgrade(cfg, "0005")
|
||||
engine.dispose()
|
||||
engine = sa.create_engine(url)
|
||||
assert "identificacion" not in sa.inspect(engine).get_table_names()
|
||||
assert not COLUMNAS_NUEVAS & _columnas(engine, "documento")
|
||||
command.upgrade(cfg, "head")
|
||||
|
||||
|
||||
def test_el_check_de_fuente_rechaza_valores_fuera_del_catalogo(tmp_path) -> None:
|
||||
url = f"sqlite:///{tmp_path / 'pld.db'}"
|
||||
command.upgrade(_config(url), "head")
|
||||
engine = sa.create_engine(url)
|
||||
base = (
|
||||
"created_at, created_by, tenant_id, valid_from, cliente_id, version, fuente, "
|
||||
"nombre_busqueda, datos"
|
||||
)
|
||||
with engine.begin() as conn:
|
||||
tenant = conn.execute(
|
||||
sa.text(
|
||||
"INSERT INTO tenant (created_at, created_by, nombre, regimen, "
|
||||
"actividad_vulnerable, uma_vigente, ventana_meses, fecha_corte) VALUES "
|
||||
"('2026-10-07', 'pytest', 'Demo', "
|
||||
"'LFPIORPI', 'Art. 17', 117.31, 6, '2026-08-31') RETURNING id"
|
||||
)
|
||||
).scalar_one()
|
||||
cliente = conn.execute(
|
||||
sa.text(
|
||||
"INSERT INTO cliente (created_at, created_by, tenant_id, id_externo, tipo_persona) "
|
||||
"VALUES ('2026-10-07', 'pytest', :t, 'X1', 'fisica') RETURNING id"
|
||||
),
|
||||
{"t": tenant},
|
||||
).scalar_one()
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO identificacion ({base}) VALUES ('2026-10-07', 'pytest', :t, "
|
||||
"'2026-10-07', :c, 1, 'captura', 'Ana', '{}')"
|
||||
),
|
||||
{"t": tenant, "c": cliente},
|
||||
)
|
||||
try:
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO identificacion ({base}) VALUES ('2026-10-07', 'pytest', :t, "
|
||||
"'2026-10-07', :c, 2, 'otra', 'Ana', '{}')"
|
||||
),
|
||||
{"t": tenant, "c": cliente},
|
||||
)
|
||||
except sa.exc.IntegrityError as exc:
|
||||
assert "ck_identificacion_fuente" in str(exc)
|
||||
else: # pragma: no cover
|
||||
raise AssertionError("el CHECK de fuente no se aplicó")
|
||||
Reference in new issue
Block a user