feat(shipping-notice): 支持发货通知解析延后至 Dify 画布,优化任务创建流程

This commit is contained in:
hugo committed 2026-06-22 16:59:38 +08:00
1 parent d46d61bfa1
commit 70e8f700ff
38 files changed
+3215 -714

No files matched your search

+12 -4
View File
@@ -1065,6 +1065,8 @@ def chat_completions():
query = data.get('query')
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
@@ -1194,14 +1196,13 @@ def chat_completions():
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
is_shipping_notice_chat_agent,
)
declares_file_check = agent_declares_file_check_progress(agent_proxy)
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_shipping_dify_chat_inputs()
elif declares_file_check or is_file_check_agent:
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
if declares_file_check or is_file_check_agent:
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
if is_file_check_agent:
@@ -1215,6 +1216,13 @@ def chat_completions():
agent_id=agent_proxy.id,
query=query,
)
elif is_shipping_agent:
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
dify_inputs = build_shipping_notice_dify_inputs(
external_conversation_id or session.session_id,
task_id=shipping_task_id,
batch_no=shipping_batch_no,
)
generator = DifyService.stream_chat(
query,
user_proxy.id,
+8 -7
View File
@@ -36,22 +36,23 @@ def _require_tool_auth() -> None:
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:读取配置中的 `SHIPPING_NOTICE_TOOL_API_KEY`,并校验 `Authorization: Bearer <token>` 或
`X-Shipping-Tool-Key` 是否命中;未配置时报服务不可用,缺失或错误时报未授权。
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
未配置时报服务不可用,缺失或错误时报未授权。
"""
configured = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError(
"SHIPPING_NOTICE_TOOL_API_KEY is not configured",
"INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
shipping_key = str(request.headers.get("X-Shipping-Tool-Key") or "").strip()
if configured in {token, shipping_key}:
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not shipping_key:
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
+34 -9
View File
@@ -121,8 +121,22 @@ def workspace_create_shipping_batch_from_notices():
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
# 用户态上传通知后仅完成抽文、建批/建任务与 raw_text 落库;
# 首轮订单需求解析由 Dify 画布读取 raw_text 后调用 parse_notice(structured=...)。
"defer_parse": True,
}
return jsonify(shipping_tools.create_batch_tasks(payload))
created = shipping_tools.create_batch_tasks(payload)
data = created.get("data") if isinstance(created, dict) else None
batch_data = data.get("batch") if isinstance(data, dict) else None
tasks_data = data.get("tasks") if isinstance(data, dict) else None
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
if isinstance(data, dict) and batch_no:
focus_task = get_focus_task_for_batch(batch_no, user.id)
if focus_task:
data["focus_task"] = serialize_task_summary(focus_task)
if isinstance(tasks_data, list):
data["tasks"] = tasks_data
return jsonify(created)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
@@ -222,7 +236,7 @@ def workspace_create_shipping_task():
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并立即触发解析。"""
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,解析延后到 Dify。"""
user, err = _require_user()
if err:
return err
@@ -277,13 +291,24 @@ def workspace_create_shipping_task_from_notice():
task.raw_content = text
db.session.commit()
payload = {"task_id": task_id}
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 "", **meta}
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
return jsonify(parsed)
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.source_file_name = str(upload.filename or "").strip() or task.source_file_name
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() or task.source_file_type
db.session.commit()
return jsonify(
{
"status": "ok",
"task_id": task_id,
"message": f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,等待 Dify 继续解析。",
"data": {
"task": serialize_task_summary(task) if task else {"task_no": task_id},
"notice_upload": {"filename": upload.filename or "", **meta},
"parse_status": "deferred",
},
}
)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
+2
View File
@@ -121,6 +121,8 @@ class Config:
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
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 = (
@@ -1,21 +1,20 @@
"""
services/shipping_notice/dify_inputs.py
用途:构建发货通知 Dify Chatflow 需要的输入变量,如 Tool API Base URL 和 Tool API Key。
依赖:agent_resolver、tool_api_url、Flask current_app 配置。
逻辑:由聊天 Agent 入口或 Dify 调用准备逻辑引用本文件,把环境相关变量注入到 Dify 请求上下文。
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
依赖:agent_resolver、models.ShippingBatch/ShippingTask。
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
把 Dify 画布需要的 conversation_id、current_batch_no、current_task_no 注入 Start 节点变量。
"""
from __future__ import annotations
from flask import current_app
from app.models import ShippingBatch, ShippingTask
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_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
SHIPPING_CONVERSATION_ID_INPUT = "conversation_id"
SHIPPING_CURRENT_BATCH_NO_INPUT = "current_batch_no"
SHIPPING_CURRENT_TASK_NO_INPUT = "current_task_no"
def is_shipping_notice_chat_agent(agent) -> bool:
@@ -23,14 +22,72 @@ def is_shipping_notice_chat_agent(agent) -> bool:
return getattr(agent, "name", None) == CHAT_AGENT_NAME
def build_dify_chat_inputs() -> dict[str, str]:
"""构建 Dify Chatflow 输入变量(Tool API Base URL 与 API Key)。"""
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_TOOLS_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
return inputs
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
"""按会话号获取最近一个发货批次,用于恢复当前批次焦点。"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return None
return (
ShippingBatch.query.filter_by(conversation_id=conv_id)
.order_by(ShippingBatch.id.desc())
.first()
)
def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
"""按会话号获取最近一个未拒绝任务,用于恢复当前任务焦点。"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return None
return (
ShippingTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingTask.process_status.notin_(["rejected"]))
.order_by(ShippingTask.id.desc())
.first()
)
def build_dify_chat_inputs(
conversation_id: str | None = None,
*,
task_id: str | None = None,
batch_no: str | None = None,
) -> dict[str, str]:
"""
构建发货通知 Dify Chatflow inputs。
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布稳定读取当前 task/batch。
"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return {}
explicit_task_no = str(task_id or "").strip().upper()
explicit_batch_no = str(batch_no or "").strip().upper()
batch = _latest_batch_for_conversation(conv_id)
task = _latest_task_for_conversation(conv_id)
current_task_no = explicit_task_no
if not current_task_no and batch and batch.current_focus_task_no:
current_task_no = str(batch.current_focus_task_no or "").strip().upper()
elif not current_task_no and task and task.task_no:
current_task_no = str(task.task_no or "").strip().upper()
current_batch_no = explicit_batch_no
if not current_batch_no and batch and batch.batch_no:
current_batch_no = str(batch.batch_no or "").strip().upper()
elif (
not current_batch_no
and task
and getattr(task, "batch", None) is not None
and getattr(task.batch, "batch_no", None)
):
current_batch_no = str(task.batch.batch_no or "").strip().upper()
return {
SHIPPING_CONVERSATION_ID_INPUT: conv_id,
SHIPPING_CURRENT_BATCH_NO_INPUT: current_batch_no,
SHIPPING_CURRENT_TASK_NO_INPUT: current_task_no,
}
@@ -3,7 +3,7 @@ services/shipping_notice/extract.py
用途:抽取发货通知中的单头字段与订单行,并在收尾阶段补充文档级字段和告警。
依赖:po_number、reservation_id、notice_lines 中的标准化与回填工具。
逻辑:由 task_workflow.parse_notice 调用本文件完成原始文本解析,再把结果交给 parse_summary 和状态机链路。
逻辑:由 task_workflow.parse_notice 调用;优先 Dify 传入的 structured,无则走后端启发式规则兜底。
"""
from __future__ import annotations
@@ -29,11 +29,14 @@ def _finalize_notice_parse(
base_confidence: float,
raw_text: str = "",
) -> tuple[dict[str, Any], float, list[str]]:
parse_source = parsed.get("parse_source")
lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else [])
parsed = enrich_notice_with_document_reservation({**parsed, "lines": lines}, raw_text=raw_text)
parsed = enrich_notice_with_document_required_date(parsed)
parsed = enrich_notice_with_document_currency(parsed)
parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text)
if parse_source:
parsed["parse_source"] = parse_source
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
warnings = validate_notice_lines(lines)
from app.services.shipping_notice.notice_lines import notice_parse_completeness
@@ -52,12 +55,16 @@ def extract_notice_fields(
) -> tuple[dict[str, Any], float, list[str]]:
"""
抽取发货通知单头与订单行,并计算置信度与 warnings。
【AI 触发时机】:由 parse_notice 内部调用;Agent 应调 parse_notice 而非直接调用本函数。
【AI 触发时机】:由 parse_notice Tool 调用;Dify 画布/Agent 应先用 LLM 产出 structured 再传入,勿依赖本函数做 LLM 抽取。
解析优先级:
1. structured:Dify LLM/画布已抽取并传入 parse_notice
2. 后端启发式规则(_heuristic_extract,仅作 Dify 无法实现时的兜底)
Args:
raw_text: 发货通知正文。
source_type: 来源类型(manual/pdf/email 等)。
structured: Dify/上游已结构化的解析结果(优先使用)。
structured: Dify 编排产出的结构化解析结果(最高优先级)。
notice_files: 附件元数据列表(预留)。
Returns:
@@ -66,15 +73,22 @@ def extract_notice_fields(
warnings: list[str] = []
if structured and isinstance(structured, dict):
return _finalize_notice_parse(
structured,
payload = {**structured, "parse_source": structured.get("parse_source") or "dify"}
parsed, confidence, line_warnings = _finalize_notice_parse(
payload,
base_confidence=float(structured.get("confidence") or 0.95),
raw_text=str(structured.get("raw_text") or ""),
raw_text=str(structured.get("raw_text") or raw_text),
)
warnings.extend(line_warnings)
return parsed, confidence, warnings
warnings.append("parse_fallback_heuristic")
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
warnings.extend(heuristic_warnings)
return _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
heuristic["parse_source"] = "heuristic"
parsed, confidence, line_warnings = _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
warnings.extend(line_warnings)
return parsed, confidence, warnings
def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]:
@@ -37,7 +37,7 @@ from app.services.shipping_notice.rpa_attempts import (
upload_rpa_attempts,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import prepend_tool_message
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -214,10 +214,23 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if lang:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
notice_lines = task.lines_json or []
total_notice_lines = len(notice_lines) if isinstance(notice_lines, list) else 0
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="正在执行库存匹配",
progress_percent=10,
current=0,
total=total_notice_lines or None,
detail="按 SKU + Reservation ID 逐行比对需求与库存",
)
db.session.flush()
# [STEP 2] 校验 Reservation ID 前置条件。
# 当前匹配规则要求订单侧必须具备 Reservation ID,缺失时要先打回上游解析而不是继续匹配。
notice_lines = task.lines_json or []
order_missing = [
{"sku": str(line.get("sku") or "").strip(), "reservation_id": str(line.get("reservation_id") or "").strip()}
for line in (notice_lines if isinstance(notice_lines, list) else [])
@@ -254,15 +267,47 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 3] 执行匹配并按结果分流。
# fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。
def _on_match_progress(processed: int, total: int) -> None:
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="正在执行库存匹配",
progress_percent=percent,
current=processed,
total=total,
detail=f"已匹配 {processed}/{total} 行",
)
if processed == total or processed % 50 == 0:
db.session.flush()
match_status, line_results, shortage = match_notice_lines(
notice_lines,
task.inventory_lines_json or [],
progress_callback=_on_match_progress,
)
if inv_missing_count and isinstance(shortage, dict):
shortage.pop("warnings", None)
task.match_status = match_status
task.line_results_json = line_results
task.shortage_json = shortage
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="needs_human" if match_status != "fulfillable" else "completed",
message="库存匹配已完成",
progress_percent=100,
current=len(line_results),
total=len(line_results),
detail=(
f"已匹配 {len(line_results)}/{len(line_results)} 行,全部订单行库存满足"
if match_status == "fulfillable"
else f"已匹配 {len(line_results)}/{len(line_results)} 行,存在缺口,需人工处理"
),
)
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() or None
match_summary = format_match_summary(
@@ -324,6 +369,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["upload_to_freight"],
next_required_action="match_inventory(须先完成库存上传与字段对齐确认)",
)
set_task_step_progress(
task,
step_key="step6_generate_file",
step_title="生成发货文件",
status="running",
message="正在生成发货 Excel",
progress_percent=60,
detail="正在按货代模板填充全部应发行",
)
# [STEP 2] 生成文件并把任务推进到等待上传阶段。
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
@@ -331,6 +385,15 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
task.export_file_path = path
task.export_file_name = filename
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
set_task_step_progress(
task,
step_key="step6_generate_file",
step_title="生成发货文件",
status="completed",
message="发货 Excel 已生成",
progress_percent=100,
detail=filename,
)
log_task_event(task, "export_generated", {"file_name": filename})
db.session.commit()
return tool_response(
@@ -380,6 +443,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
human_options=[],
)
apply_task_transition(task, TaskTransition.UPLOADED)
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message="已确认手工上传货代完成",
progress_percent=100,
detail="任务已完成",
)
ref = str(payload.get("freight_ref_no") or "").strip()
if ref:
task.freight_ref_no = ref
@@ -461,6 +533,18 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if queued and trigger:
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
attempt_no = attempts + 1
task.upload_started_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="running",
message="已触发 RPA 上传货代,等待回执",
progress_percent=65,
current=attempt_no,
total=max_attempts,
detail=f"第 {attempt_no}/{max_attempts} 次上传尝试",
)
log_task_event(
task,
"upload_rpa_triggered",
@@ -488,6 +572,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message="RPA 自动上传失败,请人工接管",
progress_percent=100,
detail="请下载 Excel 手工上传后确认完成",
)
task.error_message = "RPA 上传目录未配置或触发失败"
log_task_event(task, "upload_rpa_pending", {})
db.session.commit()
@@ -519,6 +612,16 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
success = bool(payload.get("success", True))
if success:
apply_task_transition(task, TaskTransition.UPLOADED)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message="RPA 已成功上传货代系统",
progress_percent=100,
detail="任务已完成",
)
task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None
log_task_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no})
db.session.commit()
@@ -533,6 +636,16 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message="货代上传失败,等待人工处理",
progress_percent=100,
detail="可重试上传或改为手工上传",
)
task.error_message = str(payload.get("error_message") or "RPA upload failed")[:500]
log_task_event(task, "upload_rpa_failed", {"error": task.error_message})
db.session.flush()
@@ -27,6 +27,7 @@ from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
log_task_event,
payload_wants_auto_chain_fallback,
set_task_step_progress,
)
from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.constants import RS_ALIGN_REVIEW
@@ -143,6 +144,19 @@ def inventory_mapping_checkpoint_response(
"field_alignment": field_alignment,
**extra,
}
set_task_step_progress(
task,
step_key="step4_align_confirm",
step_title="确认字段对齐",
status="needs_human",
message="请确认库存字段对齐后再继续匹配",
progress_percent=100,
current=3,
total=3,
detail="系统已识别必填列映射,请先人工确认",
extra={"field_alignment": field_alignment},
)
db.session.flush()
# [STEP 2] 明确停在人审检查点。
# 返回值必须阻止同轮继续调用 match_inventory,确保用户先确认字段对齐。
return tool_response(
@@ -253,6 +267,17 @@ def inventory_loaded_response(
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
task.inventory_lines_json = inventory_lines
field_alignment = field_alignment_for_task(task, column_meta)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running" if require_mapping_review else "completed",
message=f"已载入库存 {len(inventory_lines)} 行",
progress_percent=100,
current=len(inventory_lines),
total=len(inventory_lines),
detail="库存快照已就绪,正在进入字段对齐阶段" if require_mapping_review else "库存快照已就绪,可进入匹配阶段",
)
# [STEP 2] 如果当前策略要求映射复核,则先进入对齐确认检查点。
# 同时尝试自动串联;只有自动串联没有吃掉结果时,才真正返回给用户确认映射。
@@ -30,7 +30,11 @@ from app.services.shipping_notice.rpa_attempts import (
max_rpa_inventory_attempts,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event, rpa_inventory_timeout_seconds
from app.services.shipping_notice.tool_common import (
log_task_event,
rpa_inventory_timeout_seconds,
set_task_step_progress,
)
from app.services.shipping_notice.tool_response import tool_response
@@ -136,6 +140,17 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="已触发 RPA 库存导出,等待结果",
progress_percent=60,
current=attempt_no,
total=max_attempts,
detail=f"第 {attempt_no}/{max_attempts} 次尝试",
)
log_task_event(task, "inventory_rpa_triggered", {"trigger": trigger, "attempt": attempt_no})
if attempt_no >= max_attempts and not task.inventory_lines_json:
@@ -225,6 +240,15 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
processed = inventory_processed_dir()
lines, column_meta = ingest_inventory_file(path, move_to=processed)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="RPA 库存文件已返回,正在读取库存快照",
progress_percent=85,
detail=f"正在读取 {path.name}",
)
return inventory_loaded_response(
task,
lines,
@@ -49,7 +49,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_for_tool,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -385,6 +385,16 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
)
try:
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="正在上传并解析库存文件",
progress_percent=35,
detail=f"正在处理库存文件 {filename}",
)
db.session.flush()
save_task_inventory_upload(task.task_no, upload)
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
@@ -8,7 +8,7 @@ services/shipping_notice/match.py
from __future__ import annotations
from typing import Any
from typing import Any, Callable
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import extract_reservation_id
@@ -60,6 +60,8 @@ def _available_for_notice_line(
def match_notice_lines(
notice_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
*,
progress_callback: Callable[[int, int], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
"""
将订单行与库存行按 (sku, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。
@@ -78,7 +80,8 @@ def match_notice_lines(
has_shortage = False
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
for line in notice_lines:
total_lines = len(notice_lines)
for index, line in enumerate(notice_lines, start=1):
sku = _norm(line.get("sku"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
try:
@@ -110,6 +113,8 @@ def match_notice_lines(
line_results.append(result)
if shortage > 0:
shortages.append(result)
if progress_callback is not None:
progress_callback(index, total_lines)
# [STEP 3] 汇总整体 match_status(fulfillable / partial / unfulfillable)。
if not notice_lines:
@@ -79,7 +79,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。",
},
"servers": [{"url": server}],
"paths": {
@@ -127,11 +127,22 @@ def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
completed = sum(1 for item in tasks if item.process_status in {"uploaded", "completed", "closed"})
failed = sum(1 for item in tasks if item.process_status in {"rejected"} or item.upload_status == "failed")
running = sum(1 for item in tasks if item.process_status not in {"uploaded", "completed", "closed", "rejected"})
pending = sum(1 for item in tasks if item.process_status in {"created", "pending_review"} or not item.current_step)
focus = next(
(
item for item in sort_batch_tasks(tasks)
if item.process_status not in {"uploaded", "completed", "closed", "rejected"}
),
None,
)
return {
"total": total,
"completed": completed,
"failed": failed,
"running": running,
"pending": pending,
"current_index": int(focus.batch_index or 0) if focus else (total if total else 0),
"current_task_no": focus.task_no if focus else None,
}
@@ -171,9 +182,12 @@ def resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None:
def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"""Tool data 基础字段(裁剪前)。"""
return {
from app.services.shipping_notice.notice_upload import max_notice_chars
payload: dict[str, Any] = {
"task_no": task.task_no,
"process_status": task.process_status,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
"pending_human_reason": task.pending_human_reason,
@@ -189,7 +203,17 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"freight_ref_no": task.freight_ref_no,
"error_message": task.error_message,
"conversation_id": task.conversation_id,
"step_payload": task.step_payload_json or {},
}
raw_content = str(task.raw_content or "").strip()
lines = task.lines_json or []
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
if raw_content and (not lines or str(task.process_status or "").strip().lower() == "created"):
limit = max_notice_chars()
payload["raw_text"] = raw_content[:limit] if len(raw_content) > limit else raw_content
if len(raw_content) > limit:
payload["raw_text_truncated"] = True
return payload
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
@@ -12,6 +12,8 @@ import uuid
from datetime import datetime
from typing import Any
from flask import current_app
from app import db
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
@@ -41,8 +43,11 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
defer_parse_to_dify_enabled,
generate_task_no,
log_task_event,
set_task_step_progress,
)
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
@@ -105,12 +110,23 @@ def create_batch(payload: dict[str, Any]) -> ShippingBatch:
return batch
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
"""判断是否将 parse_notice 延后到 Dify 画布(有 structured 或显式 auto_parse 时不延后)。"""
if isinstance(item.get("structured"), dict) and item.get("structured"):
return False
if payload.get("auto_parse") is True:
return False
if payload.get("defer_parse") is False:
return False
return defer_parse_to_dify_enabled()
def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
"""
一次创建批次,并为每个 notice_item 创建任务后立即触发解析。
一次创建批次,并为每个 notice_item 创建任务;默认将字段解析延后到 Dify 画布。
【AI 触发时机】:当用户批量上传多份发货通知附件,希望系统自动拆成多个任务时调用。
核心逻辑:先创建批次,再逐个创建任务、透传 notice 原文到 `parse_notice`,最后回写批次汇总。
核心逻辑:先创建批次,再逐个创建任务;若 notice_item 已带 structured 或 auto_parse=true 则立即 parse_notice,否则仅保存 raw_text 待 Dify 续办。
Args:
payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据。
@@ -164,6 +180,20 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
warnings = item.get("warnings")
if isinstance(warnings, list):
parse_payload["warnings"] = warnings
if _should_defer_notice_parse(payload, item):
log_task_event(
task,
"parse_deferred_to_dify",
{"batch_no": batch.batch_no, "reason": "SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"},
)
created_tasks.append(
{
"task_id": task.task_no,
"batch_index": idx,
"parse_status": "deferred",
}
)
continue
parse_result = parse_notice(parse_payload)
created_tasks.append(
{
@@ -312,6 +342,17 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
if conv_id and not task.conversation_id:
task.conversation_id = conv_id
set_task_step_progress(
task,
step_key="step1_notice_submit",
step_title="提交通知",
status="running",
message="正在解析发货通知",
progress_percent=20,
detail="正在抽取单头、订单行与关键字段",
)
db.session.flush()
# [STEP 2] 提取单头、订单行与置信度,回写任务字段。
raw_text = str(payload.get("raw_text") or task.raw_content or "").strip()
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
@@ -342,6 +383,18 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
task.required_date = required_date or None
task.lines_json = lines
task.parse_confidence = confidence
set_task_step_progress(
task,
step_key="step2_parse_confirm",
step_title="确认解析",
status="needs_human" if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) else "completed",
message="发货通知解析已完成",
progress_percent=100,
current=len(lines),
total=len(lines),
detail=f"已识别 {len(lines)} 行订单,解析置信度 {confidence:.2f}",
extra={"warnings": warnings},
)
summary_kwargs = {
"task_no": task.task_no,
@@ -64,6 +64,11 @@ def auto_mapping_allow_llm() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM", False)
def defer_parse_to_dify_enabled() -> bool:
"""建单后是否延后 parse_notice,交由 Dify 画布完成 LLM 抽取与落库。"""
return cfg_bool("SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY", True)
def auto_match_enabled() -> bool:
"""auto_progress 是否自动调用 match_inventory。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
@@ -123,6 +128,49 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
return {**result, "message": f"{note}\n\n{body}" if body else note}
def set_task_step_progress(
task: ShippingTask,
*,
step_key: str,
step_title: str,
status: str,
message: str,
progress_percent: int | None = None,
current: int | None = None,
total: int | None = None,
detail: str | None = None,
extra: dict[str, Any] | None = None,
) -> None:
"""写入任务当前步骤与步骤内细粒度进度,统一落到 current_step + step_payload_json。"""
payload = dict(task.step_payload_json or {})
progress: dict[str, Any] = {
"step_key": step_key,
"step_title": step_title,
"status": status,
"message": str(message or "").strip(),
}
if progress_percent is not None:
progress["progress_percent"] = max(0, min(int(progress_percent), 100))
if current is not None:
progress["current"] = int(current)
if total is not None:
progress["total"] = int(total)
if detail:
progress["detail"] = str(detail).strip()
if extra:
progress["extra"] = extra
payload["current_step_progress"] = progress
task.current_step = step_key
task.step_payload_json = payload
def clear_task_step_progress(task: ShippingTask) -> None:
"""清空任务步骤内进度,保留其他 step_payload_json 字段。"""
payload = dict(task.step_payload_json or {})
payload.pop("current_step_progress", None)
task.step_payload_json = payload or None
@@ -0,0 +1,112 @@
"""align shipping_tasks schema drift
Revision ID: e2f4a6b8c0d1
Revises: c5d6e7f8a9b0
Create Date: 2026-06-22 09:10:00.000000
用途:一次性修复 shipping_tasks 在部分 PostgreSQL 环境里的 schema 漂移,使其与当前 ShippingTask 模型保持一致。
依赖:Alembic op / SQLAlchemy inspect;与 ShippingTask 模型、既有建单/编辑逻辑保持一致。
逻辑:upgrade 恢复 upload_status/upload_mode 的可空语义,并对齐 source_file_type 长度、export_version 默认值;downgrade 提供对称回滚。
"""
from alembic import op
import sqlalchemy as sa
revision = "e2f4a6b8c0d1"
down_revision = "c5d6e7f8a9b0"
branch_labels = None
depends_on = None
def _table_columns(insp, table_name: str) -> set[str]:
if table_name not in set(insp.get_table_names()):
return set()
return {col["name"] for col in insp.get_columns(table_name)}
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
# [STEP 1] 恢复上传相关字段的可空语义,与模型/状态机现状保持一致。
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=True,
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=True,
)
# [STEP 2] 对齐字段长度与默认值,避免模型/数据库继续出现隐性分叉。
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="1",
existing_nullable=False,
)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
# [STEP 1] 先回滚长度与默认值,恢复升级前的库侧行为。
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="0",
existing_nullable=False,
)
# [STEP 2] 回滚为 NOT NULL 前先补齐现存 NULL,避免约束恢复时失败。
if "upload_status" in columns:
op.execute("UPDATE shipping_tasks SET upload_status = '' WHERE upload_status IS NULL")
if "upload_mode" in columns:
op.execute("UPDATE shipping_tasks SET upload_mode = '' WHERE upload_mode IS NULL")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=False,
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=False,
)
@@ -0,0 +1,108 @@
"""apply shipping_tasks schema alignment
Revision ID: f1e2d3c4b5a6
Revises: e2f4a6b8c0d1
Create Date: 2026-06-22 09:45:00.000000
用途:将已处于 e2f4a6b8c0d1 版本、但未实际应用 shipping_tasks 字段对齐的数据库补齐到目标结构。
依赖:Alembic op / SQLAlchemy inspect;用于修复已执行 revision 文件被后改导致的实际库结构未变问题。
逻辑:upgrade 真正落地 upload_mode/upload_status/source_file_type/export_version 的对齐;downgrade 回退到当前本地库观测到的旧结构。
"""
from alembic import op
import sqlalchemy as sa
revision = "f1e2d3c4b5a6"
down_revision = "e2f4a6b8c0d1"
branch_labels = None
depends_on = None
def _table_columns(insp, table_name: str) -> set[str]:
if table_name not in set(insp.get_table_names()):
return set()
return {col["name"] for col in insp.get_columns(table_name)}
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=True,
server_default=None,
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=True,
server_default=None,
)
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="1",
existing_nullable=False,
)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
if "upload_mode" in columns:
op.execute("UPDATE shipping_tasks SET upload_mode = 'auto' WHERE upload_mode IS NULL")
if "upload_status" in columns:
op.execute("UPDATE shipping_tasks SET upload_status = 'not_started' WHERE upload_status IS NULL")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=True,
server_default="not_started",
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=False,
server_default="auto",
)
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="0",
existing_nullable=False,
)
+80 -4
View File
@@ -4,20 +4,42 @@
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
2. get_batch_status 返回 focus task 与任务列表。
3. switch_focus_task 可在同批次内切换当前任务。
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
"""
from app.models import ShippingBatch, ShippingTask
from app import db
from app.models import ShippingBatch, ShippingTask, User
from app.auth_jwt import issue_local_access_token
def _tool_headers():
def _tool_headers(app):
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def _workspace_headers(app):
with app.app_context():
user = User(
username="shipping_workspace_user",
email="shipping_workspace_user@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
"Authorization": f"Bearer {token}",
}
def test_create_batch_tasks_and_switch_focus(app, client):
"""验证 batch 建单、状态查询、focus task 切换主流程。"""
headers = _tool_headers()
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
@@ -93,9 +115,63 @@ def test_create_batch_tasks_and_switch_focus(app, client):
assert task_rows[1].batch_total == 2
def test_create_batch_defers_parse_without_structured(app, client):
"""默认将 parse_notice 延后到 Dify,仅保存 raw_text。"""
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"notice_items": [
{
"source_file_name": "notice-a.txt",
"raw_text": "客户:ACME 料号A001 x 10",
},
],
},
)
assert res.status_code == 200
data = res.get_json()
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.raw_content
assert not (task.lines_json or [])
def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
"""聊天/工作台批量上传通知时应仅落 raw_text,首轮解析延后到 Dify。"""
headers = _workspace_headers(app)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (__import__("io").BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-001",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["batch_no"].startswith("SB-")
assert data["data"]["batch"]["batch_no"] == data["batch_no"]
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
assert data["data"]["focus_task"]["task_no"] == data["data"]["tasks"][0]["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.raw_content
assert task.process_status == "created"
assert len(task.lines_json or []) == 0
def test_create_empty_batch_returns_batch_shell(app, client):
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
headers = _tool_headers()
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/create_batch",
+27 -1
View File
@@ -1,4 +1,4 @@
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.notice_lines import (
normalize_notice_line,
parse_notice_table_rows,
@@ -179,3 +179,29 @@ AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
assert parsed["lines"][0]["unit_price"] == 5
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.5
def test_extract_notice_fields_structured_over_heuristic():
"""Dify 传入 structured 时应直接使用,不走启发式。"""
structured = {
"customer_name": "ACME",
"lines": [{"sku": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"confidence": 0.95,
}
parsed, confidence, warnings = extract_notice_fields(
raw_text="ignored SKU x 99",
structured=structured,
)
assert parsed["parse_source"] == "dify"
assert parsed["lines"][0]["sku"] == "SKU-DIFY"
assert confidence > 0.8
assert "parse_fallback_heuristic" not in warnings
def test_extract_notice_fields_heuristic_fallback():
"""无 structured 时走后端启发式兜底。"""
text = "AWS Sku\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
parsed, _, warnings = extract_notice_fields(raw_text=text)
assert parsed["parse_source"] == "heuristic"
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert "parse_fallback_heuristic" in warnings
@@ -2,14 +2,38 @@ import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
from app.services.shipping_notice.match import match_notice_lines
def _tool_headers(app):
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def test_match_notice_lines_reports_progress():
seen: list[tuple[int, int]] = []
status, line_results, shortage = match_notice_lines(
[
{"sku": "A001", "reservation_id": "R-1", "qty": 1},
{"sku": "A002", "reservation_id": "R-2", "qty": 2},
],
[
{"sku": "A001", "reservation_id": "R-1", "available_qty": 1},
{"sku": "A002", "reservation_id": "R-2", "available_qty": 2},
],
progress_callback=lambda current, total: seen.append((current, total)),
)
assert status == "fulfillable"
assert len(line_results) == 2
assert shortage["lines"] == []
assert seen == [(1, 2), (2, 2)]
def test_shipping_notice_tool_flow(app, client):
headers = _tool_headers(app)
+1 -1
View File
@@ -3,7 +3,7 @@
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。"
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。"
},
"servers": [
{
+2113 -591
View File
File diff suppressed because it is too large. Load diff
@@ -439,6 +439,7 @@ export type {
ShippingBatchSummary,
ShippingChatAction,
ShippingChatActionsResponse,
ShippingCurrentStepProgress,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingMatchLineResult,
@@ -15,7 +15,7 @@ import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
import type { ShippingTaskSummary } from '@/features/chat/types/shipping.api.types';
import type { ShippingCurrentStepProgress, ShippingTaskSummary } from '@/features/chat/types/shipping.api.types';
const page = useChatPageContext();
const { t } = useI18n();
@@ -38,6 +38,12 @@ const statusMeta = (status?: string | null) => {
const stepLabel = (step?: string | null) => {
const map: Record<string, string> = {
step1_notice_submit: t('chat.shippingNoticeUi.currentStep.noticeParse'),
step2_parse_confirm: t('chat.shippingNoticeUi.currentStep.parseConfirm'),
step3_inventory_prepare: t('chat.shippingNoticeUi.currentStep.inventoryPrepare'),
step4_align_confirm: t('chat.shippingNoticeUi.currentStep.alignConfirm'),
step5_match_inventory: t('chat.shippingNoticeUi.currentStep.inventoryMatch'),
step6_generate_file: t('chat.shippingNoticeUi.currentStep.generateExcel'),
step7_upload_freight: t('chat.shippingNoticeUi.currentStep.uploadFreight'),
step2_inventory_prepare: t('chat.shippingNoticeUi.currentStep.inventoryPrepare'),
step3_inventory_match: t('chat.shippingNoticeUi.currentStep.inventoryMatch'),
step4_shortage_review: t('chat.shippingNoticeUi.currentStep.shortageHandle'),
@@ -56,6 +62,12 @@ const currentShippingTask = computed<ShippingTaskSummary | null>(() => {
const currentShippingTaskSource = computed(() => currentShippingTask.value || page.activeShippingTaskDetail || null);
const currentShippingSteps = computed(() => buildShippingWorkflowSteps(currentShippingTaskSource.value));
const currentShippingStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
const payload = currentShippingTaskSource.value?.step_payload;
if (!payload || typeof payload !== 'object') return null;
const progress = (payload as Record<string, unknown>).current_step_progress;
return progress && typeof progress === 'object' ? progress as ShippingCurrentStepProgress : null;
});
const currentShippingBatchProgress = computed(() => {
const task = currentShippingTask.value;
if (!task?.batch_index || !task?.batch_total) return '';
@@ -67,9 +79,20 @@ const batchCompletedCount = computed(() =>
const batchRunningCount = computed(() =>
Number(page.shippingBatchSummary?.process_summary?.running || 0),
);
const batchPendingCount = computed(() =>
Number(page.shippingBatchSummary?.process_summary?.pending || 0),
);
const batchFileCount = computed(() =>
Number(page.shippingBatchSummary?.file_count || 0),
);
const batchCurrentIndex = computed(() =>
Number(
currentShippingTask.value?.batch_index
|| page.activeShippingTaskDetail?.batch_index
|| page.shippingBatchSummary?.process_summary?.current_index
|| 0,
),
);
const batchCompletionPercent = computed(() => {
if (!batchFileCount.value) return 0;
return Math.min(100, Math.max(0, Math.round((batchCompletedCount.value / batchFileCount.value) * 100)));
@@ -175,6 +198,12 @@ const batchCompletionPercent = computed(() => {
>
{{ currentShippingBatchProgress }}
</span>
<span
v-if="batchCurrentIndex"
class="rounded-full bg-amber-50 px-2.5 py-1 text-xs font-medium text-amber-700"
>
{{ t('chat.shippingNoticeUi.batchCurrentIndex', { index: batchCurrentIndex, total: batchFileCount }) }}
</span>
</div>
<div v-if="currentShippingTaskSource" class="flex flex-wrap items-center gap-2 text-xs text-secondary">
<span class="truncate font-medium text-primary">
@@ -194,6 +223,40 @@ const batchCompletionPercent = computed(() => {
compact
class="pt-2"
/>
<div
v-if="currentShippingStepProgress"
class="mt-3 rounded-2xl border border-default/80 bg-surface/80 px-3 py-3"
>
<div class="flex items-center justify-between gap-3 text-xs">
<div class="font-medium text-primary">
{{ currentShippingStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
</div>
<div class="text-muted">
{{ currentShippingStepProgress.progress_percent ?? 0 }}%
</div>
</div>
<div class="mt-1 text-sm text-secondary">
{{ currentShippingStepProgress.message || t('chat.shippingNoticeUi.processing') }}
</div>
<div
v-if="currentShippingStepProgress.detail"
class="mt-1 text-xs text-muted"
>
{{ currentShippingStepProgress.detail }}
</div>
<div
v-if="currentShippingStepProgress.current && currentShippingStepProgress.total"
class="mt-1 text-xs text-muted"
>
{{ t('chat.shippingNoticeUi.stepDetail.counter', { current: currentShippingStepProgress.current, total: currentShippingStepProgress.total }) }}
</div>
<div class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-sky-500 transition-all"
:style="{ width: `${currentShippingStepProgress.progress_percent ?? 0}%` }"
/>
</div>
</div>
<div class="flex flex-wrap gap-2 pt-1 text-xs">
<button
v-if="page.shippingBatchSummary"
@@ -221,7 +284,7 @@ const batchCompletionPercent = computed(() => {
</button>
</div>
</div>
<div v-if="page.shippingBatchSummary" class="grid grid-cols-3 gap-2 text-right text-xs">
<div v-if="page.shippingBatchSummary" class="grid grid-cols-4 gap-2 text-right text-xs">
<div class="rounded-2xl bg-surface px-3 py-2">
<div class="text-muted">{{ t('chat.shippingNoticeUi.fileCount') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ batchFileCount }}</div>
@@ -234,6 +297,10 @@ const batchCompletionPercent = computed(() => {
<div class="text-muted">{{ t('chat.shippingNoticeUi.completedCount') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ batchCompletedCount }}</div>
</div>
<div class="rounded-2xl bg-surface px-3 py-2">
<div class="text-muted">{{ t('chat.shippingNoticeUi.pendingCount') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ batchPendingCount }}</div>
</div>
</div>
</div>
<div
@@ -83,6 +83,10 @@ const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) =>
if (Number.isInteger(data.chat_log_id)) {
msg.chat_log_id = Number(data.chat_log_id);
}
const runId = Number(data.run_id);
if (Number.isFinite(runId) && runId > 0) {
msg.run_id = runId;
}
if (typeof data.type === 'string' && data.type.trim()) {
msg.type = data.type as ChatMessage['type'];
}
@@ -177,6 +181,7 @@ export function useChat() {
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
context?: { task_id?: string; batch_no?: string },
) => {
const runViewId = viewId.value;
const runMessages = messages.value;
@@ -195,17 +200,20 @@ export function useChat() {
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: query });
let botMsgIndex: number | null = null;
let botMsgRef: ChatMessage | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
if (!botMsgRef) {
botMsgRef = {
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: [],
}) - 1;
};
runMessages.push(botMsgRef);
}
return runMessages[botMsgIndex] || null;
return botMsgRef;
};
isThinking.value = true;
@@ -220,6 +228,8 @@ export function useChat() {
conversation_id: conversationId.value,
kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
}),
});
@@ -253,6 +263,16 @@ export function useChat() {
if (!payload) continue;
try {
const eventMatch = payload.match(/"event"\s*:\s*"([^"]+)"/);
const fastEventName = eventMatch?.[1] || '';
if (
fastEventName === 'workflow_started'
|| fastEventName === 'node_started'
|| fastEventName === 'node_finished'
|| fastEventName === 'chat_perf'
) {
continue;
}
const data = JSON.parse(payload) as Record<string, unknown>;
if (data?.conversation_id) {
@@ -267,40 +287,13 @@ export function useChat() {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
if (botMsgRef) {
applyEventMetadata(botMsgRef, data);
}
} else if (eventName === 'chat_perf') {
const perf = (data.perf || {}) as Record<string, unknown>;
const nodes = Array.isArray(perf.nodes) ? perf.nodes : [];
// eslint-disable-next-line no-console
console.groupCollapsed(
`[chat-perf] request=${String(perf.request_id || '')} total=${String(perf.total_ms ?? '')}ms ttft=${String(perf.ttft_ms ?? '')}ms`,
);
if (nodes.length > 0) {
// eslint-disable-next-line no-console
console.table(
nodes.map((node) => {
const item = node as Record<string, unknown>;
return {
index: item.index,
title: item.title,
type: item.node_type,
elapsed_ms: item.elapsed_ms,
at_ms: item.at_ms,
status: item.status,
};
}),
);
} else {
// eslint-disable-next-line no-console
console.log(perf);
}
// eslint-disable-next-line no-console
console.groupEnd();
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
hasTerminalEvent = true;
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
if (relay.total_relay_ms != null) {
// eslint-disable-next-line no-console
@@ -310,30 +303,19 @@ export function useChat() {
}
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) currentBotMsg.chat_log_id = Number(data.chat_log_id);
}
if (botMsgIndex !== null) {
const runId = Number(data.run_id);
if (Number.isFinite(runId) && runId > 0) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) currentBotMsg.run_id = runId;
}
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
hasAssistantContent = true;
if (data.replace_answer) {
botMsg.content = normalizedAnswer;
} else {
botMsg.content += normalizedAnswer;
}
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
if (botMsgRef) {
applyEventMetadata(botMsgRef, data);
}
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
@@ -345,12 +327,16 @@ export function useChat() {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
}
} catch {
// ignore malformed SSE frames
}
}
}
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
run.status = 'done';
}
} catch (e: unknown) {
run.status = 'error';
const botMsg = ensureBotMessage();
@@ -284,6 +284,7 @@ export function useChatPage() {
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
refreshHistoryAfterSend,
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
tryHandleLeaveSend: leave.tryHandleLeaveSend,
@@ -210,6 +210,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|| '';
const getCurrentShippingChatContext = () => ({
task_id: getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
});
const syncActiveShippingTaskDetail = async (taskId?: string) => {
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!normalized) {
@@ -483,6 +488,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingBatchTasks,
shippingBatchTasksExpanded,
activeShippingTaskDetail,
getCurrentShippingChatContext,
getActiveShippingBatchNo,
switchShippingFocusTask,
resumeShippingTaskFromQuery,
@@ -25,6 +25,7 @@ export interface ChatPageSendContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string },
) => Promise<void>;
refreshHistoryAfterSend: () => Promise<void>;
tryHandleShippingAttachmentAutoFlow: (
@@ -43,6 +44,7 @@ export interface ChatPageSendContext {
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
copiedIndex: Ref<number | null>;
getChatContext?: () => { task_id?: string; batch_no?: string };
}
export function createChatPageSendApi(ctx: ChatPageSendContext) {
@@ -90,7 +92,13 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
ctx.clearAttachments();
await ctx.prepareToolRunProgressBeforeSend();
await ctx.sendMessage(content, ctx.currentAgentId.value, ctx.selectedKb.value, files);
await ctx.sendMessage(
content,
ctx.currentAgentId.value,
ctx.selectedKb.value,
files,
ctx.getChatContext?.(),
);
await ctx.refreshHistoryAfterSend();
await ctx.refreshToolRunProgressAfterSend();
};
@@ -29,13 +29,37 @@ export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stepper.uploadFreight',
] as const;
const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
step1_notice_submit: 0,
step2_parse_confirm: 1,
step3_inventory_prepare: 2,
step2_inventory_prepare: 2,
step4_align_confirm: 3,
step5_match_inventory: 4,
step3_inventory_match: 4,
step4_shortage_review: 4,
step6_generate_file: 5,
step5_export_excel: 5,
step7_upload_freight: 6,
step6_upload_freight: 6,
step7_finish: 6,
};
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
const currentStep = String(task?.current_step || '').trim();
const processStatus = String(task?.process_status || '').trim();
const reviewStatus = String(task?.review_status || '').trim();
const pendingReason = String(task?.pending_human_reason || '').trim();
const matchStatus = String(task?.match_status || '').trim();
const hasExport = !!String(task?.export_file_name || '').trim();
if (currentStep) {
const currentStepIndex = CURRENT_STEP_INDEX_MAP[currentStep];
if (currentStepIndex !== undefined) {
return currentStepIndex;
}
}
if (processStatus === 'uploaded' || processStatus === 'closed') return 6;
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
if (processStatus === 'matched') return 4;
@@ -1,8 +1,8 @@
/**
* features/chat/shipping/shippingUploadPrompt.ts
* 用途:库存上传后发给 Dify 的提示语构建与附件类型分类。
* 用途:库存/通知上传后发给 Dify 的提示语构建与附件类型分类。
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;classifyShippingUploadFile 区分库存/通知附件。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。
*/
/**
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
@@ -29,6 +29,34 @@ export function buildShippingInventoryUploadPrompt(
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
}
/**
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发画布 LLM 抽取 + parse_notice)。
*/
export function buildShippingNoticeUploadPrompt(
result: Record<string, unknown> | null | undefined,
options?: { fileCount?: number; fileName?: string },
): string {
const batchNo = String(
(result?.batch_no as string | undefined)
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const taskId = String(
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| (result?.task_id as string | undefined)
|| ((result?.data as { tasks?: Array<{ task_id?: string }> } | undefined)?.tasks?.[0]?.task_id)
|| '',
).trim();
const fileCount = Number(options?.fileCount || 0);
const fileLabel = options?.fileName
? `《${options.fileName}》`
: (fileCount > 1 ? `${fileCount} 份发货通知` : '发货通知');
const parts = [`我已上传${fileLabel}`];
if (batchNo) parts.push(`批次 ${batchNo}`);
if (taskId) parts.push(`当前任务 ${taskId}`);
return `${parts.join(',')}。请读取任务 raw_text,用 LLM 抽取结构化字段后调用 parse_notice(structured=...) 落库;若抽取失败可仅传 raw_text 走后端规则兜底,并展示解析结果供我确认。`;
}
/**
* 按扩展名判断附件是库存 Excel 还是发货通知文件。
*/
@@ -60,10 +60,14 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
const removeParseReviewMessageForTask = (taskId: string) => {
const normalized = String(taskId || '').trim().toUpperCase();
if (!normalized) return;
ctx.messages.value = ctx.messages.value.filter((msg) => {
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
const msg = ctx.messages.value[i];
if (!msg) continue;
const payload = getShippingParseReviewPayload(msg);
return payload?.taskId?.trim().toUpperCase() !== normalized;
});
if (payload?.taskId?.trim().toUpperCase() === normalized) {
ctx.messages.value.splice(i, 1);
}
}
};
const upsertParseReviewMessage = async (payload: ShippingParseReviewPayload) => {
@@ -12,7 +12,7 @@ import {
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { extractExt } from '../constants/shipping';
import { buildShippingInventoryUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
import { buildShippingInventoryUploadPrompt, buildShippingNoticeUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
import type { PendingAttachment } from '../types/shipping.types';
import type { Ref } from 'vue';
@@ -193,6 +193,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
tail,
].filter(Boolean).join('\n'),
);
await ctx.sendShippingMenuMessage(
buildShippingNoticeUploadPrompt(result as unknown as Record<string, unknown>, { fileName: file.name }),
);
void ctx.refreshShippingActions();
};
@@ -238,6 +241,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
tail,
].filter(Boolean).join('\n'),
);
await ctx.sendShippingMenuMessage(
buildShippingNoticeUploadPrompt(result as unknown as Record<string, unknown>, { fileCount }),
);
void ctx.refreshShippingActions();
};
@@ -25,6 +25,9 @@ export interface ShippingTaskSummary {
conversation_id?: string | null;
export_file_name?: string | null;
freight_ref_no?: string | null;
step_payload?: Record<string, unknown> & {
current_step_progress?: ShippingCurrentStepProgress;
};
created_at?: string | null;
updated_at?: string | null;
}
@@ -35,6 +38,18 @@ export interface ShippingTaskEvent {
created_at?: string | null;
}
export interface ShippingCurrentStepProgress {
step_key?: string;
step_title?: string;
status?: 'running' | 'completed' | 'needs_human' | 'pending' | string;
message?: string;
progress_percent?: number;
current?: number;
total?: number;
detail?: string;
extra?: Record<string, unknown>;
}
export interface ShippingNoticeHeader {
customer_name?: string | null;
customer_code?: string | null;
@@ -70,7 +85,6 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
step_payload?: Record<string, unknown>;
upload_receipt?: Record<string, unknown>;
export_version?: number | null;
idempotency_key?: string | null;
@@ -104,7 +118,15 @@ export interface ShippingBatchSummary {
conversation_id?: string | null;
current_focus_task_no?: string | null;
file_count?: number | null;
process_summary?: Record<string, unknown> | null;
process_summary?: Record<string, unknown> & {
total?: number;
completed?: number;
failed?: number;
running?: number;
pending?: number;
current_index?: number;
current_task_no?: string | null;
} | null;
created_at?: string | null;
updated_at?: string | null;
}
@@ -30,6 +30,7 @@ import {
updateWorkspaceShippingNoticeLine,
workspaceShippingExportUrl,
type ShippingChatAction,
type ShippingCurrentStepProgress,
type ShippingNoticeHeader,
type ShippingNoticeLine,
type ShippingTaskDetail,
@@ -90,6 +91,12 @@ const statusBadge = (status: string) => {
};
const detailWorkflowSteps = computed(() => buildShippingWorkflowSteps(detail.value));
const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
const payload = detail.value?.step_payload;
if (!payload || typeof payload !== 'object') return null;
const progress = (payload as Record<string, unknown>).current_step_progress;
return progress && typeof progress === 'object' ? progress as ShippingCurrentStepProgress : null;
});
const loadCases = async () => {
loading.value = true;
@@ -413,6 +420,38 @@ onMounted(async () => {
<ShippingWorkflowStepper :steps="detailWorkflowSteps" />
<div
v-if="detailStepProgress"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3"
>
<div class="flex items-center justify-between gap-3 text-xs">
<div class="font-medium text-primary">
{{ detailStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
</div>
<div class="text-muted">
{{ detailStepProgress.progress_percent ?? 0 }}%
</div>
</div>
<div class="mt-1 text-sm text-secondary">
{{ detailStepProgress.message || t('chat.shippingNoticeUi.processing') }}
</div>
<div v-if="detailStepProgress.detail" class="mt-1 text-xs text-muted">
{{ detailStepProgress.detail }}
</div>
<div
v-if="detailStepProgress.current && detailStepProgress.total"
class="mt-1 text-xs text-muted"
>
{{ t('chat.shippingNoticeUi.stepDetail.counter', { current: detailStepProgress.current, total: detailStepProgress.total }) }}
</div>
<div class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-sky-500 transition-all"
:style="{ width: `${detailStepProgress.progress_percent ?? 0}%` }"
/>
</div>
</div>
<dl class="grid gap-3 sm:grid-cols-2 text-sm">
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt><dd>{{ detail.process_status }}</dd></div>
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt><dd>{{ detail.match_status || '—' }}</dd></div>
+8
View File
@@ -79,6 +79,7 @@
"taskTitle": "Shipping task",
"currentTask": "Current task {taskId}",
"batchProgress": "Item {index}/{total}",
"batchCurrentIndex": "Currently processing item {index}/{total}",
"currentNotice": "Current notice",
"prevTask": "Previous",
"nextTask": "Next",
@@ -94,6 +95,7 @@
"fileCount": "Files",
"runningCount": "Running",
"completedCount": "Completed",
"pendingCount": "Pending",
"batchProgressTitle": "Batch progress",
"processing": "Processing",
"status": {
@@ -109,13 +111,19 @@
},
"currentStep": {
"noticeParse": "Notice parsing",
"parseConfirm": "Confirm parsing",
"inventoryPrepare": "Inventory prep",
"alignConfirm": "Confirm mapping",
"inventoryMatch": "Inventory match",
"shortageHandle": "Shortage handling",
"generateExcel": "Generate Excel",
"uploadFreight": "Upload to freight",
"finishArchive": "Archive"
},
"stepDetail": {
"title": "Step progress",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "Fully fulfillable",
"partial": "Partially fulfillable",
+8
View File
@@ -79,6 +79,7 @@
"taskTitle": "งานจัดส่ง",
"currentTask": "งานปัจจุบัน {taskId}",
"batchProgress": "รายการ {index}/{total}",
"batchCurrentIndex": "กำลังประมวลผลรายการที่ {index}/{total}",
"currentNotice": "ใบแจ้งปัจจุบัน",
"prevTask": "ก่อนหน้า",
"nextTask": "ถัดไป",
@@ -94,6 +95,7 @@
"fileCount": "จำนวนไฟล์",
"runningCount": "กำลังดำเนินการ",
"completedCount": "เสร็จแล้ว",
"pendingCount": "รอดำเนินการ",
"batchProgressTitle": "ความคืบหน้าของชุดงาน",
"processing": "กำลังดำเนินการ",
"status": {
@@ -109,13 +111,19 @@
},
"currentStep": {
"noticeParse": "แยกใบแจ้ง",
"parseConfirm": "ยืนยันผลแยก",
"inventoryPrepare": "เตรียมสต็อก",
"alignConfirm": "ยืนยันการจับคู่คอลัมน์",
"inventoryMatch": "จับคู่สต็อก",
"shortageHandle": "จัดการส่วนขาด",
"generateExcel": "สร้าง Excel",
"uploadFreight": "อัปโหลดผู้ให้บริการขนส่ง",
"finishArchive": "เก็บงาน"
},
"stepDetail": {
"title": "ความคืบหน้าภายในขั้นตอน",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "จัดส่งได้ครบ",
"partial": "จัดส่งได้บางส่วน",
+8
View File
@@ -79,6 +79,7 @@
"taskTitle": "发货任务",
"currentTask": "当前任务 {taskId}",
"batchProgress": "第 {index}/{total} 票",
"batchCurrentIndex": "当前处理第 {index}/{total} 票",
"currentNotice": "当前通知",
"prevTask": "上一票",
"nextTask": "下一票",
@@ -94,6 +95,7 @@
"fileCount": "文件数",
"runningCount": "处理中",
"completedCount": "已完成",
"pendingCount": "待处理",
"batchProgressTitle": "批次进度",
"processing": "处理中",
"status": {
@@ -109,13 +111,19 @@
},
"currentStep": {
"noticeParse": "通知解析",
"parseConfirm": "确认解析",
"inventoryPrepare": "库存准备",
"alignConfirm": "确认字段对齐",
"inventoryMatch": "库存匹配",
"shortageHandle": "缺口处理",
"generateExcel": "生成 Excel",
"uploadFreight": "上传货代",
"finishArchive": "完成归档"
},
"stepDetail": {
"title": "步骤内进度",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "可全部发货",
"partial": "部分满足",
+8
View File
@@ -79,6 +79,7 @@
"taskTitle": "發貨任務",
"currentTask": "當前任務 {taskId}",
"batchProgress": "第 {index}/{total} 票",
"batchCurrentIndex": "當前處理第 {index}/{total} 票",
"currentNotice": "當前通知",
"prevTask": "上一票",
"nextTask": "下一票",
@@ -94,6 +95,7 @@
"fileCount": "檔案數",
"runningCount": "處理中",
"completedCount": "已完成",
"pendingCount": "待處理",
"batchProgressTitle": "批次進度",
"processing": "處理中",
"status": {
@@ -109,13 +111,19 @@
},
"currentStep": {
"noticeParse": "通知解析",
"parseConfirm": "確認解析",
"inventoryPrepare": "庫存準備",
"alignConfirm": "確認欄位對齊",
"inventoryMatch": "庫存匹配",
"shortageHandle": "缺口處理",
"generateExcel": "生成 Excel",
"uploadFreight": "上傳貨代",
"finishArchive": "完成歸檔"
},
"stepDetail": {
"title": "步驟內進度",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "可全部發貨",
"partial": "部分滿足",