Compare commits

..

10 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 10f0c59975 Reject invalid optional access callbacks 2026-11-13 18:19:39 -06:00
Angel Capetillo Zavala 1d8cd264b8 Clarify optional cohort access boundary 2026-11-13 17:56:50 -06:00
Angel Capetillo Zavala 46eb3dfc31 Use shared access for synthetic breast follow-up 2026-11-13 17:54:56 -06:00
Angel Capetillo Zavala 9c0e03f947 Remove obsolete cohort example switch 2026-11-13 17:49:44 -06:00
Angel Capetillo Zavala 6d32115eca Check startup with retained cohort settings 2026-11-13 17:47:37 -06:00
Angel Capetillo Zavala 06dd74cdb6 Verify cervical patient identity contract 2026-11-13 17:43:50 -06:00
Angel Capetillo Zavala eeb55c4255 Use source patient identity for breast follow-up 2026-11-13 17:38:19 -06:00
edgar 2ca86232c9 Follow-up list without a salt: the kit identifies each patient by pac_id 2026-11-13 17:31:07 -06:00
Angel Capetillo Zavala 8b47f1522d Connect breast follow-up to the configured cohort 2026-11-13 15:16:14 -06:00
Angel Capetillo Zavala 7bc214b50c Validate patient identity in breast cohort links 2026-11-13 14:52:55 -06:00
15 changed files with 256 additions and 381 deletions
+6 -23
View File
@@ -99,26 +99,9 @@ se omiten.
### Seguimiento CaMa sintético
`GET /cama/seguimiento` entrega la tabla declarativa de demostración, sin consultar una base. Por defecto usa corte fijo `2026-10-20`, ventana de 3 meses, página 1 y tamaño 50. `corte` acepta fecha ISO; `meses` admite 1, 3, 6 o 12; `page` comienza en 1 y `page_size` va de 1 a 200. La ventana incluye desde el día siguiente a restar meses calendario (ajustando fin de mes) hasta el corte inclusive. Se seleccionan filas por fecha de mastografía. No se acota un corte solicitado a la última fecha del fixture.
Los filtros opcionales son `estatus` (`PENDIENTE_BIOPSIA`, `BIOPSIA_SIN_RESULTADO`, `CANCER_CONFIRMADO`, `BENIGNO`, `INFO_INSUFICIENTE`), `birads` (`BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`, `BIRADS_5`, `BIRADS_6`), `grupo_edad` (`40-49`, `50-59`, `60-69`, `70+`) y `prioridad` (`ALTA`, `MEDIA`, `BAJA`). `filtros_disponibles` anuncia códigos y etiquetas; las celdas incluyen etiquetas y campos `*_codigo`. Se ordena por fecha descendente e ID ascendente, antes de paginar. Una página fuera de rango devuelve 200 con `items: []`; una lista vacía tiene cero páginas. Parámetros inválidos producen 400 y un fallo de lectura 500 con JSON `error`.
#### Contratos candidatos F5B
`GET /cama/seguimiento/exportacion?corte=2026-10-20&meses=1&birads=BIRADS_5` devuelve todas las coincidencias, con los mismos filtros y orden de la lista. El cuerpo incluye `simulado`, `corte`, `ventana`, `campo_ventana`, `filtros`, `filtros_disponibles`, `columnas`, `total_items` e `items`. Ejemplo abreviado (los arreglos de metadatos se omiten aquí, pero siempre se envían):
```json
{"simulado":true,"corte":"2026-10-20","ventana":{"meses":1,"desde":"2026-09-21","hasta":"2026-10-20"},"campo_ventana":"mastografia_fecha","filtros":{"estatus":null,"birads":"BIRADS_5","grupo_edad":null,"prioridad":null},"total_items":1,"items":[{"id_seudonimo":"M-0001","mastografia_fecha":"2026-10-15","estatus":"Pendiente de biopsia","estatus_codigo":"PENDIENTE_BIOPSIA","birads":"BI-RADS 5","birads_codigo":"BIRADS_5","grupo_edad":"50-59","grupo_edad_codigo":"50-59","prioridad":"Alta","prioridad_codigo":"ALTA","biopsia":null,"biopsia_fecha":null,"dias_mastografia_diagnostico":null}]}
```
Más de 5,000 coincidencias produce 413 con `error`, sin truncar. No requiere parámetros de paginación; si se envían, se validan como en la lista pero no limitan el resultado. JSON vacío es 200 con `total_items: 0` e `items: []`. Las respuestas, incluidos errores, llevan `Cache-Control: no-store`.
`GET /cama/pacientes/M-0001?corte=2026-10-20&meses=1` devuelve `{"simulado":true,"corte":"2026-10-20","ventana":{"meses":1,"desde":"2026-09-21","hasta":"2026-10-20"},"item":{...}}`, donde `item` es exactamente la fila anterior. Deben enviarse el corte y la ventana de la lista; un ID inexistente o fuera de esa ventana devuelve 404. Solo existen los campos de la fila: historial, pronóstico y demás apartados no disponibles se omiten; los campos existentes sin datos son `null`. También utiliza `no-store`. Los ID `M-...` pertenecen exclusivamente al fixture y no son `pac_id`.
#### Ruta futura a persistencia
La conexión CaMa se configura mediante `CAMA_DATABASE_URL` en `Persistance/persistance/settings.py` y `db.py`; el valor por defecto es `sqlite:///cama.db`, mientras `.env.example` propone otra ruta. Esto no identifica el motor instalado en DEV. En staging, `Paciente`, `Mastografia`, `BiopsiaMama` y `OrdenesEstudio` están en `Core/core/cama/models`; la plata expone `Persona`, `Procedimiento` y `Observacion` mediante `indicadores_kit/cama/tablas.py`. `indicadores_kit/cama/plata.py` transforma tomas, reportes y observaciones; no asumir que `cama_linea_de_tiempo` está disponible en una instalación sin comprobarlo.
Antes de consultar persistencia hay que validar identidad entre `pac_id` y `pac_id_hospital`, claves opcionales, la relación `biopsiamama.mast_id`, órdenes, múltiples estudios/resultados, fechas de toma y reporte, y selección de eventos conocidos al corte. La biopsia sin fecha de reporte no aporta aún resultado en el patrón de plata. El servicio `seguimiento_de` de CaCu ilustra sesión externa, reglas parametrizadas, agrupación por paciente, ventana, orden y seudonimización; sus reglas clínicas no deben copiarse como reglas CaMa. Un identificador opaco estable con clave secreta y separación por dominio, por ejemplo HMAC, requiere acordar gestión y rotación de clave, colisiones y resolución autorizada para detalle; no exponer `str(pac_id)` directamente.
Angular hoy exige `simulado === true` en `SeguimientoTablaService`. Una fuente real requiere acordar el contrato y tratamiento de `simulado: false`, adaptar tipos, validación, etiquetas, pruebas y acceso antes de consumirla. No se ha cambiado el proveedor ni se ha verificado el despliegue remoto.
El lector usa la base configurada por `CAMA_DATABASE_URL` y publica el
`pac_id` de la plataforma como cadena decimal, con ámbito limitado a esa base
y dominio. Las rutas por paciente usan el mismo acceso de la aplicación que
Seguimiento CaCu. Los parámetros de corte, ventana y selección, la revisión, la
supresión y los ejemplos de listado, ficha y exportación se describen en
[el contrato de cohorte](docs/cama-cohort-api.md).
+22 -13
View File
@@ -1,12 +1,10 @@
# 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 for a synthetic source. The application reads the configured
CaMa database through the shared persistence settings. Patient routes have
the same application access boundary as CaCu follow-up; an optional access
callback can apply an additional boundary. An unavailable reader returns 503.
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`,
@@ -19,7 +17,7 @@ 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.
patient identifiers. 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
@@ -30,13 +28,21 @@ GET /cama/seguimiento?cohorte=cama_birads_v1&escenario=diagnostico&revision=<rev
```
For the same selected population use the same query on
`/cama/seguimiento/exportacion` or `/cama/pacientes/<id_seudonimo>`; list
`/cama/seguimiento/exportacion` or `/cama/pacientes/<pac_id>`; 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.
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
@@ -44,8 +50,8 @@ 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`.
An optional access callback 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
@@ -59,8 +65,11 @@ 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.
and does not require cohort-specific environment variables.
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, bound to loopback. It is suitable only
for local synthetic integration and does not provide production authentication.
+2 -11
View File
@@ -1,6 +1,5 @@
"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file."""
import hmac
import os
from pathlib import Path
import sqlite3
@@ -24,10 +23,6 @@ if os.name == 'nt':
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')
@@ -47,14 +42,10 @@ app = create_app()
def read(cutoff):
with Session(engine) as session:
return CamaCohort(session, secret).rows(cutoff)
return CamaCohort(session).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)
app.config['CAMA_COHORT_READER'] = read
if __name__ == '__main__':
app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False)
+34
View File
@@ -0,0 +1,34 @@
"""Serve an isolated synthetic database through a loopback-only test proxy."""
import argparse
import os
from pathlib import Path
import sys
import types
parser = argparse.ArgumentParser()
parser.add_argument('--database', required=True, help='Existing disposable synthetic SQLite database')
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')
os.environ.update(CAMA_DATABASE_URL='sqlite:///' + database.as_posix(),
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()
print(f'Isolated synthetic test proxy: http://127.0.0.1:{args.port}', flush=True)
make_server('127.0.0.1', args.port, app, threaded=True).serve_forever()
+28 -15
View File
@@ -57,7 +57,7 @@ def client(cohort_db):
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)
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()
@@ -84,7 +84,7 @@ def test_aggregate_list_detail_and_export_have_one_selection(client):
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()
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
@@ -97,7 +97,7 @@ def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
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
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
@@ -115,42 +115,38 @@ def test_cutoff_excludes_later_clinical_and_load_dates(client):
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)}
ids = {i: str(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']}
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['id_seudonimo']: item for item in later['items']}
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_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):
"""Regular windows remain available and the reader is opt-in."""
"""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_SYNTHETIC'] = False
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
@@ -169,3 +165,20 @@ def test_newer_noneligible_result_changes_revision_and_excludes_patient(client,
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
+25
View File
@@ -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'}
+11
View File
@@ -72,6 +72,17 @@ def test_a_scored_member_has_the_contracts_shape(client, seeded):
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
def test_follow_up_identity_resolves_scored_patient(client, seeded):
"""The patient selected from follow-up resolves to that patient's seeded risk."""
listing = client.get('/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200').get_json()
row = next(item for item in listing['items'] if item['pac_id'] == str(seeded[0]))
assert row['id_seudonimo'] == row['pac_id']
response = client.get(f"/cacu/pacientes/{row['pac_id']}/riesgo")
assert response.status_code == 200
assert response.get_json()['cohorte']['pap_0'] == 'ASC-US'
assert response.get_json()['riesgo']['horizontes'][0]['probabilidad'] == 0.1
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
null. Fails if either case errors or invents a risk."""
+3 -2
View File
@@ -9,7 +9,7 @@ import pytest
from conftest import cliente_de
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
"dias_toma_diagnostico", "prioridad"} # fmt: skip
@@ -31,7 +31,8 @@ def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
assert all(i["prioridad"] is None for i in cuerpo["items"])
assert "pac_id" not in response.get_data(as_text=True)
assert all(i["pac_id"] == i["id_seudonimo"] and i["pac_id"].isdigit() for i in cuerpo["items"])
assert "pac_id_hospital" not in response.get_data(as_text=True)
def test_el_pedido_se_respeta(client):
+53 -133
View File
@@ -1,152 +1,72 @@
"""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(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(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]['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_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
client.application.config['CAMA_COHORT_ACCESS'] = 'invalid'
assert client.get('/cama/seguimiento', headers=headers).status_code == 403
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
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
@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_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')
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
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'}
+3
View File
@@ -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
+28 -7
View File
@@ -21,9 +21,13 @@ class SelectionError(Exception):
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):
if not callable(reader):
raise SelectionError('Cohorte no disponible', 503)
return reader(cutoff)
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):
@@ -41,7 +45,7 @@ def cutoff_arg(args):
def patient_access():
check = current_app.config.get('CAMA_COHORT_ACCESS')
if not callable(check) or not check(request):
if check is not None and (not callable(check) or not check(request)):
raise SelectionError('Acceso no autorizado', 403)
@@ -77,14 +81,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]
@@ -98,7 +119,7 @@ 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': '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'}]},
@@ -109,7 +130,7 @@ def selection_response(args, mode, patient=None):
'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)
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)
+13 -19
View File
@@ -6,8 +6,6 @@ restore a previous value after an update.
"""
from datetime import date, datetime, time, timedelta, timezone
import hashlib
import hmac
from sqlalchemy import select
@@ -49,14 +47,8 @@ def _age_group(birth, cutoff):
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")
def __init__(self, session):
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
@@ -69,9 +61,9 @@ class CamaCohort:
p = procedures.get(identifier)
return bool(p and _known(loads.get(p.carga_id), cutoff))
def observation_known(identifier, result):
def observation_known(identifier, result, patient):
o = observations.get((identifier, result))
return bool(o and _known(loads.get(o.carga_id), cutoff))
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
@@ -82,7 +74,8 @@ class CamaCohort:
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')):
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'])
@@ -101,12 +94,13 @@ class CamaCohort:
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'])
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 (reported and ordered and ordered <= reported <= cutoff and row['toma_id']
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 procedure_known(order.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'])
@@ -124,9 +118,9 @@ class CamaCohort:
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
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
rows.append({
'id_seudonimo': self._id(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
'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,
@@ -137,6 +131,6 @@ class CamaCohort:
'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,
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(), row['id_seudonimo']))
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))
+12
View File
@@ -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
+1 -2
View File
@@ -19,7 +19,6 @@ from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seg
from sqlmodel import Session
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
def en_dev() -> bool:
@@ -40,7 +39,7 @@ def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
return jsonify({"error": str(error)}), 400
sesion = get_session()
try:
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido)
cuerpo = seguimiento_de(sesion, **pedido)
except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400
except PaginaFuera as error:
+15 -156
View File
@@ -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/<id_seudonimo>")
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
@blueprint.get("/pacientes/<pac_id>")
def paciente(pac_id):
return respond('patient', pac_id)
return blueprint