本次提交完整实现货代发货通知的自动化批量处理能力: 1. 新增发货单票后台任务类型与专用worker队列,实现任务持久化调度 2. 实现发货批次后台编排器,支持上传后自动逐票推进解析、匹配、导出全流程 3. 新增单票重试、批次待处理重试的API与前端操作界面 4. 补充全量多语言翻译,新增重试、任务列表、状态展示相关文案 5. 优化上传交互逻辑,改为后台自动处理任务,无需手动触发解析指令 6. 修复文件检核工具无数据预检逻辑,避免创建空检核批次 7. 调整发货工作流细节,优化Excel生成幂等性与任务状态同步 8. 更新环境配置与API文档,修正货代工具接口地址端口
392 lines
15 KiB
Python
392 lines
15 KiB
Python
"""shipping_notice batch tests.
|
|
|
|
覆盖 batch 新增能力的最小闭环:
|
|
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
|
|
2. get_batch_status 返回 focus task 与任务列表。
|
|
3. switch_focus_task 可在同批次内切换当前任务。
|
|
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
|
|
"""
|
|
|
|
from io import BytesIO
|
|
|
|
from app import db
|
|
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
|
|
from app.auth_jwt import issue_local_access_token
|
|
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
|
|
|
|
|
|
def _tool_headers(app):
|
|
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 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
|
|
|
|
|
|
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):
|
|
"""聊天/工作台批量上传通知时应仅落 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
|
|
data = res.get_json()
|
|
assert data["status"] == "ok"
|
|
assert data["batch_no"].startswith("SB-")
|
|
assert data["data"]["batch"]["batch_no"] == data["batch_no"]
|
|
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
|
|
assert data["data"]["focus_task"]["task_no"] == data["data"]["tasks"][0]["task_id"]
|
|
|
|
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 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
|
|
data = res.get_json()
|
|
assert data["status"] == "ok"
|
|
assert data["data"]["orchestrator_started"] is True
|
|
assert started == [data["batch_no"]]
|
|
|
|
|
|
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_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_and_updates_session(app, monkeypatch):
|
|
"""后台 Dify 执行器应带上当前任务上下文,并回写 provider conversation id。"""
|
|
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",
|
|
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",
|
|
)
|
|
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")
|
|
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["user_id"] == user.id
|
|
assert captured["agent_id"] == agent.id
|
|
assert captured["session_id"] == session.session_id
|
|
assert isinstance(captured["inputs"], dict)
|
|
assert captured["inputs"]["entry_mode"] == "orchestrator_parse"
|
|
assert captured["inputs"]["trigger_source"] == "backend_orchestrator"
|
|
assert captured["inputs"]["user_message"] == ""
|
|
assert captured["inputs"]["current_task_no"] == task.task_no
|
|
assert captured["inputs"]["current_batch_no"] == batch.batch_no
|
|
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
|
|
assert refreshed_session is not None
|
|
assert refreshed_session.external_conversation_id == "11111111-1111-1111-1111-111111111111"
|
|
|
|
|
|
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
|
|
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
|
|
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",
|
|
entry_mode="user_chat",
|
|
user_message="这票现在什么状态?",
|
|
trigger_source="frontend_chat",
|
|
)
|
|
|
|
assert inputs["entry_mode"] == "user_chat"
|
|
assert inputs["conversation_id"] == "conv-shipping-inputs-001"
|
|
assert inputs["current_batch_no"] == "SB-DIFY-INPUTS"
|
|
assert inputs["current_task_no"] == "SN-20260622-DDDD0004"
|
|
assert inputs["user_message"] == "这票现在什么状态?"
|
|
assert inputs["trigger_source"] == "frontend_chat"
|
|
|
|
|
|
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
|