TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary
This commit is contained in:
@@ -14,6 +14,7 @@ llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`,
|
||||
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from typing import NamedTuple
|
||||
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
@@ -59,6 +60,16 @@ class Hija:
|
||||
resultados: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Junta:
|
||||
"""Another staging row whose columns the row's content takes: the row of `staging` whose `llave` equals the
|
||||
row's column `columna` (an electrode value takes its metric's code and EEG). Without a match, they're null."""
|
||||
|
||||
staging: type
|
||||
llave: str
|
||||
columna: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeStaging:
|
||||
"""Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c).
|
||||
@@ -72,6 +83,10 @@ class DeStaging:
|
||||
no es un reporte); no es un descarte.
|
||||
- `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en
|
||||
`descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging.
|
||||
- `juntas`: rows of other staging tables whose columns join the content before the derived ones.
|
||||
- `observa_en`: the row gives no procedure of its own; its observations go on the procedure this parent key
|
||||
names (a metric of an EEG is a result of the EEG's recording). `clase` is unused then.
|
||||
A result's template can name the content's columns (`eeg.{metrica}`) besides `{estudio}`.
|
||||
|
||||
Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada.
|
||||
Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17).
|
||||
@@ -92,6 +107,8 @@ class DeStaging:
|
||||
paciente: str | None = "pac_id"
|
||||
solo_si: Callable | None = None
|
||||
descartar: Callable | None = None
|
||||
juntas: tuple[Junta, ...] = ()
|
||||
observa_en: Padre | None = None
|
||||
|
||||
|
||||
class LotePlata(NamedTuple):
|
||||
@@ -124,6 +141,7 @@ def plata_desde_staging(
|
||||
pacientes = set(pacientes)
|
||||
tipos, vigentes = _tipos_y_vigentes(catalogo)
|
||||
procedimientos, observaciones, descartes = [], [], {}
|
||||
indices: dict[tuple[str, str], dict] = {}
|
||||
for c in correspondencias:
|
||||
tabla = c.staging.__tablename__
|
||||
for fila in filas.get(tabla, ()):
|
||||
@@ -133,7 +151,13 @@ def plata_desde_staging(
|
||||
continue
|
||||
if c.solo_si is not None and not c.solo_si(fila):
|
||||
continue
|
||||
contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido = fila.model_dump()
|
||||
if c.juntas:
|
||||
for junta in c.juntas:
|
||||
unida = _junta(junta, filas, indices).get(contenido.get(junta.columna))
|
||||
contenido = {**(unida or dict.fromkeys(junta.staging.model_fields)), **contenido}
|
||||
fila = SimpleNamespace(**contenido)
|
||||
contenido = {**contenido, **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente)
|
||||
contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()})
|
||||
_repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital,
|
||||
@@ -168,6 +192,14 @@ def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]:
|
||||
return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3])))
|
||||
|
||||
|
||||
def _junta(junta: Junta, filas: Mapping[str, Iterable], indices: dict) -> dict:
|
||||
"""The rows of the joined table by their key, as dictionaries; built once per batch."""
|
||||
clave = (junta.staging.__tablename__, junta.llave)
|
||||
if clave not in indices:
|
||||
indices[clave] = {getattr(f, junta.llave): f.model_dump() for f in filas.get(clave[0], ())}
|
||||
return indices[clave]
|
||||
|
||||
|
||||
def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]:
|
||||
tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados}
|
||||
vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
@@ -183,6 +215,11 @@ def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, col
|
||||
motivo = f"{nombre}: {c.estudio_de} fuera de catálogo"
|
||||
descartes[motivo] = descartes.get(motivo, 0) + 1
|
||||
return
|
||||
if c.observa_en is not None:
|
||||
dueno = _parent(c.observa_en, contenido)
|
||||
if dueno is not None:
|
||||
observaciones += _observaciones(dueno, contenido, c.resultados, c.fuentes, tipos, vigentes)
|
||||
return
|
||||
llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase)
|
||||
procedimientos.append({
|
||||
"llave": llave,
|
||||
@@ -225,7 +262,9 @@ def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str],
|
||||
tipos: dict, vigentes: set) -> list[dict]:
|
||||
filas = []
|
||||
for columna, plantilla in resultados.items():
|
||||
resultado_id = plantilla.format(estudio=llave[2])
|
||||
resultado_id = plantilla.format_map({**contenido, "estudio": llave[2]})
|
||||
if resultado_id not in tipos and "{" in plantilla.replace("{estudio}", ""):
|
||||
continue # a value of the row names a result the catalog doesn't have (an unknown metric)
|
||||
filas.append({
|
||||
"procedimiento": llave,
|
||||
"pac_id": contenido.get("pac_id"),
|
||||
|
||||
Reference in New Issue
Block a user