feat(shipping-notice): 新增货代发货通知全流程业务功能

- 新增后端完整业务支持:数据库模型、API接口、核心服务与RPA对接逻辑
- 新增前端工作台页面、路由适配与多语言国际化
- 新增Dify自定义工具OpenAPI规范、Agent配置脚本与部署文档
- 新增发货Excel模板生成脚本与默认模板
- 修复测试配置文件中的环境变量命名错误
- 更新本地开发环境变量配置
This commit is contained in:
hugo committed 2026-06-01 21:22:22 +08:00
1 parent 93e99793d8
commit 2d7bdecc43
46 files changed
+3462 -7

No files matched your search

+12 -1
View File
@@ -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
+4
View File
@@ -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
+144
View File
@@ -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/<case_no>/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",
)
@@ -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/<case_no>", 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/<case_no>/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",
)
+14
View File
@@ -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')
+60 -1
View File
@@ -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")
Whitespace-only changes.
@@ -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()
@@ -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
@@ -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,
}
@@ -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
@@ -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}
@@ -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"],
),
},
}
@@ -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
@@ -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)
@@ -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
@@ -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"],
)
@@ -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')
@@ -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()
@@ -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()
+77
View File
@@ -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.")
Binary file not shown.
+1 -1
View File
@@ -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
+222
View File
@@ -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"
@@ -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": []
}
]
}
}
}
}
+211
View File
@@ -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=<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://<hxops-host>:<port>`
### 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 |
+90
View File
@@ -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 **无需**直接调用。
+93
View File
@@ -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://<PUBLIC_BASE_URL>/api/shipping-notice/tools/openapi.json`
3. 鉴权 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_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 脚本
+60
View File
@@ -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<string, unknown> | null;
created_at?: string | null;
}
export interface ShippingCaseDetail extends ShippingCaseSummary {
customer_code?: string | null;
ship_to?: string | null;
required_date?: string | null;
lines: Array<Record<string, unknown>>;
shortage?: Record<string, unknown> | null;
line_results?: Array<Record<string, unknown>>;
parse_confidence?: number | null;
error_message?: string | null;
events: ShippingCaseEvent[];
}
async function getJson<T>(url: string): Promise<T> {
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<T>;
}
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<ShippingCaseSummary[]>(`/api/workspace/shipping-cases${qs ? '?' + qs : ''}`);
};
export const getWorkspaceShippingCase = (caseNo: string) =>
getJson<ShippingCaseDetail>(`/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';
+73 -1
View File
@@ -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: '智能体',
+7
View File
@@ -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' } }
+8
View File
@@ -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;
+271
View File
@@ -0,0 +1,271 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ArrowLeft, Download, ExternalLink, RefreshCw } from 'lucide-vue-next';
import {
getWorkspaceShippingCase,
listWorkspaceShippingCases,
SHIPPING_NOTICE_AGENT_NAME,
workspaceShippingExportUrl,
type ShippingCaseDetail,
type ShippingCaseSummary,
} from '../api/shippingNotice';
import { getAuthHeaders } from '../utils/auth';
const props = defineProps<{
embedded?: boolean;
}>();
const router = useRouter();
const { t } = useI18n();
const loading = ref(false);
const detailLoading = ref(false);
const cases = ref<ShippingCaseSummary[]>([]);
const selectedCaseNo = ref<string | null>(null);
const detail = ref<ShippingCaseDetail | null>(null);
const statusFilter = ref('all');
const chatAgentId = ref<number | null>(null);
const statusOptions = computed(() => [
{ value: 'all', label: t('workspace.shippingNotice.status.all') },
{ value: 'created', label: t('workspace.shippingNotice.status.created') },
{ value: 'waiting_inventory', label: t('workspace.shippingNotice.status.waitingInventory') },
{ value: 'inventory_ready', label: t('workspace.shippingNotice.status.inventoryReady') },
{ value: 'matched', label: t('workspace.shippingNotice.status.matched') },
{ value: 'waiting_upload', label: t('workspace.shippingNotice.status.waitingUpload') },
{ value: 'uploaded', label: t('workspace.shippingNotice.status.uploaded') },
{ value: 'upload_failed', label: t('workspace.shippingNotice.status.uploadFailed') },
]);
const statusBadge = (status: string) => {
const map: Record<string, { cls: string; label: string }> = {
created: { cls: 'bg-slate-100 text-secondary', label: t('workspace.shippingNotice.status.created') },
waiting_inventory: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.shippingNotice.status.waitingInventory') },
inventory_ready: { cls: 'bg-blue-100 text-blue-700', label: t('workspace.shippingNotice.status.inventoryReady') },
matched: { cls: 'bg-emerald-100 text-emerald-700', label: t('workspace.shippingNotice.status.matched') },
waiting_upload: { cls: 'bg-amber-100 text-amber-700', label: t('workspace.shippingNotice.status.waitingUpload') },
uploaded: { cls: 'bg-emerald-100 text-emerald-700', label: t('workspace.shippingNotice.status.uploaded') },
upload_failed: { cls: 'bg-rose-100 text-rose-700', label: t('workspace.shippingNotice.status.uploadFailed') },
};
return map[status] || { cls: 'bg-slate-100 text-secondary', label: status };
};
const loadCases = async () => {
loading.value = true;
try {
cases.value = await listWorkspaceShippingCases({
process_status: statusFilter.value === 'all' ? undefined : statusFilter.value,
limit: 100,
});
} catch {
cases.value = [];
} finally {
loading.value = false;
}
};
const loadDetail = async (caseNo: string) => {
detailLoading.value = true;
try {
detail.value = await getWorkspaceShippingCase(caseNo);
} catch {
detail.value = null;
} finally {
detailLoading.value = false;
}
};
const resolveChatAgent = async () => {
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (!res.ok) return;
const agents = (await res.json()) as Array<{ id: number; name: string }>;
const found = agents.find((a) => a.name === SHIPPING_NOTICE_AGENT_NAME);
if (found) chatAgentId.value = found.id;
} catch {
/* ignore */
}
};
const openInChat = (caseNo: string) => {
if (!chatAgentId.value) return;
router.push({ path: `/chat/${chatAgentId.value}`, query: { case_id: caseNo } });
};
const downloadExport = async (caseNo: string) => {
const url = workspaceShippingExportUrl(caseNo);
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) return;
const blob = await res.blob();
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = detail.value?.export_file_name || `${caseNo}.xlsx`;
a.click();
URL.revokeObjectURL(a.href);
};
watch(selectedCaseNo, (val) => {
if (val) loadDetail(val);
else detail.value = null;
});
onMounted(async () => {
await Promise.all([loadCases(), resolveChatAgent()]);
});
</script>
<template>
<div class="space-y-5 animate-fade-in-up">
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-3">
<button
v-if="!embedded"
type="button"
class="inline-flex h-9 w-9 items-center justify-center rounded-xl border border-default text-secondary hover:bg-surface-soft"
@click="router.push('/workspace')"
>
<ArrowLeft class="h-4 w-4" />
</button>
<div>
<h2 class="text-2xl font-bold text-primary">{{ $t('workspace.shippingNotice.title') }}</h2>
<p class="text-sm text-muted">{{ $t('workspace.shippingNotice.subtitle') }}</p>
</div>
</div>
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="loadCases"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.refresh') }}
</button>
</div>
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.filters.status') }}</label>
<select v-model="statusFilter" class="rounded-xl border border-default bg-surface px-3 py-2 text-sm">
<option v-for="opt in statusOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
</select>
</div>
<button
type="button"
class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700"
@click="loadCases"
>
{{ $t('workspace.shippingNotice.search') }}
</button>
</div>
<div class="grid gap-5 lg:grid-cols-5">
<div class="lg:col-span-2 space-y-2">
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<div v-else-if="cases.length === 0" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.empty') }}
</div>
<button
v-for="item in cases"
:key="item.case_no"
type="button"
class="w-full rounded-2xl border px-4 py-3 text-left transition-colors"
:class="selectedCaseNo === item.case_no ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
@click="selectedCaseNo = item.case_no"
>
<div class="flex items-center justify-between gap-2">
<span class="font-mono text-sm font-semibold text-primary">{{ item.case_no }}</span>
<span class="rounded-full px-2 py-0.5 text-xs font-medium" :class="statusBadge(item.process_status).cls">
{{ statusBadge(item.process_status).label }}
</span>
</div>
<div class="mt-1 truncate text-sm text-secondary">{{ item.customer_name || '—' }}</div>
<div class="mt-1 text-xs text-muted">{{ item.created_at || '' }}</div>
</button>
</div>
<div class="lg:col-span-3 rounded-2xl border border-default bg-surface/50 p-5">
<div v-if="!selectedCaseNo" class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.selectCase') }}
</div>
<div v-else-if="detailLoading" class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<div v-else-if="!detail" class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loadFailed') }}
</div>
<div v-else class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<div class="font-mono text-lg font-bold text-primary">{{ detail.case_no }}</div>
<div class="text-sm text-muted">{{ detail.customer_name }} · {{ detail.customer_code || '—' }}</div>
</div>
<div class="flex flex-wrap gap-2">
<button
v-if="chatAgentId"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-brand-300 bg-brand-50 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-100"
@click="openInChat(detail.case_no)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
</button>
<button
v-if="detail.export_file_name"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
@click="downloadExport(detail.case_no)"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.download') }}
</button>
</div>
</div>
<dl class="grid gap-3 sm:grid-cols-2 text-sm">
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt><dd>{{ detail.process_status }}</dd></div>
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt><dd>{{ detail.match_status || '—' }}</dd></div>
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.shipTo') }}</dt><dd>{{ detail.ship_to || '—' }}</dd></div>
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.freightRef') }}</dt><dd>{{ detail.freight_ref_no || '—' }}</dd></div>
</dl>
<div v-if="detail.error_message" class="rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-700">
{{ detail.error_message }}
</div>
<div v-if="detail.lines?.length">
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.lines') }}</h3>
<div class="overflow-x-auto rounded-xl border border-default">
<table class="min-w-full text-sm">
<thead class="bg-surface-soft text-left text-xs text-muted">
<tr>
<th class="px-3 py-2">SKU</th>
<th class="px-3 py-2">{{ $t('workspace.shippingNotice.qty') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(line, idx) in detail.lines" :key="idx" class="border-t border-default/60">
<td class="px-3 py-2 font-mono">{{ line.sku || line.part_no || '—' }}</td>
<td class="px-3 py-2">{{ line.qty ?? line.quantity ?? '—' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-if="detail.events?.length">
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.events') }}</h3>
<ul class="max-h-48 space-y-1 overflow-y-auto text-xs text-muted">
<li v-for="(ev, idx) in [...detail.events].reverse()" :key="idx">
<span class="font-medium text-secondary">{{ ev.event_type }}</span>
<span class="ml-2">{{ ev.created_at }}</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</template>
+20 -3
View File
@@ -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<ScheduleRun[]>([]);
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(() => {
<Clock class="h-4 w-4" />
<span>{{ $t('workspace.nav.scheduleRuns') }}</span>
</button>
<button
@click="navigateToShippingNotice"
class="ws-nav-btn"
:class="{ 'ws-nav-btn--active': activeSidebarItem === 'shipping_notice' }"
>
<Package class="h-4 w-4" />
<span>{{ $t('workspace.nav.shippingNotice') }}</span>
</button>
<button
@click="openGeneralFeedback"
class="ws-nav-btn"
@@ -1998,6 +2011,10 @@ onBeforeUnmount(() => {
</div>
</template>
<template v-else-if="activeSidebarItem === 'shipping_notice'">
<ShippingNoticeView :embedded="true" />
</template>
<template v-else>
<div v-if="wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{{ wecomEntryHint }}
+37
View File
@@ -0,0 +1,37 @@
# 货代 RPA PoC
Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA 脚本在 Windows 货代终端上运行(或由本 PoC worker 在开发环境模拟)。
## 目录约定
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{case_no}.json`,RPA 读取后导库存 |
| `FREIGHT_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{case_no}.json` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
## 开发环境 Mock
1. 在 `.env.dev` 配置目录与 Tool Key(见 `docs/shipping_notice_runbook.md`)。
2. 启动后端。
3. 另开终端运行 PoC worker:
```powershell
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与 backend 一致>"
$env:FREIGHT_RPA_MOCK = "true"
# 四个 FREIGHT_* 目录与 backend 相同
python scripts/rpa/freight_rpa_worker.py
```
4. 在 Chat 中走 `ensure_inventory` / `upload_to_freight`,worker 会自动回调 `/api/shipping-notice/rpa/*`。
## 生产 RPA
`FREIGHT_RPA_MOCK=false` 时 worker **不会**自动处理触发文件,需业务按 SOP 用 UiPath / Power Automate 等:
1. 监听 `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 新 JSON → 登录货代 UI 导出库存 → 保存到 `FREIGHT_INVENTORY_DROP_DIR` → POST `inventory-ready`。
2. 监听 `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` → 读取 `file_path` 在货代 UI 上传 → POST `upload-complete`。
回调 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`。
+203
View File
@@ -0,0 +1,203 @@
"""
Freight RPA worker (PoC).
Polls trigger JSON files written by hxops and reports results back via Tool API callbacks.
Set FREIGHT_RPA_MOCK=true to simulate export/upload without a real freight UI.
Usage:
python scripts/rpa/freight_rpa_worker.py
Required env (same as backend):
HXOPS_API_BASE e.g. http://127.0.0.1:5052
SHIPPING_NOTICE_TOOL_API_KEY
FREIGHT_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR
Optional:
FREIGHT_RPA_MOCK=true
FREIGHT_RPA_POLL_SECONDS=3
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
"""
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
try:
from openpyxl import Workbook
except ImportError:
Workbook = None # type: ignore
def _env(name: str, default: str = "") -> str:
return str(os.getenv(name) or default).strip()
def _require_path(name: str) -> Path:
value = _env(name)
if not value:
raise SystemExit(f"Missing env: {name}")
path = Path(value)
path.mkdir(parents=True, exist_ok=True)
return path
def _post_callback(path: str, payload: dict) -> None:
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
key = _env("SHIPPING_NOTICE_TOOL_API_KEY") or _env("INTEGRATION_API_KEY")
if not key:
raise SystemExit("Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY")
url = f"{base}{path}"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={
"Content-Type": "application/json",
"X-Shipping-Tool-Key": key,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
body = resp.read().decode("utf-8")
print(f"[callback] {path} -> {resp.status} {body[:200]}")
except urllib.error.HTTPError as exc:
err = exc.read().decode("utf-8", errors="replace")
print(f"[callback] {path} HTTP {exc.code}: {err[:300]}", file=sys.stderr)
def _write_sample_inventory(drop_dir: Path, case_no: str) -> Path:
sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY")
if sample and Path(sample).is_file():
dest = drop_dir / Path(sample).name
shutil.copy2(sample, dest)
return dest
if Workbook is None:
raise RuntimeError("openpyxl required to generate mock inventory")
dest = drop_dir / f"inventory_{case_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
wb = Workbook()
ws = wb.active
ws.title = "Inventory"
ws.append(["料号", "可用数量"])
ws.append(["A001", 100])
ws.append(["A002", 50])
wb.save(dest)
return dest
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
case_no = str(body.get("case_no") or "").strip()
if not case_no:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
if not mock:
print(f"[inventory] real RPA not implemented; trigger kept: {trigger_path.name}")
return
try:
out_file = _write_sample_inventory(drop_dir, case_no)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"case_no": case_no,
"success": True,
"file_path": str(out_file),
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[inventory] mock export done for {case_no} -> {out_file.name}")
except Exception as exc:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"case_no": case_no,
"success": False,
"error_message": str(exc),
})
trigger_path.unlink(missing_ok=True)
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
case_no = str(body.get("case_no") or "").strip()
file_path = str(body.get("file_path") or "").strip()
if not case_no:
trigger_path.unlink(missing_ok=True)
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
if not mock:
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
return
if file_path and not Path(file_path).is_file():
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"case_no": case_no,
"success": False,
"error_message": f"queue file missing: {file_path}",
})
trigger_path.unlink(missing_ok=True)
return
ref = f"MOCK-{case_no}-{datetime.utcnow().strftime('%H%M%S')}"
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"case_no": case_no,
"success": True,
"freight_ref_no": ref,
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[upload] mock upload done for {case_no} ref={ref}")
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
if not trigger_dir.is_dir():
return
for path in sorted(trigger_dir.glob("*.json")):
if not path.is_file():
continue
try:
handler(path, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
def main() -> None:
drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR")
inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR")
upload_trigger_dir = _require_path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
poll = max(1, int(_env("FREIGHT_RPA_POLL_SECONDS", "3") or "3"))
inv_processed = inv_trigger_dir / "processed"
upload_processed = upload_trigger_dir / "processed"
print("[freight_rpa_worker] started")
print(f" mock={_env('FREIGHT_RPA_MOCK', 'true')}")
print(f" inventory_triggers={inv_trigger_dir}")
print(f" upload_triggers={upload_trigger_dir}")
print(f" drop={drop_dir}")
print(f" queue={upload_queue_dir}")
while True:
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
time.sleep(poll)
if __name__ == "__main__":
main()