preliminary release
This commit is contained in:
@@ -10,7 +10,9 @@ from webapi.blueprints.cama import cama_bp
|
||||
from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.reportes import reportes_bp
|
||||
from webapi.blueprints.tea import tea_bp
|
||||
from webapi.seguimiento import blueprint_de_seguimiento, en_dev
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
@@ -74,5 +76,11 @@ def create_app() -> Flask:
|
||||
app.register_blueprint(imports_bp, url_prefix="/imports")
|
||||
app.register_blueprint(data_bp, url_prefix="/data")
|
||||
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||
app.register_blueprint(reportes_bp, url_prefix="/reportes")
|
||||
# Patient-level follow-up list: only in DEV, with simulated data.
|
||||
if en_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -6,6 +6,7 @@ from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
from webapi.imports import audit as import_audit
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
@@ -18,6 +19,7 @@ from webapi.imports.services.import_service import (
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
@@ -83,6 +85,15 @@ def _form_json(key: str, default=None):
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
|
||||
|
||||
def _outcome(exc: Exception) -> str:
|
||||
"""How an attempt that raised is logged."""
|
||||
if isinstance(exc, ImportRequestError) and str(exc).startswith("the database refused"):
|
||||
return "rechazada_por_la_base"
|
||||
if isinstance(exc, (BadRequest, ConnectorError, ExtractionError, ImportRequestError)):
|
||||
return "solicitud_invalida"
|
||||
return "fallida"
|
||||
|
||||
|
||||
# -- catalog -------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -267,7 +278,17 @@ def document_page_image():
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
result = validate_source(_require(_json_body(), "source"))
|
||||
source = _require(_json_body(), "source")
|
||||
audit = import_audit.ImportAudit("validacion")
|
||||
try:
|
||||
result = validate_source(source, audit=audit)
|
||||
except Exception as exc:
|
||||
audit.fail(exc, _outcome(exc))
|
||||
raise
|
||||
else:
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
return jsonify(
|
||||
{
|
||||
"total_rows": result.total_rows,
|
||||
@@ -284,14 +305,26 @@ def commit():
|
||||
With `merge_duplicates`, rows of different sources sharing a natural key
|
||||
are combined into one record before writing."""
|
||||
body = _json_body()
|
||||
results = commit_sources(
|
||||
_require(body, "sources"),
|
||||
on_conflict=body.get("on_conflict", "reject"),
|
||||
merge=bool(body.get("merge_duplicates", False)),
|
||||
)
|
||||
on_conflict = body.get("on_conflict", "reject")
|
||||
merge = bool(body.get("merge_duplicates", False))
|
||||
audit = import_audit.ImportAudit("carga", {"on_conflict": on_conflict, "merge_duplicates": merge})
|
||||
try:
|
||||
results = commit_sources(_require(body, "sources"), on_conflict=on_conflict, merge=merge, audit=audit)
|
||||
except Exception as exc:
|
||||
audit.fail(exc, _outcome(exc))
|
||||
raise
|
||||
else:
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
written = sum(r.created + r.updated for r in results)
|
||||
if written and audit.domain:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": bool(written and audit.domain),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Aggregate reports: the log of import attempts and the state of the live
|
||||
indicator recomputation. Nothing here returns row-level data."""
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from webapi.imports import audit as import_audit
|
||||
from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo
|
||||
|
||||
reportes_bp = Blueprint("reportes", __name__)
|
||||
|
||||
|
||||
@reportes_bp.get("/importaciones")
|
||||
def importaciones():
|
||||
"""Totals per target over every logged attempt, plus the latest attempts
|
||||
(`?limite=50`, newest first; `?dominio=cacu` to filter)."""
|
||||
records = import_audit.default_sink().read()
|
||||
domain = request.args.get("dominio")
|
||||
if domain:
|
||||
records = [r for r in records if r.get("dominio") == domain]
|
||||
try:
|
||||
limit = max(0, int(request.args.get("limite", 50)))
|
||||
except ValueError:
|
||||
return jsonify({"error": "limite debe ser un número"}), 400
|
||||
return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]})
|
||||
|
||||
|
||||
@reportes_bp.get("/importaciones/descarga")
|
||||
def importaciones_descarga():
|
||||
"""The raw log, one JSON object per line."""
|
||||
sink = import_audit.default_sink()
|
||||
body = sink.path.read_bytes() if sink.path.exists() else b""
|
||||
return Response(
|
||||
body,
|
||||
mimetype="application/x-ndjson",
|
||||
headers={"Content-Disposition": "attachment; filename=importaciones.jsonl"},
|
||||
)
|
||||
|
||||
|
||||
@reportes_bp.get("/indicadores")
|
||||
def indicadores_estado():
|
||||
"""Per domain: state of the last recomputation and whether another is pending."""
|
||||
return jsonify(ColaDeRecalculo().estado())
|
||||
|
||||
|
||||
@reportes_bp.post("/indicadores/<dominio>/recalcular")
|
||||
def indicadores_recalcular(dominio: str):
|
||||
if dominio not in DOMINIOS:
|
||||
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
||||
ColaDeRecalculo().solicitar(dominio)
|
||||
return jsonify({"pendiente": True}), 202
|
||||
@@ -0,0 +1,341 @@
|
||||
"""Aggregate log of every import attempt (validations and commits).
|
||||
|
||||
Each attempt becomes one JSON line in `importaciones.jsonl` under
|
||||
`WEBAPI_REPORT_DIR`. A record only carries counts, field names, source
|
||||
column names and value *shapes* ("9999-99-99" for a date in an unexpected
|
||||
format): never a row, a file name, a connection string or an identifier.
|
||||
A rejected catalog value is written verbatim only when at least
|
||||
`WEBAPI_REPORT_MIN_COUNT` rows share it, so a rare (identifying) value never
|
||||
appears.
|
||||
|
||||
`ImportAudit` collects the facts while the import runs; an `AuditSink`
|
||||
decides where the finished record goes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Iterable
|
||||
|
||||
from webapi.imports.schemas.classify import ErrorCategory
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from webapi.imports.schemas.service import BatchValidationResult
|
||||
from webapi.imports.services.import_service import ImportSource
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
_SHAPE_MAX = 40
|
||||
_MESSAGE_MAX = 300
|
||||
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
|
||||
# A "column name" that is really a value: a file without a header row makes
|
||||
# its first record the header. Dates, numbers, codes such as "N-0001", long
|
||||
# text or prose are logged by shape only.
|
||||
_VALUE_LIKE = re.compile(r"^[\d\s./:-]+$|\d{4,}|^[A-Za-z]{0,3}[-_ ]?\d+$|@")
|
||||
|
||||
|
||||
def report_dir() -> Path:
|
||||
return Path(os.environ.get("WEBAPI_REPORT_DIR", "reportes"))
|
||||
|
||||
|
||||
def min_count() -> int:
|
||||
return int(os.environ.get("WEBAPI_REPORT_MIN_COUNT", "5"))
|
||||
|
||||
|
||||
def value_shape(value: Any) -> str:
|
||||
"""Letters become `A`, digits `9`; punctuation and spaces stay. Tells the
|
||||
format of a value without its content."""
|
||||
text = str(value)
|
||||
shape = "".join("9" if c.isdigit() else "A" if c.isalpha() else c for c in text[:_SHAPE_MAX])
|
||||
return shape + ("…" if len(text) > _SHAPE_MAX else "")
|
||||
|
||||
|
||||
def column_label(name: Any) -> str:
|
||||
"""A source column name as it can be logged: verbatim when it looks like a
|
||||
header, its shape when it looks like data."""
|
||||
text = str(name).strip()
|
||||
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
|
||||
return value_shape(text)
|
||||
return text
|
||||
|
||||
|
||||
def sanitize_message(message: str) -> str:
|
||||
"""Error messages from drivers and parsers may quote values (MySQL's
|
||||
"Duplicate entry 'N-0001'"); quoted text is dropped."""
|
||||
return _QUOTED.sub("'…'", str(message))[:_MESSAGE_MAX]
|
||||
|
||||
|
||||
def _blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
|
||||
def _source_origin(source: ImportSource) -> dict[str, Any]:
|
||||
"""What kind of source it was, without names, hosts or credentials."""
|
||||
payload = source.payload
|
||||
origin: dict[str, Any] = {"tipo": source.source_type}
|
||||
files = payload.get("files")
|
||||
if isinstance(files, list):
|
||||
names = [f.get("name") or "" for f in files if isinstance(f, dict)]
|
||||
else:
|
||||
names = [(payload.get("options") or {}).get("file_name") or payload.get("file_name") or ""]
|
||||
extensions = sorted({Path(n).suffix.lower() for n in names if Path(n).suffix})
|
||||
if extensions:
|
||||
origin["extensiones"] = extensions
|
||||
if isinstance(files, list):
|
||||
origin["archivos"] = len(files)
|
||||
if source.source_type == "sql":
|
||||
server = payload.get("server") if isinstance(payload.get("server"), dict) else {}
|
||||
scheme = str(payload.get("connection_string") or "").split(":", 1)[0].split("+", 1)[0]
|
||||
origin["motor"] = server.get("engine") or scheme or None
|
||||
origin["consulta_propia"] = bool(payload.get("query"))
|
||||
return origin
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FieldStats:
|
||||
with_value: int = 0
|
||||
empty: int = 0
|
||||
errors: Counter = field(default_factory=Counter)
|
||||
shapes: Counter = field(default_factory=Counter)
|
||||
catalog_values: Counter = field(default_factory=Counter)
|
||||
|
||||
def as_dict(self, threshold: int) -> dict[str, Any]:
|
||||
out: dict[str, Any] = {"con_valor": self.with_value, "vacios": self.empty}
|
||||
if self.errors:
|
||||
out["errores"] = dict(self.errors)
|
||||
if self.shapes:
|
||||
out["formatos_rechazados"] = dict(self.shapes.most_common(10))
|
||||
frequent = {v: n for v, n in self.catalog_values.most_common(20) if n >= threshold}
|
||||
if frequent:
|
||||
out["valores_fuera_de_catalogo"] = frequent
|
||||
rare = sum(n for n in self.catalog_values.values() if n < threshold)
|
||||
if rare:
|
||||
out["valores_fuera_de_catalogo_poco_frecuentes"] = rare
|
||||
return out
|
||||
|
||||
|
||||
class _SourceAudit:
|
||||
def __init__(self, source: ImportSource):
|
||||
self.source = source
|
||||
self.fields: dict[str, _FieldStats] = defaultdict(_FieldStats)
|
||||
self.rows: dict[str, Any] = {"leidas": 0}
|
||||
self.links: dict[str, int] = {}
|
||||
self.warnings: Counter = Counter()
|
||||
|
||||
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
|
||||
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
|
||||
merged = 0
|
||||
for row in rows:
|
||||
self.rows["leidas"] += 1
|
||||
if row is None:
|
||||
merged += 1
|
||||
continue
|
||||
for name in mapped:
|
||||
stats = self.fields[name]
|
||||
if _blank(row.get(name)):
|
||||
stats.empty += 1
|
||||
else:
|
||||
stats.with_value += 1
|
||||
if merged:
|
||||
self.rows["combinadas_con_otra_fuente"] = merged
|
||||
|
||||
def observe_validation(self, validation: BatchValidationResult) -> None:
|
||||
self.rows["validas"] = validation.valid_count
|
||||
self.rows["rechazadas_en_validacion"] = validation.error_count
|
||||
for row_errors in validation.rejected:
|
||||
for error in row_errors.errors:
|
||||
stats = self.fields[error.field]
|
||||
stats.errors[error.category.value] += 1
|
||||
if _blank(error.raw_value):
|
||||
continue
|
||||
if error.category is ErrorCategory.OUT_OF_CATALOG and len(str(error.raw_value)) <= _SHAPE_MAX:
|
||||
stats.catalog_values[str(error.raw_value).strip().upper()] += 1
|
||||
elif error.category in (ErrorCategory.TYPE_INVALID, ErrorCategory.UNKNOWN, ErrorCategory.OUT_OF_CATALOG):
|
||||
stats.shapes[value_shape(error.raw_value)] += 1
|
||||
|
||||
def observe_write(self, *, created: int, updated: int, conflicts: int, linked: dict[str, int]) -> None:
|
||||
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
|
||||
self.links = dict(linked)
|
||||
|
||||
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
|
||||
for warning in warnings:
|
||||
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
|
||||
|
||||
def as_dict(self, threshold: int) -> dict[str, Any]:
|
||||
spec_fields = self.source.spec.schema.model_fields
|
||||
required = {name for name, info in spec_fields.items() if info.is_required()}
|
||||
mapped = set(self.source.column_mapping.values())
|
||||
fixed = set(self.source.defaults)
|
||||
out: dict[str, Any] = {
|
||||
"destino": self.source.target,
|
||||
"origen": _source_origin(self.source),
|
||||
"mapeo": {
|
||||
"columnas_origen": sorted(column_label(c) for c in self.source.column_mapping),
|
||||
"campos_mapeados": sorted(mapped),
|
||||
"campos_con_valor_fijo": sorted(fixed),
|
||||
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
|
||||
"requeridos_sin_mapear": sorted(required - mapped - fixed),
|
||||
},
|
||||
"filas": self.rows,
|
||||
"campos": {name: stats.as_dict(threshold) for name, stats in sorted(self.fields.items())},
|
||||
}
|
||||
if self.links:
|
||||
out["vinculos_resueltos"] = self.links
|
||||
if self.warnings:
|
||||
out["advertencias"] = dict(self.warnings)
|
||||
return out
|
||||
|
||||
|
||||
class ImportAudit:
|
||||
"""The aggregate record of one attempt. `operation` is "validacion" or "carga"."""
|
||||
|
||||
def __init__(self, operation: str, options: dict[str, Any] | None = None):
|
||||
self.id = str(uuid.uuid4())
|
||||
self.operation = operation
|
||||
self.options = options or {}
|
||||
self.started = time.monotonic()
|
||||
self.date = datetime.now(timezone.utc)
|
||||
self.sources: list[_SourceAudit] = []
|
||||
self.outcome = "en_curso"
|
||||
self.error: dict[str, str] | None = None
|
||||
|
||||
def source(self, source: ImportSource) -> _SourceAudit:
|
||||
audit = _SourceAudit(source)
|
||||
self.sources.append(audit)
|
||||
return audit
|
||||
|
||||
def succeed(self, outcome: str = "completada") -> None:
|
||||
self.outcome = outcome
|
||||
|
||||
def fail(self, exc: BaseException, outcome: str = "fallida") -> None:
|
||||
self.outcome = outcome
|
||||
self.error = {"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}
|
||||
|
||||
@property
|
||||
def domain(self) -> str | None:
|
||||
return self.sources[0].source.domain if self.sources else None
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
threshold = min_count()
|
||||
record: dict[str, Any] = {
|
||||
"version": SCHEMA_VERSION,
|
||||
"id": self.id,
|
||||
"fecha": self.date.isoformat(timespec="seconds"),
|
||||
"operacion": self.operation,
|
||||
"dominio": self.domain,
|
||||
"resultado": self.outcome,
|
||||
"duracion_s": round(time.monotonic() - self.started, 2),
|
||||
"opciones": self.options,
|
||||
"fuentes": [s.as_dict(threshold) for s in self.sources],
|
||||
}
|
||||
if self.error:
|
||||
record["error"] = self.error
|
||||
totals = Counter()
|
||||
for s in self.sources:
|
||||
for key, value in s.rows.items():
|
||||
totals[key] += value
|
||||
record["totales"] = dict(totals)
|
||||
return record
|
||||
|
||||
|
||||
class AuditSink(ABC):
|
||||
@abstractmethod
|
||||
def write(self, record: dict[str, Any]) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def read(self) -> list[dict[str, Any]]: ...
|
||||
|
||||
|
||||
class JsonlAuditSink(AuditSink):
|
||||
"""One JSON object per line; appends are locked so several gunicorn
|
||||
workers can share the file."""
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
|
||||
def write(self, record: dict[str, Any]) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
line = json.dumps(record, ensure_ascii=False, default=str) + "\n"
|
||||
with open(self.path, "a", encoding="utf-8") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
handle.write(line)
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
|
||||
def read(self) -> list[dict[str, Any]]:
|
||||
if not self.path.exists():
|
||||
return []
|
||||
records = []
|
||||
with open(self.path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
records.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return records
|
||||
|
||||
|
||||
def default_sink() -> AuditSink:
|
||||
return JsonlAuditSink(report_dir() / "importaciones.jsonl")
|
||||
|
||||
|
||||
def record(audit: ImportAudit, sink: AuditSink | None = None) -> None:
|
||||
"""Writes the record; a full disk must not turn a successful import into an error."""
|
||||
try:
|
||||
(sink or default_sink()).write(audit.as_dict())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def summarize(records: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Totals per target over every logged attempt: how many rows arrived,
|
||||
how many were written, and which fields failed most and how."""
|
||||
by_target: dict[str, dict[str, Any]] = {}
|
||||
attempts = Counter()
|
||||
for rec in records:
|
||||
attempts[f"{rec.get('operacion')}:{rec.get('resultado')}"] += 1
|
||||
for src in rec.get("fuentes", []):
|
||||
target = by_target.setdefault(
|
||||
src["destino"],
|
||||
{"intentos": 0, "cargas_completadas": 0, "filas": Counter(), "errores_por_campo": defaultdict(Counter),
|
||||
"formatos_rechazados": defaultdict(Counter), "requeridos_sin_mapear": Counter(), "origenes": Counter()},
|
||||
)
|
||||
target["intentos"] += 1
|
||||
if rec.get("operacion") == "carga" and rec.get("resultado") == "completada":
|
||||
target["cargas_completadas"] += 1
|
||||
for key, value in src.get("filas", {}).items():
|
||||
target["filas"][key] += value
|
||||
target["origenes"][src.get("origen", {}).get("tipo") or "?"] += 1
|
||||
for name in src.get("mapeo", {}).get("requeridos_sin_mapear", []):
|
||||
target["requeridos_sin_mapear"][name] += 1
|
||||
for name, stats in src.get("campos", {}).items():
|
||||
target["errores_por_campo"][name].update(stats.get("errores", {}))
|
||||
target["formatos_rechazados"][name].update(stats.get("formatos_rechazados", {}))
|
||||
return {
|
||||
"intentos": dict(attempts),
|
||||
"ultimo": records[-1]["fecha"] if records else None,
|
||||
"destinos": {
|
||||
key: {
|
||||
"intentos": t["intentos"],
|
||||
"cargas_completadas": t["cargas_completadas"],
|
||||
"filas_en_cargas_completadas": dict(t["filas"]),
|
||||
"origenes": dict(t["origenes"]),
|
||||
"requeridos_sin_mapear": dict(t["requeridos_sin_mapear"]),
|
||||
"errores_por_campo": {k: dict(v) for k, v in t["errores_por_campo"].items() if v},
|
||||
"formatos_rechazados": {k: dict(v.most_common(10)) for k, v in t["formatos_rechazados"].items() if v},
|
||||
}
|
||||
for key, t in sorted(by_target.items())
|
||||
},
|
||||
}
|
||||
@@ -17,6 +17,9 @@ _RESULTADO_VPH_CATALOG = Catalog(ResultadoVPH)
|
||||
|
||||
|
||||
class CitologiaCervicalImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
cit_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Import schema for `core.cacu.models.EpisodioClinico`.
|
||||
|
||||
`nm_id` and `episodio_anterior_id` are true internal surrogate foreign keys
|
||||
with no natural-key sibling column on this table (unlike `pac_id`/
|
||||
`pac_id_hospital` or `ord_id`/`ord_numero_hospital`), so `LinkResolver` has
|
||||
no way to fill them from an external source. They stay out of this schema;
|
||||
per the model's own docstring, linking an episode to the note/order it came
|
||||
from and to its predecessor is the job of the not-yet-built IND-02/IND-03
|
||||
episode-correlation logic, not a plain field-mapping import.
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
@@ -12,6 +12,9 @@ _TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: int
|
||||
|
||||
@@ -15,6 +15,9 @@ _SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Import schema for `core.cama.models.EpisodioClinico`. Same structure as
|
||||
`webapi.imports.schemas.cacu.episodio_clinico.EpisodioClinicoImportSchema`
|
||||
(see its docstring for why `nm_id`/`episodio_anterior_id` are excluded).
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
@@ -12,6 +12,9 @@ _BIRADS_CATALOG = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
|
||||
|
||||
class MastografiaImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
mast_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_id: Optional[int] = None
|
||||
|
||||
@@ -12,6 +12,9 @@ _TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: int
|
||||
|
||||
@@ -15,6 +15,9 @@ _SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
|
||||
@@ -31,14 +31,6 @@ def optional_str(v: Any) -> Any:
|
||||
return text or None
|
||||
|
||||
|
||||
def rounded_int(v: Any) -> Any:
|
||||
"""A minutes/count field stored as an `int` column, whose source may
|
||||
report a float (e.g. a duration measured to tenths of a minute)."""
|
||||
if v is None or (isinstance(v, str) and v.strip() == ""):
|
||||
return None
|
||||
return round(float(v))
|
||||
|
||||
|
||||
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
|
||||
@@ -13,11 +13,13 @@ from pydantic import BaseModel
|
||||
from core.cacu.models import BiometriaHematica as CacuBiometriaHematica
|
||||
from core.cacu.models import BiopsiaCervical as CacuBiopsiaCervical
|
||||
from core.cacu.models import CitologiaCervical as CacuCitologiaCervical
|
||||
from core.cacu.models import EpisodioClinico as CacuEpisodioClinico
|
||||
from core.cacu.models import NotaMedica as CacuNotaMedica
|
||||
from core.cacu.models import OrdenesEstudio as CacuOrdenesEstudio
|
||||
from core.cacu.models import Paciente as CacuPaciente
|
||||
from core.cama.models import BiometriaHematica as CamaBiometriaHematica
|
||||
from core.cama.models import BiopsiaMama as CamaBiopsiaMama
|
||||
from core.cama.models import EpisodioClinico as CamaEpisodioClinico
|
||||
from core.cama.models import Mastografia as CamaMastografia
|
||||
from core.cama.models import NotaMedica as CamaNotaMedica
|
||||
from core.cama.models import OrdenesEstudio as CamaOrdenesEstudio
|
||||
@@ -35,11 +37,13 @@ from core.tea.models import PotencialesEvocadosAuditivos as TeaPotencialesEvocad
|
||||
from persistance.cacu import biometria_hematica_repository as cacu_biometria_hematica_repository
|
||||
from persistance.cacu import biopsia_cervical_repository as cacu_biopsia_cervical_repository
|
||||
from persistance.cacu import citologia_cervical_repository as cacu_citologia_cervical_repository
|
||||
from persistance.cacu import episodio_clinico_repository as cacu_episodio_clinico_repository
|
||||
from persistance.cacu import nota_medica_repository as cacu_nota_medica_repository
|
||||
from persistance.cacu import ordenes_estudio_repository as cacu_ordenes_estudio_repository
|
||||
from persistance.cacu import paciente_repository as cacu_paciente_repository
|
||||
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
|
||||
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
|
||||
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
|
||||
from persistance.cama import mastografia_repository as cama_mastografia_repository
|
||||
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
|
||||
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
|
||||
@@ -62,6 +66,9 @@ from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CacuEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.nota_medica import NotaMedicaImportSchema as CacuNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cacu.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CacuOrdenesEstudioImportSchema,
|
||||
@@ -71,6 +78,9 @@ from webapi.imports.schemas.cama.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CamaBiometriaHematicaImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.biopsia_mama import BiopsiaMamaImportSchema
|
||||
from webapi.imports.schemas.cama.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
|
||||
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
@@ -147,6 +157,14 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=cacu_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cacu.EpisodioClinico": EntitySpec(
|
||||
schema=CacuEpisodioClinicoImportSchema,
|
||||
model=CacuEpisodioClinico,
|
||||
repository=cacu_episodio_clinico_repository,
|
||||
# No hospital-visible identifier of its own, like EvaluacionPsicologica
|
||||
# or PartoNeonatal; a patient can have several episodes.
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
schema=CamaPacienteImportSchema,
|
||||
model=CamaPaciente,
|
||||
@@ -183,6 +201,12 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=cama_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.EpisodioClinico": EntitySpec(
|
||||
schema=CamaEpisodioClinicoImportSchema,
|
||||
model=CamaEpisodioClinico,
|
||||
repository=cama_episodio_clinico_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.OrdenesEstudio": EntitySpec(
|
||||
schema=TeaOrdenesEstudioImportSchema,
|
||||
model=TeaOrdenesEstudio,
|
||||
|
||||
@@ -17,7 +17,7 @@ from core.tea.enums import (
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str, rounded_int
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
@@ -32,7 +32,7 @@ _CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_ord_id: Optional[str] = None
|
||||
eeg_pac_id: Optional[str] = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = None
|
||||
@@ -45,7 +45,7 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_privacion_sueno: Optional[int] = None
|
||||
eeg_sedacion: Optional[int] = None
|
||||
eeg_sedacion_farmaco: Optional[str] = None
|
||||
eeg_duracion_min: Optional[int] = None
|
||||
eeg_duracion_min: Optional[float] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: Optional[str] = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
@@ -70,7 +70,7 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_estudio: Optional[bytes] = None
|
||||
|
||||
@field_validator(
|
||||
"eeg_ord_id", "eeg_pac_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_ord_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_descripcion_senal", "eeg_localizacion", "eeg_conclusion_texto",
|
||||
"eeg_id_registro_laboratorio", "eeg_pdf_ruta", "eeg_nlp_version",
|
||||
mode="before",
|
||||
@@ -84,11 +84,6 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@field_validator("eeg_duracion_min", mode="before")
|
||||
@classmethod
|
||||
def _coerce_duracion_min(cls, v):
|
||||
return rounded_int(v)
|
||||
|
||||
@field_validator("eeg_estudio", mode="before")
|
||||
@classmethod
|
||||
def _valid_edf(cls, v):
|
||||
|
||||
@@ -5,12 +5,12 @@ from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from typing import Any, Iterator
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from persistance.repository import ConflictPolicy
|
||||
from webapi.imports.audit import ImportAudit
|
||||
from webapi.imports.connectors import Connector, ConnectorError, build_connector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
|
||||
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
|
||||
@@ -130,8 +131,16 @@ def _jsonable(value: Any) -> Any:
|
||||
return str(value)
|
||||
|
||||
|
||||
def validate_source(raw_source: dict[str, Any]) -> BatchValidationResult:
|
||||
return ImportSource.parse(raw_source).validate()
|
||||
def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult:
|
||||
source = ImportSource.parse(raw_source)
|
||||
if audit is None:
|
||||
return source.validate()
|
||||
tracked = audit.source(source)
|
||||
rows = list(source.rows())
|
||||
tracked.observe_rows(rows)
|
||||
validation = validate_rows(source.spec.schema, rows)
|
||||
tracked.observe_validation(validation)
|
||||
return validation
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -215,7 +224,9 @@ def _key_part(value: Any) -> Any:
|
||||
return str(value).strip().upper()
|
||||
|
||||
|
||||
def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -> list[SourceCommitResult]:
|
||||
def commit_sources(
|
||||
raw_sources: Any, *, on_conflict: str, merge: bool = False, audit: ImportAudit | None = None
|
||||
) -> list[SourceCommitResult]:
|
||||
"""Writes a batch in one transaction. With `merge`, rows of different
|
||||
sources sharing a natural key are combined first (see `merge_duplicates`)."""
|
||||
try:
|
||||
@@ -224,6 +235,7 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
|
||||
|
||||
sources = _parse_batch(raw_sources)
|
||||
tracked = [audit.source(source) for source in sources] if audit else []
|
||||
if policy is ConflictPolicy.UPSERT:
|
||||
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
|
||||
if keyless:
|
||||
@@ -234,6 +246,10 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
rows: list[list[dict[str, Any] | None]] = [list(source.rows()) for source in sources]
|
||||
merged, merge_warnings = merge_duplicates(sources, rows) if merge else ({}, {})
|
||||
validated = [(source, validate_rows(source.spec.schema, source_rows)) for source, source_rows in zip(sources, rows)]
|
||||
for position, source_audit in enumerate(tracked):
|
||||
source_audit.observe_rows(rows[position])
|
||||
source_audit.observe_validation(validated[position][1])
|
||||
source_audit.observe_warnings(merge_warnings.get(position, []))
|
||||
|
||||
session = sources[0].spec.repository.open_session()
|
||||
links = LinkResolver(session)
|
||||
@@ -279,6 +295,11 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
merged=merged.get(position, 0),
|
||||
warnings=merge_warnings.get(position, []),
|
||||
)
|
||||
if tracked:
|
||||
tracked[position].observe_write(
|
||||
created=write.created_count, updated=write.updated_count,
|
||||
conflicts=write.rejected_count, linked=linked,
|
||||
)
|
||||
session.commit()
|
||||
except SQLAlchemyError as exc:
|
||||
session.rollback()
|
||||
|
||||
@@ -55,7 +55,12 @@ def dependency_rank(target_key: str) -> int:
|
||||
class LinkResolver:
|
||||
"""Looks up parent primary keys by natural key within the batch's session,
|
||||
so parents written earlier in the same uncommitted transaction are found.
|
||||
A missing parent leaves the FK null, which Core allows."""
|
||||
|
||||
The natural key wins over an id the source sent: a hospital table carries
|
||||
the hospital's internal ids, which only match ours when the parent was
|
||||
loaded with its own id. An id is kept as sent only when there is no
|
||||
natural key or its parent isn't loaded; a missing parent leaves the FK
|
||||
null, which Core allows."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
@@ -65,12 +70,13 @@ class LinkResolver:
|
||||
linked = []
|
||||
for link in links_for(target_key):
|
||||
value = row.get(link.via_field)
|
||||
if row.get(link.fk_field) is not None or value is None:
|
||||
if value is None:
|
||||
continue
|
||||
pk = self._lookup(link, value)
|
||||
if pk is not None:
|
||||
if row.get(link.fk_field) != pk:
|
||||
linked.append(link.fk_field)
|
||||
row[link.fk_field] = pk
|
||||
linked.append(link.fk_field)
|
||||
return linked
|
||||
|
||||
def _lookup(self, link: ForeignKeyLink, value: Any) -> Any:
|
||||
|
||||
+43
-11
@@ -2,17 +2,22 @@
|
||||
|
||||
`registrar_indicadores` agrega a un blueprint:
|
||||
|
||||
GET /indicadores catálogo de indicadores
|
||||
GET /indicadores catálogo de indicadores (con sus `filtros`)
|
||||
GET /indicadores/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||
GET /indicadores/<id>/datos?periodos=&estrato=&filtro= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=&filtro=
|
||||
|
||||
Las definiciones salen del kit (`measures_de`), los datos de
|
||||
`indicadores_kit.serving.datos` y las figuras de
|
||||
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||
contrato con el frontend: no se quita ni se renombra un campo.
|
||||
|
||||
`?filtro=estrato:valor[,estrato:valor]` (T-19f) cuenta lo mismo solo con las
|
||||
unidades que tienen esos valores: el mismo contrato, y en `/datos` la llave
|
||||
`filtros`. Solo se aceptan los filtros que el indicador declara
|
||||
(`extension.filtros`) y los valores de su catálogo; si no, 400.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -21,7 +26,8 @@ from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.registry.measures import Measure, measures_de
|
||||
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.contratos import FiltroNoDeclarado
|
||||
from indicadores_kit.serving.datos import datos_de, filtros_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.figuras import (
|
||||
TEMAS,
|
||||
figura_json,
|
||||
@@ -59,6 +65,21 @@ def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||
|
||||
|
||||
def filtros_pedidos(texto: str | None) -> dict[str, str]:
|
||||
"""`estrato:valor[,estrato:valor]` -> `{estrato: valor}`. Vacío si no se pidió; `ValueError` si viene mal escrito."""
|
||||
if not texto:
|
||||
return {}
|
||||
filtros = {}
|
||||
for parte in texto.split(","):
|
||||
estrato, separador, valor = parte.partition(":")
|
||||
if not separador or not estrato or not valor:
|
||||
raise ValueError(f"filtro mal escrito {parte!r}; use estrato:valor")
|
||||
if estrato in filtros:
|
||||
raise ValueError(f"el filtro {estrato!r} va dos veces")
|
||||
filtros[estrato] = valor
|
||||
return filtros
|
||||
|
||||
|
||||
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||
|
||||
@@ -92,11 +113,16 @@ def registrar_indicadores(
|
||||
|
||||
def listar_indicadores():
|
||||
# Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo.
|
||||
return _json([
|
||||
resumen_de(id_, medida)
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
# `filtros` (T-24f): los que admite cada uno, con sus valores del catálogo, para armar `?filtro=`.
|
||||
sesion = get_session()
|
||||
try:
|
||||
return _json([
|
||||
{**resumen_de(id_, medida), "filtros": filtros_de(sesion, medida)}
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
finally:
|
||||
sesion.close()
|
||||
|
||||
def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]:
|
||||
"""Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica."""
|
||||
@@ -139,6 +165,7 @@ def registrar_indicadores(
|
||||
)
|
||||
try:
|
||||
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -147,7 +174,9 @@ def registrar_indicadores(
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
@@ -171,6 +200,7 @@ def registrar_indicadores(
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -180,7 +210,9 @@ def registrar_indicadores(
|
||||
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Recomputes a domain's indicators after its staging tables change.
|
||||
|
||||
A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`),
|
||||
which only drops a marker file. A separate process (`python -m
|
||||
webapi.indicadores_vivos`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's pipeline with Hamilton (`webapi.pipeline`):
|
||||
catalogs -> staging to facts -> views -> registry -> definitions -> reports.
|
||||
Requests that arrive while a domain is running are folded into one more run.
|
||||
|
||||
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
|
||||
and `estado.json`; each run is also appended, as counts only, to
|
||||
`indicadores.jsonl` in the import report directory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
|
||||
|
||||
DOMINIOS = ("cacu", "cama", "tea")
|
||||
_SUMMARY_MAX = 400
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _short(value: Any) -> str:
|
||||
text = str(value)
|
||||
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
||||
|
||||
|
||||
class ColaDeRecalculo:
|
||||
"""Marker-file queue and status of the indicator recomputations."""
|
||||
|
||||
def __init__(self, base: Path | None = None):
|
||||
self.base = Path(base or os.environ.get("INDICADORES_DIR", "indicadores"))
|
||||
|
||||
@property
|
||||
def _pending(self) -> Path:
|
||||
return self.base / "pendiente"
|
||||
|
||||
@property
|
||||
def _status_path(self) -> Path:
|
||||
return self.base / "estado.json"
|
||||
|
||||
def solicitar(self, dominio: str) -> None:
|
||||
if dominio not in DOMINIOS:
|
||||
raise ValueError(f"dominio desconocido: {dominio!r}")
|
||||
self._pending.mkdir(parents=True, exist_ok=True)
|
||||
(self._pending / dominio).write_text(_now(), encoding="utf-8")
|
||||
|
||||
def pendientes(self) -> list[str]:
|
||||
if not self._pending.exists():
|
||||
return []
|
||||
return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS)
|
||||
|
||||
def tomar(self, dominio: str) -> bool:
|
||||
"""Consumes the marker; a request made from now on queues one more run."""
|
||||
try:
|
||||
(self._pending / dominio).unlink()
|
||||
return True
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
def estado(self) -> dict[str, Any]:
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
pending = set(self.pendientes())
|
||||
return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS}
|
||||
|
||||
def _guardar_estado(self, dominio: str, entrada: dict[str, Any]) -> None:
|
||||
self.base.mkdir(parents=True, exist_ok=True)
|
||||
lock = self.base / ".estado.lock"
|
||||
with open(lock, "w") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
status[dominio] = entrada
|
||||
tmp = self._status_path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
tmp.replace(self._status_path)
|
||||
|
||||
def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrar`: the API migrates on startup)."""
|
||||
from orquestacion import Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
|
||||
from webapi.pipeline import correr
|
||||
|
||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
|
||||
inicio = _now()
|
||||
started = time.monotonic()
|
||||
self._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True)
|
||||
nombres = [a.nombre for a in aristas_de(dominio) if a.nombre != "migrar"]
|
||||
pasos = correr(ctx, solo=nombres)
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"arista": p.arista, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
)
|
||||
except Exception as exc: # the worker must survive a failing domain
|
||||
log.exception("recálculo de %s falló", dominio)
|
||||
entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))})
|
||||
entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2))
|
||||
self._guardar_estado(dominio, entrada)
|
||||
try:
|
||||
JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada})
|
||||
except OSError:
|
||||
pass
|
||||
return entrada
|
||||
|
||||
def atender(self) -> list[str]:
|
||||
"""Runs every pending domain once; returns the ones it ran."""
|
||||
ran = []
|
||||
for dominio in self.pendientes():
|
||||
if self.tomar(dominio):
|
||||
self.correr(dominio)
|
||||
ran.append(dominio)
|
||||
return ran
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
cola = ColaDeRecalculo()
|
||||
interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
|
||||
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
|
||||
for dominio in DOMINIOS:
|
||||
cola.solicitar(dominio)
|
||||
stopping = False
|
||||
|
||||
def _stop(*_):
|
||||
nonlocal stopping
|
||||
stopping = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
|
||||
while not stopping:
|
||||
for dominio in cola.atender():
|
||||
log.info("%s: %s", dominio, cola.estado()[dominio].get("estado"))
|
||||
for _ in range(int(interval * 10)):
|
||||
if stopping:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Runs a domain's indicator pipeline with Hamilton.
|
||||
|
||||
The steps are the kit's own transformations as Orquestacion declares them
|
||||
(`orquestacion.aristas.aristas_de`): each one names the table groups it reads
|
||||
and writes, and moves data only through the database. Here every step becomes
|
||||
a Hamilton node whose inputs are the steps that write what it reads, so
|
||||
Hamilton orders and runs the graph; nothing of Orquestacion's own executor is
|
||||
used. Steps left out of `solo` are given as overrides and don't run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from orquestacion.arista import Arista, Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paso:
|
||||
"""What a step left: its short summary and how long it took. `None` summary: not run."""
|
||||
|
||||
arista: str
|
||||
resumen: Any
|
||||
segundos: float
|
||||
|
||||
|
||||
def _node(arista: Arista, ctx: Contexto, inputs: Sequence[str]) -> Callable[..., Paso]:
|
||||
def run(**_upstream: Paso) -> Paso:
|
||||
started = time.monotonic()
|
||||
return Paso(arista.nombre, arista.correr(ctx), time.monotonic() - started)
|
||||
|
||||
run.__name__ = arista.nombre
|
||||
run.__doc__ = arista.descripcion
|
||||
run.__annotations__ = {name: Paso for name in inputs} | {"return": Paso}
|
||||
run.__signature__ = inspect.Signature(
|
||||
[inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, annotation=Paso) for name in inputs],
|
||||
return_annotation=Paso,
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def modulo(ctx: Contexto, aristas: Sequence[Arista]) -> ModuleType:
|
||||
"""The Hamilton module of a domain: one function per step."""
|
||||
writer = {vertex: arista.nombre for arista in aristas for vertex in arista.escribe}
|
||||
nodes = []
|
||||
for arista in aristas:
|
||||
inputs = sorted({writer[v] for v in arista.lee if v in writer and writer[v] != arista.nombre})
|
||||
nodes.append(_node(arista, ctx, inputs))
|
||||
return ad_hoc_utils.create_temporary_module(*nodes)
|
||||
|
||||
|
||||
def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]:
|
||||
"""Runs the domain's steps (all, or only `solo`) in dependency order."""
|
||||
if ctx.repos is None:
|
||||
ctx = Contexto(ctx.proyecto, ctx.anio_inicio, ctx.anio_fin, ctx.corte, ctx.permitir_sin_definir,
|
||||
ctx.parametros, repos=repositorios_de(ctx.proyecto))
|
||||
aristas = aristas_de(ctx.proyecto)
|
||||
nombres = [a.nombre for a in aristas]
|
||||
wanted = [n for n in nombres if solo is None or n in solo]
|
||||
skipped = {n: Paso(n, None, 0.0) for n in nombres if n not in wanted}
|
||||
dr = driver.Builder().with_modules(modulo(ctx, aristas)).build()
|
||||
results = dr.execute(wanted, overrides=skipped)
|
||||
return [results[n] for n in _order(dr, wanted)]
|
||||
|
||||
|
||||
def _order(dr: driver.Driver, wanted: Sequence[str]) -> list[str]:
|
||||
"""Topological order of the requested steps, for reporting."""
|
||||
graph = dr.graph
|
||||
order: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def visit(name: str) -> None:
|
||||
if name in seen:
|
||||
return
|
||||
seen.add(name)
|
||||
for dependency in graph.nodes[name].dependencies:
|
||||
visit(dependency.name)
|
||||
if name in wanted:
|
||||
order.append(name)
|
||||
|
||||
for name in wanted:
|
||||
visit(name)
|
||||
return order
|
||||
@@ -0,0 +1,68 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, solo en DEV.
|
||||
|
||||
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
|
||||
|
||||
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
|
||||
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
|
||||
existe (404). La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida,
|
||||
se abre la sesión y se traducen los errores. El contrato: `_docs/contratos/cacu_seguimiento_y_estratos.md` §2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||
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:
|
||||
"""Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`)."""
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV."""
|
||||
blueprint = Blueprint("cacu_seguimiento", __name__)
|
||||
|
||||
@blueprint.get("/seguimiento")
|
||||
def get_seguimiento():
|
||||
try:
|
||||
pedido = _pedido(request.args)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except PaginaFuera as error:
|
||||
return jsonify({"error": str(error)}), 404
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
return blueprint
|
||||
|
||||
|
||||
def _pedido(args) -> dict:
|
||||
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
|
||||
pedido = {}
|
||||
if corte := args.get("corte"):
|
||||
if not FECHA.fullmatch(corte):
|
||||
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
|
||||
pedido["corte"] = date.fromisoformat(corte)
|
||||
for nombre in ("meses", "page", "page_size"):
|
||||
if (texto := args.get(nombre)) not in (None, ""):
|
||||
if not texto.isdigit():
|
||||
raise ValueError(f"{nombre} debe ser un entero; llegó {texto!r}")
|
||||
pedido[nombre] = int(texto)
|
||||
if estatus := args.get("estatus"):
|
||||
pedido["estatus"] = estatus
|
||||
return pedido
|
||||
Reference in New Issue
Block a user