- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。 - 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。 - 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。 - 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。 - 增强文档与代码注释,反映新的业务逻辑与功能要求。
2038 lines
82 KiB
Python
2038 lines
82 KiB
Python
"""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,
|
||
ShippingCase,
|
||
ShippingCustomer,
|
||
ShippingNoticeDocument,
|
||
ShippingNoticeIntake,
|
||
ShippingInventoryRoutingRule,
|
||
ShippingInventoryRoutingRuleCondition,
|
||
ShippingOrderExtraction,
|
||
ShippingOrderFieldDecision,
|
||
ShippingOrderFieldValue,
|
||
ShippingOrderSnapshot,
|
||
ShippingTask,
|
||
ShippingTaskEvent,
|
||
ShippingTemporaryInventorySession,
|
||
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_inputs, tools as shipping_tools
|
||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||
from tests.conftest import seed_task_inventory_source
|
||
|
||
|
||
def _confirm_direct_task_customer(task: ShippingTask) -> None:
|
||
"""为直接构造且聚焦客户门禁后流程的任务补齐已确认客户。"""
|
||
customer = ShippingCustomer.query.filter_by(short_code='BAT').one_or_none()
|
||
if customer is None:
|
||
customer = ShippingCustomer(
|
||
standard_name='批次流程测试客户', short_code='BAT', status='active',
|
||
)
|
||
db.session.add(customer)
|
||
db.session.flush()
|
||
task.shipping_case = ShippingCase(
|
||
case_no=f'CASE-{task.task_no}', customer=customer,
|
||
customer_name_snapshot=customer.standard_name,
|
||
customer_short_code_snapshot=customer.short_code,
|
||
)
|
||
task.customer_resolution_status = 'confirmed'
|
||
task.customer_resolution_method = 'test_fixture'
|
||
|
||
|
||
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()
|
||
actor_user_id = int(user.id)
|
||
|
||
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 = _unwrap_ok(res)
|
||
assert data["status"] in {"ok", "running"}
|
||
with app.app_context():
|
||
from app.models import ShippingAuditEvent
|
||
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"
|
||
# 关键断言:工作台决策须带操作人、前后快照,并双写统一审计。
|
||
assert event.actor_id == actor_user_id
|
||
assert isinstance(event.before_json, dict)
|
||
assert isinstance(event.after_json, dict)
|
||
audit = (
|
||
ShippingAuditEvent.query.filter_by(
|
||
aggregate_type='shipping_task',
|
||
aggregate_id='SN-WS-CONFIRM-001',
|
||
action='confirm_parse',
|
||
)
|
||
.order_by(ShippingAuditEvent.id.desc())
|
||
.first()
|
||
)
|
||
assert audit is not None
|
||
assert int(audit.actor_id or 0) == actor_user_id
|
||
assert audit.before_snapshot_json is not None
|
||
assert audit.after_snapshot_json is not None
|
||
|
||
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 = _unwrap_ok(res)
|
||
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):
|
||
"""旧建批入口只登记待订单抽取状态,不触发普通 Chatflow。"""
|
||
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"] == "awaiting_order_extraction"
|
||
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_awaits_order_extraction(app, client):
|
||
"""聊天/工作台批量上传通知时应返回 envelope,并仅落 raw_text,等待订单抽取主链。"""
|
||
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"] == "awaiting_order_extraction"
|
||
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_rejects_configured_file_limit_before_intake(app, client, tmp_path):
|
||
"""超过请求级文件数限制必须明确失败,且不创建批次、任务或临时上传目录。"""
|
||
headers = _workspace_headers(app)
|
||
app.config['SHIPPING_NOTICE_BATCH_MAX_FILES'] = 1
|
||
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()
|
||
|
||
response = client.post(
|
||
'/api/workspace/shipping-batches/create-from-notices',
|
||
headers=headers,
|
||
data={
|
||
'files': [
|
||
(BytesIO(b'first'), 'notice-a.txt'),
|
||
(BytesIO(b'second'), 'notice-b.txt'),
|
||
],
|
||
},
|
||
content_type='multipart/form-data',
|
||
)
|
||
|
||
assert response.status_code == 400
|
||
payload = response.get_json()
|
||
# 关键断言:请求在抽取前被阻断,避免超限文件占用临时目录或部分建单。
|
||
assert payload['error']['code'] == 'SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED'
|
||
assert payload['error']['details'] == {'max_files': 1, 'received_files': 2}
|
||
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_workspace_inventory_upload_requires_authenticated_task_and_file(app, client):
|
||
"""独立工作台库存上传端点必须保持任务归属校验,并拒绝缺少 multipart 文件的调用。"""
|
||
headers = _workspace_headers(app)
|
||
response = client.post('/api/workspace/shipping-tasks/SN-NOT-OWNED/upload-inventory', headers=headers)
|
||
assert response.status_code == 404
|
||
|
||
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-WORKSPACE-INVENTORY-UPLOAD', user_id=user.id)
|
||
db.session.add(task)
|
||
db.session.commit()
|
||
|
||
response = client.post(
|
||
'/api/workspace/shipping-tasks/SN-WORKSPACE-INVENTORY-UPLOAD/upload-inventory', headers=headers,
|
||
data={}, content_type='multipart/form-data',
|
||
)
|
||
assert response.status_code == 400
|
||
assert response.get_json()['error']['message'] == 'file is required'
|
||
|
||
|
||
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
|
||
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_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 is None
|
||
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_requires_order_freeze_before_inventory_trigger(app, tmp_path):
|
||
"""关键断言:库存自动推进前必须先阻断到订单冻结,不能消费动态订单投影。"""
|
||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
|
||
app.config["SHIPPING_NOTICE_RPA_SHARED_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", "reservation_id": "R-1", "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)"},
|
||
}
|
||
},
|
||
)
|
||
_confirm_direct_task_customer(task)
|
||
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"] == "order_freeze"
|
||
assert task.process_status == "parsed"
|
||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||
|
||
ui_state = build_task_ui_state(task)
|
||
assert ui_state["checkpoint"] == "order_freeze"
|
||
assert ui_state["current_step"]["code"] == "parse_confirm"
|
||
|
||
|
||
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["SHIPPING_NOTICE_RPA_SHARED_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_requires_order_freeze_before_inventory_source_resolution(app, tmp_path):
|
||
"""关键断言:库存源解析也不得绕过冻结 Snapshot 门禁。"""
|
||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
|
||
app.config["SHIPPING_NOTICE_RPA_SHARED_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",
|
||
destination_code="DUB",
|
||
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
|
||
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
|
||
)
|
||
_confirm_direct_task_customer(task)
|
||
db.session.add(task)
|
||
task._test_order_rows = [{"part_number": "A001", "reservation_id": "R-1", "qty": 10}]
|
||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||
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"] == "order_freeze"
|
||
# 预置的历史 Source 提示可以保留,但不可据此触发库存/RPA。
|
||
assert task.inventory_source_code == "DSV360_AWSDU"
|
||
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
|
||
assert not trigger_path.exists()
|
||
|
||
|
||
def test_inventory_source_rules_resolve_configured_dublin_source(app):
|
||
"""数据库中显式发布的 Dublin 规则应解析到已启用库存站点。"""
|
||
from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source
|
||
|
||
with app.app_context():
|
||
order_schema_service.initialize_schema({'display_name': '批次库存路由测试'}, actor_id=None)
|
||
destination_field = order_schema_service.save_field(
|
||
{'field_code': 'routing_destination_code', 'scope': 'header', 'value_type': 'string'},
|
||
actor_id=None,
|
||
)
|
||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||
saved = order_schema_service.save_draft(draft['id'], {
|
||
'fields': [{
|
||
'field_id': destination_field['id'],
|
||
'display_name': '路由目的地代码',
|
||
'required': False,
|
||
'aliases': [],
|
||
'normalizer_key': 'uppercase_trim',
|
||
'validator_keys': [],
|
||
'enum_options': [],
|
||
'evidence_policy': {
|
||
'required': True,
|
||
'source_precedence': ['attachment_table'],
|
||
'conflict_policy': 'block',
|
||
'allow_single_source': True,
|
||
},
|
||
'relation_role': None,
|
||
'comparator_key': 'normalized_text',
|
||
}],
|
||
'expected_lock_version': draft['lock_version'],
|
||
}, actor_id=None)
|
||
published = order_schema_service.publish(
|
||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||
)
|
||
task = ShippingTask(
|
||
task_no="SN-INVENTORY-SOURCE-DSV360-AWSDU",
|
||
source_type="pdf",
|
||
process_status="parsed",
|
||
destination_code="DUB",
|
||
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 10}],
|
||
)
|
||
db.session.add(task)
|
||
db.session.flush()
|
||
extraction = ShippingOrderExtraction(
|
||
task_id=task.id,
|
||
schema_version_id=published['id'],
|
||
input_snapshot_hash='b' * 64,
|
||
status='accepted',
|
||
)
|
||
db.session.add(extraction)
|
||
db.session.flush()
|
||
decision = ShippingOrderFieldDecision(
|
||
extraction_id=extraction.id,
|
||
line_id=None,
|
||
field_id=destination_field['id'],
|
||
decision_status='accepted',
|
||
supporting_observation_ids_json=[],
|
||
resolved_value_json='DUB',
|
||
)
|
||
db.session.add(decision)
|
||
db.session.flush()
|
||
db.session.add(ShippingOrderFieldValue(
|
||
extraction_id=extraction.id,
|
||
line_id=None,
|
||
field_id=destination_field['id'],
|
||
decision_id=decision.id,
|
||
value_text='DUB',
|
||
value_json='DUB',
|
||
))
|
||
task.current_order_extraction_id = extraction.id
|
||
snapshot = ShippingOrderSnapshot(
|
||
task_id=task.id,
|
||
extraction_id=extraction.id,
|
||
schema_version_id=published['id'],
|
||
order_data_version=1,
|
||
header_values_json={str(destination_field['id']): 'DUB'},
|
||
rule_versions_json={},
|
||
)
|
||
db.session.add(snapshot)
|
||
db.session.flush()
|
||
task.order_snapshot_id = snapshot.id
|
||
db.session.add(ShippingInventoryRoutingRule(
|
||
rule_code='BATCH_TEST_DUB',
|
||
rule_name='批次测试 Dublin 路由',
|
||
scope='task',
|
||
priority=100,
|
||
match_mode='all',
|
||
status='published',
|
||
action_type='add_source_candidates',
|
||
action_payload_json={'source_codes': ['DSV360_AWSDU']},
|
||
version=1,
|
||
conditions=[ShippingInventoryRoutingRuleCondition(
|
||
condition_group=1,
|
||
source_kind='order_field',
|
||
order_field_id=destination_field['id'],
|
||
operator='equals',
|
||
expected_value_json='DUB',
|
||
sequence=1,
|
||
)],
|
||
))
|
||
db.session.commit()
|
||
|
||
resolution = resolve_inventory_source(task)
|
||
|
||
assert resolution.status == "resolved"
|
||
assert resolution.source_code == "DSV360_AWSDU"
|
||
|
||
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}],
|
||
)
|
||
_confirm_direct_task_customer(task)
|
||
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"]) == 1
|
||
|
||
|
||
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",
|
||
]
|
||
|
||
|
||
def test_parse_stage_ui_state_lists_all_issues(app):
|
||
"""库存源检查点应列出当前库存源问题和解析警告,不生成旧顺序延后复核提示。"""
|
||
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={
|
||
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
|
||
"parse_validation": {
|
||
"status": "needs_review",
|
||
"issues": [
|
||
{
|
||
"line_index": 0,
|
||
"part_number": "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 行料号 A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
|
||
assert len(issues) == 4
|
||
|
||
|
||
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"]] == [
|
||
"retry_rpa",
|
||
"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_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():
|
||
batch = ShippingBatch(batch_no="SB-JOB-DETACHED", file_count=1)
|
||
task = ShippingTask(
|
||
task_no="SN-20260626-DETACHED1",
|
||
batch=batch,
|
||
source_type="manual",
|
||
process_status="parsed",
|
||
)
|
||
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_all([batch, task, 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_stops_created_legacy_task_without_calling_chatflow(app, monkeypatch):
|
||
"""created 旧壳任务必须停下并要求重新上传,不能再次调用普通 Dify Chatflow。"""
|
||
with app.app_context():
|
||
batch = ShippingBatch(batch_no="SB-ORCH-LEGACY", file_count=1)
|
||
task = ShippingTask(
|
||
task_no="SN-20260622-LEGACY01",
|
||
batch=batch,
|
||
source_type="manual",
|
||
raw_content="customer ACME\nA001 x 10",
|
||
process_status="created",
|
||
)
|
||
db.session.add_all([batch, task])
|
||
db.session.commit()
|
||
|
||
monkeypatch.setattr(
|
||
batch_orchestrator,
|
||
"auto_progress",
|
||
lambda _payload: (_ for _ in ()).throw(AssertionError("legacy created task must not auto progress")),
|
||
)
|
||
|
||
result = batch_orchestrator._run_single_task(task.task_no)
|
||
|
||
assert result["status"] == "needs_human"
|
||
assert "重新上传" in str(result["message"])
|
||
|
||
|
||
def test_submit_reparse_requires_new_intake_run_without_mutating_task(app, monkeypatch):
|
||
"""Task 重新识别必须要求重新上传创建 Intake Run,不能回退 created 或启动旧编排器。"""
|
||
with app.app_context():
|
||
batch = ShippingBatch(batch_no="SB-REPARSE-RUN", file_count=1)
|
||
task = ShippingTask(
|
||
task_no="SN-20260629-REPARSE1",
|
||
batch=batch,
|
||
source_type="manual",
|
||
raw_content="customer 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,
|
||
)
|
||
db.session.add_all([batch, task])
|
||
db.session.commit()
|
||
|
||
monkeypatch.setattr(
|
||
"app.services.shipping_notice.decision_workflow.start_task_orchestrator",
|
||
lambda _task_no: (_ for _ in ()).throw(AssertionError("must not start legacy orchestrator")),
|
||
)
|
||
result = shipping_tools.submit_decision({"task_id": task.task_no, "decision": "reparse"})
|
||
|
||
db.session.refresh(task)
|
||
assert result["status"] == "needs_human"
|
||
assert task.process_status == "pending_review"
|
||
assert task.review_status == "parse_review"
|
||
assert task.lines_json == [{"sku": "OLD", "qty": 1}]
|
||
assert "重新上传" in result["message"]
|
||
|
||
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_auto_progress(payload):
|
||
called["auto_progress"] = payload
|
||
return {"status": "ok", "message": "advanced"}
|
||
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_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_build_dify_chat_inputs_restores_pending_temporary_inventory_session(app):
|
||
"""临时库存确认跨回合时应从 HXOPS 数据库恢复会话号,而不是依赖 Dify 隐式记忆。"""
|
||
with app.app_context():
|
||
conversation_id = 'conv-temp-inventory-resume-001'
|
||
user = User(username='temp_resume_user', email='temp-resume@example.com', role='user', status='active')
|
||
user.set_password('password')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
asset = FileAsset(
|
||
asset_no='FA-TEMP-RESUME-001', owner_user_id=user.id, original_filename='inventory.xls',
|
||
storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.xls',
|
||
content_hash='a' * 64, file_size=16, extension='.xls', upload_status='ready',
|
||
)
|
||
db.session.add(asset)
|
||
db.session.flush()
|
||
pending = ShippingTemporaryInventorySession(
|
||
session_no='TIS-RESUME-001', user_id=user.id, conversation_id=conversation_id,
|
||
asset_id=asset.id, declared_intent='inventory_candidate',
|
||
file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation',
|
||
expires_at=datetime.utcnow() + timedelta(hours=1),
|
||
)
|
||
db.session.add(pending)
|
||
db.session.commit()
|
||
|
||
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
|
||
runtime_context = json.loads(inputs['agent_runtime_context'])
|
||
|
||
assert runtime_context['refs']['temporary_inventory_session_no'] == pending.session_no
|
||
assert runtime_context['refs']['run_purpose'] == 'chat_turn'
|
||
assert 'capability' not in runtime_context['refs']
|
||
|
||
|
||
def test_build_dify_chat_inputs_ignores_expired_or_terminal_temporary_inventory_session(app):
|
||
"""过期或已确认会话不得继续污染后续聊天运行态。"""
|
||
with app.app_context():
|
||
conversation_id = 'conv-temp-inventory-terminal-001'
|
||
user = User(username='temp_terminal_user', email='temp-terminal@example.com', role='user', status='active')
|
||
user.set_password('password')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
asset = FileAsset(
|
||
asset_no='FA-TEMP-TERMINAL-001', owner_user_id=user.id, original_filename='inventory.csv',
|
||
storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.csv',
|
||
content_hash='b' * 64, file_size=16, extension='.csv', upload_status='ready',
|
||
)
|
||
db.session.add(asset)
|
||
db.session.flush()
|
||
db.session.add_all([
|
||
ShippingTemporaryInventorySession(
|
||
session_no='TIS-EXPIRED-001', user_id=user.id, conversation_id=conversation_id,
|
||
asset_id=asset.id, declared_intent='inventory_candidate',
|
||
file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation',
|
||
expires_at=datetime.utcnow() - timedelta(minutes=1),
|
||
),
|
||
ShippingTemporaryInventorySession(
|
||
session_no='TIS-CONFIRMED-001', user_id=user.id, conversation_id=conversation_id,
|
||
asset_id=asset.id, declared_intent='inventory_candidate',
|
||
file_classification_status='inventory_candidate', status='confirmed_for_temporary_use',
|
||
expires_at=datetime.utcnow() + timedelta(hours=1),
|
||
),
|
||
])
|
||
db.session.commit()
|
||
|
||
inputs = dify_inputs.build_dify_chat_inputs(conversation_id)
|
||
runtime_context = json.loads(inputs['agent_runtime_context'])
|
||
|
||
assert 'temporary_inventory_session_no' not in runtime_context['refs']
|
||
|
||
|
||
def test_build_dify_chat_inputs_prefers_explicit_temporary_inventory_session(app):
|
||
"""显式锚点必须优先,便于 UI 精确续办指定的临时库存会话。"""
|
||
with app.app_context():
|
||
inputs = dify_inputs.build_dify_chat_inputs(
|
||
'conv-temp-explicit-001',
|
||
temporary_inventory_session_no='tis-explicit-001',
|
||
)
|
||
runtime_context = json.loads(inputs['agent_runtime_context'])
|
||
|
||
assert runtime_context['refs']['temporary_inventory_session_no'] == 'TIS-EXPLICIT-001'
|
||
|
||
|
||
def test_build_dify_chat_inputs_does_not_restore_temporary_session_for_backend_orchestrator(app):
|
||
"""后台订单解析不得继承聊天中的临时库存会话锚点。"""
|
||
with app.app_context():
|
||
conversation_id = 'conv-temp-inventory-worker-001'
|
||
user = User(username='temp_worker_user', email='temp-worker@example.com', role='user', status='active')
|
||
user.set_password('password')
|
||
db.session.add(user)
|
||
db.session.flush()
|
||
asset = FileAsset(
|
||
asset_no='FA-TEMP-WORKER-001', owner_user_id=user.id, original_filename='inventory.xlsx',
|
||
storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.xlsx',
|
||
content_hash='c' * 64, file_size=16, extension='.xlsx', upload_status='ready',
|
||
)
|
||
db.session.add(asset)
|
||
db.session.flush()
|
||
db.session.add(ShippingTemporaryInventorySession(
|
||
session_no='TIS-WORKER-001', user_id=user.id, conversation_id=conversation_id,
|
||
asset_id=asset.id, declared_intent='inventory_candidate',
|
||
file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation',
|
||
expires_at=datetime.utcnow() + timedelta(hours=1),
|
||
))
|
||
db.session.commit()
|
||
|
||
inputs = dify_inputs.build_dify_chat_inputs(
|
||
conversation_id,
|
||
trigger_source='backend_orchestrator',
|
||
)
|
||
runtime_context = json.loads(inputs['agent_runtime_context'])
|
||
|
||
assert 'temporary_inventory_session_no' not in runtime_context['refs']
|
||
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"
|