feat(shipping_notice): 完成货代发货通知全流程功能迭代与重构

主要变更:
1.  移除废弃的发货通知字段抽取独立Workflow Agent相关代码
2.  重构Dify服务调用,新增inputs参数支持注入环境变量配置的工具API地址与密钥
3.  新增auto_progress工具API与checkpoint catalog接口,支持流程自动推进
4.  统一字段命名,将column_mapping_json改为map_json并兼容旧有调用
5.  重构库存匹配、解析结果的展示格式,改为标准化多语言Markdown表格
6.  新增ODM ID库存字段支持,优化库存解析与映射逻辑
7.  新增LibreOffice转换隔离Profile配置,避免多实例运行冲突
8.  新增完整环境变量配置、数据库迁移脚本与测试用例
9.  适配前端代码,更新字段命名与聊天跳转逻辑
10. 更新OpenAPI规范适配Dify工具调用,删除已归档的旧部署文档
This commit is contained in:
hugo committed 2026-06-08 16:07:20 +08:00
1 parent 2ce5256483
commit c18c0394d0
50 files changed
+6088 -2407

No files matched your search

+48 -4
View File
@@ -55,13 +55,57 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# 货代发货通知 Agent
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2)
# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL)
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.108:5052/api/shipping-notice
# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL + /api/shipping-notice)
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.108:5052/
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# 解析与文本上限
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# 字段对齐确认(生产建议 true;测试可设 false)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
# 自动推进(auto_progress)
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 shipping_notice.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
# FREIGHT_RPA_MOCK=true
# FREIGHT_RPA_POLL_SECONDS=3
# FREIGHT_RPA_SAMPLE_INVENTORY=
+23 -1
View File
@@ -102,4 +102,26 @@ SRM_SQLSERVER_TIMEOUT=10
# ERP
ERP_DB_DSN=192.168.8.24:1521/topprod
TEXT2SQL_SCHEMA_PATH=
TEXT2SQL_SCHEMA_PATH=
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=120
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
SHIPPING_NOTICE_CHAT_DIFY_BASE=
+14 -1
View File
@@ -1099,7 +1099,20 @@ def chat_completions():
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
dify_inputs = None
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs, is_shipping_notice_chat_agent
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_dify_chat_inputs()
generator = DifyService.stream_chat(
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
files=normalized_files,
inputs=dify_inputs,
)
def relay_stream():
created_event = {
+15 -8
View File
@@ -8,20 +8,14 @@ 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
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
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
return resolve_tool_api_base_url()
def _dify_openapi_spec() -> dict:
@@ -37,6 +31,14 @@ def openapi_spec():
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
def checkpoint_catalog():
"""Checkpoint ids, human_options, action_buttons — developer/docs reference (Dify approach B: do not embed)."""
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
return jsonify(build_checkpoint_catalog())
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
def openapi_dify_yaml():
import yaml
@@ -83,6 +85,11 @@ def tool_ensure_inventory():
return jsonify(shipping_tools.ensure_inventory(_payload()))
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
def tool_auto_progress():
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
def tool_match_inventory():
return jsonify(shipping_tools.match_inventory(_payload()))
+82 -64
View File
@@ -7,6 +7,7 @@ from app import db
from app.auth_jwt import get_current_user
from app.models import ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
get_task_for_user,
list_tasks_for_user,
@@ -82,51 +83,18 @@ def workspace_create_shipping_task_from_notice():
raw = upload.read() or b""
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
text, meta = extract_notice_text(saved_path)
dify_file_id = ""
notice_files = None
try:
from app.config import Config
from app.services.dify import DifyService
from app.services.shipping_notice.agent_resolver import resolve_extract_agent
import requests
if not text:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
agent = resolve_extract_agent()
api_key = str(getattr(agent, "dify_api_key", "") or "").strip() if agent else ""
if api_key:
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
dify_url = DifyService._build_files_upload_url(base_url)
resp = requests.post(
dify_url,
headers={"Authorization": f"Bearer {api_key}"},
files={"file": (upload.filename or "notice", raw, upload.mimetype or "application/octet-stream")},
data={"user": str(user.id)},
timeout=(5, 300),
)
if resp.ok:
data = resp.json() if resp.content else {}
dify_file_id = str(data.get("id") or "").strip()
if dify_file_id:
notice_files = [
{
"type": "document",
"transfer_method": "local_file",
"upload_file_id": dify_file_id,
}
]
else:
meta.setdefault("warnings", []).append(f"dify_upload_failed:{resp.status_code}")
except Exception as exc:
meta.setdefault("warnings", []).append(f"dify_upload_error:{exc}")
if (not text) and (not notice_files):
return jsonify(
{
"status": "needs_human",
"task_id": task_id,
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
"data": {"notice_upload": {"filename": upload.filename or "", "dify_file_id": dify_file_id, **meta}},
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
"human_options": ["reparse", "reject"],
"checkpoint": "notice_text_extraction_failed",
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
"action_buttons": action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED),
}
)
@@ -141,12 +109,10 @@ def workspace_create_shipping_task_from_notice():
db.session.commit()
payload = {"task_id": task_id}
if notice_files:
payload["notice_files"] = notice_files
parsed = shipping_tools.parse_notice(payload)
data = parsed.get("data") if isinstance(parsed, dict) else None
if isinstance(data, dict):
data["notice_upload"] = {"filename": upload.filename or "", "dify_file_id": dify_file_id, **meta}
data["notice_upload"] = {"filename": upload.filename or "", **meta}
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
return jsonify(parsed)
@@ -198,14 +164,16 @@ def workspace_apply_inventory_mapping(task_no: str):
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
column_mapping_json = data.get("column_mapping_json")
if not isinstance(column_mapping_json, dict) or not column_mapping_json:
return jsonify({"error": "column_mapping_json is required"}), 400
map_json = data.get(MAP_JSON)
if not isinstance(map_json, dict) or not map_json:
return jsonify({"error": f"{MAP_JSON} is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "column_mapping_json": column_mapping_json}
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
return jsonify(shipping_tools.apply_inventory_mapping(payload))
@@ -226,13 +194,40 @@ def workspace_submit_shipping_decision(task_no: str):
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "decision": decision}
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
def workspace_auto_progress_shipping_task(task_no: str):
"""Hxops chat fallback: same as Dify auto_progress tool."""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload: dict = {"task_id": task.task_no}
for key in ("lang", "locale", "language"):
if data.get(key):
payload[key] = data[key]
break
result = shipping_tools.auto_progress(payload)
if isinstance(result, dict) and result.get("status") == "ok":
gen_data = result.get("data")
if isinstance(gen_data, dict) and gen_data.get("export_file_path"):
gen_data = {**gen_data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"}
result = {**result, "data": gen_data}
return jsonify(result)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
def workspace_match_shipping_inventory(task_no: str):
user, err = _require_user()
@@ -243,28 +238,51 @@ def workspace_match_shipping_inventory(task_no: str):
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint,
human_options_for_checkpoint,
)
matched = shipping_tools.match_inventory({"task_id": task.task_no})
if isinstance(matched, dict) and matched.get("status") == "ok":
generated = shipping_tools.generate_excel({"task_id": task.task_no})
if isinstance(generated, dict) and generated.get("status") == "ok":
msg = "\n".join(
[
str(matched.get("message") or "").strip(),
str(generated.get("message") or "").strip(),
]
).strip()
generated["message"] = msg
data = generated.get("data")
if not isinstance(data, dict):
data = {}
generated["data"] = data
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
generated["checkpoint"] = generated.get("checkpoint") or "export_generated"
return jsonify(generated)
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
if not isinstance(matched, dict):
return jsonify(matched)
data = matched.get("data")
if isinstance(data, dict) and data.get("export_file_path"):
matched = {
**matched,
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
}
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
if matched.get("status") == "ok" and data and data.get("export_file_path"):
matched["checkpoint"] = checkpoint
if "human_options" not in matched:
options = human_options_for_checkpoint(checkpoint)
if options is not None:
matched["human_options"] = options
if "action_buttons" not in matched:
buttons = action_buttons_for_checkpoint(checkpoint)
if buttons:
matched["action_buttons"] = buttons
return jsonify(matched)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
def workspace_mark_manual_uploaded(task_no: str):
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
return jsonify(
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
def workspace_generate_shipping_excel(task_no: str):
user, err = _require_user()
+31
View File
@@ -113,9 +113,40 @@ class Config:
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
'shipment_{task_no}_{ts}.xlsx',
)
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
+2 -1
View File
@@ -508,6 +508,7 @@ class DifyService:
request_id: str | None = None,
session_id: str | None = None,
files: list[dict[str, Any]] | None = None,
inputs: dict[str, Any] | None = None,
):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
@@ -538,7 +539,7 @@ class DifyService:
'Content-Type': 'application/json',
}
payload = {
'inputs': {},
'inputs': dict(inputs or {}),
'query': query,
'response_mode': 'streaming',
'user': str(user_id),
@@ -2,19 +2,8 @@ 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()
@@ -1,137 +1,51 @@
from __future__ import annotations
"""Backward-compatible re-exports — canonical definitions live in state_machine.py."""
from typing import Any
from app.services.shipping_notice.state_machine import (
ACTION_SPECS,
ALL_ACTION_IDS,
ALL_CHECKPOINT_IDS,
CHECKPOINT_REGISTRY,
TaskTransition,
TaskUiState,
action_buttons_for_checkpoint,
apply_task_transition,
build_action_buttons,
build_chat_actions_payload,
build_checkpoint_catalog,
checkpoint_for_task,
format_actions_directive,
human_options_for_checkpoint,
human_options_for_task,
human_options_for_task_or_checkpoint,
resolve_task_ui_state,
ui_state_for_checkpoint,
upload_req_options_for_task,
validate_registry,
)
from app.models import ShippingTask
# Legacy alias
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
"upload_inventory_file": {
"label": "选择库存文件",
"message": "我要上传库存 Excel",
"variant": "secondary",
},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
"mark_manual_uploaded": {
"label": "已手工上传",
"message": "已在货代系统手工上传完成",
"variant": "primary",
},
"paste_inventory_json": {
"label": "粘贴库存",
"message": "我粘贴库存小表",
"variant": "secondary",
},
"edit_inventory_mapping": {
"label": "修改映射",
"message": "修改库存列映射",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
"variant": "primary",
},
}
def human_options_for_task(task: ShippingTask) -> list[str] | None:
if task.process_status == "rejected" or task.review_status == "rejected":
return []
if (
task.process_status == "parsed"
and not task.review_status
and not task.pending_human_reason
and not task.inventory_lines_json
):
return ["upload_inventory_file", "retry_rpa", "paste_inventory_json"]
if (
task.process_status == "inventory_ready"
and not task.review_status
and not task.pending_human_reason
and not task.match_status
and isinstance(task.lines_json, list)
and len(task.lines_json) > 0
):
return ["match_inventory"]
if task.process_status == "matched":
if task.export_file_path:
return ["download_excel", "mark_manual_uploaded"]
return ["generate_excel"]
reason = task.pending_human_reason
if reason == "inventory_field_mapping_review" or task.review_status == "inventory_mapping_review":
return ["confirm_inventory_mapping", "correct_inventory_mapping", "reparse_inventory", "reject"]
if reason == "inventory_mapping_inference":
return ["edit_inventory_mapping", "upload_inventory_file", "paste_inventory_json", "retry_rpa"]
if reason == "reservation_id_required" or task.review_status == "reservation_id_required":
return ["reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"]
if reason == "inventory_unavailable":
return ["retry_rpa", "upload_inventory_file"]
if reason == "inventory_shortage" or task.review_status == "inventory_shortage_review":
return ["confirm", "reject", "rematch"]
if reason == "low_parse_confidence" or task.review_status == "parse_review":
return ["confirm", "reject", "reparse"]
if reason == "upload_rpa_failed" or task.process_status == "upload_failed":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
if reason == "inventory_rpa_pending" or (
task.process_status == "waiting_inventory" and reason == "inventory_rpa_pending"
):
return ["retry_rpa", "upload_inventory_file"]
if reason == "upload_rpa_pending" or task.process_status == "waiting_upload":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
return None
def checkpoint_for_task(task: ShippingTask) -> str | None:
if task.process_status == "rejected" or task.review_status == "rejected":
return "rejected"
reason = task.pending_human_reason
if reason == "inventory_field_mapping_review" or task.review_status == "inventory_mapping_review":
return "inventory_field_mapping_review"
if reason == "low_parse_confidence" or task.review_status == "parse_review":
return "parse_review"
if reason == "inventory_shortage" or task.review_status == "inventory_shortage_review":
return "inventory_shortage_review"
if reason == "inventory_unavailable":
return "inventory_upload_required"
if reason == "inventory_mapping_inference":
return "inventory_mapping_inference"
if reason == "reservation_id_required" or task.review_status == "reservation_id_required":
return "reservation_id_required"
if reason == "upload_rpa_failed" or task.process_status == "upload_failed":
return "upload_failed"
return None
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
if not option_ids:
return []
buttons: list[dict[str, str]] = []
for option_id in option_ids:
spec = ACTION_SPECS.get(option_id)
if not spec:
continue
buttons.append({"id": option_id, **spec})
return buttons
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
options = human_options_for_task(task)
buttons = build_action_buttons(options)
return {
"task_no": task.task_no,
"checkpoint": checkpoint_for_task(task),
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": buttons,
}
__all__ = [
"ACTION_SPECS",
"ALL_ACTION_IDS",
"ALL_CHECKPOINT_IDS",
"CHECKPOINT_OPTIONS",
"CHECKPOINT_REGISTRY",
"TaskTransition",
"TaskUiState",
"action_buttons_for_checkpoint",
"apply_task_transition",
"build_action_buttons",
"build_chat_actions_payload",
"build_checkpoint_catalog",
"checkpoint_for_task",
"format_actions_directive",
"human_options_for_checkpoint",
"human_options_for_task",
"human_options_for_task_or_checkpoint",
"resolve_task_ui_state",
"ui_state_for_checkpoint",
"upload_req_options_for_task",
"validate_registry",
]
@@ -0,0 +1,74 @@
"""Short canonical names for shipping notice API fields and state machine.
Naming layers (avoid drift):
- CP_* — API `checkpoint` / Dify `flow_ckpt` (see state_machine.CHECKPOINT_REGISTRY)
- RS_* — DB `review_status` where used
- PH_* — DB `pending_human_reason` (may equal CP_* when aligned)
- Button ids / registry — state_machine.py only
- DB state writes — state_machine.py `TaskTransition` / `apply_task_transition` (tools.py only)
"""
from __future__ import annotations
from typing import Any
# HTTP JSON request/response fields
MAP_JSON = "map_json"
SUGGEST_OK = "suggest_ok"
AUTO_MAP = "auto_map"
# Workspace / Hxops chat fallback only — Dify Agent 主路径应调 auto_progress,勿在画布 HTTP 传此字段
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Legacy request field names (read-only compat)
MAP_JSON_LEGACY = "column_mapping_json"
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
CP_ALIGN_REVIEW = "align_review"
CP_MAP_INFER = "map_infer"
CP_UPLOAD_REQ = "upload_req"
CP_MAP_OK = "map_ok"
CP_PARSE_OK = "parse_ok"
CP_PARSE_REVIEW = "parse_review"
CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from process_status)
CP_INVENTORY_PENDING = "inventory_pending"
CP_READY_MATCH = "ready_to_match"
CP_READY_EXPORT = "ready_to_export"
CP_EXPORT_READY = "export_ready"
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
CP_EXPORT_GENERATED = "export_generated"
CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
# review_status
RS_ALIGN_REVIEW = "align_review"
RS_PARSE_REVIEW = "parse_review"
RS_SHORTAGE_REVIEW = "shortage_review"
RS_RSV_REQ = "rsv_req"
RS_REJECTED = "rejected"
RS_CONFIRMED = "confirmed"
# pending_human_reason (internal; shortened)
PH_ALIGN_REVIEW = CP_ALIGN_REVIEW
PH_MAP_INFER = CP_MAP_INFER
PH_LOW_CONF = "low_confidence"
PH_RSV_REQ = CP_RSV_REQ
PH_SHORTAGE = "shortage"
PH_RPA_EXHAUSTED = "rpa_exhausted"
PH_RPA_PENDING = "rpa_pending"
PH_INV_UNAVAIL = "inv_unavail"
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
def payload_map_json(payload: dict[str, Any]) -> Any:
raw = payload.get(MAP_JSON)
if raw is None:
raw = payload.get(MAP_JSON_LEGACY)
if raw is None:
raw = payload.get("field_mapping")
return raw
@@ -0,0 +1,26 @@
from __future__ import annotations
from flask import current_app
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
# Dify Chatflow input variable names — must match canvas Start / 输入变量配置.
HXOPS_TOOL_API_BASE_INPUT = "hxops_tool_api_base"
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
def is_shipping_notice_chat_agent(agent) -> bool:
return getattr(agent, "name", None) == CHAT_AGENT_NAME
def build_dify_chat_inputs() -> dict[str, str]:
"""Build Dify chat API inputs so HTTP nodes can reference env-specific hxops URLs."""
base = resolve_tool_api_base_url()
key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
inputs: dict[str, str] = {}
if base:
inputs[HXOPS_TOOL_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
return inputs
+179 -10
View File
@@ -1,14 +1,15 @@
from __future__ import annotations
import os
from datetime import datetime
from pathlib import Path
from shutil import copy2
from typing import Any
from flask import current_app
from openpyxl import Workbook, load_workbook
from app.models import ShippingTask
from app.path_utils import backend_dir, resolve_backend_relative_path
DEFAULT_HEADERS = [
"客户名称",
@@ -21,31 +22,174 @@ DEFAULT_HEADERS = [
"备注",
]
HEADER_SHEET = "PVMI Pull Request Header"
DETAIL_SHEET = "PVMI Pull Request Detail"
DATA_START_ROW = 4
def _storage_root() -> Path:
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
if root:
return Path(root)
return Path(resolve_backend_relative_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)
path = Path(resolve_backend_relative_path(configured))
if path.is_file():
return path
bundled = Path(__file__).resolve().parents[2] / "templates" / "freight_shipment_upload.xlsx"
bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx"
return bundled if bundled.is_file() else None
def _is_pvmi_workbook(wb) -> bool:
return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames
def _format_delivery_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
try:
parsed = datetime.strptime(text[:10], fmt)
return parsed.strftime("%m/%d/%Y")
except ValueError:
continue
if len(text) >= 10 and text[4] == "-" and text[7] == "-":
try:
parsed = datetime.strptime(text[:10], "%Y-%m-%d")
return parsed.strftime("%m/%d/%Y")
except ValueError:
pass
return text
def _delivery_date_for_task(task: ShippingTask) -> str:
if task.required_date:
formatted = _format_delivery_date(task.required_date)
if formatted:
return formatted
for line in task.lines_json or []:
if not isinstance(line, dict):
continue
formatted = _format_delivery_date(line.get("required_date"))
if formatted:
return formatted
return ""
def _resolve_odm_id(task: ShippingTask) -> str:
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
if not inventory_lines:
return ""
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = (
str(row.get("sku") or "").strip(),
str(row.get("reservation_id") or "").strip(),
)
inv_by_key[key] = row
for line in notice_lines:
key = (
str(line.get("sku") or "").strip(),
str(line.get("reservation_id") or "").strip(),
)
matched = inv_by_key.get(key)
if matched:
odm_id = str(matched.get("odm_id") or "").strip()
if odm_id:
return odm_id
for row in inventory_lines:
odm_id = str(row.get("odm_id") or "").strip()
if odm_id:
return odm_id
return ""
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("po_number"), task.po_number):
text = str(value or "").strip()
if text:
return text
return ""
def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("currency"), getattr(task, "currency", None)):
text = str(value or "").strip().upper()
if text:
return text
return ""
def _line_vendor_part_number(line: dict[str, Any]) -> str:
return str(line.get("vendor_part_number") or "").strip()
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
if ws.max_row < from_row:
return
for row_idx in range(from_row, ws.max_row + 1):
for col_idx in range(1, ws.max_column + 1):
ws.cell(row_idx, col_idx).value = None
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
wb = load_workbook(filename=str(path))
header_ws = wb[HEADER_SHEET]
detail_ws = wb[DETAIL_SHEET]
_clear_sheet_data_rows(detail_ws)
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
if header_ws.cell(DATA_START_ROW, 1).value in (None, ""):
header_ws.cell(DATA_START_ROW, 1).value = "AWSDU"
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
header_ws.cell(DATA_START_ROW, 2).value = "n"
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
header_ws.cell(DATA_START_ROW, 3).value = "WEL"
if header_ws.cell(DATA_START_ROW, 4).value in (None, ""):
header_ws.cell(DATA_START_ROW, 4).value = "normal"
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
header_ws.cell(DATA_START_ROW, 7).value = task.task_no
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
if not notice_lines:
notice_lines = [{}]
for index, line in enumerate(notice_lines, start=1):
row_idx = DATA_START_ROW + index - 1
line_no = str(line.get("line_no") or index).strip()
qty = line.get("qty")
amount = line.get("amount")
detail_ws.cell(row_idx, 1).value = task.task_no
detail_ws.cell(row_idx, 2).value = line_no
detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line)
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
detail_ws.cell(row_idx, 11).value = _line_currency(task, line)
wb.save(path)
def _row_values(task: ShippingTask, line: dict | None) -> list:
line = line or {}
return [
task.customer_name or "",
task.customer_code or "",
task.ship_to or "",
line.get("required_date") or task.required_date or "",
task.required_date or "",
line.get("sku") or "",
line.get("qty") or "",
line.get("uom") or "EA",
@@ -53,14 +197,12 @@ def _row_values(task: ShippingTask, line: dict | None) -> list:
]
def _fill_from_template(task: ShippingTask, path: Path) -> None:
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
wb = load_workbook(filename=str(path))
ws = wb.active
lines = task.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(task, line))
wb.save(path)
@@ -77,17 +219,44 @@ def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
wb.save(path)
def _sanitize_filename(name: str) -> str:
cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."})
return cleaned or "shipment.xlsx"
def _export_filename(task: ShippingTask, ts: str) -> str:
pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip()
if not pattern:
pattern = "shipment_{task_no}_{ts}.xlsx"
try:
name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8])
except Exception:
name = f"shipment_{task.task_no}_{ts}.xlsx"
if not str(name).lower().endswith(".xlsx"):
name = f"{name}.xlsx"
return _sanitize_filename(str(name))
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
root = _storage_root() / "exports"
root.mkdir(parents=True, exist_ok=True)
filename = f"shipment_{task.task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
ts = datetime.utcnow().strftime("%Y%m%d%H%M%S")
filename = _export_filename(task, ts)
path = root / filename
template = _default_template_path()
if template:
copy2(template, path)
_fill_from_template(task, path)
wb = load_workbook(filename=str(path), read_only=True)
try:
is_pvmi = _is_pvmi_workbook(wb)
finally:
wb.close()
if is_pvmi:
_fill_pvmi_template(task, path)
else:
_fill_legacy_template(task, path)
else:
_fill_blank_workbook(task, path)
@@ -1,14 +1,10 @@
from __future__ import annotations
import json
import os
import re
from typing import Any
from app.services.dify import DifyService
from app.services.shipping_notice.po_number import enrich_notice_with_po_number
from app.services.shipping_notice.reservation_id import find_reservation_id_in_document
from app.services.shipping_notice.agent_resolver import resolve_extract_agent
from app.services.shipping_notice.notice_lines import (
enrich_notice_with_document_currency,
enrich_notice_with_document_required_date,
@@ -19,28 +15,6 @@ from app.services.shipping_notice.notice_lines import (
)
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 _finalize_notice_parse(
parsed: dict[str, Any],
*,
@@ -61,34 +35,6 @@ def _finalize_notice_parse(
return parsed, round(confidence, 4), warnings
def _resolve_workflow_file_input_key(agent) -> str | None:
forced = str(os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_FILE_INPUT_KEY") or "").strip()
if forced:
return forced
params = DifyService.get_app_parameters(agent) or {}
def _walk(v: Any) -> str | None:
if isinstance(v, dict):
var = str(v.get("variable") or v.get("name") or "").strip()
t = str(v.get("type") or v.get("value_type") or v.get("valueType") or "").strip().lower()
has_file_cfg = isinstance(v.get("file"), dict) or isinstance(v.get("file_upload"), dict) or isinstance(v.get("fileUpload"), dict)
if var and (has_file_cfg or t in {"file", "files", "file_array", "filearray", "file-list", "file_list"}):
return var
for vv in v.values():
hit = _walk(vv)
if hit:
return hit
elif isinstance(v, list):
for item in v:
hit = _walk(item)
if hit:
return hit
return None
return _walk(params)
def extract_notice_fields(
*,
raw_text: str,
@@ -105,34 +51,6 @@ def extract_notice_fields(
raw_text=str(structured.get("raw_text") or ""),
)
agent = resolve_extract_agent()
if agent and (raw_text.strip() or notice_files):
try:
inputs: dict[str, Any] = {"raw_text": raw_text, "source_type": source_type}
if notice_files:
key = _resolve_workflow_file_input_key(agent)
if key:
inputs[key] = notice_files
else:
warnings.append("workflow_file_input_key_missing")
result = DifyService.run_workflow_streaming(
agent=agent,
inputs=inputs,
user="shipping_notice_tool",
)
parsed = _parse_workflow_outputs(result)
if parsed:
finalized, confidence, line_warnings = _finalize_notice_parse(
parsed,
base_confidence=float(parsed.get("confidence") or 0.85),
raw_text=raw_text,
)
warnings.extend(line_warnings)
return finalized, confidence, warnings
warnings.append("workflow_returned_no_structured_output")
except Exception as exc:
warnings.append(f"workflow_error:{exc}")
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
warnings.extend(heuristic_warnings)
return _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
@@ -0,0 +1,178 @@
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
def _cell(value: Any) -> str:
text = str(value or "").strip()
return text if text else "-"
def _fmt_qty(qty: Any) -> str:
if qty is None or qty == "":
return "-"
try:
num = float(qty)
except (TypeError, ValueError):
return _cell(qty)
return str(int(num)) if num == int(num) else f"{num:g}"
def _mapping_source_column(field_alignment: dict[str, Any], key: str) -> str:
inv_columns = field_alignment.get("inventory_columns")
if not isinstance(inv_columns, dict):
return "-"
mapping = inv_columns.get("mapping")
if not isinstance(mapping, dict):
return "-"
entry = mapping.get(key)
if isinstance(entry, dict):
value = _cell(entry.get("source_column"))
return f"`{value}`" if value != "-" else value
return "-"
def _normalize_warning(text: str, *, lang: str) -> str:
raw = str(text or "").strip()
if not raw:
return raw
lower = raw.lower()
prefix_1 = "parsed with mapping from uploaded file:"
prefix_2 = "parsed from uploaded file:"
if lower.startswith(prefix_1):
filename = raw[len(prefix_1) :].strip()
if lang == "en":
return f"Parsed from uploaded inventory file with mapping: {filename}"
if lang == "th":
return f"แยกข้อมูลจากไฟล์สต็อกที่อัปโหลด (พร้อมการจับคู่คอลัมน์): {filename}"
return f"已按映射解析上传的库存文件:{filename}"
if lower.startswith(prefix_2):
filename = raw[len(prefix_2) :].strip()
if lang == "en":
return f"Parsed from uploaded inventory file: {filename}"
if lang == "th":
return f"แยกข้อมูลจากไฟล์สต็อกที่อัปโหลด: {filename}"
return f"已解析上传的库存文件:{filename}"
return raw
def _format_sample_lines(field_alignment: dict[str, Any], *, lang: str) -> list[str]:
parts: list[str] = []
notice_lines = field_alignment.get("sample_notice_lines") or []
inventory_lines = field_alignment.get("sample_inventory_lines") or []
if notice_lines:
parts.append(t("align.sample.notice", lang=lang))
for index, line in enumerate(notice_lines[:3], 1):
if not isinstance(line, dict):
continue
parts.append(
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.qty', lang=lang)} {_fmt_qty(line.get('qty'))}"
)
if inventory_lines:
if parts:
parts.append("")
parts.append(t("align.sample.inventory", lang=lang))
for index, line in enumerate(inventory_lines[:3], 1):
if not isinstance(line, dict):
continue
parts.append(
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.available_qty', lang=lang)} {_fmt_qty(line.get('available_qty'))}"
)
return parts
def format_field_alignment_summary(
*,
task_no: str,
field_alignment: dict[str, Any],
inventory_row_count: int | None = None,
notice_line_count: int | None = None,
warnings: list[Any] | None = None,
lang: str | None = None,
payload: dict[str, Any] | None = None,
) -> str:
"""Fixed Markdown summary for apply_inventory_mapping / field alignment review."""
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
inv_count = inventory_row_count
if inv_count is None:
inv_count = field_alignment.get("inventory_row_count")
notice_count = notice_line_count
if notice_count is None:
notice_count = field_alignment.get("notice_line_count")
match_rule = _cell(field_alignment.get("match_rule"))
match_rule_source = str(field_alignment.get("match_rule_source") or "").strip()
source_note = ""
if match_rule_source == "llm":
source_note = t("align.source.llm", lang=resolved)
elif match_rule_source == "fallback":
source_note = t("align.source.fallback", lang=resolved)
elif match_rule_source:
source_note = t("align.source.other", lang=resolved).format(source=match_rule_source)
parts = [
t("align.title", lang=resolved).format(task_no=task_no),
"",
t("align.match_rule", lang=resolved).format(rule=match_rule, note=source_note),
"",
f"| {t('align.table.sys_field', lang=resolved)} | {t('align.table.inv_col', lang=resolved)} | {t('align.table.notice_field', lang=resolved)} |",
"|---------|--------------|---------|",
f"| {t('field.reservation_id', lang=resolved)} | {_mapping_source_column(field_alignment, 'reservation_id')} | {t('field.reservation_id', lang=resolved)} |",
f"| {t('field.aws_sku', lang=resolved)} | {_mapping_source_column(field_alignment, 'sku')} | {t('field.sku', lang=resolved)} |",
f"| {t('field.available_qty', lang=resolved)} | {_mapping_source_column(field_alignment, 'available_qty')} | {t('field.qty', lang=resolved)} |",
f"| — | — | {t('align.table.display_only', lang=resolved)} |",
]
if inv_count is not None or notice_count is not None:
parts.append("")
stat_bits = []
if notice_count is not None:
if resolved == "en":
stat_bits.append(f"Order {notice_count} rows")
elif resolved == "th":
stat_bits.append(f"คำสั่งซื้อ {notice_count} แถว")
else:
stat_bits.append(f"订单 {notice_count} 行")
if inv_count is not None:
if resolved == "en":
stat_bits.append(f"Inventory {inv_count} rows")
elif resolved == "th":
stat_bits.append(f"สต็อก {inv_count} แถว")
else:
stat_bits.append(f"库存 {inv_count} 行")
if stat_bits:
sep = "; " if resolved == "en" else ";"
parts.append(t("align.stats", lang=resolved).format(stats=sep.join(stat_bits)))
sample_lines = _format_sample_lines(field_alignment, lang=resolved)
if sample_lines:
parts.append("")
parts.extend(sample_lines)
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
for item in field_alignment.get("warnings") or []:
text = str(item).strip()
if text and text not in warn_items:
warn_items.append(text)
if warn_items:
parts.append("")
parts.append(t("common.tips", lang=resolved))
for warning in warn_items[:8]:
parts.append(f"- {_normalize_warning(warning, lang=resolved)}")
parts.extend(
[
"",
t("align.confirm", lang=resolved),
t("align.hint", lang=resolved),
]
)
hint_btn = t("align.hint_btn", lang=resolved).strip()
if hint_btn:
parts.append(hint_btn)
return "\n".join(parts).strip()
@@ -0,0 +1,208 @@
from __future__ import annotations
from typing import Any
from flask import has_request_context, request
SUPPORTED_LANGS = ("zh", "en", "th")
_MESSAGES: dict[str, dict[str, str]] = {
"zh": {
"parse.title": "【发货通知解析确认】任务编号:{task_no}",
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
"parse.confirm": "请确认以上信息是否正确?",
"parse.hint": "回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。",
"parse.hint_btn": "",
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
"align.match_rule": "匹配规则:{rule}{note}",
"align.table.sys_field": "系统字段",
"align.table.inv_col": "库存 Excel 列",
"align.table.notice_field": "订单字段",
"align.table.display_only": "unit_price / amount(展示用,不参与匹配)",
"align.sample.notice": "订单样例:",
"align.sample.inventory": "库存样例:",
"align.stats": "统计:{stats}",
"align.source.llm": "(LLM 推断)",
"align.source.fallback": "(后端动态兜底)",
"align.source.other": "({source})",
"align.confirm": "请确认以上字段对齐是否正确。",
"align.hint": "回复「确认」进入匹配;「更正映射」重选列;「重新上传」换库存文件;「驳回」终止本任务。",
"align.hint_btn": "",
"common.tips": "提示:",
"table.field": "字段",
"table.value": "值",
"field.po": "采购单号",
"field.sku": "料号",
"field.reservation_id": "预订单号",
"field.qty": "数量",
"field.unit_price": "单价",
"field.amount": "金额",
"field.required_date": "需求日期",
"field.ship_to": "收货方",
"field.vendor_part_number": "供应商料号",
"field.line_no": "项次",
"field.available_qty": "可用数量",
"field.aws_sku": "料号",
"match.title": "【库存匹配结果】任务编号:{task_no}",
"match.subtitle": "匹配明细(订单数量 vs 库存可用量)",
"match.col.order_qty": "订单需求",
"match.col.inv_qty": "库存可用",
"match.col.gap": "缺口",
"match.col.status": "状态",
"match.status.ok": "✅ 充足",
"match.status.partial": "⚠️ 部分满足",
"match.status.shortage": "❌ 不足",
"match.status.unknown": "未知",
"match.conclusion.fulfillable": "**结论**:库存充足,可生成发货 Excel 并上传货代系统。",
"match.conclusion.partial": "**结论**:部分行库存不足,请复核缺口后决定是否部分发货。",
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法整单发货。",
"match.conclusion.other": "**结论**:match_status={status}",
"match.no_lines": "无订单明细,无法比对数量。",
},
"en": {
"parse.title": "[Shipping notice parsed] Task: {task_no}",
"parse.no_lines": "No order lines found. Please re-upload or re-parse.",
"parse.low_conf": "Low confidence. Please double-check SKU, Qty, Reservation ID, Unit Price and Amount.",
"parse.confirm": "Please confirm the above information.",
"parse.hint": 'Reply "Confirm" to proceed; "Re-parse" to retry; "Reject" to stop this task.',
"parse.hint_btn": "",
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
"align.match_rule": "Match rule: {rule}{note}",
"align.table.sys_field": "System field",
"align.table.inv_col": "Inventory column",
"align.table.notice_field": "Order field",
"align.table.display_only": "unit_price / amount (display only)",
"align.sample.notice": "Order samples:",
"align.sample.inventory": "Inventory samples:",
"align.stats": "Stats: {stats}",
"align.source.llm": " (LLM)",
"align.source.fallback": " (backend fallback)",
"align.source.other": " ({source})",
"align.confirm": "Please confirm the field alignment above.",
"align.hint": 'Reply "Confirm" to match; "Fix mapping" to reselect columns; "Re-upload" to change the inventory file; "Reject" to stop.',
"align.hint_btn": "",
"common.tips": "Notes:",
"table.field": "Field",
"table.value": "Value",
"field.po": "PO",
"field.sku": "SKU",
"field.reservation_id": "Reservation ID",
"field.qty": "Qty",
"field.unit_price": "Unit Price",
"field.amount": "Amount",
"field.required_date": "Required date",
"field.ship_to": "Ship to",
"field.vendor_part_number": "Vendor PN",
"field.line_no": "Line",
"field.available_qty": "Available qty",
"field.aws_sku": "AWS Sku",
"match.title": "[Inventory match result] Task: {task_no}",
"match.subtitle": "Match details (order qty vs inventory available)",
"match.col.order_qty": "Order qty",
"match.col.inv_qty": "Available",
"match.col.gap": "Gap",
"match.col.status": "Status",
"match.status.ok": "✅ OK",
"match.status.partial": "⚠️ Partial",
"match.status.shortage": "❌ Short",
"match.status.unknown": "Unknown",
"match.conclusion.fulfillable": "**Result**: Inventory is sufficient. You may generate the shipment Excel and upload.",
"match.conclusion.partial": "**Result**: Some lines are short. Review gaps before partial shipment.",
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines.",
"match.conclusion.other": "**Result**: match_status={status}",
"match.no_lines": "No order lines to compare.",
},
"th": {
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
"parse.hint": 'พิมพ์ "ยืนยัน" เพื่อไปต่อ; "แยกใหม่" เพื่อลองใหม่; "ปฏิเสธ" เพื่อยุติงานนี้',
"parse.hint_btn": "",
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
"align.match_rule": "กฎการจับคู่: {rule}{note}",
"align.table.sys_field": "ฟิลด์ระบบ",
"align.table.inv_col": "คอลัมน์สต็อก",
"align.table.notice_field": "ฟิลด์คำสั่งซื้อ",
"align.table.display_only": "unit_price / amount (แสดงผลเท่านั้น)",
"align.sample.notice": "ตัวอย่างคำสั่งซื้อ:",
"align.sample.inventory": "ตัวอย่างสต็อก:",
"align.stats": "สถิติ: {stats}",
"align.source.llm": " (LLM)",
"align.source.fallback": " (สำรองโดยระบบ)",
"align.source.other": " ({source})",
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
"align.hint": 'พิมพ์ "ยืนยัน" เพื่อจับคู่; "แก้ไขการจับคู่" เพื่อเลือกคอลัมน์ใหม่; "อัปโหลดใหม่" เพื่อเปลี่ยนไฟล์สต็อก; "ปฏิเสธ" เพื่อยุติ',
"align.hint_btn": "",
"common.tips": "หมายเหตุ:",
"table.field": "ฟิลด์",
"table.value": "ค่า",
"field.po": "PO",
"field.sku": "SKU",
"field.reservation_id": "Reservation ID",
"field.qty": "จำนวน",
"field.unit_price": "ราคาต่อหน่วย",
"field.amount": "จำนวนเงิน",
"field.required_date": "วันที่ต้องการ",
"field.ship_to": "ผู้รับ",
"field.vendor_part_number": "หมายเลขชิ้นส่วนผู้ขาย",
"field.line_no": "รายการ",
"field.available_qty": "จำนวนคงเหลือ",
"field.aws_sku": "AWS Sku",
"match.title": "【ผลการจับคู่สต็อก】งาน: {task_no}",
"match.subtitle": "รายละเอียดการจับคู่ (จำนวนสั่งซื้อ vs สต็อกคงเหลือ)",
"match.col.order_qty": "จำนวนสั่ง",
"match.col.inv_qty": "สต็อกคงเหลือ",
"match.col.gap": "ส่วนต่าง",
"match.col.status": "สถานะ",
"match.status.ok": "✅ เพียงพอ",
"match.status.partial": "⚠️ บางส่วน",
"match.status.shortage": "❌ ไม่พอ",
"match.status.unknown": "ไม่ทราบ",
"match.conclusion.fulfillable": "**สรุป**: สต็อกเพียงพอ สามารถสร้าง Excel และอัปโหลดได้",
"match.conclusion.partial": "**สรุป**: บางรายการสต็อกไม่พอ กรุณาตรวจสอบส่วนต่าง",
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด",
"match.conclusion.other": "**สรุป**: match_status={status}",
"match.no_lines": "ไม่มีรายการสั่งซื้อสำหรับเปรียบเทียบ",
},
}
def normalize_lang(raw: Any) -> str:
text = str(raw or "").strip().lower()
if not text:
return "zh"
if text in {"zh-cn", "zh_hans", "zh-hans", "cn", "zh"}:
return "zh"
if text in {"en-us", "en_us", "en"}:
return "en"
if text in {"th-th", "th_th", "th"}:
return "th"
for prefix in SUPPORTED_LANGS:
if text.startswith(prefix):
return prefix
return "zh"
def resolve_lang(payload: dict[str, Any] | None = None) -> str:
if isinstance(payload, dict):
for key in ("lang", "locale", "language"):
if key in payload:
val = str(payload.get(key) or "").strip()
if val:
return normalize_lang(val)
if has_request_context():
hdr = str(request.headers.get("X-Lang") or "").strip()
if hdr:
return normalize_lang(hdr)
accept = str(request.headers.get("Accept-Language") or "").strip()
if accept:
return normalize_lang(accept.split(",")[0].strip())
return "zh"
def t(key: str, *, lang: str | None = None) -> str:
resolved = normalize_lang(lang) if lang else "zh"
return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key
@@ -120,6 +120,8 @@ def resolve_columns_from_field_mapping(
field_mapping: dict[str, str],
) -> dict[str, int | None]:
"""Map system fields to column indexes using explicit header names."""
from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns
norm_headers = [str(h or "").strip() for h in headers]
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
@@ -133,12 +135,14 @@ def resolve_columns_from_field_mapping(
return norm_headers.index(name)
return lower_to_idx.get(name.lower())
columns: dict[str, int | None] = {
# Keep auto-detected optional columns (e.g. odm_id / qty) even when the
# required mapping is provided explicitly by LLM or user.
columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP)
columns.update({
"sku": idx_for(field_mapping.get("sku")),
"reservation_id": idx_for(field_mapping.get("reservation_id")),
"available_qty": None,
"qty": None,
}
})
avail_header = field_mapping.get("available_qty")
if avail_header:
columns["available_qty"] = idx_for(avail_header)
@@ -51,6 +51,12 @@ DEFAULT_COLUMN_MAP = {
"Qty": "qty",
"qty": "qty",
"数量": "qty",
# ODM
"ODM ID": "odm_id",
"ODM Id": "odm_id",
"ODM Code": "odm_id",
"Ship to ODM Code": "odm_id",
"Ship To ODM Code": "odm_id",
}
_RESERVATION_HEADER_PRIORITY = (
@@ -101,7 +107,7 @@ def _map_header(header: str, col_map: dict[str, str]) -> str | None:
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
idx_sku = idx_reservation = idx_available = idx_qty = None
idx_sku = idx_reservation = idx_available = idx_qty = idx_odm = None
for i, h in enumerate(headers):
mapped = _map_header(h, col_map)
if mapped == "sku" and idx_sku is None:
@@ -112,6 +118,8 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
idx_available = i
elif mapped == "qty" and idx_qty is None:
idx_qty = i
elif mapped == "odm_id" and idx_odm is None:
idx_odm = i
# 若 reservation 列未命中,按 AWS 模板常见列名再试
if idx_reservation is None:
@@ -126,6 +134,7 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
"reservation_id": idx_reservation,
"available_qty": idx_available,
"qty": idx_qty,
"odm_id": idx_odm,
}
@@ -190,6 +199,11 @@ def _normalize_inventory_row(
}
if reservation_id:
parsed["reservation_id"] = reservation_id
idx_odm = columns.get("odm_id")
if idx_odm is not None:
odm_id = str(_cell(row, idx_odm) or "").strip()
if odm_id:
parsed["odm_id"] = odm_id
return parsed
@@ -531,7 +545,7 @@ def read_inventory_schema_preview(
"sku": "料号 / AWS Sku",
"reservation_id": "Reservation ID / COM ID(可选)",
"available_qty": "可用数量 / Qty Available / Qty",
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 column_mapping_json.match_rule)",
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)",
},
"row_count_hint": data_row_count,
}
+51 -25
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import extract_reservation_id
@@ -112,18 +112,46 @@ def _fmt_qty(value: float) -> str:
return f"{value:g}"
def _md_cell(value: Any) -> str:
text = str(value or "").strip() or "-"
return text.replace("|", "\\|")
def format_match_summary(
match_status: str,
line_results: list[dict[str, Any]],
*,
task_no: str | None = None,
lang: str | None = None,
) -> str:
"""Human-readable order qty vs inventory qty for match_inventory responses."""
"""Fixed Markdown table for match_inventory responses (Agent must display verbatim)."""
resolved = resolve_lang({"lang": lang} if lang else None)
if not line_results:
return "无订单明细,无法比对数量。"
return t("match.no_lines", lang=resolved)
lines = ["匹配明细(订单数量 vs 库存可用量):"]
for i, row in enumerate(line_results, 1):
sku = str(row.get("sku") or "-")
reservation_id = str(row.get("reservation_id") or "-")
lines: list[str] = []
if task_no:
lines.append(t("match.title", lang=resolved).format(task_no=task_no))
lines.append("")
lines.append(t("match.subtitle", lang=resolved))
lines.append("")
lines.append(
"| # | "
f"{t('field.reservation_id', lang=resolved)} | "
f"{t('field.sku', lang=resolved)} | "
f"{t('match.col.order_qty', lang=resolved)} | "
f"{t('match.col.inv_qty', lang=resolved)} | "
f"{t('match.col.gap', lang=resolved)} | "
f"{t('match.col.status', lang=resolved)} |"
)
lines.append("|---:|---|---|---:|---:|---:|---|")
status_keys = {
"ok": "match.status.ok",
"partial": "match.status.partial",
"shortage": "match.status.shortage",
}
for index, row in enumerate(line_results, 1):
try:
required = float(row.get("required_qty") or 0)
except (TypeError, ValueError):
@@ -137,25 +165,23 @@ def format_match_summary(
except (TypeError, ValueError):
shortage = 0.0
status = str(row.get("line_status") or "")
status_label = {"ok": "充足", "partial": "部分满足", "shortage": "不足"}.get(
status, status or "未知"
status_label = t(status_keys.get(status, "match.status.unknown"), lang=resolved)
gap_cell = "-" if shortage <= 0 else _fmt_qty(shortage)
lines.append(
"| "
f"{index} | "
f"{_md_cell(row.get('reservation_id'))} | "
f"{_md_cell(row.get('sku'))} | "
f"{_fmt_qty(required)} | "
f"{_fmt_qty(available)} | "
f"{gap_cell} | "
f"{status_label} |"
)
detail = (
f"{i}. SKU {sku} | Reservation ID {reservation_id} | "
f"订单 {_fmt_qty(required)} / 库存 {_fmt_qty(available)} | {status_label}"
)
if shortage > 0:
detail += f"(缺口 {_fmt_qty(shortage)})"
lines.append(detail)
lines.append("")
if match_status == "fulfillable":
lines.append("结论:库存充足,可生成发货 Excel 并上传货代系统。")
elif match_status == "partial":
lines.append("结论:部分行库存不足,请复核缺口后决定是否部分发货。")
elif match_status == "unfulfillable":
lines.append("结论:库存均不足,无法整单发货。")
else:
lines.append(f"结论:match_status={match_status}")
conclusion_key = f"match.conclusion.{match_status}"
conclusion = t(conclusion_key, lang=resolved)
if conclusion == conclusion_key:
conclusion = t("match.conclusion.other", lang=resolved).format(status=match_status)
lines.append(conclusion)
return "\n".join(lines)
@@ -20,7 +20,7 @@ def _payload_root(raw: Any) -> dict[str, Any] | None:
def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]:
"""Read optional LLM fields from column_mapping_json (not column names)."""
"""Read optional LLM fields from map_json (not column names)."""
data = _payload_root(raw)
if not data:
return {}
@@ -2,6 +2,8 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.constants import MAP_JSON
def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]:
prop: dict[str, Any] = {"type": "string", "description": description}
@@ -40,7 +42,10 @@ def _post_op(
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": (
"Tool response (status: ok|running|needs_human|failed). "
"May include checkpoint, human_options, action_buttons."
),
"content": {
"application/json": {
"schema": {"type": "object"},
@@ -100,7 +105,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
enum=["true", "false"],
),
"column_mapping_json": _str_prop(
MAP_JSON: _str_prop(
'可选,列映射 JSON 字符串,如 {"sku":"AWS Sku","available_qty":"Qty Available"}'
),
"raw_inventory_text": _str_prop(
@@ -123,11 +128,11 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
{
"task_id": task_id,
"column_mapping_json": _str_prop(
MAP_JSON: _str_prop(
'列映射 JSON,含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明,缺省则后端动态兜底)'
),
},
required=["task_id", "column_mapping_json"],
required=["task_id", MAP_JSON],
),
"/tools/ensure_inventory": _post_op(
"ensure_inventory",
@@ -141,6 +146,14 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id"],
),
"/tools/auto_progress": _post_op(
"auto_progress",
"按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID(可选,用于仅知道会话时定位任务)"),
},
),
"/tools/match_inventory": _post_op(
"match_inventory",
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
@@ -190,7 +203,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
enum=["auto", "retry_upload", "manual_confirm"],
),
"freight_ref_no": _str_prop("货代系统单号(manual_confirm 时填写)"),
"freight_ref_no": _str_prop("货代系统单号(可选;manual_confirm 通常无需填写)"),
},
required=["task_id"],
),
@@ -2,6 +2,8 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
def _cell(value: Any) -> str:
text = str(value or "").strip()
@@ -42,22 +44,30 @@ def _append_table_row(rows: list[str], label: str, value: Any) -> None:
rows.append(f"| {label} | {_cell(value)} |")
def _format_line_block(line: dict[str, Any], *, doc_required_date: str = "") -> list[str]:
def _format_line_block(
line: dict[str, Any],
*,
doc_required_date: str = "",
lang: str,
) -> list[str]:
currency = line.get("currency")
required_date = str(line.get("required_date") or doc_required_date or "").strip()
rows: list[str] = ["| 字段 | 值 |", "|------|-----|"]
_append_table_row(rows, "SKU", line.get("sku"))
_append_table_row(rows, "Reservation ID", line.get("reservation_id"))
_append_table_row(rows, "数量", _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(rows, "单价", _fmt_money(line.get("unit_price"), currency))
_append_table_row(rows, "金额", _fmt_money(line.get("amount"), currency))
_append_table_row(rows, "需求日期", required_date)
rows: list[str] = [
f"| {t('table.field', lang=lang)} | {t('table.value', lang=lang)} |",
"|------|-----|",
]
_append_table_row(rows, t("field.reservation_id", lang=lang), line.get("reservation_id"))
_append_table_row(rows, t("field.sku", lang=lang), line.get("sku"))
_append_table_row(rows, t("field.qty", lang=lang), _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(rows, t("field.unit_price", lang=lang), _fmt_money(line.get("unit_price"), currency))
_append_table_row(rows, t("field.amount", lang=lang), _fmt_money(line.get("amount"), currency))
_append_table_row(rows, t("field.required_date", lang=lang), required_date)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(rows, "供应商料号", vendor_pn)
_append_table_row(rows, t("field.vendor_part_number", lang=lang), vendor_pn)
line_no = str(line.get("line_no") or "").strip()
if line_no:
_append_table_row(rows, "项次", line_no)
_append_table_row(rows, t("field.line_no", lang=lang), line_no)
return rows
@@ -71,62 +81,70 @@ def format_parse_summary(
lines: list[dict[str, Any]] | None = None,
warnings: list[Any] | None = None,
low_confidence: bool = False,
lang: str | None = None,
payload: dict[str, Any] | None = None,
) -> str:
"""Fixed Markdown summary for parse_notice / Agent display."""
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
order_lines = [line for line in (lines or []) if isinstance(line, dict)]
doc_date = str(required_date or "").strip()
parts = [f"【发货通知解析确认】任务编号:{task_no}", ""]
parts = [t("parse.title", lang=resolved).format(task_no=task_no), ""]
if not order_lines:
parts.extend(["| 字段 | 值 |", "|------|-----|"])
_append_table_row(parts, "PO", po_number)
_append_table_row(parts, "收货方", ship_to or customer_name)
_append_table_row(parts, "需求日期", doc_date)
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
_append_table_row(parts, t("field.po", lang=resolved), po_number)
_append_table_row(parts, t("field.ship_to", lang=resolved), ship_to or customer_name)
_append_table_row(parts, t("field.required_date", lang=resolved), doc_date)
parts.append("")
parts.append("未解析到订单明细行,请重新上传或重新解析。")
parts.append(t("parse.no_lines", lang=resolved))
elif len(order_lines) == 1:
line = order_lines[0]
parts.extend(["| 字段 | 值 |", "|------|-----|"])
_append_table_row(parts, "PO", po_number)
_append_table_row(parts, "SKU", line.get("sku"))
_append_table_row(parts, "Reservation ID", line.get("reservation_id"))
_append_table_row(parts, "数量", _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(parts, "单价", _fmt_money(line.get("unit_price"), line.get("currency")))
_append_table_row(parts, "金额", _fmt_money(line.get("amount"), line.get("currency")))
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
_append_table_row(parts, t("field.po", lang=resolved), po_number)
_append_table_row(parts, t("field.reservation_id", lang=resolved), line.get("reservation_id"))
_append_table_row(parts, t("field.sku", lang=resolved), line.get("sku"))
_append_table_row(parts, t("field.qty", lang=resolved), _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(parts, t("field.unit_price", lang=resolved), _fmt_money(line.get("unit_price"), line.get("currency")))
_append_table_row(parts, t("field.amount", lang=resolved), _fmt_money(line.get("amount"), line.get("currency")))
line_date = str(line.get("required_date") or doc_date or "").strip()
_append_table_row(parts, "需求日期", line_date)
_append_table_row(parts, t("field.required_date", lang=resolved), line_date)
recipient = str(ship_to or customer_name or "").strip()
_append_table_row(parts, "收货方", recipient)
_append_table_row(parts, t("field.ship_to", lang=resolved), recipient)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(parts, "供应商料号", vendor_pn)
_append_table_row(parts, t("field.vendor_part_number", lang=resolved), vendor_pn)
else:
if po_number:
parts.append(f"PO:{_cell(po_number)}")
parts.append(f"{t('field.po', lang=resolved)}:{_cell(po_number)}")
recipient = str(ship_to or customer_name or "").strip()
if recipient:
parts.append(f"收货方:{recipient}")
parts.append(f"{t('field.ship_to', lang=resolved)}:{recipient}")
if doc_date:
parts.append(f"需求日期:{doc_date}")
parts.append(f"{t('field.required_date', lang=resolved)}:{doc_date}")
parts.append("")
for index, line in enumerate(order_lines, 1):
line_no = str(line.get("line_no") or index).strip()
parts.append(f"【明细 {index}】项次 {line_no}")
parts.extend(_format_line_block(line, doc_required_date=doc_date))
if resolved == "en":
parts.append(f"[Line {index}] {t('field.line_no', lang=resolved)} {line_no}")
else:
parts.append(f"【明细 {index}】{t('field.line_no', lang=resolved)} {line_no}")
parts.extend(_format_line_block(line, doc_required_date=doc_date, lang=resolved))
parts.append("")
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
if warn_items:
parts.append("")
parts.append("提示:")
parts.append(t("common.tips", lang=resolved))
for warning in warn_items[:8]:
parts.append(f"- {warning}")
parts.append("")
if low_confidence:
parts.append("解析置信度较低,请重点核对 SKU、数量、Reservation ID、单价与金额。")
parts.append("请确认以上信息是否正确?")
parts.append("回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。")
parts.append("(Hxops 聊天页也可直接点击操作按钮,无需输入文字。)")
parts.append(t("parse.low_conf", lang=resolved))
parts.append(t("parse.confirm", lang=resolved))
parts.append(t("parse.hint", lang=resolved))
hint_btn = t("parse.hint_btn", lang=resolved).strip()
if hint_btn:
parts.append(hint_btn)
return "\n".join(parts).strip()
@@ -0,0 +1,94 @@
from __future__ import annotations
import os
from datetime import datetime
from app.models import ShippingTask, ShippingTaskEvent
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 3
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_INVENTORY_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"inventory_template_mapping_used",
}
_UPLOAD_SUCCESS_EVENTS = {
"upload_rpa_success",
"upload_manual_confirmed",
}
def inventory_rpa_attempts(task: ShippingTask | None) -> int:
if not task or task.id is None:
return 0
last_success = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_SUCCESS_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_success.created_at if last_success else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def upload_rpa_attempts(task: ShippingTask | None) -> int:
if not task or task.id is None:
return 0
last_success = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_UPLOAD_SUCCESS_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_success.created_at if last_success else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def max_rpa_inventory_attempts() -> int:
value = os.getenv("SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
return max(parsed, 1)
def max_rpa_upload_attempts() -> int:
value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
return max(parsed, 1)
@@ -0,0 +1,552 @@
"""
Canonical registry for shipping-notice human nodes.
Single source of truth for:
- checkpoint ids (API `checkpoint`, Dify `flow_ckpt`)
- action button specs (`action_buttons`, HXOPS_SHIPPING_ACTIONS)
- task DB fields → checkpoint + human_options (chat-actions API)
- task DB field writes (`TaskTransition` / `apply_task_transition` — tools.py must use these)
When adding a human node, update ONLY this module (+ tests), then:
- tools.py sets task fields via `apply_task_transition(...)` and calls `tool_response(..., checkpoint=CP_*)`
- Dify `组装直接回复` embeds directive only from HTTP `act_json` (approach B); text-only rounds use Hxops `/chat-actions`
- `GET /tools/checkpoint-catalog` is for developers/docs/CI — not wired in Dify canvas
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_MAP_INFER,
CP_PARSE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_ALIGN_REVIEW,
PH_INV_UNAVAIL,
PH_LOW_CONF,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
RS_CONFIRMED,
RS_PARSE_REVIEW,
RS_REJECTED,
RS_RSV_REQ,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
)
# ---------------------------------------------------------------------------
# Action buttons (id → label / message / variant)
# ---------------------------------------------------------------------------
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
"upload_inventory_file": {
"label": "选择库存文件",
"message": "我要上传库存 Excel",
"variant": "secondary",
},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
"mark_manual_uploaded": {
"label": "已手工上传",
"message": "已在货代系统手工上传完成",
"variant": "primary",
},
"paste_inventory_json": {
"label": "粘贴库存",
"message": "我粘贴库存小表",
"variant": "secondary",
},
"edit_inventory_mapping": {
"label": "修改映射",
"message": "修改库存列映射",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
"variant": "primary",
},
}
# checkpoint id → default human option ids (HTTP / Dify before task reload)
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
CP_ALIGN_REVIEW: (
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
"reject",
),
CP_MAP_INFER: (
"edit_inventory_mapping",
"upload_inventory_file",
"paste_inventory_json",
"retry_rpa",
),
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
RS_SHORTAGE_REVIEW: ("confirm", "reject", "rematch"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
CP_READY_MATCH: ("match_inventory",),
CP_READY_EXPORT: ("generate_excel",),
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
CP_EXPORT_GENERATED: ("download_excel", "mark_manual_uploaded"),
CP_REJECTED: (),
CP_UPLOADED: (),
CP_COMPLETED: (),
}
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
# Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ]
OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",)
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("retry_rpa", "upload_inventory_file")
@dataclass(frozen=True)
class TaskUiState:
checkpoint: str | None
human_options: list[str] | None
@property
def action_buttons(self) -> list[dict[str, str]]:
return build_action_buttons(self.human_options)
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
if not option_ids:
return []
buttons: list[dict[str, str]] = []
for option_id in option_ids:
spec = ACTION_SPECS.get(option_id)
if not spec:
continue
buttons.append({"id": option_id, **spec})
return buttons
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
if not checkpoint:
return None
key = str(checkpoint).strip()
options = CHECKPOINT_REGISTRY.get(key)
if options is None:
return None
return list(options)
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
return build_action_buttons(human_options_for_checkpoint(checkpoint))
def format_actions_directive(option_ids: list[str] | None) -> str:
buttons = build_action_buttons(option_ids)
if not buttons:
return ""
body = json.dumps(buttons, ensure_ascii=False)
return f"<!-- HXOPS_SHIPPING_ACTIONS: {body} -->"
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
options = human_options_for_checkpoint(checkpoint)
cp = str(checkpoint).strip() if checkpoint else None
if cp and cp not in CHECKPOINT_REGISTRY:
cp = None
return TaskUiState(checkpoint=cp, human_options=options)
def upload_req_options_for_task(task: ShippingTask) -> list[str]:
"""upload_req checkpoint with RPA-attempt-aware button subsets."""
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return list(OPTIONS_UPLOAD_FILE_ONLY)
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
return list(OPTIONS_UPLOAD_FILE_ONLY)
if task.pending_human_reason in {PH_INV_UNAVAIL, PH_RPA_PENDING}:
return list(OPTIONS_RPA_OR_UPLOAD)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
def human_options_for_task_or_checkpoint(
*,
task: ShippingTask | None = None,
checkpoint: str | None = None,
) -> list[str] | None:
"""Prefer task DB state; fall back to static checkpoint registry (for tool_response)."""
if task is not None:
opts = resolve_task_ui_state(task).human_options
if opts is not None:
return opts
return human_options_for_checkpoint(checkpoint)
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
"""Map ShippingTask DB fields → checkpoint + human_options for /chat-actions."""
if task.process_status == "uploaded":
return TaskUiState(checkpoint=CP_UPLOADED, human_options=[])
if task.process_status == "closed":
return TaskUiState(checkpoint=CP_COMPLETED, human_options=[])
if task.process_status == "rejected" or task.review_status == "rejected":
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if (
task.process_status == "parsed"
and not task.review_status
and not task.pending_human_reason
and not task.inventory_lines_json
):
return TaskUiState(
checkpoint=CP_INVENTORY_PENDING,
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]),
)
if (
task.process_status == "inventory_ready"
and not task.review_status
and not task.pending_human_reason
and not task.match_status
and isinstance(task.lines_json, list)
and len(task.lines_json) > 0
):
return TaskUiState(
checkpoint=CP_READY_MATCH,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
)
if task.process_status == "matched":
if task.export_file_path:
return TaskUiState(
checkpoint=CP_EXPORT_READY,
human_options=list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]),
)
return TaskUiState(
checkpoint=CP_READY_EXPORT,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
)
reason = task.pending_human_reason
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
return TaskUiState(
checkpoint=CP_ALIGN_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]),
)
if reason == PH_MAP_INFER:
return TaskUiState(
checkpoint=CP_MAP_INFER,
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
)
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
return TaskUiState(
checkpoint=CP_RSV_REQ,
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
)
if reason == PH_INV_UNAVAIL:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
return TaskUiState(
checkpoint=RS_SHORTAGE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
)
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
return TaskUiState(
checkpoint=CP_PARSE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
)
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
return TaskUiState(
checkpoint=CP_UPLOAD_FAILED,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
)
if reason == PH_RPA_PENDING or (
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
):
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if reason == PH_UPLOAD_RPA_PENDING or task.process_status == "waiting_upload":
return TaskUiState(
checkpoint=CP_WAITING_UPLOAD,
human_options=list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]),
)
return TaskUiState(checkpoint=None, human_options=None)
def checkpoint_for_task(task: ShippingTask) -> str | None:
return resolve_task_ui_state(task).checkpoint
def human_options_for_task(task: ShippingTask) -> list[str] | None:
return resolve_task_ui_state(task).human_options
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
ui = resolve_task_ui_state(task)
return {
"task_no": task.task_no,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": ui.action_buttons,
}
def build_checkpoint_catalog() -> dict[str, Any]:
"""Export for docs, CI, and developer reference — not embedded in Dify (approach B)."""
checkpoints = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
buttons = build_action_buttons(list(option_ids))
checkpoints.append(
{
"id": checkpoint_id,
"human_options": list(option_ids),
"action_buttons": buttons,
}
)
return {
"checkpoints": checkpoints,
"action_specs": ACTION_SPECS,
"dify_fallback": {
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
},
}
def validate_registry() -> list[str]:
"""Return list of validation errors (empty if ok). Used in tests."""
errors: list[str] = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
for option_id in option_ids:
if option_id not in ACTION_SPECS:
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
return errors
# ---------------------------------------------------------------------------
# Task DB field transitions (tools.py writes via apply_task_transition only)
# ---------------------------------------------------------------------------
_UNSET = object()
@dataclass(frozen=True)
class _TransitionSpec:
process_status: Any = _UNSET
review_status: Any = _UNSET
pending_human_reason: Any = _UNSET
clear_error_message: bool = False
class TaskTransition(StrEnum):
"""Named DB state writes used by shipping notice tools."""
PARSED = "parsed"
PARSE_NEEDS_REVIEW = "parse_needs_review"
INVENTORY_READY = "inventory_ready"
INVENTORY_ALIGN_REVIEW = "inventory_align_review"
MAP_INFER = "map_infer"
RPA_EXHAUSTED = "rpa_exhausted"
RPA_PENDING = "rpa_pending"
INV_UNAVAIL = "inv_unavail"
RSV_REQUIRED = "rsv_required"
MATCHED_FULFILLABLE = "matched_fulfillable"
MATCH_SHORTAGE = "match_shortage"
REJECTED = "rejected"
CLOSED = "closed"
CONFIRM_SHORTAGE = "confirm_shortage"
CONFIRM_PARSE = "confirm_parse"
CONFIRM_MATCHED = "confirm_matched"
ALIGN_REVIEW_HOLD = "align_review_hold"
MAPPING_CONFIRMED = "mapping_confirmed"
CORRECT_MAPPING = "correct_mapping"
REPARSE_INVENTORY = "reparse_inventory"
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
WAITING_UPLOAD = "waiting_upload"
UPLOAD_RPA_PENDING = "upload_rpa_pending"
UPLOAD_FAILED = "upload_failed"
UPLOADED = "uploaded"
TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
TaskTransition.PARSED: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.PARSE_NEEDS_REVIEW: _TransitionSpec(
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
),
TaskTransition.INVENTORY_READY: _TransitionSpec(
process_status="inventory_ready",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.INVENTORY_ALIGN_REVIEW: _TransitionSpec(
process_status="inventory_ready",
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
clear_error_message=True,
),
TaskTransition.MAP_INFER: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_RPA_EXHAUSTED,
),
TaskTransition.RPA_PENDING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_RPA_PENDING,
),
TaskTransition.INV_UNAVAIL: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_INV_UNAVAIL,
),
TaskTransition.RSV_REQUIRED: _TransitionSpec(
process_status="pending_review",
review_status=RS_RSV_REQ,
pending_human_reason=PH_RSV_REQ,
),
TaskTransition.MATCHED_FULFILLABLE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.MATCH_SHORTAGE: _TransitionSpec(
process_status="pending_review",
review_status=RS_SHORTAGE_REVIEW,
pending_human_reason=PH_SHORTAGE,
),
TaskTransition.REJECTED: _TransitionSpec(
process_status="rejected",
review_status=RS_REJECTED,
pending_human_reason=None,
),
TaskTransition.CLOSED: _TransitionSpec(
process_status="closed",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.CONFIRM_SHORTAGE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.CONFIRM_MATCHED: _TransitionSpec(
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.ALIGN_REVIEW_HOLD: _TransitionSpec(
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
),
TaskTransition.MAPPING_CONFIRMED: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.CORRECT_MAPPING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.REPARSE_INVENTORY: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
process_status="waiting_upload",
pending_human_reason=PH_UPLOAD_RPA_PENDING,
),
TaskTransition.UPLOAD_FAILED: _TransitionSpec(
process_status="upload_failed",
pending_human_reason=PH_UPLOAD_RPA_FAILED,
),
TaskTransition.UPLOADED: _TransitionSpec(
process_status="uploaded",
pending_human_reason=None,
clear_error_message=True,
),
}
def apply_task_transition(task: ShippingTask, transition: TaskTransition) -> None:
"""Apply a named transition to task process/review/pending_human_reason fields."""
spec = TASK_TRANSITIONS[transition]
if spec.process_status is not _UNSET:
task.process_status = spec.process_status
if spec.review_status is not _UNSET:
task.review_status = spec.review_status
if spec.pending_human_reason is not _UNSET:
task.pending_human_reason = spec.pending_human_reason
if spec.clear_error_message:
task.error_message = None
@@ -0,0 +1,24 @@
from __future__ import annotations
from flask import current_app, has_request_context, request
def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str:
"""Resolve hxops Tool API base URL (…/api/shipping-notice, no trailing slash)."""
cfg = config
if cfg is None and current_app:
cfg = current_app.config
cfg = cfg or {}
configured = str(cfg.get("SHIPPING_NOTICE_TOOL_API_BASE") or "").strip().rstrip("/")
if configured:
return configured
configured = str(cfg.get("PUBLIC_BASE_URL") or "").strip().rstrip("/")
if configured:
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
return host or ""
@@ -1,20 +1,52 @@
from __future__ import annotations
from typing import Any
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from app.models import ShippingTask
def tool_response(
*,
status: str,
task: ShippingTask | None = None,
task_id: str | None = None,
message: str = "",
data: dict[str, Any] | None = None,
human_options: list[str] | None = None,
action_buttons: list[dict[str, str]] | None = None,
checkpoint: str | None = None,
next_required_action: str | None = None,
forbidden_next_tools: list[str] | None = None,
stop_agent_turn: bool = False,
) -> dict[str, Any]:
"""Build a shipping-notice tool JSON response.
When ``checkpoint`` is omitted and ``task`` is given, checkpoint / human_options /
action_buttons are derived from ``resolve_task_ui_state(task)`` (single read path).
Explicit ``checkpoint`` wins (e.g. ``parse_ok``, ``task_exists``).
"""
from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint,
build_action_buttons,
resolve_task_ui_state,
)
if task is not None and not task_id:
task_id = task.task_no
resolved_checkpoint = checkpoint
resolved_human_options = human_options
resolved_action_buttons = action_buttons
if checkpoint is None and task is not None:
ui = resolve_task_ui_state(task)
resolved_checkpoint = ui.checkpoint
if human_options is None:
resolved_human_options = ui.human_options
if action_buttons is None and ui.action_buttons:
resolved_action_buttons = ui.action_buttons
payload: dict[str, Any] = {
"status": status,
"message": message,
@@ -22,10 +54,18 @@ def tool_response(
}
if task_id:
payload["task_id"] = task_id
if human_options:
payload["human_options"] = human_options
if checkpoint:
payload["checkpoint"] = checkpoint
if resolved_human_options is not None:
payload["human_options"] = resolved_human_options
if resolved_action_buttons is not None:
payload["action_buttons"] = resolved_action_buttons
elif resolved_human_options is not None:
payload["action_buttons"] = build_action_buttons(resolved_human_options)
elif resolved_checkpoint:
buttons = action_buttons_for_checkpoint(resolved_checkpoint)
if buttons:
payload["action_buttons"] = buttons
if resolved_checkpoint:
payload["checkpoint"] = resolved_checkpoint
if next_required_action:
payload["next_required_action"] = next_required_action
if forbidden_next_tools:
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,95 @@
"""Human-readable task progress — never expose DB / state-machine codes to end users."""
from __future__ import annotations
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_MAP_INFER,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_SHORTAGE,
PH_UPLOAD_RPA_PENDING,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.state_machine import resolve_task_ui_state
# Fields omitted from Dify Tool `data` — Agent must not parrot these to users.
TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
{
"process_status",
"review_status",
"match_status",
"pending_human_reason",
"error_message",
}
)
_CHECKPOINT_LABELS: dict[str, str] = {
CP_PARSE_REVIEW: "待确认发货通知解析",
CP_ALIGN_REVIEW: "待确认库存字段对齐",
CP_MAP_INFER: "待确认库存列映射",
CP_UPLOAD_REQ: "待上传或获取库存",
CP_INVENTORY_PENDING: "待上传库存",
CP_RSV_REQ: "待补充 Reservation ID",
CP_READY_MATCH: "待匹配库存",
CP_READY_EXPORT: "待生成发货 Excel",
CP_EXPORT_READY: "发货 Excel 已生成",
CP_WAITING_UPLOAD: "待上传货代系统",
CP_UPLOAD_FAILED: "货代上传失败,待处理",
CP_REJECTED: "任务已驳回",
CP_UPLOADED: "已完成上传",
CP_COMPLETED: "任务已完成",
}
_PROCESS_STATUS_LABELS: dict[str, str] = {
"created": "任务已创建",
"parsed": "发货通知已解析",
"pending_review": "待人工确认",
"waiting_inventory": "待获取库存",
"inventory_ready": "库存已就绪",
"matched": "库存已匹配",
"waiting_upload": "待上传货代系统",
"upload_failed": "货代上传失败",
"uploaded": "已完成上传",
"rejected": "已驳回",
"closed": "已关闭",
}
_PENDING_REASON_LABELS: dict[str, str] = {
PH_RPA_PENDING: "RPA 正在导出库存,请稍候",
PH_RPA_EXHAUSTED: "RPA 获取库存失败,请手动上传",
PH_UPLOAD_RPA_PENDING: "RPA 正在上传货代,请稍候",
PH_SHORTAGE: "库存不足,待确认",
RS_SHORTAGE_REVIEW: "库存不足,待确认",
RS_PARSE_REVIEW: "解析结果待确认",
}
def user_facing_task_stage(task: ShippingTask) -> str:
"""Short Chinese label for chat / get_task_status — no snake_case codes."""
ui = resolve_task_ui_state(task)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint]
reason = str(task.pending_human_reason or "").strip()
if reason in _PENDING_REASON_LABELS:
return _PENDING_REASON_LABELS[reason]
process = str(task.process_status or "").strip()
return _PROCESS_STATUS_LABELS.get(process, "处理中")
def strip_internal_task_fields(data: dict) -> dict:
return {k: v for k, v in data.items() if k not in TOOL_TASK_DATA_OMIT}
+22 -1
View File
@@ -12,6 +12,8 @@ from __future__ import annotations
import os
import subprocess
from pathlib import Path
import shutil
import tempfile
def soffice_timeout_sec() -> int:
@@ -46,6 +48,15 @@ def find_soffice() -> str | None:
return None
def use_isolated_soffice_profile() -> bool:
raw = str(os.environ.get("EDKB_SOFFICE_ISOLATED_PROFILE", "1")).strip().lower()
return raw not in {"0", "false", "no"}
def _new_soffice_profile_dir() -> Path:
return Path(tempfile.mkdtemp(prefix="lo-profile-")).resolve()
def run_soffice(cmd: list[str]) -> subprocess.CompletedProcess[str]:
"""
执行 soffice 命令并强制超时。
@@ -80,8 +91,14 @@ def convert_with_soffice(
:param convert_to: 目标格式,如 docx / pdf / xlsx / pptx
"""
out_dir.mkdir(parents=True, exist_ok=True)
profile_dir: Path | None = None
profile_arg: str | None = None
if use_isolated_soffice_profile():
profile_dir = _new_soffice_profile_dir()
profile_arg = f"-env:UserInstallation={profile_dir.as_uri()}"
cmd = [
soffice,
*( [profile_arg] if profile_arg else [] ),
"--headless",
"--convert-to",
convert_to,
@@ -89,4 +106,8 @@ def convert_with_soffice(
"--outdir",
str(out_dir),
]
return run_soffice(cmd)
try:
return run_soffice(cmd)
finally:
if profile_dir is not None:
shutil.rmtree(profile_dir, ignore_errors=True)
@@ -0,0 +1,51 @@
"""shorten shipping notice state and reason strings
Revision ID: e8f9a0b1c2d3
Revises: a7b8c9d0e1f2
Create Date: 2026-05-29 12:00:00.000000
"""
from alembic import op
revision = "e8f9a0b1c2d3"
down_revision = "a7b8c9d0e1f2"
branch_labels = None
depends_on = None
_PENDING_MAP = {
"inventory_field_mapping_review": "align_review",
"inventory_mapping_inference": "map_infer",
"low_parse_confidence": "low_confidence",
"inventory_shortage": "shortage",
"reservation_id_required": "rsv_req",
"inventory_rpa_exhausted": "rpa_exhausted",
"inventory_rpa_pending": "rpa_pending",
"inventory_unavailable": "inv_unavail",
}
_REVIEW_MAP = {
"inventory_mapping_review": "align_review",
"inventory_shortage_review": "shortage_review",
"reservation_id_required": "rsv_req",
}
def _replace_column(table: str, column: str, mapping: dict[str, str]) -> None:
for old, new in mapping.items():
op.execute(
f"UPDATE {table} SET {column} = '{new}' WHERE {column} = '{old}'"
)
def upgrade():
_replace_column("shipping_tasks", "pending_human_reason", _PENDING_MAP)
_replace_column("shipping_tasks", "review_status", _REVIEW_MAP)
def downgrade():
pending_rev = {v: k for k, v in _PENDING_MAP.items()}
review_rev = {v: k for k, v in _REVIEW_MAP.items()}
_replace_column("shipping_tasks", "pending_human_reason", pending_rev)
_replace_column("shipping_tasks", "review_status", review_rev)
@@ -44,11 +44,13 @@ def upgrade():
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_schedule_tasks_id'))
op.execute("ALTER TABLE users DROP CONSTRAINT IF EXISTS uq_users_wecom_unionid")
op.execute("ALTER TABLE users DROP CONSTRAINT IF EXISTS uq_users_wecom_userid")
op.execute("DROP INDEX IF EXISTS uq_users_wecom_unionid")
op.execute("DROP INDEX IF EXISTS uq_users_wecom_userid")
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('uq_users_wecom_unionid'))
batch_op.drop_index(batch_op.f('uq_users_wecom_userid'))
batch_op.create_unique_constraint(None, ['wecom_unionid'])
batch_op.create_unique_constraint(None, ['wecom_userid'])
batch_op.create_unique_constraint('uq_users_wecom_unionid', ['wecom_unionid'])
batch_op.create_unique_constraint('uq_users_wecom_userid', ['wecom_userid'])
# ### end Alembic commands ###
@@ -56,8 +58,8 @@ def upgrade():
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_constraint('uq_users_wecom_unionid', type_='unique')
batch_op.drop_constraint('uq_users_wecom_userid', type_='unique')
batch_op.create_index(batch_op.f('uq_users_wecom_userid'), ['wecom_userid'], unique=True)
batch_op.create_index(batch_op.f('uq_users_wecom_unionid'), ['wecom_unionid'], unique=True)
@@ -0,0 +1,25 @@
"""Print checkpoint → action id table for docs (§2.3.5.9)."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "backend"))
from app.services.shipping_notice.state_machine import CHECKPOINT_REGISTRY # noqa: E402
def main() -> None:
print("| checkpoint | action id 列表 |")
print("|------------|----------------|")
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
if option_ids:
actions = ", ".join(option_ids)
else:
actions = "_(无按钮)_"
print(f"| `{checkpoint_id}` | {actions} |")
if __name__ == "__main__":
main()
+1 -12
View File
@@ -3,12 +3,11 @@ import sqlalchemy as sa
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
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
app = create_app()
CHAT_DESCRIPTION = "货代发货通知智能体:自然语言驱动解析、库存匹配、Excel 生成与货代上传(Tool 编排)"
EXTRACT_DESCRIPTION = "后台专用:从邮件/PDF 文本抽取结构化发货通知字段(Workflow,供 Tool 内部调用)"
def _normalize_url(raw: str | None) -> str | None:
@@ -81,8 +80,6 @@ if __name__ == "__main__":
_ensure_pg_sequence("agents", "id")
chat_key = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_API_KEY") or os.getenv("DIFY_API_KEY")
chat_base = _normalize_url(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 = _normalize_url(os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_BASE") or chat_base)
_upsert_agent(
name=CHAT_AGENT_NAME,
@@ -92,13 +89,5 @@ if __name__ == "__main__":
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.
@@ -0,0 +1,56 @@
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
def test_format_field_alignment_summary_single_block():
field_alignment = {
"match_rule": "按 AWS Sku + Reservation Order 汇总 Qty Available 与订单 qty 比对。",
"match_rule_source": "llm",
"inventory_columns": {
"mapping": {
"sku": {"source_column": "AWS Sku"},
"reservation_id": {"source_column": "Reservation Order"},
"available_qty": {"source_column": "Qty Available"},
}
},
"sample_notice_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9},
],
"sample_inventory_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "available_qty": 12},
],
"inventory_row_count": 120,
"notice_line_count": 1,
"warnings": [],
}
text = format_field_alignment_summary(
task_no="SN-20260602-AB12CD34",
field_alignment=field_alignment,
)
assert "【库存字段对齐确认" in text
assert "SN-20260602-AB12CD34" in text
assert "| 预订单号 | `Reservation Order` | 预订单号 |" in text
assert "| 料号 | `AWS Sku` | 料号 |" in text
rid_idx = text.index("| 预订单号 |")
sku_idx = text.index("| 料号 | `AWS Sku`")
assert rid_idx < sku_idx
assert "(LLM 推断)" in text
assert "订单样例:" in text
assert "预订单号 1000140351" in text
assert "料号 504-010213-001" in text
assert "回复「确认」进入匹配" in text
def test_format_field_alignment_summary_includes_warnings():
text = format_field_alignment_summary(
task_no="SN-1",
field_alignment={
"match_rule": "test",
"inventory_columns": {"mapping": {}},
"warnings": ["库存未识别 Reservation ID 相关列"],
},
warnings=["额外提示"],
)
assert "库存未识别 Reservation ID 相关列" in text
assert "额外提示" in text
@@ -51,18 +51,36 @@ def test_read_inventory_schema_preview_skips_title_row(app, tmp_path):
def test_parse_aws_inventory_headers(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "Qty"]
headers = ["AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
data = [
["10-40594-001", "AWS-311", 2, 1],
["10-40594-002", "ORD-3002", 0, 5],
["10-40594-001", "AWS-311", 2, 1, "16754796"],
["10-40594-002", "ORD-3002", 0, 5, "16754797"],
]
lines = parse_inventory_rows(headers, data)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["available_qty"] == 2.0
assert lines[0]["odm_id"] == "16754796"
assert lines[1]["reservation_id"] == "ORD-3002"
assert lines[1]["available_qty"] == 0.0
assert lines[1]["odm_id"] == "16754797"
def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "ODM ID"]
data = [["10-40594-001", "AWS-311", 2, "16754796"]]
lines = parse_inventory_rows(
headers,
data,
field_mapping={
"sku": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
)
assert lines[0]["odm_id"] == "16754796"
def test_match_aggregates_same_sku_reservation():
@@ -15,9 +15,10 @@ def test_format_match_summary_fulfillable():
}
],
)
assert "匹配明细" in msg
assert "订单 2 / 库存 5" in msg
assert "充足" in msg
assert "【库存匹配结果】" in msg or "匹配明细" in msg
assert "| # | 预订单号 | 料号 |" in msg
assert "| 1 | AWS-311 | 10-40594-001 | 2 | 5 | - |" in msg
assert "✅ 充足" in msg
assert "可生成发货 Excel" in msg
@@ -35,6 +36,6 @@ def test_format_match_summary_shortage():
}
],
)
assert "订单 100 / 库存 5" in msg
assert "缺口 95" in msg
assert "| R-1 | A001 | 100 | 5 | 95 |" in msg
assert "⚠️ 部分满足" in msg
assert "部分行库存不足" in msg
@@ -20,9 +20,13 @@ def test_format_parse_summary_single_line():
],
)
assert "【发货通知解析确认】任务编号:SN-20260604-7249E4D7" in msg
assert "| PO | 16754796 |" in msg
assert "| SKU | 504-010213-001 |" in msg
assert "| Reservation ID | 1000140351 |" in msg
assert "| 采购单号 | 16754796 |" in msg
assert "| 预订单号 | 1000140351 |" in msg
assert "| 料号 | 504-010213-001 |" in msg
po_idx = msg.index("| 采购单号 |")
rid_idx = msg.index("| 预订单号 |")
sku_idx = msg.index("| 料号 |")
assert po_idx < rid_idx < sku_idx
assert "| 数量 | 9 PCS |" in msg
assert "| 单价 | $1,607.72 |" in msg
assert "| 金额 | $14,469.48 |" in msg
@@ -43,7 +47,7 @@ def test_format_parse_summary_multiple_lines():
)
assert "【明细 1】" in msg
assert "【明细 2】" in msg
assert "PO:PO-1" in msg
assert "采购单号:PO-1" in msg
def test_format_parse_summary_includes_warnings():
+75 -1
View File
@@ -37,7 +37,7 @@ def test_shipping_notice_tool_flow(app, client):
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| SKU | A001 |" in parse_body["message"]
assert "| 料号 | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
@@ -491,6 +491,80 @@ def test_rpa_upload_callback(app, client, tmp_path):
assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001"
def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"po_number": "SN-20260608-7FCBFA4B",
"lines": [
{
"sku": "504-010213-001",
"vendor_part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [
{
"sku": "504-010213-001",
"reservation_id": "1000140351",
"available_qty": 9,
"odm_id": "16754796",
}
],
},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "ok"
from openpyxl import load_workbook
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
wb = load_workbook(task.export_file_path, read_only=True)
header_ws = wb["PVMI Pull Request Header"]
detail_ws = wb["PVMI Pull Request Detail"]
assert header_ws.cell(4, 6).value == "16754796"
assert detail_ws.cell(4, 4).value == "504-010213-001"
wb.close()
def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
@@ -0,0 +1,78 @@
from pathlib import Path
import subprocess
from edkb_system.skills import soffice_util
def test_convert_with_soffice_uses_isolated_profile_and_cleans(monkeypatch, tmp_path):
profile_dir = tmp_path / "lo-profile-fixed"
def fake_mkdtemp(prefix=""):
profile_dir.mkdir(parents=True, exist_ok=True)
return str(profile_dir)
monkeypatch.setenv("EDKB_SOFFICE_ISOLATED_PROFILE", "1")
monkeypatch.setattr(soffice_util.tempfile, "mkdtemp", fake_mkdtemp)
captured = {}
def fake_run(cmd):
captured["cmd"] = cmd
assert profile_dir.exists()
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
monkeypatch.setattr(soffice_util, "run_soffice", fake_run)
source_path = tmp_path / "sample.doc"
source_path.write_text("dummy", encoding="utf-8")
out_dir = tmp_path / "out"
proc = soffice_util.convert_with_soffice(
"soffice",
convert_to="docx",
source_path=source_path,
out_dir=out_dir,
)
assert proc.returncode == 0
assert any(
str(item).startswith("-env:UserInstallation=") for item in captured["cmd"]
)
assert not profile_dir.exists()
def test_convert_with_soffice_can_use_shared_profile(monkeypatch, tmp_path):
called = {"mkdtemp": 0}
def fake_mkdtemp(prefix=""):
called["mkdtemp"] += 1
return str(tmp_path / "unused-profile")
monkeypatch.setenv("EDKB_SOFFICE_ISOLATED_PROFILE", "0")
monkeypatch.setattr(soffice_util.tempfile, "mkdtemp", fake_mkdtemp)
captured = {}
def fake_run(cmd):
captured["cmd"] = cmd
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
monkeypatch.setattr(soffice_util, "run_soffice", fake_run)
source_path = tmp_path / "sample.doc"
source_path.write_text("dummy", encoding="utf-8")
out_dir = tmp_path / "out"
proc = soffice_util.convert_with_soffice(
"soffice",
convert_to="docx",
source_path=source_path,
out_dir=out_dir,
)
assert proc.returncode == 0
assert called["mkdtemp"] == 0
assert not any(
str(item).startswith("-env:UserInstallation=") for item in captured["cmd"]
)
+87 -41
View File
@@ -7,7 +7,7 @@
},
"servers": [
{
"url": "http://127.0.0.1:5052/api/shipping-notice"
"url": "http://192.168.36.108:5052/api/shipping-notice"
}
],
"paths": {
@@ -53,7 +53,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -80,7 +80,7 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"raw_text": {
"type": "string",
@@ -96,7 +96,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -123,17 +123,17 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"use_uploaded_file": {
"type": "string",
"description": "true=解析该 task 已上传的 Excel(服务端直传,不经过 LLM)",
"description": "true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
"enum": [
"true",
"false"
]
},
"column_mapping_json": {
"map_json": {
"type": "string",
"description": "可选,列映射 JSON 字符串,如 {\"sku\":\"AWS Sku\",\"available_qty\":\"Qty Available\"}"
},
@@ -155,7 +155,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -182,7 +182,7 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
@@ -194,7 +194,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -221,16 +221,16 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"column_mapping_json": {
"map_json": {
"type": "string",
"description": "列映射 JSON,如 {\"sku\":\"料号\",\"reservation_id\":\"COM ID\",\"available_qty\":\"Qty Available\"}"
"description": "列映射 JSON,含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明,缺省则后端动态兜底)"
}
},
"required": [
"task_id",
"column_mapping_json"
"map_json"
]
}
}
@@ -238,7 +238,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -265,7 +265,7 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"mode": {
"type": "string",
@@ -289,7 +289,47 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/auto_progress": {
"post": {
"operationId": "auto_progress",
"summary": "按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
"description": "按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID(可选,用于仅知道会话时定位任务)"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -316,7 +356,7 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"inventory_lines_json": {
"type": "string",
@@ -332,7 +372,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -347,8 +387,8 @@
"/tools/submit_decision": {
"post": {
"operationId": "submit_decision",
"summary": "人工复核决策",
"description": "人工复核决策",
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"description": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
"parameters": [],
"requestBody": {
"required": true,
@@ -359,17 +399,23 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID;用户仅回复「确认」时用于定位任务"
},
"decision": {
"type": "string",
"description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;reparse_inventory=重新上传库存",
"description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
"enum": [
"confirm",
"confirm_parse",
"reject",
"rematch",
"reparse",
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory"
]
},
@@ -379,7 +425,6 @@
}
},
"required": [
"task_id",
"decision"
]
}
@@ -388,7 +433,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -403,8 +448,8 @@
"/tools/generate_shipment_excel": {
"post": {
"operationId": "generate_shipment_excel",
"summary": "生成固定模板发货 Excel",
"description": "生成固定模板发货 Excel",
"summary": "生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
"description": "生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
"parameters": [],
"requestBody": {
"required": true,
@@ -415,7 +460,7 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
@@ -427,7 +472,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -454,7 +499,7 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"mode": {
"type": "string",
@@ -467,7 +512,7 @@
},
"freight_ref_no": {
"type": "string",
"description": "货代系统单号(manual_confirm 时填写)"
"description": "货代系统单号(可选;manual_confirm 通常无需填写)"
}
},
"required": [
@@ -479,7 +524,7 @@
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -494,8 +539,8 @@
"/tools/get_task_status": {
"post": {
"operationId": "get_task_status",
"summary": "查询 task 当前状态与 human_options",
"description": "查询 task 当前状态与 human_options",
"summary": "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
"description": "查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
"parameters": [],
"requestBody": {
"required": true,
@@ -506,19 +551,20 @@
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID"
}
},
"required": [
"task_id"
]
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed)",
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
@@ -531,4 +577,4 @@
}
}
}
}
}
+2292 -1060
View File
File diff suppressed because it is too large. Load diff
+123 -23
View File
@@ -1,26 +1,49 @@
# 货代发货通知 — 业务操作说明
# 货代发货通知 — 业务培训手册 / 操作 SOP
> **面向对象**:货代、跟单、仓储等业务人员。
> **配套技术文档**:[`shipping_notice.md`](./shipping_notice.md)(部署、系统配置,供 IT / 开发维护)。
> **维护约定**:发货流程、字段规则、人工确认节点等发生变更时,**须同时更新本文件与 `shipping_notice.md`**,避免业务说明与系统行为不一致。
> **建议使用方式**:新同事先看 **§1 功能概述**、**§3 需要准备哪些资料**、**§5 完整操作流程**、**§6 各阶段您需要做什么**;日常处理时优先看 **§11 常见操作速查**、**§12 截图位说明**、**§13 常见问题**。
---
## 目录
1. [功能概述](#1-功能概述)
2. [入口与任务编号](#2-入口与任务编号)
- [2.1 从哪里进入](#21-从哪里进入)
- [2.2 任务编号(SN-…)](#22-任务编号sn-)
3. [需要准备哪些资料](#3-需要准备哪些资料)
4. [订单与库存字段说明](#4-订单与库存字段说明)
5. [完整操作流程](#5-完整操作流程)
6. [各阶段您需要做什么](#6-各阶段您需要做什么)
- [4.1 订单行(来自发货通知)](#41-订单行来自发货通知)
- [4.2 库存行(来自仓库/货代导出)](#42-库存行来自仓库货代导出)
5. [完整操作流程(总 SOP)](#5-完整操作流程总-sop)
6. [各阶段您需要做什么(分阶段 SOP)](#6-各阶段您需要做什么分阶段-sop)
- [阶段 ① — 提交发货通知](#阶段--提交发货通知)
- [阶段 ② — 确认发货通知解析](#阶段--确认发货通知解析)
- [阶段 ③ — 提供库存](#阶段--提供库存)
- [阶段 ④ — 确认字段对齐](#阶段--确认字段对齐)
- [阶段 ⑤ — 自动匹配库存](#阶段--自动匹配库存)
- [阶段 ⑥ — 库存不足时的决策](#阶段--库存不足时的决策)
- [阶段 ⑦⑧ — 生成 Excel 与上传货代](#阶段-生成-excel-与上传货代)
7. [库存匹配规则](#7-库存匹配规则)
8. [库存不足时的处理](#8-库存不足时的处理)
9. [生成发货 Excel 与上传货代](#9-生成发货-excel-与上传货代)
- [9.1 发货 Excel](#91-发货-excel)
- [9.2 上传货代](#92-上传货代)
10. [任务状态说明](#10-任务状态说明)
11. [常见操作速查](#11-常见操作速查)
12. [常见问题](#12-常见问题)
13. [待业务侧补充的规范](#13-待业务侧补充的规范)
12. [截图位说明(给业务培训/反馈用)](#12-截图位说明给业务培训反馈用)
- [12.1 入口页截图](#121-入口页截图)
- [12.2 发货通知解析阶段截图](#122-发货通知解析阶段截图)
- [12.3 库存上传与字段对齐阶段截图](#123-库存上传与字段对齐阶段截图)
- [12.4 匹配与缺口处理阶段截图](#124-匹配与缺口处理阶段截图)
- [12.5 发货 Excel 与上传阶段截图](#125-发货-excel-与上传阶段截图)
- [12.6 问题反馈建议截图](#126-问题反馈建议截图)
13. [常见问题](#13-常见问题)
14. [待业务侧补充的规范](#14-待业务侧补充的规范)
15. [文档版本](#文档版本)
---
@@ -36,9 +59,16 @@
整个过程中,系统在关键节点会**暂停并请您确认**,避免误发、错配。
**业务人员只需要记住 4 件事**:
- 先上传或粘贴**发货通知**,确认解析结果
- 再提供**库存**,并确认字段对齐
- 匹配结果若有缺口,决定是否**部分发货**
- 匹配通过后下载/确认**发货 Excel**,并完成货代上传
**系统如何工作(便于理解)**:
- 上传 **发货通知 PDF** 后,系统会在后台**自动**创建任务编号并解析订单行(无需您手动说「创建任务」)。
- 上传 **发货通知 PDF/Word** 或**粘贴邮件/微信正文**后,系统会在后台**自动**创建任务编号并由 AI 解析订单行(无需您手动说「创建任务」)。
- 上传 **库存 Excel** 后,系统会**自动识别表头**(如 `Reservation Order`、`COM ID`)并给出列映射建议;**不确定的列**可在对齐界面用下拉框修改后再确认。
- 匹配与生成 Excel 由系统规则执行;您主要在解析结果、字段对齐、库存不足时做确认。
@@ -75,6 +105,15 @@ SN-20260529-A1B2C3D4
**顺序要求**:须先完成发货通知解析并确认,再上传库存。若尚未有任务编号就上传库存 Excel,系统会提示您先提交发货通知。
**开工前检查清单**
| 检查项 | 通过标准 |
|--------|----------|
| 发货通知原件 | 能看到 SKU、数量,最好能看到 Reservation ID / COM ID / PR Number |
| 库存文件 | 使用 Excel 文件上传,不把整张大表粘贴进聊天 |
| 当前任务 | 已拿到任务编号 `SN-...`,且本次库存属于这一个任务 |
| 操作顺序 | 先确认解析,再传库存,再确认字段对齐 |
---
## 4. 订单与库存字段说明
@@ -131,7 +170,7 @@ SN-20260529-A1B2C3D4
---
## 5. 完整操作流程
## 5. 完整操作流程(总 SOP)
```text
① 提交发货通知
@@ -157,9 +196,15 @@ SN-20260529-A1B2C3D4
- 必须先确认**字段对齐**,再执行**库存匹配**。
- 只有匹配通过(或您确认部分发货)后,才能生成 Excel 并上传货代。
**一句话 SOP**
```text
发货通知 → 确认解析 → 上传库存 → 确认字段对齐 → 匹配库存 → 缺口决策 → 生成 Excel → 上传货代
```
---
## 6. 各阶段您需要做什么
## 6. 各阶段您需要做什么(分阶段 SOP)
### 阶段 ① — 提交发货通知
@@ -171,7 +216,7 @@ SN-20260529-A1B2C3D4
**系统会做:**
- **自动**创建任务并分配 **SN-…** 编号;
- **自动**解析客户名称、收货信息、订单明细行(PDF 上传后由系统后台完成,无需您输入「创建任务」)。
- **自动**解析客户名称、收货信息、订单明细行(PDF 上传或正文粘贴后由系统后台完成,无需您输入「创建任务」)。
**您会看到:**
@@ -377,7 +422,73 @@ SN-20260529-A1B2C3D4
---
## 12. 常见问题
## 12. 截图位说明(给业务培训/反馈用)
以下截图位建议用于:
- 新同事培训材料
- 业务 SOP 文档
- 问题反馈给 IT / 开发时的截图指引
**截图原则**
| 原则 | 说明 |
|------|------|
| 保留任务编号 | 截图里尽量带上 `SN-...`,便于定位同一任务 |
| 保留关键字段 | 至少能看到 SKU、Reservation ID、数量、状态或按钮 |
| 一屏一主题 | 一张图只说明一个阶段,避免把多个动作混在一起 |
| 注意脱敏 | 对客户名称、价格、地址等敏感信息按公司要求处理 |
### 12.1 入口页截图
| 截图位 | 应包含内容 | 用途 |
|--------|------------|------|
| 助手入口页 | 助手名称、上传入口、聊天输入框 | 培训业务如何开始处理新任务 |
| 货代发货列表页 | 任务列表、状态列、`在 Chat 中继续` 入口 | 培训如何查看历史任务和续办 |
### 12.2 发货通知解析阶段截图
| 截图位 | 应包含内容 | 用途 |
|--------|------------|------|
| 发货通知上传后结果页 | 任务编号、采购单号、SKU、Reservation ID、数量、确认/重新解析/驳回按钮 | 培训业务如何核对解析结果 |
| 低置信度提示页 | 解析结果下方的风险提示或需人工核对提示 | 培训业务识别“需要更认真核对”的场景 |
### 12.3 库存上传与字段对齐阶段截图
| 截图位 | 应包含内容 | 用途 |
|--------|------------|------|
| 上传库存入口 | 选择库存文件按钮或上传动作 | 培训业务如何上传库存 Excel |
| 字段对齐页 | 库存列、订单字段、样例数据、确认/更正映射/重新上传按钮 | 培训业务如何确认列映射 |
| 列映射下拉框 | Reservation ID、SKU、可用数量的下拉选择 | 培训业务如何修正错误映射 |
### 12.4 匹配与缺口处理阶段截图
| 截图位 | 应包含内容 | 用途 |
|--------|------------|------|
| 匹配结果页 | SKU、Reservation ID、需求数量、可用数量、缺口、状态 | 培训业务如何判断是否可发 |
| 缺口决策页 | 确认部分发货 / 驳回 / 重新匹配按钮 | 培训业务如何处理库存不足 |
### 12.5 发货 Excel 与上传阶段截图
| 截图位 | 应包含内容 | 用途 |
|--------|------------|------|
| Excel 已生成页 | 下载入口、任务编号、当前状态 | 培训业务如何获取发货文件 |
| 自动上传状态页 | 上传中 / 已上传 / 上传失败提示 | 培训业务识别自动上传进度 |
| 手工上传确认页 | 手工上传后的确认提示或聊天回复 | 培训业务如何在系统内完成收尾 |
### 12.6 问题反馈建议截图
业务反馈问题给 IT / 开发时,建议至少提供以下 3 类截图:
1. **当前页面全图**:能看到任务编号、当前状态、主要按钮
2. **异常位置局部图**:报错提示、空字段、错误映射、缺口结果等
3. **原始资料图**:原 PDF / 邮件 / 库存 Excel 中对应字段的位置
若能同时提供任务编号 `SN-...`、操作时间、当时做了什么,排查会更快。
---
## 13. 常见问题
**Q:为什么要先确认发货通知,再传库存?**
A:避免任务编号不一致、订单行未定型就占用库存比对,导致结果不可追溯。
@@ -392,20 +503,9 @@ A:可以。字段对齐环节会把 COM ID 与订单 Reservation ID 对应;
A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是库存精确匹配的关键字段。请按以下顺序处理:
1. 先在原 PDF/邮件中确认是否真的存在该字段(常见写法:`Reservation ID: 1000140351`、`COM ID: 1000140351`、`Reservation Order: 1000140351`、`PR Number: xxx@1000140351`、`PR_Number: xxx@1000140351`)。
2. 若原件里存在但系统没抽出来:请联系 IT/开发按 [`shipping_notice.md`](./shipping_notice.md) **[§2.3 发货通知字段抽取(Chatflow LLM)](./shipping_notice.md#23-发货通知字段抽取chatflow-llm-节点)** 调整 **Chatflow 画布内 LLM 节点** 提示词(无需单独 Workflow 应用)。
2. 若原件里存在但系统没抽出来:请把**原文件/截图、任务编号 SN-...、错误现象**一起反馈给 IT/开发排查。
3. 若原件里不存在:请向客户/上游确认 Reservation ID 的提供规则,否则系统只能按 SKU 汇总匹配,可能导致同 SKU 多预留号的场景误匹配。
给 IT/开发的配置说明(完整 System/User Prompt 见 `shipping_notice.md` **§2.3.4 / §2.3.3**,在 **Chatflow PDF 分支 LLM 节点** 维护):
```text
必须抽取 reservation_id(也称 COM ID / Reservation Order / PR Number / PR_Number)。
1) reservation_id 通常为 8~12 位纯数字(如 1000140351),必须输出为字符串,禁止输出为 1000140351.0。
2) 识别同义标签:"Reservation ID"/"COM ID"/"Reservation Order"/"PR Number"/"PR_Number"/"PR No"/"PR#"。
3) 若出现 "xxx@1000140351",reservation_id 取 @ 后的纯数字字符串(例如 1000140351)。
4) 若表格无该列,必须从全文找文档级 reservation_id 并回填到所有 lines[*].reservation_id。
5) 输出字段必须包含 lines[*].reservation_id(无则输出空串 "",不要省略或输出 null)。
```
**Q:Reservation ID 必须是数字吗?**
A:业务上**一般为 8~12 位纯数字**(如 `1000140351`)。若格式异常,系统会提示核对是否解析正确。
@@ -420,7 +520,7 @@ A:建议**一票货一个对话、一个 SN-… 编号**,避免混淆。
---
## 13. 待业务侧补充的规范
## 14. 待业务侧补充的规范
以下信息越明确,系统配置与解析越准确(需业务与 IT 协同):
-213
View File
@@ -1,213 +0,0 @@
# Dify Chatflow 绑定 OpenAPI — 操作手册
> **已归档**:Dify 配置已合并至 [`shipping_notice.md` §2 Dify 配置(合集)](./shipping_notice.md#2-dify-配置合集)(OpenAPI 与端口见 **§2.1–§2.2**,Chatflow 画布见 **§2.4**)。下文仅作历史参考,请以 §2 为准。
本文说明如何将 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_task`
- `parse_notice`
- `ensure_inventory`
- `match_inventory`
- `submit_decision`
- `generate_shipment_excel`
- `upload_to_freight`
- `get_task_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:配置系统提示词
将 [`shipping_notice.md` §2.5 Agent 系统指令](./shipping_notice.md#25-agent-系统指令粘贴用) 全文粘贴到 Chatflow Agent 节点 **指令 / Instructions**。
要点:
- 必须先 `create_task`,全程携带 `task_id`
- `status=needs_human` 时等待用户选择,勿跳过
- `inventory_lines_json` 传 JSON 字符串,例如:`[{"sku":"A001","available_qty":10}]`
可选 Chatflow 变量(开始节点):
| 变量 | 用途 |
|------|------|
| `sys.user_id` / 自定义 `user_id` | 传入 `create_task.user_id` |
| `sys.conversation_id` | 传入 `create_task.conversation_id` |
---
## 步骤 5:发布并验证
1. **发布** Chatflow 应用
2. 在 hxops 前端打开该 Agent Chat,或 Dify 预览窗口测试
3. 发送示例:
```
客户:ACME,料号 A001 x 10,请处理发货。
```
4. 在 Dify **日志** 中确认 Agent 依次调用:
- `create_task` → `parse_notice` → `ensure_inventory` → …
5. 工作台 **货代发货** 应出现新 task;状态为 `running` 时表示 RPA 进行中,可 `get_task_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.md` §2 | Dify 配置合集(OpenAPI、Workflow、画布、Agent 指令) |
| `docs/shipping_notice_runbook.md` | 精简部署 Runbook(Dify 见 §2) |
-92
View File
@@ -1,92 +0,0 @@
# 货代发货通知 Agent — Dify Chatflow 系统提示词
> **已归档**:Agent 系统指令完整版见 [`shipping_notice.md` §2.5 Agent 系统指令](./shipping_notice.md#25-agent-系统指令粘贴用)。下文为旧版摘要,请以 §2.5 为准。
将以下内容配置到 Dify 应用 **「货代发货通知 Agent」**(`chatflow`)的系统提示词中,并绑定 Hxops Tool OpenAPI:`GET /api/shipping-notice/tools/openapi.json`(Header:`X-Shipping-Tool-Key`)。
---
## 角色
你是 **货代发货通知助手**,帮助业务人员处理客户发货指令(邮件/微信/PDF 文本)。你通过调用 Hxops Tool API 完成确定性流程,并在需要人工复核时暂停,等待用户明确选择后再继续。
## 核心原则
1. **先建 task**:收到新的发货需求时,先调用 `create_task`,保存 `task_id`(如 `SN-20260529-ABCD1234`),后续所有 Tool 都带上 `task_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_task_status`。
## Tool 响应约定
```json
{
"status": "ok | running | needs_human | failed",
"task_id": "SN-YYYYMMDD-XXXXXXXX",
"message": "人类可读说明",
"data": {},
"human_options": ["confirm", "reject", "retry_rpa", ...]
}
```
| status | 含义 | 你的行为 |
|--------|------|----------|
| `ok` | 步骤成功 | 继续下一步或总结 |
| `running` | 异步进行中(如 RPA) | 告知用户等待,可稍后 `get_task_status` |
| `needs_human` | 必须人工选择 | 列出 `human_options`,等用户回复 |
| `failed` | 不可恢复错误 | 说明错误,建议联系管理员 |
## 典型流程
### 1. 解析发货通知
用户粘贴邮件/微信/PDF 文本 → `parse_notice`(`task_id`, `raw_content`)。
- `needs_human` + `low_parse_confidence`:展示解析字段,请用户 **confirm / reject / reparse**。
- `confirm` → `submit_decision`(`decision: confirm`)。
### 2. 库存
`ensure_inventory`(`task_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`(`task_id`)。
- `needs_human` + 库存不足:展示 shortage,请 **confirm / reject / rematch**。
- `ok` + `fulfillable` → 生成 Excel。
### 4. 生成 Excel
`generate_shipment_excel`(`task_id`)→ 告知文件名,可下载链接:`/api/shipping-notice/tasks/{task_no}/export`。
### 5. 上传货代
`upload_to_freight`(`task_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、数量、缺口)。
- 每次操作复述当前 `task_id`。
- 不要编造库存或货代单号;以 Tool 返回的 `data` 为准。
## 变量(可选)
在 Chatflow 中可注入:
- `{{user_id}}` — 创建 case 时传入
- `{{conversation_id}}` — Dify 会话 ID,便于工作台关联
## 内部 Workflow
字段抽取 Workflow **「发货通知字段抽取」** 由 `parse_notice` Tool 内部调用,Chatflow **无需**直接调用。完整画布、System/User Prompt 见 [`shipping_notice.md` §2 Dify 配置(合集)](./shipping_notice.md#2-dify-配置合集)(Workflow §2.3,Chatflow §2.4,Agent 指令 §2.5)。
-93
View File
@@ -1,93 +0,0 @@
# 货代发货通知 — 本地部署 Runbook
> **已归档**:完整部署与 Dify 配置见 [`shipping_notice.md`](./shipping_notice.md)(部署 **§1**,Dify **§2**)。下文为精简历史 Runbook,Dify 步骤请以 §2 为准。
## 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
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# RPA 目录(相对 backend/ 根目录)
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
# 发货 Excel 模板(可选,默认 templates/freight_shipment_upload.xlsx)
FREIGHT_SHIPMENT_TEMPLATE_PATH=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 配置
> **见 [`shipping_notice.md` §2 Dify 配置(合集)](./shipping_notice.md#2-dify-配置合集)**(OpenAPI §2.2、Workflow §2.3、画布 §2.4、Agent 指令 §2.5、验收 §2.6)。
1. 创建 Chatflow 应用 **货代发货通知 Agent**,写入 `.env` 后 `python seed_shipping_notice_agents.py`
2. 按 §2.2 导入 OpenAPI 与鉴权 Header
3. 按 §2.3 创建并发布 Workflow **发货通知字段抽取**
4. 按 §2.4–§2.5 配置 Chatflow 画布与 Agent 指令
## 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}?task_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_task_status。
## 8. 待业务提供
- 货代系统库存导出 SOP + 样例 Excel 列名(可配置 `FREIGHT_INVENTORY_COLUMN_MAP`)
- 货代上传 SOP + 正式上传模板列映射
- 生产 Windows RPA 账号与 UiPath/Power Automate 脚本
+34 -1
View File
@@ -101,7 +101,7 @@ export async function applyWorkspaceShippingInventoryMapping(taskNo: string, col
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ column_mapping_json: columnMappingJson }),
body: JSON.stringify({ map_json: columnMappingJson }),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
@@ -210,6 +210,39 @@ export async function matchWorkspaceShippingInventory(taskNo: string) {
return body;
}
/** Hxops 聊天兜底:等同 Dify auto_progress Tool */
export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/auto-progress`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(lang ? { lang } : {}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export async function markWorkspaceShippingManualUploaded(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export async function generateWorkspaceShippingExcel(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`,
@@ -0,0 +1,58 @@
/**
* Action button ids for shipping-notice chat.
* Keep in sync with backend `state_machine.py` → ACTION_SPECS keys.
* CI: backend/tests/test_shipping_notice_state_machine.py::test_frontend_action_ids_match_backend
*/
export const SHIPPING_ACTION_IDS = [
'confirm',
'reject',
'reparse',
'confirm_inventory_mapping',
'correct_inventory_mapping',
'reparse_inventory',
'rematch',
'retry_rpa',
'upload_inventory_file',
'retry_upload',
'download_excel',
'generate_excel',
'mark_manual_uploaded',
'paste_inventory_json',
'edit_inventory_mapping',
'match_inventory',
'refresh',
] as const;
export type ShippingActionId = (typeof SHIPPING_ACTION_IDS)[number];
export const SHIPPING_KNOWN_ACTION_ID_SET = new Set<string>(SHIPPING_ACTION_IDS);
/** Backend state-machine codes — must never appear in user-visible chat text. */
export const SHIPPING_TERMINAL_CHECKPOINTS = new Set(['uploaded', 'completed', 'rejected']);
export const SHIPPING_INTERNAL_STATUS_TOKENS = [
'rpa_pending',
'upload_rpa_pending',
'rpa_exhausted',
'inv_unavail',
'align_review',
'map_infer',
'parse_review',
'shortage_review',
'low_confidence',
'waiting_inventory',
'inventory_ready',
'pending_review',
'waiting_upload',
'upload_failed',
'ready_to_match',
'ready_to_export',
'export_ready',
'upload_req',
'inventory_pending',
'map_ok',
'parse_ok',
'needs_human',
'fulfillable',
'unfulfillable',
] as const;
+70 -2
View File
@@ -444,6 +444,9 @@ const messages = {
download: 'Download Excel',
lines: 'Shipment lines',
qty: 'Qty',
columns: {
sku: 'SKU'
},
events: 'Event log',
filters: {
status: 'Status'
@@ -1278,13 +1281,31 @@ const messages = {
disclaimer: 'AI can make mistakes. Please verify important information.',
createNewChat: 'New Chat',
shippingNoticeContinue: 'Please continue shipping task {taskId}. Call get_task_status first and tell me the next step.',
shippingNoticeActionsHint: 'Choose an action (no need to type):',
shippingNoticeActionsHint: 'Choose an action:',
shippingNoticeMissingTaskId: 'Task ID not found. Complete shipping notice parsing first.',
shippingNoticeUploadDone: 'Inventory file uploaded: {fileName}.',
shippingNoticeUploadOk: 'Upload succeeded.',
shippingNoticeUploadFailed: 'Inventory upload failed.',
shippingNoticePasteHint: 'Paste inventory rows in the input box, then send.',
shippingNoticeDecisionDone: 'Action completed.',
shippingNoticeMapping: {
inventoryHeaders: 'Inventory headers',
headerRow: 'Header row: {row}',
sample: 'Sample',
orderDetails: 'Order details',
orderRowCount: 'Order rows: {count}',
orderSkuPreview: 'SKUs (first {count}): {skus}',
skuColumnRequired: 'SKU column (required)',
availableQtyColumnRequired: 'Available qty column (required)',
reservationIdColumnOptional: 'Reservation ID column (optional)',
selectHeader: 'Select a header',
reservationIdNotUsed: '(Do not use Reservation ID)',
reupload: 'Re-upload',
applying: 'Applying...',
applyAndParse: 'Apply mapping and parse',
empty: '(empty)',
unrecognized: '(unrecognized)'
},
clearAll: 'Clear All',
clearOneRecord: 'Clear This Record',
agents: 'Agents',
@@ -1984,6 +2005,9 @@ const messages = {
download: '下载 Excel',
lines: '发货明细',
qty: '数量',
columns: {
sku: 'SKU'
},
events: '事件记录',
filters: {
status: '状态'
@@ -2798,13 +2822,31 @@ const messages = {
disclaimer: 'AI 可能会犯错,请核实重要信息。',
createNewChat: '创建新对话',
shippingNoticeContinue: '请继续处理发货任务 {taskId},请先调用 get_task_status 查询当前状态并告知我下一步。',
shippingNoticeActionsHint: '请选择操作(无需输入文字):',
shippingNoticeActionsHint: '请选择操作:',
shippingNoticeMissingTaskId: '未找到任务编号,请先完成发货通知解析。',
shippingNoticeUploadDone: '库存文件已上传:{fileName}。',
shippingNoticeUploadOk: '上传成功。',
shippingNoticeUploadFailed: '库存文件上传失败。',
shippingNoticePasteHint: '请在输入框粘贴库存小表内容后发送。',
shippingNoticeDecisionDone: '操作已完成。',
shippingNoticeMapping: {
inventoryHeaders: '库存表头',
headerRow: '表头行:{row}',
sample: '样例',
orderDetails: '订单明细',
orderRowCount: '订单行数:{count}',
orderSkuPreview: 'SKU(前{count}):{skus}',
skuColumnRequired: 'SKU 列(必填)',
availableQtyColumnRequired: '可用数量列(必填)',
reservationIdColumnOptional: 'Reservation ID 列(可选)',
selectHeader: '请选择表头列名',
reservationIdNotUsed: '(不使用 Reservation ID)',
reupload: '重新上传',
applying: '应用中...',
applyAndParse: '应用映射并解析',
empty: '(空)',
unrecognized: '(未识别)'
},
clearAll: '清空全部',
clearOneRecord: '清除该记录',
agents: '智能体',
@@ -5392,6 +5434,32 @@ const messages = {
thinking: 'กำลังสร้างคำตอบ...',
disclaimer: 'AI อาจทำผิดพลาดได้ โปรดตรวจสอบข้อมูลสำคัญ',
createNewChat: 'แชทใหม่',
shippingNoticeContinue: 'กรุณาดำเนินการงานจัดส่งต่อ {taskId} โปรดเรียก get_task_status ก่อนและบอกขั้นตอนถัดไป',
shippingNoticeActionsHint: 'เลือกการทำงาน:',
shippingNoticeMissingTaskId: 'ไม่พบรหัสงาน โปรดแยกใบแจ้งส่งสินค้าก่อน',
shippingNoticeUploadDone: 'อัปโหลดไฟล์สต็อกแล้ว: {fileName}',
shippingNoticeUploadOk: 'อัปโหลดสำเร็จ',
shippingNoticeUploadFailed: 'อัปโหลดไฟล์สต็อกล้มเหลว',
shippingNoticePasteHint: 'วางข้อมูลสต็อกในช่องข้อความแล้วส่ง',
shippingNoticeDecisionDone: 'ดำเนินการเสร็จแล้ว',
shippingNoticeMapping: {
inventoryHeaders: 'หัวคอลัมน์สต็อก',
headerRow: 'แถวหัวตาราง: {row}',
sample: 'ตัวอย่าง',
orderDetails: 'รายละเอียดคำสั่งซื้อ',
orderRowCount: 'จำนวนแถวคำสั่งซื้อ: {count}',
orderSkuPreview: 'SKU (แรก {count}): {skus}',
skuColumnRequired: 'คอลัมน์ SKU (จำเป็น)',
availableQtyColumnRequired: 'คอลัมน์จำนวนคงเหลือ (จำเป็น)',
reservationIdColumnOptional: 'คอลัมน์ Reservation ID (ไม่บังคับ)',
selectHeader: 'เลือกชื่อหัวคอลัมน์',
reservationIdNotUsed: '(ไม่ใช้ Reservation ID)',
reupload: 'อัปโหลดใหม่',
applying: 'กำลังนำไปใช้...',
applyAndParse: 'นำการจับคู่ไปใช้และแยกข้อมูล',
empty: '(ว่าง)',
unrecognized: '(ไม่รู้จัก)'
},
clearAll: 'ล้างทั้งหมด',
clearOneRecord: 'ลบรายการนี้',
agents: 'ตัวแทน',
+297 -224
View File
@@ -54,13 +54,16 @@ import {
getWorkspaceShippingTask,
applyWorkspaceShippingInventoryMapping,
getShippingChatActions,
autoProgressWorkspaceShippingTask,
generateWorkspaceShippingExcel,
markWorkspaceShippingManualUploaded,
matchWorkspaceShippingInventory,
SHIPPING_NOTICE_AGENT_NAME,
submitWorkspaceShippingDecision,
uploadWorkspaceShippingInventory,
workspaceShippingExportUrl,
} from '../api/shippingNotice';
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET, SHIPPING_TERMINAL_CHECKPOINTS } from '../constants/shippingNoticeActions';
const { t, locale } = useI18n();
const { appliedTheme, toggleLightDark } = useTheme();
@@ -176,14 +179,72 @@ const stripReasoningPrelude = (text: string) => {
const sanitizeShippingConversationText = (text: string) => {
if (!isShippingNoticeAgent.value) return text;
return String(text || '')
let result = String(text || '')
.replace(/\btask_id\s*[::]/gi, '任务编号:')
.replace(/\btask_id\b/gi, '任务编号');
// Agent 有时会复述「(显示 "rpa_pending")」类后台标记
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
result = result.replace(
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
'',
);
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
const quoted = new RegExp(`[「"'“”‘’]\\s*${token}\\s*[」"'“”‘’]`, 'gi');
result = result.replace(quoted, '');
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
}
return result.replace(/\n{3,}/g, '\n\n').trim();
};
type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
const extractShippingActionsDirective = (rawText: string): {
cleanedText: string;
buttons: Array<{ id: string; label: string; message: string; variant?: ShippingActionVariant }>;
} => {
const text = String(rawText || '');
const re = /<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*([\s\S]*?)\s*-->/gi;
let cleaned = text;
const buttons: Array<{ id: string; label: string; message: string; variant?: ShippingActionVariant }> = [];
for (;;) {
const m = re.exec(text);
if (!m) break;
const body = String(m[1] || '').trim();
if (!body) continue;
try {
const parsed = JSON.parse(body);
if (Array.isArray(parsed)) {
for (const item of parsed) {
if (!item || typeof item !== 'object') continue;
const id = String((item as any).id || '').trim();
const label = String((item as any).label || '').trim();
const message = String((item as any).message || '').trim();
const variantRaw = String((item as any).variant || '').trim();
const variant: ShippingActionVariant | undefined = (variantRaw === 'primary' || variantRaw === 'secondary' || variantRaw === 'danger')
? (variantRaw as ShippingActionVariant)
: undefined;
if (!id || !label || !message) continue;
if (!SHIPPING_KNOWN_ACTION_ID_SET.has(id)) {
console.warn(`[shipping] unknown action id in HXOPS_SHIPPING_ACTIONS: ${id}`);
}
buttons.push({ id, label, message, variant });
}
}
} catch {
// ignore
}
}
cleaned = cleaned.replace(re, '').trim();
return { cleanedText: cleaned, buttons };
};
const renderMarkdown = (text: string) => {
if (!text) return '';
const displayText = sanitizeShippingConversationText(stripReasoningPrelude(text));
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text;
const displayText = sanitizeShippingConversationText(stripReasoningPrelude(stripped));
try {
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
return marked.parse(displayText);
@@ -2128,6 +2189,7 @@ const displayHistory = computed<DisplayHistoryItem[]>(() => {
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.agentId === currentAgentId.value)
.filter((r) => r.status === 'running')
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
@@ -2362,12 +2424,15 @@ const normalizeMenuDigit = (ch: string) => {
};
const classifyShippingMenuLine = (desc: string): ShippingMenuAction | null => {
if (/上传|excel|xlsx|xls|csv|库存文件|\.xlsx/i.test(desc)) return 'upload';
const normalized = String(desc || '').trim();
if (!normalized) return null;
if (/已确认/.test(normalized)) return null;
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste';
if (/重试|rpa|拉取/i.test(desc)) return 'retry_rpa';
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
if (/驳回|取消|reject/i.test(desc)) return 'reject';
if (/确认|confirm/i.test(desc)) return 'confirm';
if (/^(?:确认|confirm)\b/i.test(normalized)) return 'confirm';
return null;
};
@@ -2387,20 +2452,6 @@ const parseShippingMenuFromContext = (
return map;
};
const buildShippingMenuButtons = (ctx: string) => {
const menu = parseShippingMenuFromContext(ctx);
if (!menu.size) return null;
return [...menu.entries()]
.sort(([a], [b]) => a - b)
.map(([num, item]) => {
const spec = SHIPPING_MENU_ACTION_SPECS[item.action];
return {
...spec,
label: `${num}. ${item.desc || spec.label}`,
};
});
};
const resolveShippingNumericChoice = (text: string): ShippingMenuAction | null => {
const normalized = text.trim();
if (!/^[1-91-9](?:[\.\、\)::]?)$/.test(normalized)) return null;
@@ -2408,142 +2459,26 @@ const resolveShippingNumericChoice = (text: string): ShippingMenuAction | null =
return parseShippingMenuFromContext(lastAssistantMessageContent()).get(num)?.action || null;
};
const isShippingFieldAlignmentPrompt = (text: string) => {
if (/无需确认|确认失败|已驳回|rejected|unfulfillable|重新创建|建议方案|不需要确认/.test(text)) {
return false;
}
const hasAlignmentTable = (
text.includes('|系统字段|库存列|')
|| text.includes('字段对齐表:')
|| text.includes('字段对齐表:')
);
if (!hasAlignmentTable) return false;
const hasConfirm = (
text.includes('请确认')
|| text.includes('确认后才能匹配')
);
if (!hasConfirm) return false;
const hasInventoryContext = (
text.includes('库存列')
|| text.includes('field_alignment')
|| text.includes('inventory_columns')
|| text.includes('available_qty')
|| text.includes('reservation_id')
);
return hasInventoryContext;
};
const inferShippingActionsFromContent = (content: string) => {
const text = String(content || '');
if (text.includes('已生成发货 Excel') || text.includes('download_excel') || text.includes('waiting_upload')) {
return [
{ id: 'download_excel', label: '下载 Excel', message: '下载发货 Excel', variant: 'secondary' as const },
];
}
if (text.includes('生成 Excel') || text.includes('generate_shipment_excel') || text.includes('generate_excel')) {
return [
{ id: 'generate_excel', label: '生成发货 Excel', message: '生成发货 Excel', variant: 'primary' as const },
];
}
if (
text.includes('match_inventory')
|| (text.includes('匹配库存') && text.includes('任务编号'))
) {
return [
{ id: 'match_inventory', label: '匹配库存', message: '匹配库存', variant: 'primary' as const },
];
}
if (
text.includes('reservation_id_required')
|| text.includes('Reservation ID 必填')
|| text.includes('缺少 Reservation ID')
) {
return [
{ id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' as const },
{ id: 'edit_inventory_mapping', label: '修改映射', message: '修改库存列映射', variant: 'primary' as const },
{ id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'secondary' as const },
{ id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const },
];
}
if (isShippingFieldAlignmentPrompt(text)) {
return [
{ id: 'confirm_inventory_mapping', label: '确认', message: '确认', variant: 'primary' as const },
{ id: 'correct_inventory_mapping', label: '更正映射', message: '更正映射', variant: 'secondary' as const },
{ id: 'reparse_inventory', label: '重新上传', message: '重新上传库存', variant: 'secondary' as const },
{ id: 'reject', label: '取消', message: '驳回', variant: 'danger' as const },
];
}
if (
text.includes('请确认以上信息')
|| text.includes('请确认以上')
|| text.includes('请确认以下')
|| text.includes('请核对')
|| text.includes('确认后继续')
|| text.includes('回复「确认」')
|| text.includes('回复"确认"')
|| /回复\s*[\[【「"'((]?\s*确认/.test(text)
) {
return [
{ id: 'confirm', label: '确认', message: '确认', variant: 'primary' as const },
{ id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' as const },
{ id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const },
];
}
if (text.includes('库存数量不足') || text.includes('缺口明细')) {
return [
{ id: 'confirm', label: '确认部分发货', message: '确认', variant: 'primary' as const },
{ id: 'rematch', label: '重新匹配', message: '重新匹配', variant: 'secondary' as const },
{ id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const },
];
}
if (
text.includes('waiting_inventory')
|| text.includes('inventory_rpa_pending')
|| text.includes('重试 RPA')
|| text.includes('上传库存')
|| text.includes('upload_inventory_file')
|| /[1-3][\.\、\)]/.test(text)
) {
const menuButtons = buildShippingMenuButtons(text);
if (menuButtons?.length) return menuButtons;
return [
{ id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' as const },
{ id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' as const },
{ id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' as const },
];
}
return [];
};
const shouldPreferInferredShippingActions = (
const resolveShippingActionButtons = (
content: string,
inferred: Array<{ id: string }>,
api: Array<{ id: string }>,
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
options?: { apiResolved?: boolean },
) => {
if (!inferred.length || !api.length) return false;
const text = String(content || '');
const hasConfirmPrompt = (
text.includes('请确认')
|| text.includes('回复「确认」')
|| text.includes('回复"确认"')
|| /回复\s*[\[【「"'((]?\s*确认/.test(text)
|| text.includes('请核对')
|| text.includes('确认后继续')
);
if (!hasConfirmPrompt) return false;
const inferredHasDecision = inferred.some((b) => ['confirm', 'reparse', 'reject'].includes(b.id));
if (!inferredHasDecision) return false;
const apiLooksLikeInventoryMenu = api.some((b) => [
'upload_inventory_file',
'retry_rpa',
'paste_inventory_json',
'confirm_inventory_mapping',
'correct_inventory_mapping',
'reparse_inventory',
'edit_inventory_mapping',
].includes(b.id));
if (!apiLooksLikeInventoryMenu) return false;
return true;
const directive = extractShippingActionsDirective(String(content || ''));
if (options?.apiResolved) {
return {
buttons: apiButtons || [],
cleanedText: directive.cleanedText,
fromDirective: false,
};
}
if (directive.buttons.length) {
return { buttons: directive.buttons, cleanedText: directive.cleanedText, fromDirective: true };
}
if (apiButtons?.length) {
return { buttons: apiButtons, cleanedText: directive.cleanedText, fromDirective: false };
}
return { buttons: [], cleanedText: directive.cleanedText, fromDirective: false };
};
const SHIPPING_DECISION_ACTIONS = new Set([
@@ -2586,7 +2521,17 @@ const executeShippingDecision = async (decision: string, displayText?: string) =
return false;
}
try {
const result = await submitWorkspaceShippingDecision(taskId, decision);
const result =
decision === 'confirm_inventory_mapping'
? await autoProgressWorkspaceShippingTask(taskId)
: await submitWorkspaceShippingDecision(taskId, decision);
if (decision === 'correct_inventory_mapping') {
const preview = result?.data?.schema_preview;
const key = String(taskId || '').trim().toUpperCase();
if (key && preview && typeof preview === 'object') {
shippingInventorySchemaPreviewCache.value = { ...shippingInventorySchemaPreviewCache.value, [key]: preview };
}
}
const userText = (displayText || decision).trim();
const assistantContent = formatShippingDecisionAssistantMessage(decision, result, taskId);
const userMsg = {
@@ -2616,6 +2561,9 @@ const executeShippingDecision = async (decision: string, displayText?: string) =
if (!exists) await loadHistory();
}
void refreshShippingActions();
if (decision === 'correct_inventory_mapping') {
await openShippingInventoryMappingFormForTask(taskId);
}
return true;
} catch (e: any) {
msg.warning(e?.message || t('chat.shippingNoticeUploadFailed'));
@@ -2653,7 +2601,9 @@ const formatShippingDecisionAssistantMessage = (
'也可点击「选择库存文件」重新上传。',
);
} else if (decision === 'confirm_inventory_mapping') {
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
if (String(result.checkpoint || '').trim() === 'map_ok') {
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
}
} else if (decision === 'reparse_inventory') {
lines.push('', '请重新上传或粘贴库存 Excel。');
}
@@ -2696,6 +2646,43 @@ const pushShippingLocalAssistantMessage = async (text: string) => {
await saveLocalMessageToBackend(assistantMsg);
};
const buildShippingInventoryUploadPrompt = (
result: Record<string, any> | null | undefined,
fileName?: string,
) => {
const checkpoint = String(result?.checkpoint || '').trim();
const hasAlignment = Boolean(result?.data?.field_alignment && typeof result?.data?.field_alignment === 'object');
const suggestOk = Boolean(result?.data?.suggest_ok);
const prefix = fileName ? `我已上传库存文件《${fileName}》` : '我已上传库存文件';
if (checkpoint === 'map_infer') {
if (suggestOk) {
return `${prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。`;
}
return `${prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。`;
}
if (checkpoint === 'align_review' || hasAlignment) {
return `${prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。`;
}
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
};
const continueShippingInventoryUploadWithDify = async (
taskId: string,
result: Record<string, any> | null | undefined,
fileName?: string,
) => {
const key = String(taskId || '').trim().toUpperCase();
const schemaPreview = result?.data?.schema_preview;
if (key && schemaPreview && typeof schemaPreview === 'object') {
shippingInventorySchemaPreviewCache.value = { ...shippingInventorySchemaPreviewCache.value, [key]: schemaPreview };
}
resolvedShippingTaskId.value = taskId;
await sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
};
const normalizeShippingHeaderForDisplay = (raw: any): string => {
const text = String(raw ?? '').replace(/\s+/g, ' ').trim();
return text.replace(/ /g, '\u00A0');
@@ -2781,21 +2768,7 @@ const handleShippingAutoUploadFile = async (file: File) => {
}
resolvedShippingTaskId.value = taskId;
const result = await uploadWorkspaceShippingInventory(taskId, file);
const checkpoint = String((result as any)?.checkpoint || '').trim();
const schemaPreview = (result as any)?.data?.schema_preview;
if (checkpoint === 'inventory_mapping_inference' && schemaPreview && typeof schemaPreview === 'object') {
shippingInventorySchemaPreviewCache.value = { ...shippingInventorySchemaPreviewCache.value, [taskId]: schemaPreview };
}
const alignmentText = buildShippingFieldAlignmentText(result);
const hint = alignmentText || String(result.message || t('chat.shippingNoticeUploadOk')).trim();
await pushShippingLocalAssistantMessage(
[
`库存已上传:${file.name}`,
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
void refreshShippingActions();
await continueShippingInventoryUploadWithDify(taskId, result as Record<string, any>, file.name);
return;
}
@@ -2859,6 +2832,58 @@ const isShippingInventoryUploadIntent = (text: string) => {
].some((pattern) => pattern.test(normalized));
};
const isShippingManualUploadIntent = (text: string) => {
const normalized = text.trim();
if (!normalized) return false;
return [
/已在货代系统手工上传/,
/已手工上传/,
/手工上传完成/,
/手动上传完成/,
/货代.*上传完成/,
].some((pattern) => pattern.test(normalized));
};
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
try {
const result = await markWorkspaceShippingManualUploaded(taskId);
const userText = (displayText || '已在货代系统手工上传完成').trim();
const assistantContent = [
String(result.message || '已标记为手工上传货代系统完成。').trim(),
`任务编号:${taskId}`,
].join('\n');
const userMsg = {
role: 'user' as const,
type: 'text' as const,
content: `${userText}\n任务编号:${taskId}`,
local_id: newLocalMessageId('shipping-user'),
local_only: true,
};
const assistantMsg = {
role: 'assistant' as const,
type: 'text' as const,
content: assistantContent,
local_id: newLocalMessageId('shipping-assistant'),
local_only: true,
shipping_actions_used: true,
};
messages.value.push(userMsg, assistantMsg);
messages.value.forEach((rawMsg) => {
const m = rawMsg as any;
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
await saveLocalMessageToBackend(userMsg, userText);
await saveLocalMessageToBackend(assistantMsg, userText);
void refreshShippingActions();
return true;
} catch (e: any) {
msg.warning(e?.message || '标记手工上传失败');
return false;
}
};
const isShippingGenerateExcelIntent = (text: string) => {
const normalized = text.trim();
if (!normalized) return false;
@@ -2919,6 +2944,11 @@ const sendShippingMenuMessage = async (message: string) => {
const handleShippingMenuAction = async (action: { id?: string; message: string }, msg?: any) => {
if (isThinking.value) return;
if (action.id === 'refresh') {
await sendShippingMenuMessage(action.message || '刷新');
return;
}
if (action.id === 'download_excel') {
const taskId = getActiveShippingTaskId();
if (!taskId) {
@@ -3022,6 +3052,18 @@ const handleShippingMenuAction = async (action: { id?: string; message: string }
return;
}
if (action.id === 'mark_manual_uploaded') {
if (msg?.shipping_actions_used) return;
if (msg) msg.shipping_actions_used = true;
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return;
}
await executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
return;
}
if (action.id === 'paste_inventory_json') {
msg.info(t('chat.shippingNoticePasteHint'));
return;
@@ -3082,6 +3124,7 @@ const refreshShippingActions = async () => {
}
if (taskId) resolvedShippingTaskId.value = taskId;
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
let apiCheckpoint: string | null = null;
let apiResolved = false;
if (taskId && !isThinking.value) {
@@ -3090,6 +3133,7 @@ const refreshShippingActions = async () => {
const data = await getShippingChatActions(taskId);
if (seq === shippingActionsRequestSeq) {
apiResolved = true;
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
}
} catch {
@@ -3097,6 +3141,16 @@ const refreshShippingActions = async () => {
}
}
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
msgs.forEach((rawMsg) => {
const m = rawMsg as any;
if (m.role === 'assistant') {
m.shipping_actions = undefined;
}
});
return;
}
let lastOpenAssistantIndex = -1;
for (let i = msgs.length - 1; i >= 0; i -= 1) {
const item = msgs[i];
@@ -3132,15 +3186,22 @@ const refreshShippingActions = async () => {
}
let buttons: Array<{ id: string; label: string; message: string; variant?: string }> = [];
if (apiResolved && index === targetAssistantIndex) {
const inferred = inferShippingActionsFromContent(String(msg.content || ''));
if (apiButtons && apiButtons.length && shouldPreferInferredShippingActions(String(msg.content || ''), inferred, apiButtons)) {
buttons = inferred;
} else {
buttons = apiButtons || inferred;
if (index === targetAssistantIndex) {
const resolved = resolveShippingActionButtons(
String(msg.content || ''),
apiResolved ? (apiButtons ?? []) : null,
{ apiResolved },
);
if (resolved.fromDirective) {
msg.content = resolved.cleanedText;
}
buttons = resolved.buttons;
} else if (!apiResolved) {
buttons = inferShippingActionsFromContent(String(msg.content || ''));
const resolved = resolveShippingActionButtons(String(msg.content || ''), null);
if (resolved.fromDirective) {
msg.content = resolved.cleanedText;
}
buttons = resolved.buttons;
}
msg.shipping_actions = buttons.length ? buttons : undefined;
});
@@ -3175,38 +3236,7 @@ const handleShippingInventorySelected = async (event: Event) => {
try {
const result = await uploadWorkspaceShippingInventory(taskId, file);
const checkpoint = String((result as any)?.checkpoint || '').trim();
const schemaPreview = (result as any)?.data?.schema_preview;
if (checkpoint === 'inventory_mapping_inference' && schemaPreview && typeof schemaPreview === 'object') {
const key = String(taskId || '').trim().toUpperCase();
if (key) {
shippingInventorySchemaPreviewCache.value = { ...shippingInventorySchemaPreviewCache.value, [key]: schemaPreview };
}
const hint = [
String((result as any)?.message || '').trim(),
'请点击下方“修改映射”,用下拉框选择 SKU / 可用数量 / Reservation ID 列。',
].filter(Boolean).join('\n');
await pushShippingLocalAssistantMessage(
[
`库存已上传:${file.name}`,
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
resolvedShippingTaskId.value = taskId;
void refreshShippingActions();
return;
}
const alignmentText = buildShippingFieldAlignmentText(result);
const hint = alignmentText || String(result.message || t('chat.shippingNoticeUploadOk')).trim();
await pushShippingLocalAssistantMessage(
[
`库存已上传:${file.name}`,
`任务编号:${taskId}`,
hint,
].filter(Boolean).join('\n'),
);
void refreshShippingActions();
await continueShippingInventoryUploadWithDify(taskId, result as Record<string, any>, file.name);
} catch (e: any) {
msg.warning(e?.message || t('chat.shippingNoticeUploadFailed'));
}
@@ -3384,6 +3414,19 @@ const handleSend = async (textOrEvent?: string | Event) => {
}
}
if (isShippingManualUploadIntent(content)) {
const taskId = getActiveShippingTaskId();
if (!taskId) {
msg.warning('未找到任务编号,请先完成前面的步骤');
return;
}
resolvedShippingTaskId.value = taskId;
if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = [];
await executeShippingManualUpload(taskId, content.trim());
return;
}
if (isShippingInventoryUploadIntent(content)) {
if (typeof textOrEvent !== 'string') input.value = '';
if (openShippingInventoryPicker()) return;
@@ -3706,6 +3749,7 @@ const deleteHistoryItem = async (id: string, event: Event) => {
try {
await deleteChatSession(id, currentAgentId.value);
history.value = history.value.filter(h => h.conversation_id !== id);
runs.value = runs.value.filter((r) => !(r.agentId === currentAgentId.value && r.conversationId === id));
if (conversationId.value === id) {
startNewChat();
}
@@ -4520,63 +4564,63 @@ const showChatRating = ref(false);
<div class="text-sm font-medium text-secondary whitespace-pre-wrap">{{ msg.content }}</div>
<div class="rounded-2xl border border-default bg-surface-soft/90 p-4 space-y-4">
<div class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">库存表头</div>
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.inventoryHeaders') }}</div>
<div class="text-xs text-muted">
表头行:{{ getShippingInventoryMappingPayload(msg)!.schema_preview.header_row_index || 1 }}
{{ $t('chat.shippingNoticeMapping.headerRow', { row: getShippingInventoryMappingPayload(msg)!.schema_preview.header_row_index || 1 }) }}
</div>
<div class="flex flex-wrap gap-2">
<span
v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])"
:key="`inv-h-${h}`"
class="rounded-full border border-default bg-surface px-3 py-1 text-xs text-secondary"
>{{ normalizeShippingHeaderForDisplay(h) || '(空)' }}</span>
>{{ normalizeShippingHeaderForDisplay(h) || $t('chat.shippingNoticeMapping.empty') }}</span>
</div>
<div
v-if="Array.isArray(getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows) && getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows.length"
class="text-xs text-muted whitespace-pre-wrap"
>
样例:{{ (getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows[0] || []).join(' | ') }}
{{ $t('chat.shippingNoticeMapping.sample') }}:{{ (getShippingInventoryMappingPayload(msg)!.schema_preview.sample_rows[0] || []).join(' | ') }}
</div>
</div>
<div class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">订单明细</div>
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
<div class="text-xs text-muted">
订单行数:{{ getShippingInventoryMappingPayload(msg)!.order.line_count }};SKU(前{{ getShippingInventoryMappingPayload(msg)!.order.skus.length }}):{{ getShippingInventoryMappingPayload(msg)!.order.skus.join(',') || '(未识别)' }}
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: getShippingInventoryMappingPayload(msg)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: getShippingInventoryMappingPayload(msg)!.order.skus.length, skus: getShippingInventoryMappingPayload(msg)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
</div>
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">SKU 列(必填)</span>
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
<select
v-model="getShippingInventoryMappingPayload(msg)!.form.sku"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
>
<option value="" disabled>请选择表头列名</option>
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
<option v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ normalizeShippingHeaderForDisplay(h) }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">可用数量列(必填)</span>
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.availableQtyColumnRequired') }}</span>
<select
v-model="getShippingInventoryMappingPayload(msg)!.form.available_qty"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
>
<option value="" disabled>请选择表头列名</option>
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
<option v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])" :key="`qty-${h}`" :value="h">{{ normalizeShippingHeaderForDisplay(h) }}</option>
</select>
</label>
<label class="space-y-1.5 md:col-span-2">
<span class="text-xs font-semibold text-muted">Reservation ID 列(可选)</span>
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
<select
v-model="getShippingInventoryMappingPayload(msg)!.form.reservation_id"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
>
<option value="">(不使用 Reservation ID)</option>
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
<option v-for="h in (getShippingInventoryMappingPayload(msg)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ normalizeShippingHeaderForDisplay(h) }}</option>
</select>
</label>
@@ -4589,7 +4633,7 @@ const showChatRating = ref(false);
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
@click="reuploadShippingInventoryFromMappingForm(msg)"
>
重新上传
{{ $t('chat.shippingNoticeMapping.reupload') }}
</button>
<button
type="button"
@@ -4597,14 +4641,14 @@ const showChatRating = ref(false);
:disabled="getShippingInventoryMappingPayload(msg)!.applying"
@click="applyShippingInventoryMappingForm(msg)"
>
{{ getShippingInventoryMappingPayload(msg)!.applying ? '应用中...' : '应用映射并解析' }}
{{ getShippingInventoryMappingPayload(msg)!.applying ? $t('chat.shippingNoticeMapping.applying') : $t('chat.shippingNoticeMapping.applyAndParse') }}
</button>
</div>
</div>
</div>
<div
v-else
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-table:w-full prose-table:border-collapse prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
@click="handleChatMarkdownClick"
v-html="renderMarkdown(msg.content)"
></div>
@@ -5263,6 +5307,35 @@ const showChatRating = ref(false);
</template>
<style scoped>
:deep(.chat-markdown table) {
width: 100%;
border-collapse: collapse;
margin: 0.75rem 0;
font-size: 0.875rem;
}
:deep(.chat-markdown th),
:deep(.chat-markdown td) {
border: 1px solid rgb(226 232 240);
padding: 0.5rem 0.75rem;
text-align: left;
vertical-align: top;
}
:deep(.chat-markdown th) {
background: rgb(248 250 252);
font-weight: 600;
}
:deep(.dark .chat-markdown th),
:deep(.dark .chat-markdown td) {
border-color: rgb(51 65 85);
}
:deep(.dark .chat-markdown th) {
background: rgb(30 41 59);
}
:deep(.chat-markdown details) {
margin-top: 1rem;
border: 1px solid rgb(226 232 240);
+7 -4
View File
@@ -89,9 +89,12 @@ const resolveChatAgent = async () => {
}
};
const openInChat = (taskNo: string) => {
const openInChat = (taskNo: string, conversationId?: string | null) => {
if (!chatAgentId.value) return;
router.push({ path: `/chat/${chatAgentId.value}`, query: { task_id: taskNo } });
const query: Record<string, string> = { task_id: taskNo };
const cid = String(conversationId || '').trim();
if (cid) query.conversation_id = cid;
router.push({ path: `/chat/${chatAgentId.value}`, query });
};
const downloadExport = async (taskNo: string) => {
@@ -207,7 +210,7 @@ onMounted(async () => {
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.task_no)"
@click="openInChat(detail.task_no, detail.conversation_id)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
@@ -241,7 +244,7 @@ onMounted(async () => {
<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.columns.sku') }}</th>
<th class="px-3 py-2">{{ $t('workspace.shippingNotice.qty') }}</th>
</tr>
</thead>