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",
+4
View File
@@ -41,6 +41,10 @@ def pytest_configure(config):
"markers",
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
)
config.addinivalue_line(
"markers",
"rpa_e2e: 真实货代 RPA 浏览器导出测试,默认跳过,需 FREIGHT_RPA_E2E=true",
)
@pytest.fixture
+241
View File
@@ -0,0 +1,241 @@
"""scripts/rpa/freight_rpa_worker.py tests.
覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径:
1. 读取 inventory_export_SN-20260629-2EDADC77.json。
2. 按 DSV360/AWSDU 库存源分发下载。
3. 成功后回调 hxops,并把 trigger 移入 processed。
"""
from __future__ import annotations
import importlib.util
import json
import os
from pathlib import Path
import pytest
from openpyxl import load_workbook
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_freight_rpa_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_under_test", module_path)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path):
"""基于失败样本 SN-20260629-2EDADC77 验证 RPA 库存导出 trigger 可被正常消费。"""
worker = _load_freight_rpa_worker()
source_trigger = (
_repo_root()
/ "backend"
/ "data"
/ "shipping_notice"
/ "freight_rpa"
/ "inventory_triggers"
/ "failed"
/ "inventory_export_SN-20260629-2EDADC77.json"
)
trigger_dir = tmp_path / "inventory_triggers"
trigger_dir.mkdir()
trigger_path = trigger_dir / source_trigger.name
trigger_path.write_text(source_trigger.read_text(encoding="utf-8"), encoding="utf-8")
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
processed_dir = trigger_dir / "processed"
callbacks: list[tuple[str, dict]] = []
download_calls: list[dict] = []
def fake_download_inventory_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
download_calls.append(trigger)
out_file = target_drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
out_file.write_bytes(b"fake inventory content")
return out_file
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
assert len(download_calls) == 1
trigger = download_calls[0]
assert trigger["task_no"] == "SN-20260629-2EDADC77"
assert trigger["attempt"] == 3
assert trigger["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU"
assert trigger["rpa_inventory_source"]["source_type"] == "dsv360"
assert trigger["rpa_inventory_source"]["query"]["program_label"] == "AWSDU - Prod (JDA)"
assert trigger["rpa_inventory_source"]["query"]["owner_code"] == "CADU-0000000100"
assert callbacks == [
(
"/api/shipping-notice/rpa/inventory-ready",
{
"task_no": "SN-20260629-2EDADC77",
"success": True,
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
"source_code": "DSV360_AWSDU",
},
)
]
assert not trigger_path.exists()
assert (processed_dir / source_trigger.name).is_file()
processed_payload = json.loads((processed_dir / source_trigger.name).read_text(encoding="utf-8"))
assert processed_payload["task_no"] == "SN-20260629-2EDADC77"
def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypatch, tmp_path):
"""基于失败样本验证 mock RPA 会真实导出一个可打开的库存 Excel。"""
worker = _load_freight_rpa_worker()
source_trigger = (
_repo_root()
/ "backend"
/ "data"
/ "shipping_notice"
/ "freight_rpa"
/ "inventory_triggers"
/ "failed"
/ "inventory_export_SN-20260629-2EDADC77.json"
)
trigger_dir = tmp_path / "inventory_triggers"
trigger_dir.mkdir()
trigger_path = trigger_dir / source_trigger.name
trigger_path.write_text(source_trigger.read_text(encoding="utf-8"), encoding="utf-8")
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
processed_dir = trigger_dir / "processed"
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
monkeypatch.delenv("FREIGHT_RPA_SAMPLE_INVENTORY", raising=False)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
exported_files = list(drop_dir.glob("inventory_SN-20260629-2EDADC77_*.xlsx"))
assert len(exported_files) == 1
exported = exported_files[0]
wb = load_workbook(exported, data_only=True, read_only=True)
try:
ws = wb.active
rows = list(ws.iter_rows(values_only=True))
finally:
wb.close()
assert rows[0] == ("料号", "可用数量")
assert rows[1] == ("A001", 100)
assert rows[2] == ("A002", 50)
assert callbacks == [
(
"/api/shipping-notice/rpa/inventory-ready",
{
"task_no": "SN-20260629-2EDADC77",
"success": True,
"file_path": str(exported),
"source_code": "DSV360_AWSDU",
},
)
]
assert not trigger_path.exists()
assert (processed_dir / source_trigger.name).is_file()
def test_open_browser_uses_configured_browser_channel(monkeypatch, tmp_path):
"""真实 RPA 可通过本机 Edge/Chrome channel 启动,避免强制下载 Playwright Chromium。"""
worker = _load_freight_rpa_worker()
observed: dict[str, object] = {}
class _FakePage:
def set_default_timeout(self, value: int) -> None:
observed["timeout"] = value
class _FakeContext:
pages = [_FakePage()]
class _FakeChromium:
def launch_persistent_context(self, profile: str, **kwargs):
observed["profile"] = profile
observed["kwargs"] = kwargs
return _FakeContext()
class _FakePlaywright:
chromium = _FakeChromium()
class _FakeStarter:
def start(self):
return _FakePlaywright()
monkeypatch.setenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false")
monkeypatch.setenv("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page = worker._open_browser(tmp_path / "downloads")
assert context is not None
assert page is not None
assert observed["profile"] == str(tmp_path / "profile")
assert observed["kwargs"] == {
"headless": False,
"accept_downloads": True,
"downloads_path": str(tmp_path / "downloads"),
"channel": "msedge",
}
@pytest.mark.rpa_e2e
def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_path):
"""
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
默认跳过;仅当 FREIGHT_RPA_E2E=true 时执行。执行前需准备 DSV 登录态或账号密码:
- FREIGHT_RPA_MOCK=false
- FREIGHT_RPA_HEADLESS=false(建议首次调试)
- FREIGHT_RPA_BROWSER_PROFILE_DIR=<已登录 profile,可选>
- FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD(可选)
"""
if str(os.getenv("FREIGHT_RPA_E2E") or "").strip().lower() != "true":
pytest.skip("set FREIGHT_RPA_E2E=true to run real freight RPA export")
worker = _load_freight_rpa_worker()
source_trigger = (
_repo_root()
/ "backend"
/ "data"
/ "shipping_notice"
/ "freight_rpa"
/ "inventory_triggers"
/ "failed"
/ "inventory_export_SN-20260629-2EDADC77.json"
)
trigger = json.loads(source_trigger.read_text(encoding="utf-8"))
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
monkeypatch.setenv("FREIGHT_RPA_MOCK", "false")
if not os.getenv("FREIGHT_RPA_HEADLESS"):
monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false")
if not os.getenv("FREIGHT_RPA_BROWSER_PROFILE_DIR"):
monkeypatch.setenv(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
str(tmp_path / "browser_profile"),
)
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
assert out_file.is_file()
assert out_file.parent == drop_dir
assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"}
assert out_file.stat().st_size > 0
+49 -7
View File
@@ -21,6 +21,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress
def _tool_headers(app):
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
@@ -123,6 +124,46 @@ def test_create_batch_tasks_and_switch_focus(app, client):
assert task_rows[1].batch_total == 2
def test_contract_batch_status_keeps_single_focus_without_advancing_other_tasks(app, client):
"""契约:多任务会话只暴露一个 focus 指针;读取批次状态不能推进整批任务。"""
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"conversation_id": "conv-contract-focus",
"notice_items": [
{"raw_text": "客户A 料号A001 x 1", "source_file_name": "A.pdf"},
{"raw_text": "客户B 料号B001 x 2", "source_file_name": "B.pdf"},
],
},
)
data = create_res.get_json()
batch_no = data["batch_no"]
task_refs = [item["task_id"] for item in data["data"]["tasks"]]
focus_task_no, other_task_no = task_refs
status_res = client.post(
"/api/shipping-notice/tools/get_batch_status",
headers=headers,
json={"batch_no": batch_no},
)
status_data = status_res.get_json()
assert status_res.status_code == 200
assert status_data["status"] == "ok"
assert status_data["data"]["current_focus_task_no"] == focus_task_no
assert [item["task_no"] for item in status_data["data"]["tasks"]] == task_refs
with app.app_context():
rows = {
task.task_no: task
for task in ShippingTask.query.filter(ShippingTask.task_no.in_([focus_task_no, other_task_no])).all()
}
assert rows[focus_task_no].process_status == "created"
assert rows[other_task_no].process_status == "created"
def test_create_batch_defers_parse_without_structured(app, client):
"""默认将 parse_notice 延后到 Dify,仅保存 raw_text。"""
headers = _tool_headers(app)
@@ -342,8 +383,8 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app):
assert task.step_payload_json["current_step_progress"]["status"] == "needs_human"
def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp_path):
"""工作台查询遇到已超时 RPA 等待态时,应兜底复查并自动触发下一次库存导出。"""
def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, client, tmp_path):
"""工作台查询必须保持纯读;已超时 RPA 等待态也不能由 GET 触发补偿或事件落库。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
@@ -394,11 +435,12 @@ def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp
triggered = [event for event in events if event.event_type == "inventory_rpa_triggered"]
failed = [event for event in events if event.event_type == "inventory_rpa_failed"]
rechecked = [event for event in events if event.event_type == "inventory_rpa_wait_rechecked"]
assert len(triggered) == 2
assert len(failed) == 1
assert len(rechecked) == 1
assert triggered[-1].detail_json["attempt"] == 2
assert task.step_payload_json["current_step_progress"]["current"] == 2
assert len(triggered) == 1
assert len(failed) == 0
assert len(rechecked) == 0
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert not list((tmp_path / "inventory_triggers").glob("inventory_export_*.json"))
def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_path):
@@ -19,6 +19,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
@@ -68,6 +69,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
@@ -159,8 +159,8 @@ def test_batch_process_summary_shared_formula(app):
assert "id" not in tool_batch
def test_resolve_task_from_payload_by_conversation_id(app):
"""conversation_id 应能解析到最近非 rejected 任务。"""
def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
"""conversation_id 仅在同会话只有一票可操作任务时允许回退。"""
with app.app_context():
task = ShippingTask(
task_no="SN-CONV-1",
@@ -178,3 +178,35 @@ def test_resolve_task_from_payload_by_conversation_id(app):
assert resolved.task_no == "SN-CONV-1"
assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01"
def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
"""同一 conversation_id 下多票可操作任务时,禁止按最近一票静默回退。"""
with app.app_context():
from app import db
db.session.add_all(
[
ShippingTask(
task_no="SN-CONV-MULTI-1",
conversation_id="conv-multi",
process_status="parsed",
source_type="manual",
),
ShippingTask(
task_no="SN-CONV-MULTI-2",
conversation_id="conv-multi",
process_status="pending_review",
source_type="manual",
),
]
)
db.session.commit()
assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None
resolved = resolve_task_from_payload(
{"conversation_id": "conv-multi", "task_id": "SN-CONV-MULTI-1"}
)
assert resolved is not None
assert resolved.task_no == "SN-CONV-MULTI-1"
+273 -5
View File
@@ -6,6 +6,7 @@ from app.services.shipping_notice.match import match_notice_lines
def _tool_headers(app):
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
@@ -13,6 +14,51 @@ def _tool_headers(app):
}
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
app.config["INTEGRATION_API_KEY"] = ""
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"},
json={"source_type": "manual"},
)
assert res.status_code == 200
assert res.get_json()["status"] == "ok"
def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "integration-secret"
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"},
json={"source_type": "manual"},
)
assert res.status_code == 200
assert res.get_json()["status"] == "ok"
def test_shipping_notice_tool_auth_reports_missing_config(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = ""
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "any"},
json={"source_type": "manual"},
)
assert res.status_code == 503
assert res.get_json()["error_code"] == "missing_auth"
def test_match_notice_lines_reports_progress():
seen: list[tuple[int, int]] = []
@@ -116,6 +162,31 @@ def test_shipping_notice_tool_flow(app, client):
assert status_res.get_json()["status"] == "ok"
def test_contract_get_task_status_accepts_task_no_anchor(app, client):
"""契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
)
task_id = create_res.get_json()["task_id"]
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"task_no": task_id},
)
data = status_res.get_json()
assert status_res.status_code == 200
assert data["status"] == "ok"
assert data["task_id"] == task_id
assert data["data"]["task_no"] == task_id
assert "当前进度" in data["message"]
def test_shipping_notice_match_shortage_needs_human(app, client):
headers = _tool_headers(app)
@@ -157,6 +228,8 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
assert "confirm" not in options
assert "reparse_inventory" in options
assert "rematch" in options
assert "generate_shipment_excel" in (data.get("forbidden_next_tools") or [])
assert "upload_to_freight" in (data.get("forbidden_next_tools") or [])
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
@@ -227,6 +300,62 @@ def test_submit_decision_rematch_reopens_shortage_for_worker(app, client, monkey
assert task.line_results_json is None
def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client, monkeypatch):
"""契约:重新匹配必须通过 submit_decision(rematch) 恢复当前任务,不经 Agent 自由续写。"""
headers = _tool_headers(app)
started: list[str] = []
from app.services.shipping_notice import decision_workflow
monkeypatch.setattr(
decision_workflow,
"start_task_orchestrator",
lambda task_no: started.append(str(task_no)) or True,
)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 20, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 1}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
rematch_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "rematch", "comment": "contract direct rematch"},
)
data = rematch_res.get_json()
assert rematch_res.status_code == 200
assert data["status"] == "running"
assert data["task_id"] == task_id
assert started == [task_id]
def test_openapi_spec_public(app, client):
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
res = client.get("/api/shipping-notice/tools/openapi.json")
@@ -245,6 +374,13 @@ def test_openapi_spec_public(app, client):
assert "/tools/switch_focus_task" not in spec["paths"]
assert "/tools/get_inventory_schema_preview" in spec["paths"]
assert "/tools/apply_inventory_mapping" in spec["paths"]
# 锁定 Dify Tool 契约:OpenAPI 暴露字符串,避免 Dify 画布无法选择上游 map_json 变量。
apply_mapping = spec["paths"]["/tools/apply_inventory_mapping"]["post"]["requestBody"]["content"][
"application/json"
]["schema"]
map_json_schema = apply_mapping["properties"]["map_json"]
assert map_json_schema["type"] == "string"
assert "JSON 字符串" in map_json_schema["description"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
@@ -734,7 +870,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"map_json": {
**preview["suggested_mapping"],
"match_rule": "LLM:Reservation Order 对齐订单 reservation_id,汇总 Qty Available。",
},
@@ -990,6 +1126,57 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "needs_human"
assert parse_data["checkpoint"] == "rsv_req"
assert "解析失败" in parse_data["message"]
assert "Reservation ID / COM ID" in parse_data["message"]
assert "confirm" not in parse_data.get("human_options", [])
assert called == {}
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "pending_review"
assert task.review_status == "rsv_req"
assert task.pending_human_reason == "rsv_req"
assert task.error_message and "解析失败" in task.error_message
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
@@ -1184,6 +1371,15 @@ def test_rpa_pending_timeout_recheck_triggers_next_inventory_export(app, client,
assert task is not None
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
db.session.add(
ShippingTaskEvent(
task_id=task.id,
@@ -1229,6 +1425,15 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
assert task is not None
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_EXHAUSTED
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
@@ -1248,7 +1453,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
)
retry_data = retry_res.get_json()
assert retry_data["status"] == "running"
assert "新一轮第 1/3 次" in retry_data["message"]
assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
@@ -1257,8 +1462,8 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
assert task.pending_human_reason == "rpa_pending"
assert task.error_message is None
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
assert progress.get("message") == "已手动重新触发 RPA 库存导出,等待结果"
assert progress.get("detail") == "新一轮第 1/3 次尝试"
assert progress.get("current") == 1
assert progress.get("extra", {}).get("manual_retry_round") is True
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@@ -1299,6 +1504,15 @@ def test_batch_retry_rechecks_timed_out_rpa_pending_immediately(app, client, tmp
assert task is not None
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
db.session.add(
ShippingTaskEvent(
task_id=task.id,
@@ -1340,7 +1554,7 @@ def test_submit_decision_by_conversation_id(app, client):
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"lines": [{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1365,6 +1579,60 @@ def test_submit_decision_by_conversation_id(app, client):
assert dup_data.get("checkpoint") == "task_exists"
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
headers = _tool_headers(app)
first = ShippingTask(
task_no="SN-MULTI-CONV-001",
conversation_id="conv-test-multi",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"sku": "A001", "reservation_id": "1000140351", "qty": 1}],
)
second = ShippingTask(
task_no="SN-MULTI-CONV-002",
conversation_id="conv-test-multi",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"sku": "A002", "reservation_id": "1000140352", "qty": 1}],
)
with app.app_context():
db.session.add_all([first, second])
db.session.commit()
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"conversation_id": "conv-test-multi", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "failed"
assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"]
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"conversation_id": "conv-test-multi"},
)
status_data = status_res.get_json()
assert status_data["status"] == "failed"
assert "任务编号" in status_data["message"]
with app.app_context():
rows = {
task.task_no: task
for task in ShippingTask.query.filter(ShippingTask.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
.order_by(ShippingTask.task_no)
.all()
}
assert rows["SN-MULTI-CONV-001"].process_status == "pending_review"
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch):
headers = _tool_headers(app)