Retire GET /cacu/pacientes/<id>/riesgo: the record reads the FHIR RiskAssessment
The WebApp patient record now reads GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> (WebApp feature/cohorts-dbt-canonical), so the custom route, its blueprint and its tests go; the risk batches and the follow-up list point to the FHIR search. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
@@ -1,89 +0,0 @@
|
|||||||
"""What this module covers: `GET /cacu/pacientes/<pac_id>/riesgo` (`webapi.patient_risk`): when the route exists, the
|
|
||||||
shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested
|
|
||||||
there.
|
|
||||||
|
|
||||||
Fixtures: `client`, the app without `DEV_REVISION` over the kit's CaCu demonstration database (`conftest.cliente_de`)
|
|
||||||
plus `seeded`: a surveillance build with two of its patients, one of them with variables and a confirmed batch.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from conftest import cliente_de
|
|
||||||
|
|
||||||
COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"}
|
|
||||||
RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "fecha_indice", "evaluado_en", "estado_lote", "horizontes"}
|
|
||||||
MODEL_INDEX = date(2026, 6, 1) # the model's index date: not the member's (2025-03-01)
|
|
||||||
HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def client(tmp_path_factory):
|
|
||||||
"""The app over the CaCu demonstration database, with no `DEV_REVISION` in the environment."""
|
|
||||||
with pytest.MonkeyPatch.context() as mp:
|
|
||||||
mp.delenv("DEV_REVISION", raising=False)
|
|
||||||
yield from cliente_de("cacu", tmp_path_factory)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
|
||||||
def seeded(client):
|
|
||||||
"""Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at
|
|
||||||
1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build)."""
|
|
||||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable
|
|
||||||
from persistance import cacu
|
|
||||||
from persistance.db import get_cacu_session
|
|
||||||
|
|
||||||
scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)]
|
|
||||||
with get_cacu_session() as session:
|
|
||||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
|
||||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-route", marco_sha="m",
|
|
||||||
n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
|
|
||||||
session.add(build)
|
|
||||||
session.flush()
|
|
||||||
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
|
|
||||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
|
|
||||||
for p in (scored, unscored)])
|
|
||||||
session.flush()
|
|
||||||
session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"),
|
|
||||||
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
|
|
||||||
session.commit()
|
|
||||||
build_id = build.armado_id
|
|
||||||
batch, _ = cacu.cohort_repository.save_batch(
|
|
||||||
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
|
||||||
"cin2_12m", [(scored, MODEL_INDEX, 3.0, 0.3, None, None), (scored, MODEL_INDEX, 1.0, 0.1, None, None)],
|
|
||||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
|
||||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
|
||||||
return scored, unscored, outside
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_scored_member_has_the_contracts_shape(client, seeded):
|
|
||||||
"""Pins down: without `DEV_REVISION` the route exists, and the body has `simulado`, `cohorte` and `riesgo` with
|
|
||||||
exactly the contract's fields, the horizons in ascending order, probabilities in 0..1 and the date as ISO-8601 UTC.
|
|
||||||
Fails if the route depends on an environment variable again, or if a field is renamed or dropped, which would break
|
|
||||||
the WebApp's validation."""
|
|
||||||
response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo")
|
|
||||||
|
|
||||||
body = response.get_json()
|
|
||||||
assert response.status_code == 200 and body["simulado"] is True
|
|
||||||
assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS
|
|
||||||
assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None)
|
|
||||||
assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final"
|
|
||||||
assert (body["riesgo"]["fecha_indice"], body["cohorte"]["fecha_indice"]) == ("2026-06-01", "2025-03-01")
|
|
||||||
horizons = body["riesgo"]["horizontes"]
|
|
||||||
assert all(set(h) == HORIZON_KEYS for h in horizons)
|
|
||||||
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
|
|
||||||
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
|
|
||||||
null. Fails if either case errors or invents a risk."""
|
|
||||||
member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json()
|
|
||||||
outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json()
|
|
||||||
|
|
||||||
assert member["cohorte"] is not None and member["riesgo"] is None
|
|
||||||
assert outside == {"simulado": True, "cohorte": None, "riesgo": None}
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_unknown_patient_is_404(client, seeded):
|
|
||||||
"""Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed."""
|
|
||||||
assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404
|
|
||||||
+2
-4
@@ -92,18 +92,16 @@ def create_app() -> Flask:
|
|||||||
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
||||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
||||||
url_prefix=f"/{domain}/fhir")
|
url_prefix=f"/{domain}/fhir")
|
||||||
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
|
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
|
||||||
# an access rule still to be defined, not an environment variable.
|
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
|
||||||
from persistance import cacu as cacu_repositories
|
from persistance import cacu as cacu_repositories
|
||||||
from persistance.db import get_cacu_session, get_cama_session
|
from persistance.db import get_cacu_session, get_cama_session
|
||||||
|
|
||||||
from webapi.patient_risk import patient_risk_blueprint
|
|
||||||
from webapi.risk_batches import risk_batches_blueprint
|
from webapi.risk_batches import risk_batches_blueprint
|
||||||
|
|
||||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||||
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
||||||
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
||||||
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
|
||||||
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||||
|
|
||||||
return app
|
return app
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
|
|||||||
|
|
||||||
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
|
**Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de
|
||||||
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
|
acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la
|
||||||
misma que usan los lotes de riesgo y `GET /cacu/pacientes/<pac_id>/riesgo`; `id_seudonimo` repite ese valor
|
misma que usan los lotes de riesgo y `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`; `id_seudonimo` repite ese valor
|
||||||
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
|
mientras los consumidores migran. Nunca sale `pac_id_hospital`.
|
||||||
|
|
||||||
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
|
Las reglas son de `parametros.toml` (`PARAMETROS_DE_LA_LISTA` y las del estrato `estatus_seguimiento`
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
"""A CaCu patient's individual risk: `GET /cacu/pacientes/<pac_id>/riesgo`.
|
|
||||||
|
|
||||||
The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance
|
|
||||||
cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed
|
|
||||||
evaluation, with the index date the model scored her from (`riesgo.fecha_indice`). Patient data, on simulated data: every response carries `simulado: true`. The route is always registered;
|
|
||||||
who may see it is an access rule still to be defined. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never
|
|
||||||
removed or renamed, only added.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import timezone
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify
|
|
||||||
|
|
||||||
COHORT_URL = "cacu/cohorte_vigilancia"
|
|
||||||
COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0")
|
|
||||||
|
|
||||||
|
|
||||||
def patient_risk_blueprint(repositories) -> Blueprint:
|
|
||||||
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
|
|
||||||
blueprint = Blueprint("cacu_patient_risk", __name__)
|
|
||||||
|
|
||||||
@blueprint.get("/pacientes/<int:pac_id>/riesgo")
|
|
||||||
def get_patient_risk(pac_id: int):
|
|
||||||
"""A patient's cohort membership and risks in the current batch (DEV only, simulated data)."""
|
|
||||||
if repositories.persona_repository.get(pac_id) is None:
|
|
||||||
return jsonify({"error": f"no existe la paciente {pac_id}"}), 404
|
|
||||||
membership = repositories.cohort_repository.membership(pac_id, COHORT_URL)
|
|
||||||
risk = repositories.cohort_repository.current_risk(pac_id)
|
|
||||||
return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)})
|
|
||||||
|
|
||||||
return blueprint
|
|
||||||
|
|
||||||
|
|
||||||
def _cohort(membership) -> dict | None:
|
|
||||||
if membership is None:
|
|
||||||
return None
|
|
||||||
return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(),
|
|
||||||
**{name: membership.variables.get(name) for name in COHORT_VARIABLES}}
|
|
||||||
|
|
||||||
|
|
||||||
def _risk(risk) -> dict | None:
|
|
||||||
if risk is None:
|
|
||||||
return None
|
|
||||||
evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc)
|
|
||||||
return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version,
|
|
||||||
# the model's index date for the patient: the horizons count from it (not the cohort's)
|
|
||||||
"fecha_indice": risk.fecha_indice.isoformat() if risk.fecha_indice else None,
|
|
||||||
"evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
||||||
"estado_lote": risk.estado_lote,
|
|
||||||
"horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
|
|
||||||
"ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}
|
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
|
"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
|
||||||
confirm one (`preliminary` -> `final`, visible on `/cacu/pacientes/<id>/riesgo`) or void it (`entered-in-error`).
|
confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`,
|
||||||
|
`/cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`) or void it (`entered-in-error`).
|
||||||
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
|
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
|
||||||
to be defined, as `patient_risk.py` notes for reads.
|
to be defined.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
from flask import Blueprint, jsonify, request
|
||||||
|
|||||||
Reference in New Issue
Block a user