feat(rohs-check): 增强 RoHS 检核工具进度展示,新增判定统计与当前步骤信息

This commit is contained in:
hugo committed 2026-06-11 11:47:07 +08:00
1 parent b82f31af8f
commit ee39270069
9 files changed
+349 -11

No files matched your search

+2
View File
@@ -13,6 +13,7 @@ from flask import Blueprint, current_app, jsonify, request, send_file
from sqlalchemy import text
from app import db
from app.api.workspace_rohs_check import serialize_rohs_judgement
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
@@ -165,6 +166,7 @@ def _serialize_tool_run(run: ScheduleRun) -> dict:
"success_count": payload["success_count"],
"failed_count": payload["failed_count"],
"skipped_count": payload["skipped_count"],
"judgement": serialize_rohs_judgement(payload),
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
"duration_ms": payload.get("duration_ms"),
+41 -2
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from flask import Blueprint, jsonify
from flask import Blueprint, jsonify, request
from app.auth_jwt import get_current_user
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
@@ -31,6 +31,35 @@ def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def serialize_rohs_judgement(payload: dict) -> dict:
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {}
return {
"qualified_count": int(judgement.get("qualified_count") or 0),
"unqualified_count": int(judgement.get("unqualified_count") or 0),
"manual_count": int(judgement.get("manual_count") or 0),
"dify_error_count": int(judgement.get("dify_error_count") or 0),
"invalid_result_count": int(judgement.get("invalid_result_count") or 0),
}
def serialize_current_step(payload: dict) -> dict | None:
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
current_step = response_summary.get("current_step") if isinstance(response_summary.get("current_step"), dict) else None
if not current_step:
return None
return {
"step": str(current_step.get("step") or ""),
"label": str(current_step.get("label") or current_step.get("step") or ""),
"row_id": current_step.get("row_id"),
"started_at": current_step.get("started_at"),
"processed_count": int(current_step.get("processed_count") or 0),
"success_count": int(current_step.get("success_count") or 0),
"failed_count": int(current_step.get("failed_count") or 0),
"skipped_count": int(current_step.get("skipped_count") or 0),
}
def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
total = int(payload.get("total_count") or 0)
@@ -51,6 +80,8 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"success_count": success,
"failed_count": failed,
"skipped_count": skipped,
"judgement": serialize_rohs_judgement(payload),
"current_step": serialize_current_step(payload),
"progress_percent": percent,
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
@@ -75,13 +106,21 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
def workspace_rohs_active_run():
_require_user()
conversation_id = str(request.args.get("conversation_id") or "").strip()
rows = (
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
.filter(ScheduleRun.status == "running")
.order_by(ScheduleRun.id.desc())
.all()
)
run = next((row for row in rows if _is_rohs_check_task(row.task)), None)
run = next((
row for row in rows
if _is_rohs_check_task(row.task)
and (
not conversation_id
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
)
), None)
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
@@ -339,11 +339,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
run.failed_count = failed_count
run.skipped_count = skipped_count
run.step_logs = step_logs if step_logs else None
run.response_summary_json = {
response_summary = dict(run.response_summary_json or {})
response_summary.update({
"errors": errors[:20],
"schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path,
}
})
run.response_summary_json = response_summary
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data
run.excel_file_name = file_name
+78 -2
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Any, Callable
from flask import current_app
from flask import current_app, has_app_context
from app.services.rohs_check import RoHSCheckService
@@ -16,13 +16,31 @@ except Exception: # pragma: no cover
def _connect(conn_str: str):
if pyodbc is None:
raise RuntimeError("pyodbc is not installed")
return pyodbc.connect(conn_str, timeout=15)
return pyodbc.connect(conn_str, timeout=_sql_timeout_seconds())
def _sql_timeout_seconds() -> int:
if not has_app_context():
return 15
try:
value = int(current_app.config.get("SRM_SQLSERVER_TIMEOUT", 15) or 15)
except Exception:
value = 15
return max(1, value)
def _apply_cursor_timeout(cursor) -> None:
try:
cursor.timeout = _sql_timeout_seconds()
except Exception:
pass
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
conn = _connect(conn_str)
try:
cur = conn.cursor()
_apply_cursor_timeout(cur)
if params:
cur.execute(sql, params)
else:
@@ -38,6 +56,7 @@ def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
conn = _connect(conn_str)
try:
cur = conn.cursor()
_apply_cursor_timeout(cur)
cur.execute(sql, params)
conn.commit()
finally:
@@ -111,6 +130,16 @@ def _make_step(
return entry
def _step_label(step: str) -> str:
return {
"fetch_srm": "查询待检数据",
"pre_dify": "查询成分明细",
"call_dify": "调用 Dify 判定",
"writeback_srm": "写回 SRM",
"completed": "处理完成",
}.get(step, step)
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
if len(s) <= max_len:
return s
@@ -158,6 +187,14 @@ def _run_check_job_loop(
success_count = 0
failed_count = 0
skipped_count = 0
judgement_stats = {
"qualified_count": 0,
"unqualified_count": 0,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
current_step: dict[str, Any] | None = None
all_errors: list[str] = []
def _save_progress(total: int | None = None) -> None:
@@ -175,13 +212,33 @@ def _run_check_job_loop(
progress_run.success_count = success_count
progress_run.failed_count = failed_count
progress_run.skipped_count = skipped_count
summary = dict(progress_run.response_summary_json or {})
summary["rohs_judgement"] = dict(judgement_stats)
if current_step:
summary["current_step"] = dict(current_step)
progress_run.response_summary_json = summary
db.session.commit()
except Exception as progress_exc:
if current_app:
current_app.logger.warning("[%s] save progress failed run_id=%s error=%s", log_prefix, run_id, progress_exc)
def _set_current_step(step: str, row_id: str | None = None, total: int | None = None) -> None:
nonlocal current_step
current_step = {
"step": step,
"label": _step_label(step),
"row_id": row_id,
"started_at": _ts(),
"processed_count": success_count + failed_count + skipped_count,
"success_count": success_count,
"failed_count": failed_count,
"skipped_count": skipped_count,
}
_save_progress(total=total)
t0 = _ts()
try:
_set_current_step("fetch_srm")
rows = fetch_fn(conn_str)
if max_rows > 0:
rows = rows[:max_rows]
@@ -221,6 +278,7 @@ def _run_check_job_loop(
if pre_dify_fn:
t_pre = _ts()
try:
_set_current_step("pre_dify", row_id_value)
pre_result = pre_dify_fn(conn_str, item, row_id_value)
except Exception as pre_exc:
pre_result = {
@@ -257,6 +315,7 @@ def _run_check_job_loop(
dify_inputs["system_prompt"] = prompt
t_dify = _ts()
try:
_set_current_step("call_dify", row_id_value)
dify_res = RoHSCheckService.evaluate(
agent=agent,
run_no=run_no,
@@ -280,6 +339,19 @@ def _run_check_job_loop(
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
dify_ok = True
if dify_result == "合格":
judgement_stats["qualified_count"] += 1
elif dify_result == "不合格":
judgement_stats["unqualified_count"] += 1
else:
judgement_stats["manual_count"] += 1
if dify_error:
judgement_stats["dify_error_count"] += 1
raw_outputs = dify_res.get("raw_outputs") if isinstance(dify_res, dict) else None
if dify_result == "人工判定" and isinstance(raw_outputs, dict) and not dify_error:
raw_result = str(raw_outputs.get("dify_result") or raw_outputs.get("result") or "").strip()
if raw_result and raw_result not in {"合格", "不合格", "人工判定"}:
judgement_stats["invalid_result_count"] += 1
if current_app:
current_app.logger.info(
@@ -304,11 +376,13 @@ def _run_check_job_loop(
dify_result = "人工判定"
dify_message = "未配置 Agent ID,跳过 Dify"
dify_ok = True
judgement_stats["manual_count"] += 1
wb_sql = writeback_sql
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
t_wb = _ts()
try:
_set_current_step("writeback_srm", row_id_value)
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
"sql": _truncate_str(wb_sql, 500),
@@ -352,6 +426,7 @@ def _run_check_job_loop(
all_errors.append(str(exc))
t_wb2 = _ts()
try:
_set_current_step("writeback_srm", row_id_value)
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
item["writeback_srm"] = True
@@ -366,5 +441,6 @@ def _run_check_job_loop(
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
_set_current_step("completed")
total_count = success_count + failed_count + skipped_count
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs