Files
syops/backend/tests/test_shipping_notice_batches.py
T

2193 lines
87 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""shipping_notice batch tests.
覆盖 batch 新增能力的最小闭环:
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
2. get_batch_status 返回 focus task 与任务列表。
3. switch_focus_task 可在同批次内切换当前任务。
4. 工作台批量上传通知时仅为可解析文件建任务,并返回 envelope + 文件级摘要。
"""
import json
from datetime import datetime, timedelta
from io import BytesIO
import pytest
from app import db
from app.models import (
Agent,
ChatSession,
FileAsset,
Job,
KbJob,
ShippingBatch,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
ShippingTaskEvent,
User,
)
from app.core.auth.jwt import issue_local_access_token
from app.jobs.context import JobContext
from app.jobs.queue import process_next_job
from app.jobs.types import JobType
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools
from app.services.shipping_notice.progress_workflow import auto_progress
from tests.conftest import seed_task_inventory_source
def _tool_headers(app):
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def _workspace_headers(app):
with app.app_context():
user = User(
username="shipping_workspace_user",
email="shipping_workspace_user@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
"Authorization": f"Bearer {token}",
}
def _unwrap_ok(res):
"""解包 workspace 成功 envelope,减少断言噪音。"""
payload = res.get_json()
assert payload["success"] is True
assert payload["request_id"]
assert payload["timestamp"]
return payload["data"]
def test_create_batch_tasks_and_switch_focus(app, client):
"""验证 batch 建单、状态查询、focus task 切换主流程。"""
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"source_type": "manual",
"notice_items": [
{
"source_file_name": "notice-a.txt",
"raw_text": "客户:ACME 料号A001 x 10",
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
{
"source_file_name": "notice-b.txt",
"raw_text": "客户:Wistron 料号B002 x 5",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "B002", "reservation_id": "R-2", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
],
},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
batch = create_data["data"]["batch"]
tasks = create_data["data"]["tasks"]
batch_no = batch["batch_no"]
assert batch_no.startswith("SB-")
assert len(tasks) == 2
assert batch["current_focus_task_no"] == tasks[0]["task_id"]
assert batch["process_summary"]["total"] == 2
status_res = client.post(
"/api/shipping-notice/tools/get_batch_status",
headers=headers,
json={"batch_no": batch_no},
)
assert status_res.status_code == 200
status_data = status_res.get_json()
assert status_data["status"] == "ok"
assert status_data["data"]["batch_no"] == batch_no
assert len(status_data["data"]["tasks"]) == 2
assert status_data["data"]["focus_task"] is None
assert status_data["data"]["tasks"][0]["task_no"] == tasks[0]["task_id"]
target_task_no = tasks[1]["task_id"]
switch_res = client.post(
"/api/shipping-notice/tools/switch_focus_task",
headers=headers,
json={"batch_no": batch_no, "task_no": target_task_no},
)
assert switch_res.status_code == 200
switch_data = switch_res.get_json()
assert switch_data["status"] == "ok"
assert switch_data["task_no"] == target_task_no
assert switch_data["data"]["batch"]["current_focus_task_no"] == target_task_no
assert switch_data["data"]["focus_task"]["task_no"] == target_task_no
with app.app_context():
batch_row = ShippingBatch.query.filter_by(batch_no=batch_no).first()
task_rows = ShippingTask.query.filter_by(batch_id=batch_row.id).order_by(ShippingTask.batch_index.asc()).all()
assert batch_row is not None
assert len(task_rows) == 2
assert batch_row.current_focus_task_no == target_task_no
assert task_rows[0].batch_total == 2
assert task_rows[1].batch_total == 2
focus_events = (
ShippingTaskEvent.query.filter_by(task_id=task_rows[1].id, event_type="focus_switched")
.order_by(ShippingTaskEvent.id.desc())
.all()
)
assert len(focus_events) == 1
assert focus_events[0].detail_json["action"] == "switch_focus"
assert focus_events[0].detail_json["source"] == "tool_api"
assert focus_events[0].detail_json["previous_focus_task_no"] == task_rows[0].task_no
assert focus_events[0].detail_json["next_focus_task_no"] == task_rows[1].task_no
def test_workspace_submit_decision_updates_reference_context_last_action(app, client):
"""用户在工作台点击确认后,下次 runtime_context 应暴露标准 confirm 动作。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-WS-CONFIRM-001",
user_id=user.id,
conversation_id="conv-ws-confirm-001",
current_focus_task_no="SN-WS-CONFIRM-001",
file_count=1,
)
task = ShippingTask(
task_no="SN-WS-CONFIRM-001",
batch=batch,
user_id=user.id,
conversation_id="conv-ws-confirm-001",
source_type="manual",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
raw_content="客户:ACME\nA001 x 10",
)
db.session.add_all([batch, task])
db.session.commit()
res = client.post(
"/api/workspace/shipping-tasks/SN-WS-CONFIRM-001/submit-decision",
headers=headers,
json={"decision": "confirm", "comment": "用户确认"},
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] in {"ok", "running"}
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-WS-CONFIRM-001").one()
event = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="parse_confirmed")
.order_by(ShippingTaskEvent.id.desc())
.first()
)
assert event is not None
assert event.detail_json["action"] == "confirm"
assert event.detail_json["source"] == "workspace_api"
inputs = dify_inputs.build_dify_chat_inputs("conv-ws-confirm-001")
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["reference_context"]["last_action_target"] == {
"type": "task",
"id": "SN-WS-CONFIRM-001",
"action": "confirm_parse",
}
def test_workspace_switch_focus_updates_reference_context(app, client):
"""用户切换 focus 后,下次 runtime_context 应同时反映新的 focus_object 与 switch_focus 动作。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-WS-FOCUS-001",
user_id=user.id,
conversation_id="conv-ws-focus-001",
current_focus_task_no="SN-WS-FOCUS-001",
file_count=2,
)
old_focus = ShippingTask(
task_no="SN-WS-FOCUS-001",
batch=batch,
user_id=user.id,
conversation_id="conv-ws-focus-001",
source_type="manual",
process_status="created",
batch_index=1,
batch_total=2,
)
new_focus = ShippingTask(
task_no="SN-WS-FOCUS-002",
batch=batch,
user_id=user.id,
conversation_id="conv-ws-focus-001",
source_type="manual",
process_status="pending_review",
match_status="shortage",
pending_human_reason="shortage",
shortage_json={"A001": 3},
batch_index=2,
batch_total=2,
)
db.session.add_all([batch, old_focus, new_focus])
db.session.commit()
res = client.post(
"/api/workspace/shipping-batches/SB-WS-FOCUS-001/focus-task",
headers=headers,
json={"task_no": "SN-WS-FOCUS-002", "comment": "切到异常票"},
)
assert res.status_code == 200
data = res.get_json()
assert data["batch"]["current_focus_task_no"] == "SN-WS-FOCUS-002"
with app.app_context():
target = ShippingTask.query.filter_by(task_no="SN-WS-FOCUS-002").one()
event = (
ShippingTaskEvent.query.filter_by(task_id=target.id, event_type="focus_switched")
.order_by(ShippingTaskEvent.id.desc())
.first()
)
assert event is not None
assert event.detail_json["action"] == "switch_focus"
assert event.detail_json["source"] == "workspace_api"
assert event.detail_json["previous_focus_task_no"] == "SN-WS-FOCUS-001"
assert event.detail_json["next_focus_task_no"] == "SN-WS-FOCUS-002"
inputs = dify_inputs.build_dify_chat_inputs("conv-ws-focus-001")
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["reference_context"]["focus_object"]["id"] == "SN-WS-FOCUS-002"
assert runtime_context["reference_context"]["last_action_target"] == {
"type": "task",
"id": "SN-WS-FOCUS-002",
"action": "switch_focus",
}
assert runtime_context["reference_context"]["last_failed_target"]["id"] == "SN-WS-FOCUS-002"
assert "candidates" not in runtime_context["reference_context"]
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)
res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"notice_items": [
{
"source_file_name": "notice-a.txt",
"raw_text": "客户:ACME 料号A001 x 10",
},
],
},
)
assert res.status_code == 200
data = res.get_json()
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.raw_content
assert not (task.lines_json or [])
def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
"""聊天/工作台批量上传通知时应返回 envelope,并仅落 raw_text,首轮解析延后到 Dify。"""
headers = _workspace_headers(app)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-001",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
result = _unwrap_ok(res)
assert result["status"] == "ok"
assert result["batch_no"].startswith("SB-")
assert result["data"]["batch"]["batch_no"] == result["batch_no"]
assert result["data"]["tasks"][0]["parse_status"] == "deferred"
assert result["data"]["focus_task"]["task_no"] == result["data"]["tasks"][0]["task_id"]
file_summary = result["file_summary"]
assert file_summary["total_files"] == 1
assert file_summary["accepted_count"] == 1
assert file_summary["rejected_count"] == 0
assert file_summary["duplicate_count"] == 0
assert file_summary["accepted_files"][0]["filename"] == "notice-a.txt"
assert len(file_summary["accepted_files"][0]["content_hash"]) == 64
assert file_summary["rejected_files"] == []
assert file_summary["duplicate_files"] == []
with app.app_context():
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.raw_content
assert task.process_status == "created"
assert len(task.lines_json or []) == 0
def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(app, client, monkeypatch):
"""开启编排器时,工作台上传接口应返回 orchestrator_started。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"] = True
started: list[str] = []
def fake_start(batch_no: str | None) -> bool:
if batch_no:
started.append(batch_no)
return True
monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-002",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
result = _unwrap_ok(res)
assert result["status"] == "ok"
assert result["data"]["orchestrator_started"] is True
assert started == [result["batch_no"]]
def test_workspace_create_batch_from_notices_skips_failed_files_and_keeps_batch_non_empty(app, client, monkeypatch, tmp_path):
"""部分文件抽取失败时,只为成功文件建任务,并回传 rejected_files 摘要。"""
from app.services.shipping_notice import notice_upload
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
with app.app_context():
batch_count_before = ShippingBatch.query.count()
task_count_before = ShippingTask.query.count()
def fake_extract_notice_text(saved_path: str):
name = str(saved_path).replace("\\", "/")
if name.endswith("/notice-a.txt"):
return "客户:ACME\nA001 x 10", {"warnings": []}
if name.endswith("/notice-b.pdf"):
return "", {"warnings": ["ocr_empty"]}
raise AssertionError(f"unexpected saved_path: {saved_path}")
monkeypatch.setattr(notice_upload, "extract_notice_text", fake_extract_notice_text)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": [
(BytesIO("ok".encode("utf-8")), "notice-a.txt"),
(BytesIO(b"%PDF-1.4"), "notice-b.pdf"),
],
"conversation_id": "conv-workspace-batch-partial",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
result = _unwrap_ok(res)
assert result["status"] == "ok"
assert result["file_summary"]["accepted_count"] == 1
assert result["file_summary"]["rejected_count"] == 1
assert len(result["data"]["tasks"]) == 1
assert result["file_summary"]["accepted_files"][0]["filename"] == "notice-a.txt"
assert result["file_summary"]["rejected_files"] == [
{
"filename": "notice-b.pdf",
"source_type": "pdf",
"source_file_type": "application/pdf",
"reason": "empty_text",
"message": "notice text is empty after extraction",
"warnings": ["ocr_empty"],
}
]
with app.app_context():
assert ShippingBatch.query.count() == batch_count_before + 1
assert ShippingTask.query.count() == task_count_before + 1
batch = ShippingBatch.query.filter_by(batch_no=result["batch_no"]).one()
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).one()
assert batch.file_count == 1
assert batch.current_focus_task_no == task.task_no
assert task.source_file_name == "notice-a.txt"
assert not (tmp_path / "notice_uploads" / "_tmp").exists()
def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_creating_batch(app, client, monkeypatch, tmp_path):
"""全部文件失败或空文本时,应直接报 ValidationError,且不创建空 batch/task。"""
from app.services.shipping_notice import notice_upload
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
with app.app_context():
batch_count_before = ShippingBatch.query.count()
task_count_before = ShippingTask.query.count()
monkeypatch.setattr(
notice_upload,
"extract_notice_text",
lambda saved_path: ("", {"warnings": ["ocr_empty"]}),
)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": [
(BytesIO(b"%PDF-1.4"), "notice-a.pdf"),
(BytesIO(b"%PDF-1.4"), "notice-b.pdf"),
],
"conversation_id": "conv-workspace-batch-all-failed",
},
content_type="multipart/form-data",
)
assert res.status_code == 400
payload = res.get_json()
assert payload["success"] is False
assert payload["error"]["message"] == "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试"
file_summary = payload["error"]["details"]["file_summary"]
assert file_summary["accepted_count"] == 0
assert file_summary["rejected_count"] == 1
assert file_summary["duplicate_count"] == 1
assert file_summary["rejected_files"] == [
{
"filename": "notice-a.pdf",
"source_type": "pdf",
"source_file_type": "application/pdf",
"reason": "empty_text",
"message": "notice text is empty after extraction",
"warnings": ["ocr_empty"],
},
]
assert file_summary["duplicate_files"][0]["filename"] == "notice-b.pdf"
assert file_summary["duplicate_files"][0]["duplicate_of"] == "notice-a.pdf"
with app.app_context():
assert ShippingBatch.query.count() == batch_count_before
assert ShippingTask.query.count() == task_count_before
assert not (tmp_path / "notice_uploads" / "_tmp").exists()
def test_parse_notice_empty_result_requires_reupload_instead_of_review(app):
"""无订单行且无单头字段时,不应生成空审核卡片,应停在重新上传/清洗节点。"""
with app.app_context():
user = User(username="shipping_empty_parse_user", email="shipping_empty_parse_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-EMPTY-PARSE-001",
user_id=user.id,
source_type="pdf",
process_status="created",
raw_content="This PDF extraction contains no order table.",
)
db.session.add(task)
db.session.commit()
result = shipping_tools.parse_notice({"task_id": task.task_no})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "notice_text_extraction_failed"
assert [button["id"] for button in result["action_buttons"]] == [
"replace_notice_file",
"reparse",
"reject",
]
assert task.pending_human_reason == "notice_text_extraction_failed"
assert task.review_status is None
assert task.lines_json == []
assert "重新上传" in result["message"]
def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app, client):
"""重新上传当前任务通知应保留 task_no/batch_no,只覆盖正文并清理旧解析结果。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-REPLACE-NOTICE-001",
user_id=user.id,
conversation_id="conv-replace-notice",
current_focus_task_no="SN-REPLACE-NOTICE-001",
file_count=1,
)
db.session.add(batch)
db.session.flush()
task = ShippingTask(
task_no="SN-REPLACE-NOTICE-001",
batch_id=batch.id,
user_id=user.id,
conversation_id="conv-replace-notice",
source_type="pdf",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
raw_content="old text",
source_file_name="old.pdf",
lines_json=[{"sku": "OLD", "qty": 1}],
match_status="shortage",
shortage_json={"OLD": 1},
export_file_name="old.xlsx",
)
db.session.add(task)
db.session.commit()
original_batch_count = ShippingBatch.query.count()
original_task_count = ShippingTask.query.count()
res = client.post(
"/api/workspace/shipping-tasks/SN-REPLACE-NOTICE-001/replace-notice",
headers=headers,
data={"file": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "new-notice.txt")},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = _unwrap_ok(res)
assert data["status"] in {"ok", "running"}
assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001"
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-REPLACE-NOTICE-001").one()
assert ShippingBatch.query.count() == original_batch_count
assert ShippingTask.query.count() == original_task_count
assert task.batch.batch_no == "SB-REPLACE-NOTICE-001"
assert task.raw_content == "客户:ACME\nA001 x 10"
assert task.source_file_name == "new-notice.txt"
assert task.lines_json == []
assert task.review_status is None
assert task.pending_human_reason is None
assert task.match_status is None
assert task.shortage_json is None
assert task.export_file_name is None
def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = ""
with app.app_context():
user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-STEP-001",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
current_step="step2_parse_confirm",
step_payload_json={
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
}
},
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inv_unavail"
assert task.current_step == "step3_inventory_prepare"
assert task.step_payload_json["current_step_progress"]["status"] == "needs_human"
from app.services.shipping_notice.ui_state import build_task_ui_state
ui_state = build_task_ui_state(task)
inventory_step = next(step for step in ui_state["steps"] if step["code"] == "inventory_prepare")
assert inventory_step["status"] == "blocked"
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
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 5
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
task = ShippingTask(
task_no="SN-RPA-RECHECK-001",
user_id=user.id,
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
step_payload_json={
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"},
}
},
)
db.session.add(task)
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=10),
)
)
db.session.commit()
res = client.get("/api/workspace/shipping-tasks/SN-RPA-RECHECK-001", headers=headers)
assert res.status_code == 200
data = _unwrap_ok(res)
assert data["process_status"] == "waiting_inventory"
assert data["pending_human_reason"] == "rpa_pending"
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-RPA-RECHECK-001").one()
events = ShippingTaskEvent.query.filter_by(task_id=task.id).order_by(ShippingTaskEvent.id.asc()).all()
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) == 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):
"""目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers")
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
with app.app_context():
user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-DUB",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="Ship to Dublin DUB\nA001 x 10",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 10}],
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "running"
source = task.step_payload_json["rpa_inventory_source"]
assert source["source_code"] == "DSV360_AWSDU"
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
assert trigger_path.exists()
trigger_text = trigger_path.read_text(encoding="utf-8")
assert '"source_code": "DSV360_AWSDU"' in trigger_text
assert '"connector_type": "dsv360"' in trigger_text
def test_inventory_source_rules_cover_dsv360_programs(app):
"""截图中的 DSV 360 Program 均应能通过别名解析到对应库存源。"""
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
cases = [
("BYAWSATL01", "DSV360_AWSBI_BYAWSATL01"),
("Cincinnati", "DSV360_AWSCV"),
("Moerdijk", "DSV360_AWSAMS"),
]
with app.app_context():
for ship_to, expected_code in cases:
task = ShippingTask(
task_no=f"SN-INVENTORY-SOURCE-{expected_code}",
source_type="pdf",
process_status="parsed",
ship_to=ship_to,
lines_json=[{"sku": "A001", "qty": 10}],
)
resolution = resolve_inventory_source(task)
assert resolution.status == "resolved"
assert resolution.source_code == expected_code
def test_auto_progress_unknown_destination_requires_inventory_source_review(app):
"""无法根据目的地唯一判断库存源时,应停在库存源人工确认检查点。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
with app.app_context():
user = User(username="shipping_inventory_source_unknown", email="shipping_inventory_source_unknown@example.com")
db.session.add(user)
db.session.flush()
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-UNKNOWN",
user_id=user.id,
source_type="pdf",
process_status="parsed",
parse_confidence=0.95,
raw_content="Ship to Mystery Port\nA001 x 10",
ship_to="Mystery Port",
lines_json=[{"sku": "A001", "qty": 10}],
)
db.session.add(task)
db.session.commit()
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "inventory_source_review"
assert task.process_status == "pending_review"
assert task.pending_human_reason == "inventory_source_unresolved"
assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved"
assert len(result["data"]["inventory_source_candidates"]) >= 4
def test_inventory_source_review_chat_actions_return_source_buttons(app):
"""库存源待确认且只有一个候选时,统一 UI State 会携带具体 source_code。"""
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-ACTIONS",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
}
],
}
},
)
ui_state = build_task_ui_state(task)
assert ui_state["checkpoint"] == "inventory_source_review"
first = ui_state["action_buttons"][0]
assert first["id"] == "confirm_inventory_source"
assert first["source_code"] == "DSV360_AWSDU"
assert first["label"] == "确认:DSV 360 / Dublin / AWSDU - Prod (JDA)"
assert ui_state["current_step"]["code"] == "inventory_prepare"
def test_inventory_source_review_chat_actions_do_not_list_all_sources(app):
"""库存源候选很多时,统一 UI State 不应把全部数据源铺成按钮。"""
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
task = ShippingTask(
task_no="SN-INVENTORY-SOURCE-MANY-ACTIONS",
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason="inventory_source_unresolved",
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
"candidates": [
{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"display_name": "DSV 360 / Bison / AWSBI / BYAWSATL01",
},
{
"source_code": "DSV360_AWSDU",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
},
],
}
},
)
ui_state = build_task_ui_state(task)
source_buttons = [
item for item in ui_state["action_buttons"]
if item["id"] == "confirm_inventory_source" and item.get("source_code")
]
assert source_buttons == []
assert [item["id"] for item in ui_state["action_buttons"]] == [
"confirm_inventory_source",
"retry_resolve_inventory_source",
"upload_inventory_file",
]
def test_parse_stage_ui_state_lists_all_issues(app):
"""文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。"""
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
task = ShippingTask(
task_no="SN-PARSE-ISSUES-LIST",
source_type="pdf",
process_status="pending_review",
pending_human_reason="inventory_source_unresolved",
error_message="无法根据发货通知唯一确定库存查询来源",
parse_confidence=0.4,
step_payload_json={
"pending_parse_review_after_source": True,
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
"parse_validation": {
"status": "needs_review",
"issues": [
{
"line_index": 0,
"sku": "A001",
"field": "reservation_id",
"reason": "invalid_format",
"severity": "blocking",
"raw_value": "1f1a682dfdc446a393415dee93eb36ce",
}
],
},
"current_step_progress": {
"extra": {
"warnings": [
"部分订单行缺少 Reservation ID,可能影响精确匹配。",
"parse_fallback_heuristic",
]
}
},
},
)
ui_state = build_task_ui_state(task)
issues = ui_state["summary"]["issues"]
assert ui_state["checkpoint"] == "inventory_source_review"
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
assert "第 1 行 SKU A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
assert len(issues) == 5
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
"""任务/批次工作台读接口直接返回 UI State,Chat 和工作台不再各自推导状态。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch = ShippingBatch(
batch_no="SB-UI-STATE-001",
user_id=user.id,
current_focus_task_no="SN-UI-STATE-001",
file_count=1,
)
task = ShippingTask(
task_no="SN-UI-STATE-001",
source_type="pdf",
user_id=user.id,
batch=batch,
batch_index=1,
batch_total=1,
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
)
db.session.add_all([batch, task])
db.session.commit()
task_state_res = client.get("/api/workspace/shipping-tasks/SN-UI-STATE-001/ui-state", headers=headers)
task_detail_res = client.get("/api/workspace/shipping-tasks/SN-UI-STATE-001", headers=headers)
batch_detail_res = client.get("/api/workspace/shipping-batches/SB-UI-STATE-001", headers=headers)
batch_state_res = client.get("/api/workspace/shipping-batches/SB-UI-STATE-001/ui-state", headers=headers)
assert task_state_res.status_code == 200
assert task_detail_res.status_code == 200
assert batch_detail_res.status_code == 200
assert batch_state_res.status_code == 200
task_state = _unwrap_ok(task_state_res)
task_detail = _unwrap_ok(task_detail_res)
batch_detail = _unwrap_ok(batch_detail_res)
batch_state = _unwrap_ok(batch_state_res)
assert task_state["checkpoint"] == "shortage_review"
assert [item["id"] for item in task_state["action_buttons"]] == [
"reparse_inventory",
"rematch",
"reject",
]
assert "correct_inventory_mapping" not in [item["id"] for item in task_state["action_buttons"]]
assert task_detail["ui_state"]["action_buttons"] == task_state["action_buttons"]
assert task_state["current_step"]["status"] == "blocked"
assert batch_detail["focus_task_ui_state"]["task_no"] == "SN-UI-STATE-001"
assert batch_state["focus_task_ui_state"]["task_no"] == "SN-UI-STATE-001"
assert batch_state["tasks"][0]["ui_state"]["action_buttons"] == task_state["action_buttons"]
def test_chat_completions_streams_shipping_ui_state(app, client, monkeypatch):
"""发货通知聊天流应先下发状态机 UI State,前端无需等待 Dify 正文结束才显示按钮。"""
from app.services import dify as dify_module
with app.app_context():
user = User(
username="shipping_stream_user",
email="shipping_stream_user@example.com",
role="user",
status="active",
)
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
is_active=True,
)
user.agents.append(agent)
batch = ShippingBatch(
batch_no="SB-STREAM-UI-STATE",
user_id=user.id,
conversation_id="conv-stream-ui-state",
current_focus_task_no="SN-STREAM-UI-STATE",
file_count=1,
)
task = ShippingTask(
task_no="SN-STREAM-UI-STATE",
batch=batch,
user_id=user.id,
conversation_id="conv-stream-ui-state",
source_type="pdf",
process_status="pending_review",
review_status="shortage_review",
pending_human_reason="shortage",
)
db.session.add_all([user, agent, batch, task])
db.session.commit()
user_id = user.id
agent_id = agent.id
def fake_stream_chat(*args, **kwargs):
yield 'data: {"event":"message","answer":"当前库存不足。"}\n\n'
yield 'data: {"event":"message_end","answer":"","conversation_id":"dify-conv"}\n\n'
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
res = client.post(
"/api/chat/completions",
headers={
"X-User-Id": str(user_id),
"X-Username": "shipping_stream_user",
"X-Role": "user",
"Content-Type": "application/json",
},
json={
"agent_id": agent_id,
"query": "继续处理当前任务",
"conversation_id": "conv-stream-ui-state",
"task_id": "SN-STREAM-UI-STATE",
"batch_no": "SB-STREAM-UI-STATE",
},
)
body = res.get_data(as_text=True)
assert res.status_code == 200
assert '"event": "shipping_ui_state"' in body
assert '"task_no": "SN-STREAM-UI-STATE"' in body
assert '"checkpoint": "shortage_review"' in body
assert '"action_buttons"' in body
def test_chat_completions_streams_order_extraction_terminal_ui_state(app, client, monkeypatch):
"""事务提交并解绑 ORM 后仍须调用 Dify,并按本轮 Intake 补发权威 Batch UI State。"""
from app.services import dify as dify_module
from app.services.shipping_notice import order_extraction as order_extraction_module
with app.app_context():
user = User(
username="shipping_extraction_stream_user",
email="shipping_extraction_stream_user@example.com",
role="user",
status="active",
)
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
is_active=True,
)
user.agents.append(agent)
db.session.add_all([user, agent])
db.session.flush()
session = ChatSession(
session_id="conv-extraction-terminal-ui-state",
user_id=user.id,
agent_id=agent.id,
title="Order extraction",
)
asset = FileAsset(
asset_no="FA-EXTRACTION-STREAM",
owner_user_id=user.id,
original_filename="orders.eml",
storage_provider="minio",
storage_bucket="test",
storage_key="test/orders.eml",
content_hash="extraction-stream-hash",
file_size=128,
mime_type="message/rfc822",
upload_status="ready",
lifecycle_status="referenced",
)
batch = ShippingBatch(
batch_no="SB-EXTRACTION-STREAM",
user_id=user.id,
conversation_id=session.session_id,
current_focus_task_no="SN-EXTRACTION-STREAM",
file_count=1,
)
task = ShippingTask(
task_no="SN-EXTRACTION-STREAM",
batch=batch,
user_id=user.id,
conversation_id=session.session_id,
source_type="email",
process_status="pending_review",
pending_human_reason="rsv_req",
)
db.session.add_all([session, asset, batch, task])
db.session.flush()
intake = ShippingNoticeIntake(
intake_no="SNI-EXTRACTION-STREAM",
asset_id=asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose="shipping_notice",
parse_status="parsed",
parser_version="v6",
order_extraction_status="not_started",
)
db.session.add(intake)
db.session.commit()
user_id = user.id
agent_id = agent.id
dify_called = False
original_start_order_extraction = order_extraction_module.start_order_extraction
def detaching_start_order_extraction(**kwargs):
"""模拟生产流开始前原请求 scoped session 已清理,强制暴露 ORM 跨流引用。"""
result = original_start_order_extraction(**kwargs)
db.session.expunge_all()
return result
def fake_stream_chat(*args, **kwargs):
nonlocal dify_called
dify_called = True
# 模拟 Dify submit_order_extraction Tool 在 terminal 前提交消费关系。
with app.app_context():
intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-STREAM").one()
batch = ShippingBatch.query.filter_by(batch_no="SB-EXTRACTION-STREAM").one()
intake.parse_status = "consumed"
intake.order_extraction_status = "completed"
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = batch.id
db.session.commit()
yield 'data: {"event":"message","answer":"已创建发货任务。"}\n\n'
yield 'data: {"event":"workflow_finished","answer":"","conversation_id":"dify-extraction-conv"}\n\n'
monkeypatch.setattr(order_extraction_module, "start_order_extraction", detaching_start_order_extraction)
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
res = client.post(
"/api/chat/completions",
headers={
"X-User-Id": str(user_id),
"X-Username": "shipping_extraction_stream_user",
"X-Role": "user",
"Content-Type": "application/json",
},
json={
"agent_id": agent_id,
"query": "请解析邮件并自动建单",
"conversation_id": "conv-extraction-terminal-ui-state",
"shipping_intake_nos": ["SNI-EXTRACTION-STREAM"],
},
)
body = res.get_data(as_text=True)
assert res.status_code == 200
# 关键断言:prepare_stream 提交事务并解绑 ORM 后,relay 首帧仍可发送且 Dify generator 必须被迭代。
assert dify_called is True
assert '"event": "session_created"' in body
assert '"event": "message", "answer": "已创建发货任务。"' in body
assert '"event": "shipping_ui_state"' in body
assert '"source": "order_extraction"' in body
assert '"batch_no": "SB-EXTRACTION-STREAM"' in body
assert '"task_no": "SN-EXTRACTION-STREAM"' in body
assert body.index('"event": "workflow_finished"') < body.rindex('"event": "shipping_ui_state"')
@pytest.mark.parametrize('failure_mode', ['sse_error', 'relay_exception'])
def test_chat_completions_closes_order_extraction_on_upstream_error(
app,
client,
monkeypatch,
failure_mode,
):
"""Dify SSE error 或 relay 异常都必须即时收口,不能等待五分钟超时。"""
from app.services import dify as dify_module
with app.app_context():
user = User(
username="shipping_extraction_error_user",
email="shipping_extraction_error_user@example.com",
role="user",
status="active",
)
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
is_active=True,
)
user.agents.append(agent)
db.session.add_all([user, agent])
db.session.flush()
session = ChatSession(
session_id="conv-extraction-upstream-error",
user_id=user.id,
agent_id=agent.id,
title="Order extraction error",
)
asset = FileAsset(
asset_no="FA-EXTRACTION-ERROR",
owner_user_id=user.id,
original_filename="orders-error.eml",
storage_provider="minio",
storage_bucket="test",
storage_key="test/orders-error.eml",
content_hash="extraction-error-hash",
file_size=128,
mime_type="message/rfc822",
upload_status="ready",
lifecycle_status="referenced",
)
db.session.add_all([session, asset])
db.session.flush()
intake = ShippingNoticeIntake(
intake_no="SNI-EXTRACTION-ERROR",
asset_id=asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose="shipping_notice",
parse_status="parsed",
parser_version="v6",
order_extraction_status="not_started",
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type="attachment",
attachment_key="orders-error.pdf",
filename="orders-error.pdf",
content_hash="extraction-error-document-hash",
classification="order_notice",
parse_status="parsed",
extracted_text="SKU ERROR-SKU QTY 1",
)
db.session.add(document)
db.session.commit()
user_id = user.id
agent_id = agent.id
def fake_stream_chat(*args, **kwargs):
"""模拟 Dify 主动返回 error,或流迭代期间直接抛出异常。"""
if failure_mode == 'relay_exception':
raise RuntimeError('Dify connection reset')
yield 'data: {"event":"error","message":"Dify unavailable"}\n\n'
monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat))
res = client.post(
"/api/chat/completions",
headers={
"X-User-Id": str(user_id),
"X-Username": "shipping_extraction_error_user",
"X-Role": "user",
"Content-Type": "application/json",
},
json={
"agent_id": agent_id,
"query": "请解析邮件并自动建单",
"conversation_id": "conv-extraction-upstream-error",
"shipping_intake_nos": ["SNI-EXTRACTION-ERROR"],
},
)
body = res.get_data(as_text=True)
assert res.status_code == 200
assert '"event": "error"' in body
with app.app_context():
intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-ERROR").one()
document = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).one()
assert intake.order_extraction_status == "failed"
assert intake.order_extraction_error_code == "SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED"
assert intake.order_extraction_error_message == (
"Dify connection reset" if failure_mode == 'relay_exception' else "Dify unavailable"
)
assert document.order_extraction_status == "failed"
def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client):
"""同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。"""
headers = _workspace_headers(app)
with app.app_context():
user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
assert user is not None
batch_a = ShippingBatch(
batch_no="SB-CONV-WS-A",
user_id=user.id,
conversation_id="conv-workspace-multi",
current_focus_task_no="SN-20260626-CONVA001",
file_count=2,
)
batch_b = ShippingBatch(
batch_no="SB-CONV-WS-B",
user_id=user.id,
conversation_id="conv-workspace-multi",
current_focus_task_no="SN-20260626-CONVB001",
file_count=2,
)
other_batch = ShippingBatch(
batch_no="SB-CONV-WS-OTHER",
user_id=user.id,
conversation_id="conv-workspace-other",
file_count=1,
)
db.session.add_all([batch_a, batch_b, other_batch])
db.session.flush()
db.session.add_all([
ShippingTask(
task_no="SN-20260626-CONVA001",
batch_id=batch_a.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="uploaded",
batch_index=1,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVA002",
batch_id=batch_a.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="matched",
batch_index=2,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVB001",
batch_id=batch_b.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="waiting_inventory",
review_status="align_review",
batch_index=1,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-CONVB002",
batch_id=batch_b.id,
user_id=user.id,
conversation_id="conv-workspace-multi",
source_type="manual",
process_status="matched",
upload_status="failed",
batch_index=2,
batch_total=2,
),
ShippingTask(
task_no="SN-20260626-OTHER001",
batch_id=other_batch.id,
user_id=user.id,
conversation_id="conv-workspace-other",
source_type="manual",
process_status="uploaded",
batch_index=1,
batch_total=1,
),
])
db.session.commit()
res = client.get(
"/api/workspace/shipping-conversations/conv-workspace-multi/batch-workspace",
headers=headers,
)
assert res.status_code == 200
data = _unwrap_ok(res)
assert data["conversation_id"] == "conv-workspace-multi"
assert data["summary"] == {
"batch_count": 2,
"total": 4,
"completed": 1,
"running": 1,
"failed": 1,
"needs_human": 1,
"pending": 0,
}
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-WS-A", "SB-CONV-WS-B"]
assert data["batches"][0]["focus_task"]["task_no"] == "SN-20260626-CONVA001"
assert len(data["batches"][1]["tasks"]) == 2
assert "ui_state" in data["batches"][0]["tasks"][0]
assert isinstance(data["batches"][0]["tasks"][0]["ui_state"]["action_buttons"], list)
def test_workspace_conversation_batch_workspace_filters_by_user(app, client):
"""会话级工作台只能返回当前用户可访问的批次。"""
headers = _workspace_headers(app)
with app.app_context():
current = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first()
other = User(
username="shipping_workspace_other",
email="shipping_workspace_other@example.com",
role="user",
status="active",
)
other.set_password("password")
db.session.add(other)
db.session.flush()
own_batch = ShippingBatch(
batch_no="SB-CONV-OWN",
user_id=current.id,
conversation_id="conv-workspace-secure",
file_count=1,
)
foreign_batch = ShippingBatch(
batch_no="SB-CONV-FOREIGN",
user_id=other.id,
conversation_id="conv-workspace-secure",
file_count=1,
)
db.session.add_all([own_batch, foreign_batch])
db.session.flush()
db.session.add_all([
ShippingTask(
task_no="SN-20260626-OWN00001",
batch_id=own_batch.id,
user_id=current.id,
conversation_id="conv-workspace-secure",
source_type="manual",
process_status="created",
),
ShippingTask(
task_no="SN-20260626-FGN00001",
batch_id=foreign_batch.id,
user_id=other.id,
conversation_id="conv-workspace-secure",
source_type="manual",
process_status="uploaded",
),
])
db.session.commit()
res = client.get(
"/api/workspace/shipping-conversations/conv-workspace-secure/batch-workspace",
headers=headers,
)
assert res.status_code == 200
data = _unwrap_ok(res)
assert data["summary"]["batch_count"] == 1
assert [item["batch_no"] for item in data["batches"]] == ["SB-CONV-OWN"]
def test_shipping_orchestrator_enqueues_generic_job_not_kb_job(app):
"""发货通知后台编排应写入通用 jobs,不能污染 kb_jobs。"""
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
batch = ShippingBatch(batch_no="SB-JOBS-QUEUE", file_count=1, user_id=123)
task = ShippingTask(
task_no="SN-20260626-JOBS0001",
batch=batch,
user_id=123,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
started = batch_orchestrator.start_task_orchestrator(task.task_no)
assert started is True
job = Job.query.filter_by(
domain="shipping_notice",
job_type="shipping_notice_run",
business_ref=task.task_no,
).first()
assert job is not None
assert job.status == "queued"
assert job.payload_json["task_no"] == task.task_no
assert KbJob.query.filter_by(job_type="shipping_notice_run").count() == 0
def test_process_shipping_job_survives_session_remove(app, monkeypatch):
"""Job Runner 应能处理业务编排内部 db.session.remove 后的状态回写。"""
app.config["SHIPPING_NOTICE_TASK_EXECUTION_MODE"] = "worker"
with app.app_context():
job = Job(
domain="shipping_notice",
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status="queued",
business_ref="SN-20260626-DETACHED1",
payload_json={"task_no": "SN-20260626-DETACHED1"},
message="等待后台处理发货任务",
)
db.session.add(job)
db.session.commit()
job_id = job.id
def fake_run_single_task(task_no: str):
db.session.remove()
return {"status": "ok", "message": f"done {task_no}"}
monkeypatch.setattr(batch_orchestrator, "_run_single_task", fake_run_single_task)
ctx = JobContext(config=dict(app.config), logger=app.logger, extras={"queues": ["shipping"]})
processed, message = process_next_job(
ctx=ctx,
domain="shipping_notice",
job_types=[JobType.SHIPPING_NOTICE_RUN],
timeout_config_key="SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS",
)
assert processed is True
assert message == JobType.SHIPPING_NOTICE_RUN.value
refreshed = db.session.get(Job, job_id)
assert refreshed is not None
assert refreshed.status == "success"
assert refreshed.result_json["status"] == "ok"
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE", file_count=1)
task = ShippingTask(
task_no="SN-20260622-AAAA0001",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
called["dify"] = task_ref
return {"status": "ok", "message": "parsed-by-dify"}
def fake_auto_progress(payload):
raise AssertionError("created task should not call auto_progress when auto_progress is disabled")
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert called.get("dify") == task_no
def test_submit_reparse_resets_task_and_starts_dify_orchestrator(app, monkeypatch):
"""重新解析必须回退到 created 并交给后台 Dify,不允许同步启发式解析。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-REPARSE-DIFY", file_count=1)
task = ShippingTask(
task_no="SN-20260629-REPARSE1",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
lines_json=[{"sku": "OLD", "qty": 1}],
parse_confidence=0.42,
match_status="shortage",
shortage_json={"OLD": 1},
line_results_json=[{"sku": "OLD", "status": "shortage"}],
inventory_lines_json=[{"sku": "OLD", "available_qty": 0}],
error_message="old error",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
started: list[str] = []
def fake_start(task_ref: str | None) -> bool:
if task_ref:
started.append(task_ref)
return True
monkeypatch.setattr(
"app.services.shipping_notice.decision_workflow.start_task_orchestrator",
fake_start,
)
result = shipping_tools.submit_decision({"task_id": task_no, "decision": "reparse"})
db.session.refresh(task)
assert result["status"] == "running"
assert started == [task_no]
assert task.process_status == "created"
assert task.review_status is None
assert task.pending_human_reason is None
assert task.lines_json == []
assert task.parse_confidence is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.inventory_lines_json is None
assert task.error_message is None
assert "Dify" in result["message"]
assert "【发货通知解析确认】" not in result["message"]
def test_run_single_task_refreshes_after_dify_parse_before_auto_progress(app, monkeypatch):
"""Dify Tool 提交解析结果后,编排器应刷新 session 并继续触发自动推进。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE-FOLLOW", file_count=1)
task = ShippingTask(
task_no="SN-20260629-FOLLOW01",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
stmt = (
ShippingTask.__table__.update()
.where(ShippingTask.__table__.c.task_no == task_ref)
.values(
process_status="parsed",
review_status=None,
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
)
)
with db.engine.begin() as conn:
conn.execute(stmt)
return {"status": "ok", "message": "parsed-by-dify"}
def fake_auto_progress(payload):
called["auto_progress"] = payload
return {"status": "running", "message": "rpa triggered"}
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task_no)
assert result["status"] == "running"
assert isinstance(called.get("auto_progress"), dict)
assert called["auto_progress"]["task_id"] == task_no
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-AUTO", file_count=1)
task = ShippingTask(
task_no="SN-20260622-BBBB0002",
batch=batch,
source_type="manual",
process_status="parsed",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
raise AssertionError(f"parsed task should not call dify parse executor: {task_ref}")
def fake_auto_progress(payload):
called["auto_progress"] = payload
return {"status": "ok", "message": "advanced"}
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert isinstance(called.get("auto_progress"), dict)
assert called["auto_progress"]["task_id"] == task_no
def test_run_shipping_parse_via_dify_passes_task_context_without_persisting_chat(app, monkeypatch):
"""后台 Dify 执行器应带当前任务上下文,但不复用/污染前端聊天记录。"""
with app.app_context():
user = User(
username="shipping_dify_user",
email="shipping_dify_user@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.flush()
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
dify_api_key="test-dify-key",
is_active=True,
)
db.session.add(agent)
db.session.flush()
session = ChatSession(
session_id="conv-shipping-dify-001",
user_id=user.id,
agent_id=agent.id,
title="shipping parse",
status="running",
external_conversation_id="22222222-2222-2222-2222-222222222222",
)
batch = ShippingBatch(
batch_no="SB-DIFY-EXEC",
user_id=user.id,
conversation_id=session.session_id,
file_count=1,
)
task = ShippingTask(
task_no="SN-20260622-CCCC0003",
batch=batch,
user_id=user.id,
conversation_id=session.session_id,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([session, batch, task])
db.session.commit()
captured: dict[str, object] = {}
def fake_stream_chat(query, user_id, agent_obj, conversation_id=None, **kwargs):
captured["query"] = query
captured["user_id"] = user_id
captured["agent_id"] = agent_obj.id
captured["conversation_id"] = conversation_id
captured["session_id"] = kwargs.get("session_id")
captured["inputs"] = kwargs.get("inputs")
captured["persist_chat_log"] = kwargs.get("persist_chat_log")
yield 'data: {"event":"message_end","conversation_id":"11111111-1111-1111-1111-111111111111","answer":"parsed"}\n\n'
monkeypatch.setattr(dify_executor.DifyService, "stream_chat", staticmethod(fake_stream_chat))
result = dify_executor.run_shipping_parse_via_dify(task.task_no)
assert result["status"] == "ok"
assert captured["query"] == "解析当前发货通知任务"
assert captured["user_id"] == user.id
assert captured["agent_id"] == agent.id
assert captured["conversation_id"] is None
assert captured["session_id"] == session.session_id
assert captured["persist_chat_log"] is False
assert isinstance(captured["inputs"], dict)
runtime_context = json.loads(captured["inputs"]["agent_runtime_context"])
assert runtime_context["schema_version"] == "1"
assert runtime_context["agent_code"] == "shipping_notice"
assert runtime_context["scope"] == "task_run"
assert runtime_context["platform"]["session_id"] == session.session_id
assert runtime_context["platform"]["request_id"] == f"shipping-orch-{task.task_no}"
assert runtime_context["platform"]["trigger_source"] == "backend_orchestrator"
assert runtime_context["refs"]["task_no"] == task.task_no
assert runtime_context["refs"]["batch_no"] == batch.batch_no
assert runtime_context["refs"]["run_purpose"] == "parse_notice"
assert runtime_context["domain"]["type"] == "shipping_notice"
assert runtime_context["domain"]["state_hint"]["focus_task_no"] == task.task_no
assert runtime_context["domain"]["state_hint"]["status"] == task.process_status
assert runtime_context["reference_context"]["focus_object"]["id"] == task.task_no
assert set(captured["inputs"].keys()) == {"agent_runtime_context"}
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "22222222-2222-2222-2222-222222222222"
def test_build_dify_chat_inputs_returns_agent_runtime_context_only(app):
"""货代发货 Agent 仅应向 Dify 注入 agent_runtime_context。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
conversation_id="conv-shipping-inputs-001",
current_focus_task_no="SN-20260622-DDDD0004",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260622-DDDD0004",
batch=batch,
conversation_id="conv-shipping-inputs-001",
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(
"conv-shipping-inputs-001",
trigger_source="frontend_chat",
request_id="req-frontend-001",
)
assert set(inputs.keys()) == {"agent_runtime_context"}
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["schema_version"] == "1"
assert runtime_context["agent_code"] == "shipping_notice"
assert runtime_context["scope"] == "chat_turn"
assert runtime_context["platform"]["session_id"] == "conv-shipping-inputs-001"
assert runtime_context["platform"]["request_id"] == "req-frontend-001"
assert runtime_context["platform"]["trigger_source"] == "frontend_chat"
assert runtime_context["refs"] == {
"task_no": "SN-20260622-DDDD0004",
"batch_no": "SB-DIFY-INPUTS",
"run_purpose": "chat_turn",
}
assert runtime_context["domain"]["state_hint"]["focus_task_no"] == "SN-20260622-DDDD0004"
assert runtime_context["domain"]["state_hint"]["status"] == "created"
assert runtime_context["reference_context"]["focus_object"]["id"] == "SN-20260622-DDDD0004"
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
"""已有 Dify provider 会话号时,agent_runtime_context 仍应按本地 session 解析。"""
with app.app_context():
local_session_id = "conv-shipping-local-session-001"
provider_conversation_id = "f3b371e7-4d8b-40b6-80be-76fd98459c65"
batch = ShippingBatch(
batch_no="SB-DIFY-LOCAL",
conversation_id=local_session_id,
current_focus_task_no="SN-20260626-LOCAL001",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260626-LOCAL001",
batch=batch,
conversation_id=local_session_id,
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
provider_inputs = dify_inputs.build_dify_chat_inputs(provider_conversation_id)
local_inputs = dify_inputs.build_dify_chat_inputs(local_session_id)
provider_runtime_context = json.loads(provider_inputs["agent_runtime_context"])
assert provider_runtime_context["refs"] == {"run_purpose": "chat_turn"}
local_runtime_context = json.loads(local_inputs["agent_runtime_context"])
assert local_runtime_context["refs"]["task_no"] == "SN-20260626-LOCAL001"
assert local_runtime_context["refs"]["batch_no"] == "SB-DIFY-LOCAL"
assert set(provider_inputs.keys()) == {"agent_runtime_context"}
assert set(local_inputs.keys()) == {"agent_runtime_context"}
def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explicit_anchor(app):
"""多票/无码头场景缺少显式锚点时,不应按最近任务给 Dify 注入 task ref。"""
with app.app_context():
conversation_id = "conv-shipping-no-anchor-001"
older_task = ShippingTask(
task_no="SN-20260630-OLDER001",
conversation_id=conversation_id,
source_type="manual",
process_status="created",
)
newer_task = ShippingTask(
task_no="SN-20260630-NEWER001",
conversation_id=conversation_id,
source_type="manual",
process_status="created",
)
db.session.add_all([older_task, newer_task])
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
assert set(inputs.keys()) == {"agent_runtime_context"}
runtime_context = json.loads(inputs["agent_runtime_context"])
assert runtime_context["refs"] == {"run_purpose": "chat_turn"}
def test_shipping_notice_agent_code_from_resolver():
"""发货通知识别应基于 resolve_agent_code,不再提供 dify_inputs 名称启发式。"""
from app.services.agent_registry.resolver import resolve_agent_code
class AgentLike:
name = "智能发货通知Agent"
agent_code = "shipping_notice"
assert resolve_agent_code(AgentLike()) == "shipping_notice"
class GenericLike:
name = "智能发货通知Agent"
agent_code = "generic"
assert resolve_agent_code(GenericLike()) != "shipping_notice"
def test_create_empty_batch_returns_batch_shell(app, client):
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={"file_count": 1},
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["batch_no"].startswith("SB-")
assert data["data"]["file_count"] == 1
def _workspace_user_headers(app, username: str):
"""创建独立工作台用户并返回 Authorization header。"""
with app.app_context():
user = User(
username=username,
email=f"{username}@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
user_id = user.id
return {"Authorization": f"Bearer {token}"}, user_id
def test_create_batch_idempotency_key_replays_same_batch(app, client, monkeypatch):
"""相同建单幂等键调用两次只创建一个批次,第二次不启动编排器。"""
headers = _workspace_headers(app)
idempotency_key = "batch-idem-001"
started: list[str] = []
def fake_start(batch_no: str | None) -> bool:
if batch_no:
started.append(batch_no)
return True
monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
raw = "客户:ACME\nA001 x 10".encode("utf-8")
def _payload():
return {
"files": (BytesIO(raw), "notice-a.txt"),
"conversation_id": "conv-idem-001",
"idempotency_key": idempotency_key,
}
first = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers, "Idempotency-Key": idempotency_key},
data=_payload(),
content_type="multipart/form-data",
)
second = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers, "Idempotency-Key": idempotency_key},
data=_payload(),
content_type="multipart/form-data",
)
assert first.status_code == 200
assert second.status_code == 200
first_result = _unwrap_ok(first)
second_result = _unwrap_ok(second)
assert first_result["batch_no"] == second_result["batch_no"]
assert second_result.get("idempotent_replay") is True
assert second_result["data"]["orchestrator_started"] is False
assert started == [first_result["batch_no"]]
with app.app_context():
batch_count = ShippingBatch.query.filter_by(create_idempotency_key=idempotency_key).count()
task_count = ShippingTask.query.filter_by(batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id).count()
assert batch_count == 1
assert task_count == 1
def test_create_batch_same_request_duplicate_files_create_one_task(app, client):
"""同一次上传两个内容相同文件只创建一个任务。"""
headers = _workspace_headers(app)
raw = "客户:ACME\nA001 x 10".encode("utf-8")
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": [
(BytesIO(raw), "notice-a.txt"),
(BytesIO(raw), "notice-b.txt"),
],
"conversation_id": "conv-dedupe-files",
"idempotency_key": "batch-dedupe-files-001",
},
content_type="multipart/form-data",
)
result = _unwrap_ok(res)
assert result["file_summary"]["duplicate_count"] == 1
assert len(result["data"]["tasks"]) == 1
def test_create_batch_persists_source_content_hash(app, client):
"""建单后任务应保存完整 SHA-256 内容哈希。"""
import hashlib
headers = _workspace_headers(app)
raw = "客户:ACME\nA001 x 10".encode("utf-8")
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO(raw), "notice-a.txt"),
"conversation_id": "conv-hash-persist",
"idempotency_key": "batch-hash-persist-001",
},
content_type="multipart/form-data",
)
result = _unwrap_ok(res)
expected_hash = hashlib.sha256(raw).hexdigest().lower()
with app.app_context():
task = ShippingTask.query.filter_by(task_no=result["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.source_content_hash == expected_hash
def test_create_batch_idempotency_key_scoped_per_user(app, client):
"""不同用户使用相同幂等键互不冲突。"""
headers_a, _user_a = _workspace_user_headers(app, "shipping_idem_user_a")
headers_b, _user_b = _workspace_user_headers(app, "shipping_idem_user_b")
idempotency_key = "shared-idem-key"
def _payload():
return {
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"idempotency_key": idempotency_key,
}
res_a = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers_a, "Idempotency-Key": idempotency_key},
data=_payload(),
content_type="multipart/form-data",
)
res_b = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers_b, "Idempotency-Key": idempotency_key},
data=_payload(),
content_type="multipart/form-data",
)
batch_a = _unwrap_ok(res_a)["batch_no"]
batch_b = _unwrap_ok(res_b)["batch_no"]
assert batch_a != batch_b
def test_create_batch_without_idempotency_key_still_works(app, client):
"""兼容期:缺少幂等键的旧请求仍可建批。"""
headers = _workspace_headers(app)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-legacy-no-idem",
},
content_type="multipart/form-data",
)
result = _unwrap_ok(res)
assert result["batch_no"].startswith("SB-")
def test_create_batch_idempotency_replays_after_tasks_exist(app, client):
"""相同幂等键在首批任务已落库后应幂等重放,而非返回文件重复错误。"""
headers = _workspace_headers(app)
idempotency_key = "batch-idem-after-tasks"
raw = "客户:ACME\nA001 x 10".encode("utf-8")
def _payload():
return {
"files": (BytesIO(raw), "notice-a.txt"),
"conversation_id": "conv-idem-after-tasks",
"idempotency_key": idempotency_key,
}
first = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers, "Idempotency-Key": idempotency_key},
data=_payload(),
content_type="multipart/form-data",
)
second = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers, "Idempotency-Key": idempotency_key},
data=_payload(),
content_type="multipart/form-data",
)
assert first.status_code == 200
assert second.status_code == 200
first_result = _unwrap_ok(first)
second_result = _unwrap_ok(second)
assert second_result.get("idempotent_replay") is True
assert first_result["batch_no"] == second_result["batch_no"]
with app.app_context():
task_count = ShippingTask.query.filter_by(
batch_id=ShippingBatch.query.filter_by(batch_no=first_result["batch_no"]).first().id
).count()
assert task_count == 1
def test_create_batch_idempotency_key_conflicts_on_different_files(app, client):
"""相同幂等键但文件集合不同时应返回 SHIPPING.BATCH_IDEMPOTENCY_CONFLICT。"""
headers = _workspace_headers(app)
idempotency_key = "batch-idem-conflict-001"
first = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers, "Idempotency-Key": idempotency_key},
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"idempotency_key": idempotency_key,
},
content_type="multipart/form-data",
)
assert first.status_code == 200
second = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers={**headers, "Idempotency-Key": idempotency_key},
data={
"files": (BytesIO("客户:BETA\nB002 x 20".encode("utf-8")), "notice-b.txt"),
"idempotency_key": idempotency_key,
},
content_type="multipart/form-data",
)
assert second.status_code == 409
payload = second.get_json()
assert payload["success"] is False
assert payload["error"]["code"] == "SHIPPING.BATCH_IDEMPOTENCY_CONFLICT"