Files
collina-pld/tests/test_migracion_0009.py
Jorem Juárez 4030947c53 feat(clientes): un solo servicio de alta con antiduplicados por RFC y CURP
services/clientes.alta_cliente es el único camino de alta (origen
interfaz, importacion, plantado o tercero_declaracion): valida y
normaliza RFC y CURP (formato SAT y RENAPO), rechaza un RFC o una CURP
de otro cliente vigente devolviendo el existente, crea cliente,
identificación, perfil y declaración, evalúa (motivo inicial, T1–T3
proyectados), corre reglas y screening, y deja el origen en el audit
trail. id_externo ALTA-000001 secuencial por tenant, con reintento sobre
el UNIQUE. Alta mínima (socio o tercero sin datos operativos).

Migración 0009: identificacion.rfc y .curp con backfill e índices únicos
parciales entre vigentes; participación vigente única por socio y tipo.
expediente.crear_cliente queda como alias; plantar_casos y el importador
usan el módulo. La ficha nombra a los relacionados por su relación
actual.
2026-10-28 13:09:45 -06:00

91 lines
3.5 KiB
Python

"""Migración 0009: RFC y CURP en `identificacion` (backfill) e índices únicos parciales."""
import json
from pathlib import Path
import pytest
import sqlalchemy as sa
from alembic import command
from alembic.config import Config
RAIZ = Path(__file__).resolve().parents[1]
def _config(url: str) -> Config:
cfg = Config(str(RAIZ / "alembic.ini"))
cfg.set_main_option("sqlalchemy.url", url)
return cfg
def _base_en_0008(tmp_path: Path, identificaciones: list[tuple[int, dict, str | None]]) -> str:
"""Tenant, dos clientes y las identificaciones (cliente 1|2, datos, valid_to)."""
url = f"sqlite:///{tmp_path / 'pld.db'}"
command.upgrade(_config(url), "0008")
engine = sa.create_engine(url)
with engine.begin() as conn:
tenant = conn.execute(
sa.text(
"INSERT INTO tenant (created_at, created_by, nombre, clave, regimen, "
"actividad_vulnerable, uma_vigente, ventana_meses, fecha_corte) VALUES "
"('2026-10-08', 'pytest', 'Demo', 'demo', 'LFPIORPI', 'Art. 17', 117.31, 6, "
"'2026-08-31') RETURNING id"
)
).scalar_one()
ids = [
conn.execute(
sa.text(
"INSERT INTO cliente (created_at, created_by, tenant_id, id_externo, "
"tipo_persona) VALUES ('2026-10-08', 'pytest', :t, :e, 'fisica') RETURNING id"
),
{"t": tenant, "e": f"C{n}"},
).scalar_one()
for n in (1, 2)
]
for cliente, datos, valid_to in identificaciones:
conn.execute(
sa.text(
"INSERT INTO identificacion (created_at, created_by, tenant_id, valid_from, "
"valid_to, cliente_id, version, fuente, nombre_busqueda, datos) VALUES "
"('2026-10-08', 'pytest', :t, '2026-10-08', :vt, :c, 1, 'captura', 'X', :d)"
),
{"t": tenant, "vt": valid_to, "c": ids[cliente - 1], "d": json.dumps(datos)},
)
engine.dispose()
return url
def test_backfill_normaliza_y_crea_los_indices(tmp_path: Path) -> None:
url = _base_en_0008(
tmp_path,
[
(1, {"rfc": " pela 900504ab1", "curp": "pela900504mjcrpn01"}, None),
(2, {"rfc": "", "nombre": "Sin RFC"}, None),
(2, {"rfc": "PELA900504AB1"}, "2026-10-08"), # cerrada: no choca
],
)
command.upgrade(_config(url), "0009")
engine = sa.create_engine(url)
with engine.connect() as conn:
filas = conn.execute(sa.text("SELECT rfc, curp FROM identificacion ORDER BY id")).all()
assert filas == [("PELA900504AB1", "PELA900504MJCRPN01"), (None, None), ("PELA900504AB1", None)]
indices = {i["name"] for i in sa.inspect(engine).get_indexes("identificacion")}
assert {"ux_identificacion_rfc_vigente", "ux_identificacion_curp_vigente"} <= indices
assert "ux_participacion_vigente" in {
i["name"] for i in sa.inspect(engine).get_indexes("participacion")
}
engine.dispose()
command.downgrade(_config(url), "0008")
engine = sa.create_engine(url)
columnas = {c["name"] for c in sa.inspect(engine).get_columns("identificacion")}
assert not {"rfc", "curp"} & columnas
engine.dispose()
def test_duplicados_vigentes_detienen_la_migracion(tmp_path: Path) -> None:
url = _base_en_0008(
tmp_path, [(1, {"rfc": "PELA900504AB1"}, None), (2, {"rfc": "pela900504ab1"}, None)]
)
with pytest.raises(RuntimeError, match="RFC duplicados"):
command.upgrade(_config(url), "0009")