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:
1 parent
2ce5256483
commit
c18c0394d0
50 files changed
+6088
-2407
No files matched your search
+14
-1
@@ -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 = {
|
||||
|
||||
@@ -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()))
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
Reference in new issue
Block a user