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
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user