feat(file-check): 新增文件检核相关 API 和工具,替换 RoHS 检核功能
This commit is contained in:
1 parent
fa0cdee8df
commit
24310b63b3
35 files changed
+3066
-659
No files matched your search
+21
-18
@@ -1084,6 +1084,7 @@ def chat_completions():
|
||||
name=getattr(agent, 'name', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
@@ -1174,31 +1175,33 @@ def chat_completions():
|
||||
else:
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.rohs_check_tools.dify_inputs import (
|
||||
build_dify_chat_inputs as build_rohs_dify_chat_inputs,
|
||||
is_rohs_check_chat_agent,
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
declares_file_check = agent_declares_file_check_progress(agent_proxy)
|
||||
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
|
||||
if is_shipping_notice_chat_agent(agent_proxy):
|
||||
dify_inputs = build_shipping_dify_chat_inputs()
|
||||
elif is_rohs_check_chat_agent(agent_proxy):
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
|
||||
elif declares_file_check or is_file_check_agent:
|
||||
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
|
||||
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
|
||||
if is_file_check_agent:
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_rohs_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
dify_inputs = build_rohs_dify_chat_inputs(
|
||||
hxops_session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
)
|
||||
register_file_check_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
@@ -1206,7 +1209,7 @@ def chat_completions():
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id if is_rohs_check_chat_agent(agent_proxy) else None,
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""
|
||||
backend/app/api/rohs_check_tools.py
|
||||
文件用途:RoHS Chatflow 显式 HTTP Tool API。
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 Chatflow 显式 HTTP Tool API。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,25 +16,24 @@ 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.api.workspace_file_check import serialize_file_judgement
|
||||
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
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
|
||||
|
||||
rohs_check_bp = Blueprint("rohs_check_tools", __name__)
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_ROHS_GLOBAL_LOCK_KEY = 8700000000
|
||||
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("ROHS_TOOLS_API_KEY")
|
||||
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or current_app.config.get("SECRET_KEY")
|
||||
or "default-secret"
|
||||
@@ -48,19 +50,19 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[rohs-tool] download token validation failed: %s", exc)
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
configured = str(
|
||||
current_app.config.get("ROHS_TOOLS_API_KEY")
|
||||
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
"FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
@@ -100,7 +102,7 @@ def _tool_error_code(exc: AppError) -> str:
|
||||
return exc.code
|
||||
|
||||
|
||||
@rohs_check_bp.errorhandler(AppError)
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
@@ -114,39 +116,28 @@ def _public_base_url() -> str:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
|
||||
|
||||
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 _acquire_rohs_start_lock() -> None:
|
||||
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "rohs_check_excel",
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/rohs-check/tools/runs/{run.id}/excel?token={token}"
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@rohs_check_bp.before_request
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
@@ -166,7 +157,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),
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
@@ -204,41 +195,37 @@ def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None)
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
if not _is_rohs_check_task(task):
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_rohs_tasks():
|
||||
rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all()
|
||||
tasks = []
|
||||
for task in rows:
|
||||
if not _is_rohs_check_task(task):
|
||||
continue
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks.append({
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
})
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_rohs_bind_payload(data: dict | None) -> dict:
|
||||
"""
|
||||
规范化启动检核 Body 中的绑定字段,兼容 Chatflow 漏传 hxops_session_id 的场景。
|
||||
|
||||
核心逻辑:若 hxops_session_id 为空但 conversation_id 实为 HXOPS session_id,则自动补齐。
|
||||
"""
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
@@ -254,25 +241,19 @@ def _normalize_rohs_bind_payload(data: dict | None) -> dict:
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_rohs_bind_payload(data: dict | None) -> dict:
|
||||
"""
|
||||
合并规范化与 turn 注册表推断,得到可用于 ChatLog 绑定的启动检核 Body。
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
核心逻辑:Dify HTTP 漏传 hxops_turn_id / hxops_session_id 时,从 HXOPS 侧登记轮次补齐。
|
||||
"""
|
||||
from app.services.rohs_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_rohs_bind_payload(data)
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
"""写入 ScheduleRun 绑定上下文,并同步 turn 注册表。"""
|
||||
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.rohs_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
@@ -280,31 +261,29 @@ def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_rohs_check():
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_rohs_bind_payload(request.get_json(silent=True) or {})
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_rohs_start_lock()
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.all()
|
||||
.first()
|
||||
)
|
||||
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
|
||||
if existing:
|
||||
_record_rohs_run_bind(existing, data)
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[rohs-tool-perf] run_rohs_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
@@ -333,7 +312,7 @@ def run_rohs_check():
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_rohs_run_bind(run, data)
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
@@ -348,7 +327,7 @@ def run_rohs_check():
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[rohs-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
@@ -356,12 +335,12 @@ def run_rohs_check():
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start()
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[rohs-tool-perf] run_rohs_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
@@ -370,16 +349,16 @@ def run_rohs_check():
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_rohs_run(run_id: int):
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_rohs_runs():
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_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))
|
||||
@@ -389,12 +368,12 @@ def list_rohs_runs():
|
||||
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)]
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
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):
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
@@ -413,8 +392,8 @@ def download_rohs_run_excel(run_id: int):
|
||||
)
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_rohs_run(task_id: int):
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
@@ -422,6 +401,6 @@ def get_latest_rohs_run(task_id: int):
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def rohs_openapi_spec():
|
||||
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -1624,11 +1624,9 @@ def get_agent_details(id):
|
||||
raise ForbiddenError('Access denied')
|
||||
extra_config = agent.extra_config or {}
|
||||
if isinstance(extra_config, dict):
|
||||
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
|
||||
from app.services.rohs_check_tools.task_resolver import enrich_tool_run_progress_extra
|
||||
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
|
||||
|
||||
if is_rohs_check_chat_agent(agent):
|
||||
extra_config = enrich_tool_run_progress_extra(extra_config)
|
||||
extra_config = enrich_agent_extra_if_file_check(agent)
|
||||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||||
|
||||
dify_parameters = None
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
|
||||
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
@@ -5,14 +12,12 @@ from io import BytesIO
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.errors import NotFoundError, UnauthorizedError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.rohs_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
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 文件检核")
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
@@ -22,21 +27,12 @@ def _require_user():
|
||||
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_rohs_judgement(payload: dict) -> dict:
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
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 {}
|
||||
judgement = response_summary.get("file_judgement")
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
"qualified_count": int(judgement.get("qualified_count") or 0),
|
||||
"unqualified_count": int(judgement.get("unqualified_count") or 0),
|
||||
@@ -76,14 +72,14 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"title": payload.get("schedule_name") or "RoHS 文件检核",
|
||||
"title": payload.get("schedule_name") or "",
|
||||
"status": payload["status"],
|
||||
"total_count": total,
|
||||
"processed_count": processed,
|
||||
"success_count": success,
|
||||
"failed_count": failed,
|
||||
"skipped_count": skipped,
|
||||
"judgement": serialize_rohs_judgement(payload),
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"current_step": serialize_current_step(payload),
|
||||
"progress_percent": percent,
|
||||
"started_at": payload.get("started_at"),
|
||||
@@ -93,7 +89,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": f"/api/workspace/rohs-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
"download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
@@ -106,8 +102,8 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
}
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/for-log", methods=["GET"])
|
||||
def workspace_rohs_run_for_log():
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
@@ -125,16 +121,16 @@ def workspace_rohs_run_for_log():
|
||||
})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/for-session", methods=["GET"])
|
||||
def workspace_rohs_run_for_session():
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
|
||||
def workspace_rohs_active_run():
|
||||
"""查询当前进行中的 RoHS 检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
@@ -146,13 +142,11 @@ def workspace_rohs_active_run():
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
# 已按 schedule_task_id 过滤;不再比对 conversation_id(HXOPS session_id ≠ Dify sys.conversation_id)
|
||||
run = next((row for row in rows if _is_rohs_check_task(row.task)), None)
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((
|
||||
row for row in rows
|
||||
if _is_rohs_check_task(row.task)
|
||||
and (
|
||||
if (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
@@ -160,25 +154,21 @@ def workspace_rohs_active_run():
|
||||
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):
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_file_check_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)})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_rohs_run_excel(run_id: int):
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_file_check_run_excel(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")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("excel_not_found")
|
||||
return send_file(
|
||||
Reference in new issue
Block a user