Files
syops/backend/tests/test_shipping_notice_tools.py
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

544 lines
22 KiB
Python

"""
backend/tests/test_shipping_notice_tools.py
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
依赖:Flask 测试客户端、ShippingNotice/ShippingOrderTask/Customer、货代 workflow 测试辅助。
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
"""
import json
from pathlib import Path
import pytest
from app import db
from app.models import (
Agent,
ChatLog,
ChatSession,
ShippingCustomer,
FreightRpaOnhandField,
FreightRpaOnhandRoutingRule,
FreightRpaOnhandReportFile,
FreightRpaOnhandRoutingRuleCondition,
ShippingNotice,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
ShippingTaskEvent,
ShippingTaskOnhandLink,
User,
)
from app.services.shipping_notice.match import match_notice_lines
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import confirm_test_customer_resolution, inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
def _tool_headers(app):
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def _seed_test_user(*, username: str) -> int:
"""创建测试用户并返回主键,供 OT 建单与能力强令牌使用。"""
user = User(username=username, email=f"{username}@example.test", password_hash='x')
db.session.add(user)
db.session.flush()
return int(user.id)
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
fields = {
code: order_schema_service.save_field(
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
)
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
}
draft = order_schema_service.create_draft({}, actor_id=None)
purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'}
configs = [{
'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code],
'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal',
'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'],
'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True},
'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text',
} for code, field in fields.items()]
saved = order_schema_service.save_draft(
draft['id'], {'fields': configs, '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'])
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
field_ids = {
str(item['field_code']): str(item['field_id'])
for item in (version.definition_json or {}).get('fields') or []
}
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}
for code, value in values.items():
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json=value,
)
db.session.add(decision)
db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=value,
))
task.current_order_extraction_id = extraction.id
# RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时
# 建立最小履约真相,避免旧测试绕过阶段 1 门禁。
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=task.order_data_version or 1,
rule_versions_json={'fulfillment_policy': {
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
'definition': {'field_bindings': [
{'capability_code': 'fulfillment.part_number', 'field_id': field_ids['part_number'], 'scope': 'line'},
{'capability_code': 'fulfillment.reservation_identity', 'field_id': field_ids['reservation_id'], 'scope': 'line'},
{'capability_code': 'fulfillment.quantity', 'field_id': field_ids['qty'], 'scope': 'line'},
]},
}},
header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, line_no=1, part_number=part_number, reservation_id=reservation_id,
qty=quantity, field_values_json={
str(field_ids['part_number']): part_number,
str(field_ids['reservation_id']): reservation_id,
str(field_ids['qty']): quantity,
},
))
task.order_snapshot_id = snapshot.id
db.session.flush()
def _confirm_test_task_customer(task: ShippingOrderTask) -> None:
"""为 RPA 回调/超时链路补齐已确认客户,避免自动推进被客户门禁提前阻断。"""
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name='RPA 直接回调测试客户', short_code='RPC', status='active',
)
db.session.add(customer)
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
task._test_customer_confirmed = True
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
app.config["INTEGRATION_API_KEY"] = ""
user_id = _seed_test_user(username='auth-dedicated')
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"},
json={"source_type": "direct_pdf", "user_id": user_id},
)
assert res.status_code == 200
assert res.get_json()["status"] == "ok"
def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "integration-secret"
user_id = _seed_test_user(username='auth-integration')
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"},
json={"source_type": "direct_pdf", "user_id": user_id},
)
assert res.status_code == 200
assert res.get_json()["status"] == "ok"
def test_shipping_notice_tool_auth_reports_missing_config(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = ""
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "any"},
json={"source_type": "direct_pdf"},
)
assert res.status_code == 503
assert res.get_json()["error_code"] == "missing_auth"
def test_parse_notice_tool_is_removed(app, client):
"""固定字段解析旁路已删除;订单创建只能经动态订单抽取提交。"""
response = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=_tool_headers(app),
json={"task_id": "OT-REMOVED"},
)
assert response.status_code == 404
def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch):
"""旧 Tool 入口不能绕过 GateAttempt 直接生成 Excel。"""
from app.services.shipping_notice import fulfillment_workflow
submitted: dict[str, object] = {}
def _submit(task_no, **kwargs):
submitted['task_no'] = task_no
submitted.update(kwargs)
return {'status': 'running', 'data': {}}
monkeypatch.setattr(
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
_submit,
)
result = fulfillment_workflow.generate_excel({
'task_id': 'OT-FORMAL-EXCEL-ONLY',
'operator_id': 7,
'idempotency_key': 'formal-excel-only',
})
assert result['status'] == 'running'
assert submitted == {
'task_no': 'OT-FORMAL-EXCEL-ONLY',
'trigger': 'tool_api_generate_excel',
'expected_version': None,
'idempotency_key': 'formal-excel-only',
'resume_gate_code': 'artifact_generation',
'operator_id': 7,
}
def test_match_notice_lines_reports_progress():
seen: list[tuple[int, int]] = []
status, line_results, shortage = match_notice_lines(
[
{"order-part": "A001", "order-ref": "R-1", "__required_qty": 1},
{"order-part": "A002", "order-ref": "R-2", "__required_qty": 2},
],
[
{"701": "A001", "702": "R-1", "703": 1},
{"701": "A002", "702": "R-2", "703": 2},
],
match_keys=[
{'order_field_id': 'order-part', 'inventory_field_id': '701'},
{'order_field_id': 'order-ref', 'inventory_field_id': '702'},
],
quantity_field_id='703',
progress_callback=lambda current, total: seen.append((current, total)),
)
assert status == "fulfillable"
assert len(line_results) == 2
assert shortage["lines"] == []
assert seen == [(1, 2), (2, 2)]
def test_contract_get_task_status_accepts_task_no_anchor(app, client):
"""契约:用户输入 OT-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability
headers = _tool_headers(app)
with app.app_context():
app.config["SHIPPING_CHAT_CAPABILITY_SECRET"] = "test-capability-secret"
user_id = _seed_test_user(username='status-anchor')
agent = Agent(name='shipping-agent', agent_code='shipping_notice_status_anchor')
db.session.add(agent)
db.session.flush()
session = ChatSession(session_id='status-anchor-session', user_id=user_id, agent_id=agent.id)
db.session.add(session)
db.session.commit()
session_id = session.session_id
agent_id = int(agent.id)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "direct_pdf", "user_id": user_id, "conversation_id": session_id,
"raw_content": "客户:ACME 料号A001 x 10"},
)
task_id = create_res.get_json()["task_id"]
token = issue_chat_capability(user_id=user_id, session_id=session_id, agent_id=agent_id, task_no=task_id)
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"task_no": task_id, "shipping_chat_capability_token": token},
)
data = status_res.get_json()
assert status_res.status_code == 200
assert data["status"] == "ok"
assert data["task_id"] == task_id
assert data["data"]["task_no"] == task_id
assert "当前进度" in data["message"]
def test_openapi_spec_public(app, client):
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
res = client.get("/api/shipping-notice/tools/openapi.json")
assert res.status_code == 200
spec = res.get_json()
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
assert "/rpa/" not in str(spec["paths"])
assert "/tools/create_task" not in spec["paths"]
assert "/tools/create_batch" not in spec["paths"]
assert "/tools/parse_notice" not in spec["paths"]
assert "/tools/parse_inventory" not in spec["paths"]
assert "/tools/ensure_inventory" not in spec["paths"]
assert "/tools/auto_progress" not in spec["paths"]
assert "/tools/match_inventory" not in spec["paths"]
assert "/tools/generate_shipment_excel" not in spec["paths"]
assert "/tools/upload_to_freight" not in spec["paths"]
assert "/tools/switch_focus_task" not in spec["paths"]
assert set(spec["paths"]) == {"/tools/get_task_status"}
spec_text = str(spec)
assert "只读解释" in spec_text
assert "submit_decision" not in spec_text
def test_confirm_inventory_source_route_is_removed(app, client):
"""库存源人工确认已下线,任何旧 Tool 写入口均不得可达。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingOrderTask(
task_no="OT-HTTP-CONFIRM-SRC",
user_id=1,
source_type="eml",
pending_human_reason="inventory_source_unresolved",
)
db.session.add(task)
db.session.commit()
res = client.post(
"/api/shipping-notice/tools/confirm_inventory_source",
headers=headers,
json={"task_id": "OT-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
)
assert res.status_code == 404
def test_static_openapi_snapshot_contains_shipping_contract_keywords():
"""静态 OpenAPI 快照应同步最新推进约束,避免 Dify 导入旧版说明。"""
spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json"
spec = json.loads(spec_path.read_text(encoding="utf-8"))
assert spec["openapi"] == "3.0.0"
assert "/tools/submit_decision" not in spec["paths"]
assert "/tools/parse_notice" not in spec["paths"]
spec_text = str(spec)
assert "只读解释" in spec_text
assert "match_inventory" not in spec_text
def test_parse_inventory_from_chat_text_route_is_removed(app, client):
"""正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。"""
headers = _tool_headers(app)
parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": "OT-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"},
)
assert parse_inv.status_code == 404
assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
def test_parse_inventory_empty_text_route_is_removed(app, client):
"""即使输入为空,已移除的正式任务库存文本入口也必须保持不可访问。"""
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": "OT-REMOVED", "raw_inventory_text": " "},
)
assert res.status_code == 404
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
def test_match_by_supplier_sku_and_reservation_id(app, client):
"""旧任务级库存解析入口不得因表头看似可识别而重新启用。"""
headers = _tool_headers(app)
removed = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": "OT-REMOVED",
"raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n",
},
)
assert removed.status_code == 404
def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, client):
"""正式任务不存在待确认的任务级映射,旧解析入口必须直接不可访问。"""
headers = _tool_headers(app)
removed = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": "OT-REMOVED",
"raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n",
},
)
assert removed.status_code == 404
def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, client, tmp_path):
"""正式任务不允许通过旧入口重开任务级映射修正。"""
headers = _tool_headers(app)
removed = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": "OT-REMOVED",
"raw_inventory_text": (
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
"D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n"
),
},
)
assert removed.status_code == 404
def test_legacy_task_inventory_mapping_routes_are_removed(app, client):
"""任务级库存上传和列映射已下线,不能再成为正式库存解析旁路。"""
headers = _tool_headers(app)
for path in (
"/api/shipping-notice/tools/upload_inventory_file",
"/api/shipping-notice/tools/get_inventory_schema_preview",
"/api/shipping-notice/tools/apply_inventory_mapping",
):
response = client.post(path, headers=headers, json={"task_id": "OT-LEGACY-REMOVED"})
assert response.status_code == 404
@pytest.mark.auto_rpa
def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import _run_single_task
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger)
app.config["FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS"] = 1
monkeypatch.setattr(
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
with app.app_context():
user_id = _seed_test_user(username='rpa-timeout-recheck')
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "direct_pdf", "user_id": user_id},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
_confirm_test_task_customer(task)
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="onhand_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=5),
)
)
db.session.commit()
with app.app_context():
result = _run_single_task(task_id)
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["status"] == "needs_human"
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="onhand_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="onhand_rpa_triggered").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="onhand_rpa_exhausted").count() == 1
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
def test_parse_inventory_oversized_text_route_is_removed(app, client):
"""旧正式库存文本入口无论内容大小都不可访问。"""
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": "OT-REMOVED", "raw_inventory_text": "x" * 200},
)
assert res.status_code == 404
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
task = ShippingOrderTask(
task_no="OT-20260101-TEST0001",
user_id=1,
source_type="eml",
review_status="rejected",
)
ui_state = build_task_ui_state(task)
assert ui_state["review_status"] == "rejected"
assert ui_state["actions"] == {"primary": None, "secondary": []}
assert "action_buttons" not in ui_state