feat(rohs-check): 新增 RoHS 检核工具 API 及相关功能

This commit is contained in:
hugo committed 2026-06-10 15:17:09 +08:00
1 parent 8a541211b7
commit 24551e9a9a
39 files changed
+3128 -189

No files matched your search

+12 -3
View File
@@ -1163,10 +1163,19 @@ def chat_completions():
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
dify_inputs = None
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs, is_shipping_notice_chat_agent
dify_inputs: dict[str, 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.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
is_shipping_notice_chat_agent,
)
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_dify_chat_inputs()
dify_inputs = build_shipping_dify_chat_inputs()
elif is_rohs_check_chat_agent(agent_proxy):
dify_inputs = build_rohs_dify_chat_inputs()
generator = DifyService.stream_chat(
query,
user_proxy.id,
+322
View File
@@ -0,0 +1,322 @@
"""
backend/app/api/rohs_check_tools.py
文件用途:RoHS Chatflow 显式 HTTP Tool API。
"""
from __future__ import annotations
import threading
import time
from io import BytesIO
from datetime import datetime
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, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.hxops_tool_api import resolve_hxops_tool_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__)
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
_RUN_START_LOCK = threading.Lock()
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
def _tool_token_secret() -> str:
return str(
current_app.config.get("ROHS_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or current_app.config.get("SECRET_KEY")
or "default-secret"
).strip()
def _decode_download_token(token: str | None) -> dict | None:
normalized = str(token or "").strip()
if not normalized:
return None
try:
import jwt
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)
return 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()
if not configured:
raise ServiceUnavailableError(
"ROHS_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
message = str(exc.message or "").strip()
if message in {
"missing_auth",
"invalid_auth",
"task_not_found",
"task_disabled",
"run_not_found",
"excel_not_ready",
"kb_sync_failed",
}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
if exc.code == "RESOURCE.NOT_FOUND":
return message or "run_not_found"
if exc.code == "VALIDATION.INVALID_PARAM":
return message or "invalid_request"
if exc.code == "RESOURCE.CONFLICT":
return message or "conflict"
return exc.code
@rohs_check_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
status = exc.http_status
return jsonify({
"ok": False,
"error_code": _tool_error_code(exc),
"message": exc.message,
}), status
def _public_base_url() -> str:
return resolve_hxops_tool_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_task_start_lock(task_id: int) -> None:
"""Serialize same-task 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)})
def _build_excel_download_url(run: ScheduleRun) -> str:
import jwt
payload = {
"scope": "rohs_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}"
@rohs_check_bp.before_request
def _verify_tool_access():
if request.path.endswith("/openapi.json"):
return None
_require_tool_auth()
return None
def _serialize_tool_run(run: ScheduleRun) -> dict:
payload = serialize_run(run)
return {
"run_id": payload["id"],
"run_no": payload["run_no"],
"task_id": payload["schedule_task_id"],
"task_name": payload.get("schedule_name"),
"status": payload["status"],
"total_count": payload["total_count"],
"success_count": payload["success_count"],
"failed_count": payload["failed_count"],
"skipped_count": payload["skipped_count"],
"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": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
},
"knowledge_base": {
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
"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"),
},
}
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 not task:
task_no = str(data.get("task_no") or "").strip()
if task_no:
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,
})
return jsonify({"ok": True, "tasks": tasks})
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_rohs_check():
data = request.get_json(silent=True) or {}
task = _resolve_check_task(data)
if not task.enabled:
raise ValidationError("task_disabled")
with _RUN_START_LOCK:
_acquire_task_start_lock(task.id)
existing = ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running").first()
if existing:
db.session.commit()
return jsonify({
"ok": False,
"error_code": "check_running",
"message": "该检核任务正在执行中,请稍后查询结果",
"run": _serialize_tool_run(existing),
}), 409
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type="dify_chatflow",
started_at=datetime.utcnow(),
status="running",
api_request_json={
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
"user_message": data.get("user_message"),
},
)
db.session.add(run)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
task_id = task.id
def _background():
with app.app_context():
t = db.session.get(ScheduleTask, task_id)
r = db.session.get(ScheduleRun, run_id)
if not t or not r:
return
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)
r = db.session.get(ScheduleRun, run_id)
if r and r.status == "running":
r.status = "failed"
r.error_message = str(exc)
r.finished_at = datetime.utcnow()
db.session.commit()
threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start()
db.session.refresh(run)
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):
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/<int:run_id>/excel", methods=["GET"])
def download_rohs_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:
raise UnauthorizedError("Unauthorized")
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
if not run.excel_file_data:
raise ConflictError("excel_not_ready")
filename = run.excel_file_name or f"{run.run_no}.xlsx"
return send_file(
BytesIO(run.excel_file_data),
as_attachment=True,
download_name=filename,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
def get_latest_rohs_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:
raise NotFoundError("run_not_found")
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_tool_api_base()))
+36 -7
View File
@@ -106,6 +106,11 @@ def test_schedule_run(task_id: int):
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
limit = min(int(data.get('limit') or 3), 10)
raw_kb_sync = data.get('kb_sync_enabled', False)
if isinstance(raw_kb_sync, str):
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
else:
test_kb_sync_enabled = bool(raw_kb_sync)
base = cfg.base_fetch_sql or cfg.fetch_sql
if cfg.base_fetch_sql:
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
@@ -190,7 +195,8 @@ def test_schedule_run(task_id: int):
detail_alias_order = cfg.detail_alias_order or []
try:
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
except Exception:
except Exception as excel_exc:
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
file_data, file_name, file_size = (None, None, 0)
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
@@ -204,12 +210,28 @@ def test_schedule_run(task_id: int):
run.excel_file_data = file_data
run.excel_file_name = file_name
run.excel_file_size = file_size or 0
db.session.commit()
if test_kb_sync_enabled:
try:
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
db.session.refresh(task)
db.session.refresh(run)
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
db.session.refresh(run)
except Exception as kb_exc:
db.session.rollback()
db.session.refresh(run)
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
run.kb_sync_status = 'failed'
run.kb_group_id = getattr(task, 'kb_group_id', None)
run.kb_sync_error = str(kb_exc)
db.session.commit()
try:
if task.notify_enabled:
_notify_schedule_run_wecom(task, run)
except Exception as wecom_exc:
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
db.session.commit()
import decimal, datetime as dt
def _safe(v):
@@ -224,8 +246,10 @@ def test_schedule_run(task_id: int):
for item in details:
safe_item = {k: _safe(v) for k, v in item.items()}
safe_details.append(safe_item)
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot})
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
except Exception as e:
db.session.rollback()
run = db.session.get(ScheduleRun, run.id)
duration_ms = int((_time.time() - start_ts) * 1000)
run.finished_at = datetime.utcnow()
run.duration_ms = duration_ms
@@ -277,7 +301,7 @@ def import_schedules():
schedule_no = str(item.get('schedule_no') or '').strip()
if schedule_no:
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database')}
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
if existing:
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
@@ -287,6 +311,8 @@ def import_schedules():
else:
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
task.data_source_type = task_payload['data_source_type']
task.kb_sync_enabled = task_payload['kb_sync_enabled']
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
db.session.commit()
if cfg:
upsert_schedule_task_config(task.id, cfg)
@@ -305,6 +331,9 @@ def post_schedule():
data_source_type = str(data.get('data_source_type') or 'database')
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
task.data_source_type = data_source_type
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
raw_kb_group_id = data.get('kb_group_id')
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
@@ -446,12 +475,12 @@ def get_schedule_runs(task_id: int):
sb = request.args.get('started_before')
if sa:
try:
started_after = datetime.fromisoformat(sa)
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
except (ValueError, TypeError):
pass
if sb:
try:
started_before = datetime.fromisoformat(sb)
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
except (ValueError, TypeError):
pass
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
@@ -474,4 +503,4 @@ def get_schedule_run_excel(run_id: int):
if not run.excel_file_data:
raise NotFoundError('Excel not found')
buf = BytesIO(run.excel_file_data)
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
+2 -2
View File
@@ -19,8 +19,8 @@ def workspace_schedule_runs():
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
started_after_str = request.args.get('started_after')
started_before_str = request.args.get('started_before')
started_after = datetime.fromisoformat(started_after_str) if started_after_str else None
started_before = datetime.fromisoformat(started_before_str) if started_before_str else None
started_after = datetime.fromisoformat(started_after_str.replace('Z', '+00:00')) if started_after_str else None
started_before = datetime.fromisoformat(started_before_str.replace('Z', '+00:00')) if started_before_str else None
limit = int(request.args.get('limit') or 100)
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
+5 -1
View File
@@ -75,7 +75,11 @@ def workspace_create_shipping_task_from_notice():
)
source_type = guess_source_type(upload.filename or "")
created = shipping_tools.create_task({"user_id": user.id, "source_type": source_type})
conversation_id = str(request.form.get("conversation_id") or "").strip()
payload = {"user_id": user.id, "source_type": source_type}
if conversation_id:
payload["conversation_id"] = conversation_id
created = shipping_tools.create_task(payload)
task_id = str(created.get("task_id") or "").strip()
if not task_id:
return jsonify({"error": "failed to create task"}), 500