Conecta demografía y ruta CaCu a persistencia configurada
This commit is contained in:
@@ -0,0 +1,9 @@
|
|||||||
|
# Acceso a fecha de nacimiento de CaCu
|
||||||
|
|
||||||
|
`GET /cacu/seguimiento/pacientes/<pac_id>/demografia` consulta la persona en la base CaCu configurada y devuelve únicamente `pac_id` y `fecha_nacimiento` (fecha ISO o `null`). Un identificador inexistente responde 404.
|
||||||
|
|
||||||
|
El endpoint no implementa autenticación ni autorización propias y expone información demográfica individual a quien pueda acceder a WebApi. La protección de acceso, si se requiere, debe aplicarse en la instalación que lo publique.
|
||||||
|
|
||||||
|
La ruta individual de tamizaje API-02 utiliza la persistencia configurada. El equipo responsable deberá establecer los controles de acceso individual apropiados antes de utilizar datos personales reales; no se ha implementado autenticación específica de endpoints en esta intervención.
|
||||||
|
|
||||||
|
Actualmente el contrato de seguimiento emite `simulado: true` de manera incondicional, incluso cuando consulta la persistencia configurada. Esta marca no permite identificar la procedencia real de cada registro; no se modifica su valor aquí.
|
||||||
@@ -14,6 +14,34 @@ LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "edad_al_corte", "est
|
|||||||
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("fecha", ["1980-01-01", None])
|
||||||
|
def test_demografia_consulta_persona_y_distingue_nulo(monkeypatch, fecha):
|
||||||
|
from datetime import date
|
||||||
|
from flask import Flask
|
||||||
|
from webapi.follow_up import routes
|
||||||
|
|
||||||
|
class Resultado:
|
||||||
|
def first(self):
|
||||||
|
return (date.fromisoformat(fecha) if fecha else None,)
|
||||||
|
|
||||||
|
class Sesion:
|
||||||
|
def execute(self, consulta):
|
||||||
|
assert consulta.compile().params == {"pac_id_1": 42}
|
||||||
|
return Resultado()
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.register_blueprint(routes.follow_up_blueprint(Sesion), url_prefix="/cacu")
|
||||||
|
respuesta = app.test_client().get('/cacu/seguimiento/pacientes/42/demografia')
|
||||||
|
assert respuesta.status_code == 200
|
||||||
|
assert respuesta.json == {"pac_id": "42", "fecha_nacimiento": fecha}
|
||||||
|
|
||||||
|
|
||||||
|
def test_demografia_rechaza_identificador_fuera_de_rango(client):
|
||||||
|
assert client.get('/cacu/seguimiento/pacientes/9223372036854775808/demografia').status_code == 404
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def client(tmp_path_factory):
|
def client(tmp_path_factory):
|
||||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||||
@@ -258,13 +286,12 @@ def test_un_caso_es_un_carcinoma_invasor_o_in_situ():
|
|||||||
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
||||||
|
|
||||||
|
|
||||||
def test_ruta_es_optativa_sintetica_y_se_proyecta_solo_para_la_pagina(client, monkeypatch):
|
def test_ruta_es_optativa_y_se_proyecta_solo_para_la_pagina(client, monkeypatch):
|
||||||
from webapi.follow_up import listing, routes
|
from webapi.follow_up import listing
|
||||||
|
|
||||||
base = "/cacu/seguimiento?corte=2025-12-31&meses=12&q=%20&page_size=2&page=2"
|
base = "/cacu/seguimiento?corte=2025-12-31&meses=12&q=%20&page_size=2&page=2"
|
||||||
normal = client.get(base).get_json()
|
normal = client.get(base).get_json()
|
||||||
assert normal["items"] and "ruta_tamizaje" not in normal["items"][0]
|
assert normal["items"] and "ruta_tamizaje" not in normal["items"][0]
|
||||||
assert client.get(base + "&incluir=ruta_tamizaje").status_code == 404
|
|
||||||
assert client.get(base + "&incluir=otra").status_code == 400
|
assert client.get(base + "&incluir=otra").status_code == 400
|
||||||
|
|
||||||
llamadas = []
|
llamadas = []
|
||||||
@@ -274,7 +301,6 @@ def test_ruta_es_optativa_sintetica_y_se_proyecta_solo_para_la_pagina(client, mo
|
|||||||
llamadas.append({pac_id for pac_id, _ in tomas.values()})
|
llamadas.append({pac_id for pac_id, _ in tomas.values()})
|
||||||
return proyectar(sesion, tomas, corte, tablas)
|
return proyectar(sesion, tomas, corte, tablas)
|
||||||
|
|
||||||
monkeypatch.setattr(routes, "_rutas_sinteticas", lambda sesion: True)
|
|
||||||
monkeypatch.setattr(listing, "rutas_de", en_bloque)
|
monkeypatch.setattr(listing, "rutas_de", en_bloque)
|
||||||
respuesta = client.get(base + "&incluir=ruta_tamizaje")
|
respuesta = client.get(base + "&incluir=ruta_tamizaje")
|
||||||
assert respuesta.status_code == 200
|
assert respuesta.status_code == 200
|
||||||
@@ -289,5 +315,3 @@ def test_ruta_es_optativa_sintetica_y_se_proyecta_solo_para_la_pagina(client, mo
|
|||||||
assert client.get(ruta["detalle_url"].replace("corte=" + ruta["corte"], "corte=2026-12-31")).status_code == 404
|
assert client.get(ruta["detalle_url"].replace("corte=" + ruta["corte"], "corte=2026-12-31")).status_code == 404
|
||||||
assert client.get(ruta["detalle_url"].replace(f"/rutas/{fila['pac_id']}/", "/rutas/999999/")).status_code == 404
|
assert client.get(ruta["detalle_url"].replace(f"/rutas/{fila['pac_id']}/", "/rutas/999999/")).status_code == 404
|
||||||
assert cuerpo == normal
|
assert cuerpo == normal
|
||||||
monkeypatch.undo()
|
|
||||||
assert client.get(ruta["detalle_url"]).status_code == 404
|
|
||||||
|
|||||||
+17
-13
@@ -18,20 +18,13 @@ from datetime import date
|
|||||||
from flask import Blueprint, Response, jsonify, request
|
from flask import Blueprint, Response, jsonify, request
|
||||||
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
from webapi.follow_up.listing import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||||
from webapi.follow_up.screening import detalle_de
|
from webapi.follow_up.screening import detalle_de
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session, select
|
||||||
|
from webapi.orchestration.tables.cacu import TABLAS
|
||||||
|
|
||||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||||
RUTA_ID = re.compile(r"[0-9a-f]{64}")
|
RUTA_ID = re.compile(r"[0-9a-f]{64}")
|
||||||
|
|
||||||
|
|
||||||
def _rutas_sinteticas(sesion: Session) -> bool:
|
|
||||||
"""DEV no acredita autorización por paciente. Limitar los dos contratos al fixture local."""
|
|
||||||
if os.environ.get("DEV_REVISION") != "cacu-dev-sintetico":
|
|
||||||
return False
|
|
||||||
url = sesion.get_bind().url
|
|
||||||
return url.drivername == "sqlite" and url.database == "/workspace/entorno-dev/datos-sinteticos/cacu.db"
|
|
||||||
|
|
||||||
|
|
||||||
def in_dev() -> bool:
|
def in_dev() -> bool:
|
||||||
"""Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará."""
|
"""Obsoleta: las rutas por paciente ya no dependen de `DEV_REVISION` y nada la llama. Se quitará."""
|
||||||
warnings.warn("in_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
|
warnings.warn("in_dev() está obsoleta: las rutas por paciente se registran siempre", DeprecationWarning, stacklevel=2)
|
||||||
@@ -50,8 +43,6 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
|||||||
return jsonify({"error": str(error)}), 400
|
return jsonify({"error": str(error)}), 400
|
||||||
sesion = get_session()
|
sesion = get_session()
|
||||||
try:
|
try:
|
||||||
if pedido.get("incluir_ruta") and not _rutas_sinteticas(sesion):
|
|
||||||
return jsonify({"error": "Ruta de tamizaje no disponible"}), 404
|
|
||||||
cuerpo = seguimiento_de(sesion, **pedido)
|
cuerpo = seguimiento_de(sesion, **pedido)
|
||||||
except PedidoInvalido as error:
|
except PedidoInvalido as error:
|
||||||
return jsonify({"error": str(error)}), 400
|
return jsonify({"error": str(error)}), 400
|
||||||
@@ -61,6 +52,21 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
|||||||
sesion.close()
|
sesion.close()
|
||||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||||
|
|
||||||
|
@blueprint.get("/seguimiento/pacientes/<int:pac_id>/demografia")
|
||||||
|
def get_demografia(pac_id: int):
|
||||||
|
no_disponible = {"error": "Información demográfica no disponible"}
|
||||||
|
if pac_id > 2**63 - 1:
|
||||||
|
return jsonify(no_disponible), 404
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
fila = sesion.execute(select(TABLAS.Persona.fecha_nacimiento).where(TABLAS.Persona.pac_id == pac_id)).first()
|
||||||
|
if fila is None:
|
||||||
|
return jsonify(no_disponible), 404
|
||||||
|
nacimiento = fila[0]
|
||||||
|
return jsonify({"pac_id": str(pac_id), "fecha_nacimiento": nacimiento.isoformat() if nacimiento is not None else None})
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
|
||||||
@blueprint.get("/seguimiento/rutas/<int:pac_id>/<ruta_id>")
|
@blueprint.get("/seguimiento/rutas/<int:pac_id>/<ruta_id>")
|
||||||
def get_ruta(pac_id: int, ruta_id: str):
|
def get_ruta(pac_id: int, ruta_id: str):
|
||||||
no_disponible = {"error": "Ruta de tamizaje no disponible"}
|
no_disponible = {"error": "Ruta de tamizaje no disponible"}
|
||||||
@@ -68,8 +74,6 @@ def follow_up_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
|||||||
return jsonify(no_disponible), 404
|
return jsonify(no_disponible), 404
|
||||||
sesion = get_session()
|
sesion = get_session()
|
||||||
try:
|
try:
|
||||||
if not _rutas_sinteticas(sesion):
|
|
||||||
return jsonify(no_disponible), 404
|
|
||||||
texto = request.args.get("corte", "")
|
texto = request.args.get("corte", "")
|
||||||
try:
|
try:
|
||||||
if not FECHA.fullmatch(texto):
|
if not FECHA.fullmatch(texto):
|
||||||
|
|||||||
Reference in New Issue
Block a user