feat(shipping-notice): 新增库存确认来源接口及相关逻辑

This commit is contained in:
hugo committed 2026-07-13 21:53:45 +08:00
1 parent a31735b689
commit 0a9bd6415d
69 files changed
+8442 -775

No files matched your search

+105 -17
View File
@@ -6,6 +6,7 @@ import pytest
from app import db
from app.models import ChatLog, 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):
@@ -17,6 +18,23 @@ def _tool_headers(app):
}
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"
@@ -389,6 +407,7 @@ def test_openapi_spec_public(app, client):
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)
@@ -410,6 +429,30 @@ def test_openapi_spec_public(app, client):
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"
@@ -495,6 +538,7 @@ def test_parse_inventory_empty_needs_human(app, client):
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,
@@ -620,11 +664,16 @@ def test_match_inventory_requires_reservation_id(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 1, "uom": "EA"}],
"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()
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
@@ -704,20 +753,38 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
)
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(["料号", "可用数量"])
ws.append(["A001", 20])
ws.append(["Warehouse ID", "料号", "可用数量"])
ws.append(["AWSDU", "A001", 20])
wb.save(inv_file)
wb.close()
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
json={
"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 cb_res.status_code == 200
data = cb_res.get_json()
@@ -890,8 +957,8 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["10-40594-001", "AWS-311", 5])
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)
@@ -909,7 +976,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
apply_res = client.post(
@@ -941,6 +1008,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
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")
@@ -976,15 +1044,16 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
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(["SKU", "Reservation ID", "Available Qty"])
ws.append(["A001", "R-1", 10])
ws.append(["A002", "R-2", 10])
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)
@@ -1019,6 +1088,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
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
@@ -1026,8 +1096,8 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["504-010213-001", "1000140351", 5])
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)
@@ -1067,6 +1137,7 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
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",
@@ -1086,6 +1157,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
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
@@ -1094,8 +1166,8 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Part No", "Resv", "On Hand"])
ws.append(["SKU-99", "R-1", 12])
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)
@@ -1143,7 +1215,8 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"ship_to": "Dublin",
"lines": [{"sku": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1437,7 +1510,11 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
@pytest.mark.auto_rpa
def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path):
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"
@@ -1478,6 +1555,8 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
"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()
retry_res = client.post(
@@ -1544,6 +1623,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
"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,
@@ -1568,7 +1648,11 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
@pytest.mark.auto_rpa
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path):
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
@@ -1602,6 +1686,8 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
"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(
@@ -1681,6 +1767,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
"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,
@@ -1849,6 +1936,7 @@ def test_parse_inventory_rejects_oversized_text(app, client):
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",