- 新增接口支持覆盖当前任务的发货通知 - 重新解析时重置任务状态,避免重复任务 - 增加库存 RPA 等待时间的复查逻辑 - 更新状态机以处理文本抽取失败的情况 - 增强测试用例以覆盖新功能
959 lines
37 KiB
Python
959 lines
37 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 datetime import datetime, timedelta
|
|
from io import BytesIO
|
|
|
|
from app import db
|
|
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, 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, tools as shipping_tools
|
|
from app.services.shipping_notice.progress_workflow import auto_progress
|
|
|
|
|
|
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_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 = res.get_json()
|
|
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):
|
|
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
|
|
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
|
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
|
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",
|
|
)
|
|
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"
|
|
|
|
|
|
def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp_path):
|
|
"""工作台查询遇到已超时 RPA 等待态时,应兜底复查并自动触发下一次库存导出。"""
|
|
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}],
|
|
)
|
|
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 = res.get_json()
|
|
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) == 2
|
|
assert len(failed) == 1
|
|
assert len(rechecked) == 1
|
|
assert triggered[-1].detail_json["attempt"] == 2
|
|
assert task.step_payload_json["current_step_progress"]["current"] == 2
|
|
|
|
|
|
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 = res.get_json()
|
|
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
|
|
|
|
|
|
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 = res.get_json()
|
|
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",
|
|
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
|