Files
syops/backend/tests/test_shipping_notice_tools.py
T

2151 lines
77 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent
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)
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": [{"sku": "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(
[
{"sku": "A001", "reservation_id": "R-1", "qty": 1},
{"sku": "A002", "reservation_id": "R-2", "qty": 2},
],
[
{"sku": "A001", "reservation_id": "R-1", "available_qty": 1},
{"sku": "A002", "reservation_id": "R-2", "available_qty": 2},
],
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": [{
"sku": "A001",
"reservation_id": "R-1",
"qty": 10,
"uom": "EA",
"source_type": "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": [{"sku": "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"] == "running"
assert "订单" in match_data["message"]
assert "库存" in match_data["message"]
assert "A001" in match_data["message"]
with app.app_context():
auto_exported = ShippingTask.query.filter_by(task_no=task_id).first()
assert auto_exported is not None
assert auto_exported.export_file_path
assert auto_exported.process_status == "waiting_upload"
assert auto_exported.pending_human_reason == "upload_rpa_pending"
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"] == "ok"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
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_shortage_needs_human(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": [{"sku": "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": [{"sku": "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 data["status"] == "needs_human"
assert "订单" in data["message"]
assert "库存" in data["message"]
assert "缺口" in data["message"]
options = data.get("human_options") or []
assert "confirm" not in options
assert "reparse_inventory" in options
assert "rematch" in options
assert "generate_shipment_excel" in (data.get("forbidden_next_tools") or [])
assert "upload_to_freight" in (data.get("forbidden_next_tools") or [])
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
assert confirm_res.get_json()["status"] == "failed"
def test_submit_decision_rematch_reruns_match_and_returns_shortage(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": [{"sku": "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": [{"sku": "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"] == "needs_human"
assert "已重新完成库存匹配" in data["message"]
assert "缺口" in data["message"]
assert started == []
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
assert task.process_status == "pending_review"
assert task.review_status == "shortage_review"
assert task.pending_human_reason == "shortage"
assert task.match_status is not None
assert task.shortage_json is not None
assert task.line_results_json is not None
def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client, monkeypatch):
"""契约:重新匹配必须通过 submit_decision(rematch) 同步完成匹配,不经后台 orchestrator 二次点击。"""
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": [{"sku": "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": [{"sku": "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"] == "needs_human"
assert data["task_id"] == task_id
assert "已重新完成库存匹配" in data["message"]
assert started == []
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"]
assert "/tools/get_inventory_schema_preview" in spec["paths"]
assert "/tools/apply_inventory_mapping" in spec["paths"]
# 锁定 Dify Tool 契约:OpenAPI 暴露字符串,避免 Dify 画布无法选择上游 map_json 变量。
apply_mapping = spec["paths"]["/tools/apply_inventory_mapping"]["post"]["requestBody"]["content"][
"application/json"
]["schema"]
map_json_schema = apply_mapping["properties"]["map_json"]
assert map_json_schema["type"] == "string"
assert "JSON 字符串" in map_json_schema["description"]
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=[{"sku": "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
def test_parse_inventory_from_chat_text(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": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
inv_text = "料号\t可用数量\nA001\t10\nB002\t5"
parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
assert parse_inv.status_code == 200
data = parse_inv.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "align_review"
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "field_alignment" in data["data"]
assert "retry_rpa" in [button["id"] for button in data.get("action_buttons") or []]
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "needs_human"
assert confirm_data.get("checkpoint") == "align_review"
assert "Reservation ID" in (confirm_data.get("message") or "")
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
assert match_res.get_json()["status"] in {"failed", "needs_human"}
def test_parse_inventory_empty_needs_human(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"]
_parse_notice_for_stable_inventory_source(client, headers, task_id)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
body = res.get_json()
assert body.get("checkpoint") in {"map_infer", "upload_req"}
assert body.get("human_options") is not None or body.get("action_buttons")
def test_match_by_aws_sku_and_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": "AWS",
"lines": [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"},
{"sku": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"},
],
"confidence": 0.95,
},
},
)
inv_text = (
"AWS Sku\tCOM ID\tQty Available\n"
"10-40594-001\tAWS-311\t2\n"
"10-40594-001\tORD-3002\t0\n"
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
results = {r["reservation_id"]: r for r in data["data"]["line_results"]}
assert results["AWS-311"]["line_status"] == "ok"
assert results["ORD-3002"]["line_status"] == "shortage"
def test_match_inventory_blocked_before_mapping_confirm(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": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
assert blocked.get("checkpoint") == "align_review"
assert blocked.get("stop_agent_turn") is True
assert "field_alignment" in blocked["data"]
mapping = blocked["data"]["field_alignment"]
assert mapping["inventory_columns"]["mapping"]["sku"]["source_column"] == "AWS Sku"
assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID"
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": [{"sku": "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 = [{"sku": "A001", "qty": 1, "uom": "EA"}]
db.session.commit()
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory as ensure_inventory_service,
parse_inventory as parse_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": [{"sku": "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
parse_data = parse_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert parse_data["status"] == "needs_human"
assert parse_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_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
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",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
correct_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "map_infer"
assert data.get("stop_agent_turn") is True
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
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["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["FREIGHT_RPA_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"]
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()
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "料号", "可用数量"])
ws.append(["AWSDU", "A001", 20])
wb.save(inv_file)
wb.close()
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",
"site_id": "AWSDU",
"warehouse_id": "AWSDU",
}
)
assert data["status"] == "needs_human"
assert data.get("checkpoint") in {"map_infer", "align_review"}
assert "confirm_inventory_mapping" 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["FREIGHT_UPLOAD_QUEUE_DIR"] = str(queue)
app.config["FREIGHT_RPA_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": [{"sku": "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": [{"sku": "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_vendor_part_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": [
{
"sku": "504-010213-001",
"vendor_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": [
{
"sku": "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"] == "ok"
from openpyxl import load_workbook
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
wb = load_workbook(task.export_file_path, read_only=True)
header_ws = wb["PVMI Pull Request Header"]
detail_ws = wb["PVMI Pull Request Detail"]
assert header_ws.cell(4, 6).value == "16754796"
assert detail_ws.cell(4, 4).value == "504-010213-001"
wb.close()
def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000
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",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
upload_res = client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={
"task_id": task_id,
"file": (buf, "inventory.xlsx"),
},
)
assert upload_res.status_code == 200
upload_data = upload_res.get_json()
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"map_json": {
**preview["suggested_mapping"],
"match_rule": "LLM:Reservation Order 对齐订单 reservation_id,汇总 Qty Available。",
},
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data.get("checkpoint") == "align_review"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:")
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm"
with app.app_context():
assert ShippingInventoryMapping.query.filter_by(customer_code="GLOBAL").count() >= 1
def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_path, monkeypatch):
"""已手工上传完成的票不能被后续批次库存快照重新带回 RPA 上传链路。"""
from io import BytesIO
from openpyxl import Workbook
from app.models import ShippingBatch, ShippingTaskInventoryLink
from app.services.shipping_notice import inventory_file_store
from tests.conftest import seed_task_inventory_source
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "freight" / "upload_queue")
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(tmp_path / "freight" / "upload_triggers")
started_task_nos: list[str] = []
def fake_start_task_orchestrator(task_no: str) -> bool:
started_task_nos.append(task_no)
return True
monkeypatch.setattr(inventory_file_store, "start_task_orchestrator", fake_start_task_orchestrator, raising=False)
with app.app_context():
batch = ShippingBatch(batch_no="SB-COMPLETED-LOCK", file_count=2)
completed = ShippingTask(
task_no="SN-20260629-DONE0001",
batch=batch,
source_type="manual",
process_status="uploaded",
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
batch_index=1,
batch_total=2,
)
pending = ShippingTask(
task_no="SN-20260629-PEND0002",
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}],
batch_index=2,
batch_total=2,
)
seed_task_inventory_source(pending, source_code="DSV360_AWSDU")
db.session.add_all([batch, completed, pending])
db.session.commit()
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "SKU", "Reservation ID", "Available Qty"])
ws.append(["AWSDU", "A001", "R-1", 10])
ws.append(["AWSDU", "A002", "R-2", 10])
wb.save(buf)
wb.close()
buf.seek(0)
upload_res = client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": "SN-20260629-PEND0002", "file": (buf, "inventory.xlsx")},
)
assert upload_res.status_code == 200
with app.app_context():
completed = ShippingTask.query.filter_by(task_no="SN-20260629-DONE0001").one()
pending = ShippingTask.query.filter_by(task_no="SN-20260629-PEND0002").one()
completed_links = ShippingTaskInventoryLink.query.filter_by(task_id=completed.id, is_active=True).count()
pending_links = ShippingTaskInventoryLink.query.filter_by(task_id=pending.id, is_active=True).count()
assert completed.process_status == "uploaded"
assert completed.pending_human_reason is None
assert completed_links == 0
assert pending_links == 1
assert "SN-20260629-DONE0001" not in started_task_nos
def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
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_notice_for_stable_inventory_source(client, headers, task_id)
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": task_id, "file": (buf, "inventory.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
},
)
apply_data = apply_res.get_json()
match_rule = apply_data["data"]["field_alignment"]["match_rule"]
assert "AWS Sku" in match_rule
assert "COM ID" in match_rule
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback"
def test_get_inventory_schema_preview(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
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_notice_for_stable_inventory_source(client, headers, task_id)
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
headers=headers,
json={"task_id": task_id},
)
assert missing.get_json()["checkpoint"] == "upload_req"
def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
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_notice_for_stable_inventory_source(client, headers, task_id)
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "Part No", "Resv", "On Hand"])
ws.append(["AWSDU", "SKU-99", "R-1", 12])
wb.save(buf)
wb.close()
buf.seek(0)
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": task_id, "file": (buf, "inv.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "Part No",
"reservation_id": "Resv",
"available_qty": "On Hand",
},
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["available_qty"] == 12
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": [{"sku": "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": [{"sku": "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": [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"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": [{"sku": "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 = "AWS Sku\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": [{"sku": "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": [{"sku": "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": [{"sku": "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["FREIGHT_RPA_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": [{"sku": "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
def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, monkeypatch):
import app.services.shipping_notice.decision_workflow as decision_workflow
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(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator)
monkeypatch.setattr(task_workflow, "start_task_orchestrator", lambda _task_no: 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": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "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_db_id = task.id
task.inventory_lines_json = [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
db.session.commit()
with app.app_context():
db.session.add(
ShippingTaskEvent(
task_id=task_db_id,
event_type="inventory_mapping_inferred",
detail_json={
"column_meta": {
"headers": ["Reservation ID", "SKU", "Qty Available"],
"field_mapping": {
"reservation_id": "Reservation ID",
"sku": "SKU",
"available_qty": "Qty Available",
},
"mapping": {
"reservation_id": {"source_column": "Reservation ID"},
"sku": {"source_column": "SKU"},
"available_qty": {"source_column": "Qty Available"},
},
}
},
)
)
db.session.commit()
persisted = ShippingTask.query.filter_by(task_no=task_id).first()
assert persisted is not None
assert persisted.review_status == "align_review"
confirm_data = decision_workflow.submit_decision(
{"task_id": task_id, "decision": "confirm_inventory_mapping"}
)
assert confirm_data["status"] == "running"
assert "后台继续处理匹配与后续步骤" in confirm_data["message"]
assert called.get("task_no") == task_id
@pytest.mark.auto_rpa
def test_retry_rpa_force_refresh_clears_inventory_mapping_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["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["FREIGHT_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.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
task.inventory_lines_json = [{"sku": "OLD", "reservation_id": "R-1", "available_qty": 3}]
task.match_status = "fulfillable"
task.shortage_json = {"lines": []}
task.line_results_json = [{"sku": "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):
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_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
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.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["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["FREIGHT_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.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):
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["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
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.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": [{"sku": "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=[{"sku": "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=[{"sku": "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_rejects_oversized_text(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
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_notice_for_stable_inventory_source(client, headers, task_id)
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": "x" * 200},
)
data = res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "upload_req"
assert "过大" in data["message"]
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"] == []