Use source patient identity for breast follow-up

This commit is contained in:
Angel Capetillo Zavala
2026-11-13 17:38:19 -06:00
parent 2ca86232c9
commit eeb55c4255
11 changed files with 73 additions and 110 deletions
+8 -4
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):
@@ -115,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'}]},
@@ -126,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)
+3 -11
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
@@ -128,7 +120,7 @@ class CamaCohort:
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
rows.append({
'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,
@@ -141,4 +133,4 @@ class CamaCohort:
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None,
})
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), row['id_seudonimo']))
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))
+5 -9
View File
@@ -1,4 +1,4 @@
"""Configure the opt-in synthetic breast cohort for the application."""
"""Configure the breast cohort using the shared persistence settings."""
import hmac
import os
@@ -9,19 +9,15 @@ 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)
return CamaCohort(session).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'))
return bool(re.fullmatch(r'[A-Za-z0-9_-]{32,}', token)) and 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)
app.config.update(CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=access)
+3 -3
View File
@@ -39,8 +39,8 @@ def blueprint_seguimiento_cama():
def exportacion():
return respond('export')
@blueprint.get("/pacientes/<id_seudonimo>")
def paciente(id_seudonimo):
return respond('patient', id_seudonimo)
@blueprint.get("/pacientes/<pac_id>")
def paciente(pac_id):
return respond('patient', pac_id)
return blueprint