feat(SimulationAPI): add function to retrieve latest report ID for a given simulation

- Implemented `_get_report_id_for_simulation` to find the most recent report ID associated with a simulation ID by scanning the reports directory.
- Updated `get_simulation_history` to include the retrieved report ID in the response, enhancing the simulation data returned to the client.
This commit is contained in:
666ghj 2026-01-09 16:04:35 +08:00
parent b4fe7f2f03
commit e25d2e38f4

View file

@ -809,6 +809,65 @@ def list_simulations():
}), 500
def _get_report_id_for_simulation(simulation_id: str) -> str:
"""
获取 simulation 对应的最新 report_id
遍历 reports 目录找出 simulation_id 匹配的 report
如果有多个则返回最新的 created_at 排序
Args:
simulation_id: 模拟ID
Returns:
report_id None
"""
import json
from datetime import datetime
# reports 目录路径backend/uploads/reports
# __file__ 是 app/api/simulation.py需要向上两级到 backend/
reports_dir = os.path.join(os.path.dirname(__file__), '../../uploads/reports')
if not os.path.exists(reports_dir):
return None
matching_reports = []
try:
for report_folder in os.listdir(reports_dir):
report_path = os.path.join(reports_dir, report_folder)
if not os.path.isdir(report_path):
continue
meta_file = os.path.join(report_path, "meta.json")
if not os.path.exists(meta_file):
continue
try:
with open(meta_file, 'r', encoding='utf-8') as f:
meta = json.load(f)
if meta.get("simulation_id") == simulation_id:
matching_reports.append({
"report_id": meta.get("report_id"),
"created_at": meta.get("created_at", ""),
"status": meta.get("status", "")
})
except Exception:
continue
if not matching_reports:
return None
# 按创建时间倒序排序,返回最新的
matching_reports.sort(key=lambda x: x.get("created_at", ""), reverse=True)
return matching_reports[0].get("report_id")
except Exception as e:
logger.warning(f"查找 simulation {simulation_id} 的 report 失败: {e}")
return None
@simulation_bp.route('/history', methods=['GET'])
def get_simulation_history():
"""
@ -836,6 +895,7 @@ def get_simulation_history():
"updated_at": "2024-12-10",
"total_rounds": 120,
"current_round": 120,
"report_id": "report_xxxx",
"version": "v1.0.2"
},
...
@ -892,6 +952,9 @@ def get_simulation_history():
else:
sim_dict["files"] = []
# 获取关联的 report_id查找该 simulation 最新的 report
sim_dict["report_id"] = _get_report_id_for_simulation(sim.simulation_id)
# 添加版本号
sim_dict["version"] = "v1.0.2"