feat(queue): 添加旧知识库任务入队兼容入口
- 增加 enqueue_kb_job 和 enqueue_clean_job 函数以支持旧 KB 清洗任务入队 - 在 enqueue 函数中处理 KB_CLEAN 和 KB_DIFY_SYNC 类型的任务 - 引入 ValidationError 以处理 job_id 缺失的情况 feat(shipping_notice): 更新库存 RPA 工作流逻辑 - 修改 ensure_inventory_via_rpa 函数以支持手动重试逻辑 - 优化库存导出触发和状态更新的消息提示 fix(i18n): 更新任务未找到的提示信息 - 修改中文和英文提示,明确用户操作要求 feat(shipping_notice): 增强任务解析逻辑 - 添加缺失 Reservation ID 的检查,阻止任务进入确认阶段 - 更新 get_task_status 函数以处理多票会话的任务解析
This commit is contained in:
1 parent
eb0466245b
commit
4cd987eef6
45 files changed
+2748
-1406
No files matched your search
@@ -340,6 +340,8 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task=task,
|
||||
message=match_summary,
|
||||
data=serialize_task_for_tool(task),
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.decision.fulfillment_running": "发货通知已确认,后台继续处理库存与后续步骤。",
|
||||
"workflow.decision.rematch_running": "已提交重新匹配请求,后台继续处理。",
|
||||
"workflow.decision.mapping_confirmed_running": "库存字段对齐已确认,后台继续处理匹配与后续步骤。",
|
||||
"workflow.decision.task_not_found": "未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。",
|
||||
"workflow.decision.task_not_found": "未找到明确任务。用户说「确认/重新解析/驳回」时禁止 create_task;多票会话必须带任务编号。",
|
||||
"workflow.decision.rejected": "已驳回该发货任务。",
|
||||
"workflow.decision.closed": "已关闭该发货任务(可在同一会话重新开新单)。",
|
||||
"workflow.decision.shortage_confirm_blocked": "库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
|
||||
@@ -209,7 +209,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.decision.fulfillment_running": "The shipping notice is confirmed. The backend is continuing inventory handling and the remaining steps.",
|
||||
"workflow.decision.rematch_running": "The rematch request has been submitted. The backend is continuing processing.",
|
||||
"workflow.decision.mapping_confirmed_running": "The inventory mapping is confirmed. The backend is continuing matching and the remaining steps.",
|
||||
"workflow.decision.task_not_found": "Task not found. When the user says confirm / re-parse / reject, do not call create_task. Please call get_task_status(conversation_id=...) first or pass the task ID to submit_decision.",
|
||||
"workflow.decision.task_not_found": "No unambiguous task was found. When the user says confirm / re-parse / reject, do not call create_task; multi-task conversations must include the task ID.",
|
||||
"workflow.decision.rejected": "The shipping task has been rejected.",
|
||||
"workflow.decision.closed": "The shipping task has been closed. You may start a new one in the same conversation.",
|
||||
"workflow.decision.shortage_confirm_blocked": "Inventory is insufficient. You cannot use confirm for the whole task. Please use reparse_inventory, rematch, or reject.",
|
||||
@@ -344,7 +344,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.decision.fulfillment_running": "ยืนยันใบแจ้งส่งสินค้าแล้ว ระบบหลังบ้านกำลังดำเนินการสต็อกและขั้นตอนถัดไปต่อ",
|
||||
"workflow.decision.rematch_running": "ส่งคำขอจับคู่ใหม่แล้ว ระบบหลังบ้านกำลังดำเนินการต่อ",
|
||||
"workflow.decision.mapping_confirmed_running": "ยืนยันการจับคู่คอลัมน์สต็อกแล้ว ระบบหลังบ้านกำลังดำเนินการจับคู่และขั้นตอนถัดไปต่อ",
|
||||
"workflow.decision.task_not_found": "ไม่พบงาน เมื่อผู้ใช้พูดว่ายืนยัน / แยกใหม่ / ปฏิเสธ ห้ามเรียก create_task โปรดเรียก get_task_status(conversation_id=...) ก่อน หรือส่ง task ID ให้ submit_decision",
|
||||
"workflow.decision.task_not_found": "ไม่พบงานที่ระบุได้ชัดเจน เมื่อผู้ใช้พูดว่ายืนยัน / แยกใหม่ / ปฏิเสธ ห้ามเรียก create_task และหากมีหลายงานต้องส่ง task ID มาด้วย",
|
||||
"workflow.decision.rejected": "ปฏิเสธงานจัดส่งนี้แล้ว",
|
||||
"workflow.decision.closed": "ปิดงานจัดส่งนี้แล้ว และสามารถเริ่มงานใหม่ในบทสนทนาเดิมได้",
|
||||
"workflow.decision.shortage_confirm_blocked": "สต็อกไม่เพียงพอ จึงไม่สามารถใช้ confirm เพื่อยืนยันทั้งงานได้ โปรดใช้ reparse_inventory, rematch หรือ reject",
|
||||
|
||||
@@ -263,7 +263,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
# 已达到最大次数时直接转人工;若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
max_attempts = max_rpa_inventory_attempts()
|
||||
if attempts >= max_attempts and not task.inventory_lines_json:
|
||||
if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||||
@@ -312,7 +312,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
else "已触发 RPA 库存导出,等待结果"
|
||||
)
|
||||
progress_detail = (
|
||||
f"新一轮第 {attempt_no}/{max_attempts} 次尝试"
|
||||
f"手动第 {attempt_no} 次尝试"
|
||||
if manual_retry_round
|
||||
else f"第 {attempt_no}/{max_attempts} 次尝试"
|
||||
)
|
||||
@@ -324,7 +324,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
message=progress_message,
|
||||
progress_percent=60,
|
||||
current=attempt_no,
|
||||
total=max_attempts,
|
||||
total=max(attempt_no, max_attempts),
|
||||
detail=progress_detail,
|
||||
extra={"manual_retry_round": manual_retry_round} if manual_retry_round else None,
|
||||
)
|
||||
@@ -334,7 +334,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
{"trigger": trigger, "attempt": attempt_no, "manual_retry_round": manual_retry_round},
|
||||
)
|
||||
|
||||
if attempt_no >= max_attempts and not task.inventory_lines_json:
|
||||
if attempt_no >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempt_no})
|
||||
@@ -347,7 +347,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
)
|
||||
|
||||
response_prefix = (
|
||||
f"已手动重新触发 RPA 库存导出(新一轮第 {attempt_no}/{max_attempts} 次)。"
|
||||
f"已手动重新触发 RPA 库存导出(手动第 {attempt_no} 次)。"
|
||||
if manual_retry_round
|
||||
else f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||||
)
|
||||
@@ -355,7 +355,7 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=f"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。",
|
||||
message=f"{response_prefix}若 {timeout_seconds}s 内无回调/无落盘文件,可手动重试,或上传库存 Excel。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
|
||||
@@ -19,10 +19,10 @@ from app.services.shipping_notice.inventory_sources import build_rpa_inventory_s
|
||||
ROUTE_RULES: tuple[dict[str, Any], ...] = (
|
||||
{"source_code": "DSV360_AWSBI", "aliases": ("BISON", "AWSBI")},
|
||||
{"source_code": "DSV360_AWSCV", "aliases": ("CINCINNATI", "CVG", "AWSCV")},
|
||||
{"source_code": "DSV360_AWSDU", "aliases": ("DUB", "DUBLIN")},
|
||||
{"source_code": "DSV360_AWSDU", "aliases": ("DBS DUB", "DUB", "DUBLIN")},
|
||||
{"source_code": "DSV360_AWSAMS", "aliases": ("MOERDIJK", "AMS", "AWSAMS")},
|
||||
{"source_code": "DSV360_AWSSL", "aliases": ("USLCK", "SALT LAKE CITY", "SALTLAKECITY")},
|
||||
{"source_code": "DSV360_AWSSG", "aliases": ("SINGAPORE", "SG")},
|
||||
{"source_code": "DSV360_AWSSG", "aliases": ("SINGAPORE HUB", "SINGAPORE", "SG")},
|
||||
{"source_code": "CRANE_TZR2", "aliases": ("TZR2", "THAILAND")},
|
||||
)
|
||||
|
||||
|
||||
@@ -171,7 +171,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
{
|
||||
"task_id": task_id,
|
||||
MAP_JSON: _str_prop(
|
||||
'列映射 JSON,含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明,缺省则后端动态兜底)'
|
||||
"Dify Tool 参数使用 JSON 字符串,内容含 sku/reservation_id/available_qty;"
|
||||
"可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。"
|
||||
),
|
||||
},
|
||||
required=["task_id", MAP_JSON],
|
||||
|
||||
@@ -201,8 +201,17 @@ def extract_task_no_from_text(text: str) -> str | None:
|
||||
return match.group(0).upper() if match else None
|
||||
|
||||
|
||||
def resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None:
|
||||
"""按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。"""
|
||||
def resolve_task_from_payload(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
allow_conversation_fallback: bool = True,
|
||||
) -> ShippingTask | None:
|
||||
"""
|
||||
按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。
|
||||
|
||||
核心逻辑:显式任务号永远优先;conversation_id 仅在同会话下只有一票可操作任务时回退,
|
||||
多票场景返回 None,避免用户只说“确认/继续”时误推进最近一票。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
|
||||
@@ -218,14 +227,20 @@ def resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None:
|
||||
if task:
|
||||
return task
|
||||
|
||||
if not allow_conversation_fallback:
|
||||
return None
|
||||
|
||||
conv_id = str(payload.get("conversation_id") or "").strip()
|
||||
if conv_id:
|
||||
return (
|
||||
candidates = (
|
||||
ShippingTask.query.filter_by(conversation_id=conv_id)
|
||||
.filter(ShippingTask.process_status.notin_(["rejected"]))
|
||||
.filter(ShippingTask.process_status.notin_(["rejected", "closed", "uploaded"]))
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.first()
|
||||
.limit(2)
|
||||
.all()
|
||||
)
|
||||
if len(candidates) == 1:
|
||||
return candidates[0]
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from datetime import datetime
|
||||
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
|
||||
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 3
|
||||
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 1
|
||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||
|
||||
_INVENTORY_SUCCESS_EVENTS = {
|
||||
|
||||
@@ -130,7 +130,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
"retry_resolve_inventory_source",
|
||||
"upload_inventory_file",
|
||||
),
|
||||
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
|
||||
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("reparse_inventory", "correct_inventory_mapping", "rematch", "reject"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
|
||||
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
@@ -248,9 +248,9 @@ def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
|
||||
def upload_req_options_for_task(task: ShippingTask) -> list[str]:
|
||||
"""upload_req checkpoint 的动作子集,随 RPA 重试次数动态收缩。"""
|
||||
if task.pending_human_reason == PH_RPA_EXHAUSTED:
|
||||
return list(OPTIONS_UPLOAD_FILE_ONLY)
|
||||
return list(OPTIONS_RPA_OR_UPLOAD)
|
||||
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
|
||||
return list(OPTIONS_UPLOAD_FILE_ONLY)
|
||||
return list(OPTIONS_RPA_OR_UPLOAD)
|
||||
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])
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_OK,
|
||||
CP_RSV_REQ,
|
||||
CP_TASK_EXISTS,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
@@ -40,6 +41,7 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task as qs_serialize_task,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||||
@@ -101,6 +103,29 @@ def _has_parse_review_content(task: ShippingTask, lines: list[Any]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
检查解析结果中缺少 Reservation ID / COM ID 的订单行。
|
||||
|
||||
核心逻辑:复用库存匹配阶段的 Reservation ID 提取规则;解析阶段缺失时提前阻断,
|
||||
避免用户确认后才在库存匹配阶段失败。
|
||||
"""
|
||||
missing: list[dict[str, Any]] = []
|
||||
for index, line in enumerate(lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if extract_reservation_id(line.get("reservation_id")):
|
||||
continue
|
||||
missing.append(
|
||||
{
|
||||
"line_index": index,
|
||||
"sku": str(line.get("sku") or "").strip(),
|
||||
"reservation_id": str(line.get("reservation_id") or "").strip(),
|
||||
}
|
||||
)
|
||||
return missing
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
@@ -565,7 +590,45 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
# [STEP 3] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。
|
||||
# [STEP 3] Reservation ID 是后续匹配的硬前置;解析阶段缺失时直接阻断,禁止进入普通确认。
|
||||
missing_reservation = _missing_reservation_lines(lines)
|
||||
if missing_reservation:
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
task.error_message = "解析失败:未识别到 Reservation ID / COM ID(预定单号)"
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="failed",
|
||||
message="解析失败:未识别到预定单号",
|
||||
progress_percent=100,
|
||||
current=len(lines) - len(missing_reservation),
|
||||
total=len(lines),
|
||||
detail="请重新上传包含 Reservation ID / COM ID 的发货通知,或重新解析后补充预定单号。",
|
||||
extra={"warnings": warnings, "missing_reservation": missing_reservation[:5]},
|
||||
)
|
||||
detail = {
|
||||
"missing_count": len(missing_reservation),
|
||||
"missing_preview": missing_reservation[:5],
|
||||
"warnings": warnings,
|
||||
}
|
||||
log_task_event(task, "notice_reservation_id_missing", detail)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=(
|
||||
"解析失败:未识别到 Reservation ID / COM ID(预定单号),"
|
||||
"当前任务无法继续匹配库存。请重新上传包含该字段的通知,或重新解析后补充预定单号。"
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "missing_reservation": detail},
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=["replace_notice_file", "reparse", "reject"],
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 4] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。
|
||||
if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
|
||||
if not _has_parse_review_content(task, lines):
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
@@ -1068,9 +1131,9 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def get_task_status(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
查询任务当前进度(Tool / 工作台共用)。
|
||||
【AI 触发时机】:当 Agent 丢失上下文、只知道 conversation_id,或需要先确认当前卡在哪个检查点时调用。
|
||||
【AI 触发时机】:当 Agent 需要按任务编号确认当前卡在哪个检查点时调用;多票会话必须传 task_id/task_no。
|
||||
|
||||
核心逻辑:按任务号或 conversation_id 定位任务,并返回面向用户的当前阶段描述与任务快照。
|
||||
核心逻辑:优先按任务号定位;conversation_id 仅在同会话下唯一可操作任务时回退,并返回面向用户的当前阶段描述。
|
||||
Args:
|
||||
payload: 可包含 task_id、task_no、conversation_id 等定位参数。
|
||||
|
||||
@@ -1081,7 +1144,7 @@ def get_task_status(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
message="未找到任务。请提供任务编号或 conversation_id(Dify 会话 ID)。",
|
||||
message="未找到明确任务。请提供任务编号;多票会话不能只靠 conversation_id 查询或继续。",
|
||||
)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
|
||||
Reference in new issue
Block a user