Files
syops/backend/tests/test_shipping_notice_tools.py
T
hugo 1f3ecb87b7 feat(shipping_notice): 新增货代订单全流程业务模块及配套基建
本次提交新增货代订单处理全流程的完整业务能力、数据库迁移与测试用例:
1.  统一追加式审计事件体系,支持全链路不可篡改的业务追溯
2.  货代任务撤销、版本替代管控逻辑,规范已上传订单的合规版本更替
3.  订单抽取路由审计、模板自动冻结资格、路由计数等核心业务基建
4.  EML订单补充表解析契约与合并逻辑,完善订单补全能力
5.  Chatflow只读能力令牌校验机制,保障工具调用安全
6.  人工复核证据校验服务,规范人工审核的证据留存
所有变更均配套完整的单元测试与迁移契约测试,支持受控回退
2026-07-28 08:56:58 +08:00

873 lines
36 KiB
Python

"""
backend/tests/test_shipping_notice_tools.py
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
依赖:Flask 测试客户端、ShippingTask/Customer、货代 workflow 测试辅助。
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
"""
import json
from pathlib import Path
import pytest
from app import db
from app.models import (
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule,
ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingTask,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
ShippingTaskEvent, ShippingTaskInventoryLink,
)
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 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 _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。"""
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'])
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='t' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
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=fields[code]['id'], 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=fields[code]['id'], 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=published['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': fields['part_number']['id'], 'scope': 'line'},
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'},
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'},
]},
}},
header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id,
qty=quantity, field_values_json={
str(fields['part_number']['id']): part_number,
str(fields['reservation_id']['id']): reservation_id,
str(fields['qty']['id']): quantity,
},
))
task.order_snapshot_id = snapshot.id
db.session.flush()
@pytest.fixture(autouse=True)
def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch):
"""为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。"""
from app.services.shipping_notice import task_workflow
original = task_workflow.resolve_shipping_case_for_new_task
def _resolve_confirmed_case(**kwargs):
case = original(**kwargs)
if case.customer_id is not None:
return case
customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name="Tool 流程测试客户",
short_code="TST",
status="active",
)
db.session.add(customer)
db.session.flush()
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
return case
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
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"] = ""
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"},
json={"source_type": "manual"},
)
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"
res = client.post(
"/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"},
json={"source_type": "manual"},
)
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": "manual"},
)
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": "SN-REMOVED"},
)
assert response.status_code == 404
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):
"""契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
)
task_id = create_res.get_json()["task_id"]
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"task_no": task_id},
)
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", "/tools/get_batch_status"}
spec_text = str(spec)
assert "只读解释" in spec_text
assert "submit_decision" not in spec_text
def test_confirm_inventory_source_route_returns_json(app, client):
"""confirm_inventory_source HTTP 路由必须存在且可调用。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(
task_no="SN-HTTP-CONFIRM-SRC",
source_type="manual",
process_status="pending_review",
pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
)
db.session.add(task)
db.session.commit()
res = client.post(
"/api/shipping-notice/tools/confirm_inventory_source",
headers=headers,
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
)
assert res.status_code == 200
assert res.get_json()["status"] in {"ok", "needs_human", "running"}
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
@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"])
def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory")
db.session.add(task)
db.session.commit()
response = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision},
)
assert response.status_code == 200
body = response.get_json()
# These decisions must never reopen manual mapping or mutate the task.
assert body["status"] == "failed"
assert "已发布解析方案" in body["message"]
def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path):
"""重新上传库存只重置正式库存结果,不进入任务级字段映射。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingTask(
task_no="SN-REUPLOAD-INVENTORY",
source_type="manual",
process_status="matched",
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
match_status="fulfillable",
line_results_json=[{"part_number": "A001"}],
shortage_json={"lines": []},
export_file_path=str(tmp_path / "shipment.xlsx"),
export_file_name="shipment.xlsx",
)
db.session.add(task)
db.session.flush()
inventory_file = ShippingInventoryFile(
inventory_file_no="SIF-REUPLOAD-001",
storage_path=str(tmp_path / "inventory.xlsx"),
source_file_name="inventory.xlsx",
)
db.session.add(inventory_file)
db.session.flush()
link = ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inventory_file.id,
link_role="owner",
)
db.session.add(link)
db.session.commit()
response = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"},
)
assert response.status_code == 200
body = response.get_json()
assert body["status"] == "needs_human"
assert body["checkpoint"] == "upload_req"
assert body["human_options"] == ["upload_inventory_file", "retry_rpa"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
assert link.is_active is False
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inv_unavail"
assert task.inventory_lines_json is None
assert task.match_status is None
assert task.line_results_json is None
assert task.shortage_json is None
assert task.export_file_path is None
assert task.export_file_name is None
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": "SN-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": "SN-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": "SN-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": "SN-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": "SN-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": "SN-LEGACY-REMOVED"})
assert response.status_code == 404
@pytest.mark.auto_rpa
def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch):
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
trigger.mkdir()
inventory_drop.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.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)
task.process_status = "inventory_ready"
task.review_status = None
task.pending_human_reason = "inv_unavail"
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
task.match_status = "fulfillable"
task.shortage_json = {"lines": []}
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
task.export_file_path = str(tmp_path / "old.xlsx")
task.export_file_name = "old.xlsx"
task.upload_status = "failed"
task.upload_mode = "rpa"
task.upload_error_message = "old upload failed"
task.freight_ref_no = "OLD-REF"
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")
task.process_status = "parsed"
db.session.commit()
from app.services.shipping_notice import decision_workflow
with app.app_context():
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
assert retry_data["status"] == "running"
assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"}
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.review_status is None
assert task.inventory_lines_json is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.export_file_path is None
assert task.export_file_name is None
assert task.upload_status is None
assert task.upload_error_message is None
assert task.freight_ref_no is None
event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first()
assert event is not None
assert event.detail_json.get("force_refresh") is True
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@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["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.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)
task.process_status = "waiting_inventory"
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="inventory_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 = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["status"] == "needs_human"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
@pytest.mark.auto_rpa
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch):
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
from datetime import datetime, timedelta
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
trigger.mkdir()
inventory_drop.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.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)
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_EXHAUSTED
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")
task.process_status = "parsed"
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": idx + 1},
created_at=base_time + timedelta(seconds=idx),
)
)
db.session.commit()
from app.services.shipping_notice import decision_workflow
with app.app_context():
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
assert retry_data["status"] == "running"
assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.error_message is None
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
assert progress.get("current") == 1
assert progress.get("extra", {}).get("manual_retry_round") is True
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@pytest.mark.auto_rpa
def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path, monkeypatch):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
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["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={"conversation_id": "conv-rpa-batch-retry"},
)
batch_no = create_res.get_json()["batch_no"]
task_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={
"batch_no": batch_no,
"conversation_id": "conv-rpa-batch-retry",
"source_type": "manual",
},
)
task_id = task_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.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)
task.process_status = "waiting_inventory"
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="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=5),
)
)
db.session.commit()
with app.app_context():
result = retry_batch_pending_tasks(batch_no)
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["started"] == 1
assert result["skipped"] == 0
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
headers = _tool_headers(app)
first = ShippingTask(
task_no="SN-MULTI-CONV-001",
conversation_id="conv-test-multi",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
)
second = ShippingTask(
task_no="SN-MULTI-CONV-002",
conversation_id="conv-test-multi",
process_status="pending_review",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}],
)
with app.app_context():
db.session.add_all([first, second])
db.session.commit()
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"conversation_id": "conv-test-multi", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "failed"
assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"]
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"conversation_id": "conv-test-multi"},
)
status_data = status_res.get_json()
assert status_data["status"] == "failed"
assert "任务编号" in status_data["message"]
with app.app_context():
rows = {
task.task_no: task
for task in ShippingTask.query.filter(ShippingTask.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
.order_by(ShippingTask.task_no)
.all()
}
assert rows["SN-MULTI-CONV-001"].process_status == "pending_review"
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
import app.services.shipping_notice.decision_workflow as decision_workflow
captured: dict[str, object] = {}
def fake_ensure_inventory(payload):
captured.update(payload)
return {
"status": "running",
"task_id": payload["task_id"],
"message": "已触发库存获取(测试桩)",
}
monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory)
res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"},
)
data = res.get_json()
assert data["status"] == "running"
assert data["task_id"] == task_id
assert data["message"] == "已触发库存获取(测试桩)"
assert captured["task_id"] == task_id
assert captured["mode"] == "retry_rpa"
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": "SN-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.chat_actions import human_options_for_task
from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context():
task = ShippingTask(
task_no="SN-20260101-TEST0001",
source_type="manual",
process_status="rejected",
review_status="rejected",
)
assert human_options_for_task(task) == []
ui_state = build_task_ui_state(task)
assert ui_state["checkpoint"] == "rejected"
assert ui_state["action_buttons"] == []