115 lines
4.0 KiB
Python
115 lines
4.0 KiB
Python
"""Nombres sintéticos de la cartera importada (Pieza J; antes en `seed/identidades_sinteticas`).
|
|
|
|
El esquema de origen no trae nombres. Para que la cartera se lea y el screening tenga sobre qué
|
|
correr, cada cliente importado recibe una identificación con nombre y apellidos de
|
|
`Faker("es_MX")` sembrado con su `id_externo` (que a su vez sale del hash con la sal fija): misma
|
|
sal, mismo `id_externo`, mismo nombre en cualquier base. `fuente = "sintetico_anonimizacion"` y
|
|
**solo** campos de nombre (sin CURP, RFC ni domicilio). El esquema no trae género: es libre.
|
|
|
|
`asignar_nombres_sinteticos` es idempotente (quien ya tiene identificación no se toca; las altas
|
|
`ALTA-…` y los plantados `PLANT-…` nunca reciben uno) y deja **una** fila de audit trail por
|
|
ejecución, no una por cliente. La llama el importador del esquema al cargar y el comando
|
|
`python -m seed.identidades_sinteticas` para la cartera ya importada. No hace commit.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
from dataclasses import dataclass
|
|
|
|
from faker import Faker
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import audit
|
|
from app.models import Cliente, Identificacion, Tenant, ahora_utc
|
|
from app.schemas.expediente import validar_identificacion
|
|
|
|
FUENTE_SINTETICA = "sintetico_anonimizacion"
|
|
PREFIJOS_CAPTURADOS = ("ALTA-", "PLANT-") # altas a mano y casos plantados: nombre propio
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class NombreSintetico:
|
|
nombre: str
|
|
apellido_paterno: str
|
|
apellido_materno: str
|
|
|
|
|
|
def semilla_de(id_externo: str) -> int:
|
|
return int(hashlib.sha256(id_externo.encode("utf-8")).hexdigest()[:16], 16)
|
|
|
|
|
|
def nombre_sintetico(id_externo: str) -> NombreSintetico:
|
|
"""Nombre y apellidos deterministas para un `id_externo`."""
|
|
faker = Faker("es_MX")
|
|
faker.seed_instance(semilla_de(id_externo))
|
|
return NombreSintetico(
|
|
nombre=faker.first_name(),
|
|
apellido_paterno=faker.last_name(),
|
|
apellido_materno=faker.last_name(),
|
|
)
|
|
|
|
|
|
def asignar_nombres_sinteticos(
|
|
session: Session,
|
|
tenant: Tenant,
|
|
usuario: str,
|
|
*,
|
|
motivo: str,
|
|
cliente_ids: list[int] | None = None,
|
|
lote_carga_id: int | None = None,
|
|
) -> int:
|
|
"""Identidad sintética para cada cliente importado sin identificación. Devuelve cuántas creó."""
|
|
con_identificacion = select(Identificacion.cliente_id).where(
|
|
Identificacion.tenant_id == tenant.id
|
|
)
|
|
consulta = select(Cliente).where(
|
|
Cliente.tenant_id == tenant.id,
|
|
Cliente.tipo_persona == "fisica",
|
|
Cliente.id.not_in(con_identificacion),
|
|
)
|
|
if cliente_ids is not None:
|
|
consulta = consulta.where(Cliente.id.in_(cliente_ids))
|
|
ahora = ahora_utc()
|
|
creadas = 0
|
|
for cliente in session.scalars(consulta.order_by(Cliente.id)):
|
|
if cliente.id_externo.startswith(PREFIJOS_CAPTURADOS):
|
|
continue
|
|
nombre = nombre_sintetico(cliente.id_externo)
|
|
validada = validar_identificacion(
|
|
"fisica",
|
|
{
|
|
"nombre": nombre.nombre,
|
|
"apellido_paterno": nombre.apellido_paterno,
|
|
"apellido_materno": nombre.apellido_materno,
|
|
"fuente": FUENTE_SINTETICA,
|
|
},
|
|
)
|
|
session.add(
|
|
Identificacion(
|
|
tenant_id=tenant.id,
|
|
created_by=usuario,
|
|
valid_from=ahora,
|
|
cliente_id=cliente.id,
|
|
version=1,
|
|
fuente=FUENTE_SINTETICA,
|
|
nombre_busqueda=validada.nombre_completo[:300],
|
|
datos=validada.model_dump(mode="json"),
|
|
)
|
|
)
|
|
creadas += 1
|
|
if creadas:
|
|
session.flush()
|
|
audit.registrar(
|
|
session,
|
|
"lote_carga" if lote_carga_id is not None else "identificacion",
|
|
lote_carga_id,
|
|
"nombres_sinteticos",
|
|
despues={"creadas": creadas, "fuente": FUENTE_SINTETICA},
|
|
motivo=motivo,
|
|
usuario=usuario,
|
|
tenant_id=tenant.id,
|
|
)
|
|
return creadas
|