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

+2 -2
View File
@@ -55,9 +55,9 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOL_API_BASE)
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
HXOPS_TOOL_API_BASE=http://192.168.100.192:8890
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
+1 -1
View File
@@ -59,4 +59,4 @@ MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
HXOPS_TOOL_API_BASE=http://192.168.100.230:8891
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8891
+1 -1
View File
@@ -75,7 +75,7 @@ WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,perm
INTEGRATION_API_MODE=local
DIFY_API_BASE=https://api.dify.ai/v1
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖)
HXOPS_TOOL_API_BASE=
HXOPS_TOOLS_API_BASE=
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
+3 -3
View File
@@ -59,11 +59,11 @@ MINIO_SECURE=false
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOL_API_BASE)
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
HXOPS_TOOL_API_BASE=http://192.168.100.192:8890
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
+2
View File
@@ -56,6 +56,7 @@ def create_app(config_name='default'):
from app.api.schedule_admin import schedule_admin_bp
from app.api.workspace_schedule import workspace_schedule_bp
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
from app.api.workspace_rohs_check import workspace_rohs_check_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.shipping_notice_tools import shipping_notice_bp
from app.api.rohs_check_tools import rohs_check_bp
@@ -76,6 +77,7 @@ def create_app(config_name='default'):
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_rohs_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(rohs_check_bp, url_prefix='/api/rohs-check')
+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)})
+2 -2
View File
@@ -108,13 +108,13 @@ class Config:
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 共用;无尾斜杠)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOL_API_BASE')
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RoHS 检核 Chatflow Tool API
ROHS_TOOL_API_KEY = os.getenv('ROHS_TOOL_API_KEY')
ROHS_TOOLS_API_KEY = os.getenv('ROHS_TOOLS_API_KEY')
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
+2 -2
View File
@@ -7,14 +7,14 @@ from __future__ import annotations
from flask import current_app, has_request_context, request
def resolve_hxops_tool_api_base(*, config: dict | None = None, request_host: str | None = None) -> str:
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
"""返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
cfg = config
if cfg is None and current_app:
cfg = current_app.config
cfg = cfg or {}
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOL_API_BASE", "PUBLIC_BASE_URL"):
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
configured = str(cfg.get(key) or "").strip().rstrip("/")
if configured:
return configured
@@ -2,7 +2,7 @@ from __future__ import annotations
from flask import current_app
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.agent_resolver import is_rohs_check_chat_agent
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致(见 docs/rohs_chatflow_guide.md §3.1)
@@ -12,9 +12,9 @@ HXOPS_TOOL_API_TOKEN_INPUT = "hxops_tool_api_token"
def build_dify_chat_inputs() -> dict[str, str]:
"""Build Dify chat API inputs for RoHS Chatflow HTTP nodes."""
base = resolve_hxops_tool_api_base()
base = resolve_HXOPS_TOOLS_API_BASE()
key = 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 ""
).strip()
@@ -7,7 +7,7 @@
},
"servers": [
{
"url": "http://192.168.100.192:8891",
"url": "http://192.168.100.192:8890",
"description": "部署时设为 HXOPS_TOOLS_API_BASE;GET /tools/openapi.json 会按服务端配置自动覆盖"
}
],
@@ -58,7 +58,7 @@
}
},
"409": {
"description": "检核进行中,同任务不可重复启动",
"description": "RoHS 检核进行中,全局不可重复启动",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/CheckRunningResponse" }
@@ -71,6 +71,41 @@
}
}
},
"/api/rohs-check/tools/runs": {
"get": {
"operationId": "list_rohs_runs",
"summary": "查询 RoHS 检核批次列表",
"tags": ["RoHS Check"],
"parameters": [
{
"name": "task_id",
"in": "query",
"required": false,
"schema": { "type": "integer", "example": 12 },
"description": "可选;指定检核任务 ID 时只返回该任务批次"
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 },
"description": "返回条数,最大 100"
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ListRunsResponse" }
}
}
},
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/TaskNotFound" }
}
}
},
"/api/rohs-check/tools/runs/{run_id}": {
"get": {
"operationId": "get_rohs_run",
@@ -165,7 +200,7 @@
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "ROHS_TOOL_API_KEY 或 INTEGRATION_API_KEY"
"description": "ROHS_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
},
"IntegrationKey": {
"type": "apiKey",
@@ -258,7 +293,8 @@
"conversation_id": { "type": "string", "nullable": true },
"user_message": { "type": "string", "nullable": true }
},
"description": "task_id 与 task_no 至少提供一个;优先使用 task_id"
"required": ["task_id"],
"description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程"
},
"RunCheckSuccessResponse": {
"type": "object",
@@ -287,6 +323,18 @@
"run": { "$ref": "#/components/schemas/RunDetail" }
}
},
"ListRunsResponse": {
"type": "object",
"required": ["ok", "runs", "count"],
"properties": {
"ok": { "type": "boolean", "example": true },
"count": { "type": "integer", "example": 2 },
"runs": {
"type": "array",
"items": { "$ref": "#/components/schemas/RunDetail" }
}
}
},
"ErrorResponse": {
"type": "object",
"required": ["ok", "error_code", "message"],
@@ -315,14 +363,14 @@
}
},
"MissingAuth": {
"description": "服务端未配置 ROHS_TOOL_API_KEY / INTEGRATION_API_KEY",
"description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
"example": {
"ok": false,
"error_code": "missing_auth",
"message": "ROHS_TOOL_API_KEY or INTEGRATION_API_KEY is not configured"
"message": "ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
}
}
}
+29 -6
View File
@@ -154,12 +154,38 @@ def _run_check_job_loop(
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
step_logs: list[dict[str, Any]] = []
details: list[dict[str, Any]] = []
success_count = 0
failed_count = 0
skipped_count = 0
all_errors: list[str] = []
def _save_progress(total: int | None = None) -> None:
if run_id is None:
return
try:
from app import db
from app.models import ScheduleRun
progress_run = db.session.get(ScheduleRun, run_id)
if not progress_run or progress_run.status != "running":
return
if total is not None:
progress_run.total_count = max(0, int(total))
progress_run.success_count = success_count
progress_run.failed_count = failed_count
progress_run.skipped_count = skipped_count
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)
t0 = _ts()
try:
rows = fetch_fn(conn_str)
if max_rows > 0:
rows = rows[:max_rows]
_save_progress(total=len(rows))
step_logs.append(_make_step(
"fetch_srm",
"success",
@@ -175,12 +201,6 @@ def _run_check_job_loop(
))
raise
details: list[dict[str, Any]] = []
success_count = 0
failed_count = 0
skipped_count = 0
all_errors: list[str] = []
for row in rows:
if run_id is not None and is_run_cancelled(run_id):
item = dict(row)
@@ -192,6 +212,7 @@ def _run_check_job_loop(
})
skipped_count += 1
details.append(item)
_save_progress()
continue
item = dict(row)
@@ -215,6 +236,7 @@ def _run_check_job_loop(
failed_count += 1
all_errors.append(pre_result.get("writeback_err", ""))
details.append(item)
_save_progress()
continue
record_text, attachment_url = build_record_fn(conn_str, item, row_id_value)
@@ -339,6 +361,7 @@ def _run_check_job_loop(
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
details.append(item)
_save_progress()
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
@@ -6,7 +6,7 @@ from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
# Dify Chatflow input variable names — must match canvas Start / 输入变量配置.
HXOPS_TOOL_API_BASE_INPUT = "hxops_tool_api_base"
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
@@ -20,7 +20,7 @@ def build_dify_chat_inputs() -> dict[str, str]:
key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
inputs: dict[str, str] = {}
if base:
inputs[HXOPS_TOOL_API_BASE_INPUT] = base
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
return inputs
@@ -1,8 +1,8 @@
from __future__ import annotations
from app.services.hxops_tool_api import resolve_hxops_tool_api_base
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str:
"""Resolve hxops Tool API root URL (no trailing slash)."""
return resolve_hxops_tool_api_base(config=config, request_host=request_host)
return resolve_HXOPS_TOOLS_API_BASE(config=config, request_host=request_host)
+123 -3
View File
@@ -177,6 +177,126 @@ def test_rohs_tool_running_conflict(app, client):
assert data['error_code'] == 'check_running'
def test_rohs_tool_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/rohs-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
def test_rohs_tool_rejects_invalid_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/rohs-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': 'abc'},
)
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_invalid'
def test_rohs_tool_running_conflict_is_global(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
running_task = _mk_check_task(admin.id)
second_task = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核备用',
schedule_type='platform_app',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/2',
enabled=True,
)
db.session.add(second_task)
db.session.flush()
running = ScheduleRun(run_no='RUN-ROHS-RUNNING', schedule_task_id=running_task.id, status='running', trigger_type='manual')
db.session.add(running)
db.session.commit()
second_task_id = second_task.id
running_id = running.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': second_task_id},
)
assert res.status_code == 409
data = res.get_json()
assert data['error_code'] == 'check_running'
assert data['run']['run_id'] == running_id
def test_rohs_tool_lists_all_rohs_runs(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
rohs_task = _mk_check_task(admin.id)
other_task = _mk_non_rohs_task(admin.id)
db.session.add_all([
ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=rohs_task.id, status='success', trigger_type='manual', total_count=3, success_count=3),
ScheduleRun(run_no='RUN-ROHS-002', schedule_task_id=rohs_task.id, status='partial_failed', trigger_type='manual', total_count=4, success_count=3, failed_count=1),
ScheduleRun(run_no='RUN-OTHER-001', schedule_task_id=other_task.id, status='success', trigger_type='manual', total_count=9, success_count=9),
])
db.session.commit()
res = client.get('/api/rohs-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['count'] == 2
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002'}
def test_workspace_rohs_active_run_returns_progress(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-ACTIVE',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=10,
success_count=3,
failed_count=1,
skipped_count=1,
)
db.session.add(run)
db.session.commit()
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['run']['run_no'] == 'RUN-ROHS-ACTIVE'
assert data['run']['processed_count'] == 5
assert data['run']['progress_percent'] == 50
def test_workspace_rohs_active_run_returns_null_when_idle(app, client):
with app.app_context():
_mk_admin()
db.session.commit()
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_rohs_tool_excel_download_uses_signed_token(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -267,7 +387,7 @@ def test_rohs_dify_chat_inputs(app):
with app.app_context():
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
app.config['ROHS_TOOL_API_KEY'] = 'rohs-secret'
app.config['ROHS_TOOLS_API_KEY'] = 'rohs-secret'
inputs = build_dify_chat_inputs()
assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com'
assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret'
@@ -278,8 +398,8 @@ def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app):
with app.app_context():
app.config.pop('HXOPS_TOOLS_API_BASE', None)
app.config['HXOPS_TOOL_API_BASE'] = 'https://legacy-tool.example.com'
app.config.pop('ROHS_TOOL_API_KEY', None)
app.config['HXOPS_TOOLS_API_BASE'] = 'https://legacy-tool.example.com'
app.config.pop('ROHS_TOOLS_API_KEY', None)
app.config['INTEGRATION_API_KEY'] = 'integration-secret'
inputs = build_dify_chat_inputs()
assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com'
+37
View File
@@ -0,0 +1,37 @@
import { requestJson } from './client';
import { getAuthHeaders } from '../utils/auth';
export interface ToolRunProgress {
run_id: number;
run_no: string;
task_id?: number;
title: string;
status: string;
total_count: number;
processed_count: number;
success_count: number;
failed_count: number;
skipped_count: number;
progress_percent: number;
started_at?: string | null;
finished_at?: string | null;
duration_ms?: number | null;
error_message?: string | null;
excel?: {
file_name?: string | null;
file_size?: number | null;
download_url?: string | null;
};
knowledge_base?: {
sync_status?: string | null;
error_message?: string | null;
};
}
export interface ToolRunProgressResponse {
ok: boolean;
run: ToolRunProgress | null;
}
export const getToolRunProgress = (url: string) =>
requestJson<ToolRunProgressResponse>(url, { headers: getAuthHeaders() });
@@ -0,0 +1,105 @@
<script setup lang="ts">
import { AlertCircle, CheckCircle2, Clock3, Download, Loader2 } from 'lucide-vue-next';
import type { ToolRunProgress } from '@/api/toolRunProgress';
const props = defineProps<{
run: ToolRunProgress | null;
loading?: boolean;
error?: string;
fallbackTitle?: string;
}>();
const statusLabel = (status?: string) => {
const map: Record<string, string> = {
running: '执行中',
success: '已完成',
partial_failed: '部分失败',
failed: '失败',
cancelled: '已取消',
canceled: '已取消',
};
return map[String(status || '')] || status || '等待中';
};
const formatTime = (value?: string | null) => {
if (!value) return '-';
return String(value).replace('T', ' ').slice(0, 19);
};
const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent || 0), 100));
</script>
<template>
<section
v-if="run || loading || error"
class="mx-auto mb-4 w-full max-w-4xl overflow-hidden rounded-2xl border border-sky-100 bg-gradient-to-br from-sky-50 via-white to-emerald-50 shadow-sm"
>
<div class="flex items-start justify-between gap-3 border-b border-sky-100/80 px-4 py-3">
<div>
<div class="flex items-center gap-2 text-sm font-semibold text-slate-800">
<Loader2 v-if="run?.status === 'running'" class="h-4 w-4 animate-spin text-sky-600" />
<CheckCircle2 v-else-if="run?.status === 'success'" class="h-4 w-4 text-emerald-600" />
<AlertCircle v-else-if="run?.status === 'failed' || run?.status === 'partial_failed'" class="h-4 w-4 text-amber-600" />
<Clock3 v-else class="h-4 w-4 text-sky-600" />
{{ run?.title || fallbackTitle || '任务进度' }}
</div>
<p class="mt-1 text-xs text-slate-500">
<template v-if="run">批次:{{ run.run_no }} · 状态:{{ statusLabel(run.status) }}</template>
<template v-else-if="loading">正在查询任务进度...</template>
<template v-else>{{ error }}</template>
</p>
</div>
<a
v-if="run?.excel?.download_url"
:href="run.excel.download_url"
target="_blank"
class="inline-flex items-center gap-1 rounded-full bg-sky-600 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-sky-700"
>
<Download class="h-3.5 w-3.5" />
下载 Excel
</a>
</div>
<div v-if="run" class="space-y-3 px-4 py-4">
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
:style="{ width: `${percent()}%` }"
></div>
</div>
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
<span>进度 {{ percent() }}%</span>
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
</div>
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
<div class="rounded-xl bg-white/80 px-3 py-2">
<div class="text-xs text-slate-500">总数</div>
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div>
</div>
<div class="rounded-xl bg-white/80 px-3 py-2">
<div class="text-xs text-slate-500">已处理</div>
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div>
</div>
<div class="rounded-xl bg-white/80 px-3 py-2">
<div class="text-xs text-slate-500">成功</div>
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div>
</div>
<div class="rounded-xl bg-white/80 px-3 py-2">
<div class="text-xs text-slate-500">失败</div>
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div>
</div>
<div class="rounded-xl bg-white/80 px-3 py-2">
<div class="text-xs text-slate-500">跳过</div>
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div>
</div>
</div>
<div v-if="run.knowledge_base?.sync_status || run.error_message" class="rounded-xl bg-white/70 px-3 py-2 text-xs text-slate-600">
<div v-if="run.knowledge_base?.sync_status">知识库同步:{{ run.knowledge_base.sync_status }}</div>
<div v-if="run.knowledge_base?.error_message" class="text-amber-700">同步错误:{{ run.knowledge_base.error_message }}</div>
<div v-if="run.error_message" class="text-rose-700">错误信息:{{ run.error_message }}</div>
</div>
</div>
</section>
</template>
@@ -0,0 +1,97 @@
import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue';
import { getToolRunProgress, type ToolRunProgress } from '@/api/toolRunProgress';
export interface ToolRunProgressConfig {
type?: string;
title?: string;
poll_interval_seconds?: number;
active_url?: string;
detail_url_template?: string;
lock_input_when_running?: boolean;
lock_message?: string;
}
const TERMINAL_STATUSES = new Set(['success', 'partial_failed', 'failed', 'cancelled', 'canceled']);
const clampPollMs = (seconds: unknown) => {
const raw = Number(seconds);
const safe = Number.isFinite(raw) ? raw : 2;
return Math.max(1, Math.min(safe, 30)) * 1000;
};
export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>) {
const run = ref<ToolRunProgress | null>(null);
const loading = ref(false);
const error = ref('');
let timer: number | undefined;
const enabled = computed(() => !!configRef.value?.active_url);
const isRunning = computed(() => run.value?.status === 'running');
const shouldLockInput = computed(() => Boolean(configRef.value?.lock_input_when_running) && isRunning.value);
const lockMessage = computed(() => configRef.value?.lock_message || '当前任务执行中,请等待完成');
const clearTimer = () => {
if (timer !== undefined) {
window.clearTimeout(timer);
timer = undefined;
}
};
const scheduleNext = () => {
clearTimer();
if (!enabled.value) return;
const interval = clampPollMs(configRef.value?.poll_interval_seconds);
timer = window.setTimeout(() => {
void refresh();
}, interval);
};
const refresh = async () => {
const cfg = configRef.value;
if (!cfg?.active_url) {
run.value = null;
error.value = '';
clearTimer();
return;
}
loading.value = true;
try {
const payload = await getToolRunProgress(cfg.active_url);
run.value = payload.run;
error.value = '';
} catch (e: any) {
error.value = e?.message || '任务进度查询失败';
} finally {
loading.value = false;
}
if (!run.value || run.value.status === 'running' || !TERMINAL_STATUSES.has(run.value.status)) {
scheduleNext();
} else {
clearTimer();
}
};
watch(
() => JSON.stringify(configRef.value || {}),
() => {
run.value = null;
error.value = '';
clearTimer();
if (enabled.value) void refresh();
},
{ immediate: true },
);
onBeforeUnmount(clearTimer);
return {
run,
loading,
error,
isRunning,
shouldLockInput,
lockMessage,
refresh,
};
}
+48 -12
View File
@@ -12,9 +12,11 @@ import LocaleToggleButton from '@/components/LocaleToggleButton.vue';
import FilePreviewModal from '@/components/FilePreviewModal.vue';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '@/components/GeneralFeedbackDialog.vue';
import ToolRunProgressCard from '@/features/chat/components/ToolRunProgressCard.vue';
import ChatShell from '@/layouts/ChatShell.vue';
import { useChat } from '@/features/chat/composables/useChat';
import { useChatSourceFiles } from '@/features/chat/composables/useChatSourceFiles';
import { useToolRunProgress, type ToolRunProgressConfig } from '@/features/chat/composables/useToolRunProgress';
import { config } from '@/config';
import {
listChatSessions,
@@ -439,7 +441,7 @@ const handleVoiceFeatureClick = () => {
msg.info(t('chat.devComingSoon'));
return;
}
if (isThinking.value || isVoiceTranscribing.value) return;
if (isThinking.value || isVoiceTranscribing.value || toolRunShouldLockInput.value) return;
const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) {
msg.warning(t(unavailable));
@@ -458,6 +460,22 @@ const showGeneralFeedbackDialog = ref(false);
const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
const canUseLeaveFeature = computed(() => LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()));
const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
const extra = currentAgent.value?.extra_config || {};
const capabilities = Array.isArray(extra.capabilities) ? extra.capabilities.map((item: unknown) => String(item)) : [];
if (!capabilities.includes('tool_run_progress')) return null;
const raw = extra.tool_run_progress;
if (!raw || typeof raw !== 'object') return null;
return raw as ToolRunProgressConfig;
});
const {
run: toolRunProgress,
loading: toolRunProgressLoading,
error: toolRunProgressError,
shouldLockInput: toolRunShouldLockInput,
lockMessage: toolRunLockMessage,
} = useToolRunProgress(toolRunProgressConfig);
type AgentSuggestedQuestionItem = {
question: string;
group: string;
@@ -674,7 +692,7 @@ const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false);
const canSendMessage = computed(() => {
if (isThinking.value || isUploadingAttachments.value) return false;
if (isThinking.value || isUploadingAttachments.value || toolRunShouldLockInput.value) return false;
if (input.value.trim()) return true;
if (isShippingNoticeAgent.value && attachments.value.length > 0) return true;
return false;
@@ -687,7 +705,7 @@ const closeAttachmentMenu = () => {
};
const toggleAttachmentMenu = async () => {
if (isThinking.value || isUploadingAttachments.value) return;
if (isThinking.value || isUploadingAttachments.value || toolRunShouldLockInput.value) return;
showAttachmentMenu.value = !showAttachmentMenu.value;
if (!showAttachmentMenu.value) {
showAttachmentUrlPanel.value = false;
@@ -696,13 +714,13 @@ const toggleAttachmentMenu = async () => {
};
const selectAttachmentLocal = () => {
if (!attachmentPolicy.value.canLocal) return;
if (!attachmentPolicy.value.canLocal || toolRunShouldLockInput.value) return;
closeAttachmentMenu();
filePickerRef.value?.click();
};
const selectAttachmentUrl = async () => {
if (!attachmentPolicy.value.canRemote) return;
if (!attachmentPolicy.value.canRemote || toolRunShouldLockInput.value) return;
showAttachmentMenu.value = true;
showAttachmentUrlPanel.value = true;
await nextTick();
@@ -3107,6 +3125,10 @@ const reuploadShippingInventoryFromMappingForm = (msgObj: any) => {
*/
const handleSend = async (textOrEvent?: string | Event) => {
if (toolRunShouldLockInput.value) {
msg.info(toolRunLockMessage.value);
return;
}
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
const trimmed = content.trim();
if ((shippingAutoFlowRequested.value || !trimmed) && isShippingNoticeAgent.value && attachments.value.length > 0 && !isThinking.value && !isUploadingAttachments.value) {
@@ -4063,6 +4085,12 @@ const showChatRating = ref(false);
<div
:class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'"
>
<ToolRunProgressCard
:run="toolRunProgress"
:loading="toolRunProgressLoading"
:error="toolRunProgressError"
:fallback-title="toolRunProgressConfig?.title"
/>
<div v-if="messages.length === 0" class="flex h-full min-h-0 w-full flex-col items-center px-4 pt-2 pb-2 md:pb-3">
<template v-if="suggestedQuestionsStyle === 'styled' && styledSuggestedQuestionSections.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
@@ -4640,10 +4668,10 @@ const showChatRating = ref(false);
v-model="input"
@keydown.enter.prevent="handleSend"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
:placeholder="toolRunShouldLockInput ? toolRunLockMessage : isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent"
style="min-height: 44px; max-height: 220px;"
:disabled="isThinking || isVoiceTranscribing"
:disabled="isThinking || isVoiceTranscribing || toolRunShouldLockInput"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
@@ -4654,6 +4682,7 @@ const showChatRating = ref(false);
type="file"
class="hidden"
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
:disabled="toolRunShouldLockInput"
@change="handleShippingInventorySelected"
/>
@@ -4663,6 +4692,7 @@ const showChatRating = ref(false);
multiple
class="hidden"
:accept="attachmentPolicy.accept || undefined"
:disabled="toolRunShouldLockInput"
@change="handleLocalFilesSelected"
/>
@@ -4694,13 +4724,19 @@ const showChatRating = ref(false);
</button>
<span>点发送开始处理</span>
</div>
<div
v-if="toolRunShouldLockInput"
class="px-3 pb-1 text-xs font-medium text-amber-700"
>
{{ toolRunLockMessage }}
</div>
<div class="mt-2 flex items-center justify-between px-2 pb-1">
<div class="flex items-center gap-3">
<button
@click="handleVoiceFeatureClick"
type="button"
:disabled="isThinking || isVoiceTranscribing"
:disabled="isThinking || isVoiceTranscribing || toolRunShouldLockInput"
:title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')"
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
:class="isVoiceRecording ? 'text-red-500 animate-pulse' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'"
@@ -4712,7 +4748,7 @@ const showChatRating = ref(false);
<button
@click="toggleAttachmentMenu"
type="button"
:disabled="isThinking || isUploadingAttachments"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput"
title="附件"
class="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
>
@@ -4745,14 +4781,14 @@ const showChatRating = ref(false);
<input
ref="attachmentUrlInputRef"
v-model="attachmentUrlInput"
:disabled="isThinking || isUploadingAttachments"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput"
placeholder="粘贴附件 URL(http/https)"
class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0"
@keydown.enter.prevent="addRemoteUrlAttachment"
/>
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput"
@click="addRemoteUrlAttachment"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="添加"
@@ -4761,7 +4797,7 @@ const showChatRating = ref(false);
</button>
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput"
@click="closeAttachmentMenu"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="取消"