- 添加单票与多票发货需求的处理方式 - 说明库存 Excel 上传后的保存与关联机制 - 解释库存匹配与 Excel 生成的独立执行方式 - 明确批次库存的真相来源 feat(chat): 优化发货库存上传提示语 - 根据上传结果生成更详细的提示信息 - 增加批次号的提示逻辑 - 使用国际化支持替换硬编码字符串 refactor(chat): 重构发货库存上传处理逻辑 - 移除多余的任务选择逻辑 - 简化上传处理流程 - 增强代码可读性与维护性 feat(locales): 更新多语言支持的提示信息 - 添加库存上传与任务处理的多语言提示 - 更新库存缺口与任务状态的描述
514 lines
20 KiB
Python
514 lines
20 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, Job, KbJob, ShippingBatch, ShippingTask, User
|
|
from app.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
|
|
|
|
|
|
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_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_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",
|
|
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)
|
|
assert captured["inputs"]["hxops_context"]["schema_version"] == "1"
|
|
assert captured["inputs"]["hxops_context"]["session"]["id"] == session.session_id
|
|
assert captured["inputs"]["hxops_context"]["request"]["id"] == f"shipping-orch-{task.task_no}"
|
|
assert captured["inputs"]["hxops_context"]["request"]["trigger_source"] == "backend_orchestrator"
|
|
assert captured["inputs"]["hxops_context"]["refs"] == [
|
|
{"field": "task", "value": task.task_no},
|
|
{"field": "batch", "value": 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 == "22222222-2222-2222-2222-222222222222"
|
|
|
|
|
|
def test_build_dify_chat_inputs_returns_hxops_context_only(app):
|
|
"""货代发货 Agent 应只注入平台统一的 hxops_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()) == {"hxops_context"}
|
|
assert inputs["hxops_context"]["schema_version"] == "1"
|
|
assert inputs["hxops_context"]["session"]["id"] == "conv-shipping-inputs-001"
|
|
assert inputs["hxops_context"]["request"]["id"] == "req-frontend-001"
|
|
assert inputs["hxops_context"]["request"]["trigger_source"] == "frontend_chat"
|
|
assert inputs["hxops_context"]["refs"] == [
|
|
{"field": "task", "value": "SN-20260622-DDDD0004"},
|
|
{"field": "batch", "value": "SB-DIFY-INPUTS"},
|
|
]
|
|
|
|
|
|
def test_build_dify_chat_inputs_requires_local_session_not_provider_conversation(app):
|
|
"""已有 Dify provider 会话号时,HXOPS 上下文仍应按本地 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)
|
|
|
|
assert provider_inputs["hxops_context"]["refs"] == []
|
|
assert local_inputs["hxops_context"]["session"]["id"] == local_session_id
|
|
assert local_inputs["hxops_context"]["refs"] == [
|
|
{"field": "task", "value": "SN-20260626-LOCAL001"},
|
|
{"field": "batch", "value": "SB-DIFY-LOCAL"},
|
|
]
|
|
|
|
|
|
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
|
|
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
|
|
class AgentLike:
|
|
name = "智能发货通知Agent"
|
|
|
|
assert dify_inputs.is_shipping_notice_chat_agent(AgentLike()) is True
|
|
|
|
|
|
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
|