feat(rohs-check): 新增 RoHS 检核工具进度查询功能及相关接口
This commit is contained in:
1 parent
fee33f69d9
commit
a18a07ef1a
19 files changed
+654
-58
No files matched your search
@@ -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')
|
||||
|
||||
@@ -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()))
|
||||
@@ -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)})
|
||||
@@ -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'
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
@@ -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'
|
||||
|
||||
Reference in new issue
Block a user