Files

60 lines
2.2 KiB
Python

"""Aggregate reports: the log of import attempts and the state of the live
indicator recomputation. Nothing here returns row-level data."""
import os
from flask import Blueprint, Response, jsonify, request
from webapi.detached_jobs import cluster_environment
from webapi.imports import audit as import_audit
from webapi.recomputation import DOMAINS, RecomputationQueue
reports_bp = Blueprint("reportes", __name__)
@reports_bp.get("/importaciones")
def import_log():
"""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]})
@reports_bp.get("/importaciones/descarga")
def import_log_download():
"""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"},
)
@reports_bp.get("/indicadores")
def recomputation_status():
"""Per domain: state of the last recomputation and whether another is pending."""
return jsonify(RecomputationQueue().status())
@reports_bp.post("/indicadores/<dominio>/recalcular")
def recompute(dominio: str):
if dominio not in DOMAINS:
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
body = request.get_json(silent=True) if request.get_data() else {}
if not isinstance(body, dict):
return jsonify({"error": "El cuerpo debe ser un objeto JSON."}), 400
try:
cluster = cluster_environment(body, dict(os.environ))
except ValueError as error:
return jsonify({"error": str(error)}), 400
RecomputationQueue().request_run(dominio, cluster)
return jsonify({"pendiente": True}), 202