Files
edgar e2732f5e8a Risk batches: a decision that collides with another of the same batch is a 409
Two decisions of one batch at the same moment (a double click reaching both workers) wrote the same evaluation
version and the second surfaced as a server error.
2026-11-22 09:34:49 -06:00

52 lines
2.5 KiB
Python

"""Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet,
confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`,
`/cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`) or void it (`entered-in-error`).
`GET/POST /<domain>/riesgos/lotes...`. The route is always registered; who may act on it is an access rule still
to be defined.
"""
from flask import Blueprint, jsonify, request
from sqlalchemy.exc import IntegrityError
from persistance.edges.gold import ERROR, FINAL
def risk_batches_blueprint(repositories, name: str = "risk_batches") -> Blueprint:
"""The blueprint, to register with `url_prefix="/<domain>"`. `repositories` is `persistance.<domain>`; `name` is
unique per domain registered."""
blueprint = Blueprint(name, __name__)
@blueprint.get("/riesgos/lotes")
def list_pending_batches():
"""Pending batches, newest first."""
return jsonify([_batch(b) for b in repositories.cohort_repository.pending_batches()])
@blueprint.post("/riesgos/lotes/<int:lote_id>/confirmar")
def confirm_batch(lote_id: int):
"""Moves every current evaluation of the batch to `final` (ADR-MD-008): a clinical decision, with its
reason. 404 if the batch doesn't exist or has no evaluation left to decide."""
return _decide(lote_id, FINAL)
@blueprint.post("/riesgos/lotes/<int:lote_id>/anular")
def void_batch(lote_id: int):
"""Moves every current evaluation of the batch to `entered-in-error`."""
return _decide(lote_id, ERROR)
def _decide(lote_id: int, estado: str):
reason = (request.get_json(silent=True) or {}).get("reason", "").strip()
if not reason:
return jsonify({"error": "se requiere un motivo"}), 400
try:
changed = repositories.cohort_repository.change_state(lote_id, estado, reason)
except IntegrityError: # another request decided the same batch at the same moment
return jsonify({"error": f"el lote {lote_id} ya se está decidiendo en otra solicitud"}), 409
if not changed:
return jsonify({"error": f"el lote {lote_id} no existe o ya no tiene evaluaciones vigentes"}), 404
return jsonify({"lote_id": lote_id, "evaluaciones_cambiadas": changed})
return blueprint
def _batch(batch) -> dict:
return {"lote_id": batch.lote_id, "modelo_nombre": batch.modelo_nombre, "modelo_version": batch.modelo_version,
"evaluado_en": batch.evaluado_en.isoformat(), "n_evaluaciones": batch.n_evaluaciones}