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

+2
View File
@@ -58,6 +58,7 @@ def create_app(config_name='default'):
from app.api.workspace_shipping_notice import workspace_shipping_notice_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
from app.api.speech import speech_bp
# 聊天相关接口
@@ -77,6 +78,7 @@ def create_app(config_name='default'):
app.register_blueprint(workspace_shipping_notice_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')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
# Eagerly load persisted runtime settings so the very first request after
+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
+7 -2
View File
@@ -107,10 +107,14 @@ class Config:
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
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')
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# OpenAPI servers.url 基地址(Dify 调 Tool 时访问 hxops,不是 Dify 的 8882)
SHIPPING_NOTICE_TOOL_API_BASE = os.getenv('SHIPPING_NOTICE_TOOL_API_BASE')
# RoHS 检核 Chatflow Tool API
ROHS_TOOL_API_KEY = os.getenv('ROHS_TOOL_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'
@@ -270,3 +274,4 @@ config = {
'production': ProductionConfig,
'default': DevelopmentConfig,
}
+13
View File
@@ -585,6 +585,8 @@ class ScheduleTask(Base):
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
@@ -597,6 +599,7 @@ class ScheduleTask(Base):
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
@@ -672,12 +675,22 @@ class ScheduleRun(Base):
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
kb_sync_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True)
kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), nullable=True)
kb_sync_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_jobs.id'), nullable=True)
kb_sync_error: Mapped[Optional[str]] = mapped_column(Text)
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
kb_document: Mapped[Optional["KbDocument"]] = relationship("KbDocument", foreign_keys=[kb_document_id])
kb_document_version: Mapped[Optional["KbDocumentVersion"]] = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
kb_sync_job: Mapped[Optional["KbJob"]] = relationship("KbJob", foreign_keys=[kb_sync_job_id])
class ShippingTask(Base):
+60
View File
@@ -0,0 +1,60 @@
"""
backend/app/services/db_sequence.py
文件用途:修复 PostgreSQL 主键序列与 MAX(id) 不同步导致的 UniqueViolation。
"""
from __future__ import annotations
from sqlalchemy import text
from sqlalchemy.exc import IntegrityError
from app import db
def repair_pg_id_sequence(table_name: str) -> None:
"""将 PostgreSQL 自增序列对齐到 MAX(id),修复手工导入或迁移后的主键冲突。"""
bind = db.session.get_bind()
if bind.dialect.name != "postgresql":
return
qualified = f"public.{table_name}"
db.session.execute(
text(
"SELECT setval("
"pg_get_serial_sequence(:qualified, 'id'), "
f"COALESCE((SELECT MAX(id) FROM {table_name}), 0), true)"
),
{"qualified": qualified},
)
def is_pk_sequence_conflict(exc: IntegrityError, table_name: str) -> bool:
orig = getattr(exc, "orig", exc)
return f"{table_name}_pkey" in str(orig)
def add_and_flush_with_sequence_retry(instance, table_name: str) -> None:
"""插入并 flush;若主键序列落后则修复后重试一次。
使用 SAVEPOINT 隔离单次插入失败,避免全局 rollback 把同事务中已创建的
前置对象一并回滚。
"""
try:
nested = db.session.begin_nested()
try:
db.session.add(instance)
db.session.flush()
nested.commit()
except Exception:
nested.rollback()
raise
except IntegrityError as exc:
if not is_pk_sequence_conflict(exc, table_name):
raise
repair_pg_id_sequence(table_name)
nested = db.session.begin_nested()
try:
db.session.add(instance)
db.session.flush()
nested.commit()
except Exception:
nested.rollback()
raise
+27
View File
@@ -0,0 +1,27 @@
"""
backend/app/services/hxops_tool_api.py
文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
"""
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:
"""返回无尾斜杠的 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"):
configured = str(cfg.get(key) or "").strip().rstrip("/")
if configured:
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
return host or ""
@@ -12,6 +12,7 @@ import requests
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
from app.services.db_sequence import add_and_flush_with_sequence_retry
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
@@ -257,7 +258,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
sync_hash=sync_hash,
synced_by_id=synced_by_id,
)
db.session.add(record)
add_and_flush_with_sequence_retry(record, "kb_dify_sync_records")
else:
record.dataset_id = dataset_id
record.dataset_name = dataset_name
@@ -12,7 +12,7 @@ import zipfile
from flask import current_app
from app import db
from app.models import KbDocument, KbDocumentVersion, KbJob
from app.models import KbDocument, KbDocumentVersion, KbJob, ScheduleRun
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
from app.services.knowledge_cleaning.dify_sync_service import (
KbDifySyncError,
@@ -25,6 +25,26 @@ def _utc_now() -> datetime:
return datetime.utcnow()
def _schedule_run_id_from_job(job: KbJob | None) -> int | None:
payload = dict(getattr(job, "payload_json", None) or {})
raw_run_id = payload.get("schedule_run_id")
if raw_run_id in (None, "", 0, "0"):
return None
try:
return int(raw_run_id)
except (TypeError, ValueError):
return None
def _touch_schedule_run_kb_sync(job: KbJob | None, *, status: str, error: str | None = None) -> None:
run_id = _schedule_run_id_from_job(job)
if not run_id:
return
from app.services.schedule.kb_sync import update_schedule_run_kb_sync_status
update_schedule_run_kb_sync_status(run_id, status=status, error=error)
def _infer_missing_extension(source_path: Path) -> str:
if zipfile.is_zipfile(source_path):
try:
@@ -398,6 +418,24 @@ def run_path_upload_job(job_id: int) -> tuple[bool, str]:
db.session.commit()
return False, 'partial_failed'
sync_job_id = None
payload = dict(job.payload_json or {})
if payload.get('auto_sync_dify'):
sync_job = KbJob(
job_type='sync_dify',
status='queued',
group_id=job.group_id,
document_id=job.document_id,
document_version_id=job.document_version_id,
progress=0,
message='等待同步到 Dify',
payload_json={'document_version_id': job.document_version_id, 'source_job_id': job.id},
created_by_id=job.created_by_id,
)
db.session.add(sync_job)
db.session.flush()
sync_job_id = sync_job.id
job.status = 'success'
job.message = f'路径上传完成,成功 {success_count} 条'
job.error_message = None
@@ -432,6 +470,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
job.error_message = '关联文档版本不存在'
job.finished_at = _utc_now()
db.session.commit()
_touch_schedule_run_kb_sync(job, status='failed', error='关联文档版本不存在')
return False, '关联文档版本不存在'
source_path = Path(version.source_file_path)
@@ -442,6 +481,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
version.error_message = '原始文件不存在,无法执行 clean'
job.finished_at = _utc_now()
db.session.commit()
_touch_schedule_run_kb_sync(job, status='failed', error='原始文件不存在,无法执行 clean')
return False, '原始文件不存在'
job.status = 'running'
@@ -450,6 +490,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
job.started_at = _utc_now()
version.status = 'processing'
db.session.commit()
_touch_schedule_run_kb_sync(job, status='cleaning')
target_dir = source_path.parent
warnings = []
@@ -479,6 +520,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
version.status = 'failed'
version.error_message = str(exc)
db.session.commit()
_touch_schedule_run_kb_sync(job, status='failed', error=str(exc))
return False, 'timeout'
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
@@ -516,8 +558,42 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
job.error_message = None
job.result_json = result
job.finished_at = _utc_now()
sync_job_id = None
payload = dict(job.payload_json or {})
if payload.get('auto_sync_dify'):
sync_job = KbJob(
job_type='sync_dify',
status='queued',
group_id=job.group_id,
document_id=job.document_id,
document_version_id=job.document_version_id,
progress=0,
message='等待同步到 Dify',
payload_json={
'document_version_id': job.document_version_id,
'source_job_id': job.id,
'schedule_run_id': payload.get('schedule_run_id'),
},
created_by_id=job.created_by_id,
)
db.session.add(sync_job)
db.session.flush()
sync_job_id = sync_job.id
run_id = _schedule_run_id_from_job(job)
if run_id:
run = db.session.get(ScheduleRun, run_id)
if run:
run.kb_sync_job_id = sync_job_id
run.kb_sync_status = 'syncing'
db.session.commit()
if sync_job_id:
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
enqueue_kb_job(sync_job_id)
return True, 'ok'
@@ -552,6 +628,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
job.message = '同步到 Dify 失败'
job.finished_at = _utc_now()
db.session.commit()
_touch_schedule_run_kb_sync(job, status='failed', error=str(exc))
return False, str(exc)
except Exception as exc:
version.status = 'ready'
@@ -561,6 +638,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
job.message = '同步到 Dify 失败'
job.finished_at = _utc_now()
db.session.commit()
_touch_schedule_run_kb_sync(job, status='failed', error=str(exc))
return False, str(exc)
version.status = 'synced'
@@ -571,4 +649,5 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
job.result_json = result
job.finished_at = _utc_now()
db.session.commit()
_touch_schedule_run_kb_sync(job, status='success')
return True, 'ok'
+98
View File
@@ -0,0 +1,98 @@
"""
backend/app/services/rohs_check.py
文件用途:RoHS 文件检核统一判定入口,当前适配现有 Dify Workflow。
"""
from __future__ import annotations
from typing import Any
from app.services.dify import DifyService
VALID_ROHS_RESULTS = {"合格", "不合格", "人工判定"}
class RoHSCheckService:
"""Wrap RoHS judgement behind a stable backend interface."""
PROVIDER = "dify_workflow"
@classmethod
def evaluate(
cls,
*,
agent,
run_no: str,
record: str,
attachment_url: str | None = None,
system_prompt: str | None = None,
user: str = "schedule_system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
inputs: dict[str, Any] = {
"run_no": run_no,
"record": record,
"attachment_url": attachment_url,
}
prompt = str(system_prompt or "").strip()
if prompt:
inputs["system_prompt"] = prompt
try:
workflow_result = DifyService.run_workflow_streaming(
agent=agent,
inputs=inputs,
user=user,
timeout=timeout,
)
except Exception as exc:
return {
"dify_result": "人工判定",
"dify_message": f"Dify执行失败:{exc}",
"provider": cls.PROVIDER,
"workflow_run_id": None,
"error": str(exc),
}
normalized = cls.normalize_workflow_result(workflow_result)
normalized["provider"] = cls.PROVIDER
return normalized
@staticmethod
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data
output_data = outputs if isinstance(outputs, dict) else {}
dify_result = str(output_data.get("dify_result") or output_data.get("result") or "").strip()
dify_message = str(output_data.get("dify_message") or output_data.get("message") or "").strip()
workflow_run_id = data.get("workflow_run_id") if isinstance(data, dict) else None
status = data.get("status") if isinstance(data, dict) else None
error = data.get("error") if isinstance(data, dict) else None
if status == "failed" or (error and not output_data):
return {
"dify_result": "人工判定",
"dify_message": f"Dify执行失败:{error or f'status={status}'}",
"workflow_run_id": workflow_run_id,
"error": str(error or ""),
"raw_outputs": output_data,
}
if dify_result not in VALID_ROHS_RESULTS:
bad_value = dify_result or "空"
extra = f" | {dify_message}" if dify_message else ""
return {
"dify_result": "人工判定",
"dify_message": f"返回值异常:{bad_value}{extra}",
"workflow_run_id": workflow_run_id,
"error": None,
"raw_outputs": output_data,
}
return {
"dify_result": dify_result,
"dify_message": dify_message,
"workflow_run_id": workflow_run_id,
"error": None,
"raw_outputs": output_data,
}
Whitespace-only changes.
@@ -0,0 +1,21 @@
from __future__ import annotations
from app.models import Agent
# Dify / HXOPS Agent.name 常见取值(含「助手」后缀)
CHAT_AGENT_NAMES = frozenset(
{
"RoHS文件检核",
"RoHS文件检核助手",
"RoHS 文件检核助手",
}
)
def is_rohs_check_chat_agent(agent) -> bool:
name = (getattr(agent, "name", None) or "").strip()
return name in CHAT_AGENT_NAMES
def resolve_chat_agent() -> Agent | None:
return Agent.query.filter(Agent.name.in_(CHAT_AGENT_NAMES), Agent.is_active.is_(True)).first()
@@ -0,0 +1,34 @@
from __future__ import annotations
from flask import current_app
from app.services.hxops_tool_api import resolve_hxops_tool_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)
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
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()
key = str(
current_app.config.get("ROHS_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
inputs: dict[str, str] = {}
if base:
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_TOKEN_INPUT] = key
return inputs
__all__ = [
"HXOPS_TOOLS_API_BASE_INPUT",
"HXOPS_TOOL_API_TOKEN_INPUT",
"build_dify_chat_inputs",
"is_rohs_check_chat_agent",
]
@@ -0,0 +1,387 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS RoHS Check Tool API",
"description": "RoHS 文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"version": "1.0.0"
},
"servers": [
{
"url": "http://192.168.100.192:8891",
"description": "部署时设为 HXOPS_TOOLS_API_BASE;GET /tools/openapi.json 会按服务端配置自动覆盖"
}
],
"security": [
{ "BearerAuth": [] },
{ "IntegrationKey": [] }
],
"paths": {
"/api/rohs-check/tools/tasks": {
"get": {
"operationId": "list_rohs_tasks",
"summary": "查询 RoHS 检核任务列表",
"tags": ["RoHS Check"],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ListTasksResponse" }
}
}
},
"401": { "$ref": "#/components/responses/Unauthorized" },
"503": { "$ref": "#/components/responses/MissingAuth" }
}
}
},
"/api/rohs-check/tools/tasks/run": {
"post": {
"operationId": "run_rohs_check",
"summary": "异步启动 RoHS 检核",
"tags": ["RoHS Check"],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/RunCheckRequest" }
}
}
},
"responses": {
"200": {
"description": "启动成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/RunCheckSuccessResponse" }
}
}
},
"409": {
"description": "检核进行中,同任务不可重复启动",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/CheckRunningResponse" }
}
}
},
"400": { "$ref": "#/components/responses/BadRequest" },
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/TaskNotFound" }
}
}
},
"/api/rohs-check/tools/runs/{run_id}": {
"get": {
"operationId": "get_rohs_run",
"summary": "查询指定检核批次",
"tags": ["RoHS Check"],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 88 }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/GetRunResponse" }
}
}
},
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/RunNotFound" }
}
}
},
"/api/rohs-check/tools/tasks/{task_id}/latest-run": {
"get": {
"operationId": "get_latest_rohs_run",
"summary": "查询检核任务最近一次检核",
"tags": ["RoHS Check"],
"parameters": [
{
"name": "task_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 12 }
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/GetRunResponse" }
}
}
},
"401": { "$ref": "#/components/responses/Unauthorized" },
"404": { "$ref": "#/components/responses/RunNotFound" }
}
}
},
"/api/rohs-check/tools/runs/{run_id}/excel": {
"get": {
"operationId": "download_rohs_run_excel",
"summary": "下载检核报告 Excel(短期签名 token)",
"tags": ["RoHS Check"],
"security": [],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": { "type": "integer", "example": 88 }
},
{
"name": "token",
"in": "query",
"required": true,
"description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
"schema": { "type": "string" }
}
],
"responses": {
"200": {
"description": "Excel 文件流",
"content": {
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
"schema": { "type": "string", "format": "binary" }
}
}
},
"409": { "$ref": "#/components/responses/ExcelNotReady" }
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "ROHS_TOOL_API_KEY 或 INTEGRATION_API_KEY"
},
"IntegrationKey": {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Key",
"description": "与 Bearer 二选一"
}
},
"schemas": {
"TaskSummary": {
"type": "object",
"properties": {
"task_id": { "type": "integer", "example": 12 },
"task_no": { "type": "string", "example": "CHK202606090001" },
"name": { "type": "string", "example": "RoHS 自动检核" },
"enabled": { "type": "boolean" },
"last_status": { "type": "string", "nullable": true, "example": "success" },
"last_run_at": { "type": "string", "format": "date-time", "nullable": true },
"next_run_at": { "type": "string", "format": "date-time", "nullable": true }
}
},
"RunExcel": {
"type": "object",
"properties": {
"file_name": { "type": "string", "nullable": true, "example": "RUN202606090001.xlsx" },
"file_size": { "type": "integer", "nullable": true, "example": 45678 },
"download_url": {
"type": "string",
"nullable": true,
"example": "http://192.168.100.192:8891/api/rohs-check/tools/runs/88/excel?token=..."
}
}
},
"RunKnowledgeBase": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"sync_status": {
"type": "string",
"nullable": true,
"enum": ["skipped", "queued", "cleaning", "syncing", "ready", "success", "failed"]
},
"group_id": { "type": "integer", "nullable": true },
"document_id": { "type": "integer", "nullable": true },
"document_version_id": { "type": "integer", "nullable": true },
"sync_job_id": { "type": "integer", "nullable": true },
"error_message": { "type": "string", "nullable": true }
}
},
"RunDetail": {
"type": "object",
"properties": {
"run_id": { "type": "integer", "example": 88 },
"run_no": { "type": "string", "example": "RUN202606090001" },
"task_id": { "type": "integer", "example": 12 },
"task_name": { "type": "string", "example": "RoHS 自动检核" },
"status": {
"type": "string",
"enum": ["running", "success", "partial_failed", "failed", "queued", "cancelled"]
},
"total_count": { "type": "integer" },
"success_count": { "type": "integer" },
"failed_count": { "type": "integer" },
"skipped_count": { "type": "integer" },
"started_at": { "type": "string", "format": "date-time", "nullable": true },
"finished_at": { "type": "string", "format": "date-time", "nullable": true },
"duration_ms": { "type": "integer", "nullable": true },
"error_message": { "type": "string", "nullable": true },
"excel": { "$ref": "#/components/schemas/RunExcel" },
"knowledge_base": { "$ref": "#/components/schemas/RunKnowledgeBase" }
}
},
"ListTasksResponse": {
"type": "object",
"required": ["ok", "tasks"],
"properties": {
"ok": { "type": "boolean", "example": true },
"tasks": {
"type": "array",
"items": { "$ref": "#/components/schemas/TaskSummary" }
}
}
},
"RunCheckRequest": {
"type": "object",
"properties": {
"task_id": { "type": "integer", "example": 12 },
"task_no": { "type": "string", "example": "CHK202606090001" },
"trigger_source": { "type": "string", "default": "dify_chatflow" },
"conversation_id": { "type": "string", "nullable": true },
"user_message": { "type": "string", "nullable": true }
},
"description": "task_id 与 task_no 至少提供一个;优先使用 task_id"
},
"RunCheckSuccessResponse": {
"type": "object",
"required": ["ok", "message", "run"],
"properties": {
"ok": { "type": "boolean", "example": true },
"message": { "type": "string", "example": "检核已启动" },
"run": { "$ref": "#/components/schemas/RunDetail" }
}
},
"CheckRunningResponse": {
"type": "object",
"required": ["ok", "error_code", "message", "run"],
"properties": {
"ok": { "type": "boolean", "example": false },
"error_code": { "type": "string", "example": "check_running" },
"message": { "type": "string", "example": "该检核任务正在执行中,请稍后查询结果" },
"run": { "$ref": "#/components/schemas/RunDetail" }
}
},
"GetRunResponse": {
"type": "object",
"required": ["ok", "run"],
"properties": {
"ok": { "type": "boolean", "example": true },
"run": { "$ref": "#/components/schemas/RunDetail" }
}
},
"ErrorResponse": {
"type": "object",
"required": ["ok", "error_code", "message"],
"properties": {
"ok": { "type": "boolean", "example": false },
"error_code": { "type": "string" },
"message": { "type": "string" }
}
}
},
"responses": {
"Unauthorized": {
"description": "鉴权失败",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
"examples": {
"missing_auth": {
"value": { "ok": false, "error_code": "missing_auth", "message": "missing_auth" }
},
"invalid_auth": {
"value": { "ok": false, "error_code": "invalid_auth", "message": "invalid_auth" }
}
}
}
}
},
"MissingAuth": {
"description": "服务端未配置 ROHS_TOOL_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"
}
}
}
},
"BadRequest": {
"description": "请求无效或检核任务已停用",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
"example": {
"ok": false,
"error_code": "task_disabled",
"message": "task_disabled"
}
}
}
},
"TaskNotFound": {
"description": "检核任务不存在",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
"example": {
"ok": false,
"error_code": "task_not_found",
"message": "task_not_found"
}
}
}
},
"RunNotFound": {
"description": "检核批次不存在",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
"example": {
"ok": false,
"error_code": "run_not_found",
"message": "run_not_found"
}
}
}
},
"ExcelNotReady": {
"description": "Excel 尚未生成",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
"example": {
"ok": false,
"error_code": "excel_not_ready",
"message": "excel_not_ready"
}
}
}
}
}
}
}
@@ -0,0 +1,24 @@
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json")
def _load_base_spec() -> dict[str, Any]:
with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp:
return json.load(fp)
def build_rohs_openapi_spec(base_url: str) -> dict[str, Any]:
"""Build OpenAPI 3.0 spec for RoHS Chatflow HTTP tools."""
spec = copy.deepcopy(_load_base_spec())
base = str(base_url or "").strip().rstrip("/")
servers = spec.get("servers")
if base and isinstance(servers, list) and servers:
servers[0]["url"] = base
servers[0]["description"] = "HXOPS_TOOLS_API_BASE"
return spec
+252
View File
@@ -0,0 +1,252 @@
"""
backend/app/services/schedule/kb_sync.py
文件用途:把排程运行生成的 Excel 结果注册为知识库文档并触发清洗/同步。
"""
from __future__ import annotations
import hashlib
from pathlib import Path
from flask import current_app
from werkzeug.utils import secure_filename
from app import db
from app.services.db_sequence import add_and_flush_with_sequence_retry
from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob, ScheduleRun, ScheduleTask
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
def update_schedule_run_kb_sync_status(
run_id: int | None,
*,
status: str,
error: str | None = None,
) -> None:
"""回写排程运行的知识库同步状态,供 Chatflow 查询。"""
if not run_id:
return
run = db.session.get(ScheduleRun, int(run_id))
if not run:
return
run.kb_sync_status = status
if error is not None:
run.kb_sync_error = error
elif status == "success":
run.kb_sync_error = None
db.session.commit()
def _kb_storage_root() -> Path:
root = Path(current_app.config.get("KB_STORAGE_ROOT")).resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def _next_version_no(document: KbDocument) -> int:
versions = list(getattr(document, "versions", []) or [])
if not versions:
return 1
return max(item.version_no for item in versions) + 1
def _safe_excel_name(raw_name: str) -> str:
name = Path(str(raw_name or "")).name.strip() or "schedule_result.xlsx"
safe_stem = secure_filename(Path(name).stem) or "schedule_result"
suffix = Path(name).suffix or ".xlsx"
return f"{safe_stem}{suffix}"
def _create_kb_document_with_sequence_retry(**fields) -> KbDocument:
document = KbDocument(**fields)
add_and_flush_with_sequence_retry(document, "kb_documents")
return document
def sync_schedule_run_excel_to_kb(
task: ScheduleTask,
run: ScheduleRun,
*,
enabled: bool | None = None,
process_inline: bool = True,
) -> None:
kb_enabled = bool(getattr(task, "kb_sync_enabled", False)) if enabled is None else bool(enabled)
if not kb_enabled:
run.kb_sync_status = "skipped"
run.kb_sync_error = None
if current_app:
current_app.logger.info("[schedule-kb-sync] skipped run=%s: kb sync disabled", run.id)
return
if not task.kb_group_id:
run.kb_sync_status = "failed"
run.kb_sync_error = "未配置目标知识库分组"
if current_app:
current_app.logger.warning("[schedule-kb-sync] failed run=%s: kb_group_id missing", run.id)
return
if run.status not in ("success", "partial_failed"):
run.kb_sync_status = "skipped"
run.kb_sync_error = None
if current_app:
current_app.logger.info(
"[schedule-kb-sync] skipped run=%s: status=%s",
run.id,
run.status,
)
return
if not run.excel_file_data:
run.kb_sync_status = "skipped"
run.kb_sync_error = "未生成 Excel 文件"
if current_app:
current_app.logger.warning(
"[schedule-kb-sync] skipped run=%s: excel_file_data empty (size=%s)",
run.id,
run.excel_file_size,
)
return
group = db.session.get(KbGroup, task.kb_group_id)
if not group or not group.is_active:
run.kb_sync_status = "failed"
run.kb_group_id = task.kb_group_id
run.kb_sync_error = "目标知识库分组不存在或已停用"
return
title = f"{task.name}_{run.run_no}"
actor_id = run.triggered_by_user_id or task.owner_user_id
document = _create_kb_document_with_sequence_retry(
group_id=group.id,
title=title,
description=f"排程 {task.name} 运行结果 {run.run_no}",
status="uploaded",
source_type="schedule",
created_by_id=actor_id,
updated_by_id=actor_id,
)
version_no = _next_version_no(document)
source_file_name = _safe_excel_name(run.excel_file_name or f"{run.run_no}.xlsx")
version_dir = _kb_storage_root() / f"group_{group.id:04d}" / f"document_{document.id:06d}" / f"v{version_no:03d}"
version_dir.mkdir(parents=True, exist_ok=True)
target_path = version_dir / source_file_name
target_path.write_bytes(run.excel_file_data)
sha256 = hashlib.sha256(run.excel_file_data).hexdigest()
file_size = len(run.excel_file_data)
version = KbDocumentVersion(
document_id=document.id,
version_no=version_no,
status="uploaded",
is_current=True,
source_file_name=source_file_name,
source_file_path=str(target_path),
source_file_ext=Path(source_file_name).suffix.lower().lstrip(".") or None,
source_file_size=file_size,
sha256=sha256,
uploaded_by_id=run.triggered_by_user_id or task.owner_user_id,
)
add_and_flush_with_sequence_retry(version, "kb_document_versions")
clean_job = KbJob(
job_type="clean",
status="queued",
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
progress=0,
message="等待清洗排程结果 Excel",
payload_json={
"document_version_id": version.id,
"source_file_name": source_file_name,
"source_type": "schedule_run",
"schedule_run_id": run.id,
"run_no": run.run_no,
"auto_sync_dify": True,
},
created_by_id=run.triggered_by_user_id or task.owner_user_id,
)
add_and_flush_with_sequence_retry(clean_job, "kb_jobs")
run.kb_sync_status = "queued"
run.kb_group_id = group.id
run.kb_document_id = document.id
run.kb_document_version_id = version.id
run.kb_sync_job_id = clean_job.id
run.kb_sync_error = None
db.session.commit()
if current_app:
current_app.logger.info(
"[schedule-kb-sync] registered run=%s document_id=%s clean_job_id=%s",
run.id,
run.kb_document_id,
run.kb_sync_job_id,
)
if process_inline:
db.session.refresh(run)
process_schedule_kb_jobs_inline(run)
else:
enqueue_clean_job(clean_job.id)
def _find_pending_sync_job(run: ScheduleRun) -> KbJob | None:
from app.models import KbJob
if run.kb_sync_job_id:
job = db.session.get(KbJob, int(run.kb_sync_job_id))
if job and job.job_type == "sync_dify" and job.status == "queued":
return job
if not run.kb_document_id:
return None
return (
db.session.query(KbJob)
.filter(
KbJob.job_type == "sync_dify",
KbJob.document_id == run.kb_document_id,
KbJob.status == "queued",
)
.order_by(KbJob.id.desc())
.first()
)
def process_schedule_kb_jobs_inline(run: ScheduleRun) -> None:
"""
同步执行清洗与 Dify 同步。
默认在注册 Excel 后立即执行,避免仅 queued 而 worker_kb 未运行导致知识库看不到文档。
"""
if not run.id:
return
from app.models import KbJob
from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job
try:
db.session.refresh(run)
clean_job_id = run.kb_sync_job_id
if not clean_job_id:
return
clean_job = db.session.get(KbJob, int(clean_job_id))
if clean_job and clean_job.job_type == "clean" and clean_job.status == "queued":
run_clean_job(clean_job.id)
db.session.refresh(run)
sync_job = _find_pending_sync_job(run)
if sync_job:
run_sync_job(sync_job.id)
db.session.refresh(run)
if run.kb_sync_status in (None, "queued", "cleaning", "syncing"):
if run.kb_document_id:
run.kb_sync_status = "ready"
run.kb_sync_error = None
db.session.commit()
except Exception as exc:
if current_app:
current_app.logger.error(
"[schedule-kb-sync] inline process failed for run %s: %s",
run.id,
exc,
exc_info=True,
)
run.kb_sync_status = "failed"
run.kb_sync_error = str(exc)
db.session.commit()
+28 -11
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import func
@@ -8,6 +8,15 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.response_utils import utc_iso
def _as_naive_utc(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt
def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict:
@@ -23,14 +32,16 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
'dify_agent_id': task.dify_agent_id,
'platform_api_path': task.platform_api_path,
'data_source_type': task.data_source_type,
'kb_sync_enabled': bool(getattr(task, 'kb_sync_enabled', False)),
'kb_group_id': getattr(task, 'kb_group_id', None),
'notify_user_ids_json': task.notify_user_ids_json or [],
'notify_enabled': bool(task.notify_enabled),
'enabled': bool(task.enabled),
'next_run_at': task.next_run_at.isoformat() if task.next_run_at else None,
'last_run_at': task.last_run_at.isoformat() if task.last_run_at else None,
'next_run_at': utc_iso(task.next_run_at),
'last_run_at': utc_iso(task.last_run_at),
'last_status': last_status,
'created_at': task.created_at.isoformat() if task.created_at else None,
'updated_at': task.updated_at.isoformat() if task.updated_at else None,
'created_at': utc_iso(task.created_at),
'updated_at': utc_iso(task.updated_at),
}
@@ -42,8 +53,8 @@ def serialize_run(run: ScheduleRun) -> dict:
'schedule_name': run.task.name if run.task else None,
'trigger_type': run.trigger_type,
'triggered_by_user_id': run.triggered_by_user_id,
'started_at': run.started_at.isoformat() if run.started_at else None,
'finished_at': run.finished_at.isoformat() if run.finished_at else None,
'started_at': utc_iso(run.started_at),
'finished_at': utc_iso(run.finished_at),
'duration_ms': run.duration_ms,
'status': run.status,
'total_count': run.total_count,
@@ -58,10 +69,16 @@ def serialize_run(run: ScheduleRun) -> dict:
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
'kb_document_version_id': run.kb_document_version_id,
'kb_sync_job_id': run.kb_sync_job_id,
'kb_sync_error': run.kb_sync_error,
'wecom_notified': bool(run.wecom_notified),
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
'wecom_notified_at': utc_iso(run.wecom_notified_at),
'wecom_notify_error': run.wecom_notify_error,
'created_at': run.created_at.isoformat() if run.created_at else None,
'created_at': utc_iso(run.created_at),
}
@@ -104,9 +121,9 @@ def list_runs(
if status:
query = query.filter(ScheduleRun.status == status)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= started_after)
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
if started_before is not None:
query = query.filter(ScheduleRun.started_at < started_before)
query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before))
if owner_user_id is not None:
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
if notify_user_id is not None:
@@ -211,6 +211,11 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
task.notify_user_ids_json = payload.get("notify_user_ids_json")
if "kb_sync_enabled" in payload:
task.kb_sync_enabled = bool(payload.get("kb_sync_enabled"))
if "kb_group_id" in payload:
raw_group_id = payload.get("kb_group_id")
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
if not normalize_platform_api_path(task.platform_api_path):
raise ValueError("platform_api_path is required for platform_app")
@@ -343,6 +348,25 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
run.excel_file_data = file_data
run.excel_file_name = file_name
run.excel_file_size = file_size or 0
task.last_run_at = datetime.utcnow()
db.session.commit()
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, process_inline=True)
db.session.refresh(run)
except Exception as kb_exc:
db.session.rollback()
db.session.refresh(run)
if current_app:
current_app.logger.error("[schedule-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:
@@ -351,8 +375,6 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
if current_app:
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
task.last_run_at = datetime.utcnow()
db.session.commit()
return run
+25 -50
View File
@@ -5,7 +5,7 @@ from typing import Any, Callable
from flask import current_app
from app.services.dify import DifyService
from app.services.rohs_check import RoHSCheckService
try:
import pyodbc # type: ignore
@@ -235,9 +235,12 @@ def _run_check_job_loop(
dify_inputs["system_prompt"] = prompt
t_dify = _ts()
try:
dify_res = DifyService.run_workflow_streaming(
dify_res = RoHSCheckService.evaluate(
agent=agent,
inputs=dify_inputs,
run_no=run_no,
record=record_text,
attachment_url=attachment_url,
system_prompt=prompt,
user=user,
timeout=(5, max(300, int(wait_seconds))),
)
@@ -251,58 +254,30 @@ def _run_check_job_loop(
}))
raise
dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
dify_ok = True
if dify_status == "failed" or (dify_error and not dify_res.get("outputs")):
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
dify_result = "人工判定"
dify_message = f"Dify执行失败:{err_detail}"
if current_app:
current_app.logger.info(
"[%s] %s=%s dify_result=%s dify_message=%s",
log_prefix, log_prefix, row_id_value, dify_result, dify_message,
)
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": _truncate_str(str(dify_res)),
"workflow_run_id": workflow_run_id,
}))
item.update({
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": {
"provider": dify_res.get("provider") if isinstance(dify_res, dict) else None,
"dify_result": dify_result,
"dify_message": dify_message,
"writeback_srm": False,
"writeback_err": err_detail,
})
failed_count += 1
all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}")
details.append(item)
continue
else:
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
if current_app:
current_app.logger.info(
"[%s] %s=%s dify_result=%s dify_message=%s",
log_prefix, log_prefix, row_id_value,
(outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None,
(outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None,
)
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
dify_ok = True
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": {
"status": dify_status,
"dify_result": dify_result,
"dify_message": _truncate_str(dify_message),
"workflow_run_id": workflow_run_id,
},
}))
"dify_message": _truncate_str(dify_message),
"workflow_run_id": workflow_run_id,
"error": dify_error,
},
}))
else:
dify_result = "人工判定"
dify_message = "未配置 Agent ID,跳过 Dify"
@@ -24,3 +24,4 @@ def build_dify_chat_inputs() -> dict[str, str]:
if key:
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
return inputs
@@ -81,6 +81,7 @@ def format_parse_summary(
lines: list[dict[str, Any]] | None = None,
warnings: list[Any] | None = None,
low_confidence: bool = False,
include_confirmation_hint: bool = True,
lang: str | None = None,
payload: dict[str, Any] | None = None,
) -> str:
@@ -141,10 +142,11 @@ def format_parse_summary(
parts.append("")
if low_confidence:
parts.append(t("parse.low_conf", lang=resolved))
parts.append(t("parse.confirm", lang=resolved))
parts.append(t("parse.hint", lang=resolved))
hint_btn = t("parse.hint_btn", lang=resolved).strip()
if hint_btn:
parts.append(hint_btn)
if include_confirmation_hint:
parts.append(t("parse.confirm", lang=resolved))
parts.append(t("parse.hint", lang=resolved))
hint_btn = t("parse.hint_btn", lang=resolved).strip()
if hint_btn:
parts.append(hint_btn)
return "\n".join(parts).strip()
@@ -1,24 +1,8 @@
from __future__ import annotations
from flask import current_app, has_request_context, request
from app.services.hxops_tool_api import resolve_hxops_tool_api_base
def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str:
"""Resolve hxops Tool API base URL (…/api/shipping-notice, no trailing slash)."""
cfg = config
if cfg is None and current_app:
cfg = current_app.config
cfg = cfg or {}
configured = str(cfg.get("SHIPPING_NOTICE_TOOL_API_BASE") or "").strip().rstrip("/")
if configured:
return configured
configured = str(cfg.get("PUBLIC_BASE_URL") or "").strip().rstrip("/")
if configured:
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
return host or ""
"""Resolve hxops Tool API root URL (no trailing slash)."""
return resolve_hxops_tool_api_base(config=config, request_host=request_host)
+36 -5
View File
@@ -760,15 +760,20 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.PARSED)
_log_event(task, "parsed", {"confidence": confidence, "warnings": warnings})
db.session.commit()
summary_text = format_parse_summary(**summary_kwargs, payload=payload)
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
if confidence >= auto_threshold and not task.inventory_lines_json:
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
summary_text = format_parse_summary(
**summary_kwargs,
payload=payload,
include_confirmation_hint=not should_auto_continue,
)
if should_auto_continue:
lang = payload.get("lang") if isinstance(payload, dict) else None
auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
if lang:
auto_payload["lang"] = lang
auto_result = ensure_inventory(auto_payload)
auto_result = auto_progress(auto_payload) if _auto_progress_enabled() else ensure_inventory(auto_payload)
msg = str(auto_result.get("message") or "").strip()
merged_message = summary_text if not msg else f"{summary_text}\n\n{msg}"
merged_data = {}
@@ -1583,7 +1588,10 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
_log_event(task, "parse_confirmed", {"comment": comment})
db.session.commit()
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
return ensure_inventory({"task_id": task.task_no, "mode": "auto"})
next_payload = _merge_tool_payload(task, payload, extra={"mode": "auto"})
if _payload_wants_auto_chain_fallback(payload):
return auto_progress(next_payload)
return ensure_inventory(next_payload)
return tool_response(
status="ok",
task=task,
@@ -1609,6 +1617,29 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
data=_serialize_task_for_tool(task),
)
if task.process_status == "waiting_inventory" or (
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
):
follow_payload = _merge_tool_payload(task, payload, extra={"mode": "auto"})
if _payload_wants_auto_chain_fallback(payload):
return auto_progress(follow_payload)
return ensure_inventory(follow_payload)
if _awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return _inventory_mapping_checkpoint_response(task, lang=lang or None)
if task.inventory_lines_json or task.process_status == "inventory_ready":
follow_payload = _merge_tool_payload(task, payload)
if _payload_wants_auto_chain_fallback(payload):
return auto_progress(follow_payload)
return tool_response(
status="ok",
task=task,
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
data=_serialize_task_for_tool(task),
)
return tool_response(
status="failed",
task_id=task.task_no,