feat(shipping-notice): 新增货代发货通知全流程业务功能
- 新增后端完整业务支持:数据库模型、API接口、核心服务与RPA对接逻辑 - 新增前端工作台页面、路由适配与多语言国际化 - 新增Dify自定义工具OpenAPI规范、Agent配置脚本与部署文档 - 新增发货Excel模板生成脚本与默认模板 - 修复测试配置文件中的环境变量命名错误 - 更新本地开发环境变量配置
This commit is contained in:
1 parent
93e99793d8
commit
2d7bdecc43
46 files changed
+3462
-7
No files matched your search
@@ -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
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
@@ -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
@@ -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"],
|
||||
)
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -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()
|
||||
@@ -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.
@@ -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
|
||||
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user