Files
WebApi/webapi/imports/services/catalog_commit_service.py
T
2026-11-11 08:33:16 -06:00

115 lines
5.1 KiB
Python

"""Writes the catalog-fallback fields a document source's records carry
(captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`)
into the silver layer directly: one synthetic `procedimiento` per record
per estudio its resolved fields touch, with their `observacion`s matched
or minted against the project's catalog (`catalog_matching`).
There is no staging row for these — the whole point is a field outside
today's structured schemas — so this bypasses `DESDE_STAGING` and writes
straight through the domain's existing `carga_repository`, the same one
`webapi.orquestacion`'s `cargar` step uses for staging-derived batches.
Marked clearly apart from every staging-derived procedimiento:
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
staging table name. `fuente_id` is the record's own natural key (not a SQL
row's surrogate id), so reprocessing the same record later — read again
from the SQL source, re-uploaded as a file, or corrected by hand — updates
the same rows in place instead of duplicating them; the structured fields
a source also carries keep going through the unmodified staging/import
path (`commit_sources`), independently of this.
"""
from collections import defaultdict
from dataclasses import dataclass
from importlib import import_module
from extraction import ExtractedRecord
from indicadores_kit.plata.procedimiento import LotePlata
from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo
from indicadores_kit.tablas import tablas_de
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
@dataclass
class CatalogCommitResult:
proyecto: str
records_written: int = 0
records_without_patient: int = 0
fields_matched: int = 0
fields_minted: int = 0
def commit_discovered_fields(
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None
) -> CatalogCommitResult:
"""A patient without a row in `persona` is counted and skipped: this
path only fills in fields for a patient already known, it doesn't
create one."""
dominio = import_module(f"persistance.{proyecto}")
tablas = tablas_de(proyecto)
ruta = ruta_de_catalogo(proyecto)
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
result = CatalogCommitResult(proyecto=proyecto)
procedures, observations = [], []
for record in records:
if not record.discovered or record.key is None:
continue
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
if not patients:
result.records_without_patient += 1
continue
pac_id = patients[0].pac_id
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id)
if any(field.is_new for field in matched):
catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too
matched = _fold_duplicates(matched)
by_estudio: dict[str, list] = defaultdict(list)
for field in matched:
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
result.fields_minted += int(field.is_new)
result.fields_matched += int(not field.is_new)
for estudio, fields in by_estudio.items():
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
observations += [
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
for field in fields
]
result.records_written += 1
if procedures:
_sync_catalog(dominio, proyecto, tablas)
dominio.carga_repository.guardar_carga(
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
)
return result
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
"""A record's discovered captions can repeat the same resultado_id (a
static label such as "FECHA" printed on several pages): `observacion`
has one row per `(procedimiento, resultado_id)`, so only the first
occurrence survives. `discover_captions` keeps every repeat on purpose
and leaves folding to the caller (see its docstring)."""
seen: set[str] = set()
folded = []
for field in matched:
if field.resultado_id in seen:
continue
seen.add(field.resultado_id)
folded.append(field)
return folded
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
"""A field minted by `match_or_mint` only exists in the TOML until this
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
the matching `cat_estudio`/`cat_resultado` row to already be there."""
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
dominio.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)