|
|
@@ -0,0 +1,119 @@
|
|
|
+"""健康评估结果只读接口。
|
|
|
+
|
|
|
+算法服务器/平台导入后的 health.json 与 Word 报告落在 HDKG_OUT_ROOT:
|
|
|
+ <root>/<fieldCode>/<YYYY-MM>/detail/health.json
|
|
|
+ <root>/<fieldCode>/<YYYY-MM>/report/internal.docx
|
|
|
+ <root>/<fieldCode>/<YYYY-MM>/report/external.docx
|
|
|
+ <root>/<fieldCode>/<YYYY-MM>/registration.json
|
|
|
+
|
|
|
+本路由只读文件,不触发批次、不写数据库;批次仍由 hdkg-run 或平台导入任务完成。
|
|
|
+"""
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import json
|
|
|
+import os
|
|
|
+import re
|
|
|
+from pathlib import Path
|
|
|
+from typing import Any, Dict, List, Optional
|
|
|
+
|
|
|
+from fastapi import APIRouter, HTTPException
|
|
|
+from fastapi.responses import FileResponse
|
|
|
+
|
|
|
+router = APIRouter(prefix="/health-assessment", tags=["health-assessment"])
|
|
|
+
|
|
|
+OUT_ROOT = Path(os.getenv("HDKG_OUT_ROOT", "/data/hdkg/out")).resolve()
|
|
|
+FIELD_RE = re.compile(r"^WOF\d{9,}$")
|
|
|
+PERIOD_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
|
|
|
+
|
|
|
+
|
|
|
+def _safe_parts(field_code: str, period: str) -> tuple[str, str]:
|
|
|
+ if not FIELD_RE.match(field_code or ""):
|
|
|
+ raise HTTPException(status_code=400, detail="fieldCode 格式不正确")
|
|
|
+ if not PERIOD_RE.match(period or ""):
|
|
|
+ raise HTTPException(status_code=400, detail="period 须为 YYYY-MM")
|
|
|
+ return field_code, period
|
|
|
+
|
|
|
+
|
|
|
+def _period_dir(field_code: str, period: str) -> Path:
|
|
|
+ field_code, period = _safe_parts(field_code, period)
|
|
|
+ p = (OUT_ROOT / field_code / period).resolve()
|
|
|
+ if OUT_ROOT not in p.parents and p != OUT_ROOT:
|
|
|
+ raise HTTPException(status_code=400, detail="路径不合法")
|
|
|
+ return p
|
|
|
+
|
|
|
+
|
|
|
+def _read_json(path: Path) -> Optional[Dict[str, Any]]:
|
|
|
+ try:
|
|
|
+ with open(path, "r", encoding="utf-8") as f:
|
|
|
+ return json.load(f)
|
|
|
+ except (OSError, ValueError):
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
+@router.get("/periods")
|
|
|
+def periods(fieldCode: str) -> Dict[str, Any]:
|
|
|
+ """列出某场已发布期次;没有产物时返回空数组,不报 500。"""
|
|
|
+ if not FIELD_RE.match(fieldCode or ""):
|
|
|
+ raise HTTPException(status_code=400, detail="fieldCode 格式不正确")
|
|
|
+ field_dir = (OUT_ROOT / fieldCode).resolve()
|
|
|
+ if not field_dir.is_dir():
|
|
|
+ return {"code": 200, "data": []}
|
|
|
+ out: List[Dict[str, Any]] = []
|
|
|
+ for period_dir in sorted(field_dir.iterdir(), reverse=True):
|
|
|
+ if not period_dir.is_dir() or not PERIOD_RE.match(period_dir.name):
|
|
|
+ continue
|
|
|
+ reg = _read_json(period_dir / "registration.json") or {}
|
|
|
+ detail = period_dir / "detail/health.json"
|
|
|
+ if not detail.is_file() and not reg:
|
|
|
+ continue
|
|
|
+ out.append(
|
|
|
+ {
|
|
|
+ "fieldCode": fieldCode,
|
|
|
+ "period": period_dir.name,
|
|
|
+ "status": reg.get("status") or ("ok" if detail.is_file() else "unknown"),
|
|
|
+ "detailAvailable": detail.is_file(),
|
|
|
+ "internalReportAvailable": (period_dir / "report/internal.docx").is_file(),
|
|
|
+ "externalReportAvailable": (period_dir / "report/external.docx").is_file(),
|
|
|
+ "tables": reg.get("tables"),
|
|
|
+ "error": reg.get("error"),
|
|
|
+ }
|
|
|
+ )
|
|
|
+ return {"code": 200, "data": out}
|
|
|
+
|
|
|
+
|
|
|
+@router.get("/detail")
|
|
|
+def detail(fieldCode: str, period: str) -> Dict[str, Any]:
|
|
|
+ """读取前端版 health.json(不含 health_full 内部版)。"""
|
|
|
+ period_dir = _period_dir(fieldCode, period)
|
|
|
+ p = period_dir / "detail/health.json"
|
|
|
+ if not p.is_file():
|
|
|
+ raise HTTPException(status_code=404, detail="该场该期暂无 health.json")
|
|
|
+ doc = _read_json(p)
|
|
|
+ if not isinstance(doc, dict):
|
|
|
+ raise HTTPException(status_code=500, detail="health.json 不是合法 JSON 对象")
|
|
|
+ return {"code": 200, "data": doc}
|
|
|
+
|
|
|
+
|
|
|
+@router.get("/registration")
|
|
|
+def registration(fieldCode: str, period: str) -> Dict[str, Any]:
|
|
|
+ period_dir = _period_dir(fieldCode, period)
|
|
|
+ doc = _read_json(period_dir / "registration.json")
|
|
|
+ if not isinstance(doc, dict):
|
|
|
+ raise HTTPException(status_code=404, detail="暂无 registration.json")
|
|
|
+ return {"code": 200, "data": doc}
|
|
|
+
|
|
|
+
|
|
|
+@router.get("/report")
|
|
|
+def report(fieldCode: str, period: str, edition: str = "internal"):
|
|
|
+ """下载内部版/对外版 Word 报告。"""
|
|
|
+ if edition not in ("internal", "external"):
|
|
|
+ raise HTTPException(status_code=400, detail="edition 只支持 internal/external")
|
|
|
+ period_dir = _period_dir(fieldCode, period)
|
|
|
+ p = period_dir / "report" / f"{edition}.docx"
|
|
|
+ if not p.is_file():
|
|
|
+ raise HTTPException(status_code=404, detail="报告文件不存在")
|
|
|
+ return FileResponse(
|
|
|
+ str(p),
|
|
|
+ media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
|
+ filename=f"{fieldCode}_{period}_{edition}.docx",
|
|
|
+ )
|