Files
syops/backend/tests/test_shipping_notice_tools.py
T

1898 lines
71 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,
ShippingTaskEvent, ShippingTaskInventoryLink,
)
from app.services.shipping_notice.match import match_notice_lines
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",
}
@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)
@pytest.fixture(autouse=True)
def _stable_inventory_source_for_legacy_tool_flows(app):
"""为遗留库存 Tool 用例提供测试专用兜底路由,避免绕过当前 Source Gate。"""
with app.app_context():
rule = ShippingInventoryRoutingRule(
rule_code='TEST_TOOL_SOURCE_FALLBACK', rule_name='Legacy tool test source fallback',
scope='task', priority=-100, match_mode='all', status='published',
action_type='add_source_candidates', action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1,
)
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
condition_group=1, source_kind='system_fact', system_fact_key='task.customer_code', operator='is_empty',
expected_value_json=None, sequence=1,
))
db.session.add(rule)
db.session.commit()
def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None:
"""测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。"""
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"ship_to": "Dublin",
"lines": [{"part_number": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
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_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_shipping_notice_tool_flow(app, client):
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"},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
task_id = create_data["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{
"part_number": "A001",
"reservation_id": "R-1",
"qty": 10,
"uom": "EA",
"inventory_source_hint": "AWS Dublin",
}],
"confidence": 0.95,
},
},
)
assert parse_res.status_code == 200
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human", "running"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| 内部料号 | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
assert inv_res.status_code == 200
assert inv_res.get_json()["status"] == "ok"
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
assert match_res.status_code == 200
match_data = match_res.get_json()
assert match_data["status"] == "failed"
assert "订单解析版本" in match_data["message"] # 旧固定字段链不得绕过动态 Extraction。
with app.app_context():
auto_exported = ShippingTask.query.filter_by(task_no=task_id).first()
assert auto_exported is not None
assert auto_exported.match_status is None
assert auto_exported.export_file_path is None
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "failed"
assert "订单解析版本" in excel_res.get_json()["message"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path is None
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"task_id": task_id},
)
assert status_res.status_code == 200
assert status_res.get_json()["status"] == "ok"
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_shipping_notice_match_requires_dynamic_order_extraction(app, client):
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"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert match_res.status_code == 200
assert data["status"] == "failed"
assert "订单解析版本" in data["message"]
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "generate_shipment_excel" in (data.get("forbidden_next_tools") or [])
assert "upload_to_freight" in (data.get("forbidden_next_tools") or [])
def test_submit_decision_rematch_keeps_dynamic_order_extraction_gate(app, client, monkeypatch):
"""旧固定字段任务即使请求重新匹配,也不能绕过动态订单解析版本门禁。"""
headers = _tool_headers(app)
started: list[str] = []
from app.services.shipping_notice import decision_workflow
monkeypatch.setattr(
decision_workflow,
"start_task_orchestrator",
lambda task_no: started.append(str(task_no)) or True,
)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
rematch_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "rematch"},
)
data = rematch_res.get_json()
assert rematch_res.status_code == 200
assert data["status"] == "failed"
assert "订单解析版本" in data["message"]
assert started == []
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
def test_contract_submit_decision_rematch_cannot_bypass_dynamic_order_gate(app, client, monkeypatch):
"""契约:重新匹配仍须使用已接受的动态订单解析,不得回退旧固定字段。"""
headers = _tool_headers(app)
started: list[str] = []
from app.services.shipping_notice import decision_workflow
monkeypatch.setattr(
decision_workflow,
"start_task_orchestrator",
lambda task_no: started.append(str(task_no)) or True,
)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 20, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 1}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
rematch_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "rematch", "comment": "contract direct rematch"},
)
data = rematch_res.get_json()
assert rematch_res.status_code == 200
assert data["status"] == "failed"
assert data["task_id"] == task_id
assert "订单解析版本" in data["message"]
assert started == []
def test_contract_dynamic_order_shortage_and_rematch_recompute_inventory(app, client):
"""已接受动态订单解析必须执行真实匹配,库存更新后 rematch 应同步重算并解除缺口。"""
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"ship_to": "Dublin",
"lines": [{"part_number": "A001", "reservation_id": "AWS-311", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
inventory_fields = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(["part_number", "reservation_id", "available_qty"])
).all()
}
schema = ShippingOrderSchema(schema_code="SHIPPING_ORDER", display_name="Match contract")
part_field = ShippingOrderField(
id="test-order-part-number",
schema=schema,
field_code="part_number",
scope="line",
value_type="string",
)
reservation_field = ShippingOrderField(
id="test-order-reservation-id",
schema=schema,
field_code="reservation_id",
scope="line",
value_type="string",
)
version = ShippingOrderSchemaVersion(
schema=schema,
version=1,
status="published",
checksum="m" * 64,
definition_json={
"fields": [
{"id": part_field.id, "field_code": part_field.field_code, "scope": "line", "value_type": "string"},
{"id": reservation_field.id, "field_code": reservation_field.field_code, "scope": "line", "value_type": "string"},
]
},
)
db.session.add_all([schema, part_field, reservation_field, version])
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id,
input_snapshot_hash="m" * 64,
status="accepted",
)
db.session.add(extraction)
db.session.flush()
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key="1")
db.session.add(order_line)
db.session.flush()
part_decision = ShippingOrderFieldDecision(
extraction_id=extraction.id,
line_id=order_line.id,
field_id=part_field.id,
decision_status="accepted",
resolved_value_json="A001",
)
reservation_decision = ShippingOrderFieldDecision(
extraction_id=extraction.id,
line_id=order_line.id,
field_id=reservation_field.id,
decision_status="accepted",
resolved_value_json="AWS-311",
)
db.session.add_all([part_decision, reservation_decision])
db.session.flush()
db.session.add_all([
ShippingOrderFieldValue(
extraction_id=extraction.id,
line_id=order_line.id,
field_id=part_field.id,
value_text="A001",
decision_id=part_decision.id,
),
ShippingOrderFieldValue(
extraction_id=extraction.id,
line_id=order_line.id,
field_id=reservation_field.id,
value_text="AWS-311",
decision_id=reservation_decision.id,
),
])
task.current_order_extraction_id = extraction.id
task.inventory_lines_json = [{
inventory_fields["part_number"]: "A001",
inventory_fields["reservation_id"]: "AWS-311",
inventory_fields["available_qty"]: 5,
}]
task.process_status = "inventory_ready"
db.session.commit()
assert task.current_order_extraction_id == extraction.id
with app.app_context():
from app.services.shipping_notice.export import order_field_id_values
persisted_task = ShippingTask.query.filter_by(task_no=task_id).one()
persisted_extraction = db.session.get(ShippingOrderExtraction, persisted_task.current_order_extraction_id)
assert persisted_extraction is not None
assert persisted_extraction.status == "accepted"
assert order_field_id_values(persisted_task)[1][0]["test-order-part-number"] == "A001"
# Flask 测试 fixture 保持外层 app_context;清除其旧 Task identity,模拟真实独立请求重读数据库。
db.session.expire_all()
first_match = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
).get_json()
assert first_match["status"] == "needs_human", json.dumps(first_match, ensure_ascii=False)
assert first_match["checkpoint"] == "shortage_review"
assert first_match["stop_agent_turn"] is True
assert first_match["forbidden_next_tools"] == ["generate_shipment_excel", "upload_to_freight"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
updated_inventory = [dict(item) for item in task.inventory_lines_json]
updated_inventory[0][inventory_fields["available_qty"]] = 20
task.inventory_lines_json = updated_inventory
db.session.commit()
db.session.expire_all()
rematch = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "rematch"},
).get_json()
assert rematch["status"] == "ok", json.dumps(rematch, ensure_ascii=False)
assert "已重新完成库存匹配" in rematch["message"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
assert task.process_status == "matched"
assert task.match_status == "fulfillable"
assert task.shortage_json == {"lines": []}
assert task.line_results_json[0]["available_qty"] == 20.0
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_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"]
# 正式库存站点只能走已发布解析方案,Dify 不得恢复任务级临时映射入口。
assert "/tools/get_inventory_schema_preview" not in spec["paths"]
assert "/tools/apply_inventory_mapping" not in spec["paths"]
assert "/tools/upload_inventory_file" not in spec["paths"]
assert "/tools/submit_temporary_inventory_mapping_suggestion" in spec["paths"]
assert "/tools/confirm_inventory_source" in spec["paths"]
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
spec_text = str(spec)
assert "submit_decision" in spec_text
assert "match_inventory" in spec_text
assert "generate_shipment_excel" in spec_text
assert "upload_to_freight" in spec_text
assert "retry_task" in spec_text
assert "confirm_inventory_source" in spec_text
assert "唯一 task_id" in spec_text
assert "模糊指代不能直接推进" in spec_text
assert "状态机" in spec_text
assert "不得自行宣布完成" in spec_text
assert "不要在自然语言正文列出按钮清单" in spec_text
submit_desc = spec["paths"]["/tools/submit_decision"]["post"]["description"]
assert "唯一 task_id" in submit_desc
assert "模糊指代" in submit_desc
assert "needs_human 或 failed" in submit_desc
assert "按钮由 HXOPS 前端渲染" in submit_desc
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" in spec["paths"]
spec_text = str(spec)
assert "reference_context" in spec_text
assert "状态机" in spec_text
assert "不得自行改写成完成" in spec_text
assert "不要在自然语言正文列出按钮清单" in spec_text
assert "match_inventory" in spec_text
assert "generate_shipment_excel" in spec_text
assert "upload_to_freight" in spec_text
submit_desc = spec["paths"]["/tools/submit_decision"]["post"]["description"]
assert "唯一 task_id" in submit_desc
assert "模糊指代" in submit_desc
assert "按钮由 HXOPS 前端渲染" in submit_desc
@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_match_inventory_requires_reservation_id(app, client):
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"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "qty": 1, "uom": "EA"}]
db.session.commit()
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory as ensure_inventory_service,
upload_inventory_file as upload_inventory_file_service,
)
from io import BytesIO
from werkzeug.datastructures import FileStorage
direct_data = ensure_inventory_service({
"task_id": task_id,
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert direct_data["status"] == "needs_human", direct_data
assert direct_data.get("checkpoint") == "rsv_req"
assert not task.inventory_lines_json
upload_data = upload_inventory_file_service(
task_id,
FileStorage(stream=BytesIO(b"sku,qty\nA001,1"), filename="inventory.csv"),
)
assert upload_data["status"] == "needs_human"
assert upload_data.get("checkpoint") == "rsv_req"
from app.services.shipping_notice.fulfillment_workflow import match_inventory as match_inventory_service
match_data = match_inventory_service({"task_id": task_id})
assert match_data["status"] == "needs_human"
assert match_data.get("checkpoint") == "rsv_req"
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_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
headers = _tool_headers(app)
drop = tmp_path / "drop"
trigger = tmp_path / "triggers"
drop.mkdir()
trigger.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [
{
"part_number": "A001",
"reservation_id": "R-1",
"qty": 1,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
from app import db
from tests.conftest import seed_task_inventory_source
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-TOOLS-CB")
db.session.commit()
inv_file = drop / "stock.xlsx"
inv_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU", qty=20).getvalue())
from app.services.shipping_notice import tools as shipping_tools
with app.app_context():
data = shipping_tools.rpa_report_inventory(
{
"task_no": task_id,
"success": True,
"file_path": str(inv_file),
"run_no": "RUN-TOOLS-CB",
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
}
)
assert data["status"] == "ok"
assert data.get("checkpoint") == "ready_to_match"
assert "confirm_inventory_mapping" not in (data.get("human_options") or [])
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
def test_rpa_upload_callback(app, client, tmp_path):
headers = _tool_headers(app)
queue = tmp_path / "queue"
trigger = tmp_path / "upload_triggers"
queue.mkdir()
trigger.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(queue)
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
cb_res = client.post(
"/api/shipping-notice/rpa/upload-complete",
headers=headers,
json={"task_no": task_id, "success": True, "freight_ref_no": "FR-001"},
)
assert cb_res.status_code == 200
assert cb_res.get_json()["status"] == "ok"
assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001"
def test_generate_shipment_excel_writes_part_number_and_odm_id(app, client):
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"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"po_number": "SN-20260608-7FCBFA4B",
"lines": [
{
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [
{
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"available_qty": 9,
"odm_id": "16754796",
}
],
},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "failed"
assert "订单解析版本" in excel_res.get_json()["message"] # 旧固定字段链必须在动态 Extraction 门禁处阻断。
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
def test_confirm_parse_does_not_skip_inventory_match(app, client):
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"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"ship_to": "Dublin",
"lines": [{"part_number": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
)
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] in {"ok", "running", "needs_human"}
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
excel_data = excel_res.get_json()
assert excel_data["status"] == "failed"
assert "匹配" in excel_data["message"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status in {"parsed", "waiting_inventory"}
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "needs_human"
assert parse_data["checkpoint"] == "rsv_req"
assert "解析失败" in parse_data["message"]
assert "Reservation ID / COM ID" in parse_data["message"]
assert "confirm" not in parse_data.get("human_options", [])
assert called == {}
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "pending_review"
assert task.review_status == "rsv_req"
assert task.pending_human_reason == "rsv_req"
assert task.error_message and "解析失败" in task.error_message
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_blocks_invalid_nonempty_reservation_id(app, client, monkeypatch):
"""非空内部 hex ID 仍应被后端硬闸门阻断,并在 step_payload 留存解析问题。"""
import app.services.shipping_notice.task_workflow as task_workflow
monkeypatch.setattr(task_workflow, "start_task_orchestrator", lambda task_no: True)
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"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"raw_text": "Commodity group ID External reservation ID 1f1a682dfdc446a393415dee93eb36ce 3000092917",
"structured": {
"lines": [
{
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
"qty": 10,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
data = parse_res.get_json()
assert data["status"] == "needs_human"
assert data["checkpoint"] == "rsv_req"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert "reservation_id" not in task.lines_json[0]
validation = (task.step_payload_json or {})["parse_validation"]
assert validation["status"] == "needs_review"
assert validation["issues"][0]["reason"] == "invalid_format"
@pytest.mark.auto_rpa
def test_human_edit_revalidates_reservation_and_blocks_stale_confirm(app, client, monkeypatch):
"""人工修订应重算硬契约;非法值不能确认,改成合法字母型业务 ID 后清除阻断。"""
import app.services.shipping_notice.decision_workflow as decision_workflow
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", lambda task_no: True)
headers = _tool_headers(app)
task_id = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
).get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
"confidence": 0.4,
},
},
)
invalid_edit = client.post(
"/api/shipping-notice/tools/update_notice_line",
headers=headers,
json={"task_id": task_id, "line_index": 0, "patch": {"reservation_id": "f" * 32}},
)
assert invalid_edit.get_json()["status"] == "ok"
blocked = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_parse"},
).get_json()
assert blocked["status"] == "needs_human"
assert blocked["data"]["parse_validation"]["issues"][0]["reason"] == "invalid_format"
valid_edit = client.post(
"/api/shipping-notice/tools/update_notice_line",
headers=headers,
json={"task_id": task_id, "line_index": 0, "patch": {"reservation_id": "AWS-311"}},
)
assert valid_edit.get_json()["status"] == "ok"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
validation = (task.step_payload_json or {})["parse_validation"]
assert validation["status"] == "ready"
assert validation["issues"] == []
@pytest.mark.auto_rpa
def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(app, client):
"""两个值格式都合法时,原文列证据冲突仍必须进入 parse_review,不能靠高置信度自动通过。"""
headers = _tool_headers(app)
task_id = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
).get_json()["task_id"]
raw_text = "Part Number\tReservation ID\tQty\nA001\t3000092917\t2"
result = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"raw_text": raw_text,
"structured": {
"lines": [{"part_number": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
"confidence": 0.95,
},
},
).get_json()
assert result["status"] == "needs_human"
assert result["checkpoint"] == "parse_review"
assert result["data"]["parse_validation"]["issues"][0]["reason"] == "source_conflict"
@pytest.mark.auto_rpa
def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app, client):
headers = _tool_headers(app)
with app.app_context():
from app.models import User
user = User(username="parse_review_card_user", email="parse_review_card_user@example.com")
db.session.add(user)
db.session.commit()
user_id = user.id
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-no-parse-card", "user_id": user_id},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"conversation_id": "conv-no-parse-card",
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.4,
},
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "needs_human"
assert parse_data.get("checkpoint") == "parse_review"
with app.app_context():
assert db.session.query(ChatLog).filter_by(
session_id="conv-no-parse-card",
message_type="shipping-parse-review",
).count() == 0
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
headers = _tool_headers(app)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
parse_data = parse_res.get_json()
assert parse_data["status"] == "running"
assert "【发货通知解析确认】" in parse_data["message"]
assert "回复「确认」进入库存检查" not in parse_data["message"]
assert parse_data.get("checkpoint") != "parse_review"
assert called.get("task_no") == task_id
@pytest.mark.auto_rpa
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path, monkeypatch):
import app.services.shipping_notice.task_workflow as task_workflow
import app.services.shipping_notice.decision_workflow as decision_workflow
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
called: dict[str, str] = {}
def fake_start_task_orchestrator(task_no: str | None) -> bool:
called["task_no"] = str(task_no or "")
return True
monkeypatch.setattr(task_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
assert parse_res.get_json()["status"] == "running"
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "running"
assert "后台" in confirm_data["message"]
assert "ensure_inventory" not in confirm_data["message"]
assert "match_inventory" not in confirm_data["message"]
assert called.get("task_no") == task_id
@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
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 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": "R-1", "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
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 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
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 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
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 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_by_conversation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
"lines": [{"part_number": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
)
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"conversation_id": "conv-test-001", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] in {"ok", "running", "needs_human"}
assert confirm_data["task_id"] == task_id
dup_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
dup_data = dup_res.get_json()
assert dup_data["task_id"] == task_id
assert dup_data.get("checkpoint") == "task_exists"
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"] == []