diff --git a/docs/cama-cohort-api.md b/docs/cama-cohort-api.md index 47d2ea3..d4713c3 100644 --- a/docs/cama-cohort-api.md +++ b/docs/cama-cohort-api.md @@ -1,12 +1,17 @@ # Breast cohort: synthetic integration contract -This contract is opt-in and only for a synthetic source. The server must set -`CAMA_COHORT_SYNTHETIC` to `True`, provide `CAMA_COHORT_READER(cutoff)` and -provide `CAMA_COHORT_ACCESS(request)`. Without a reader the aggregate returns -503. Without an access callback or when it returns false, all cohort patient -list, detail and export requests return 403. The existing fixture endpoints -remain available when `cohorte` is absent. This is not a production access -policy; authorization for real patient data has not been implemented. +This contract is opt-in and only for a synthetic source. Set +`CAMA_COHORT_SYNTHETIC=1`, `CAMA_COHORT_SECRET` and +`CAMA_COHORT_ACCESS_TOKEN` in the server environment. The pseudonym secret +must have at least 32 UTF-8 bytes; the token must be at least 32 ASCII +letters, digits, underscores or hyphens. The application reads the configured CaMa database +and checks the `X-Cama-Cohort-Token` request header on patient routes. Store +the pseudonym secret persistently: changing it changes every pseudonym. The +header must be supplied by a trusted server-side access boundary, never +embedded in browser code. Without an enabled reader the aggregate returns +503; without authorized access the patient routes return 403. This is not a +production access policy; authorization for real patient data has not been +implemented. `GET /cama/analisis/indicadores?corte=2026-10-20` returns a descriptive count by BI-RADS. It includes `cohorte`, `revision`, `escenario`, `corte`, @@ -37,6 +42,14 @@ accepts `page` and `page_size` (maximum 200). Export is limited to 5,000. cohort is empty it is the cutoff. `hasta` is the inclusive cutoff. Windows 1, 3, 6 and 12 retain their calendar-month semantics. +Regular follow-up accepts the same window and filters without cohort context; +it reads the same source, checks access and returns its cohort context and +revision. When omitted, cutoff is the server's current date and the window is +three months. Quote the returned context in subsequent page, detail and export +requests to pin them to that revision. The old independent fixture, status and +priority filters are no longer served; these values cannot be derived safely +from the available records. + BI-RADS codes are `BIRADS_4`, `BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`, `BIRADS_5`, `BIRADS_6`. Age options are `MENOR_40`, `40-49`, `50-59`, `60-69`, `70+`, `SIN_DATO`. Filters combine with AND. Unknown, duplicated or @@ -64,3 +77,8 @@ and requires `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` of at least Other domain database URLs are set to isolated in-memory SQLite by the example. The Windows-only `fcntl` shim raises if locking is attempted: this example does not validate file-locking functionality. + +`examples/serve_cama_integration.py` runs normal application configuration +against an existing disposable SQLite copy, with a stable secret file and a +temporary token injected by its loopback-only test proxy. It is suitable only +for local synthetic integration and does not provide production authentication. diff --git a/examples/serve_cama_integration.py b/examples/serve_cama_integration.py new file mode 100644 index 0000000..0da2c83 --- /dev/null +++ b/examples/serve_cama_integration.py @@ -0,0 +1,50 @@ +"""Serve an isolated synthetic database through a loopback-only test proxy.""" + +import argparse +import os +from pathlib import Path +import secrets +import sys +import types + +parser = argparse.ArgumentParser() +parser.add_argument('--database', required=True, help='Existing disposable synthetic SQLite database') +parser.add_argument('--secret-file', required=True, help='Persistent local pseudonym secret file') +parser.add_argument('--port', type=int, default=5059) +args = parser.parse_args() +database = Path(args.database).resolve(strict=True) +if not database.is_file(): + raise ValueError('The synthetic database must be an existing file') +secret_file = Path(args.secret_file).resolve() +if not secret_file.exists(): + with secret_file.open('x', encoding='ascii') as output: + output.write(secrets.token_hex(32)) +secret = secret_file.read_text(encoding='ascii').strip() +token = secrets.token_hex(32) +os.environ.update(CAMA_DATABASE_URL='sqlite:///' + database.as_posix(), + CAMA_COHORT_SYNTHETIC='1', CAMA_COHORT_SECRET=secret, + CAMA_COHORT_ACCESS_TOKEN=token, MLFLOW_DISABLE_AGENT_HINT='1', + MLFLOW_DISABLE_TELEMETRY='true') +for domain in ('CACU', 'TEA', 'GOVERNANCE'): + os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:' +if os.name == 'nt': + fcntl = types.ModuleType('fcntl') + fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8 + def unavailable(*_args): + raise RuntimeError('POSIX locking is unavailable in this Windows test harness') + fcntl.flock = unavailable + sys.modules['fcntl'] = fcntl + +from webapi import create_app +from werkzeug.serving import make_server + +app = create_app() +application = app.wsgi_app + +def test_proxy(environ, start_response): + # The harness is loopback-only and replaces any caller-supplied test token. + environ['HTTP_X_CAMA_COHORT_TOKEN'] = token + return application(environ, start_response) + +print(f'Isolated synthetic test proxy: http://127.0.0.1:{args.port}', flush=True) +make_server('127.0.0.1', args.port, test_proxy, threaded=True).serve_forever() diff --git a/tests/test_cama_cohort.py b/tests/test_cama_cohort.py index 907d288..ff4ac4a 100644 --- a/tests/test_cama_cohort.py +++ b/tests/test_cama_cohort.py @@ -130,19 +130,16 @@ def test_links_and_load_dates_are_distinct(client, cohort_db): assert set(rows) == set(rows_later) -def test_full_application_registers_cohort_and_preserves_legacy(client): - """The application registers the aggregate while retaining legacy follow-up.""" +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').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 - rows = full.get('/cama/seguimiento?corte=2026-10-16&meses=1').get_json()['items'] - future = next(row for row in rows if row['id_seudonimo'] == 'M-0002') - assert future['biopsia_fecha'] is None and future['biopsia'] is None def test_windows_and_disabled_provider(client): diff --git a/tests/test_cama_runtime.py b/tests/test_cama_runtime.py new file mode 100644 index 0000000..47a68df --- /dev/null +++ b/tests/test_cama_runtime.py @@ -0,0 +1,38 @@ +"""Verify the synthetic cohort's opt-in startup and server-side access check.""" + +import pytest +from flask import Flask + +from webapi.cama_runtime import configure_cama_cohort + + +def test_synthetic_cohort_requires_explicit_configuration(monkeypatch): + """Missing or short secrets must not silently enable patient access.""" + monkeypatch.delenv('CAMA_COHORT_SYNTHETIC', raising=False) + app = Flask(__name__) + configure_cama_cohort(app) + assert 'CAMA_COHORT_READER' not in app.config + monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1') + monkeypatch.setenv('CAMA_COHORT_SECRET', 'short') + monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32) + with pytest.raises(ValueError): + configure_cama_cohort(app) + monkeypatch.setenv('CAMA_COHORT_SECRET', 's' * 32) + monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32 + '";') + with pytest.raises(ValueError): + configure_cama_cohort(app) + + +def test_access_token_is_checked_on_the_server(monkeypatch): + """Only requests bearing the configured token can use the cohort patient routes.""" + monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1') + monkeypatch.setenv('CAMA_COHORT_SECRET', 's' * 32) + monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32) + app = Flask(__name__) + configure_cama_cohort(app) + with app.test_request_context(headers={'X-Cama-Cohort-Token': 't' * 32}): + from flask import request + assert app.config['CAMA_COHORT_ACCESS'](request) + with app.test_request_context(headers={'X-Cama-Cohort-Token': 'incorrect'}): + from flask import request + assert not app.config['CAMA_COHORT_ACCESS'](request) diff --git a/tests/test_seguimiento_cama.py b/tests/test_seguimiento_cama.py index 729042e..64e5dd0 100644 --- a/tests/test_seguimiento_cama.py +++ b/tests/test_seguimiento_cama.py @@ -1,152 +1,58 @@ -"""Contrato HTTP de seguimiento CaMa, con datos exclusivamente inventados.""" +"""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(id_seudonimo=f'patient-{n}', 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(blueprint_seguimiento_cama(), url_prefix="/cama") + 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 get(client, query=""): - return client.get("/cama/seguimiento" + query) +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]['id_seudonimo'] + query + context, headers=headers).get_json()['item'] == rows[0] + assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store' -def test_formato_y_metadatos(client): - response = get(client) - assert response.status_code == 200 and response.mimetype == "application/json" - data = response.get_json() - assert set(data) == {"simulado", "corte", "ventana", "campo_ventana", "filtros", "filtros_disponibles", "columnas", "paginacion", "items"} - assert data["simulado"] is True and data["corte"] == "2026-10-20" - assert data["ventana"] == {"meses": 3, "desde": "2026-07-21", "hasta": "2026-10-20"} - assert data["paginacion"] == {"page": 1, "page_size": 50, "total_items": 5, "total_pages": 1} - assert set(data["filtros"]) == {f["clave"] for f in data["filtros_disponibles"]} - assert all(f["opciones"] for f in data["filtros_disponibles"]) - assert data["campo_ventana"] == "mastografia_fecha" - assert [c["clave"] for c in data["columnas"]] == ["id_seudonimo", "grupo_edad", "estatus", "birads", "biopsia", "dias_mastografia_diagnostico", "prioridad"] - for f in data["filtros_disponibles"]: - opciones = {o["codigo"]: o["etiqueta"] for o in f["opciones"]} - assert all(opciones[i[f["clave"] + "_codigo"]] == i[f["clave"]] for i in data["items"]) - assert all(isinstance(v, (str, int, float)) or v is None for i in data["items"] for v in i.values()) - assert len({i["id_seudonimo"] for i in data["items"]}) == 5 - assert "pac_id" not in response.get_data(as_text=True) - for columna in data["columnas"]: - assert all(columna["clave"] in item and all(d["clave"] in item for d in columna.get("detalles", [])) for item in data["items"]) +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 -def test_ruta_registrada_en_aplicacion(): - from webapi import create_app - - response = create_app().test_client().get("/cama/seguimiento") - assert response.status_code == 200 and response.get_json()["simulado"] is True - - -@pytest.mark.parametrize("clave,codigo,valor", [ - ("estatus", "PENDIENTE_BIOPSIA", "Pendiente de biopsia"), ("birads", "BIRADS_5", "BI-RADS 5"), - ("grupo_edad", "40-49", "40-49"), ("prioridad", "ALTA", "Alta"), -]) -def test_filtros(client, clave, codigo, valor): - data = get(client, f"?meses=12&{clave}={codigo}").get_json() - assert data["filtros"][clave] == codigo and data["items"] - assert all(item[clave] == valor for item in data["items"]) - - -def test_combinacion_paginacion_y_orden(client): - query = "?meses=12&prioridad=ALTA&page_size=1" - paginas = [get(client, query + f"&page={n}").get_json() for n in (1, 2, 3)] - assert all(p["paginacion"]["total_items"] == 3 and p["paginacion"]["total_pages"] == 3 for p in paginas) - assert [p["items"][0]["id_seudonimo"] for p in paginas] == ["M-0001", "M-0004", "M-0007"] - fuera = get(client, query + "&page=4") - assert fuera.status_code == 200 and fuera.get_json()["items"] == [] - assert fuera.get_json()["paginacion"]["total_pages"] == 3 - ids = [i["id_seudonimo"] for i in get(client).get_json()["items"]] - assert ids[:2] == ["M-0001", "M-0002"] - assert ids == [i["id_seudonimo"] for i in get(client).get_json()["items"]] - - -def test_ventanas_y_fronteras(client): - assert get(client, "?corte=2026-10-20&meses=1").get_json()["ventana"]["desde"] == "2026-09-21" - assert get(client, "?corte=2026-10-20&meses=6").get_json()["paginacion"]["total_items"] == 6 - assert get(client, "?corte=2026-10-20&meses=12").get_json()["paginacion"]["total_items"] == 8 - assert [i["id_seudonimo"] for i in get(client, "?corte=2026-07-21&meses=1").get_json()["items"]] == ["M-0005"] - assert get(client, "?corte=2024-03-31&meses=1").get_json()["ventana"]["desde"] == "2024-03-01" - - -def test_vacio_y_pagina_vacia(client): - for query in ("?corte=2020-01-01&page=5", "?estatus=BENIGNO&birads=BIRADS_5"): - response = get(client, query) - assert response.status_code == 200 - assert response.get_json()["items"] == [] - assert response.get_json()["paginacion"]["total_pages"] == 0 - - -@pytest.mark.parametrize("query", ["?corte=ayer", "?corte=2026-02-30", "?corte=0001-01-01", "?meses=2", "?meses=x", "?page=0", "?page=-1", "?page_size=0", "?page_size=201", "?estatus=X", "?birads=X", "?grupo_edad=X", "?prioridad=X"]) -def test_parametros_invalidos(client, query): - response = get(client, query) - assert response.status_code == 400 and isinstance(response.get_json()["error"], str) - - -def test_error_de_fuente_es_json(client, monkeypatch): - def fallar(corte, desde): - raise RuntimeError("detalle interno") - monkeypatch.setattr("webapi.seguimiento_cama.leer_fixture", fallar) - response = get(client) - assert response.status_code == 500 and response.is_json - assert "detalle interno" not in response.get_data(as_text=True) - -@pytest.mark.parametrize("query", ["?meses=12", "?meses=6&estatus=BENIGNO", "?meses=12&birads=BIRADS_5", "?meses=12&grupo_edad=40-49", "?meses=12&prioridad=ALTA", "?meses=12&prioridad=ALTA&birads=BIRADS_5", "?corte=2026-07-21&meses=1", "?estatus=BENIGNO&birads=BIRADS_5"]) -def test_exportacion_coincide_con_paginas(client, query): - response = client.get('/cama/seguimiento/exportacion' + query + '&page=2&page_size=1') - assert response.status_code == 200 and response.headers['Cache-Control'] == 'no-store' - data = response.get_json() - primera = get(client, query + '&page=1&page_size=1').get_json() - items = [] - for page in range(1, primera['paginacion']['total_pages'] + 1): - items.extend(get(client, query + f'&page={page}&page_size=1').get_json()['items']) - assert data['items'] == items - assert data['total_items'] == len(items) == primera['paginacion']['total_items'] - for key in ('simulado', 'corte', 'ventana', 'campo_ventana', 'filtros', 'filtros_disponibles', 'columnas'): - assert data[key] == primera[key] - assert data['simulado'] is True - - -@pytest.mark.parametrize('query', ['?corte=ayer', '?corte=0001-01-01', '?meses=2', '?meses=x', '?estatus=X', '?birads=X', '?grupo_edad=X', '?prioridad=X']) -def test_exportacion_parametros_invalidos(client, query): - response = client.get('/cama/seguimiento/exportacion' + query) - assert response.status_code == 400 and response.headers['Cache-Control'] == 'no-store' - - -def test_exportacion_limite_y_error(client, monkeypatch): - import webapi.seguimiento_cama as modulo - original = modulo.leer_fixture - fila = original(None, None)[0] - monkeypatch.setattr(modulo, 'leer_fixture', lambda corte, desde: [fila] * 5000) - assert client.get('/cama/seguimiento/exportacion').get_json()['total_items'] == 5000 - monkeypatch.setattr(modulo, 'leer_fixture', lambda corte, desde: [fila] * 5001) - response = client.get('/cama/seguimiento/exportacion') - assert response.status_code == 413 and 'items' not in response.get_json() - def fallar(corte, desde): - raise RuntimeError('secreto interno') - monkeypatch.setattr(modulo, 'leer_fixture', fallar) - response = client.get('/cama/seguimiento/exportacion') - assert response.status_code == 500 and 'secreto interno' not in response.get_data(as_text=True) - - -def test_detalle_misma_fila_y_ausencias(client): - lista = get(client, '?meses=12').get_json() - response = client.get('/cama/pacientes/M-0001?meses=12') - data = response.get_json() - assert response.status_code == 200 and response.headers['Cache-Control'] == 'no-store' - assert data['simulado'] is True and data['ventana'] == lista['ventana'] - assert data['item'] == lista['items'][0] - assert data['item']['biopsia'] is None and data['item']['biopsia_fecha'] is None - assert set(data) == {'simulado', 'corte', 'ventana', 'item'} - assert set(data['item']) == set(lista['items'][0]) - assert client.get('/cama/pacientes/M-0008').status_code == 404 - assert client.get('/cama/pacientes/M-0008?meses=12').status_code == 200 - assert client.get('/cama/pacientes/M-9999?meses=12').status_code == 404 - assert client.get('/cama/pacientes/M-0001?meses=2').status_code == 400 +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_SYNTHETIC'] = False + assert client.get('/cama/seguimiento', headers=headers).status_code == 503 diff --git a/webapi/__init__.py b/webapi/__init__.py index f14c714..c23cdd5 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -35,6 +35,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 diff --git a/webapi/cama_analysis.py b/webapi/cama_analysis.py index 5b48601..c566bbd 100644 --- a/webapi/cama_analysis.py +++ b/webapi/cama_analysis.py @@ -77,14 +77,31 @@ def cohort_request(args): 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) - rows = read_cohort(cutoff) + 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 - since = _desde(cutoff, months) + 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] diff --git a/webapi/cama_runtime.py b/webapi/cama_runtime.py new file mode 100644 index 0000000..ded6fbb --- /dev/null +++ b/webapi/cama_runtime.py @@ -0,0 +1,27 @@ +"""Configure the opt-in synthetic breast cohort for the application.""" + +import hmac +import os +import re + +from persistance.db import get_cama_session +from webapi.cama_cohort import CamaCohort + + +def configure_cama_cohort(app): + if os.environ.get('CAMA_COHORT_SYNTHETIC') != '1': + return + secret = os.environ.get('CAMA_COHORT_SECRET', '').encode('utf-8') + token = os.environ.get('CAMA_COHORT_ACCESS_TOKEN', '') + if len(secret) < 32 or not re.fullmatch(r'[A-Za-z0-9_-]{32,}', token): + raise ValueError('Synthetic cohort requires a stable secret and a URL-safe access token of at least 32 characters') + + def read(cutoff): + with get_cama_session() as session: + return CamaCohort(session, secret).rows(cutoff) + + def access(req): + supplied = req.headers.get('X-Cama-Cohort-Token', '') + return hmac.compare_digest(supplied.encode('utf-8'), token.encode('utf-8')) + + app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=access) diff --git a/webapi/seguimiento_cama.py b/webapi/seguimiento_cama.py index ffb0a25..1d2c944 100644 --- a/webapi/seguimiento_cama.py +++ b/webapi/seguimiento_cama.py @@ -1,49 +1,11 @@ -"""Seguimiento CaMa de demostración: contrato independiente de la fuente de datos. +"""Patient follow-up for the configured breast cohort.""" -Para conectar cama_linea_de_tiempo, sustituir ``leer_fixture`` por un lector que -entregue los mismos campos escalares y fechas de estudio; mantener el filtrado, -orden y contrato HTTP. Los IDs de este fixture no representan pacientes reales. -""" import calendar -import logging from datetime import date, timedelta from flask import Blueprint, jsonify, request -from webapi.seguimiento import _pedido - -logger = logging.getLogger(__name__) -CATEGORIAS = { - "estatus": ("Estatus de seguimiento", {"PENDIENTE_BIOPSIA": "Pendiente de biopsia", "BIOPSIA_SIN_RESULTADO": "Biopsia sin resultado", "CANCER_CONFIRMADO": "Cáncer confirmado", "BENIGNO": "Benigno, regresa a tamizaje", "INFO_INSUFICIENTE": "Información insuficiente"}), - "birads": ("Categoría BI-RADS", {f"BIRADS_{v}": f"BI-RADS {v}" for v in ("4A", "4B", "4C", "5", "6")}), - "grupo_edad": ("Grupo de edad", {v: v for v in ("40-49", "50-59", "60-69", "70+")}), - "prioridad": ("Prioridad", {"ALTA": "Alta", "MEDIA": "Media", "BAJA": "Baja"}), -} -COLUMNAS = [ - {"clave": "id_seudonimo", "etiqueta": "Identificador seudónimo"}, - {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, - {"clave": "estatus", "etiqueta": "Estatus de seguimiento"}, - {"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 biopsia"}]}, - {"clave": "dias_mastografia_diagnostico", "etiqueta": "Días de mastografía a diagnóstico"}, - {"clave": "prioridad", "etiqueta": "Prioridad"}, -] - - -def leer_fixture(corte, desde): - """Filas inventadas; el futuro lector recibe el corte y la ventana solicitados.""" - datos = [ - ("M-0001", "2026-10-15", "PENDIENTE_BIOPSIA", "BIRADS_5", "50-59", "ALTA", None, None, None), - ("M-0002", "2026-10-15", "BIOPSIA_SIN_RESULTADO", "BIRADS_4A", "40-49", "MEDIA", None, "2026-10-18", None), - ("M-0003", "2026-09-01", "BENIGNO", "BIRADS_4B", "60-69", "BAJA", "Benigno", "2026-09-10", 16), - ("M-0004", "2026-08-15", "CANCER_CONFIRMADO", "BIRADS_4C", "70+", "ALTA", "Carcinoma invasor", "2026-08-22", 20), - ("M-0005", "2026-07-21", "INFO_INSUFICIENTE", "BIRADS_6", "40-49", "MEDIA", None, None, None), - ("M-0006", "2026-05-01", "BENIGNO", "BIRADS_4B", "60-69", "BAJA", "Benigno", "2026-05-09", 15), - ("M-0007", "2026-01-20", "PENDIENTE_BIOPSIA", "BIRADS_5", "50-59", "ALTA", None, None, None), - ("M-0008", "2025-11-01", "BIOPSIA_SIN_RESULTADO", "BIRADS_4A", "40-49", "MEDIA", None, "2025-11-10", None), - ] - claves = ("id_seudonimo", "mastografia_fecha", "estatus", "birads", "grupo_edad", "prioridad", "biopsia", "biopsia_fecha", "dias_mastografia_diagnostico") - return [dict(zip(claves, fila)) for fila in datos] +from webapi.cama_analysis import SelectionError, selection_response def _desde(corte, meses): @@ -55,133 +17,30 @@ def _desde(corte, meses): return anterior + timedelta(days=1) -def _consulta(args): - allowed = {'corte', 'meses', 'page', 'page_size', *CATEGORIAS} - if set(args) - allowed or any(len(args.getlist(key)) != 1 for key in args): - raise ValueError('Parámetros desconocidos o repetidos') - pedido = _pedido(args) - corte = pedido.get("corte", date(2026, 10, 20)) - meses, page, size = (pedido.get("meses", 3), pedido.get("page", 1), pedido.get("page_size", 50)) - if meses not in (1, 3, 6, 12) or page < 1 or not 1 <= size <= 200: - raise ValueError("meses debe ser 1, 3, 6 o 12; page desde 1 y page_size entre 1 y 200") - filtros = {clave: args.get(clave) or None for clave in CATEGORIAS} - for clave, valor in filtros.items(): - if valor is not None and valor not in CATEGORIAS[clave][1]: - raise ValueError(f"{clave} desconocido: {valor!r}") - return corte, meses, page, size, filtros, _desde(corte, meses) - - -def _filas(corte, desde, filtros): - fuente = [] - for original in leer_fixture(corte, desde): - fila = dict(original) - if fila['biopsia_fecha'] and fila['biopsia_fecha'] > corte.isoformat(): - fila.update(biopsia=None, biopsia_fecha=None, dias_mastografia_diagnostico=None, - estatus='INFO_INSUFICIENTE') - fuente.append(fila) - filas = [fila for fila in fuente - if desde.isoformat() <= fila["mastografia_fecha"] <= corte.isoformat() - and all(valor is None or fila[clave] == valor for clave, valor in filtros.items())] - filas.sort(key=lambda fila: fila["id_seudonimo"]) - filas.sort(key=lambda fila: fila["mastografia_fecha"], reverse=True) - return filas - - -def _item(fila): - item = dict(fila) - for clave, (_, opciones) in CATEGORIAS.items(): - item[clave + "_codigo"] = item[clave] - item[clave] = opciones[item[clave]] - return item - - -def _metadatos(corte, meses, desde, filtros): - return dict(simulado=True, corte=corte.isoformat(), - ventana={"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()}, - campo_ventana="mastografia_fecha", filtros=filtros, - filtros_disponibles=[{"clave": clave, "etiqueta": etiqueta, - "opciones": [{"codigo": c, "etiqueta": e} for c, e in opciones.items()]} - for clave, (etiqueta, opciones) in CATEGORIAS.items()], - columnas=COLUMNAS) - - def blueprint_seguimiento_cama(): blueprint = Blueprint("cama_seguimiento", __name__) @blueprint.after_request - def sin_cache_en_contratos_nuevos(response): - if 'cohorte' in request.args or request.endpoint in ("cama_seguimiento.exportacion", "cama_seguimiento.paciente"): - response.headers["Cache-Control"] = "no-store" + 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(): - """Lista sintética de seguimiento CaMa con filtros y columnas declarativos.""" - if 'cohorte' in request.args: - from webapi.cama_analysis import SelectionError, selection_response - try: - return selection_response(request.args, 'list') - except SelectionError as error: - return jsonify(error=error.message), error.status - try: - corte, meses, page, size, filtros, desde = _consulta(request.args) - except ValueError as error: - return jsonify(error=str(error)), 400 - try: - filas = _filas(corte, desde, filtros) - total = len(filas) - return jsonify(**_metadatos(corte, meses, desde, filtros), - paginacion={"page": page, "page_size": size, "total_items": total, - "total_pages": (total + size - 1) // size}, - items=[_item(fila) for fila in filas[(page - 1) * size:page * size]]) - except Exception: - logger.exception("Error al leer seguimiento CaMa") - return jsonify(error="No se pudo consultar el seguimiento CaMa"), 500 + return respond('list') @blueprint.get("/seguimiento/exportacion") def exportacion(): - if 'cohorte' in request.args: - from webapi.cama_analysis import SelectionError, selection_response - try: - return selection_response(request.args, 'export') - except SelectionError as error: - return jsonify(error=error.message), error.status - try: - corte, meses, _, _, filtros, desde = _consulta(request.args) - except ValueError as error: - return jsonify(error=str(error)), 400 - try: - filas = _filas(corte, desde, filtros) - if len(filas) > 5000: - return jsonify(error="La exportación supera el límite de 5000 registros"), 413 - return jsonify(**_metadatos(corte, meses, desde, filtros), total_items=len(filas), - items=[_item(fila) for fila in filas]) - except Exception: - logger.exception("Error al exportar seguimiento CaMa") - return jsonify(error="No se pudo consultar el seguimiento CaMa"), 500 + return respond('export') @blueprint.get("/pacientes/") def paciente(id_seudonimo): - if 'cohorte' in request.args: - from webapi.cama_analysis import SelectionError, selection_response - try: - return selection_response(request.args, 'patient', id_seudonimo) - except SelectionError as error: - return jsonify(error=error.message), error.status - try: - corte, meses, _, _, _, desde = _consulta(request.args) - except ValueError as error: - return jsonify(error=str(error)), 400 - try: - filas = _filas(corte, desde, {clave: None for clave in CATEGORIAS}) - fila = next((fila for fila in filas if fila["id_seudonimo"] == id_seudonimo), None) - if fila is None: - return jsonify(error="Paciente no encontrado en la ventana solicitada"), 404 - return jsonify(simulado=True, corte=corte.isoformat(), - ventana={"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()}, - item=_item(fila)) - except Exception: - logger.exception("Error al consultar paciente CaMa") - return jsonify(error="No se pudo consultar el paciente CaMa"), 500 + return respond('patient', id_seudonimo) return blueprint