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:
hugo committed 2026-06-30 21:00:25 +08:00
1 parent eb0466245b
commit 4cd987eef6
45 files changed
+2748 -1406

No files matched your search

+13 -6
View File
@@ -43,13 +43,20 @@ def _require_tool_auth() -> None:
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
未配置时报服务不可用,缺失或错误时报未授权。
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
"""
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
configured = str(
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
or current_app.config.get('INTEGRATION_API_KEY')
or ''
).strip()
if not configured:
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured', code='missing_auth')
raise ServiceUnavailableError(
'SHIPPING_NOTICE_TOOL_API_KEY or 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 ''
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
@@ -331,4 +338,4 @@ def download_task_export(task_no: str):
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
@@ -53,27 +53,6 @@ def _require_user():
return user
def _maybe_recheck_inventory_rpa_wait(task: ShippingTask | None) -> None:
"""
工作台查询兜底复查库存 RPA 等待态。
常规超时/重试由 shipping worker 执行;这里仅在用户查询时发现已超时仍未推进的任务,补偿触发一次幂等复查。
"""
if not task:
return
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
maybe_recheck_inventory_rpa_wait(task, source="workspace_query")
def _maybe_recheck_batch_inventory_rpa_wait(batch: ShippingBatch | None) -> None:
"""对批次下任务执行工作台查询兜底复查,避免 worker 异常时页面长期停在等待结果。"""
if not batch:
return
for task in batch.tasks or []:
_maybe_recheck_inventory_rpa_wait(task)
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
@@ -97,8 +76,6 @@ def workspace_shipping_conversation_batch_workspace(conversation_id: str):
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
).all()
for batch in batches:
_maybe_recheck_batch_inventory_rpa_wait(batch)
return jsonify(get_conversation_batch_workspace(conversation_id, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
@@ -165,7 +142,6 @@ def workspace_shipping_batch_detail(batch_no: str):
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
_maybe_recheck_batch_inventory_rpa_wait(batch)
focus_task = get_focus_task_for_batch(batch_no, user.id)
return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None})
@@ -176,7 +152,6 @@ def workspace_shipping_batch_tasks(batch_no: str):
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
_maybe_recheck_batch_inventory_rpa_wait(batch)
return jsonify(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
@@ -186,7 +161,6 @@ def workspace_shipping_batch_focus_task(batch_no: str):
batch = get_batch_for_user(batch_no, user.id)
if not batch:
raise NotFoundError('Not found')
_maybe_recheck_batch_inventory_rpa_wait(batch)
focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task:
raise NotFoundError('Focus task not found')
@@ -312,7 +286,6 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
_maybe_recheck_inventory_rpa_wait(task)
return jsonify(serialize_task_detail(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
+2 -2
View File
@@ -146,7 +146,7 @@ class Config:
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'
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '1'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
@@ -160,7 +160,7 @@ class Config:
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
'shipment_{task_no}_{ts}.xlsx',
)
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'true').lower() == 'true'
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')
+1 -2
View File
@@ -6,7 +6,7 @@ backend/app/jobs/__init__.py
逻辑:Web API enqueue;worker.py 调用 runner.run_forever。
"""
from app.jobs.types import JobStatus, JobType
from app.jobs.queue import enqueue, enqueue_clean_job, enqueue_kb_job, enqueue_shipping_notice_job
from app.jobs.queue import enqueue, enqueue_clean_job, enqueue_kb_job
__all__ = [
'JobType',
@@ -14,5 +14,4 @@ __all__ = [
'enqueue',
'enqueue_kb_job',
'enqueue_clean_job',
'enqueue_shipping_notice_job',
]
+39 -3
View File
@@ -1,9 +1,9 @@
"""
backend/app/jobs/queue.py
用途:通用后台任务入队、领取与完成状态管理。
依赖:models.Job、jobs.types、Flask app.config。
逻辑:业务服务调用 enqueue 写入 jobs;worker 调用 claim/finish/fail 完成执行闭环。
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。
"""
from __future__ import annotations
@@ -15,6 +15,7 @@ from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.core.errors import ValidationError
from app.jobs.types import JobType
from app.models import Job
@@ -65,6 +66,32 @@ def _find_shipping_notice_job_id(task_no: str) -> int | None:
return None
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
"""
兼容旧知识库后台任务入队入口。
Args:
job_id: KbJob 主键;由清洗、路径上传、Dify 同步等知识库流程传入。
Returns:
(是否接受入队, 队列状态说明)。
"""
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job as _enqueue_kb_job
return _enqueue_kb_job(job_id)
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
"""
兼容旧清洗任务入队入口。
Args:
job_id: clean 类型 KbJob 主键。
Returns:
(是否接受入队, 队列状态说明)。
"""
return enqueue_kb_job(job_id)
def enqueue(
job_type: JobType | str,
payload: dict[str, Any],
@@ -96,6 +123,15 @@ def enqueue(
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
"""
normalized_type = _normalize_job_type(job_type)
if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}:
raw_job_id = (payload or {}).get("job_id") if isinstance(payload, dict) else None
if not raw_job_id:
raise ValidationError("job_id is required")
ok, message_text = enqueue_kb_job(int(raw_job_id))
if not ok:
raise ValidationError(message_text or "enqueue kb job failed")
return int(raw_job_id)
normalized_domain = str(domain or "").strip() or "default"
normalized_ref = str(business_ref or correlation_id or "").strip() or None
if not normalized_type:
@@ -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"],
)
+3 -3
View File
@@ -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",