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

+187 -2
View File
@@ -1,4 +1,5 @@
import pytest
from pathlib import Path
def parse_api_error(body: dict) -> dict:
@@ -50,7 +51,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request):
def _shipping_notice_stable_auto_config(app, request, monkeypatch):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
tmp_path = request.getfixturevalue("tmp_path")
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
@@ -61,6 +62,10 @@ def _shipping_notice_stable_auto_config(app, request):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
@@ -78,6 +83,186 @@ def _shipping_notice_stable_auto_config(app, request):
reset_rpa_worker_alert_state_for_tests()
@pytest.fixture(autouse=True)
def _shipping_test_default_destination(monkeypatch, request):
"""
为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。
标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
"""
if request.node.get_closest_marker("inventory_source_gate"):
return
from app.services.shipping_notice import extract as extract_mod
import app.services.shipping_notice.task_workflow as task_workflow_mod
original = extract_mod.extract_notice_fields
def _extract_with_default_destination(*args, structured=None, **kwargs):
patched = structured
if isinstance(structured, dict):
patched = dict(structured)
has_dest = any(
str(patched.get(key) or "").strip()
for key in ("ship_to", "destination_city", "destination_port", "destination_country", "warehouse_hint")
) or isinstance(patched.get("destination"), dict)
if not has_dest:
for line in patched.get("lines") or []:
if isinstance(line, dict) and any(
str(line.get(key) or "").strip()
for key in ("ship_to", "destination_city", "destination_port", "warehouse_hint")
):
has_dest = True
break
if not has_dest:
patched.setdefault("ship_to", "Dublin")
patched.setdefault("destination", {"city": "Dublin", "country": "IE"})
return original(*args, structured=patched, **kwargs)
monkeypatch.setattr(extract_mod, "extract_notice_fields", _extract_with_default_destination)
monkeypatch.setattr(task_workflow_mod, "extract_notice_fields", _extract_with_default_destination)
def seed_task_inventory_source(
task: "ShippingTask",
*,
source_code: str = "DSV360_AWSDU",
) -> None:
"""测试辅助:为直接构造的 ShippingTask 写入稳定库存源独立字段。"""
from app.services.shipping_notice.inventory_source_rules import (
compute_routing_fingerprint,
extract_routing_context,
)
from app.services.shipping_notice.inventory_sources import (
get_inventory_source,
get_inventory_sources_config_version,
)
source = get_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
context = extract_routing_context(task)
resolution = resolve_inventory_source_identity(source, context)
if not resolution.ok or not resolution.identity:
raise ValueError(
f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}"
)
identity = resolution.identity
task.inventory_source_code = identity.source_code
task.inventory_source_type = identity.source_type
task.inventory_site_id = identity.site_id
task.inventory_warehouse_id = identity.warehouse_id
task.inventory_source_status = "resolved"
task.inventory_source_method = "rule_exact"
task.inventory_source_config_version = get_inventory_sources_config_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
def seed_rpa_inventory_trigger(
task: "ShippingTask",
*,
run_no: str = "RUN-TEST-001",
trigger_path: str | None = None,
) -> None:
"""测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。"""
from app import db
from app.services.shipping_notice.tool_common import log_task_event
if task.id is None:
db.session.add(task)
db.session.flush()
trigger = trigger_path or f"inventory_export_batch_{run_no}.json"
log_task_event(
task,
"inventory_rpa_triggered",
{"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False},
)
def inventory_xlsx_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
qty: int = 1,
) -> "BytesIO":
"""生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。"""
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "SKU", "Qty"])
ws.append([warehouse_id, sku, qty])
wb.save(buf)
wb.close()
buf.seek(0)
return buf
def inventory_csv_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
qty: int = 1,
delimiter: str = ",",
) -> "BytesIO":
"""生成带 Warehouse ID 列的库存 CSV,供身份校验测试使用。"""
from io import BytesIO
buf = BytesIO()
content = f"Warehouse ID{delimiter}SKU{delimiter}Qty\n{warehouse_id}{delimiter}{sku}{delimiter}{qty}\n"
buf.write(content.encode("utf-8"))
buf.seek(0)
return buf
def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Worker 身份字段。"""
return {
"source_code": str(task.inventory_source_code or ""),
"site_id": str(task.inventory_site_id or ""),
"warehouse_id": str(task.inventory_warehouse_id or ""),
}
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
"""构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。"""
from app.services.shipping_notice.inventory_sources import get_inventory_source
source = get_inventory_source(source_code)
if not source:
raise ValueError(f"unknown inventory source for tests: {source_code}")
item = {
"source_code": source_code,
"site_id": str(source.get("site_id") or ""),
"warehouse_id": str(source.get("warehouse_id") or ""),
}
item.update(overrides)
return item
def rpa_callback_payload(
task: "ShippingTask",
file_path: str | Path,
*,
run_no: str = "RUN-TEST-001",
status: str = "success",
) -> dict:
"""构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。"""
return {
"task_id": task.task_no,
"status": status,
"file_path": str(file_path),
"run_no": run_no,
"source_code": task.inventory_source_code,
"site_id": task.inventory_site_id,
"warehouse_id": task.inventory_warehouse_id,
}
def pytest_configure(config):
config.addinivalue_line(
"markers",
@@ -85,7 +270,7 @@ def pytest_configure(config):
)
config.addinivalue_line(
"markers",
"rpa_e2e: 真实货代 RPA 浏览器导出测试,默认跳过,需 FREIGHT_RPA_E2E=true",
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
)