From 2d7bdecc4336f77b3e464b4b3966bc35dcae2252 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 1 Jun 2026 21:22:22 +0800 Subject: [PATCH 1/8] =?UTF-8?q?feat(shipping-notice):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E8=B4=A7=E4=BB=A3=E5=8F=91=E8=B4=A7=E9=80=9A=E7=9F=A5=E5=85=A8?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E4=B8=9A=E5=8A=A1=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增后端完整业务支持:数据库模型、API接口、核心服务与RPA对接逻辑 - 新增前端工作台页面、路由适配与多语言国际化 - 新增Dify自定义工具OpenAPI规范、Agent配置脚本与部署文档 - 新增发货Excel模板生成脚本与默认模板 - 修复测试配置文件中的环境变量命名错误 - 更新本地开发环境变量配置 --- .env.dev | 13 +- backend/app/__init__.py | 4 + backend/app/api/shipping_notice_tools.py | 144 +++++ backend/app/api/workspace_shipping_notice.py | 60 ++ backend/app/config.py | 14 + backend/app/models.py | 61 ++- .../app/services/shipping_notice/__init__.py | 0 .../shipping_notice/agent_resolver.py | 20 + .../app/services/shipping_notice/export.py | 94 ++++ .../app/services/shipping_notice/extract.py | 81 +++ .../shipping_notice/inventory_snapshot.py | 80 +++ backend/app/services/shipping_notice/match.py | 65 +++ .../services/shipping_notice/openapi_spec.py | 163 ++++++ .../services/shipping_notice/query_service.py | 72 +++ backend/app/services/shipping_notice/rpa.py | 94 ++++ .../services/shipping_notice/tool_response.py | 23 + backend/app/services/shipping_notice/tools.py | 518 ++++++++++++++++++ ...t_SN-20260601-3E31F63B_20260601112744.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-72B96411_20260601112745.xlsx | Bin 0 -> 5022 bytes ...t_SN-20260601-AF7CFD94_20260601112831.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-B63171EA_20260601112802.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-BB77BCD8_20260601112817.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-D6697279_20260601113529.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-D95651FB_20260601112758.xlsx | Bin 0 -> 5022 bytes ...t_SN-20260601-DE45474D_20260601112816.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-E0F355C5_20260601113530.xlsx | Bin 0 -> 5021 bytes ...t_SN-20260601-F58C2DCF_20260601112832.xlsx | Bin 0 -> 5021 bytes .../d8e9f0a1b2c3_add_shipping_cases.py | 73 +++ .../scripts/export_shipping_notice_openapi.py | 32 ++ .../generate_freight_shipment_template.py | 35 ++ backend/seed_shipping_notice_agents.py | 77 +++ .../templates/freight_shipment_upload.xlsx | Bin 0 -> 4966 bytes backend/tests/conftest.py | 2 +- backend/tests/test_shipping_notice_tools.py | 222 ++++++++ docs/openapi/shipping_notice_tools.dify.json | 445 +++++++++++++++ docs/shipping_notice_dify_openapi_setup.md | 211 +++++++ docs/shipping_notice_dify_prompt.md | 90 +++ docs/shipping_notice_runbook.md | 93 ++++ frontend/src/api/shippingNotice.ts | 60 ++ frontend/src/i18n.ts | 74 ++- frontend/src/router/index.ts | 7 + frontend/src/views/ChatView.vue | 8 + frontend/src/views/ShippingNoticeView.vue | 271 +++++++++ frontend/src/views/WorkspaceView.vue | 23 +- scripts/rpa/README.md | 37 ++ scripts/rpa/freight_rpa_worker.py | 203 +++++++ 46 files changed, 3462 insertions(+), 7 deletions(-) create mode 100644 backend/app/api/shipping_notice_tools.py create mode 100644 backend/app/api/workspace_shipping_notice.py create mode 100644 backend/app/services/shipping_notice/__init__.py create mode 100644 backend/app/services/shipping_notice/agent_resolver.py create mode 100644 backend/app/services/shipping_notice/export.py create mode 100644 backend/app/services/shipping_notice/extract.py create mode 100644 backend/app/services/shipping_notice/inventory_snapshot.py create mode 100644 backend/app/services/shipping_notice/match.py create mode 100644 backend/app/services/shipping_notice/openapi_spec.py create mode 100644 backend/app/services/shipping_notice/query_service.py create mode 100644 backend/app/services/shipping_notice/rpa.py create mode 100644 backend/app/services/shipping_notice/tool_response.py create mode 100644 backend/app/services/shipping_notice/tools.py create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-3E31F63B_20260601112744.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-72B96411_20260601112745.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-AF7CFD94_20260601112831.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-B63171EA_20260601112802.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-BB77BCD8_20260601112817.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-D6697279_20260601113529.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-D95651FB_20260601112758.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-DE45474D_20260601112816.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-E0F355C5_20260601113530.xlsx create mode 100644 backend/backend/data/shipping_notice/exports/shipment_SN-20260601-F58C2DCF_20260601112832.xlsx create mode 100644 backend/migrations/versions/d8e9f0a1b2c3_add_shipping_cases.py create mode 100644 backend/scripts/export_shipping_notice_openapi.py create mode 100644 backend/scripts/generate_freight_shipment_template.py create mode 100644 backend/seed_shipping_notice_agents.py create mode 100644 backend/templates/freight_shipment_upload.xlsx create mode 100644 backend/tests/test_shipping_notice_tools.py create mode 100644 docs/openapi/shipping_notice_tools.dify.json create mode 100644 docs/shipping_notice_dify_openapi_setup.md create mode 100644 docs/shipping_notice_dify_prompt.md create mode 100644 docs/shipping_notice_runbook.md create mode 100644 frontend/src/api/shippingNotice.ts create mode 100644 frontend/src/views/ShippingNoticeView.vue create mode 100644 scripts/rpa/README.md create mode 100644 scripts/rpa/freight_rpa_worker.py diff --git a/.env.dev b/.env.dev index 5ac490a6..9eccc536 100644 --- a/.env.dev +++ b/.env.dev @@ -35,7 +35,7 @@ CASDOOR_SCOPE=openid profile email CASDOOR_WECOM_PROVIDER_HINT=wecom # 知识库 Dify 对接 -PUBLIC_BASE_URL=http://192.168.100.192:8891 +PUBLIC_BASE_URL=http://192.168.100.192:8890 DIFY_API_BASE=http://192.168.100.192:8882/v1 DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF DEFAULT_ADMIN_USERNAME=admin @@ -54,3 +54,14 @@ MINIO_ACCESS_KEY=minio_testing_admin MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx MINIO_SECURE=false MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 + +# 货代发货通知 Agent +SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh +# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL) +SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890 +SHIPPING_NOTICE_STORAGE_ROOT=backend/data/shipping_notice +FREIGHT_INVENTORY_DROP_DIR=backend/data/freight_rpa/inventory_drop +FREIGHT_RPA_INVENTORY_TRIGGER_DIR=backend/data/freight_rpa/inventory_triggers +FREIGHT_UPLOAD_QUEUE_DIR=backend/data/freight_rpa/upload_queue +FREIGHT_RPA_UPLOAD_TRIGGER_DIR=backend/data/freight_rpa/upload_triggers +FREIGHT_SHIPMENT_TEMPLATE_PATH=backend/templates/freight_shipment_upload.xlsx diff --git a/backend/app/__init__.py b/backend/app/__init__.py index f8837109..39282c64 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -53,7 +53,9 @@ def create_app(config_name='default'): from app.api.integration import integration_bp from app.api.schedule_admin import schedule_admin_bp from app.api.workspace_schedule import workspace_schedule_bp + from app.api.workspace_shipping_notice import workspace_shipping_notice_bp from app.api.internal_jobs import internal_jobs_bp + from app.api.shipping_notice_tools import shipping_notice_bp # 聊天相关接口 app.register_blueprint(chat_bp, url_prefix='/api/chat') @@ -69,7 +71,9 @@ def create_app(config_name='default'): app.register_blueprint(integration_bp, url_prefix='/api/integration') app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') # Eagerly load persisted runtime settings so the very first request after # a worker boot already sees the admin-saved configuration (otherwise the diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py new file mode 100644 index 00000000..296f2746 --- /dev/null +++ b/backend/app/api/shipping_notice_tools.py @@ -0,0 +1,144 @@ +""" +货代发货通知 Tool API — 供 Dify Chatflow Agent 调用 +""" +from __future__ import annotations + +from flask import Blueprint, current_app, jsonify, request, send_file +from pathlib import Path + +from app.services.shipping_notice import tools as shipping_tools +from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec + +shipping_notice_bp = Blueprint("shipping_notice", __name__) + + +def _tool_api_base_url() -> str: + """Base URL for OpenAPI servers — hxops backend, NOT Dify (8882).""" + configured = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_BASE") or "").strip().rstrip("/") + if configured: + return configured + configured = str(current_app.config.get("PUBLIC_BASE_URL") or "").strip().rstrip("/") + if configured: + return configured + host = request.host_url.rstrip("/") if request else "" + return host + + +def _dify_openapi_spec() -> dict: + return build_dify_openapi_spec(_tool_api_base_url()) + + +def _require_tool_key(): + configured = ( + str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip() + or str(current_app.config.get("INTEGRATION_API_KEY") or "").strip() + ) + if not configured: + return jsonify({"error": "SHIPPING_NOTICE_TOOL_API_KEY is not configured"}), 503 + + incoming = ( + str(request.headers.get("X-Shipping-Tool-Key") or "").strip() + or str(request.headers.get("X-Integration-Key") or "").strip() + ) + if incoming and incoming == configured: + return None + return jsonify({"error": "Unauthorized"}), 401 + + +def _payload() -> dict: + return request.get_json(silent=True) or {} + + +@shipping_notice_bp.before_request +def _auth_tools(): + if request.endpoint in { + "shipping_notice.openapi_spec", + "shipping_notice.openapi_dify_yaml", + "shipping_notice.download_case_export", + }: + return None + err = _require_tool_key() + if err: + return err + return None + + +@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"]) +def openapi_spec(): + return jsonify(_dify_openapi_spec()) + + +@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"]) +def openapi_dify_yaml(): + import yaml + + body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False) + return current_app.response_class(body, mimetype="text/yaml; charset=utf-8") + + +@shipping_notice_bp.route("/tools/create_case", methods=["POST"]) +def tool_create_case(): + return jsonify(shipping_tools.create_case(_payload())) + + +@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"]) +def tool_parse_notice(): + return jsonify(shipping_tools.parse_notice(_payload())) + + +@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"]) +def tool_ensure_inventory(): + return jsonify(shipping_tools.ensure_inventory(_payload())) + + +@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"]) +def tool_match_inventory(): + return jsonify(shipping_tools.match_inventory(_payload())) + + +@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"]) +def tool_submit_decision(): + return jsonify(shipping_tools.submit_decision(_payload())) + + +@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"]) +def tool_generate_shipment_excel(): + return jsonify(shipping_tools.generate_excel(_payload())) + + +@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"]) +def tool_upload_to_freight(): + return jsonify(shipping_tools.upload_to_freight(_payload())) + + +@shipping_notice_bp.route("/tools/get_case_status", methods=["POST"]) +def tool_get_case_status(): + return jsonify(shipping_tools.get_case_status(_payload())) + + +@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"]) +def rpa_inventory_ready(): + return jsonify(shipping_tools.rpa_report_inventory(_payload())) + + +@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"]) +def rpa_upload_complete(): + return jsonify(shipping_tools.rpa_report_upload(_payload())) + + +@shipping_notice_bp.route("/cases//export", methods=["GET"]) +def download_case_export(case_no: str): + from app.services.shipping_notice.tools import _get_case + + case = _get_case(case_no) + if not case or not case.export_file_path: + return jsonify({"error": "export file not found"}), 404 + path = Path(case.export_file_path) + if not path.is_file(): + return jsonify({"error": "export file missing on disk"}), 404 + return send_file( + path, + as_attachment=True, + download_name=case.export_file_name or path.name, + mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) diff --git a/backend/app/api/workspace_shipping_notice.py b/backend/app/api/workspace_shipping_notice.py new file mode 100644 index 00000000..cd40fb07 --- /dev/null +++ b/backend/app/api/workspace_shipping_notice.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from flask import Blueprint, jsonify, request, send_file +from pathlib import Path + +from app.auth_jwt import get_current_user +from app.services.shipping_notice.query_service import ( + get_case_for_user, + list_cases_for_user, + serialize_case_detail, +) + +workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) + + +def _require_user(): + user = get_current_user() + if not user: + return None, (jsonify({"error": "Unauthorized"}), 401) + return user, None + + +@workspace_shipping_notice_bp.route("/shipping-cases", methods=["GET"]) +def workspace_shipping_cases(): + user, err = _require_user() + if err: + return err + process_status = str(request.args.get("process_status") or "").strip() or None + limit = int(request.args.get("limit") or 100) + return jsonify(list_cases_for_user(user.id, process_status=process_status, limit=limit)) + + +@workspace_shipping_notice_bp.route("/shipping-cases/", methods=["GET"]) +def workspace_shipping_case_detail(case_no: str): + user, err = _require_user() + if err: + return err + case = get_case_for_user(case_no, user.id) + if not case: + return jsonify({"error": "Not found"}), 404 + return jsonify(serialize_case_detail(case)) + + +@workspace_shipping_notice_bp.route("/shipping-cases//export", methods=["GET"]) +def workspace_shipping_case_export(case_no: str): + user, err = _require_user() + if err: + return err + case = get_case_for_user(case_no, user.id) + if not case or not case.export_file_path: + return jsonify({"error": "export file not found"}), 404 + path = Path(case.export_file_path) + if not path.is_file(): + return jsonify({"error": "export file missing on disk"}), 404 + return send_file( + path, + as_attachment=True, + download_name=case.export_file_name or path.name, + mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) diff --git a/backend/app/config.py b/backend/app/config.py index e4bde29b..66e39288 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -90,6 +90,20 @@ class Config: INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE') INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY') + # 货代发货通知 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') + SHIPPING_NOTICE_STORAGE_ROOT = os.getenv('SHIPPING_NOTICE_STORAGE_ROOT') + SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float( + os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7' + ) + FREIGHT_INVENTORY_DROP_DIR = os.getenv('FREIGHT_INVENTORY_DROP_DIR') + FREIGHT_RPA_INVENTORY_TRIGGER_DIR = os.getenv('FREIGHT_RPA_INVENTORY_TRIGGER_DIR') + FREIGHT_UPLOAD_QUEUE_DIR = os.getenv('FREIGHT_UPLOAD_QUEUE_DIR') + FREIGHT_RPA_UPLOAD_TRIGGER_DIR = os.getenv('FREIGHT_RPA_UPLOAD_TRIGGER_DIR') + FREIGHT_SHIPMENT_TEMPLATE_PATH = os.getenv('FREIGHT_SHIPMENT_TEMPLATE_PATH') + # WeCom (企业微信) 登录配置 WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true' WECOM_CORP_ID = os.getenv('WECOM_CORP_ID') diff --git a/backend/app/models.py b/backend/app/models.py index 6f8ca90c..02b850a2 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,6 +1,6 @@ from datetime import datetime from typing import Optional, List -from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, text +from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, Float, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app import db from werkzeug.security import generate_password_hash, check_password_hash @@ -679,3 +679,62 @@ class ScheduleRun(Base): task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id]) + +class ShippingCase(Base): + """货代发货通知 case(Chatflow Tool 编排状态机)""" + __tablename__ = 'shipping_cases' + __table_args__ = ( + Index('ix_shipping_cases_user_status', 'user_id', 'process_status'), + Index('ix_shipping_cases_conversation', 'conversation_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + case_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) + user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) + conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) + source_type: Mapped[str] = mapped_column(String(32), default='manual') + + raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list) + parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) + + process_status: Mapped[str] = mapped_column(String(32), default='created', index=True) + review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True) + inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + + export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + events: Mapped[List["ShippingCaseEvent"]] = relationship( + "ShippingCaseEvent", + back_populates="case", + cascade="all, delete-orphan", + ) + + +class ShippingCaseEvent(Base): + """发货 case 审计事件""" + __tablename__ = 'shipping_case_events' + + id: Mapped[int] = mapped_column(primary_key=True) + case_id: Mapped[int] = mapped_column(ForeignKey('shipping_cases.id'), index=True) + event_type: Mapped[str] = mapped_column(String(64), index=True) + detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + + case: Mapped["ShippingCase"] = relationship("ShippingCase", back_populates="events") + diff --git a/backend/app/services/shipping_notice/__init__.py b/backend/app/services/shipping_notice/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/app/services/shipping_notice/agent_resolver.py b/backend/app/services/shipping_notice/agent_resolver.py new file mode 100644 index 00000000..eca6dd85 --- /dev/null +++ b/backend/app/services/shipping_notice/agent_resolver.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from app.models import Agent + +EXTRACT_AGENT_NAME = "发货通知字段抽取" +CHAT_AGENT_NAME = "货代发货通知 Agent" + + +def resolve_extract_agent() -> Agent | None: + agent = Agent.query.filter_by(name=EXTRACT_AGENT_NAME, is_active=True).first() + if not agent or not agent.dify_api_key: + return None + app_type = (agent.extra_config or {}).get("dify_app_type") + if app_type and app_type != "workflow": + return None + return agent + + +def resolve_chat_agent() -> Agent | None: + return Agent.query.filter_by(name=CHAT_AGENT_NAME, is_active=True).first() diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py new file mode 100644 index 00000000..28c877ed --- /dev/null +++ b/backend/app/services/shipping_notice/export.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import os +from datetime import datetime +from pathlib import Path +from shutil import copy2 + +from flask import current_app +from openpyxl import Workbook, load_workbook + +from app.models import ShippingCase + +DEFAULT_HEADERS = [ + "客户名称", + "客户代码", + "收货地址", + "要求交期", + "料号", + "发货数量", + "单位", + "备注", +] + + +def _storage_root() -> Path: + root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip() + if root: + return Path(root) + return Path(current_app.instance_path) / "shipping_notice" + + +def _default_template_path() -> Path | None: + configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip() + if configured: + path = Path(configured) + if path.is_file(): + return path + bundled = Path(__file__).resolve().parents[2] / "templates" / "freight_shipment_upload.xlsx" + return bundled if bundled.is_file() else None + + +def _row_values(case: ShippingCase, line: dict | None) -> list: + line = line or {} + return [ + case.customer_name or "", + case.customer_code or "", + case.ship_to or "", + case.required_date or "", + line.get("sku") or "", + line.get("qty") or "", + line.get("uom") or "EA", + line.get("remark") or "", + ] + + +def _fill_from_template(case: ShippingCase, path: Path) -> None: + wb = load_workbook(filename=str(path)) + ws = wb.active + lines = case.lines_json or [None] + start_row = ws.max_row + 1 if ws.max_row >= 1 else 2 + if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)): + ws.append(DEFAULT_HEADERS) + start_row = 2 + for line in lines: + ws.append(_row_values(case, line)) + wb.save(path) + + +def _fill_blank_workbook(case: ShippingCase, path: Path) -> None: + wb = Workbook() + ws = wb.active + ws.title = "Shipment" + ws.append(DEFAULT_HEADERS) + lines = case.lines_json or [None] + for line in lines: + ws.append(_row_values(case, line)) + wb.save(path) + + +def generate_shipment_excel(case: ShippingCase) -> tuple[str, str]: + root = _storage_root() / "exports" + root.mkdir(parents=True, exist_ok=True) + + filename = f"shipment_{case.case_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx" + path = root / filename + + template = _default_template_path() + if template: + copy2(template, path) + _fill_from_template(case, path) + else: + _fill_blank_workbook(case, path) + + return str(path), filename diff --git a/backend/app/services/shipping_notice/extract.py b/backend/app/services/shipping_notice/extract.py new file mode 100644 index 00000000..e970b582 --- /dev/null +++ b/backend/app/services/shipping_notice/extract.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import json +import re +from typing import Any + +from app.services.dify import DifyService +from app.services.shipping_notice.agent_resolver import resolve_extract_agent + + +def _parse_workflow_outputs(result: dict[str, Any]) -> dict[str, Any] | None: + outputs = result.get("outputs") if isinstance(result, dict) else None + if not isinstance(outputs, dict): + data = result.get("data") if isinstance(result, dict) else None + outputs = data.get("outputs") if isinstance(data, dict) else None + if not isinstance(outputs, dict): + return None + + for key in ("result", "text", "json", "structured", "output"): + val = outputs.get(key) + if isinstance(val, dict): + return val + if isinstance(val, str) and val.strip(): + try: + parsed = json.loads(val) + if isinstance(parsed, dict): + return parsed + except json.JSONDecodeError: + continue + return outputs if outputs else None + + +def extract_notice_fields( + *, + raw_text: str, + source_type: str = "manual", + structured: dict[str, Any] | None = None, +) -> tuple[dict[str, Any], float, list[str]]: + warnings: list[str] = [] + + if structured and isinstance(structured, dict): + return structured, float(structured.get("confidence") or 0.95), warnings + + agent = resolve_extract_agent() + if agent and raw_text.strip(): + try: + result = DifyService.run_workflow_streaming( + agent=agent, + inputs={"raw_text": raw_text, "source_type": source_type}, + user="shipping_notice_tool", + ) + parsed = _parse_workflow_outputs(result) + if parsed: + confidence = float(parsed.get("confidence") or 0.85) + return parsed, confidence, warnings + warnings.append("workflow_returned_no_structured_output") + except Exception as exc: + warnings.append(f"workflow_error:{exc}") + + return _heuristic_extract(raw_text), 0.5, warnings + + +def _heuristic_extract(raw_text: str) -> dict[str, Any]: + text = str(raw_text or "").strip() + customer_name = "" + m = re.search(r"客户[::]\s*(\S+)", text) + if m: + customer_name = m.group(1) + + lines: list[dict[str, Any]] = [] + for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text): + lines.append({"sku": m.group(1), "qty": float(m.group(2)), "uom": "EA"}) + + return { + "customer_name": customer_name, + "customer_code": "", + "ship_to": "", + "required_date": "", + "lines": lines, + "confidence": 0.5 if lines else 0.3, + } diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py new file mode 100644 index 00000000..83d8f084 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_snapshot.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import json +import os +import re +import shutil +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app +from openpyxl import load_workbook + + +DEFAULT_COLUMN_MAP = { + "料号": "sku", + "SKU": "sku", + "sku": "sku", + "可用数量": "available_qty", + "可用量": "available_qty", + "available_qty": "available_qty", + "库存": "available_qty", +} + + +def _column_map() -> dict[str, str]: + raw = current_app.config.get("FREIGHT_INVENTORY_COLUMN_MAP") + if isinstance(raw, dict) and raw: + return {str(k): str(v) for k, v in raw.items()} + return DEFAULT_COLUMN_MAP + + +def parse_inventory_excel(path: Path) -> list[dict[str, Any]]: + wb = load_workbook(filename=str(path), data_only=True, read_only=True) + try: + ws = wb.active + rows = list(ws.iter_rows(values_only=True)) + finally: + wb.close() + if not rows: + return [] + + headers = [str(c or "").strip() for c in rows[0]] + col_map = _column_map() + idx_sku = idx_qty = None + for i, h in enumerate(headers): + key = col_map.get(h) or col_map.get(h.lower()) + if key == "sku": + idx_sku = i + elif key == "available_qty": + idx_qty = i + if idx_sku is None: + idx_sku = 0 + if idx_qty is None: + idx_qty = 1 if len(headers) > 1 else 0 + + lines: list[dict[str, Any]] = [] + for row in rows[1:]: + if not row: + continue + sku = str(row[idx_sku] or "").strip() if idx_sku < len(row) else "" + if not sku: + continue + try: + qty = float(row[idx_qty] if idx_qty < len(row) else 0) + except (TypeError, ValueError): + qty = 0.0 + lines.append({"sku": sku, "available_qty": qty}) + return lines + + +def ingest_inventory_file(source_path: Path, *, move_to: Path | None = None) -> list[dict[str, Any]]: + lines = parse_inventory_excel(source_path) + if move_to: + move_to.mkdir(parents=True, exist_ok=True) + target = move_to / source_path.name + if target.exists(): + target = move_to / f"{source_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{source_path.suffix}" + shutil.move(str(source_path), str(target)) + return lines diff --git a/backend/app/services/shipping_notice/match.py b/backend/app/services/shipping_notice/match.py new file mode 100644 index 00000000..7fd87d79 --- /dev/null +++ b/backend/app/services/shipping_notice/match.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import Any + + +def match_notice_lines( + notice_lines: list[dict[str, Any]], + inventory_lines: list[dict[str, Any]], +) -> tuple[str, list[dict[str, Any]], dict[str, Any]]: + inv_map: dict[str, float] = {} + for row in inventory_lines: + sku = str(row.get("sku") or "").strip() + if not sku: + continue + try: + inv_map[sku] = float(row.get("available_qty") or 0) + except (TypeError, ValueError): + inv_map[sku] = 0.0 + + line_results: list[dict[str, Any]] = [] + shortages: list[dict[str, Any]] = [] + has_partial = False + has_shortage = False + + for line in notice_lines: + sku = str(line.get("sku") or "").strip() + try: + required = float(line.get("qty") or 0) + except (TypeError, ValueError): + required = 0.0 + available = inv_map.get(sku, 0.0) + if available >= required: + line_status = "ok" + shortage = 0.0 + elif available > 0: + line_status = "partial" + shortage = required - available + has_partial = True + else: + line_status = "shortage" + shortage = required + has_shortage = True + + result = { + "sku": sku, + "required_qty": required, + "available_qty": available, + "shortage_qty": shortage, + "line_status": line_status, + } + line_results.append(result) + if shortage > 0: + shortages.append(result) + + if not notice_lines: + return "unfulfillable", line_results, {"lines": shortages} + + if has_shortage and not has_partial and all(r["line_status"] == "shortage" for r in line_results): + match_status = "unfulfillable" + elif has_partial or has_shortage: + match_status = "partial" + else: + match_status = "fulfillable" + + return match_status, line_results, {"lines": shortages} diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py new file mode 100644 index 00000000..613426cc --- /dev/null +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +from typing import Any + + +def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]: + prop: dict[str, Any] = {"type": "string", "description": description} + if enum: + prop["enum"] = enum + return prop + + +def _int_prop(description: str) -> dict[str, Any]: + return {"type": "integer", "description": description} + + +def _post_op( + operation_id: str, + summary: str, + properties: dict[str, Any], + *, + required: list[str] | None = None, +) -> dict[str, Any]: + schema: dict[str, Any] = {"type": "object", "properties": properties} + if required: + schema["required"] = required + return { + "post": { + "operationId": operation_id, + "summary": summary, + "description": summary, + "parameters": [], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": schema, + } + }, + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": {"type": "object"}, + } + }, + } + }, + "security": [{"ShippingToolKey": []}], + } + } + + +def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: + """Build OpenAPI 3.0 spec for Dify Chatflow custom tools (agent-facing only).""" + server = str(base_url or "").strip().rstrip("/") + if not server.endswith("/api/shipping-notice"): + server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice" + + case_id = _str_prop("发货任务编号,如 SN-20260529-ABCD1234") + + return { + "openapi": "3.0.0", + "info": { + "title": "Hxops Shipping Notice Tools", + "version": "1.0.0", + "description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。", + }, + "servers": [{"url": server}], + "components": { + "securitySchemes": { + "ShippingToolKey": { + "type": "apiKey", + "in": "header", + "name": "X-Shipping-Tool-Key", + "description": "与 hxops SHIPPING_NOTICE_TOOL_API_KEY 相同", + } + } + }, + "security": [{"ShippingToolKey": []}], + "paths": { + "/tools/create_case": _post_op( + "create_case", + "创建发货任务 case", + { + "user_id": _int_prop("Hxops 用户 ID(可选)"), + "conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"), + "source_type": _str_prop("来源:manual|email|wecom|pdf", enum=["manual", "email", "wecom", "pdf"]), + "raw_content": _str_prop("原始发货通知文本(可选,后续 parse 也可传入)"), + }, + ), + "/tools/parse_notice": _post_op( + "parse_notice", + "解析发货通知文本", + { + "case_id": case_id, + "raw_text": _str_prop("待解析的发货通知全文"), + }, + required=["case_id"], + ), + "/tools/ensure_inventory": _post_op( + "ensure_inventory", + "确保库存快照可用(RPA 或手工 JSON)", + { + "case_id": case_id, + "mode": _str_prop("auto=自动/RPA;retry_rpa=重试 RPA", enum=["auto", "retry_rpa"]), + "inventory_lines_json": _str_prop( + '手工库存 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]' + ), + }, + required=["case_id"], + ), + "/tools/match_inventory": _post_op( + "match_inventory", + "匹配发货需求与库存", + { + "case_id": case_id, + "inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"), + }, + required=["case_id"], + ), + "/tools/submit_decision": _post_op( + "submit_decision", + "人工复核决策", + { + "case_id": case_id, + "decision": _str_prop( + "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析", + enum=["confirm", "reject", "rematch", "reparse"], + ), + "comment": _str_prop("备注(可选)"), + }, + required=["case_id", "decision"], + ), + "/tools/generate_shipment_excel": _post_op( + "generate_shipment_excel", + "生成固定模板发货 Excel", + {"case_id": case_id}, + required=["case_id"], + ), + "/tools/upload_to_freight": _post_op( + "upload_to_freight", + "上传 Excel 到货代系统(RPA 或手工确认)", + { + "case_id": case_id, + "mode": _str_prop( + "auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成", + enum=["auto", "retry_upload", "manual_confirm"], + ), + "freight_ref_no": _str_prop("货代系统单号(manual_confirm 时填写)"), + }, + required=["case_id"], + ), + "/tools/get_case_status": _post_op( + "get_case_status", + "查询 case 当前状态与 human_options", + {"case_id": case_id}, + required=["case_id"], + ), + }, + } diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py new file mode 100644 index 00000000..98bc0b57 --- /dev/null +++ b/backend/app/services/shipping_notice/query_service.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from typing import Any + +from sqlalchemy import desc + +from app.models import ShippingCase, ShippingCaseEvent + + +def serialize_case_summary(case: ShippingCase) -> dict[str, Any]: + return { + "id": case.id, + "case_no": case.case_no, + "source_type": case.source_type, + "customer_name": case.customer_name, + "process_status": case.process_status, + "review_status": case.review_status, + "match_status": case.match_status, + "pending_human_reason": case.pending_human_reason, + "conversation_id": case.conversation_id, + "export_file_name": case.export_file_name, + "freight_ref_no": case.freight_ref_no, + "created_at": case.created_at.isoformat() if case.created_at else None, + "updated_at": case.updated_at.isoformat() if case.updated_at else None, + } + + +def serialize_case_detail(case: ShippingCase) -> dict[str, Any]: + data = serialize_case_summary(case) + data.update({ + "customer_code": case.customer_code, + "ship_to": case.ship_to, + "required_date": case.required_date, + "lines": case.lines_json or [], + "shortage": case.shortage_json, + "line_results": case.line_results_json or [], + "parse_confidence": case.parse_confidence, + "error_message": case.error_message, + "events": [ + { + "event_type": e.event_type, + "detail_json": e.detail_json, + "created_at": e.created_at.isoformat() if e.created_at else None, + } + for e in sorted(case.events or [], key=lambda x: x.created_at or "") + ], + }) + return data + + +def list_cases_for_user( + user_id: int, + *, + process_status: str | None = None, + limit: int = 100, +) -> list[dict[str, Any]]: + q = ShippingCase.query.filter( + (ShippingCase.user_id == user_id) | (ShippingCase.user_id.is_(None)) + ) + if process_status: + q = q.filter(ShippingCase.process_status == process_status) + rows = q.order_by(desc(ShippingCase.created_at)).limit(max(1, min(limit, 500))).all() + return [serialize_case_summary(c) for c in rows] + + +def get_case_for_user(case_no: str, user_id: int) -> ShippingCase | None: + case = ShippingCase.query.filter_by(case_no=case_no).first() + if not case: + return None + if case.user_id is not None and case.user_id != user_id: + return None + return case diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py new file mode 100644 index 00000000..ecee3e57 --- /dev/null +++ b/backend/app/services/shipping_notice/rpa.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import json +import shutil +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + + +def _path(key: str) -> Path | None: + value = str(current_app.config.get(key) or "").strip() + if not value: + return None + return Path(value) + + +def inventory_drop_dir() -> Path | None: + return _path("FREIGHT_INVENTORY_DROP_DIR") + + +def inventory_processed_dir() -> Path | None: + base = inventory_drop_dir() + if not base: + return None + return base / "processed" + + +def inventory_trigger_dir() -> Path | None: + return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") + + +def upload_queue_dir() -> Path | None: + return _path("FREIGHT_UPLOAD_QUEUE_DIR") + + +def upload_trigger_dir() -> Path | None: + return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR") + + +def write_inventory_export_trigger(case_no: str, payload: dict[str, Any] | None = None) -> str | None: + trigger_dir = inventory_trigger_dir() + if not trigger_dir: + return None + trigger_dir.mkdir(parents=True, exist_ok=True) + body = { + "action": "inventory_export", + "case_no": case_no, + "requested_at": datetime.utcnow().isoformat(), + **(payload or {}), + } + path = trigger_dir / f"inventory_export_{case_no}.json" + path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8") + return str(path) + + +def write_upload_trigger(case_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]: + queue = upload_queue_dir() + trigger_dir = upload_trigger_dir() + if not queue or not trigger_dir: + return None, None + queue.mkdir(parents=True, exist_ok=True) + trigger_dir.mkdir(parents=True, exist_ok=True) + + src = Path(export_file_path) + if not src.is_file(): + return None, None + dest = queue / f"{case_no}_{src.name}" + shutil.copy2(src, dest) + + body = { + "action": "shipment_upload", + "case_no": case_no, + "file_path": str(dest), + "requested_at": datetime.utcnow().isoformat(), + **(payload or {}), + } + trigger_path = trigger_dir / f"upload_{case_no}.json" + trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8") + return str(dest), str(trigger_path) + + +def find_latest_inventory_file() -> Path | None: + drop = inventory_drop_dir() + if not drop or not drop.is_dir(): + return None + candidates = [ + p for p in drop.iterdir() + if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"} + ] + if not candidates: + return None + return max(candidates, key=lambda p: p.stat().st_mtime) diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py new file mode 100644 index 00000000..51b110d0 --- /dev/null +++ b/backend/app/services/shipping_notice/tool_response.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from typing import Any + + +def tool_response( + *, + status: str, + case_id: str | None = None, + message: str = "", + data: dict[str, Any] | None = None, + human_options: list[str] | None = None, +) -> dict[str, Any]: + payload: dict[str, Any] = { + "status": status, + "message": message, + "data": data or {}, + } + if case_id: + payload["case_id"] = case_id + if human_options: + payload["human_options"] = human_options + return payload diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py new file mode 100644 index 00000000..1afeaea2 --- /dev/null +++ b/backend/app/services/shipping_notice/tools.py @@ -0,0 +1,518 @@ +from __future__ import annotations + +import uuid +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +from app import db +from app.models import ShippingCase, ShippingCaseEvent +from app.services.shipping_notice.export import generate_shipment_excel +from app.services.shipping_notice.extract import extract_notice_fields +from app.services.shipping_notice.match import match_notice_lines +from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file +from app.services.shipping_notice.rpa import ( + find_latest_inventory_file, + inventory_processed_dir, + write_inventory_export_trigger, + write_upload_trigger, +) +from app.services.shipping_notice.tool_response import tool_response + + +def _parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None: + raw = payload.get("inventory_lines") + if isinstance(raw, list) and raw: + return raw + text = payload.get("inventory_lines_json") + if isinstance(text, str) and text.strip(): + import json + + try: + parsed = json.loads(text) + if isinstance(parsed, list): + return parsed + except json.JSONDecodeError: + return None + return None + + +def _generate_case_no() -> str: + return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def _log_event(case: ShippingCase, event_type: str, detail: dict[str, Any] | None = None) -> None: + if case.id is None: + db.session.flush() + db.session.add(ShippingCaseEvent( + case_id=case.id, + event_type=event_type, + detail_json=detail or {}, + )) + + +def _get_case(case_id: str) -> ShippingCase | None: + value = str(case_id or "").strip() + if not value: + return None + case = ShippingCase.query.filter_by(case_no=value).first() + if case: + return case + if value.isdigit(): + return db.session.get(ShippingCase, int(value)) + return None + + +def _serialize_case(case: ShippingCase) -> dict[str, Any]: + return { + "case_no": case.case_no, + "process_status": case.process_status, + "review_status": case.review_status, + "match_status": case.match_status, + "pending_human_reason": case.pending_human_reason, + "customer_name": case.customer_name, + "customer_code": case.customer_code, + "ship_to": case.ship_to, + "required_date": case.required_date, + "lines": case.lines_json or [], + "shortage": case.shortage_json, + "line_results": case.line_results_json, + "export_file_name": case.export_file_name, + "freight_ref_no": case.freight_ref_no, + "error_message": case.error_message, + "conversation_id": case.conversation_id, + } + + +def create_case(payload: dict[str, Any]) -> dict[str, Any]: + case = ShippingCase( + case_no=_generate_case_no(), + user_id=payload.get("user_id"), + conversation_id=str(payload.get("conversation_id") or "").strip() or None, + source_type=str(payload.get("source_type") or "manual"), + raw_content=str(payload.get("raw_content") or "").strip() or None, + process_status="created", + ) + db.session.add(case) + _log_event(case, "case_created", {"source_type": case.source_type}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message=f"已创建发货任务 {case.case_no}", + data=_serialize_case(case), + ) + + +def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + raw_text = str(payload.get("raw_text") or case.raw_content or "").strip() + structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None + parsed, confidence, warnings = extract_notice_fields( + raw_text=raw_text, + source_type=case.source_type, + structured=structured, + ) + + case.raw_content = raw_text or case.raw_content + case.customer_name = str(parsed.get("customer_name") or "").strip() or None + case.customer_code = str(parsed.get("customer_code") or "").strip() or None + case.ship_to = str(parsed.get("ship_to") or "").strip() or None + case.required_date = str(parsed.get("required_date") or "").strip() or None + case.lines_json = parsed.get("lines") if isinstance(parsed.get("lines"), list) else [] + case.parse_confidence = confidence + case.process_status = "parsed" + case.pending_human_reason = None + + if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7): + case.process_status = "pending_review" + case.review_status = "parse_review" + case.pending_human_reason = "low_parse_confidence" + _log_event(case, "parse_needs_review", {"confidence": confidence, "warnings": warnings}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message="解析置信度较低,请核对客户、料号、数量是否正确。", + data={**_serialize_case(case), "warnings": warnings}, + human_options=["confirm", "reject", "reparse"], + ) + + _log_event(case, "parsed", {"confidence": confidence, "warnings": warnings}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="发货通知解析完成,可继续检查库存。", + data={**_serialize_case(case), "warnings": warnings}, + ) + + +def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + mode = str(payload.get("mode") or "auto").strip().lower() + inventory_lines = _parse_inventory_lines(payload) + if inventory_lines: + case.inventory_lines_json = inventory_lines + case.process_status = "inventory_ready" + case.pending_human_reason = None + case.error_message = None + _log_event(case, "inventory_uploaded", {"row_count": len(inventory_lines)}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message=f"已载入库存 {len(inventory_lines)} 行,可进行匹配。", + data=_serialize_case(case), + ) + + if mode == "retry_rpa" or mode == "auto": + latest = find_latest_inventory_file() + processed = inventory_processed_dir() + if latest and processed: + try: + lines = ingest_inventory_file(latest, move_to=processed) + if lines: + case.inventory_lines_json = lines + case.process_status = "inventory_ready" + case.pending_human_reason = None + _log_event(case, "inventory_rpa_drop_ingested", {"file": latest.name, "rows": len(lines)}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message=f"已从 RPA 落盘载入库存 {len(lines)} 行。", + data=_serialize_case(case), + ) + except Exception as exc: + case.error_message = str(exc)[:500] + + trigger = write_inventory_export_trigger(case.case_no, {"mode": mode}) + if trigger: + case.process_status = "waiting_inventory" + case.pending_human_reason = "inventory_rpa_pending" + _log_event(case, "inventory_rpa_triggered", {"trigger": trigger}) + db.session.commit() + return tool_response( + status="running", + case_id=case.case_no, + message="已触发 RPA 库存导出,完成后可继续匹配。", + data={**_serialize_case(case), "trigger_path": trigger}, + ) + + _log_event(case, "inventory_rpa_retry_requested", {}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。", + data=_serialize_case(case), + human_options=["upload_inventory_file", "retry_rpa"], + ) + + if case.inventory_lines_json: + case.process_status = "inventory_ready" + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="已有库存快照,可进行匹配。", + data=_serialize_case(case), + ) + + case.process_status = "waiting_inventory" + case.pending_human_reason = "inventory_unavailable" + _log_event(case, "inventory_missing", {}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message="暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。", + data=_serialize_case(case), + human_options=["retry_rpa", "upload_inventory_file"], + ) + + +def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + inventory_lines = _parse_inventory_lines(payload) + if inventory_lines: + case.inventory_lines_json = inventory_lines + elif not case.inventory_lines_json: + return ensure_inventory({"case_id": case.case_no}) + + notice_lines = case.lines_json or [] + match_status, line_results, shortage = match_notice_lines( + notice_lines, + case.inventory_lines_json or [], + ) + case.match_status = match_status + case.line_results_json = line_results + case.shortage_json = shortage + case.pending_human_reason = None + + if match_status == "fulfillable": + case.process_status = "matched" + case.review_status = "confirmed" + _log_event(case, "matched_fulfillable", {"match_status": match_status}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="库存充足,可生成发货 Excel 并上传货代系统。", + data=_serialize_case(case), + ) + + case.process_status = "pending_review" + case.review_status = "inventory_shortage_review" + case.pending_human_reason = "inventory_shortage" + _log_event(case, "match_needs_review", {"match_status": match_status, "shortage": shortage}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message="库存数量不足,请复核缺口明细后决定是否部分发货。", + data=_serialize_case(case), + human_options=["confirm", "reject", "rematch"], + ) + + +def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + decision = str(payload.get("decision") or "").strip().lower() + comment = str(payload.get("comment") or "").strip() + + if decision == "reject": + case.process_status = "rejected" + case.review_status = "rejected" + case.pending_human_reason = None + _log_event(case, "decision_rejected", {"comment": comment}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="已驳回该发货任务。", + data=_serialize_case(case), + ) + + if decision in {"confirm", "confirmed"}: + case.review_status = "confirmed" + case.process_status = "matched" + case.pending_human_reason = None + _log_event(case, "decision_confirmed", {"comment": comment}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="已确认,可继续生成 Excel 并上传货代系统。", + data=_serialize_case(case), + ) + + if decision == "rematch": + _log_event(case, "decision_rematch", {"comment": comment}) + db.session.commit() + return match_inventory({"case_id": case.case_no}) + + if decision == "reparse": + return parse_notice({"case_id": case.case_no, "raw_text": case.raw_content or ""}) + + return tool_response(status="failed", case_id=case.case_no, message=f"未知 decision: {decision}") + + +def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + if case.process_status not in {"matched", "uploaded"} and case.review_status != "confirmed": + return tool_response( + status="failed", + case_id=case.case_no, + message="当前状态不允许生成 Excel,请先完成匹配或人工确认。", + data=_serialize_case(case), + ) + + path, filename = generate_shipment_excel(case) + case.export_file_path = path + case.export_file_name = filename + case.process_status = "waiting_upload" + _log_event(case, "export_generated", {"file_name": filename}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message=f"已生成发货 Excel:{filename}", + data={**_serialize_case(case), "download_hint": f"/api/shipping-notice/cases/{case.case_no}/export"}, + ) + + +def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + if not case.export_file_path: + gen = generate_excel({"case_id": case.case_no}) + if gen.get("status") != "ok": + return gen + + mode = str(payload.get("mode") or "auto").strip().lower() + if mode == "manual_confirm": + ref = str(payload.get("freight_ref_no") or "").strip() + case.process_status = "uploaded" + case.freight_ref_no = ref or None + case.pending_human_reason = None + _log_event(case, "upload_manual_confirmed", {"freight_ref_no": ref}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="已标记为手工上传货代系统完成。", + data=_serialize_case(case), + ) + + if mode == "retry_upload" or mode == "auto": + queued, trigger = write_upload_trigger(case.case_no, case.export_file_path or "") + if queued and trigger: + case.process_status = "waiting_upload" + case.pending_human_reason = "upload_rpa_pending" + _log_event(case, "upload_rpa_triggered", {"queue_file": queued, "trigger": trigger}) + db.session.commit() + return tool_response( + status="running", + case_id=case.case_no, + message="已触发 RPA 上传货代,请稍候…", + data={**_serialize_case(case), "queue_file": queued}, + ) + + case.process_status = "upload_failed" + case.pending_human_reason = "upload_rpa_failed" + case.error_message = "RPA 上传目录未配置或触发失败" + _log_event(case, "upload_rpa_pending", {}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。", + data=_serialize_case(case), + human_options=["retry_upload", "download_excel", "mark_manual_uploaded"], + ) + + +def get_case_status(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_id") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + return tool_response( + status="ok", + case_id=case.case_no, + message=f"当前状态:{case.process_status}", + data=_serialize_case(case), + human_options=_human_options_for_case(case), + ) + + +def _human_options_for_case(case: ShippingCase) -> list[str] | None: + reason = case.pending_human_reason + if reason == "inventory_unavailable": + return ["retry_rpa", "upload_inventory_file"] + if reason == "inventory_shortage": + return ["confirm", "reject", "rematch"] + if reason == "low_parse_confidence" or case.review_status == "parse_review": + return ["confirm", "reject", "reparse"] + if reason == "upload_rpa_failed" or case.process_status == "upload_failed": + return ["retry_upload", "download_excel", "mark_manual_uploaded"] + if reason == "inventory_rpa_pending" or case.process_status == "waiting_inventory": + return ["retry_rpa", "upload_inventory_file"] + if reason == "upload_rpa_pending" or case.process_status == "waiting_upload": + return ["retry_upload", "download_excel", "mark_manual_uploaded"] + return None + + +def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_no") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + success = bool(payload.get("success", True)) + if not success: + case.process_status = "waiting_inventory" + case.pending_human_reason = "inventory_unavailable" + case.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500] + _log_event(case, "inventory_rpa_failed", {"error": case.error_message}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message=case.error_message, + data=_serialize_case(case), + human_options=["retry_rpa", "upload_inventory_file"], + ) + + file_path = str(payload.get("file_path") or "").strip() + path = Path(file_path) if file_path else find_latest_inventory_file() + if not path or not path.is_file(): + return tool_response(status="failed", case_id=case.case_no, message="库存文件不存在") + + processed = inventory_processed_dir() + lines = ingest_inventory_file(path, move_to=processed) + case.inventory_lines_json = lines + case.process_status = "inventory_ready" + case.pending_human_reason = None + case.error_message = None + _log_event(case, "inventory_rpa_ready", {"file": path.name, "rows": len(lines)}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message=f"RPA 库存已就绪,共 {len(lines)} 行。", + data=_serialize_case(case), + ) + + +def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: + case = _get_case(str(payload.get("case_no") or "")) + if not case: + return tool_response(status="failed", message="未找到 case_id") + + success = bool(payload.get("success", True)) + if success: + case.process_status = "uploaded" + case.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None + case.pending_human_reason = None + case.error_message = None + _log_event(case, "upload_rpa_success", {"freight_ref_no": case.freight_ref_no}) + db.session.commit() + return tool_response( + status="ok", + case_id=case.case_no, + message="RPA 已成功上传货代系统。", + data=_serialize_case(case), + ) + + case.process_status = "upload_failed" + case.pending_human_reason = "upload_rpa_failed" + case.error_message = str(payload.get("error_message") or "RPA upload failed")[:500] + _log_event(case, "upload_rpa_failed", {"error": case.error_message}) + db.session.commit() + return tool_response( + status="needs_human", + case_id=case.case_no, + message=case.error_message, + data=_serialize_case(case), + human_options=["retry_upload", "download_excel", "mark_manual_uploaded"], + ) diff --git a/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-3E31F63B_20260601112744.xlsx b/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-3E31F63B_20260601112744.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e505e8b510d990ba37eaa2b7806a6504b91adf07 GIT binary patch literal 5021 zcmZ`-1yoeq*B`otnV}?AO1hPnkdPQb5Jvg|BRRBmi-?r8Gy+2?F(Tyvf`lVdLxXe* z2uP1K-}qc_`Q&^5d+#}S-L>v-pR@P+?KoRki-3?80058zyfRx%)jsKHq~N}KaDxUn zY+S5$-CbNgg#U7N74m^Q>0opyT16;{XPfVN)ul(VAuipPkIHGp2t9gI%L@-b+T0+# z>77%n(DUDB3xYT6P4l!$B{x;XI@m^qJM?xRA@{k6E%XJji4Fyd>OzG_&R3IS9QQyCig)vNX~*uF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iv{y1xA!n)yv0G?uRqZpga=zPFLMwmRoGnuL zY+zKCjN9eSA<>_TPFN{9NZ=wfKTc8VUtabzGF!R0IR5mr*!UJmn+VPAV6GjK`06lC z107)lMJ~d~{ON3)!7>N`g8ibZk|2pOQpl^;Vrl#7d@-7oJvZmHdj;LSpp+w z@ph)!XB+K`hYMEJ0?@Mr@BXh1LMJaHg{G~(nhL%JlqI~UWFW90N#Y^>v@k?ARRElg zrT4M?X6*SC4{U{CkdELhy6HBqT;Y{B1byTQ9D+;AB!<*?eA1$%m^Pg0duE^%d+GIZ z$c`J(Jtc4GfD&=I-?M(>U^50qF&^!I&FmDK>1P&vA@zx`E!3Ce410_-GSe>u|02`B z&HOj9Y7*oxJr<#Sf&?uA7)yro@QZ}X=oliy4uPS!D@$89m|FlEto0%fFsaQyY;1)k zqWop`MrA>}cHEt?PwQ*|ge(i4>c|`|ckF(_{FOio$f{BesXfa~3;X4_9dX)vf|t&( zju)*;DwGF3m)fQl2`FPPQL*9WTQXTRZFR!lXfaN_9$$EU&GhIk1QF5&0tyq`Kd)L% z3id0!_0()~!w4mbQGZu{b#`xUp5jjyWkx86GvgE-CHQqfG*NMJ_JlcmS{V4c!aU4= zGO0WXgJTjU+M@8=BL{IQSH(4<82MTF|#mU6pg5RYhLixO*i|l zcP`JV36n2%-sz_Q2(mBaBKeCWiNs+`uT4#BQCDu!2iSRFUq;- hO26ft;^h2?W9e!U;aW2Q02%I9z(w&pKU-IT{{v^8z-j;h literal 0 HcmV?d00001 diff --git a/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-72B96411_20260601112745.xlsx b/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-72B96411_20260601112745.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4ab24d4d728bef5b6b5842fd8382705f37a4547f GIT binary patch literal 5022 zcmZ`-2T)VX*AKk~DFIQcbm?8`Rf?1df)MEfF@S{7t4J{-(xmrJ0F@Gv8sLEx5ow{L zbOZ!Mq(?eme9jx6eD8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0>Tz9`a*IfZ^-uiB8F%VKQ`uYl+$f(-;&-om zId*(=`A;mE{b}+~HUh`cMTwoas3Yc;&?%%PngIYP@UJpHitGODT><_N(!RZ( literal 0 HcmV?d00001 diff --git a/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-AF7CFD94_20260601112831.xlsx b/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-AF7CFD94_20260601112831.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..6ff1be5e44d2cd83140cb88a1865e68760574cd7 GIT binary patch literal 5021 zcmZ`-1yoeq*B?r15N1e8m6Glb2?>c21Yx8fAt4RYEsnHwcPlZ{DM$@S4UKdQ2uRPP z`NrpZ>pl72|K5AfU3abf+vn`Peml^JM=zFZL-2X_o|%$e>aiL1ml@>UvExW&Z>7g-&|ls1vPO#13gwpuH9t78$O_D z|8m{O%`t98%U8%mIrmC&O_q*jsGxWSD?`aFEdj~87qfIYsj65K2hMf4Rv)=m=C@vl z3v--S+(t@`-&FW|$2|5sdh2}{008LUDwsJqTm00aAg0ZxgBJ)hE?CWc0LccfoK;q6 z5xyoDb`z+ahINHj2*tKsrkARV)XsdS+`2w`j3D^bDLtgMA%$cApj>g%O*41Fob?3{ z#{JBm6ev@!>QWBzpkpJ9(c|^*H)V~4HEP<53K)@E`z#M)JGZ+2!KIRwWuQWKBJC?$ zSu#v}PA$iMBuwmi51%lh5Kx|POdv@Zyw^A*jqF=jr<`(CPSK%YzQsR_EA^=-t6Qh7 zF1NA&iapw}06!L)DLf_Q`F@uH^)98n*Cr!rGvpIVWn)~8N1DOIGY7fJnQucE9UkOX zIIUOe{+PcTCdD9~k>nNtkj@GKkfIIaVawxcWnpLWYv%iDnjJlTmuXQlzg_r{hb796 z5Fs2`TTSX>?KV@L61)Rpcmsk)+IpJD1pBut36u0C679sQH>OEqb8emwDk!aQh%Kb=1?h_oA?@WTFDG)Yw9@|->qI_5I7<4(~h*r!ywg_WoZbh zJ~*}Qx|p7qwm@!*)A0w|^U^@?`VT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T z=D&$m6DM>1sUXQSB*hAVwq!IHyNJJxiY7et7#N~lS=zou-v&@;XcT;eN^bpO4HFQJ z@R!n=kfPYP<>-Na+++k4NZq7T8DFI2h(65!!W>8pURS6gu)8_m#&qLdcZ`+}-}TE| zQ$_1yvgJ=+itmyM29zC+~9Ny20de3dAfp2?2|CqTjovRFOU!4#K8nc)v>+^&6j(hxw-?SuUQ?~v};uO`Ik zJ0BFq;G9p`(gT9@RTT?W!t@)WhUnN|EPYuxB-7Ycx!vH_-PWaS;-Z-KqAL8>0neh| zkza6PRG1?V=r8q;c6n9U>$X_Ey>zff5>GhgS`Io!QzMG7pbI}ZgHLVf1C{7*?Blb! zekY6A2KD7pI1%u34Q|kCrsH~PWVd2$w~53u!g}j7Ct}W(^u$2?!4YeL*ADK7w|z|e z-r1bz#&o`9x#!#dRtagd)7)u9J z4`7b*yB4?#y&AiJLkCFyh~!s+S7YICU>&9a!R+~Om%R$U>gT_~w3xVx0sjxLzbfad hEB%&pj*;^pj-{=MhiT0K0EC!V78Awq{cK$U{twmr#2o+t literal 0 HcmV?d00001 diff --git a/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-D6697279_20260601113529.xlsx b/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-D6697279_20260601113529.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..0735bdc81cf16aca3e374267f8ec0c7872526e24 GIT binary patch literal 5021 zcmZ`-1yoeq*B?q+n4y%EmTqYzBqRoq8X5@)kRGI4M5LraQeX%rhHgP>L~5j!P5}|= zc{JbnTyOd0d;fdyId|Q)?r)#7_xkNPTSo&2ml6N~5CB}VI?Pl)XsM-Oz6LRa95ZZP zZFD?b-CzO_-Q4(noSn2#TEv}#B-a+&A9yvqieiLczb6}&(~9DM@~ocAIs9aM3-_*z zuWv71KK~0Aj{0=vUH%nk5#bM{@)N8la{YaIQF$x=6+*M2F;%o=a3)5au6*aokY_?9 z5(7&Ol^bLHD$pmWR7LM{a3_TI~njgDdG=+v_8V}xO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~$pnob^{TzG^^O!aEWg983HpPJ$21V}!E>z=c?9 zAFFRBp3ku;tl>105!^-M?o)~tUU_4XC!WADXECY7kmlYG8YIMXhV!3Z=qtotf4dg4 z=MMBp$s0Q&fgc|Ze!p|H9n(ZS746Sreh$g>GY`I!`b0LDo69kVJ;fNA_LqTwk?G%N z{+n2J39{Fp3X(iSfK~xFO2+cAi}=f^Xd=UofuZ-RN;|jcIsj@6&4R|L)b_t@p#q{& z{?fXW(x82Njy}5&-x&dLX?iNZ8Ony#32I-&1$m?YkgFTA~Jc2W(7hxCJh0@oZ~)@&pN z`xV}OZa%YR)Fg&dZ7gSAIM`ew{*y(S5sKk-7zHPBejN}^m0Vps?OZ%9^?lv!VCFxW zRGx&wFo^_dS@`XVqlko?{3d@4&-eGl;oas1UvsTpJzZZ;SF69SB2CdKK%)PGow1iT z*x(LGL1hhnl_;5>$&ZI5K_UopSf8kYL6=3@kq_!T@Rx#`0?4_2u(k0HX^;KtLQQ_~ z*`XL*3kci#C?Eqh#X?n3gQl2aTJ{&qOACi&>buIfn>>0ukoU~o6mwqGL^2=nEb1Tm zg(SyBIPp-tQ~ThMUxU42kJaB#3vDKO;!L^z8Xc#h9zzI6UJJ?MQyuQ165Wk|cs4ia zVin({wld~S1pHEm8@!h7v{4$}s~F#FCb<%ByY+=Le9oQp#85)}h!yU&gWFR%z_jn3 z%Xw}}>r0k*zU@DOC`>|XlSVGeBJN@cgN02A_}{G*3~T$iMDj-@zY4q>3x5L}Fa-!^&40V>Rq$0m{|&x@iK`g!|M2>&a<014 gZ#m}}Isf5UIvRMG)(ikZh`Hr3QT+bT))nCY03z4JasU7T literal 0 HcmV?d00001 diff --git a/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-D95651FB_20260601112758.xlsx b/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-D95651FB_20260601112758.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..419826453fcdc5677642c03239feb49b4d7b7fc7 GIT binary patch literal 5022 zcmZ`-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+QWMXLlZr-p;1X~4yx|WZ4<@u7`7Dnb5GRSN3qlmQnz65$`?xrBUeYO@z?A?H3Ed3P4Hx2XcBmYobIR;_j6(lDRzK zVho*+%~vze7dX_m2zuFYz5?mT(`sd2Ib)C~p1?5|Nx6jJhMsO+ad^<>jg{_K|LkPJV|pew0Qd~>Ct6l>V;SR*t3H1JO{ z{oBlc6RSF2@!B&H^5;mK%1pOKnC7WttNJ4UT9;xUeOb)XDE2> z^5%5GhNMzy;GZ&klp;?{*oxHcdHFt@uUfP_W2D;55^lxi-`cb|tpFo}`#?ZpLdQQV zHxh&V@|9m$&TgC5OQN;vN^dS6ZZ4Dk&Z3NPwJ;{Ef|GbZ4~XXKa92;LtEaWGuN&0E z@&}Vj6VX^Ek)y2hzdmsimvK|s6pH5GY9$Nnw9NbR+7|8!|8u57=S?|9vThy<^OwgN zS8=T!e!m<{(ZpAshV8k^cyJ;loH(1~i8dH?S&$WRuiBkxIk5gI6`v38U4kRV6Tj*Z zvu}b>Gz&bBq`8+G(qCC9S`NEkA3e;-6}hs!ctokQr*W&^y{8Rz+rmvPJF+t3<{|%* z@v&cUQgpa8KlKOgZpYk8+zkhuzCK1+1Njpdn)NrBSY4fH5(J7cI8#t-xQkX|FYb@C z`2km(xO(l?F&9$cR5gCkT9)%haa505T#tq9YMA}@6i?XvV~SG~nY+gv2(MlIuJ`?H z2i~uF&dnKpDRa(u{3nq4iKx325lf0lWh`NEaA^SlyOn}v&EHor*24e4v2qoCwTtl+ z3jhS;bo?9rPfz12{OVc%7kn1G{C}MMuL`(Y>-{63CWM9fZvp>V`CXNAHT(Y~B^bvL zTMuBj@v9cN3cVV;e?bSye~aW-fmdVUFJLXU0Ku;LZ9iUt1ksAC6_9OMq?7001P|TL~M*@BC<80sarJ$HYAV literal 0 HcmV?d00001 diff --git a/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-E0F355C5_20260601113530.xlsx b/backend/backend/data/shipping_notice/exports/shipment_SN-20260601-E0F355C5_20260601113530.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!s>d=Tpz@K@ zgJ_*Ho#EaW_&tY3#VU}OgC}!O#W**Rq`o^~5a_qEBrc#PYC0gt)x#w~8 z=q06ei%)i1<&PF^D0ocHdI&@w9rSP9IoyhBAe)TzXR$alN%yk|x|I5a*B2Yhu!cRs8kym@fq#?f z-)8=cST%9dSDp$0pP{Ih0rbVAxwwUVr8IQmp+}$)rOJ}_O~y8W8dIad19WohPdg~T zNQA$n-h?F8o;^no;cHAnP8{?{9UWIAi|HN+0r=GvIAzU_|D(&N2y zadWb8O;o1r$xE>v3W0!9=3+&=+g!_LOXlq`%$+vV_*=0Bx7N*%-|8TPd#OPDgbpvO z))IpJ3S^&KOm7-Dh@w^N%Wlr^uYV=`lSS!a3J6B5f)jYZFNkJ}&Q2Z>Cl4zFUl)kG z#V;n6C7`iP0(MyyeD`z|7ITqX=ZoUrcu$7tw8;OKZR70W{Br88MouMpl4gDv=BN89 zdr6%wexC$X+Q?Utn)#XBSa5<#7;zS>r!f|XFihNvM1_7{s^=MN|}c9d^5xOKO6DVe({WWA^gzq!x7 zU~uRcoEQ}b;|9M|`{ zXZxM3V;j_#M&YEOFE#i-{aDHiU`zF9H8q`CXQBIs5-DB^XB! zTMuB5@lP#q8G1Q({{tNW{t?M9124zIe}Hw^0tCC~zg_k+__Ck>1E$BuRV?^_c>QHL imtE-}IcHco|KV7=ngrO^3;;laePyswT>V$;3h;kwQ^B?X literal 0 HcmV?d00001 diff --git a/backend/migrations/versions/d8e9f0a1b2c3_add_shipping_cases.py b/backend/migrations/versions/d8e9f0a1b2c3_add_shipping_cases.py new file mode 100644 index 00000000..53c35ca6 --- /dev/null +++ b/backend/migrations/versions/d8e9f0a1b2c3_add_shipping_cases.py @@ -0,0 +1,73 @@ +"""add shipping_cases tables for freight notice agent tools + +Revision ID: d8e9f0a1b2c3 +Revises: c9d8e7f6a5b4 +Create Date: 2026-05-29 12:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +revision = 'd8e9f0a1b2c3' +down_revision = 'c9d8e7f6a5b4' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'shipping_cases', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('case_no', sa.String(length=64), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('conversation_id', sa.String(length=100), nullable=True), + sa.Column('source_type', sa.String(length=32), nullable=False, server_default='manual'), + sa.Column('raw_content', sa.Text(), nullable=True), + sa.Column('customer_name', sa.String(length=200), nullable=True), + sa.Column('customer_code', sa.String(length=64), nullable=True), + sa.Column('ship_to', sa.Text(), nullable=True), + sa.Column('required_date', sa.String(length=32), nullable=True), + sa.Column('lines_json', sa.JSON(), nullable=True), + sa.Column('parse_confidence', sa.Float(), nullable=True), + sa.Column('process_status', sa.String(length=32), nullable=False, server_default='created'), + sa.Column('review_status', sa.String(length=32), nullable=True), + sa.Column('match_status', sa.String(length=32), nullable=True), + sa.Column('shortage_json', sa.JSON(), nullable=True), + sa.Column('line_results_json', sa.JSON(), nullable=True), + sa.Column('inventory_snapshot_id', sa.Integer(), nullable=True), + sa.Column('inventory_lines_json', sa.JSON(), nullable=True), + sa.Column('export_file_path', sa.String(length=500), nullable=True), + sa.Column('export_file_name', sa.String(length=255), nullable=True), + sa.Column('freight_ref_no', sa.String(length=128), nullable=True), + sa.Column('pending_human_reason', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_shipping_cases_case_no', 'shipping_cases', ['case_no'], unique=True) + op.create_index('ix_shipping_cases_user_status', 'shipping_cases', ['user_id', 'process_status']) + op.create_index('ix_shipping_cases_conversation', 'shipping_cases', ['conversation_id']) + op.create_index('ix_shipping_cases_process_status', 'shipping_cases', ['process_status']) + op.create_index('ix_shipping_cases_created_at', 'shipping_cases', ['created_at']) + + op.create_table( + 'shipping_case_events', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('case_id', sa.Integer(), nullable=False), + sa.Column('event_type', sa.String(length=64), nullable=False), + sa.Column('detail_json', sa.JSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['case_id'], ['shipping_cases.id']), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_shipping_case_events_case_id', 'shipping_case_events', ['case_id']) + op.create_index('ix_shipping_case_events_event_type', 'shipping_case_events', ['event_type']) + op.create_index('ix_shipping_case_events_created_at', 'shipping_case_events', ['created_at']) + + +def downgrade(): + op.drop_table('shipping_case_events') + op.drop_table('shipping_cases') diff --git a/backend/scripts/export_shipping_notice_openapi.py b/backend/scripts/export_shipping_notice_openapi.py new file mode 100644 index 00000000..32887e6f --- /dev/null +++ b/backend/scripts/export_shipping_notice_openapi.py @@ -0,0 +1,32 @@ +"""Export Dify-compatible OpenAPI for 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.shipping_notice.openapi_spec import build_dify_openapi_spec + + +def main() -> None: + base = ( + os.getenv("SHIPPING_NOTICE_TOOL_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) + out_dir = ROOT / "docs" / "openapi" + out_dir.mkdir(parents=True, exist_ok=True) + json_path = out_dir / "shipping_notice_tools.dify.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/shipping-notice/tools/openapi.json") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/generate_freight_shipment_template.py b/backend/scripts/generate_freight_shipment_template.py new file mode 100644 index 00000000..17897a25 --- /dev/null +++ b/backend/scripts/generate_freight_shipment_template.py @@ -0,0 +1,35 @@ +"""Generate the default freight shipment upload Excel template.""" +from __future__ import annotations + +from pathlib import Path + +from openpyxl import Workbook + + +HEADERS = [ + "客户名称", + "客户代码", + "收货地址", + "要求交期", + "料号", + "发货数量", + "单位", + "备注", +] + + +def main() -> None: + root = Path(__file__).resolve().parents[1] + out = root / "templates" / "freight_shipment_upload.xlsx" + out.parent.mkdir(parents=True, exist_ok=True) + + wb = Workbook() + ws = wb.active + ws.title = "Shipment" + ws.append(HEADERS) + wb.save(out) + print(f"Wrote {out}") + + +if __name__ == "__main__": + main() diff --git a/backend/seed_shipping_notice_agents.py b/backend/seed_shipping_notice_agents.py new file mode 100644 index 00000000..2ec5c63a --- /dev/null +++ b/backend/seed_shipping_notice_agents.py @@ -0,0 +1,77 @@ +"""Seed agents for freight shipping notice Chatflow orchestration.""" +from app import create_app, db +from app.models import Agent +from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME, EXTRACT_AGENT_NAME + +app = create_app() + +CHAT_DESCRIPTION = "货代发货通知智能体:自然语言驱动解析、库存匹配、Excel 生成与货代上传(Tool 编排)" +EXTRACT_DESCRIPTION = "后台专用:从邮件/PDF 文本抽取结构化发货通知字段(Workflow,供 Tool 内部调用)" + + +def _upsert_agent( + *, + name: str, + description: str, + dify_app_type: str, + dify_app_id: str | None = None, + dify_api_key: str | None = None, + api_base_url: str | None = None, +): + agent = Agent.query.filter_by(name=name).first() + extra_config = {"dify_app_type": dify_app_type} + if not agent: + agent = Agent( + name=name, + description=description, + type="api", + dify_app_id=dify_app_id, + dify_api_key=dify_api_key, + api_base_url=api_base_url, + extra_config=extra_config, + is_active=True, + ) + db.session.add(agent) + print(f"Created agent: {name}") + else: + agent.description = description + agent.type = "api" + agent.extra_config = extra_config + if dify_app_id: + agent.dify_app_id = dify_app_id + if dify_api_key: + agent.dify_api_key = dify_api_key + if api_base_url: + agent.api_base_url = api_base_url + agent.is_active = True + print(f"Updated agent: {name}") + return agent + + +if __name__ == "__main__": + import os + + with app.app_context(): + chat_key = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_API_KEY") or os.getenv("DIFY_API_KEY") + chat_base = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_BASE") or os.getenv("DIFY_API_BASE") + extract_key = os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_API_KEY") + extract_base = os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_BASE") or chat_base + + _upsert_agent( + name=CHAT_AGENT_NAME, + description=CHAT_DESCRIPTION, + dify_app_type="chatflow", + dify_app_id=os.getenv("SHIPPING_NOTICE_CHAT_DIFY_APP_ID"), + dify_api_key=chat_key, + api_base_url=chat_base, + ) + _upsert_agent( + name=EXTRACT_AGENT_NAME, + description=EXTRACT_DESCRIPTION, + dify_app_type="workflow", + dify_app_id=os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_APP_ID"), + dify_api_key=extract_key, + api_base_url=extract_base, + ) + db.session.commit() + print("Shipping notice agents seeded.") diff --git a/backend/templates/freight_shipment_upload.xlsx b/backend/templates/freight_shipment_upload.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..96c93f049f4b3ed0e6c5b412a894ef5418822116 GIT binary patch literal 4966 zcmZ`-2Q(c0*IvB`tA=RNqW9j35@bUN8$DQyXhGD75;l7DZUw6(TJ#z{2w`>6dl1pt zAj-E%&U^C4_x@+j%$zxAo;!1&x%avEcXhO|uqgom06ySOdYg$__g#%d^j$ytAVVM4 z&Q?0E&Ms~Ok6c{%y&N6xBJUEl3liflwA}ZoO$}#6T)Qn74sSy8KMkqjatuD**}_(E z^7ihb&*2Zd$x)M{y2robC?ecVqBzcaD&Nd0}N2nZ1( zmi)9-`)*^DUk&;cnWXGlA+5{Nu>=;CF6U$_nz=zpw&uewA3>odmCS>48KKulr3e4g z>wIR7(}LGPqw|*wEP24Gujo(j!vFxt|Lua6vn%AM4|%a|_8o%6F!Q_>_$?5N;PPoj zxgOCADsc~yiYeHKuyV1u=JSl=yAn0itu&jLhj+RN-*?In>aEM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4v fcDm5|{2z&>qlJT>u>b%B=v^MI;=rFXD8T;#gny~~ literal 0 HcmV?d00001 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 685433a4..65c2a33e 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -14,7 +14,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path): """ from app import env_persistence - monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', tmp_path / 'isolated.env') + monkeypatch.setattr(env_persistence, 'LEGACY_BACKEND_ENV_PATH', tmp_path / 'isolated.env') @pytest.fixture diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py new file mode 100644 index 00000000..a796968c --- /dev/null +++ b/backend/tests/test_shipping_notice_tools.py @@ -0,0 +1,222 @@ +from app import db +from app.models import ShippingCase + + +def _tool_headers(app): + key = app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or app.config.get("INTEGRATION_API_KEY") or "test-tool-key" + app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = key + app.config["INTEGRATION_API_KEY"] = key + return { + "Content-Type": "application/json", + "X-Shipping-Tool-Key": key, + } + + +def test_shipping_notice_tool_flow(app, client): + headers = _tool_headers(app) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"}, + ) + assert create_res.status_code == 200 + create_data = create_res.get_json() + assert create_data["status"] == "ok" + case_id = create_data["case_id"] + + parse_res = client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={"case_id": case_id, "raw_text": "客户:ACME 料号A001 x 10"}, + ) + assert parse_res.status_code == 200 + assert parse_res.get_json()["status"] in {"ok", "needs_human"} + + inv_res = client.post( + "/api/shipping-notice/tools/ensure_inventory", + headers=headers, + json={ + "case_id": case_id, + "inventory_lines": [{"sku": "A001", "available_qty": 10}], + }, + ) + assert inv_res.status_code == 200 + assert inv_res.get_json()["status"] == "ok" + + match_res = client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"case_id": case_id}, + ) + assert match_res.status_code == 200 + assert match_res.get_json()["status"] == "ok" + + excel_res = client.post( + "/api/shipping-notice/tools/generate_shipment_excel", + headers=headers, + json={"case_id": case_id}, + ) + assert excel_res.status_code == 200 + assert excel_res.get_json()["status"] == "ok" + + with app.app_context(): + case = ShippingCase.query.filter_by(case_no=case_id).first() + assert case is not None + assert case.export_file_path + + status_res = client.post( + "/api/shipping-notice/tools/get_case_status", + headers=headers, + json={"case_id": case_id}, + ) + assert status_res.status_code == 200 + assert status_res.get_json()["status"] == "ok" + + +def test_shipping_notice_match_shortage_needs_human(app, client): + headers = _tool_headers(app) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "ACME", + "lines": [{"sku": "A001", "qty": 100, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + client.post( + "/api/shipping-notice/tools/ensure_inventory", + headers=headers, + json={"case_id": case_id, "inventory_lines": [{"sku": "A001", "available_qty": 5}]}, + ) + match_res = client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"case_id": case_id}, + ) + data = match_res.get_json() + assert data["status"] == "needs_human" + assert "confirm" in (data.get("human_options") or []) + + confirm_res = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"case_id": case_id, "decision": "confirm"}, + ) + assert confirm_res.get_json()["status"] == "ok" + + +def test_openapi_spec_public(app, client): + app.config["SHIPPING_NOTICE_TOOL_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() + assert "create_case" in str(spec) + assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice" + props = spec["paths"]["/tools/create_case"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"] + assert "raw_content" in props + assert "ShippingToolKey" in spec["components"]["securitySchemes"] + assert "/rpa/" not in str(spec["paths"]) + + +def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): + headers = _tool_headers(app) + drop = tmp_path / "drop" + trigger = tmp_path / "triggers" + drop.mkdir() + trigger.mkdir() + app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop) + app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + from openpyxl import Workbook + + inv_file = drop / "stock.xlsx" + wb = Workbook() + ws = wb.active + ws.append(["料号", "可用数量"]) + ws.append(["A001", 20]) + wb.save(inv_file) + wb.close() + + cb_res = client.post( + "/api/shipping-notice/rpa/inventory-ready", + headers=headers, + json={"case_no": case_id, "success": True, "file_path": str(inv_file)}, + ) + assert cb_res.status_code == 200 + data = cb_res.get_json() + assert data["status"] == "ok" + assert data["data"]["process_status"] == "inventory_ready" + + +def test_rpa_upload_callback(app, client, tmp_path): + headers = _tool_headers(app) + queue = tmp_path / "queue" + trigger = tmp_path / "upload_triggers" + queue.mkdir() + trigger.mkdir() + app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(queue) + app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(trigger) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "ACME", + "lines": [{"sku": "A001", "qty": 5, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + client.post( + "/api/shipping-notice/tools/ensure_inventory", + headers=headers, + json={"case_id": case_id, "inventory_lines": [{"sku": "A001", "available_qty": 10}]}, + ) + client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"case_id": case_id}, + ) + client.post( + "/api/shipping-notice/tools/generate_shipment_excel", + headers=headers, + json={"case_id": case_id}, + ) + + cb_res = client.post( + "/api/shipping-notice/rpa/upload-complete", + headers=headers, + json={"case_no": case_id, "success": True, "freight_ref_no": "FR-001"}, + ) + assert cb_res.status_code == 200 + assert cb_res.get_json()["status"] == "ok" + assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001" diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json new file mode 100644 index 00000000..b4542940 --- /dev/null +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -0,0 +1,445 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "Hxops Shipping Notice Tools", + "version": "1.0.0", + "description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。" + }, + "servers": [ + { + "url": "http://192.168.100.192:8890/api/shipping-notice" + } + ], + "components": { + "securitySchemes": { + "ShippingToolKey": { + "type": "apiKey", + "in": "header", + "name": "X-Shipping-Tool-Key", + "description": "与 hxops SHIPPING_NOTICE_TOOL_API_KEY 相同" + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ], + "paths": { + "/tools/create_case": { + "post": { + "operationId": "create_case", + "summary": "创建发货任务 case", + "description": "创建发货任务 case", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "user_id": { + "type": "integer", + "description": "Hxops 用户 ID(可选)" + }, + "conversation_id": { + "type": "string", + "description": "Dify 会话 ID,便于工作台关联" + }, + "source_type": { + "type": "string", + "description": "来源:manual|email|wecom|pdf", + "enum": [ + "manual", + "email", + "wecom", + "pdf" + ] + }, + "raw_content": { + "type": "string", + "description": "原始发货通知文本(可选,后续 parse 也可传入)" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/parse_notice": { + "post": { + "operationId": "parse_notice", + "summary": "解析发货通知文本", + "description": "解析发货通知文本", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "raw_text": { + "type": "string", + "description": "待解析的发货通知全文" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/ensure_inventory": { + "post": { + "operationId": "ensure_inventory", + "summary": "确保库存快照可用(RPA 或手工 JSON)", + "description": "确保库存快照可用(RPA 或手工 JSON)", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "mode": { + "type": "string", + "description": "auto=自动/RPA;retry_rpa=重试 RPA", + "enum": [ + "auto", + "retry_rpa" + ] + }, + "inventory_lines_json": { + "type": "string", + "description": "手工库存 JSON 数组字符串,如 [{\"sku\":\"A001\",\"available_qty\":10}]" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/match_inventory": { + "post": { + "operationId": "match_inventory", + "summary": "匹配发货需求与库存", + "description": "匹配发货需求与库存", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "inventory_lines_json": { + "type": "string", + "description": "可选,覆盖库存 JSON 数组后再匹配" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/submit_decision": { + "post": { + "operationId": "submit_decision", + "summary": "人工复核决策", + "description": "人工复核决策", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "decision": { + "type": "string", + "description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析", + "enum": [ + "confirm", + "reject", + "rematch", + "reparse" + ] + }, + "comment": { + "type": "string", + "description": "备注(可选)" + } + }, + "required": [ + "case_id", + "decision" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/generate_shipment_excel": { + "post": { + "operationId": "generate_shipment_excel", + "summary": "生成固定模板发货 Excel", + "description": "生成固定模板发货 Excel", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/upload_to_freight": { + "post": { + "operationId": "upload_to_freight", + "summary": "上传 Excel 到货代系统(RPA 或手工确认)", + "description": "上传 Excel 到货代系统(RPA 或手工确认)", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "mode": { + "type": "string", + "description": "auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成", + "enum": [ + "auto", + "retry_upload", + "manual_confirm" + ] + }, + "freight_ref_no": { + "type": "string", + "description": "货代系统单号(manual_confirm 时填写)" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + }, + "/tools/get_case_status": { + "post": { + "operationId": "get_case_status", + "summary": "查询 case 当前状态与 human_options", + "description": "查询 case 当前状态与 human_options", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + }, + "security": [ + { + "ShippingToolKey": [] + } + ] + } + } + } +} \ No newline at end of file diff --git a/docs/shipping_notice_dify_openapi_setup.md b/docs/shipping_notice_dify_openapi_setup.md new file mode 100644 index 00000000..41cf3e1f --- /dev/null +++ b/docs/shipping_notice_dify_openapi_setup.md @@ -0,0 +1,211 @@ +# Dify Chatflow 绑定 OpenAPI — 操作手册 + +本文说明如何将 hxops **货代发货通知 Tool API** 绑定到 Dify **Chatflow** 应用「货代发货通知 Agent」。 + +--- + +## 前置条件 + +| 项 | 说明 | +|----|------| +| hxops 可访问 | Dify 服务器必须能 HTTP 访问 **hxops 后端**(不是 Dify 自己) | +| Tool API 基地址 | 见下方「端口说明」 | +| Tool Key | `.env` 中 `SHIPPING_NOTICE_TOOL_API_KEY` | +| Dify 应用 | Chatflow 类型,名称 **货代发货通知 Agent** | + +### 端口说明(易混) + +| 端口 | 服务 | OpenAPI / Tool 是否用这个 | +|------|------|---------------------------| +| **8882** | **Dify**(`DIFY_API_BASE`) | ❌ **不要**写进 OpenAPI `servers.url` | +| **8890** | hxops 前端 + `/api` 反代(docker `8890:80`) | ✅ **Dify 调 Tool 用这个** | +| **8891** | 旧知识库/Integration 等(视环境而定) | 一般不用作 Tool API | +| **5052** | hxops 后端直连(`backend/run.py`) | ✅ 本地开发、Dify 容器访问宿主机 | + +OpenAPI JSON 里 `servers[0].url` 必须是 **hxops Tool API** 地址,例如: + +- 部署/联调:`http://192.168.100.192:8890/api/shipping-notice` +- 直连 backend(无 nginx):`http://192.168.100.192:5052/api/shipping-notice` + +**8882 是 Dify 自己的端口**,Agent 执行工具时会从 Dify 发 HTTP 到 hxops;若写成 8882,请求会打到 Dify 自身,Tool 必然失败。 + +可在 `.env` 单独指定(优先于 `PUBLIC_BASE_URL`): + +```env +SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890 +``` + +验证 OpenAPI 可访问: + +```bash +curl -s http://192.168.100.192:8890/api/shipping-notice/tools/openapi.json | head +``` + +`servers[0].url` 应为 `http://192.168.100.192:8890/api/shipping-notice`。 + +本地导出静态文件(可选): + +```bash +cd backend +set SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890 +python scripts/export_shipping_notice_openapi.py +# 输出 docs/openapi/shipping_notice_tools.dify.json +``` + +--- + +## 步骤 1:在 Dify 创建 Chatflow 应用 + +1. 登录 Dify 控制台 → **工作室** → **创建应用** +2. 类型选 **Chatflow**(对话型工作流,支持 Agent 工具调用) +3. 名称:**货代发货通知 Agent** +4. 创建后记录 **App ID** 与 **API Key**(应用 → API 访问) + +写入 hxops `.env.dev` 并 seed: + +```env +SHIPPING_NOTICE_CHAT_DIFY_APP_ID= +SHIPPING_NOTICE_CHAT_DIFY_API_KEY=app-xxxxxxxx +SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 +``` + +```bash +cd backend +python seed_shipping_notice_agents.py +``` + +--- + +## 步骤 2:导入自定义工具(OpenAPI) + +### 方式 A — 从 URL 导入(推荐) + +1. Dify → **工具** → **自定义** → **创建自定义工具** +2. 名称:`Hxops Shipping Notice`(或 `货代发货通知 Tools`) +3. Schema 来源:**从 URL 导入** +4. URL: + + ``` + http://192.168.100.192:8890/api/shipping-notice/tools/openapi.json + ``` + + 将 host 换成你的 `PUBLIC_BASE_URL`。 + +5. 若 Dify 未自动识别鉴权,手动配置: + - 认证类型:**API Key** + - Header 名称:`X-Shipping-Tool-Key` + - API Key 值:与 hxops `SHIPPING_NOTICE_TOOL_API_KEY` 一致 + +6. 点击 **测试** / **保存**,确认 8 个工具均解析成功: + - `create_case` + - `parse_notice` + - `ensure_inventory` + - `match_inventory` + - `submit_decision` + - `generate_shipment_excel` + - `upload_to_freight` + - `get_case_status` + +> OpenAPI 已针对 Dify 优化:每个 POST 含 `parameters: []`、扁平 `requestBody` 字段、不含 RPA 回调接口。 + +### 方式 B — 粘贴 Schema + +若 URL 导入失败(网络隔离),使用导出的 JSON: + +``` +docs/openapi/shipping_notice_tools.dify.json +``` + +在创建自定义工具时选择 **粘贴 OpenAPI Schema**,粘贴文件内容后同样配置 API Key Header。 + +YAML 版本(可选): + +``` +GET /api/shipping-notice/tools/openapi.dify.yaml +``` + +--- + +## 步骤 3:在 Chatflow 启用 Agent + 工具 + +1. 打开 **货代发货通知 Agent** Chatflow 编排页 +2. 确认画布中有 **Agent** 节点(或 **LLM + 工具** 节点,视 Dify 版本而定) +3. 在 Agent 节点 → **工具** → 添加刚创建的 **Hxops Shipping Notice** 自定义工具 +4. 勾选全部 8 个 operation(或按需勾选,建议全选) + +--- + +## 步骤 4:配置系统提示词 + +将 `docs/shipping_notice_dify_prompt.md` 中「角色」至「对话风格」段落粘贴到 Chatflow **系统提示词 / Instructions**。 + +要点: + +- 必须先 `create_case`,全程携带 `case_id` +- `status=needs_human` 时等待用户选择,勿跳过 +- `inventory_lines_json` 传 JSON 字符串,例如:`[{"sku":"A001","available_qty":10}]` + +可选 Chatflow 变量(开始节点): + +| 变量 | 用途 | +|------|------| +| `sys.user_id` / 自定义 `user_id` | 传入 `create_case.user_id` | +| `sys.conversation_id` | 传入 `create_case.conversation_id` | + +--- + +## 步骤 5:发布并验证 + +1. **发布** Chatflow 应用 +2. 在 hxops 前端打开该 Agent Chat,或 Dify 预览窗口测试 +3. 发送示例: + + ``` + 客户:ACME,料号 A001 x 10,请处理发货。 + ``` + +4. 在 Dify **日志** 中确认 Agent 依次调用: + - `create_case` → `parse_notice` → `ensure_inventory` → … + +5. 工作台 **货代发货** 应出现新 case;状态为 `running` 时表示 RPA 进行中,可 `get_case_status` 轮询。 + +--- + +## 常见问题 + +### OpenAPI 导入报 invalid schema + +- 确认使用 `/tools/openapi.json`(新版 Dify 兼容 schema),不要用旧版泛型 `object` +- POST 需含 `parameters: []`(已在 spec 中内置) +- 避免 nested object 参数;库存用 `inventory_lines_json` 字符串 + +### Dify 调 Tool 401 Unauthorized + +- 检查自定义工具 Header `X-Shipping-Tool-Key` 是否与 backend 一致 +- backend 未配置 key 时返回 503 + +### Dify 调 Tool 连接失败 + +- Dify 容器/进程访问的是 `localhost:5052` 会失败;`servers.url` 必须是 Dify 能 reach 的内网 IP +- 设置 `PUBLIC_BASE_URL=http://:` + +### Agent 不调用工具 + +- 确认 Chatflow 已发布(非草稿) +- Agent 节点已绑定自定义工具 +- 系统提示词明确要求使用 Tool API + +### 与内部 Workflow 的关系 + +字段抽取 Workflow **「发货通知字段抽取」** 由 hxops `parse_notice` 内部调用,**无需**在 Chatflow 再绑一次。 + +--- + +## 相关文件 + +| 文件 | 说明 | +|------|------| +| `backend/app/services/shipping_notice/openapi_spec.py` | Dify 兼容 OpenAPI 生成 | +| `GET /api/shipping-notice/tools/openapi.json` | 动态 spec(含绝对 server URL) | +| `docs/shipping_notice_dify_prompt.md` | 系统提示词 | +| `docs/shipping_notice_runbook.md` | 整体部署 Runbook | diff --git a/docs/shipping_notice_dify_prompt.md b/docs/shipping_notice_dify_prompt.md new file mode 100644 index 00000000..4b0650fa --- /dev/null +++ b/docs/shipping_notice_dify_prompt.md @@ -0,0 +1,90 @@ +# 货代发货通知 Agent — Dify Chatflow 系统提示词 + +将以下内容配置到 Dify 应用 **「货代发货通知 Agent」**(`chatflow`)的系统提示词中,并绑定 Hxops Tool OpenAPI:`GET /api/shipping-notice/tools/openapi.json`(Header:`X-Shipping-Tool-Key`)。 + +--- + +## 角色 + +你是 **货代发货通知助手**,帮助业务人员处理客户发货指令(邮件/微信/PDF 文本)。你通过调用 Hxops Tool API 完成确定性流程,并在需要人工复核时暂停,等待用户明确选择后再继续。 + +## 核心原则 + +1. **先建 case**:收到新的发货需求时,先调用 `create_case`,保存 `case_id`(如 `SN-20260529-ABCD1234`),后续所有 Tool 都带上 `case_id`。 +2. **按序编排**:`parse_notice` → `ensure_inventory` → `match_inventory` →(人工确认)→ `generate_shipment_excel` → `upload_to_freight`。 +3. **尊重 Tool 响应**:每次 Tool 返回 `status` 为 `needs_human` 或 `running` 时,向用户说明原因与可选操作(`human_options`),**不要擅自跳过**。 +4. **人工决策**:用户说「确认/驳回/重试 RPA/手工上传完成」等时,调用 `submit_decision` 或对应 Tool 的 `mode` 参数。 +5. **状态查询**:不确定进度时调用 `get_case_status`。 + +## Tool 响应约定 + +```json +{ + "status": "ok | running | needs_human | failed", + "case_id": "SN-YYYYMMDD-XXXXXXXX", + "message": "人类可读说明", + "data": {}, + "human_options": ["confirm", "reject", "retry_rpa", ...] +} +``` + +| status | 含义 | 你的行为 | +|--------|------|----------| +| `ok` | 步骤成功 | 继续下一步或总结 | +| `running` | 异步进行中(如 RPA) | 告知用户等待,可稍后 `get_case_status` | +| `needs_human` | 必须人工选择 | 列出 `human_options`,等用户回复 | +| `failed` | 不可恢复错误 | 说明错误,建议联系管理员 | + +## 典型流程 + +### 1. 解析发货通知 + +用户粘贴邮件/微信/PDF 文本 → `parse_notice`(`case_id`, `raw_content`)。 + +- `needs_human` + `low_parse_confidence`:展示解析字段,请用户 **confirm / reject / reparse**。 +- `confirm` → `submit_decision`(`decision: confirm`)。 + +### 2. 库存 + +`ensure_inventory`(`case_id`, `mode: auto`)。 + +- `running`:RPA 已触发,告知等待。 +- `needs_human` + 无库存:提供 **retry_rpa** 或 **upload_inventory_file**(用户上传 Excel 路径/内容由 Tool 处理)。 +- 手工库存可传 `inventory_lines_json` 字符串,如 `[{"sku":"A001","available_qty":10}]`。 +- `ok` → 继续匹配。 + +### 3. 匹配 + +`match_inventory`(`case_id`)。 + +- `needs_human` + 库存不足:展示 shortage,请 **confirm / reject / rematch**。 +- `ok` + `fulfillable` → 生成 Excel。 + +### 4. 生成 Excel + +`generate_shipment_excel`(`case_id`)→ 告知文件名,可下载链接:`/api/shipping-notice/cases/{case_no}/export`。 + +### 5. 上传货代 + +`upload_to_freight`(`case_id`, `mode: auto`)。 + +- `running`:RPA 上传中。 +- `needs_human`:提供 **retry_upload / download_excel / mark_manual_uploaded**。 +- 用户手工上传后说「已上传,单号 XXX」→ `upload_to_freight`(`mode: manual_confirm`, `freight_ref_no: XXX`)。 + +## 对话风格 + +- 简洁中文,先给结论再列明细表格(SKU、数量、缺口)。 +- 每次操作复述当前 `case_id`。 +- 不要编造库存或货代单号;以 Tool 返回的 `data` 为准。 + +## 变量(可选) + +在 Chatflow 中可注入: + +- `{{user_id}}` — 创建 case 时传入 +- `{{conversation_id}}` — Dify 会话 ID,便于工作台关联 + +## 内部 Workflow + +字段抽取 Workflow **「发货通知字段抽取」** 由 `parse_notice` Tool 内部调用,Chatflow **无需**直接调用。 diff --git a/docs/shipping_notice_runbook.md b/docs/shipping_notice_runbook.md new file mode 100644 index 00000000..c9fcfb52 --- /dev/null +++ b/docs/shipping_notice_runbook.md @@ -0,0 +1,93 @@ +# 货代发货通知 — 本地部署 Runbook + +## 1. 数据库迁移 + +```bash +cd backend +flask db upgrade +``` + +## 2. 环境变量(`.env.dev` 示例) + +```env +# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) +SHIPPING_NOTICE_TOOL_API_KEY=your-tool-key + +# 文件存储(可选,默认 instance/shipping_notice) +SHIPPING_NOTICE_STORAGE_ROOT=backend/data/shipping_notice + +# RPA 目录(开发机本地路径,需 RPA worker 与 backend 一致) +FREIGHT_INVENTORY_DROP_DIR=backend/data/freight_rpa/inventory_drop +FREIGHT_RPA_INVENTORY_TRIGGER_DIR=backend/data/freight_rpa/inventory_triggers +FREIGHT_UPLOAD_QUEUE_DIR=backend/data/freight_rpa/upload_queue +FREIGHT_RPA_UPLOAD_TRIGGER_DIR=backend/data/freight_rpa/upload_triggers + +# 发货 Excel 模板(可选,默认 backend/templates/freight_shipment_upload.xlsx) +FREIGHT_SHIPMENT_TEMPLATE_PATH=backend/templates/freight_shipment_upload.xlsx + +# Dify Chatflow / Workflow(seed 脚本用) +SHIPPING_NOTICE_CHAT_DIFY_APP_ID= +SHIPPING_NOTICE_CHAT_DIFY_API_KEY= +SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 +SHIPPING_NOTICE_EXTRACT_DIFY_APP_ID= +SHIPPING_NOTICE_EXTRACT_DIFY_API_KEY= +``` + +生成模板(若尚未存在): + +```bash +python backend/scripts/generate_freight_shipment_template.py +``` + +## 3. 注册 Agent 记录 + +```bash +cd backend +python seed_shipping_notice_agents.py +``` + +在 Dify 创建同名应用后,把 `dify_app_id` / API Key 写入 `.env` 并重新 seed。 + +## 4. Dify Chatflow 配置 + +详细图文步骤见 **`docs/shipping_notice_dify_openapi_setup.md`**。 + +1. 创建 Chatflow 应用 **货代发货通知 Agent**,写入 `.env` 后 `python seed_shipping_notice_agents.py` +2. Dify → **工具 → 自定义** → 从 URL 导入: + `http:///api/shipping-notice/tools/openapi.json` +3. 鉴权 Header:`X-Shipping-Tool-Key: ` +4. Chatflow Agent 节点绑定该工具(8 个 operation) +5. 系统提示词:复制 `docs/shipping_notice_dify_prompt.md` + +## 5. 开发环境 Mock RPA + +```powershell +# 与 backend 相同四个 FREIGHT_* 目录 +$env:HXOPS_API_BASE = "http://127.0.0.1:5052" +$env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" +$env:FREIGHT_RPA_MOCK = "true" +python scripts/rpa/freight_rpa_worker.py +``` + +详见 `scripts/rpa/README.md`。 + +## 6. 前端入口 + +- 工作台侧边栏 **货代发货**(只读 case 列表) +- 独立路由 `/shipping-notice` +- 点击 **在 Chat 中继续** → `/chat/{agentId}?case_id=SN-...` 自动查询状态 + +## 7. 端到端验证 + +```bash +cd backend +pytest tests/test_shipping_notice_tools.py -q +``` + +Tool 流程:create → parse → ensure_inventory(inventory_lines)→ match → generate_excel → get_case_status。 + +## 8. 待业务提供 + +- 货代系统库存导出 SOP + 样例 Excel 列名(可配置 `FREIGHT_INVENTORY_COLUMN_MAP`) +- 货代上传 SOP + 正式上传模板列映射 +- 生产 Windows RPA 账号与 UiPath/Power Automate 脚本 diff --git a/frontend/src/api/shippingNotice.ts b/frontend/src/api/shippingNotice.ts new file mode 100644 index 00000000..bce63bd1 --- /dev/null +++ b/frontend/src/api/shippingNotice.ts @@ -0,0 +1,60 @@ +import { getAuthHeaders } from '../utils/auth'; + +export interface ShippingCaseSummary { + id: number; + case_no: string; + source_type: string; + customer_name?: string | null; + process_status: string; + review_status?: string | null; + match_status?: string | null; + pending_human_reason?: string | null; + conversation_id?: string | null; + export_file_name?: string | null; + freight_ref_no?: string | null; + created_at?: string | null; + updated_at?: string | null; +} + +export interface ShippingCaseEvent { + event_type: string; + detail_json?: Record | null; + created_at?: string | null; +} + +export interface ShippingCaseDetail extends ShippingCaseSummary { + customer_code?: string | null; + ship_to?: string | null; + required_date?: string | null; + lines: Array>; + shortage?: Record | null; + line_results?: Array>; + parse_confidence?: number | null; + error_message?: string | null; + events: ShippingCaseEvent[]; +} + +async function getJson(url: string): Promise { + const res = await fetch(url, { headers: getAuthHeaders() }); + if (!res.ok) { + const body = await res.json().catch(() => ({})); + throw new Error((body as { error?: string }).error || res.statusText); + } + return res.json() as Promise; +} + +export const listWorkspaceShippingCases = (params?: { process_status?: string; limit?: number }) => { + const sp = new URLSearchParams(); + if (params?.process_status) sp.set('process_status', params.process_status); + if (params?.limit) sp.set('limit', String(params.limit)); + const qs = sp.toString(); + return getJson(`/api/workspace/shipping-cases${qs ? '?' + qs : ''}`); +}; + +export const getWorkspaceShippingCase = (caseNo: string) => + getJson(`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}`); + +export const workspaceShippingExportUrl = (caseNo: string) => + `/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/export`; + +export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'; diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index c341a190..4e639bc1 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1,4 +1,4 @@ -import { createI18n } from 'vue-i18n'; +import { createI18n } from 'vue-i18n'; const messages = { 'en': { @@ -353,6 +353,7 @@ const messages = { applications: 'Applications', knowledgeBase: 'Knowledge Base', scheduleRuns: 'Schedule Runs', + shippingNotice: 'Shipping Notice', feedback: 'Feedback', updates: 'Recent Updates', backToChat: 'Back to Chat', @@ -408,6 +409,40 @@ const messages = { downloadExcelFailed: 'Failed to download Excel' } }, + shippingNotice: { + title: 'Shipping Notice Cases', + subtitle: 'Read-only view. Continue processing in Chat.', + refresh: 'Refresh', + search: 'Search', + loading: 'Loading...', + empty: 'No shipping cases yet', + selectCase: 'Select a case to view details', + loadFailed: 'Failed to load case', + openChat: 'Continue in Chat', + download: 'Download Excel', + lines: 'Shipment lines', + qty: 'Qty', + events: 'Event log', + filters: { + status: 'Status' + }, + fields: { + status: 'Process status', + match: 'Match status', + shipTo: 'Ship to', + freightRef: 'Freight ref no.' + }, + status: { + all: 'All', + created: 'Created', + waitingInventory: 'Waiting inventory', + inventoryReady: 'Inventory ready', + matched: 'Matched', + waitingUpload: 'Waiting upload', + uploaded: 'Uploaded', + uploadFailed: 'Upload failed' + } + }, profile: { msg: { loadFailed: 'Failed to load profile', @@ -1214,6 +1249,7 @@ const messages = { thinking: 'Generating response...', disclaimer: 'AI can make mistakes. Please verify important information.', createNewChat: 'New Chat', + shippingNoticeContinue: 'Please continue shipping case {caseId}. Call get_case_status first and tell me the next step.', clearAll: 'Clear All', clearOneRecord: 'Clear This Record', agents: 'Agents', @@ -1808,6 +1844,7 @@ const messages = { applications: '应用管理', knowledgeBase: '知识库管理', scheduleRuns: '排程记录', + shippingNotice: '货代发货', feedback: '意见反馈', updates: '最近更新', backToChat: '返回聊天', @@ -1863,6 +1900,40 @@ const messages = { downloadExcelFailed: '下载 Excel 失败' } }, + shippingNotice: { + title: '货代发货通知', + subtitle: '只读工作台,请在 Chat 中继续处理。', + refresh: '刷新', + search: '查询', + loading: '正在加载...', + empty: '暂无发货任务', + selectCase: '选择左侧任务查看详情', + loadFailed: '加载失败', + openChat: '在 Chat 中继续', + download: '下载 Excel', + lines: '发货明细', + qty: '数量', + events: '事件记录', + filters: { + status: '状态' + }, + fields: { + status: '流程状态', + match: '匹配状态', + shipTo: '收货地址', + freightRef: '货代单号' + }, + status: { + all: '全部', + created: '已创建', + waitingInventory: '等待库存', + inventoryReady: '库存就绪', + matched: '已匹配', + waitingUpload: '等待上传', + uploaded: '已上传', + uploadFailed: '上传失败' + } + }, profile: { msg: { loadFailed: '加载个人中心失败', @@ -2648,6 +2719,7 @@ const messages = { thinking: '正在生成回答...', disclaimer: 'AI 可能会犯错,请核实重要信息。', createNewChat: '创建新对话', + shippingNoticeContinue: '请继续处理发货任务 {caseId},请先调用 get_case_status 查询当前状态并告知我下一步。', clearAll: '清空全部', clearOneRecord: '清除该记录', agents: '智能体', diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 2e7ca496..8903cda2 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -6,6 +6,7 @@ import ChatView from '../views/ChatView.vue'; import AdminView from '../views/AdminView.vue'; import ResetPasswordView from '../views/ResetPasswordView.vue'; import KbWorkspaceView from '../views/KbWorkspaceView.vue'; +import ShippingNoticeView from '../views/ShippingNoticeView.vue'; import { config } from '../config'; import { getStoredAuthUser } from '../utils/auth'; @@ -47,6 +48,12 @@ const routes = [ component: KbWorkspaceView, meta: { title: '知识库工作台' } }, + { + path: '/shipping-notice', + name: 'ShippingNotice', + component: ShippingNoticeView, + meta: { title: '货代发货通知' } + }, { path: '/kb/admin', redirect: { path: '/admin', query: { module: 'knowledge_base' } } diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 31f5a689..34ff6830 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -1671,6 +1671,11 @@ const presetQuestion = computed(() => { return typeof q === 'string' ? q : ''; }); +const shippingCaseIdFromQuery = computed(() => { + const value = route.query.case_id; + return typeof value === 'string' ? value.trim() : ''; +}); + /** * handleSend * 用途:将输入框内容发送给当前 Agent @@ -2072,6 +2077,9 @@ onMounted(async () => { if (presetQuestion.value) { input.value = presetQuestion.value; handleSend(); + } else if (shippingCaseIdFromQuery.value) { + input.value = t('chat.shippingNoticeContinue', { caseId: shippingCaseIdFromQuery.value }); + handleSend(); } // Use config from config.ts instead of API showChatRating.value = config.workspace?.showChatRating ?? true; diff --git a/frontend/src/views/ShippingNoticeView.vue b/frontend/src/views/ShippingNoticeView.vue new file mode 100644 index 00000000..620f4a65 --- /dev/null +++ b/frontend/src/views/ShippingNoticeView.vue @@ -0,0 +1,271 @@ + + + diff --git a/frontend/src/views/WorkspaceView.vue b/frontend/src/views/WorkspaceView.vue index 93550e25..06e238f1 100644 --- a/frontend/src/views/WorkspaceView.vue +++ b/frontend/src/views/WorkspaceView.vue @@ -56,8 +56,9 @@ import { } from 'lucide-vue-next'; import KbWorkspaceView from './KbWorkspaceView.vue'; +import ShippingNoticeView from './ShippingNoticeView.vue'; import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule'; -import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next'; +import { Clock, Download, Search, RefreshCw, Package } from 'lucide-vue-next'; const { t, locale } = useI18n(); const msg = useMessage(); @@ -779,7 +780,7 @@ const handleRegister = async () => { } }; -const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base' | 'schedule_runs' | 'history'>('applications'); +const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base' | 'schedule_runs' | 'shipping_notice' | 'history'>('applications'); const wsScheduleFilterInputClass = 'admin-table-filter-input text-xs py-1.5 px-2'; const isProfileLoading = ref(false); const isProfileSaving = ref(false); @@ -1040,6 +1041,10 @@ const navigateToScheduleRuns = () => { loadWorkspaceScheduleRuns(); }; +const navigateToShippingNotice = () => { + activeSidebarItem.value = 'shipping_notice'; +}; + const workspaceScheduleRuns = ref([]); const workspaceScheduleLoading = ref(false); const wsScheduleStatusFilter = ref('all'); @@ -1385,7 +1390,7 @@ onMounted(async () => { await fetchHome(); await handleWecomDeeplinkContext(); const viewParam = route.query.view as string; - const validViews: string[] = ['profile', 'applications', 'feedback', 'updates', 'knowledge_base', 'schedule_runs', 'history']; + const validViews: string[] = ['profile', 'applications', 'feedback', 'updates', 'knowledge_base', 'schedule_runs', 'shipping_notice', 'history']; if (viewParam && validViews.includes(viewParam)) { activeSidebarItem.value = viewParam as typeof activeSidebarItem.value; if (viewParam === 'profile' && !profileUser.value.id) { @@ -1626,6 +1631,14 @@ onBeforeUnmount(() => { {{ $t('workspace.nav.scheduleRuns') }} +