diff --git a/.env.dev b/.env.dev index 411aadb2..69b14f34 100644 --- a/.env.dev +++ b/.env.dev @@ -55,11 +55,11 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx MINIO_SECURE=false MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 -# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2) -# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) +# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOL_API_BASE) +# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致) +HXOPS_TOOL_API_BASE=http://192.168.100.192:8890 +# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh -# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL + /api/shipping-notice) -SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.108:5052/ # 文件存储(相对 backend/ 根目录) SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice diff --git a/.env.prod b/.env.prod index a4fb9b61..70a75e10 100644 --- a/.env.prod +++ b/.env.prod @@ -57,3 +57,6 @@ MINIO_SECRET_KEY=difyai123456 MINIO_SECURE=false # MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问 MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000 + +# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致) +HXOPS_TOOL_API_BASE=http://192.168.100.230:8891 \ No newline at end of file diff --git a/.env.shared b/.env.shared index fb371f36..c42233de 100644 --- a/.env.shared +++ b/.env.shared @@ -74,6 +74,8 @@ WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,perm # Common integration defaults INTEGRATION_API_MODE=local DIFY_API_BASE=https://api.dify.ai/v1 +# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖) +HXOPS_TOOL_API_BASE= # MinIO:按环境配置见 .env.dev / .env.test / .env.prod # MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export) diff --git a/.env.test b/.env.test index 118fcd4d..36bf0282 100644 --- a/.env.test +++ b/.env.test @@ -59,11 +59,11 @@ MINIO_SECURE=false # MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问 MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 -# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2) -# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) +# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOL_API_BASE) +# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致) +HXOPS_TOOL_API_BASE=http://192.168.100.192:8890 +# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh -# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL + /api/shipping-notice) -SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890/ # 文件存储(相对 backend/ 根目录) SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice diff --git a/AGENTS.md b/AGENTS.md index 7b152d6e..0b3baa3f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,9 +90,10 @@ docker compose logs -f hxops-backend - 提交信息必须符合 **Conventional Commits**,由 `commitlint.config.cjs` + `.githooks/commit-msg` **自动拦截**。 - 首次拉取后需安装 hooks:`./scripts/install_git_hooks.sh`。 -- 格式:`(): `,`subject` 用祈使语气、不以句号结尾、≤100 字符。 +- 格式:`(): `;`type`/`scope` 英文(scope 为 kebab-case 模块名),`subject` 中文,祈使语气、不以句号结尾、≤100 字符。 - 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。 - 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。 +- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);Agent 代提交读 `.cursor/rules/`。 详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 25b56f5a..4e933e2f 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -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 diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 951badf5..2a61d278 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -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, diff --git a/backend/app/api/rohs_check_tools.py b/backend/app/api/rohs_check_tools.py new file mode 100644 index 00000000..7b9c3f6c --- /dev/null +++ b/backend/app/api/rohs_check_tools.py @@ -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/", 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//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//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())) diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py index 39bb43e6..3e055f15 100644 --- a/backend/app/api/schedule_admin.py +++ b/backend/app/api/schedule_admin.py @@ -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') \ No newline at end of file + return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') diff --git a/backend/app/api/workspace_schedule.py b/backend/app/api/workspace_schedule.py index 7edc1787..496482c6 100644 --- a/backend/app/api/workspace_schedule.py +++ b/backend/app/api/workspace_schedule.py @@ -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)) diff --git a/backend/app/api/workspace_shipping_notice.py b/backend/app/api/workspace_shipping_notice.py index f82d19bc..77cd866b 100644 --- a/backend/app/api/workspace_shipping_notice.py +++ b/backend/app/api/workspace_shipping_notice.py @@ -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 diff --git a/backend/app/config.py b/backend/app/config.py index 4e838ee2..f03b7ff0 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -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, } + diff --git a/backend/app/models.py b/backend/app/models.py index 2ff6bdae..7c13a345 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -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): diff --git a/backend/app/response_utils.py b/backend/app/response_utils.py index 0b29e8e7..4bfd69ac 100644 --- a/backend/app/response_utils.py +++ b/backend/app/response_utils.py @@ -19,6 +19,15 @@ def utc_iso_now() -> str: return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") +def utc_iso(dt: datetime | None) -> str | None: + """将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串,便于前端正确转本地时区。""" + if dt is None: + return None + if dt.tzinfo is not None: + return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z" + return dt.isoformat() + "Z" + + def ok(data: Any, *, request_id: str | None = None, status: int = 200): payload: dict[str, Any] = { "success": True, diff --git a/backend/app/services/db_sequence.py b/backend/app/services/db_sequence.py new file mode 100644 index 00000000..bd3f25f7 --- /dev/null +++ b/backend/app/services/db_sequence.py @@ -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 diff --git a/backend/app/services/hxops_tool_api.py b/backend/app/services/hxops_tool_api.py new file mode 100644 index 00000000..01f4c1a1 --- /dev/null +++ b/backend/app/services/hxops_tool_api.py @@ -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 "" + + diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index bf8b5cc0..73a4e2c0 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -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 diff --git a/backend/app/services/knowledge_cleaning/tasks.py b/backend/app/services/knowledge_cleaning/tasks.py index 3e2df93e..a4938ad9 100644 --- a/backend/app/services/knowledge_cleaning/tasks.py +++ b/backend/app/services/knowledge_cleaning/tasks.py @@ -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' diff --git a/backend/app/services/rohs_check.py b/backend/app/services/rohs_check.py new file mode 100644 index 00000000..b4a7ebab --- /dev/null +++ b/backend/app/services/rohs_check.py @@ -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, + } diff --git a/backend/app/services/rohs_check_tools/__init__.py b/backend/app/services/rohs_check_tools/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/app/services/rohs_check_tools/agent_resolver.py b/backend/app/services/rohs_check_tools/agent_resolver.py new file mode 100644 index 00000000..3f43c785 --- /dev/null +++ b/backend/app/services/rohs_check_tools/agent_resolver.py @@ -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() diff --git a/backend/app/services/rohs_check_tools/dify_inputs.py b/backend/app/services/rohs_check_tools/dify_inputs.py new file mode 100644 index 00000000..415a5c2d --- /dev/null +++ b/backend/app/services/rohs_check_tools/dify_inputs.py @@ -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", +] diff --git a/backend/app/services/rohs_check_tools/openapi_base.json b/backend/app/services/rohs_check_tools/openapi_base.json new file mode 100644 index 00000000..a17ccbb5 --- /dev/null +++ b/backend/app/services/rohs_check_tools/openapi_base.json @@ -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" + } + } + } + } + } + } +} + + + diff --git a/backend/app/services/rohs_check_tools/openapi_spec.py b/backend/app/services/rohs_check_tools/openapi_spec.py new file mode 100644 index 00000000..5f4a08b3 --- /dev/null +++ b/backend/app/services/rohs_check_tools/openapi_spec.py @@ -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 diff --git a/backend/app/services/schedule/kb_sync.py b/backend/app/services/schedule/kb_sync.py new file mode 100644 index 00000000..c15419d0 --- /dev/null +++ b/backend/app/services/schedule/kb_sync.py @@ -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() diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index 3542d1e0..6b9d3d30 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -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: diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index 15166ed4..1ee5250f 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -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 diff --git a/backend/app/services/schedule/srm_service.py b/backend/app/services/schedule/srm_service.py index 5fc53eb9..79f87b29 100644 --- a/backend/app/services/schedule/srm_service.py +++ b/backend/app/services/schedule/srm_service.py @@ -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" diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 523ce84f..e528409f 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -24,3 +24,4 @@ def build_dify_chat_inputs() -> dict[str, str]: if key: inputs[HXOPS_TOOL_API_KEY_INPUT] = key return inputs + diff --git a/backend/app/services/shipping_notice/parse_summary.py b/backend/app/services/shipping_notice/parse_summary.py index 0eb3e9f0..c860fa3b 100644 --- a/backend/app/services/shipping_notice/parse_summary.py +++ b/backend/app/services/shipping_notice/parse_summary.py @@ -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() diff --git a/backend/app/services/shipping_notice/tool_api_url.py b/backend/app/services/shipping_notice/tool_api_url.py index 1287ec30..c047715d 100644 --- a/backend/app/services/shipping_notice/tool_api_url.py +++ b/backend/app/services/shipping_notice/tool_api_url.py @@ -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) diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 701d8749..8c597531 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -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, diff --git a/backend/migrations/versions/b8c9d0e1f2a3_add_rohs_schedule_kb_sync_fields.py b/backend/migrations/versions/b8c9d0e1f2a3_add_rohs_schedule_kb_sync_fields.py new file mode 100644 index 00000000..7a5080a7 --- /dev/null +++ b/backend/migrations/versions/b8c9d0e1f2a3_add_rohs_schedule_kb_sync_fields.py @@ -0,0 +1,50 @@ +"""add rohs schedule kb sync fields + +Revision ID: b8c9d0e1f2a3 +Revises: 5569936e6e0b +Create Date: 2026-06-09 00:00:00.000000 +""" +from alembic import op +import sqlalchemy as sa + + +revision = 'b8c9d0e1f2a3' +down_revision = '5569936e6e0b' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column('schedule_tasks', sa.Column('kb_sync_enabled', sa.Boolean(), server_default=sa.text('false'), nullable=False)) + op.add_column('schedule_tasks', sa.Column('kb_group_id', sa.Integer(), nullable=True)) + op.create_index('ix_schedule_tasks_kb_group_id', 'schedule_tasks', ['kb_group_id']) + op.create_foreign_key('fk_schedule_tasks_kb_group_id_kb_groups', 'schedule_tasks', 'kb_groups', ['kb_group_id'], ['id']) + + op.add_column('schedule_runs', sa.Column('kb_sync_status', sa.String(length=32), nullable=True)) + op.add_column('schedule_runs', sa.Column('kb_group_id', sa.Integer(), nullable=True)) + op.add_column('schedule_runs', sa.Column('kb_document_id', sa.Integer(), nullable=True)) + op.add_column('schedule_runs', sa.Column('kb_document_version_id', sa.Integer(), nullable=True)) + op.add_column('schedule_runs', sa.Column('kb_sync_job_id', sa.Integer(), nullable=True)) + op.add_column('schedule_runs', sa.Column('kb_sync_error', sa.Text(), nullable=True)) + op.create_foreign_key('fk_schedule_runs_kb_group_id_kb_groups', 'schedule_runs', 'kb_groups', ['kb_group_id'], ['id']) + op.create_foreign_key('fk_schedule_runs_kb_document_id_kb_documents', 'schedule_runs', 'kb_documents', ['kb_document_id'], ['id']) + op.create_foreign_key('fk_schedule_runs_kb_document_version_id_kb_document_versions', 'schedule_runs', 'kb_document_versions', ['kb_document_version_id'], ['id']) + op.create_foreign_key('fk_schedule_runs_kb_sync_job_id_kb_jobs', 'schedule_runs', 'kb_jobs', ['kb_sync_job_id'], ['id']) + + +def downgrade(): + op.drop_constraint('fk_schedule_runs_kb_sync_job_id_kb_jobs', 'schedule_runs', type_='foreignkey') + op.drop_constraint('fk_schedule_runs_kb_document_version_id_kb_document_versions', 'schedule_runs', type_='foreignkey') + op.drop_constraint('fk_schedule_runs_kb_document_id_kb_documents', 'schedule_runs', type_='foreignkey') + op.drop_constraint('fk_schedule_runs_kb_group_id_kb_groups', 'schedule_runs', type_='foreignkey') + op.drop_column('schedule_runs', 'kb_sync_error') + op.drop_column('schedule_runs', 'kb_sync_job_id') + op.drop_column('schedule_runs', 'kb_document_version_id') + op.drop_column('schedule_runs', 'kb_document_id') + op.drop_column('schedule_runs', 'kb_group_id') + op.drop_column('schedule_runs', 'kb_sync_status') + + op.drop_constraint('fk_schedule_tasks_kb_group_id_kb_groups', 'schedule_tasks', type_='foreignkey') + op.drop_index('ix_schedule_tasks_kb_group_id', table_name='schedule_tasks') + op.drop_column('schedule_tasks', 'kb_group_id') + op.drop_column('schedule_tasks', 'kb_sync_enabled') diff --git a/backend/scripts/export_rohs_check_openapi.py b/backend/scripts/export_rohs_check_openapi.py new file mode 100644 index 00000000..de485ac5 --- /dev/null +++ b/backend/scripts/export_rohs_check_openapi.py @@ -0,0 +1,31 @@ +"""Export Dify-compatible OpenAPI for RoHS Check tools paste/import.""" +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "backend")) + +from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec + + +def main() -> None: + base = ( + os.getenv("HXOPS_TOOLS_API_BASE") + or os.getenv("PUBLIC_BASE_URL") + or "http://127.0.0.1:5052" + ).rstrip("/") + spec = build_rohs_openapi_spec(base) + out_dir = ROOT / "docs" / "openapi" + out_dir.mkdir(parents=True, exist_ok=True) + json_path = out_dir / "rohs_check_tools_openapi.json" + json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"Wrote {json_path}") + print(f"Import URL: {base}/api/rohs-check/tools/openapi.json") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/export_shipping_notice_openapi.py b/backend/scripts/export_shipping_notice_openapi.py index 32887e6f..4f505bf5 100644 --- a/backend/scripts/export_shipping_notice_openapi.py +++ b/backend/scripts/export_shipping_notice_openapi.py @@ -14,9 +14,8 @@ from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec def main() -> None: base = ( - os.getenv("SHIPPING_NOTICE_TOOL_API_BASE") + os.getenv("HXOPS_TOOLS_API_BASE") or os.getenv("PUBLIC_BASE_URL") - or os.getenv("HXOPS_PUBLIC_BASE_URL") or "http://127.0.0.1:5052" ).rstrip("/") spec = build_dify_openapi_spec(base) @@ -30,3 +29,4 @@ def main() -> None: if __name__ == "__main__": main() + diff --git a/backend/tests/test_rohs_check_tools.py b/backend/tests/test_rohs_check_tools.py new file mode 100644 index 00000000..c31c2c2d --- /dev/null +++ b/backend/tests/test_rohs_check_tools.py @@ -0,0 +1,583 @@ +import sys +import types + +import pytest + +from app import db +from app.models import ScheduleRun, ScheduleTask, User +from app.services.rohs_check import RoHSCheckService + + +@pytest.fixture(autouse=True) +def _stub_minio(monkeypatch): + minio_module = types.ModuleType('minio') + minio_error_module = types.ModuleType('minio.error') + + class DummyMinio: + def __init__(self, *args, **kwargs): + pass + + def bucket_exists(self, *args, **kwargs): + return True + + class DummyS3Error(Exception): + pass + + minio_module.Minio = DummyMinio + minio_error_module.S3Error = DummyS3Error + monkeypatch.setitem(sys.modules, 'minio', minio_module) + monkeypatch.setitem(sys.modules, 'minio.error', minio_error_module) + + +def _mk_admin(): + admin = User(username='admin', email='admin-rohs@example.com', role='admin', status='active') + admin.set_password('x') + db.session.add(admin) + return admin + + +def _mk_check_task(owner_id: int, *, enabled=True): + task = ScheduleTask( + schedule_no='CHK-ROHS-001', + name='RoHS 自动检核', + schedule_type='platform_app', + owner_user_id=owner_id, + cron_expr='0 * * * *', + wait_seconds=5, + platform_api_path='/1', + enabled=enabled, + ) + db.session.add(task) + db.session.commit() + return task + + +def _mk_non_rohs_task(owner_id: int): + task = ScheduleTask( + schedule_no='CHK-GENERAL-001', + name='通用检核', + schedule_type='platform_app', + owner_user_id=owner_id, + cron_expr='0 * * * *', + wait_seconds=5, + platform_api_path='/general-check', + enabled=True, + ) + db.session.add(task) + db.session.commit() + return task + + +def test_rohs_service_normalizes_failed_workflow(): + payload = RoHSCheckService.normalize_workflow_result({ + 'status': 'failed', + 'error': 'workflow timeout', + 'workflow_run_id': 'wf-2', + }) + assert payload['dify_result'] == '人工判定' + assert 'Dify执行失败' in payload['dify_message'] + assert payload['workflow_run_id'] == 'wf-2' + + +def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch): + class _Agent: + id = 1 + + def _boom(**kwargs): + raise RuntimeError('dify down') + + monkeypatch.setattr('app.services.rohs_check.DifyService.run_workflow_streaming', _boom) + payload = RoHSCheckService.evaluate( + agent=_Agent(), + run_no='RUN-1', + record='Pb: 100ppm', + ) + assert payload['dify_result'] == '人工判定' + assert 'Dify执行失败' in payload['dify_message'] + assert payload['error'] == 'dify down' + + +def test_rohs_service_normalizes_invalid_result(): + payload = RoHSCheckService.normalize_workflow_result({ + 'status': 'succeeded', + 'outputs': {'dify_result': 'OK', 'dify_message': 'bad enum'}, + 'workflow_run_id': 'wf-1', + }) + assert payload['dify_result'] == '人工判定' + assert '返回值异常' in payload['dify_message'] + assert payload['workflow_run_id'] == 'wf-1' + + +def test_rohs_tool_requires_auth(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + res = client.get('/api/rohs-check/tools/tasks') + assert res.status_code == 401 + assert res.get_json()['error_code'] == 'missing_auth' + + +def test_rohs_tool_rejects_invalid_auth(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'wrong'}) + assert res.status_code == 401 + assert res.get_json()['error_code'] == 'invalid_auth' + + +def test_rohs_tool_lists_tasks(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + admin = _mk_admin() + db.session.commit() + _mk_check_task(admin.id) + _mk_non_rohs_task(admin.id) + + res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'secret'}) + assert res.status_code == 200 + data = res.get_json() + assert data['ok'] is True + assert [item['task_no'] for item in data['tasks']] == ['CHK-ROHS-001'] + + +def test_rohs_tool_rejects_non_rohs_task(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + admin = _mk_admin() + db.session.commit() + task = _mk_non_rohs_task(admin.id) + task_id = task.id + + res = client.post( + '/api/rohs-check/tools/tasks/run', + headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, + json={'task_id': task_id}, + ) + assert res.status_code == 404 + assert res.get_json()['error_code'] == 'task_not_found' + + +def test_rohs_tool_running_conflict(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + admin = _mk_admin() + db.session.commit() + task = _mk_check_task(admin.id) + task_id = task.id + run = ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=task.id, status='running', trigger_type='manual') + db.session.add(run) + db.session.commit() + + res = client.post( + '/api/rohs-check/tools/tasks/run', + headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, + json={'task_id': task_id}, + ) + assert res.status_code == 409 + data = res.get_json() + assert data['error_code'] == 'check_running' + + +def test_rohs_tool_excel_download_uses_signed_token(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + admin = _mk_admin() + db.session.commit() + task = _mk_check_task(admin.id) + run = ScheduleRun( + run_no='RUN-ROHS-EXCEL', + schedule_task_id=task.id, + status='success', + trigger_type='manual', + excel_file_name='result.xlsx', + excel_file_data=b'xlsx-bytes', + excel_file_size=10, + ) + db.session.add(run) + db.session.commit() + run_id = run.id + + query_res = client.get(f'/api/rohs-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'}) + token_url = query_res.get_json()['run']['excel']['download_url'] + download_path = token_url[token_url.index('/api/rohs-check'):] + + res = client.get(download_path) + assert res.status_code == 200 + assert res.data == b'xlsx-bytes' + + res = client.get('/api/rohs-check/tools/tasks?token=' + download_path.split('token=', 1)[1]) + assert res.status_code == 401 + + +def test_rohs_tool_task_disabled(app, client): + with app.app_context(): + app.config['INTEGRATION_API_KEY'] = 'secret' + admin = _mk_admin() + db.session.commit() + task = _mk_check_task(admin.id, enabled=False) + task_id = task.id + + res = client.post( + '/api/rohs-check/tools/tasks/run', + headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, + json={'task_id': task_id}, + ) + assert res.status_code == 400 + assert res.get_json()['error_code'] == 'task_disabled' + + +def test_rohs_openapi_injects_tool_api_base(app, client): + with app.app_context(): + app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com' + res = client.get('/api/rohs-check/tools/openapi.json') + assert res.status_code == 200 + assert res.get_json()['servers'][0]['url'] == 'https://rohs-tool.example.com' + + +def test_rohs_dify_chat_inputs(app): + from app.services.rohs_check_tools.dify_inputs import ( + HXOPS_TOOL_API_TOKEN_INPUT, + HXOPS_TOOLS_API_BASE_INPUT, + build_dify_chat_inputs, + ) + from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent + + class _Agent: + def __init__(self, name: str): + self.name = name + + assert is_rohs_check_chat_agent(_Agent('RoHS文件检核助手')) + assert not is_rohs_check_chat_agent(_Agent('货代发货通知 Agent')) + + with app.app_context(): + app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com' + app.config['ROHS_TOOL_API_KEY'] = 'rohs-secret' + inputs = build_dify_chat_inputs() + assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com' + assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret' + + +def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app): + from app.services.rohs_check_tools.dify_inputs import build_dify_chat_inputs + + with app.app_context(): + app.config.pop('HXOPS_TOOLS_API_BASE', None) + app.config['HXOPS_TOOL_API_BASE'] = 'https://legacy-tool.example.com' + app.config.pop('ROHS_TOOL_API_KEY', None) + app.config['INTEGRATION_API_KEY'] = 'integration-secret' + inputs = build_dify_chat_inputs() + assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com' + assert inputs['hxops_tool_api_token'] == 'integration-secret' + + +def test_kb_sync_skips_failed_run(app): + from app.models import KbGroup + from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb + + with app.app_context(): + admin = _mk_admin() + group = KbGroup(name='RoHS KB', is_active=True) + db.session.add(group) + db.session.commit() + task = _mk_check_task(admin.id) + task.kb_sync_enabled = True + task.kb_group_id = group.id + run = ScheduleRun( + run_no='RUN-KB-SKIP', + schedule_task_id=task.id, + status='failed', + trigger_type='manual', + excel_file_data=b'xlsx', + excel_file_name='result.xlsx', + ) + db.session.add(run) + db.session.commit() + + sync_schedule_run_excel_to_kb(task, run) + assert run.kb_sync_status == 'skipped' + + +def test_kb_sync_repairs_document_id_sequence_on_pkey_conflict(app, monkeypatch, tmp_path): + from app.models import KbDocument, KbGroup + from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb + from sqlalchemy.exc import IntegrityError + + monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path)) + original_flush = db.session.flush + failed = {'value': False} + + def _flush_with_one_pkey_failure(*args, **kwargs): + if not failed['value'] and any(isinstance(item, KbDocument) for item in db.session.new): + failed['value'] = True + raise IntegrityError('insert', {}, Exception('duplicate key value violates unique constraint "kb_documents_pkey"')) + return original_flush(*args, **kwargs) + + monkeypatch.setattr(db.session, 'flush', _flush_with_one_pkey_failure) + repaired: list[str] = [] + monkeypatch.setattr( + 'app.services.db_sequence.repair_pg_id_sequence', + lambda table_name: repaired.append(table_name), + ) + + with app.app_context(): + admin = _mk_admin() + group = KbGroup(name='RoHS KB Seq', is_active=True) + db.session.add(group) + db.session.commit() + task = _mk_check_task(admin.id) + task.kb_sync_enabled = True + task.kb_group_id = group.id + run = ScheduleRun( + run_no='TEST-RUN-KB-SEQ', + schedule_task_id=task.id, + status='success', + trigger_type='test', + triggered_by_user_id=admin.id, + excel_file_data=b'fake-xlsx', + excel_file_name='result.xlsx', + ) + db.session.add(run) + db.session.commit() + + sync_schedule_run_excel_to_kb(task, run, process_inline=False) + + assert repaired == ['kb_documents'] + assert run.kb_document_id is not None + assert run.kb_sync_status == 'queued' + + +def test_kb_sync_repairs_version_id_sequence_without_losing_document(app, monkeypatch, tmp_path): + from app.models import KbDocumentVersion, KbGroup + from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb + from sqlalchemy.exc import IntegrityError + + monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path)) + original_flush = db.session.flush + failed = {'value': False} + + def _flush_with_version_pkey_failure(*args, **kwargs): + if not failed['value'] and any(isinstance(item, KbDocumentVersion) for item in db.session.new): + failed['value'] = True + raise IntegrityError('insert', {}, Exception('duplicate key value violates unique constraint "kb_document_versions_pkey"')) + return original_flush(*args, **kwargs) + + monkeypatch.setattr(db.session, 'flush', _flush_with_version_pkey_failure) + repaired: list[str] = [] + monkeypatch.setattr( + 'app.services.db_sequence.repair_pg_id_sequence', + lambda table_name: repaired.append(table_name), + ) + + with app.app_context(): + admin = _mk_admin() + group = KbGroup(name='RoHS KB Version Seq', is_active=True) + db.session.add(group) + db.session.commit() + task = _mk_check_task(admin.id) + task.kb_sync_enabled = True + task.kb_group_id = group.id + run = ScheduleRun( + run_no='TEST-RUN-KB-VERSION-SEQ', + schedule_task_id=task.id, + status='success', + trigger_type='test', + triggered_by_user_id=admin.id, + excel_file_data=b'fake-xlsx', + excel_file_name='result.xlsx', + ) + db.session.add(run) + db.session.commit() + + sync_schedule_run_excel_to_kb(task, run, process_inline=False) + + assert repaired == ['kb_document_versions'] + assert run.kb_document_id is not None + assert run.kb_document_version_id is not None + assert run.kb_sync_status == 'queued' + + +def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeypatch, tmp_path): + from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup + from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module + from sqlalchemy.exc import IntegrityError + + monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path)) + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'ensure_dataset', + lambda self, group: ('ds-001', group.name), + ) + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'create_document_by_text', + lambda self, dataset_id, name, text: {'document': {'id': 'remote-doc-001', 'name': name}}, + ) + + with app.app_context(): + admin = _mk_admin() + group = KbGroup(name='RoHS KB Dify', is_active=True, dify_dataset_id='ds-001') + document = KbDocument( + group_id=None, + title='RoHS sync seq', + status='ready', + source_type='schedule', + created_by_id=admin.id, + updated_by_id=admin.id, + ) + db.session.add(group) + db.session.flush() + document.group_id = group.id + db.session.add(document) + db.session.flush() + cleaned = tmp_path / 'cleaned.md' + cleaned.write_text('# RoHS report', encoding='utf-8') + version = KbDocumentVersion( + document_id=document.id, + version_no=1, + status='ready', + is_current=True, + source_file_name='report.xlsx', + source_file_path=str(cleaned), + cleaned_file_path=str(cleaned), + uploaded_by_id=admin.id, + ) + db.session.add(version) + db.session.commit() + + original_flush = db.session.flush + repaired: list[str] = [] + failed = {'value': False} + + def _flush_with_one_pkey_failure(*args, **kwargs): + if not failed['value'] and any(isinstance(item, KbDifySyncRecord) for item in db.session.new): + failed['value'] = True + raise IntegrityError( + 'insert', + {}, + Exception( + 'duplicate key value violates unique constraint "kb_dify_sync_records_pkey"' + ), + ) + return original_flush(*args, **kwargs) + + monkeypatch.setattr(db.session, 'flush', _flush_with_one_pkey_failure) + monkeypatch.setattr( + 'app.services.db_sequence.repair_pg_id_sequence', + lambda table_name: repaired.append(table_name), + ) + + result = dify_sync_module.sync_document_version_to_dify(version.id, synced_by_id=admin.id) + + assert repaired == ['kb_dify_sync_records'] + assert result['remote_document_id'] == 'remote-doc-001' + + +def test_kb_sync_queues_test_run_excel(app, monkeypatch, tmp_path): + from app.models import KbGroup + from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb + + monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path)) + enqueued: list[int] = [] + monkeypatch.setattr( + 'app.services.schedule.kb_sync.enqueue_clean_job', + lambda job_id: enqueued.append(job_id), + ) + + with app.app_context(): + admin = _mk_admin() + group = KbGroup(name='RoHS KB Test', is_active=True) + db.session.add(group) + db.session.commit() + task = _mk_check_task(admin.id) + task.kb_sync_enabled = True + task.kb_group_id = group.id + run = ScheduleRun( + run_no='TEST-RUN-KB-001', + schedule_task_id=task.id, + status='success', + trigger_type='test', + triggered_by_user_id=admin.id, + excel_file_data=b'fake-xlsx', + excel_file_name='result.xlsx', + ) + db.session.add(run) + db.session.commit() + + sync_schedule_run_excel_to_kb(task, run, process_inline=False) + + assert run.kb_sync_status == 'queued' + assert run.kb_document_id is not None + assert run.kb_sync_job_id is not None + assert enqueued == [run.kb_sync_job_id] + + +def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path): + from app.models import KbGroup, KbJob + from app.services.schedule.kb_sync import process_schedule_kb_jobs_inline, sync_schedule_run_excel_to_kb + + monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path)) + clean_calls: list[int] = [] + sync_calls: list[int] = [] + + def _fake_clean(job_id: int): + clean_calls.append(job_id) + job = db.session.get(KbJob, job_id) + 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='pending', + payload_json={'document_version_id': job.document_version_id}, + created_by_id=job.created_by_id, + ) + db.session.add(sync_job) + db.session.flush() + run = db.session.get(ScheduleRun, (job.payload_json or {}).get('schedule_run_id')) + if run: + run.kb_sync_job_id = sync_job.id + run.kb_sync_status = 'syncing' + job.status = 'success' + db.session.commit() + return True, 'ok' + + def _fake_sync(job_id: int): + sync_calls.append(job_id) + job = db.session.get(KbJob, job_id) + job.status = 'success' + db.session.commit() + return True, 'ok' + + monkeypatch.setattr('app.services.knowledge_cleaning.tasks.run_clean_job', _fake_clean) + monkeypatch.setattr('app.services.knowledge_cleaning.tasks.run_sync_job', _fake_sync) + + with app.app_context(): + admin = _mk_admin() + group = KbGroup(name='RoHS KB Inline', is_active=True) + db.session.add(group) + db.session.commit() + task = _mk_check_task(admin.id) + task.kb_sync_enabled = True + task.kb_group_id = group.id + run = ScheduleRun( + run_no='TEST-RUN-KB-INLINE', + schedule_task_id=task.id, + status='success', + trigger_type='test', + triggered_by_user_id=admin.id, + excel_file_data=b'fake-xlsx', + excel_file_name='result.xlsx', + ) + db.session.add(run) + db.session.commit() + + sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=False) + clean_job_id = run.kb_sync_job_id + process_schedule_kb_jobs_inline(run) + db.session.refresh(run) + + assert run.kb_document_id is not None + assert clean_calls == [clean_job_id] + assert sync_calls + assert run.kb_sync_status in ('success', 'ready', 'syncing') diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index 2f05234c..c464e57c 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -132,7 +132,7 @@ def test_shipping_notice_match_shortage_needs_human(app, client): def test_openapi_spec_public(app, client): - app.config["SHIPPING_NOTICE_TOOL_API_BASE"] = "http://tool-api.example.com" + app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com" res = client.get("/api/shipping-notice/tools/openapi.json") assert res.status_code == 200 spec = res.get_json() @@ -804,6 +804,71 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client): assert task.match_status is None +def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client): + headers = _tool_headers(app) + + create_res = client.post( + "/api/shipping-notice/tools/create_task", + headers=headers, + json={"source_type": "manual"}, + ) + task_id = create_res.get_json()["task_id"] + + parse_res = client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "ACME", + "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + parse_data = parse_res.get_json() + assert "【发货通知解析确认】" in parse_data["message"] + assert "回复「确认」进入库存检查" not in parse_data["message"] + assert parse_data.get("checkpoint") != "parse_review" + + +def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path): + headers = _tool_headers(app) + trigger = tmp_path / "inventory_triggers" + trigger.mkdir() + app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + + create_res = client.post( + "/api/shipping-notice/tools/create_task", + headers=headers, + json={"source_type": "manual"}, + ) + task_id = create_res.get_json()["task_id"] + + parse_res = client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "ACME", + "lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + assert parse_res.get_json()["status"] == "running" + + confirm_res = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"task_id": task_id, "decision": "confirm"}, + ) + confirm_data = confirm_res.get_json() + assert confirm_data["status"] == "running" + assert "RPA 库存导出" in confirm_data["message"] + + def test_submit_decision_by_conversation_id(app, client): headers = _tool_headers(app) @@ -883,3 +948,4 @@ def test_chat_actions_empty_when_task_rejected(app): payload = build_chat_actions_payload(task) assert payload["checkpoint"] == "rejected" assert payload["action_buttons"] == [] + diff --git a/docs/convention/COMMIT_CONVENTION.md b/docs/convention/COMMIT_CONVENTION.md index 0bf797a7..73946c61 100644 --- a/docs/convention/COMMIT_CONVENTION.md +++ b/docs/convention/COMMIT_CONVENTION.md @@ -6,7 +6,7 @@ - 一个提交只做一件事(或同一类紧密相关的事)。 - 提交信息要让不了解上下文的人也能快速理解“改了什么、为什么改”。 -- 优先使用英文提交信息,避免中英文混用造成解析不一致。 +- **`type` 与 `scope` 使用英文**;**`subject` 与 `body` 使用中文**,便于团队阅读且 scope 与代码模块一一对应。 - 所有人遵循同一格式,减少代码评审和回溯成本。 ## 2. 标准格式(必须) @@ -21,10 +21,10 @@ 说明: -- `type`:变更类型(必填)。 -- `scope`:影响范围(选填,但推荐填写)。 -- `subject`:一句话概述(必填)。 -- `body`:详细说明(选填,建议在复杂改动时填写)。 +- `type`:变更类型(必填,**英文枚举**)。 +- `scope`:影响模块(选填但推荐,**英文 kebab-case**,与代码目录/包名一致)。 +- `subject`:一句话概述(必填,**中文**)。 +- `body`:详细说明(选填,建议在复杂改动时填写,**中文**)。 - `footer`:关联任务、破坏性变更等(选填)。 ## 3. Header 书写规则(必须) @@ -32,16 +32,18 @@ Header 即第一行:`(): ` - 必须小写 `type`,后接英文冒号和空格。 -- `subject` 使用祈使语气,简明描述动作,如 `add` `fix` `remove` `refactor`。 +- `scope` 小写英文,多词用 kebab-case(如 `shipping-notice`),**禁止中文**。 +- `subject` 使用祈使语气,简明描述动作,如「新增」「修复」「移除」「重构」。 - 不以句号结尾。 - Header 最大长度建议不超过 100 个字符。 正确示例: ```text -feat(auth): add SMS login support -fix(order): handle null coupon in checkout -refactor(api): split user service and repository +feat(schedule): 新增 RoHS 知识库同步字段 +fix(shipping-notice): 修复 Dify 入参解析空值问题 +refactor(rohs-check): 拆分 Agent 解析与工具 API +build(jenkins): 保留最近 10 组镜像并自动清理旧镜像 ``` 错误示例: @@ -50,6 +52,9 @@ refactor(api): split user service and repository Feat: Added login feature. fix: bug update code +feat(排程): 新增 RoHS 知识库同步字段 +feat(schedule): add kb sync fields +fix(shipping-notice): handle null coupon ``` ## 4. Type 定义(必须使用以下枚举) @@ -68,18 +73,33 @@ update code ## 5. Scope 约定(推荐) -Scope 用于快速识别改动模块,建议使用以下命名: +Scope 应对齐代码模块,便于从提交信息定位到目录。选取规则: -- 按业务域:`auth` `order` `payment` `user` -- 按技术层:`api` `db` `ui` `deps` `config` -- 按工程对象:`docker` `github-actions` `eslint` +1. 看主要改动文件所在目录(`backend/app/services//`、`backend/app/api/`、`frontend/src/features/`)。 +2. 目录名转 kebab-case:`shipping_notice` → `shipping-notice`,`rohs_check` → `rohs-check`。 +3. 跨模块改动选影响最大的模块;纯基建用 `jenkins`、`migration`、`deps`、`ci` 等。 + +| scope | 典型目录/模块 | +| --- | --- | +| `schedule` | `services/schedule/`、`api/schedule_admin`、前端 `features/admin/modules/schedules/` | +| `shipping-notice` | `services/shipping_notice/`、`api/workspace_shipping_notice` | +| `rohs-check` | `services/rohs_check*`、`api/rohs_check_tools` | +| `knowledge-base` | `api/knowledge_base`、`services/knowledge_cleaning/` | +| `chat` | `api/chat`、前端 chat 相关 | +| `auth` | 登录认证 | +| `admin` | 管理后台通用 | +| `agents` | Agent 管理 | +| `api` | 跨模块 API 层重构 | +| `migration` | Alembic 迁移 | +| `jenkins` / `ci` / `deps` | 工程与依赖 | 示例: ```text -fix(payment): prevent duplicate callback handling -ci(github-actions): cache pnpm store -build(deps): upgrade axios to v1.9.0 +fix(shipping-notice): 防止回调重复处理 +ci(github-actions): 缓存 pnpm store +build(deps): 升级 axios 至 v1.9.0 +perf(schedule): 优化排程查询分页加载 ``` ## 6. Body 编写建议(复杂改动强烈建议) @@ -93,11 +113,10 @@ Body 与 Header 空一行,重点写“为什么”和“影响面”: 示例: ```text -feat(order): support partial shipment +feat(shipping-notice): 支持部分发货 -Allow splitting one order into multiple shipment packages to support -warehouse stock differences. This change updates shipment status flow -and adds validation for package-level tracking numbers. +允许将同一订单拆分为多个发货包裹,以应对仓库库存差异。 +本次变更更新发货状态流转,并增加包裹级运单号校验。 ``` ## 7. Footer 约定(推荐) @@ -112,7 +131,7 @@ and adds validation for package-level tracking numbers. 若存在不兼容修改,必须明确标注: ```text -BREAKING CHANGE: remove legacy /v1/login endpoint, use /v2/login instead. +BREAKING CHANGE: 移除旧版 /v1/login 接口,请改用 /v2/login。 ``` ## 8. 常见场景示例 @@ -120,36 +139,36 @@ BREAKING CHANGE: remove legacy /v1/login endpoint, use /v2/login instead. 新增功能: ```text -feat(profile): add avatar upload API +feat(auth): 新增头像上传接口 ``` 修复问题: ```text -fix(cart): recalculate total when item quantity is zero +fix(shipping-notice): 商品数量为 0 时重新计算总价 ``` 依赖升级: ```text -build(deps): bump spring-boot to 3.3.2 +build(deps): 升级 spring-boot 至 3.3.2 ``` 仅文档: ```text -docs(readme): add local development instructions +docs(readme): 补充本地开发说明 ``` 回滚提交: ```text -revert: feat(payment): support WeChat QR checkout +revert: feat(shipping-notice): 支持微信扫码结账 ``` ## 9. Pull Request 要求(建议) -- PR 标题建议复用同样格式:`type(scope): subject` +- PR 标题建议复用同样格式:`type(scope): subject`(scope 英文模块名,subject 中文) - 一个 PR 尽量聚焦一个主题。 - 合并前整理提交历史,避免大量无意义提交(如 `update` `fix` `test`)。 @@ -158,12 +177,14 @@ revert: feat(payment): support WeChat QR checkout - 禁止无语义提交信息:`update` `fix bug` `modify` `111` - 禁止把多个无关改动放在同一提交中。 - 禁止漏写破坏性变更说明。 +- 禁止 `scope` 使用中文(如 `排程`、`发货通知`)。 +- 禁止 `subject` 使用英文(历史英文提交可保留,新提交统一中文)。 ## 11. 自检清单(提交前) - 提交类型是否正确(`feat/fix/...`)? -- `subject` 是否清晰说明“做了什么”? -- 是否需要 `scope` 来提升可读性? +- `scope` 是否为英文模块名且与改动目录一致? +- `subject` 是否为中文且清晰说明“做了什么”? - 是否存在破坏性变更,若有是否标注 `BREAKING CHANGE`? - 是否关联了任务编号(`Refs/Closes #id`)? @@ -171,9 +192,10 @@ revert: feat(payment): support WeChat QR checkout 仓库已通过 Git Hook 自动校验提交信息,配置如下: -- **commitlint**:根目录 `commitlint.config.cjs`,规则与本文档对齐。 +- **commitlint**:根目录 `commitlint.config.cjs`,规则与本文档对齐(校验 type 格式与 Header 长度,不限制 subject 语言)。 - **commit-msg Hook**:`.githooks/commit-msg`,在 `git commit` 时自动运行。 - **安装**:`./scripts/install_git_hooks.sh`(会设置 `core.hooksPath` 并执行根目录 `npm install`)。 +- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**;Agent 对话代提交读取 **`.cursor/rules/git-commit-zh.mdc`**。两者内容需保持一致。 详见 [Git Hooks 团队启用指南](../GIT_HOOKS.md)。 diff --git a/docs/demand.md b/docs/demand.md index 475bb082..f292694a 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -22,6 +22,15 @@ ## 3. 范围说明 +### 3.x RoHS 文件检核补充需求 + +- **核心目标**:提供 RoHS 文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。 +- 新增 `RoHSCheckService` 作为统一判定入口,内部复用现有 Dify RoHS Workflow 中的 Prompt 与模型配置。 +- 新增 Dify Chatflow 显式 HTTP Tool,用于对话中发起检核、查询检核状态与展示结果;不使用 Agent 节点做逐条判定。 +- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 通过 Knowledge Retrieval 检索已入库历史报告(与 Tool API 实时查询并存)。 +- 后台执行、定时触发、数据抓取与写回沿用现有任务引擎(实现细节对用户透明)。 +- Dify Chatflow 编排与 OpenAPI 导入见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)。 + ### 3.1 本期范围 - 查询员工本人假期余额 diff --git a/docs/funclist.md b/docs/funclist.md index 457de7db..e3950914 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -16,6 +16,15 @@ ## 2. 详细功能拆分 +### RoHS 文件检核 + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| RoHSCheckService 判定入口 | 已实现 | 检核执行链路统一调用,内部复用现有 Dify Workflow | +| Chatflow 发起与查询检核 | 已实现 | Tool API:查检核任务、启动检核、查检核批次、查最近检核、Excel 报告链接 | +| RoHS Chatflow 编排手册 | 已文档化 | 见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md) | +| 检核报告同步知识库 | 已实现 | 检核 success / partial_failed 且生成 Excel 后同步到所选知识库分组 | + ### F-01 本人假期查询 #### 目标 diff --git a/docs/openapi/rohs_check_tools_openapi.json b/docs/openapi/rohs_check_tools_openapi.json new file mode 100644 index 00000000..4fc52961 --- /dev/null +++ b/docs/openapi/rohs_check_tools_openapi.json @@ -0,0 +1,635 @@ +{ + "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" + } + ], + "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" + } + } + } + } + } + } +} \ No newline at end of file diff --git a/docs/shipping_notice.md b/docs/shipping_notice.md index 11052237..c154cc5f 100644 --- a/docs/shipping_notice.md +++ b/docs/shipping_notice.md @@ -65,9 +65,10 @@ flask db upgrade ### 1.2 环境变量(`.env.dev` 示例) ```env -# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) +# Tool API 基地址(RoHS / 货代共用,无尾斜杠) +HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890 +# 货代 Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) SHIPPING_NOTICE_TOOL_API_KEY=your-tool-key -SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.114:5052 # 文件存储(相对 backend/ 根目录;勿写 backend/data/… 以免 cwd 在 backend/ 时变成 backend/backend/…) SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice @@ -194,7 +195,7 @@ curl -s http://192.168.100.192:8890/api/shipping-notice/tools/openapi.json | hea ```bash cd backend -set SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890 +set HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890 python scripts/export_shipping_notice_openapi.py # → docs/openapi/shipping_notice_tools.dify.json ``` @@ -409,21 +410,21 @@ flowchart TD | 输入变量名 | 类型 | 必填 | 说明 | |------------|------|------|------| -| `hxops_tool_api_base` | string | 否 | hxops 后端根地址,**无**尾斜杠,例 `http://host:8890` | +| `HXOPS_TOOLS_API_BASE` | string | 否 | hxops 后端根地址,**无**尾斜杠,例 `http://host:8890` | | `hxops_tool_api_key` | string | 否 | 与 hxops `SHIPPING_NOTICE_TOOL_API_KEY` 一致 | -2. **hxops 自动注入**:用户经前端聊天调用 `货代发货通知 Agent` 时,`/api/chat/completions` 会把上述两项写入 Dify `inputs`(读 `SHIPPING_NOTICE_TOOL_API_BASE` / `SHIPPING_NOTICE_TOOL_API_KEY`)。**切换 dev / test / prod 只改 hxops 环境变量,Dify 画布 YAML 可原样导入**。 +2. **hxops 自动注入**:用户经前端聊天调用 `货代发货通知 Agent` 时,`/api/chat/completions` 会把上述两项写入 Dify `inputs`(读 `HXOPS_TOOLS_API_BASE` / `SHIPPING_NOTICE_TOOL_API_KEY`)。**切换 dev / test / prod 只改 hxops 环境变量,Dify 画布 YAML 可原样导入**。 3. **HTTP 节点统一模板**(所有 `HTTP_*` 节点 URL / Header 均按此填写,勿再写死 IP): | 项 | 模板 | |----|------| -| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/`,例 `…/api/shipping-notice/tools/create_task` | +| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/`,例 `…/api/shipping-notice/tools/create_task` | | Header `X-Shipping-Tool-Key` | `{{#hxops_tool_api_key#}}` | -> Dify 版本差异:若 UI 无法直接填 `{{#变量名#}}`,用变量选择器绑定 **输入变量** `hxops_tool_api_base` / `hxops_tool_api_key` 即可,语义相同。 +> Dify 版本差异:若 UI 无法直接填 `{{#变量名#}}`,用变量选择器绑定 **输入变量** `HXOPS_TOOLS_API_BASE` / `hxops_tool_api_key` 即可,语义相同。 -**Agent 自定义工具(OpenAPI)**:导入地址 `{hxops_tool_api_base}/api/shipping-notice/tools/openapi.json`(或 Dify 环境变量拼 URL);换环境时重新「从 URL 导入」或改工具 Server URL 一次,**不必改 Chatflow 连线**。 +**Agent 自定义工具(OpenAPI)**:导入地址 `{HXOPS_TOOLS_API_BASE}/api/shipping-notice/tools/openapi.json`(或 Dify 环境变量拼 URL);换环境时重新「从 URL 导入」或改工具 Server URL 一次,**不必改 Chatflow 连线**。 **HTTP 公共配置** @@ -432,7 +433,7 @@ flowchart TD | Method | POST | | Header | `X-Shipping-Tool-Key: {{#hxops_tool_api_key#}}` | | Header | `Content-Type: application/json`(JSON Body 节点) | -| 基 URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/`(**禁止**写死 IP;旧示例 IP 仅作联调参考) | +| 基 URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/`(**禁止**写死 IP;旧示例 IP 仅作联调参考) | **Dify Code 节点配置说明** @@ -715,7 +716,7 @@ def main( | 项 | 值 | |----|-----| | Method | POST | -| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/create_task` | +| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/create_task` | | Header | `X-Shipping-Tool-Key: {{#hxops_tool_api_key#}}`;`Content-Type: application/json` | | Body | `{{#拼装 create_task Body.create_body_json#}}`(JSON 对象,勿再加引号) | | 出参 | `body` · **String** | @@ -839,7 +840,7 @@ def main(text: str) -> dict: | 项 | 值 | |----|-----| -| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/parse_notice` | +| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/parse_notice` | | Header | `X-Shipping-Tool-Key`;`Content-Type: application/json` | | Body | 见下 | | 出参 | `body` · **String** | @@ -927,7 +928,7 @@ def main(body: str) -> dict: | 项 | 值 | |----|-----| | Method | POST | -| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/upload_inventory_file` | +| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/upload_inventory_file` | | Header | `X-Shipping-Tool-Key: {{#hxops_tool_api_key#}}` | | Body 类型 | **form-data** | | form `task_id` | `{{#conversation.task_id#}}` · String | @@ -3024,3 +3025,4 @@ GET /api/shipping-notice/tools/checkpoint-catalog | `backend/tests/test_shipping_notice_tools.py` | Tool 集成测试 | | `backend/tests/test_shipping_notice_state_machine.py` | registry / task UI 快照 | | `scripts/rpa/freight_rpa_worker.py` | RPA Worker | + diff --git a/docs/tec.md b/docs/tec.md index d4fe4090..4c1028c7 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -10,6 +10,14 @@ ## 2. 现有可复用能力 +### 2.x RoHS 文件检核可复用能力 + +- **产品语义**:对外统一为 RoHS 文件检核(发起、实时查询、报告、知识库同步、历史报告检索);Tool API 使用 `/api/rohs-check/tools/tasks` 与 `task_id` / `task_no` 字段;历史查询走 Dify Knowledge Retrieval(绑定检核报告同步的 Dataset);对外基地址由环境变量 `HXOPS_TOOLS_API_BASE` 配置。 +- 通过 `RoHSCheckService.evaluate()` 包装现有 Dify Workflow 调用,保持 `dify_result / dify_message` 输出兼容。 +- 新增 `/api/rohs-check/tools/*` 显式 HTTP Tool API,供 Dify Chatflow 发起检核、查询检核结果并返回 Excel 报告短期签名链接。 +- Chatflow 完整编排、Dify 逐步配置与 OpenAPI 导入见 **[docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)**;OpenAPI 规范见 **[docs/openapi/rohs_check_tools_openapi.json](openapi/rohs_check_tools_openapi.json)**(`python backend/scripts/export_rohs_check_openapi.py` 重新生成)。 +- 复用知识库 `KbDocument / KbDocumentVersion / KbJob` 清洗与 Dify 同步链路,将检核报告 Excel 作为独立文档入库。 + ### 2.1 已有聊天路由能力 - 后端 `chat` 接口已支持按意图分流 @@ -878,3 +886,4 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth; - Web 进程压力下降,系统稳定性提升 - 失败任务可重试,进度展示更清晰 - 整体知识库链路更适合后续扩展为高并发、多批次处理模式 + diff --git a/frontend/src/api/schedule.ts b/frontend/src/api/schedule.ts index f2dabb21..546333ee 100644 --- a/frontend/src/api/schedule.ts +++ b/frontend/src/api/schedule.ts @@ -13,6 +13,8 @@ export interface ScheduleTask { dify_agent_id?: number | null; platform_api_path?: string | null; data_source_type?: string; + kb_sync_enabled?: boolean; + kb_group_id?: number | null; notify_user_ids_json: number[]; notify_enabled: boolean; enabled: boolean; @@ -45,6 +47,12 @@ export interface ScheduleRun { error_message?: string | null; excel_file_name?: string | null; excel_file_size?: number | null; + kb_sync_status?: string | null; + kb_group_id?: number | null; + kb_document_id?: number | null; + kb_document_version_id?: number | null; + kb_sync_job_id?: number | null; + kb_sync_error?: string | null; wecom_notified: boolean; wecom_notified_at?: string | null; wecom_notify_error?: string | null; @@ -77,6 +85,9 @@ async function getJson(url: string): Promise { export const listAdminSchedules = () => getJson('/api/admin/schedules'); +export const getAdminSchedule = (taskId: number) => + getJson(`/api/admin/schedules/${taskId}`); + export const exportAdminScheduleUrl = (taskId: number) => `/api/admin/schedules/${taskId}/export`; export const importAdminSchedules = async (payload: any) => { @@ -127,9 +138,20 @@ export interface TestScheduleRunResult { step_logs: StepLog[]; dify_agent_id: number | null; dify_execution_snapshot?: DifyExecutionSnapshot | null; + kb_sync_status?: string | null; + kb_sync_error?: string | null; + kb_document_id?: number | null; } -export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) => +export const testAdminScheduleRun = ( + taskId: number, + payload: { + fetch_where_conditions?: string; + fetch_order_by?: string; + limit?: number; + kb_sync_enabled?: boolean; + }, +) => requestJson(`/api/admin/schedule-config/${taskId}/test-run`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, diff --git a/frontend/src/api/shippingNotice.ts b/frontend/src/api/shippingNotice.ts index f32c2fef..b74d3d5b 100644 --- a/frontend/src/api/shippingNotice.ts +++ b/frontend/src/api/shippingNotice.ts @@ -153,9 +153,10 @@ export interface ShippingNoticeUploadResponse { human_options?: string[]; } -export async function createWorkspaceShippingTaskFromNotice(file: File) { +export async function createWorkspaceShippingTaskFromNotice(file: File, conversationId?: string) { const form = new FormData(); form.append('file', file); + if (conversationId) form.append('conversation_id', conversationId); const headers = getAuthHeaders(); delete (headers as Record)['Content-Type']; const res = await fetch('/api/workspace/shipping-tasks/create-from-notice', { diff --git a/frontend/src/features/admin/modules/schedules/SchedulesPage.vue b/frontend/src/features/admin/modules/schedules/SchedulesPage.vue index a8ecc467..7bf885a4 100644 --- a/frontend/src/features/admin/modules/schedules/SchedulesPage.vue +++ b/frontend/src/features/admin/modules/schedules/SchedulesPage.vue @@ -15,17 +15,20 @@ const admin = useSchedulesAdmin(); onMounted(() => { void admin.loadAll(); }); const { - agents, users, schedules, selectedScheduleRuns, scheduleLoading, scheduleRunsLoading, + agents, users, kbGroups, schedules, selectedScheduleRuns, scheduleLoading, scheduleRunsLoading, selectedScheduleId, scheduleRunStatusFilter, scheduleRunStartedAfter, scheduleRunStartedBefore, scheduleRunColumnDefs, scheduleViewMode, showScheduleCreateModal, scheduleCreateSaving, scheduleEditingId, scheduleCreateForm, scheduleConfigCollapsed, scheduleCronDesigner, weeklyDayOptions, scheduleCronPreview, scheduleNextRunPreview, selectedSchedule, scheduleRunStatusOptions, getScheduleRunStatusBadge, formatDateTime, expandedScheduleRunId, expandedScheduleRun, stepLabelMap, stepStatusMap, showTestRunDialog, testRunSchedule, - testRunWhere, testRunOrderBy, testRunBaseFetchSql, testRunLimit, testRunLoading, testRunResult, + testRunWhere, testRunOrderBy, testRunBaseFetchSql, testRunLimit, testRunKbSync, testRunKbSyncAvailable, + testRunKbSyncAttempted, testRunLoading, testRunResult, filteredScheduleRuns, selectedScheduleRunMetrics, selectedScheduleLatestRunAt, scheduleEnabledCount, scheduleDisabledCount, scheduleRunningCount, scheduleSqlEditForm, - scheduleTestLoading, scheduleTestResult, scheduleNotifyDropdownOpen, + scheduleTestLoading, scheduleTestResult, scheduleNotifyDropdownOpen, scheduleNotifyUserQuery, + filteredNotifyUsers, scheduleCloseNotifyDropdown, scheduleOwnerDropdownOpen, scheduleOwnerQuery, + filteredOwnerUsers, selectScheduleOwner, handleScheduleOwnerInput, scheduleCloseOwnerDropdown, showDeleteConfirmDialog, deleteConfirmTitle, deleteConfirmMessage, loadSchedules, startScheduleColResize, openScheduleCreateModal, openScheduleEditModal, openScheduleRunSubmenu, backToScheduleOverview, viewScheduleRuns, resetScheduleRunFilters, @@ -416,7 +419,7 @@ const {
@@ -661,12 +719,33 @@ const {
- -
- + +
+ +
+ {{ $t('admin.wecom.noData') }} +
@@ -927,6 +1006,21 @@ const {
+
+ +

{{ $t('admin.schedule.form.kbSyncHint') }}

+
+ + +
+
+
@@ -1045,44 +1139,53 @@ const {
- - {{ $t('admin.schedule.form.selectNotifyUsers') }} + + {{ getUserName(uid) }} + + +
-
{{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }} + +
+ {{ $t('admin.wecom.noData') }}
diff --git a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts index bca7059a..2d0d0fdf 100644 --- a/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts +++ b/frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts @@ -5,9 +5,11 @@ import { computed, ref, watch } from 'vue'; import { useI18n } from 'vue-i18n'; import { listAdminAgents, listAdminUsers } from '@/api/admin'; +import { getKbGroups, type KbGroup } from '@/api/kb'; import { createAdminSchedule, deleteAdminSchedule, + getAdminSchedule, getAdminScheduleTaskConfig, listAdminScheduleRuns, listAdminSchedules, @@ -30,6 +32,7 @@ export function useSchedulesAdmin() { const agents = ref([]); const users = ref([]); + const kbGroups = ref([]); const showDeleteConfirmDialog = ref(false); const deleteConfirmTitle = ref(''); @@ -81,6 +84,15 @@ export function useSchedulesAdmin() { } }; + const loadKbGroups = async (): Promise => { + try { + kbGroups.value = await getKbGroups(); + } catch (e) { + console.error('Failed to load kb groups', e); + kbGroups.value = []; + } + }; + const schedules = ref([]); const schedulesLoaded = ref(false); void schedulesLoaded; const selectedScheduleRuns = ref([]); @@ -164,6 +176,8 @@ const scheduleCreateForm = ref({ wait_seconds: 300, notify_enabled: true, notify_user_ids_json: [] as number[], + kb_sync_enabled: false, + kb_group_id: null as number | null, enabled: true, }); const scheduleConfigCollapsed = ref(true); @@ -331,6 +345,8 @@ const resetScheduleCreateForm = () => { wait_seconds: 300, notify_enabled: true, notify_user_ids_json: [], + kb_sync_enabled: false, + kb_group_id: null, enabled: true, }; scheduleSqlEditForm.value = { @@ -360,6 +376,10 @@ const resetScheduleCreateForm = () => { dify_system_prompt: '', }; scheduleTestResult.value = null; + scheduleNotifyUserQuery.value = ''; + scheduleNotifyDropdownOpen.value = false; + scheduleOwnerQuery.value = ''; + scheduleOwnerDropdownOpen.value = false; scheduleCronDesigner.value = { mode: 'every_minutes', every_minutes: 30, @@ -375,13 +395,16 @@ const resetScheduleCreateForm = () => { const openScheduleCreateModal = async () => { resetScheduleCreateForm(); scheduleConfigCollapsed.value = true; - await Promise.all([loadAgents(), loadUsers()]); + await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]); showScheduleCreateModal.value = true; }; const openScheduleEditModal = async (task: ScheduleTask) => { - await Promise.all([loadAgents(), loadUsers()]); + await Promise.all([loadAgents(), loadUsers(), loadKbGroups()]); scheduleConfigCollapsed.value = true; + scheduleNotifyUserQuery.value = ''; + scheduleNotifyDropdownOpen.value = false; + scheduleOwnerDropdownOpen.value = false; scheduleEditingId.value = task.id; scheduleCreateForm.value = { name: task.name || '', @@ -391,6 +414,8 @@ const openScheduleEditModal = async (task: ScheduleTask) => { wait_seconds: task.wait_seconds || 0, notify_enabled: !!task.notify_enabled, notify_user_ids_json: task.notify_user_ids_json || [], + kb_sync_enabled: !!task.kb_sync_enabled, + kb_group_id: task.kb_group_id || null, enabled: !!task.enabled, data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api', }; @@ -458,6 +483,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => { scheduleTestResult.value = null; parseCronExprToDesigner(task.cron_expr); + syncScheduleOwnerQuery(); showScheduleCreateModal.value = true; }; @@ -484,9 +510,14 @@ const getScheduleRunStatusBadge = (status: string) => { return map[status] || { cls: 'bg-surface-soft text-secondary', label: status }; }; +const parseApiUtcDate = (iso: string) => { + const normalized = /(?:Z|[+-]\d{2}:\d{2})$/i.test(iso) ? iso : `${iso}Z`; + return new Date(normalized); +}; + const formatDateTime = (iso?: string | null) => { if (!iso) return '-'; - const d = new Date(iso); + const d = parseApiUtcDate(iso); if (isNaN(d.getTime())) return iso; const pad = (n: number) => String(n).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; @@ -517,11 +548,23 @@ const testRunWhere = ref(''); const testRunOrderBy = ref(''); const testRunBaseFetchSql = ref(''); const testRunLimit = ref(3); +const testRunKbSync = ref(false); +const testRunKbSyncAttempted = ref(false); const testRunLoading = ref(false); const testRunResult = ref(null); +const testRunKbSyncAvailable = computed( + () => !!(testRunSchedule.value?.kb_group_id), +); + const openTestRunDialog = async (s: ScheduleTask) => { - testRunSchedule.value = s; + let freshTask = s; + try { + freshTask = await getAdminSchedule(s.id); + } catch { + // 列表数据兜底 + } + testRunSchedule.value = freshTask; try { const result = await getAdminScheduleTaskConfig(s.id); const cfg = result.config; @@ -534,6 +577,8 @@ const openTestRunDialog = async (s: ScheduleTask) => { testRunBaseFetchSql.value = ''; } testRunLimit.value = 3; + testRunKbSync.value = !!(freshTask.kb_group_id && freshTask.kb_sync_enabled); + testRunKbSyncAttempted.value = false; testRunResult.value = null; testRunLoading.value = false; showTestRunDialog.value = true; @@ -544,11 +589,13 @@ const handleTestRun = async () => { if (!s?.id) return; testRunLoading.value = true; testRunResult.value = null; + testRunKbSyncAttempted.value = testRunKbSync.value; try { const result = await testAdminScheduleRun(s.id, { fetch_where_conditions: testRunWhere.value, fetch_order_by: testRunOrderBy.value, limit: testRunLimit.value, + kb_sync_enabled: testRunKbSync.value, }); testRunResult.value = result; await loadSchedules(); @@ -580,9 +627,10 @@ const selectedScheduleRunMetrics = computed(() => { ); }); -const selectedScheduleLatestRunAt = computed( - () => selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at || '-' -); +const selectedScheduleLatestRunAt = computed(() => { + const raw = selectedScheduleRuns.value[0]?.started_at || selectedSchedule.value?.last_run_at; + return raw ? formatDateTime(raw) : '-'; +}); const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length); const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length); @@ -662,6 +710,78 @@ const handleTestScheduleSql = async () => { }; const scheduleNotifyDropdownOpen = ref(false); +const scheduleNotifyUserQuery = ref(''); +let scheduleNotifyCloseTimer: ReturnType | null = null; + +const filteredNotifyUsers = computed(() => { + const keyword = scheduleNotifyUserQuery.value.trim().toLowerCase(); + return users.value.filter((u) => { + if (!keyword) return true; + return [u.real_name, u.username, u.employee_id, String(u.id)] + .filter(Boolean) + .some((val) => String(val).toLowerCase().includes(keyword)); + }); +}); + +const scheduleCloseNotifyDropdown = (): void => { + if (scheduleNotifyCloseTimer) clearTimeout(scheduleNotifyCloseTimer); + scheduleNotifyCloseTimer = setTimeout(() => { + scheduleNotifyDropdownOpen.value = false; + }, 150); +}; + +const scheduleOwnerDropdownOpen = ref(false); +const scheduleOwnerQuery = ref(''); +let scheduleOwnerCloseTimer: ReturnType | null = null; + +const formatUserOptionLabel = (u: AdminUserRow) => + `${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`; + +const filteredOwnerUsers = computed(() => { + const keyword = scheduleOwnerQuery.value.trim().toLowerCase(); + return users.value.filter((u) => { + if (!keyword) return true; + return [u.real_name, u.username, u.employee_id, String(u.id)] + .filter(Boolean) + .some((val) => String(val).toLowerCase().includes(keyword)); + }); +}); + +const syncScheduleOwnerQuery = (): void => { + const ownerId = scheduleCreateForm.value.owner_user_id; + if (!ownerId) { + scheduleOwnerQuery.value = ''; + return; + } + const u = users.value.find((x) => x.id === ownerId); + scheduleOwnerQuery.value = u ? formatUserOptionLabel(u) : String(ownerId); +}; + +const selectScheduleOwner = (id: number): void => { + const u = users.value.find((x) => x.id === id); + if (!u) return; + scheduleCreateForm.value.owner_user_id = id; + scheduleOwnerQuery.value = formatUserOptionLabel(u); + scheduleOwnerDropdownOpen.value = false; +}; + +const handleScheduleOwnerInput = (): void => { + scheduleOwnerDropdownOpen.value = true; + const ownerId = scheduleCreateForm.value.owner_user_id; + if (!ownerId) return; + const u = users.value.find((x) => x.id === ownerId); + const currentLabel = u ? formatUserOptionLabel(u) : ''; + if (scheduleOwnerQuery.value.trim() !== currentLabel) { + scheduleCreateForm.value.owner_user_id = null; + } +}; + +const scheduleCloseOwnerDropdown = (): void => { + if (scheduleOwnerCloseTimer) clearTimeout(scheduleOwnerCloseTimer); + scheduleOwnerCloseTimer = setTimeout(() => { + scheduleOwnerDropdownOpen.value = false; + }, 150); +}; watch(() => scheduleCreateForm.value.dify_agent_id, (agentId) => { if (!agentId) { @@ -760,6 +880,8 @@ const createSchedule = async () => { dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined, notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [], notify_enabled: scheduleCreateForm.value.notify_enabled, + kb_sync_enabled: scheduleCreateForm.value.kb_sync_enabled, + kb_group_id: scheduleCreateForm.value.kb_sync_enabled ? scheduleCreateForm.value.kb_group_id : null, enabled: scheduleCreateForm.value.enabled, data_source_type: dst, config: configPayload, @@ -808,8 +930,12 @@ const viewScheduleRuns = async (taskId: number) => { try { const params: { status?: string; started_after?: string; started_before?: string } = {}; if (scheduleRunStatusFilter.value !== 'all') params.status = scheduleRunStatusFilter.value; - if (scheduleRunStartedAfter.value) params.started_after = scheduleRunStartedAfter.value; - if (scheduleRunStartedBefore.value) params.started_before = scheduleRunStartedBefore.value; + if (scheduleRunStartedAfter.value) { + params.started_after = new Date(scheduleRunStartedAfter.value).toISOString(); + } + if (scheduleRunStartedBefore.value) { + params.started_before = new Date(scheduleRunStartedBefore.value).toISOString(); + } selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params); } finally { scheduleRunsLoading.value = false; @@ -898,6 +1024,7 @@ const deleteSchedule = (task: ScheduleTask) => { return { agents, users, + kbGroups, schedules, selectedScheduleRuns, scheduleLoading, @@ -931,6 +1058,9 @@ const deleteSchedule = (task: ScheduleTask) => { testRunOrderBy, testRunBaseFetchSql, testRunLimit, + testRunKbSync, + testRunKbSyncAvailable, + testRunKbSyncAttempted, testRunLoading, testRunResult, filteredScheduleRuns, @@ -943,6 +1073,15 @@ const deleteSchedule = (task: ScheduleTask) => { scheduleTestLoading, scheduleTestResult, scheduleNotifyDropdownOpen, + scheduleNotifyUserQuery, + filteredNotifyUsers, + scheduleCloseNotifyDropdown, + scheduleOwnerDropdownOpen, + scheduleOwnerQuery, + filteredOwnerUsers, + selectScheduleOwner, + handleScheduleOwnerInput, + scheduleCloseOwnerDropdown, showDeleteConfirmDialog, deleteConfirmTitle, deleteConfirmMessage, diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index e3aee42e..91c0907f 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1203,6 +1203,11 @@ const messages = { nextRun: 'Next run', notifyEnabled: 'Enable notifications', selectNotifyUsers: 'Select notification recipients...', + kbSyncEnabled: 'Sync result Excel to knowledge base', + kbSyncHint: 'After successful or partially successful runs, the generated Excel will be added to the selected knowledge base group.', + kbGroup: 'Knowledge base group', + selectKbGroup: 'Select knowledge base group...', + noKbGroups: 'No knowledge base groups available', enableOnCreate: 'Enable after creation', cancel: 'Cancel', saving: 'Saving...', @@ -1227,7 +1232,11 @@ const messages = { errors: 'Errors ({count})', queryResult: 'Query result', resultSummary: '{total} total, showing {showing}', - viewGeneratedSql: 'View generated SQL' + viewGeneratedSql: 'View generated SQL', + writeToKb: 'Write to knowledge base', + writeToKbHint: 'After a successful or partially successful test run, sync the Excel result to the schedule knowledge base group.', + noKbGroupHint: 'Enable knowledge base sync and select a group in schedule settings first.', + kbSyncNoStatus: 'Knowledge base sync was requested but no status was returned. Check backend logs or schedule KB settings.' }, status: { all: 'All', @@ -1253,6 +1262,11 @@ const messages = { callInternalApi: 'Call internal API', preDify: 'Dify pre-processing' }, + kbSync: { + title: 'Knowledge base sync', + status: 'Status', + document: 'Document ID' + }, deleteDialogTitle: 'Delete Schedule', deleteConfirmMessage: 'Confirm deleting schedule \"{name}\"?', msg: { @@ -2771,6 +2785,11 @@ const messages = { nextRun: '下次执行', notifyEnabled: '启用通知', selectNotifyUsers: '选择通知人员...', + kbSyncEnabled: '同步结果 Excel 至知识库', + kbSyncHint: '排程成功或部分成功后,会把生成的 Excel 加入所选知识库分组。', + kbGroup: '知识库分组', + selectKbGroup: '选择知识库分组...', + noKbGroups: '暂无可用知识库分组', enableOnCreate: '创建后启用', cancel: '取消', saving: '保存中...', @@ -2795,7 +2814,11 @@ const messages = { errors: '错误信息 ({count})', queryResult: '查询结果', resultSummary: '共 {total} 条,展示 {showing} 条', - viewGeneratedSql: '查看生成 SQL' + viewGeneratedSql: '查看生成 SQL', + writeToKb: '写入知识库', + writeToKbHint: '测试成功或部分成功后,将 Excel 结果同步至排程已配置的知识库分组。', + noKbGroupHint: '请先在排程编辑中启用知识库同步并选择分组。', + kbSyncNoStatus: '已请求写入知识库,但未返回同步状态,请检查排程知识库配置或后端日志。' }, status: { all: '全部状态', @@ -2821,6 +2844,11 @@ const messages = { callInternalApi: '调用内部API', preDify: 'Dify前处理' }, + kbSync: { + title: '知识库同步', + status: '状态', + document: '文档 ID' + }, deleteDialogTitle: '删除排程', deleteConfirmMessage: '确认删除排程「{name}」?', msg: { @@ -4186,6 +4214,13 @@ const messages = { // Common Messages schedule: { + form: { + kbSyncEnabled: '同步結果 Excel 至知識庫', + kbSyncHint: '排程成功或部分成功後,會把生成的 Excel 加入所選知識庫分組。', + kbGroup: '知識庫分組', + selectKbGroup: '選擇知識庫分組...', + noKbGroups: '暫無可用知識庫分組' + }, status: { all: '全部狀態', success: '成功', @@ -4210,6 +4245,17 @@ const messages = { callInternalApi: '調用內部API', preDify: 'Dify前處理' }, + kbSync: { + title: '知識庫同步', + status: '狀態', + document: '文件 ID' + }, + testRun: { + writeToKb: '寫入知識庫', + writeToKbHint: '測試成功或部分成功後,將 Excel 結果同步至排程已配置的知識庫分組。', + noKbGroupHint: '請先在排程編輯中啟用知識庫同步並選擇分組。', + kbSyncNoStatus: '已請求寫入知識庫,但未返回同步狀態,請檢查排程知識庫配置或後端日誌。' + }, deleteDialogTitle: '刪除排程', deleteConfirmMessage: '確認刪除排程「{name}」?', msg: { @@ -5465,6 +5511,13 @@ const messages = { // Common Messages schedule: { + form: { + kbSyncEnabled: 'ซิงค์ Excel ผลลัพธ์ไปยังคลังความรู้', + kbSyncHint: 'เมื่อรันสำเร็จหรือสำเร็จบางส่วน ระบบจะเพิ่ม Excel ที่สร้างขึ้นไปยังกลุ่มคลังความรู้ที่เลือก', + kbGroup: 'กลุ่มคลังความรู้', + selectKbGroup: 'เลือกกลุ่มคลังความรู้...', + noKbGroups: 'ไม่มีกลุ่มคลังความรู้ที่ใช้งานได้' + }, status: { all: 'ทุกสถานะ', success: 'สำเร็จ', @@ -5489,6 +5542,17 @@ const messages = { callInternalApi: 'เรียกใช้ API ภายใน', preDify: 'ประมวลผลก่อน Dify' }, + kbSync: { + title: 'การซิงค์คลังความรู้', + status: 'สถานะ', + document: 'รหัสเอกสาร' + }, + testRun: { + writeToKb: 'เขียนไปยังคลังความรู้', + writeToKbHint: 'หลังทดสอบสำเร็จหรือสำเร็จบางส่วน จะซิงค์ Excel ไปยังกลุ่มคลังความรู้ของตารางเวลา', + noKbGroupHint: 'โปรดเปิดใช้การซิงค์คลังความรู้และเลือกกลุ่มในการแก้ไขตารางเวลาก่อน', + kbSyncNoStatus: 'มีการขอเขียนคลังความรู้แล้ว แต่ไม่ได้รับสถานะซิงค์ โปรดตรวจการตั้งค่าคลังความรู้หรือบันทึก backend' + }, deleteDialogTitle: 'ลบตารางเวลา', deleteConfirmMessage: 'ยืนยันการลบตารางเวลา \"{name}\"?', msg: { diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 7cf91761..8858f476 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -3017,7 +3017,10 @@ const handleShippingAutoUploadFile = async (file: File) => { if (kind === 'inventory') { let taskId = getActiveShippingTaskId(); if (!taskId) { - const created = await createWorkspaceShippingTask({ source_type: 'manual' }); + const created = await createWorkspaceShippingTask({ + source_type: 'manual', + conversation_id: String(conversationId.value || '').trim() || undefined, + }); taskId = String(created.task_id || '').trim(); if (!taskId) { msg.warning('自动创建发货任务失败'); @@ -3030,7 +3033,10 @@ const handleShippingAutoUploadFile = async (file: File) => { return; } - const result = await createWorkspaceShippingTaskFromNotice(file); + const result = await createWorkspaceShippingTaskFromNotice( + file, + String(conversationId.value || '').trim() || undefined, + ); const taskId = String(result.task_id || '').trim(); if (taskId) resolvedShippingTaskId.value = taskId; const hint = String(result.message || '').trim();