From 1d5f1e0cc4c92d0184160191952afea07449bcc7 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 13:27:18 -0600 Subject: [PATCH] Add synthetic breast cohort reconciliation --- docs/cama-cohort-api.md | 66 +++++++++++++ examples/serve_cama_cohort.py | 60 ++++++++++++ tests/test_cama_cohort.py | 171 ++++++++++++++++++++++++++++++++++ webapi/__init__.py | 2 + webapi/cama_analysis.py | 147 +++++++++++++++++++++++++++++ webapi/cama_cohort.py | 142 ++++++++++++++++++++++++++++ webapi/seguimiento_cama.py | 32 ++++++- 7 files changed, 618 insertions(+), 2 deletions(-) create mode 100644 docs/cama-cohort-api.md create mode 100644 examples/serve_cama_cohort.py create mode 100644 tests/test_cama_cohort.py create mode 100644 webapi/cama_analysis.py create mode 100644 webapi/cama_cohort.py diff --git a/docs/cama-cohort-api.md b/docs/cama-cohort-api.md new file mode 100644 index 0000000..47d2ea3 --- /dev/null +++ b/docs/cama-cohort-api.md @@ -0,0 +1,66 @@ +# 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. + +`GET /cama/analisis/indicadores?corte=2026-10-20` returns a descriptive count +by BI-RADS. It includes `cohorte`, `revision`, `escenario`, `corte`, +`umbral_supresion`, `unidad`, `denominador` and `grupos`. A sample group is +`{"codigo":"BIRADS_5","n":6,"suprimido":false}`. A suppressed group's `n` +is null. The prototype's required `indicadores` array is empty: the new +`grupos` is a count distribution, not an incidence or survival estimate. +No survival, recurrence, subgroup grid or other analysis endpoints are supplied. + +One patient contributes once: choose the latest mammogram with a BI-RADS report +available by cutoff; then include it if BI-RADS is 4, 4A, 4B, 4C, 5 or 6. +`revision` is a digest of the materialized cohort, including its data and stable +pseudonyms. It is an integrity marker, not an authorization credential. + +For each patient request send `cohorte=cama_birads_v1`, `escenario=diagnostico`, +the exact `revision` and `corte` from the aggregate, `meses`, and any selected +`birads` or `grupo_edad`. For example: + +``` +GET /cama/seguimiento?cohorte=cama_birads_v1&escenario=diagnostico&revision=&corte=2026-10-20&meses=0&birads=BIRADS_5 +``` + +For the same selected population use the same query on +`/cama/seguimiento/exportacion` or `/cama/pacientes/`; list +accepts `page` and `page_size` (maximum 200). Export is limited to 5,000. +`meses=0` means the whole eligible cohort through cutoff. Its inclusive +`desde` is the earliest eligible mammography date before filtering; when the +cohort is empty it is the cutoff. `hasta` is the inclusive cutoff. Windows 1, +3, 6 and 12 retain their calendar-month semantics. + +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 +invalid parameters return 400. A filtered group with fewer than five patients, +or a nonempty whole cohort smaller than five, returns 403; empty unfiltered +cohorts return an empty page. A revision mismatch returns 409; absent detail +returns 404, an unavailable reader returns 503 and oversized exports return 413. +Authorization is checked independently of suppression. Responses containing +patient data carry `Cache-Control: no-store`. + +The source uses the kit's silver mammography and biopsy queries. A biopsy must +be linked through its order to the selected mammogram and patient. Clinical +dates and load start timestamps are distinct fields. Procedure and observation +load timestamps must be no later than the UTC cutoff day. Silver stores only +the current row: a historical value overwritten later cannot be reconstructed, +and the person table does not version date of birth. Therefore this contract +does not certify a historical snapshot. Revision detects changes between +requests but does not persist the previous cohort. The current implementation +materializes the full cohort in memory and has not been sized for production. + +The local example `examples/serve_cama_cohort.py` accepts an existing synthetic +SQLite file in `CAMA_SYNTHETIC_SQLITE`, opens it read-only, binds to loopback, +and requires `CAMA_COHORT_SECRET` and `CAMA_COHORT_ACCESS_TOKEN` of at least +32 characters. Send the latter in `X-Cama-Cohort-Token` for patient requests. +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. diff --git a/examples/serve_cama_cohort.py b/examples/serve_cama_cohort.py new file mode 100644 index 0000000..187733a --- /dev/null +++ b/examples/serve_cama_cohort.py @@ -0,0 +1,60 @@ +"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file.""" + +import hmac +import os +from pathlib import Path +import sqlite3 +from urllib.parse import quote + +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +if os.name == 'nt': + import sys + import types + + fcntl = types.ModuleType('fcntl') + fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8 + + def unavailable(*args): + raise RuntimeError('File locking is unavailable in this local Windows example') + + fcntl.flock = unavailable + sys.modules['fcntl'] = fcntl + + +path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True) +secret = os.environ['CAMA_COHORT_SECRET'].encode() +token = os.environ['CAMA_COHORT_ACCESS_TOKEN'] +if len(secret) < 32 or len(token) < 32: + raise ValueError('Both the cohort secret and access token must be at least 32 characters') +if not path.is_file(): + raise ValueError('The synthetic SQLite database must already exist') + +# The cohort reader can only open the named file in read-only mode. +uri = 'file:' + quote(path.as_posix(), safe='/:') + '?mode=ro' +engine = create_engine('sqlite://', creator=lambda: sqlite3.connect(uri, uri=True)) + +# The other application blueprints must not inherit a live database URL. +for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'): + os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:' + +from webapi import create_app +from webapi.cama_cohort import CamaCohort + +app = create_app() + + +def read(cutoff): + with Session(engine) as session: + return CamaCohort(session, secret).rows(cutoff) + + +def authorized(request): + return hmac.compare_digest(request.headers.get('X-Cama-Cohort-Token', ''), token) + + +app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=authorized) + +if __name__ == '__main__': + app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False) diff --git a/tests/test_cama_cohort.py b/tests/test_cama_cohort.py new file mode 100644 index 0000000..b27e489 --- /dev/null +++ b/tests/test_cama_cohort.py @@ -0,0 +1,171 @@ +"""Exercise cohort selection with isolated synthetic silver rows and Flask clients.""" + +from datetime import date, datetime, timezone + +import pytest +from flask import Flask +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +from indicadores_kit.cama.tablas 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, b'x' * 32).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['id_seudonimo'] + 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'] = None + 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.""" + with Session(cohort_db) as session: + ids = {i: CamaCohort(session, b'x' * 32)._id(i) for i in range(1, 5)} + data = client.get('/cama/seguimiento' + query(client)).get_json() + rows = {item['id_seudonimo']: 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['id_seudonimo']: 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_preserves_legacy(client): + """The application registers the aggregate while retaining legacy follow-up.""" + 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?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): + """Regular windows remain available and the reader is opt-in.""" + 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_SYNTHETIC'] = False + 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 diff --git a/webapi/__init__.py b/webapi/__init__.py index 7e4c928..f14c714 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -14,6 +14,7 @@ from webapi.blueprints.reportes import reportes_bp from webapi.blueprints.tea import tea_bp from webapi.seguimiento import blueprint_de_seguimiento from webapi.seguimiento_cama import blueprint_seguimiento_cama +from webapi.cama_analysis import analysis as cama_analysis class IsoJSONProvider(DefaultJSONProvider): @@ -74,6 +75,7 @@ def create_app() -> Flask: app.register_blueprint(cacu_bp, url_prefix="/cacu") app.register_blueprint(cama_bp, url_prefix="/cama") app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama") + app.register_blueprint(cama_analysis, url_prefix="/cama") app.register_blueprint(tea_bp, url_prefix="/tea") app.register_blueprint(imports_bp, url_prefix="/imports") app.register_blueprint(data_bp, url_prefix="/data") diff --git a/webapi/cama_analysis.py b/webapi/cama_analysis.py new file mode 100644 index 0000000..5b48601 --- /dev/null +++ b/webapi/cama_analysis.py @@ -0,0 +1,147 @@ +"""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 current_app.config.get('CAMA_COHORT_SYNTHETIC') is not True or not callable(reader): + raise SelectionError('Cohorte no disponible', 503) + return reader(cutoff) + + +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 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() + cutoff, months, page, size, filters, revision = cohort_request(args) + 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) + 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': 'id_seudonimo', 'etiqueta': 'Identificador seudónimo'}, + {'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['id_seudonimo'] == 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..7228549 --- /dev/null +++ b/webapi/cama_cohort.py @@ -0,0 +1,142 @@ +"""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 +import hashlib +import hmac + +from sqlalchemy import select + +from indicadores_kit.cama.consultas.plata import biopsias, mastografias +from indicadores_kit.cama.familias.histopatologia_birads.consulta import BIRADS +from indicadores_kit.cama.tablas import TABLAS + + +COHORT = "cama_birads_v1" +SCENARIO = "diagnostico" +THRESHOLD = 5 + + +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, secret: bytes): + if not secret or len(secret) < 32: + raise ValueError("A stable secret of at least 32 bytes is required") + self.session = session + self.secret = secret + + def _id(self, patient): + return hmac.new(self.secret, f"cama:{patient}".encode(), hashlib.sha256).hexdigest() + + 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): + o = observations.get((identifier, result)) + return bool(o 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(select(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 observation_known(row['reporte_id'], 'mastografia.birads')): + 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(select(biopsias(t))).mappings(): + reported, ordered = _date(row['fecha_reporte']), _date(row['fecha_solicitud']) + procedure = procedures.get(row['procedimiento_id']) + order = procedures.get(procedure.padre_id) if procedure else None + if not (reported and ordered and ordered <= reported <= cutoff and row['toma_id'] + and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id']) + and order 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') else None + rows.append({ + 'id_seudonimo': self._id(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') else None, + }) + return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), row['id_seudonimo'])) diff --git a/webapi/seguimiento_cama.py b/webapi/seguimiento_cama.py index 108826e..ffb0a25 100644 --- a/webapi/seguimiento_cama.py +++ b/webapi/seguimiento_cama.py @@ -56,6 +56,9 @@ def _desde(corte, meses): 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)) @@ -69,7 +72,14 @@ def _consulta(args): def _filas(corte, desde, filtros): - filas = [fila for fila in leer_fixture(corte, desde) + 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"]) @@ -100,13 +110,19 @@ def blueprint_seguimiento_cama(): @blueprint.after_request def sin_cache_en_contratos_nuevos(response): - if request.endpoint in ("cama_seguimiento.exportacion", "cama_seguimiento.paciente"): + if 'cohorte' in request.args or request.endpoint in ("cama_seguimiento.exportacion", "cama_seguimiento.paciente"): response.headers["Cache-Control"] = "no-store" return response @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: @@ -124,6 +140,12 @@ def blueprint_seguimiento_cama(): @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: @@ -140,6 +162,12 @@ def blueprint_seguimiento_cama(): @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: