"""Aggregate and select the breast cohort through the same configured reader.""" from datetime import date import hashlib import hmac import json from flask import Blueprint, current_app, jsonify, request from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD analysis = Blueprint('cama_analysis', __name__) BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6') AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO') class SelectionError(Exception): def __init__(self, message, status=400): self.message, self.status = message, status def read_cohort(cutoff): reader = current_app.config.get('CAMA_COHORT_READER') if not callable(reader): raise SelectionError('Cohorte no disponible', 503) try: return reader(cutoff) except Exception: current_app.logger.exception('Breast cohort provider failed') raise SelectionError('Cohorte no disponible', 503) from None def cutoff_arg(args): text = args.get('corte') if not text: raise SelectionError('Se requiere corte') try: value = date.fromisoformat(text) if value.isoformat() != text or value.year == 9999: raise ValueError() return value except ValueError: raise SelectionError('Corte inválido') from None def patient_access(): check = current_app.config.get('CAMA_COHORT_ACCESS') if check is not None and (not callable(check) or not check(request)): raise SelectionError('Acceso no autorizado', 403) def revision_of(rows): """Identify the materialized cohort without exposing its patient identifiers.""" encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode() return hashlib.sha256(encoded).hexdigest() def cohort_request(args): allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'} if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args): raise SelectionError('Parámetros desconocidos o repetidos') if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO: raise SelectionError('Cohorte o escenario desconocido') revision = args.get('revision', '') if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision): raise SelectionError('Revisión de cohorte inválida') cutoff = cutoff_arg(args) try: months = int(args.get('meses', '3')) page = int(args.get('page', '1')) size = int(args.get('page_size', '50')) if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200: raise ValueError() except ValueError: raise SelectionError('Ventana o paginación inválida') from None filters = {key: args.get(key) for key in ('birads', 'grupo_edad')} if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES): raise SelectionError('Filtro inválido') return cutoff, months, page, size, filters, revision def selected(args): patient_access() from werkzeug.datastructures import MultiDict args = MultiDict(args) if 'cohorte' not in args: if any(key in args for key in ('revision', 'escenario')): raise SelectionError('Contexto de cohorte incompleto') if 'corte' not in args: args['corte'] = date.today().isoformat() cutoff = cutoff_arg(args) rows = read_cohort(cutoff) args.update({'cohorte': COHORT, 'escenario': SCENARIO, 'revision': revision_of(rows)}) else: rows = None cutoff, months, page, size, filters, revision = cohort_request(args) if rows is None: rows = read_cohort(cutoff) if not hmac.compare_digest(revision, revision_of(rows)): raise SelectionError('La cohorte cambió; actualiza el análisis', 409) selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())] if months: from webapi.seguimiento_cama import _desde try: since = _desde(cutoff, months) except (ValueError, OverflowError): raise SelectionError('Ventana inválida') from None else: since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff) selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff] # Every filtered selection is checked on the server after applying the window. if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())): raise SelectionError('Selección no disponible', 403) return cutoff, months, page, size, filters, since, selected_rows, revision def selection_response(args, mode, patient=None): cutoff, months, page, size, filters, since, rows, revision = selected(args) options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)] columns = [ {'clave': 'pac_id', 'etiqueta': 'Identificador de paciente'}, {'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'}, {'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]}, {'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]}, ] meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(), 'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()}, 'campo_ventana': 'mastografia_fecha', 'filtros': filters, 'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]} for k, label, values in options], 'columnas': columns} if mode == 'patient': found = next((row for row in rows if row['pac_id'] == patient), None) if found is None: raise SelectionError('Paciente no encontrado', 404) return jsonify(**meta, item=found) if mode == 'export': if len(rows) > 5000: raise SelectionError('La exportación supera el límite de 5000 registros', 413) return jsonify(**meta, total_items=len(rows), items=rows) return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows), 'total_pages': (len(rows) + size - 1) // size}, items=rows[(page - 1) * size:page * size]) @analysis.get('/analisis/indicadores') def indicators(): try: if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1: raise SelectionError('Se requiere únicamente corte') cutoff = cutoff_arg(request.args) rows = read_cohort(cutoff) groups = [] for code in BIRADS: count = sum(r['birads'] == code for r in rows) groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD}) return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(), horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente', denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6', indicadores=[], grupos=groups) except SelectionError as e: return jsonify(error=e.message), e.status @analysis.after_request def no_cache(response): response.headers['Cache-Control'] = 'no-store' return response