feat(rohs-check): 新增 RoHS 检核工具进度查询功能及相关接口

This commit is contained in:
hugo committed 2026-06-11 10:05:29 +08:00
1 parent fee33f69d9
commit a18a07ef1a
19 files changed
+654 -58

No files matched your search

+45 -13
View File
@@ -13,9 +13,9 @@ from flask import Blueprint, current_app, jsonify, request, send_file
from sqlalchemy import text
from app import db
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError
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_tool_api_base
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
@@ -24,12 +24,13 @@ rohs_check_bp = Blueprint("rohs_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
_RUN_START_LOCK = threading.Lock()
_ROHS_GLOBAL_LOCK_KEY = 8700000000
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
def _tool_token_secret() -> str:
return str(
current_app.config.get("ROHS_TOOL_API_KEY")
current_app.config.get("ROHS_TOOLS_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or current_app.config.get("SECRET_KEY")
or "default-secret"
@@ -51,10 +52,14 @@ def _decode_download_token(token: str | None) -> dict | None:
def _require_tool_auth() -> None:
configured = str(current_app.config.get("ROHS_TOOL_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or "").strip()
configured = str(
current_app.config.get("ROHS_TOOLS_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"ROHS_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
"ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
@@ -105,7 +110,7 @@ def _handle_tool_app_error(exc: AppError):
def _public_base_url() -> str:
return resolve_hxops_tool_api_base()
return resolve_HXOPS_TOOLS_API_BASE()
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
@@ -120,12 +125,12 @@ def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def _acquire_task_start_lock(task_id: int) -> None:
"""Serialize same-task start checks across processes when PostgreSQL is used."""
def _acquire_rohs_start_lock() -> None:
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
bind = db.session.get_bind()
if bind.dialect.name != "postgresql":
return
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": 8700000000 + int(task_id)})
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
def _build_excel_download_url(run: ScheduleRun) -> str:
@@ -184,7 +189,13 @@ def _serialize_tool_run(run: ScheduleRun) -> dict:
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
data = data or {}
raw_task_id = task_id if task_id is not None else data.get("task_id")
task = db.session.get(ScheduleTask, int(raw_task_id)) if raw_task_id not in (None, "", 0, "0") else None
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
raise ValidationError("task_id_required")
try:
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
except (TypeError, ValueError):
raise ValidationError("task_id_invalid")
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
if not task:
task_no = str(data.get("task_no") or "").strip()
if task_no:
@@ -227,8 +238,14 @@ def run_rohs_check():
task = _resolve_check_task(data)
with _RUN_START_LOCK:
_acquire_task_start_lock(task.id)
existing = ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running").first()
_acquire_rohs_start_lock()
existing = (
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
.filter(ScheduleRun.status == "running")
.order_by(ScheduleRun.id.desc())
.all()
)
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
if existing:
db.session.commit()
return jsonify({
@@ -286,6 +303,21 @@ def get_rohs_run(run_id: int):
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@rohs_check_bp.route("/tools/runs", methods=["GET"])
def list_rohs_runs():
raw_task_id = request.args.get("task_id", type=int)
raw_limit = request.args.get("limit", default=20, type=int)
limit = max(1, min(int(raw_limit or 20), 100))
if raw_task_id is not None:
task = _resolve_check_task(task_id=raw_task_id)
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
else:
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
runs = [_serialize_tool_run(row) for row in rows if _is_rohs_check_task(row.task)]
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
@rohs_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
def download_rohs_run_excel(run_id: int):
token_payload = _decode_download_token(request.args.get("token"))
@@ -317,4 +349,4 @@ def get_latest_rohs_run(task_id: int):
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
def rohs_openapi_spec():
return jsonify(build_rohs_openapi_spec(resolve_hxops_tool_api_base()))
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
+96
View File
@@ -0,0 +1,96 @@
from __future__ import annotations
from flask import Blueprint, jsonify
from app.auth_jwt import get_current_user
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.query_service import get_run, serialize_run
workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__)
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
def _require_user():
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
total = int(payload.get("total_count") or 0)
success = int(payload.get("success_count") or 0)
failed = int(payload.get("failed_count") or 0)
skipped = int(payload.get("skipped_count") or 0)
processed = success + failed + skipped
percent = int(round((processed / total) * 100)) if total > 0 else 0
percent = max(0, min(percent, 100))
return {
"run_id": payload["id"],
"run_no": payload["run_no"],
"task_id": payload["schedule_task_id"],
"title": payload.get("schedule_name") or "RoHS 文件检核",
"status": payload["status"],
"total_count": total,
"processed_count": processed,
"success_count": success,
"failed_count": failed,
"skipped_count": skipped,
"progress_percent": percent,
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
"duration_ms": payload.get("duration_ms"),
"error_message": payload.get("error_message"),
"excel": {
"file_name": payload.get("excel_file_name"),
"file_size": payload.get("excel_file_size"),
"download_url": f"/api/workspace/schedule-runs/{run.id}/excel" if payload.get("excel_file_name") else None,
},
"knowledge_base": {
"sync_status": payload.get("kb_sync_status"),
"group_id": payload.get("kb_group_id"),
"document_id": payload.get("kb_document_id"),
"document_version_id": payload.get("kb_document_version_id"),
"sync_job_id": payload.get("kb_sync_job_id"),
"error_message": payload.get("kb_sync_error"),
},
}
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
def workspace_rohs_active_run():
_require_user()
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)
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>", methods=["GET"])
def workspace_rohs_run_detail(run_id: int):
_require_user()
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
if not _is_rohs_check_task(run.task):
raise ForbiddenError("Forbidden")
return jsonify({"ok": True, "run": _serialize_progress_run(run)})