diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 32e7d21..c882adb 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -36,9 +36,14 @@ fi # One-shot training of the CaCu model on the loaded data (compose profile # `entrenar`): the trained version goes into production and the worker's next -# cycle estimates with it. +# cycle estimates with it. `--source dbt` (dbt's cohort, not the kit's numbered +# builds) is required: a PROD run needs its cohort build named (ML-03), and +# --export --source dbt is the only way to do that without knowing the build +# number ahead of time; it also makes the promotion gate's cohort-link check +# portable (tag-based, no live lookup of a local build row), unlike the kit's. if [ "$1" = "entrenar" ]; then - exec uv run --no-sync python -m models run cacu cin2_logistic --export --train --promote + exec uv run --no-sync python -m models run cacu cin2_logistic --export --source dbt --manifest "$DBT_MANIFEST" \ + --environment prod --train --promote fi # --no-sync: the environment was synced at build time; syncing at startup diff --git a/tests/test_cama_cohort.py b/tests/test_cama_cohort.py new file mode 100644 index 0000000..5677387 --- /dev/null +++ b/tests/test_cama_cohort.py @@ -0,0 +1,193 @@ +"""What this module covers: `CamaCohort.rows` (`webapi.cama_cohort`) and the `/cama/analisis`, `/cama/seguimiento` +and `/cama/pacientes` routes over it: eligibility (BI-RADS 4-6, dated and known by the cutoff), the biopsy link +(mammogram -> order -> report, never across patients or before the mammogram), pagination, export, patient detail +and access control. + +Fixtures: `cohort_db`, an isolated SQLite engine with six synthetic patients' `Persona`/`Carga`/`Procedimiento`/ +`Observacion` rows (`webapi.orchestration.tables.cama.TABLAS`), one load from 2025 and one from 2027; `client`, a +minimal Flask app registering only the two CaMa blueprints over `cohort_db`, with an always-authorized access +callback. +""" + +from datetime import date, datetime, timezone + +import pytest +from flask import Flask +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from webapi.orchestration.tables.cama import TABLAS +from webapi.cama_analysis import analysis +from webapi.cama_cohort import CamaCohort +from webapi.seguimiento_cama import blueprint_seguimiento_cama + + +@pytest.fixture +def cohort_db(): + """Six eligible people, one linked biopsy and one biopsy without a link.""" + t = TABLAS + engine = create_engine('sqlite:///:memory:') + for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion): + model.__table__.create(engine) + with Session(engine) as session: + session.add_all([ + t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)), + t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)), + ]) + for patient in range(1, 7): + session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1))) + session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient), + carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1))) + session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia', + fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia', + clase='reporte', fecha=date(2025, 2, 2))) + session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1, + pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5')) + for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)): + report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15) + session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama', + fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia', + clase='orden', fecha=date(2025, 2, 10))) + session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2, + fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient, + estudio_id='biopsia', clase='reporte', fecha=report_date)) + session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load, + pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO')) + session.commit() + yield engine + engine.dispose() + + +@pytest.fixture +def client(cohort_db): + """Configure an explicitly synthetic reader and an authorized test principal.""" + app = Flask(__name__) + app.register_blueprint(analysis, url_prefix='/cama') + app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama') + def read(cutoff): + with Session(cohort_db) as session: + return CamaCohort(session).rows(cutoff) + app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True) + return app.test_client() + + +QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5' + + +def query(client, cutoff='2026-10-20'): + revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision'] + return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision + + +def test_aggregate_list_detail_and_export_have_one_selection(client): + """The published aggregate reconciles with pages, patient details and export.""" + aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json() + assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6 + selection = query(client) + first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json() + assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'} + items = [] + for page in (1, 2, 3): + data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json() + items.extend(data['items']) + exported = client.get('/cama/seguimiento/exportacion' + selection).get_json() + assert exported['items'] == items and exported['total_items'] == 6 + for item in items: + detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json() + assert detail['item'] == item and detail['corte'] == aggregate['corte'] + assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1 + assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items + + +def test_rejects_unknown_and_suppressed_selections_and_denies_access(client): + """Unknown filters and small groups cannot silently broaden patient access.""" + selection = query(client) + assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400 + assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403 + assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400 + assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409 + client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False + assert client.get('/cama/seguimiento' + selection).status_code == 403 + assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403 + assert client.get('/cama/pacientes/some-id' + selection).status_code == 403 + + +def test_cutoff_excludes_later_clinical_and_load_dates(client): + """A report or observation not yet known at the cutoff cannot appear.""" + early = query(client, '2025-02-09') + rows = client.get('/cama/seguimiento' + early).get_json()['items'] + assert len(rows) == 6 and all(row['biopsia'] is None for row in rows) + empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '') + response = client.get('/cama/seguimiento' + empty).get_json() + assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01' + + +def test_links_and_load_dates_are_distinct(client, cohort_db): + """A missing link and a late load cannot supply a diagnosis before cutoff.""" + ids = {i: str(i) for i in range(1, 5)} + data = client.get('/cama/seguimiento' + query(client)).get_json() + rows = {item['pac_id']: item for item in data['items']} + assert rows[ids[1]]['biopsia'] == 'BENIGNO' + assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None + assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15' + assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None + later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json() + rows_later = {item['pac_id']: item for item in later['items']} + assert rows_later[ids[3]]['biopsia'] == 'BENIGNO' + assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15' + assert set(rows) == set(rows_later) + + +def test_full_application_registers_cohort_and_regular_followup(client): + """The regular follow-up uses the configured reader instead of unrelated fixture rows.""" + from webapi import create_app + + app = create_app() + app.config.update(client.application.config) + full = app.test_client() + assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200 + assert full.get('/cama/seguimiento?corte=2026-10-20&meses=0').get_json()['paginacion']['total_items'] == 6 + assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400 + + +def test_windows_and_disabled_provider(client): + """Regular windows remain available and a missing reader returns unavailable.""" + selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '') + body = client.get('/cama/seguimiento' + selection).get_json() + assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21' + client.application.config['CAMA_COHORT_READER'] = None + assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503 + + +def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db): + """The latest reported result is selected before checking BI-RADS eligibility.""" + previous = query(client) + with Session(cohort_db) as session: + session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new', + carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1))) + session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new', + carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2))) + session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6, + resultado_id='mastografia.birads', valor_fuente='B1')) + session.commit() + assert client.get('/cama/seguimiento' + previous).status_code == 409 + aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json() + assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5 + assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5 + + +def test_cross_patient_links_and_observations_are_not_used(cohort_db): + """A mismatched patient or an order before the mammogram cannot supply a result.""" + with Session(cohort_db) as session: + # The biopsy order is linked to patient 1's mammogram but belongs to patient 2. + session.get(TABLAS.Procedimiento, 102).pac_id = 2 + # Patient 3's otherwise linked biopsy order predates the mammogram. + session.get(TABLAS.Procedimiento, 106).fecha = date(2025, 1, 1) + # The BI-RADS observation belongs to a different patient. + session.get(TABLAS.Observacion, 6).pac_id = 5 + session.commit() + reader = CamaCohort(session) + rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))} + assert '6' not in rows + assert rows['1']['biopsia'] is None + assert rows['3']['biopsia'] is None diff --git a/tests/test_cama_runtime.py b/tests/test_cama_runtime.py new file mode 100644 index 0000000..756f421 --- /dev/null +++ b/tests/test_cama_runtime.py @@ -0,0 +1,25 @@ +"""Verify default persistent cohort setup with retained legacy configuration.""" + +from flask import Flask + +from webapi.cama_runtime import configure_cama_cohort + + +def test_default_reader_uses_shared_persistence(monkeypatch): + """The reader is registered without special cohort environment variables.""" + for key in ('CAMA_COHORT_SYNTHETIC', 'CAMA_COHORT_SECRET', 'CAMA_COHORT_ACCESS_TOKEN'): + monkeypatch.delenv(key, raising=False) + app = Flask(__name__) + configure_cama_cohort(app) + assert callable(app.config['CAMA_COHORT_READER']) + assert 'CAMA_COHORT_ACCESS' not in app.config + + +def test_application_starts_with_retained_obsolete_configuration(monkeypatch): + """Retained synthetic settings cannot prevent the health endpoint starting.""" + monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1') + monkeypatch.delenv('CAMA_COHORT_SECRET', raising=False) + monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'invalid') + from webapi import create_app + + assert create_app().test_client().get('/health').get_json() == {'status': 'ok'} diff --git a/tests/test_governance_endpoints.py b/tests/test_governance_endpoints.py index e2bc1be..8b42fd9 100644 --- a/tests/test_governance_endpoints.py +++ b/tests/test_governance_endpoints.py @@ -173,6 +173,64 @@ def test_model_version_not_found(client): assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404 +def test_training_needs_a_dbt_manifest(client, monkeypatch): + """Pins down: with no `DBT_MANIFEST`, `/train` refuses before running anything. Fails if it tries to train with + no manifest configured instead of failing fast.""" + monkeypatch.delenv("DBT_MANIFEST", raising=False) + + response = client.post("/governance/model-versions/cacu/cin2_logistic/train") + + assert response.status_code == 503 + + +def test_training_runs_the_same_pipeline_entrenar_does(client, monkeypatch): + """Pins down: `/train` calls `models.__main__.main` with exactly the arguments the `entrenar` compose profile + runs (export from dbt, PROD, train, promote), reading the manifest path from `DBT_MANIFEST`, and returns its + captured output on success. Fails if the route drifts from that one-shot invocation, or stops using the + deployment's own manifest.""" + monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json") + calls = [] + + def fake_main(argv): + calls.append(argv) + print("trained: version 1, from dbt/1.parquet") + print("in production: version 1") + return 0 + + monkeypatch.setattr("models.__main__.main", fake_main) + + response = client.post("/governance/model-versions/cacu/cin2_logistic/train") + + assert response.status_code == 200 + assert calls == [["run", "cacu", "cin2_logistic", "--export", "--source", "dbt", "--manifest", + "/data/dbt/manifest.json", "--environment", "prod", "--train", "--promote"]] + assert "in production: version 1" in response.get_json()["output"] + + +@pytest.mark.parametrize("stderr, expected_status", [ + ("no such model: cacu/ninguno\n", 404), + ("not promoted, missing: MLD-01 (reporte de pruebas técnicas)\n", 409), + ("a query of cacu/cohorte_vigilancia failed (no such table: cohorte_armado)\n", 503), +]) +def test_training_failures_map_to_their_status(client, monkeypatch, stderr, expected_status): + """Pins down: an unknown model is 404, a trained-but-unpromotable version is 409 (attach reports, then + `/promote`), and anything else operational is 503. Fails if a failure that needs a human step (missing reports) + reads the same as a hard, transient failure, or either is swallowed as success.""" + import sys + + def fake_main(argv): + sys.stderr.write(stderr) + return 1 + + monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json") + monkeypatch.setattr("models.__main__.main", fake_main) + + response = client.post("/governance/model-versions/cacu/cin2_logistic/train") + + assert response.status_code == expected_status + assert response.get_json()["error"] == stderr.strip() + + def test_ocr_run_unknown_job_is_404(client): response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"}) assert response.status_code == 404 diff --git a/tests/test_risk_batches.py b/tests/test_risk_batches.py new file mode 100644 index 0000000..fee812b --- /dev/null +++ b/tests/test_risk_batches.py @@ -0,0 +1,102 @@ +"""What this module covers: `GET /cacu/riesgos/lotes` and the confirm/void routes (`webapi.risk_batches`): which +batches are listed, that confirming or voiding moves a batch off the list and that the route rejects a missing +reason or an unknown batch. The reads and writes behind it are Persistance's, tested there. + +Fixtures: `client`, the app over the kit's CaCu demonstration database (`conftest.cliente_de`); `batches`, two +batches over a fresh surveillance build, both still preliminary. +""" + +from datetime import date, datetime, timezone + +import pytest +from conftest import cliente_de + + +@pytest.fixture(scope="module") +def client(tmp_path_factory): + yield from cliente_de("cacu", tmp_path_factory) + + +@pytest.fixture(scope="module") +def batches(client): + """Three preliminary batches over one patient of the demo data: `older` and `newer` are confirmed/voided by + the tests that exercise those routes; `untouched` stays preliminary for the tests that must not change a + batch's state (an unknown id, a missing reason).""" + from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro + from persistance import cacu + from persistance.db import get_cacu_session + + pac_id = cacu.persona_repository.list(limit=1)[0].pac_id + with get_cacu_session() as session: + build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r", + parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-batches", marco_sha="m", + n_miembros=1, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)) + session.add(build) + session.flush() + session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=pac_id, fecha_indice=date(2025, 3, 1), + indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))) + session.commit() + build_id = build.armado_id + provenance = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"} + + def batch(version, risk, ahora): + lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version}, + "cin2_12m", [(pac_id, 1.0, risk, None, None)], ahora=ahora) + return lote_id + + older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc)) + newer = batch("2", 0.2, datetime(2026, 10, 2, tzinfo=timezone.utc)) + untouched = batch("3", 0.3, datetime(2026, 10, 3, tzinfo=timezone.utc)) + return older, newer, untouched + + +def test_pending_batches_are_listed_newest_first(client, batches): + """Pins down: every preliminary batch is listed, newest first, with the fields the WebApp reads. Fails if the + order is reversed or a field is renamed.""" + older, newer, untouched = batches + + body = client.get("/cacu/riesgos/lotes").get_json() + + assert [b["lote_id"] for b in body if b["lote_id"] in batches] == [untouched, newer, older] + listed = next(b for b in body if b["lote_id"] == untouched) + assert set(listed) == {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "n_evaluaciones"} + assert (listed["modelo_nombre"], listed["modelo_version"], listed["n_evaluaciones"]) == ("cacu-cin2_logistic", "3", 1) + + +def test_confirming_drops_a_batch_off_the_pending_list(client, batches): + """Pins down: confirming a batch moves its evaluations to `final` and it stops being listed as pending. Fails if + it stays listed, or the evaluations aren't actually changed.""" + older, _, _ = batches + + response = client.post(f"/cacu/riesgos/lotes/{older}/confirmar", json={"reason": "revisado por clínica"}) + + assert response.status_code == 200 and response.get_json() == {"lote_id": older, "evaluaciones_cambiadas": 1} + assert older not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()] + + +def test_voiding_also_drops_a_batch_off_the_pending_list(client, batches): + """Pins down: voiding is the other way out of the pending list, distinct from confirming. Fails if it confirms + instead of voiding, or leaves the batch pending.""" + _, newer, _ = batches + + response = client.post(f"/cacu/riesgos/lotes/{newer}/anular", json={"reason": "modelo equivocado"}) + + assert response.status_code == 200 and response.get_json()["evaluaciones_cambiadas"] == 1 + assert newer not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()] + + +def test_a_decision_needs_a_reason(client, batches): + """Pins down: confirming or voiding with no reason is refused and changes nothing. Fails if the batch moves + anyway, which would leave a decision with no recorded motive (ADR-MD-008).""" + _, _, untouched = batches + + response = client.post(f"/cacu/riesgos/lotes/{untouched}/confirmar", json={"reason": " "}) + + assert response.status_code == 400 + assert untouched in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()] + + +def test_an_unknown_batch_is_404(client): + """Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed + nothing.""" + assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404 diff --git a/tests/test_seguimiento_cama.py b/tests/test_seguimiento_cama.py new file mode 100644 index 0000000..c374f54 --- /dev/null +++ b/tests/test_seguimiento_cama.py @@ -0,0 +1,72 @@ +"""Exercise regular and cohort follow-up with an authorized synthetic reader.""" + +from datetime import date + +import pytest +from flask import Flask + +from webapi.cama_analysis import analysis, revision_of +from webapi.seguimiento_cama import blueprint_seguimiento_cama + + +@pytest.fixture +def client(): + """A fixed six-person cohort and a server-controlled access callback.""" + rows = [dict(pac_id=str(n + 1), mastografia_fecha='2026-10-15', + birads='BIRADS_5', grupo_edad='50-59', biopsia=None, + biopsia_fecha=None) for n in range(6)] + app = Flask(__name__) + app.register_blueprint(analysis, url_prefix='/cama') + app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama') + app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=lambda cutoff: rows, + CAMA_COHORT_ACCESS=lambda request: request.headers.get('X-Test') == 'yes') + return app.test_client() + + +def test_regular_list_detail_and_export_use_the_same_selection(client): + """Pagination, detail and export resolve the same filtered persistent cohort.""" + headers = {'X-Test': 'yes'} + query = '?corte=2026-10-20&meses=3&birads=BIRADS_5' + page = client.get('/cama/seguimiento' + query + '&page_size=2', headers=headers).get_json() + assert page['paginacion']['total_items'] == 6 + assert page['cohorte'] == 'cama_birads_v1' + context = '&cohorte=' + page['cohorte'] + '&escenario=' + page['escenario'] + '&revision=' + page['revision'] + rows = [] + for number in (1, 2, 3): + rows.extend(client.get('/cama/seguimiento' + query + context + f'&page_size=2&page={number}', headers=headers).get_json()['items']) + exported = client.get('/cama/seguimiento/exportacion' + query + context, headers=headers).get_json() + assert exported['items'] == rows + assert client.get('/cama/pacientes/' + rows[0]['pac_id'] + query + context, headers=headers).get_json()['item'] == rows[0] + assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store' + + +def test_regular_followup_checks_access_and_suppression(client): + """The ordinary route cannot bypass authorization or suppression.""" + assert client.get('/cama/seguimiento').status_code == 403 + headers = {'X-Test': 'yes'} + assert client.get('/cama/seguimiento?corte=2026-10-20&birads=BIRADS_4', headers=headers).status_code == 403 + assert client.get('/cama/seguimiento?corte=2026-10-20&estatus=BENIGNO', headers=headers).status_code == 400 + assert client.get('/cama/seguimiento?revision=' + '0' * 64, headers=headers).status_code == 400 + client.application.config['CAMA_COHORT_ACCESS'] = 'invalid' + assert client.get('/cama/seguimiento', headers=headers).status_code == 403 + + +def test_disabled_provider_and_empty_window(client): + """Unavailable sources fail closed and an empty unfiltered window stays empty.""" + headers = {'X-Test': 'yes'} + body = client.get('/cama/seguimiento?corte=2025-01-01&meses=3', headers=headers).get_json() + assert body['items'] == [] and body['paginacion']['total_items'] == 0 + client.application.config['CAMA_COHORT_READER'] = None + assert client.get('/cama/seguimiento', headers=headers).status_code == 503 + + +def test_provider_failure_does_not_break_other_routes(client): + """A failing cohort source returns unavailable while the app can serve other requests.""" + def fail(_cutoff): + raise RuntimeError('provider unavailable') + + client.application.add_url_rule('/health', 'health', lambda: {'status': 'ok'}) + client.application.config['CAMA_COHORT_READER'] = fail + assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503 + assert client.get('/cama/seguimiento?corte=2026-10-20', headers={'X-Test': 'yes'}).status_code == 503 + assert client.get('/health').get_json() == {'status': 'ok'} diff --git a/webapi/__init__.py b/webapi/__init__.py index c832bb5..fd9e34d 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -31,6 +31,9 @@ class IsoJSONProvider(DefaultJSONProvider): def create_app() -> Flask: app = Flask(__name__) app.json = IsoJSONProvider(app) + from webapi.cama_runtime import configure_cama_cohort + + configure_cama_cohort(app) # File sources travel inside the request; cap them per request. app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024 @@ -93,8 +96,17 @@ def create_app() -> Flask: from persistance.db import get_cacu_session from webapi.patient_risk import patient_risk_blueprint + from webapi.risk_batches import risk_batches_blueprint app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu") + app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu") + + # CaMa's follow-up list and analysis selection, over the breast screening cohort `configure_cama_cohort` reads. + from webapi.cama_analysis import analysis as cama_analysis_bp + from webapi.seguimiento_cama import blueprint_seguimiento_cama + + app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama") + app.register_blueprint(cama_analysis_bp, url_prefix="/cama") return app diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index c907e28..ec4c11e 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -1,13 +1,18 @@ """Model governance (ML, MLD, EL and VAR requirements): model versions and -their promotion, notebooks run on a cohort build, and the OCR extraction -jobs with their manual review queue. +their training and promotion, notebooks run on a cohort build, and the OCR +extraction jobs with their manual review queue. -Versions and artifacts live in MLflow (`models.io.registry`); training runs -elsewhere and registers its result through `POST /model-versions`, naming -the indicator kit cohort build it was trained on (`cohorte_armado_id`). +Versions and artifacts live in MLflow (`models.io.registry`). Training can +either run elsewhere and register its result through `POST /model-versions` +(naming the indicator kit cohort build it was trained on, +`cohorte_armado_id`), or be triggered in place through `POST +/model-versions///train`, for a deployment with no +command-line access to run the `entrenar` compose profile by hand. Notebooks (`models.pipelines.experiment`) run in the background on the build's file alone and are kept as MLflow runs. """ +import contextlib +import io import json import os from concurrent.futures import ThreadPoolExecutor @@ -84,6 +89,34 @@ def register_model_version(): return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201 +@governance_bp.post("/model-versions///train") +def train_model_version(domain: str, scenario: str): + """Exports the scenario's latest dbt cohort build, trains a PROD version on it unless one from the same file, + code and environment already exists, and tries to promote it: the same one-shot pipeline the `entrenar` + compose profile runs (`models run --export --source dbt --environment prod --train + --promote`), over HTTP instead of a shell. 503 with no dbt manifest configured; 404 for a domain/scenario with + no trainer or whose cohort isn't exportable yet; 409 with the training's own version trained but not promoted + (it's missing its validation reports: attach them, then `/promote`).""" + from models.__main__ import main as models_main + + manifest = os.environ.get("DBT_MANIFEST") + if not manifest: + return jsonify({"error": "No hay un manifest de dbt configurado."}), 503 + argv = ["run", domain, scenario, "--export", "--source", "dbt", "--manifest", manifest, "--environment", "prod", + "--train", "--promote"] + out, err = io.StringIO(), io.StringIO() + try: + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = models_main(argv) + except SystemExit as exit: + code = exit.code if isinstance(exit.code, int) else 1 + output, error = out.getvalue().strip(), err.getvalue().strip() + if code == 0: + return jsonify({"output": output}) + status = 404 if "no such model" in error else 409 if "not promoted, missing" in error else 503 + return jsonify({"error": error or "No se pudo entrenar el modelo.", "output": output}), status + + @governance_bp.patch("/model-versions////reports") def attach_reports(domain: str, scenario: str, version: str): """MLD-01/01b/03 documents, usually written after training.""" diff --git a/webapi/cama_analysis.py b/webapi/cama_analysis.py new file mode 100644 index 0000000..0d9f523 --- /dev/null +++ b/webapi/cama_analysis.py @@ -0,0 +1,168 @@ +"""Aggregate and select the breast cohort through the same configured reader.""" + +from datetime import date +import hashlib +import hmac +import json + +from flask import Blueprint, current_app, jsonify, request + +from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD + +analysis = Blueprint('cama_analysis', __name__) +BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6') +AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO') + + +class SelectionError(Exception): + def __init__(self, message, status=400): + self.message, self.status = message, status + + +def read_cohort(cutoff): + reader = current_app.config.get('CAMA_COHORT_READER') + if not callable(reader): + raise SelectionError('Cohorte no disponible', 503) + try: + return reader(cutoff) + except Exception: + current_app.logger.exception('Breast cohort provider failed') + raise SelectionError('Cohorte no disponible', 503) from None + + +def cutoff_arg(args): + text = args.get('corte') + if not text: + raise SelectionError('Se requiere corte') + try: + value = date.fromisoformat(text) + if value.isoformat() != text or value.year == 9999: + raise ValueError() + return value + except ValueError: + raise SelectionError('Corte inválido') from None + + +def patient_access(): + check = current_app.config.get('CAMA_COHORT_ACCESS') + if check is not None and (not callable(check) or not check(request)): + raise SelectionError('Acceso no autorizado', 403) + + +def revision_of(rows): + """Identify the materialized cohort without exposing its patient identifiers.""" + encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode() + return hashlib.sha256(encoded).hexdigest() + + +def cohort_request(args): + allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'} + if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args): + raise SelectionError('Parámetros desconocidos o repetidos') + if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO: + raise SelectionError('Cohorte o escenario desconocido') + revision = args.get('revision', '') + if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision): + raise SelectionError('Revisión de cohorte inválida') + cutoff = cutoff_arg(args) + try: + months = int(args.get('meses', '3')) + page = int(args.get('page', '1')) + size = int(args.get('page_size', '50')) + if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200: + raise ValueError() + except ValueError: + raise SelectionError('Ventana o paginación inválida') from None + filters = {key: args.get(key) for key in ('birads', 'grupo_edad')} + if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES): + raise SelectionError('Filtro inválido') + return cutoff, months, page, size, filters, revision + + +def selected(args): + patient_access() + from werkzeug.datastructures import MultiDict + + args = MultiDict(args) + if 'cohorte' not in args: + if any(key in args for key in ('revision', 'escenario')): + raise SelectionError('Contexto de cohorte incompleto') + if 'corte' not in args: + args['corte'] = date.today().isoformat() + cutoff = cutoff_arg(args) + rows = read_cohort(cutoff) + args.update({'cohorte': COHORT, 'escenario': SCENARIO, 'revision': revision_of(rows)}) + else: + rows = None + cutoff, months, page, size, filters, revision = cohort_request(args) + if rows is None: + rows = read_cohort(cutoff) + if not hmac.compare_digest(revision, revision_of(rows)): + raise SelectionError('La cohorte cambió; actualiza el análisis', 409) + selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())] + if months: + from webapi.seguimiento_cama import _desde + try: + since = _desde(cutoff, months) + except (ValueError, OverflowError): + raise SelectionError('Ventana inválida') from None + else: + since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff) + selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff] + # Every filtered selection is checked on the server after applying the window. + if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())): + raise SelectionError('Selección no disponible', 403) + return cutoff, months, page, size, filters, since, selected_rows, revision + + +def selection_response(args, mode, patient=None): + cutoff, months, page, size, filters, since, rows, revision = selected(args) + options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)] + columns = [ + {'clave': 'pac_id', 'etiqueta': 'Identificador de paciente'}, + {'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'}, + {'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]}, + {'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]}, + ] + meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(), + 'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()}, + 'campo_ventana': 'mastografia_fecha', 'filtros': filters, + 'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]} + for k, label, values in options], 'columnas': columns} + if mode == 'patient': + found = next((row for row in rows if row['pac_id'] == patient), None) + if found is None: + raise SelectionError('Paciente no encontrado', 404) + return jsonify(**meta, item=found) + if mode == 'export': + if len(rows) > 5000: + raise SelectionError('La exportación supera el límite de 5000 registros', 413) + return jsonify(**meta, total_items=len(rows), items=rows) + return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows), + 'total_pages': (len(rows) + size - 1) // size}, + items=rows[(page - 1) * size:page * size]) + + +@analysis.get('/analisis/indicadores') +def indicators(): + try: + if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1: + raise SelectionError('Se requiere únicamente corte') + cutoff = cutoff_arg(request.args) + rows = read_cohort(cutoff) + groups = [] + for code in BIRADS: + count = sum(r['birads'] == code for r in rows) + groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD}) + return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(), + horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente', + denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6', + indicadores=[], grupos=groups) + except SelectionError as e: + return jsonify(error=e.message), e.status + + +@analysis.after_request +def no_cache(response): + response.headers['Cache-Control'] = 'no-store' + return response diff --git a/webapi/cama_cohort.py b/webapi/cama_cohort.py new file mode 100644 index 0000000..63ef008 --- /dev/null +++ b/webapi/cama_cohort.py @@ -0,0 +1,195 @@ +"""Read the breast screening cohort from the existing silver tables. + +The current silver tables keep only the last version of each fact. Filtering by +load date prevents future facts from appearing at an earlier cutoff, but cannot +restore a previous value after an update. +""" + +from datetime import date, datetime, time, timedelta, timezone + +from sqlalchemy import func, select +from sqlalchemy.orm import aliased + +from webapi.orchestration.tables.cama import TABLAS + + +COHORT = "cama_birads_v1" +SCENARIO = "diagnostico" +THRESHOLD = 5 + +# `core/catalogos/cama.toml`'s `mastografia.resultados.birads`: the cohort is restricted to the codes that call +# for a biopsy (B4 and its subcategories, B5, B6); B0 to B3 fall out by not being in this map. +BIRADS = {"B4": "BIRADS_4", "B4A": "BIRADS_4A", "B4B": "BIRADS_4B", "B4C": "BIRADS_4C", "B5": "BIRADS_5", "B6": "BIRADS_6"} + + +def mastografias(t): + """One row per mammogram taken, with the report that hangs from it (nulls when it has none): the Python + equivalent of `Transformation/models/cama/silver/cama_mastografias.sql`, kept independent of dbt's manifest + since this reader runs without one.""" + toma, reporte, obs_birads = aliased(t.Procedimiento), aliased(t.Procedimiento), aliased(t.Observacion) + return ( + select( + toma.procedimiento_id.label("procedimiento_id"), + toma.fuente_tabla.label("fuente_tabla"), + toma.fuente_id.label("fuente_id"), + toma.pac_id.label("pac_id"), + toma.fecha.label("fecha_toma"), + reporte.procedimiento_id.label("reporte_id"), + reporte.fecha.label("fecha_reporte"), + func.coalesce(obs_birads.valor_id, obs_birads.valor_fuente).label("birads"), + ) + .select_from(toma) + .outerjoin(reporte, (reporte.padre_id == toma.procedimiento_id) & (reporte.estudio_id == "mastografia") + & (reporte.clase == "reporte")) + .outerjoin(obs_birads, (obs_birads.procedimiento_id == reporte.procedimiento_id) + & (obs_birads.resultado_id == "mastografia.birads")) + .where(toma.estudio_id == "mastografia", toma.clase == "toma") + ) + + +def biopsias(t): + """One row per biopsy report with its grade, its order and the mammogram that led to it, if found: mammogram + (toma) -> biopsy order -> biopsy report, by `padre_id`. The Python equivalent of + `Transformation/models/cama/silver/cama_biopsias.sql`, plus the mammogram's own date and patient (`fecha_toma`, + `toma_pac_id`), which the cohort's cross-check needs and the dbt model doesn't expose.""" + reporte, orden, toma, obs_grado = (aliased(t.Procedimiento), aliased(t.Procedimiento), aliased(t.Procedimiento), + aliased(t.Observacion)) + return ( + select( + reporte.procedimiento_id.label("procedimiento_id"), + reporte.fuente_tabla.label("fuente_tabla"), + reporte.fuente_id.label("fuente_id"), + reporte.pac_id.label("pac_id"), + reporte.fecha.label("fecha_reporte"), + func.coalesce(obs_grado.valor_id, obs_grado.valor_fuente).label("grado"), + orden.fecha.label("fecha_solicitud"), + toma.procedimiento_id.label("toma_id"), + toma.fecha.label("fecha_toma"), + toma.pac_id.label("toma_pac_id"), + ) + .select_from(reporte) + .outerjoin(obs_grado, (obs_grado.procedimiento_id == reporte.procedimiento_id) + & (obs_grado.resultado_id == "biopsia.grado")) + .outerjoin(orden, (orden.procedimiento_id == reporte.padre_id) & (orden.estudio_id == "biopsia") + & (orden.clase == "orden")) + .outerjoin(toma, (toma.procedimiento_id == orden.padre_id) & (toma.estudio_id == "mastografia") + & (toma.clase == "toma")) + .where(reporte.estudio_id == "biopsia", reporte.clase == "reporte") + ) + + +def _date(value): + return date.fromisoformat(value) if isinstance(value, str) else value + + +def _known(value, cutoff): + if value is None: + return False + if isinstance(value, str): + value = datetime.fromisoformat(value) + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc) + + +def _age_group(birth, cutoff): + if birth is None or birth > cutoff: + return "SIN_DATO" + age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day)) + if age < 40: + return "MENOR_40" + if age >= 70: + return "70+" + return f"{age // 10 * 10}-{age // 10 * 10 + 9}" + + +class CamaCohort: + """Materialize one row per eligible patient, using a caller-owned session.""" + + def __init__(self, session): + self.session = session + + def rows(self, cutoff: date): + t = TABLAS + loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()} + procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()} + observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()} + people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()} + + def procedure_known(identifier): + p = procedures.get(identifier) + return bool(p and _known(loads.get(p.carga_id), cutoff)) + + def observation_known(identifier, result, patient): + o = observations.get((identifier, result)) + return bool(o and o.pac_id == patient and _known(loads.get(o.carga_id), cutoff)) + + def load_time(record): + value = loads.get(record.carga_id) if record else None + return value.isoformat() if value else None + + candidates = {} + for row in self.session.execute(mastografias(t)).mappings(): + taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte']) + if not (taken and reported and taken <= reported <= cutoff and row['birads'] + and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id']) + and procedures[row['reporte_id']].pac_id == row['pac_id'] + and observation_known(row['reporte_id'], 'mastografia.birads', row['pac_id'])): + continue + key = (taken, str(row['fuente_id']), reported, row['reporte_id']) + prior = candidates.get(row['pac_id']) + if prior is None or key > prior[0]: + candidates[row['pac_id']] = (key, row) + + reports = {} + orders = {} + for p in procedures.values(): + when = _date(p.fecha) + if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when + or when > cutoff or not procedure_known(p.procedimiento_id)): + continue + key = (p.pac_id, p.padre_id) + rank = (when, str(p.fuente_id), p.procedimiento_id) + if key not in orders or rank > orders[key][0]: + orders[key] = (rank, p) + for row in self.session.execute(biopsias(t)).mappings(): + reported, ordered, taken = (_date(row['fecha_reporte']), _date(row['fecha_solicitud']), + _date(row['fecha_toma'])) + procedure = procedures.get(row['procedimiento_id']) + order = procedures.get(procedure.padre_id) if procedure else None + if not (taken and reported and ordered and taken <= ordered <= reported <= cutoff and row['toma_id'] + and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id']) + and order and order.pac_id == row['pac_id'] and procedure_known(order.procedimiento_id)): + continue + key = (row['pac_id'], row['toma_id']) + rank = (reported, str(row['fuente_id']), row['procedimiento_id']) + if key not in reports or rank > reports[key][0]: + reports[key] = (rank, row) + + rows = [] + for patient, (_, m) in candidates.items(): + code = BIRADS.get(m['birads']) + if not code or patient not in people: + continue + b = reports.get((patient, m['procedimiento_id'])) + b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None + order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None + if not order: + found_order = orders.get((patient, m['procedimiento_id'])) + order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None + grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None + rows.append({ + 'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(), + 'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(), + 'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff), + 'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None, + 'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None, + 'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]), + 'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]), + 'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))), + 'biopsia_solicitud_carga_inicio': load_time(order), + 'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None, + 'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado'))) + if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None, + }) + return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id']))) diff --git a/webapi/cama_runtime.py b/webapi/cama_runtime.py new file mode 100644 index 0000000..a14ae3f --- /dev/null +++ b/webapi/cama_runtime.py @@ -0,0 +1,12 @@ +"""Configure the breast cohort using the shared persistence settings.""" + +from persistance.db import get_cama_session +from webapi.cama_cohort import CamaCohort + + +def configure_cama_cohort(app): + def read(cutoff): + with get_cama_session() as session: + return CamaCohort(session).rows(cutoff) + + app.config['CAMA_COHORT_READER'] = read diff --git a/webapi/risk_batches.py b/webapi/risk_batches.py new file mode 100644 index 0000000..c92217d --- /dev/null +++ b/webapi/risk_batches.py @@ -0,0 +1,45 @@ +"""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//riesgo`) or void it (`entered-in-error`). +`GET/POST //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. +""" + +from flask import Blueprint, jsonify, request +from persistance.edges.gold import ERROR, FINAL + + +def risk_batches_blueprint(repositories) -> Blueprint: + """The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`.""" + blueprint = Blueprint("risk_batches", __name__) + + @blueprint.get("/riesgos/lotes") + def list_pending_batches(): + """Pending batches, newest first.""" + return jsonify([_batch(b) for b in repositories.cohort_repository.pending_batches()]) + + @blueprint.post("/riesgos/lotes//confirmar") + def confirm_batch(lote_id: int): + """Moves every current evaluation of the batch to `final` (ADR-MD-008): a clinical decision, with its + reason. 404 if the batch doesn't exist or has no evaluation left to decide.""" + return _decide(lote_id, FINAL) + + @blueprint.post("/riesgos/lotes//anular") + def void_batch(lote_id: int): + """Moves every current evaluation of the batch to `entered-in-error`.""" + return _decide(lote_id, ERROR) + + def _decide(lote_id: int, estado: str): + reason = (request.get_json(silent=True) or {}).get("reason", "").strip() + if not reason: + return jsonify({"error": "se requiere un motivo"}), 400 + changed = repositories.cohort_repository.change_state(lote_id, estado, reason) + if not changed: + return jsonify({"error": f"el lote {lote_id} no existe o ya no tiene evaluaciones vigentes"}), 404 + return jsonify({"lote_id": lote_id, "evaluaciones_cambiadas": changed}) + + return blueprint + + +def _batch(batch) -> dict: + return {"lote_id": batch.lote_id, "modelo_nombre": batch.modelo_nombre, "modelo_version": batch.modelo_version, + "evaluado_en": batch.evaluado_en.isoformat(), "n_evaluaciones": batch.n_evaluaciones} diff --git a/webapi/seguimiento_cama.py b/webapi/seguimiento_cama.py new file mode 100644 index 0000000..bcac080 --- /dev/null +++ b/webapi/seguimiento_cama.py @@ -0,0 +1,46 @@ +"""Patient follow-up for the configured breast cohort.""" + +import calendar +from datetime import date, timedelta + +from flask import Blueprint, jsonify, request + +from webapi.cama_analysis import SelectionError, selection_response + + +def _desde(corte, meses): + indice = corte.year * 12 + corte.month - 1 - meses + anio, mes = divmod(indice, 12) + if anio < 1: + raise ValueError("la ventana excede el rango de fechas admitido") + anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1])) + return anterior + timedelta(days=1) + + +def blueprint_seguimiento_cama(): + blueprint = Blueprint("cama_seguimiento", __name__) + + @blueprint.after_request + def no_cache(response): + response.headers["Cache-Control"] = "no-store" + return response + + def respond(mode, patient=None): + try: + return selection_response(request.args, mode, patient) + except SelectionError as error: + return jsonify(error=error.message), error.status + + @blueprint.get("/seguimiento") + def seguimiento(): + return respond('list') + + @blueprint.get("/seguimiento/exportacion") + def exportacion(): + return respond('export') + + @blueprint.get("/pacientes/") + def paciente(pac_id): + return respond('patient', pac_id) + + return blueprint