From e25d2e38f44974c6724872cd55fed2a2a6527859 Mon Sep 17 00:00:00 2001 From: 666ghj <670939375@qq.com> Date: Fri, 9 Jan 2026 16:04:35 +0800 Subject: [PATCH] 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. --- backend/app/api/simulation.py | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/backend/app/api/simulation.py b/backend/app/api/simulation.py index 298b8dc..3a0f681 100644 --- a/backend/app/api/simulation.py +++ b/backend/app/api/simulation.py @@ -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"