feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动
外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
911afa0f73
commit
4c2a7e2a23
145 files changed
+11695
-4214
No files matched your search
@@ -2,10 +2,12 @@
|
||||
|
||||
用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与
|
||||
GET /matchings/{id} 进度恢复;无权限 403、未认证 401;
|
||||
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7)。
|
||||
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7);
|
||||
证据压缩包路径与当天清单(Task 5)。
|
||||
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes、factories。
|
||||
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
|
||||
in_transit_transfer Agent 授权校验。
|
||||
in_transit_transfer Agent 授权校验。证据下载用内存字节替换
|
||||
file_asset_storage.get_bytes,清单用 presigned_get_url 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -49,8 +51,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file):
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
# 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
|
||||
del record_kind
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -233,7 +236,7 @@ def test_executable_items_lists_ready_rows_with_decoration(
|
||||
# 行装饰的文件对账在 matching_service 命名空间——与执行门禁②同口径替身。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
|
||||
lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "d" * 64},
|
||||
)
|
||||
_create_matching(client, admin_headers)
|
||||
@@ -605,9 +608,36 @@ def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client,
|
||||
)
|
||||
for i in range(25)
|
||||
]
|
||||
class _Rows:
|
||||
"""分页测试用的查询替身:count/offset/limit/all 与 Query 同形。"""
|
||||
|
||||
def __init__(self, items):
|
||||
self._items = items
|
||||
self._offset = 0
|
||||
self._limit = None
|
||||
|
||||
def count(self):
|
||||
return len(self._items)
|
||||
|
||||
def offset(self, start):
|
||||
self._offset = start
|
||||
return self
|
||||
|
||||
def limit(self, size):
|
||||
self._limit = size
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
end = None if self._limit is None else self._offset + self._limit
|
||||
return self._items[self._offset:end]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.backlog_service.circle_ledger_records_scope_union",
|
||||
lambda: rows,
|
||||
lambda: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.backlog_service.pending_ledger_query",
|
||||
lambda **_kwargs: _Rows(rows),
|
||||
)
|
||||
|
||||
legacy = client.get(f"{API_PREFIX}/backlog/pending-match", headers=admin_headers)
|
||||
@@ -628,13 +658,33 @@ def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client,
|
||||
|
||||
|
||||
def test_list_transfer_sources(app, client, admin_headers):
|
||||
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
|
||||
"""来源实例列表:返回启用来源,并附入站/出站两条证据流。
|
||||
|
||||
扁平 file_status / has_ready_file 必须等于入站那条,供尚未改完的前端。
|
||||
生产侧漏掉 streams、把两条合成一条、或扁平字段改读出站,本用例都会失败。
|
||||
"""
|
||||
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
sources = response.get_json()["data"]
|
||||
assert isinstance(sources, list)
|
||||
# 测试种子来源 DSV360_AWSDU(dbs)应在列表中
|
||||
assert any(item["source_code"] == "DSV360_AWSDU" for item in sources)
|
||||
dsv = next(item for item in sources if item["source_code"] == "DSV360_AWSDU")
|
||||
# 两条都返回且入站在前:前端按 record_kind 过滤,扁平字段仍跟入站。
|
||||
# 种子来源没有出站报表配置,出站必须是 unconfigured,不能抄入站投影。
|
||||
assert len(dsv["streams"]) == 2
|
||||
assert dsv["streams"][0]["record_kind"] == "inbound"
|
||||
assert set(dsv["streams"][0]) == {
|
||||
"record_kind", "file_status", "has_ready_file", "file_no", "file_sha256",
|
||||
}
|
||||
assert dsv["streams"][1] == {
|
||||
"record_kind": "outbound",
|
||||
"file_status": "unconfigured",
|
||||
"has_ready_file": False,
|
||||
"file_no": None,
|
||||
"file_sha256": None,
|
||||
}
|
||||
assert dsv["file_status"] == dsv["streams"][0]["file_status"]
|
||||
assert dsv["has_ready_file"] == dsv["streams"][0]["has_ready_file"]
|
||||
for item in sources:
|
||||
assert item["source_code"]
|
||||
assert item["platform"] in {"dbs", "crane"}
|
||||
@@ -647,6 +697,27 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_reparse_current_without_file_returns_422(client, admin_headers):
|
||||
# [断言意图] 没有出站归档时重解析是 422,不是 202 抓取中。
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
|
||||
headers=admin_headers,
|
||||
json={"record_kind": "outbound"},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert response.get_json()["error"]["code"] == "TRANSFER.CURRENT_REPARSE_NO_FILE"
|
||||
|
||||
|
||||
def test_reparse_current_forbidden(client, unauthorized_headers):
|
||||
# [断言意图] 无调拨权限不能重解析。
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/DSV360_AWSDU/reparse",
|
||||
headers=unauthorized_headers,
|
||||
json={"record_kind": "inbound"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 4:retry-rpa 对 parse_failed 先本地重解析(成功 200+ready / 仍失败 ok=False;
|
||||
# 两条路径均不触发 RPA、不返回 202/fetching)
|
||||
@@ -801,6 +872,310 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h
|
||||
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||
|
||||
|
||||
def _ensure_hub_to_hub_both_streams():
|
||||
"""启用 hub_to_hub,范围规则显式包含入站与出站两条证据流。
|
||||
|
||||
核心逻辑:类型表没有 record_kinds 列。record_kinds_of 从 record_kind
|
||||
规则推导;不写该规则时也会得到双流。这里用 match=in 写明两个值,
|
||||
批量重试才能同时看到入站与出站。已存在则直接复用。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
create_config,
|
||||
get_by_code,
|
||||
)
|
||||
|
||||
try:
|
||||
return get_by_code("hub_to_hub")
|
||||
except ValidationError:
|
||||
return create_config({
|
||||
"code": "hub_to_hub",
|
||||
"names": {"zh-CN": "仓间调拨"},
|
||||
"enabled": True,
|
||||
"scope_rules": [
|
||||
{"field": "record_kind", "match": "in", "values": ["inbound", "outbound"]},
|
||||
],
|
||||
})
|
||||
|
||||
|
||||
def _stream_status(file_status: str) -> dict:
|
||||
"""投影替身的最小状态字典(与 resolve_source_file_status 四键一致)。"""
|
||||
ready = file_status == "ready"
|
||||
return {
|
||||
"file_status": file_status,
|
||||
"has_ready_file": ready,
|
||||
"file_no": "a.xlsx" if ready else None,
|
||||
"file_sha256": "abc" if ready or file_status == "parse_failed" else None,
|
||||
}
|
||||
|
||||
|
||||
def test_batch_retry_skips_ready_inbound_and_triggers_outbound(app, client, admin_headers, monkeypatch):
|
||||
"""HUB 仓间调拨:入站已就绪不重抓,出站未就绪才触发。"""
|
||||
import app.api.in_transit_transfer as api_module
|
||||
|
||||
_ensure_hub_to_hub_both_streams()
|
||||
|
||||
def fail_inbound(**kwargs):
|
||||
raise AssertionError("inbound batch")
|
||||
|
||||
called = {}
|
||||
|
||||
def record_outbound(**kwargs):
|
||||
called["codes"] = kwargs["source_codes"]
|
||||
return {"ok": True, "triggered": True}
|
||||
|
||||
def status(*, source_code, record_kind="inbound"):
|
||||
if record_kind == "outbound":
|
||||
return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None}
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "a.xlsx", "file_sha256": "abc"}
|
||||
|
||||
monkeypatch.setattr(api_module, "trigger_inbound_rpa_batch", fail_inbound)
|
||||
monkeypatch.setattr(api_module, "trigger_outbound_rpa_batch", record_outbound)
|
||||
monkeypatch.setattr(api_module, "resolve_source_file_status", status)
|
||||
response = client.post("/api/in-transit-transfer/sources/retry-rpa-batch", json={
|
||||
"source_codes": ["DSV360_AWSBI"],
|
||||
"transfer_type": "hub_to_hub",
|
||||
}, headers=admin_headers)
|
||||
# 断言意图:入站 ready 不进 trigger;出站 none 只写出站 batch,并回 202。
|
||||
assert response.status_code == 202
|
||||
assert called["codes"] == ["DSV360_AWSBI"]
|
||||
|
||||
|
||||
def test_retry_rpa_outbound_triggers_outbound_rpa(app, client, admin_headers, monkeypatch):
|
||||
"""单源重试带 record_kind=outbound 时走出站触发,不碰入站。"""
|
||||
called = {}
|
||||
|
||||
def fail_inbound(**kwargs):
|
||||
raise AssertionError("inbound")
|
||||
|
||||
def record_outbound(**kwargs):
|
||||
called["source_code"] = kwargs["source_code"]
|
||||
called["reason"] = kwargs["reason"]
|
||||
return {"ok": True, "callback_id": "cb-out"}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
|
||||
fail_inbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa",
|
||||
record_outbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": _stream_status("none"),
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/DSV360_AWSBI/retry-rpa",
|
||||
headers=admin_headers,
|
||||
json={"record_kind": "outbound"},
|
||||
)
|
||||
# 断言意图:缺省才是入站;显式 outbound 必须 202 且 reason 为出站重试。
|
||||
assert response.status_code == 202
|
||||
assert called["source_code"] == "DSV360_AWSBI"
|
||||
assert called["reason"] == "transfer_retry_outbound"
|
||||
assert response.get_json()["data"]["file_status"] == "fetching"
|
||||
|
||||
|
||||
def test_retry_rpa_outbound_parse_failed_retriggers_outbound_rpa(app, client, admin_headers, monkeypatch):
|
||||
"""出站 parse_failed 重新触发出站 RPA,不走入站本地重解析。"""
|
||||
called = {"sync": 0, "outbound": 0}
|
||||
|
||||
def status(*, source_code, record_kind="inbound"):
|
||||
if record_kind == "outbound":
|
||||
return _stream_status("parse_failed")
|
||||
return _stream_status("ready")
|
||||
|
||||
def fake_sync(**kwargs):
|
||||
called["sync"] += 1
|
||||
return True
|
||||
|
||||
def fail_inbound(**kwargs):
|
||||
raise AssertionError("inbound")
|
||||
|
||||
def record_outbound(**kwargs):
|
||||
called["outbound"] += 1
|
||||
return {"ok": True, "callback_id": "cb-out"}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
|
||||
status,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback",
|
||||
fake_sync,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
|
||||
fail_inbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa",
|
||||
record_outbound,
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/DSV360_AWSBI/retry-rpa",
|
||||
headers=admin_headers,
|
||||
json={"record_kind": "outbound"},
|
||||
)
|
||||
# 断言意图:本地重解析只留给入站;出站解析失败仍是一次 RPA 重抓。
|
||||
assert response.status_code == 202
|
||||
assert called["sync"] == 0
|
||||
assert called["outbound"] == 1
|
||||
|
||||
|
||||
def test_batch_retry_records_unconfigured_without_trigger(app, client, admin_headers, monkeypatch):
|
||||
"""未配置的流不写 trigger,结果 ok=false 且沿用既有配置缺失码。"""
|
||||
_ensure_hub_to_hub_both_streams()
|
||||
called = {}
|
||||
|
||||
def record_inbound(**kwargs):
|
||||
called["inbound"] = list(kwargs["source_codes"])
|
||||
return {"ok": True, "triggered": True, "results": []}
|
||||
|
||||
def record_outbound(**kwargs):
|
||||
called["outbound"] = list(kwargs["source_codes"])
|
||||
return {"ok": True, "triggered": True, "results": []}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch",
|
||||
record_inbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch",
|
||||
record_outbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": _stream_status("unconfigured"),
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch",
|
||||
headers=admin_headers,
|
||||
json={"source_codes": ["DSV360_AWSBI"], "transfer_type": "hub_to_hub"},
|
||||
)
|
||||
# 断言意图:两条流都是 unconfigured 时两个 batch 都不写,并各记配置缺失码。
|
||||
assert response.status_code == 200
|
||||
assert "inbound" not in called and "outbound" not in called
|
||||
body = response.get_json()["data"]
|
||||
assert body["ok"] is False
|
||||
assert body["triggered"] is False
|
||||
assert body["results"] == [
|
||||
{
|
||||
"source_code": "DSV360_AWSBI",
|
||||
"record_kind": "inbound",
|
||||
"ok": False,
|
||||
"error_code": "RPA_INBOUND_CONFIG_MISSING",
|
||||
},
|
||||
{
|
||||
"source_code": "DSV360_AWSBI",
|
||||
"record_kind": "outbound",
|
||||
"ok": False,
|
||||
"error_code": "RPA_OUTBOUND_CONFIG_MISSING",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_batch_retry_skips_fetching_stream(app, client, admin_headers, monkeypatch):
|
||||
"""抓取中的流不写入 trigger。"""
|
||||
_ensure_hub_to_hub_both_streams()
|
||||
called = {}
|
||||
|
||||
def record(**kwargs):
|
||||
called["codes"] = list(kwargs["source_codes"])
|
||||
return {"ok": True, "triggered": True, "results": []}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch",
|
||||
record,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch",
|
||||
record,
|
||||
)
|
||||
|
||||
def status(*, source_code, record_kind="inbound"):
|
||||
if record_kind == "outbound":
|
||||
return _stream_status("fetching")
|
||||
return _stream_status("ready")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
|
||||
status,
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch",
|
||||
headers=admin_headers,
|
||||
json={"source_codes": ["DSV360_AWSBI"], "transfer_type": "hub_to_hub"},
|
||||
)
|
||||
# 断言意图:ready 与 fetching 都跳过,不回 202,结果为空。
|
||||
assert response.status_code == 200
|
||||
assert called == {}
|
||||
body = response.get_json()["data"]
|
||||
assert body["ok"] is True
|
||||
assert body["triggered"] is False
|
||||
assert body["results"] == []
|
||||
|
||||
|
||||
def test_batch_retry_groups_one_batch_per_stream(app, client, admin_headers, monkeypatch):
|
||||
"""同一请求最多一个入站 batch 和一个出站 batch,结果带 record_kind。"""
|
||||
_ensure_hub_to_hub_both_streams()
|
||||
calls = []
|
||||
|
||||
def record_inbound(**kwargs):
|
||||
calls.append(("inbound", list(kwargs["source_codes"]), kwargs["reason"]))
|
||||
return {
|
||||
"ok": True,
|
||||
"triggered": True,
|
||||
"results": [{"source_code": code, "ok": True} for code in kwargs["source_codes"]],
|
||||
}
|
||||
|
||||
def record_outbound(**kwargs):
|
||||
calls.append(("outbound", list(kwargs["source_codes"]), kwargs["reason"]))
|
||||
return {
|
||||
"ok": True,
|
||||
"triggered": True,
|
||||
"results": [{"source_code": code, "ok": True} for code in kwargs["source_codes"]],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch",
|
||||
record_inbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch",
|
||||
record_outbound,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": _stream_status("none"),
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch",
|
||||
headers=admin_headers,
|
||||
json={
|
||||
"source_codes": ["DSV360_AWSBI", "DSV360_AWSDU"],
|
||||
"transfer_type": "hub_to_hub",
|
||||
},
|
||||
)
|
||||
# 断言意图:两个来源按流合并成各一次 batch,而不是逐来源各写一个文件。
|
||||
assert response.status_code == 202
|
||||
assert calls == [
|
||||
("inbound", ["DSV360_AWSBI", "DSV360_AWSDU"], "transfer_retry_inbound"),
|
||||
("outbound", ["DSV360_AWSBI", "DSV360_AWSDU"], "transfer_retry_outbound"),
|
||||
]
|
||||
pairs = {
|
||||
(item["source_code"], item["record_kind"])
|
||||
for item in response.get_json()["data"]["results"]
|
||||
}
|
||||
assert pairs == {
|
||||
("DSV360_AWSBI", "inbound"),
|
||||
("DSV360_AWSBI", "outbound"),
|
||||
("DSV360_AWSDU", "inbound"),
|
||||
("DSV360_AWSDU", "outbound"),
|
||||
}
|
||||
|
||||
|
||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||
@@ -978,8 +1353,9 @@ def _custom_transfer_deps(monkeypatch, rows: list[dict], stocks: list[tuple[str,
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
# 执行门禁②(文件版本对账)替身:与 transfer_deps 夹具同语义。
|
||||
del record_kind
|
||||
return {"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "d" * 64}
|
||||
|
||||
@@ -1679,3 +2055,282 @@ def test_pending_match_reparse_forbidden_without_permission(app, client, unautho
|
||||
json={"source_code": "X"})
|
||||
assert preview.status_code == 403
|
||||
assert execute.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 5:证据压缩包按记录类型分目录;当天清单只列可用文件的大小与预签地址
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
EVIDENCE_SOURCE = "DSV360_AWSBI"
|
||||
_INBOUND_ONLY_TYPE = "evidence_inbound_only"
|
||||
|
||||
|
||||
def _ensure_inbound_only_type():
|
||||
"""启用一个范围规则把记录类型收成只要 inbound 的调拨类型。
|
||||
|
||||
核心逻辑:没有 record_kinds 列。equals inbound 的 record_kind 规则经
|
||||
record_kinds_of 只得到入站。已存在则复用。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
create_config,
|
||||
get_by_code,
|
||||
)
|
||||
|
||||
try:
|
||||
return get_by_code(_INBOUND_ONLY_TYPE)
|
||||
except ValidationError:
|
||||
return create_config({
|
||||
"code": _INBOUND_ONLY_TYPE,
|
||||
"names": {"zh-CN": "仅入站证据"},
|
||||
"enabled": True,
|
||||
"scope_rules": [
|
||||
{"field": "record_kind", "match": "equals", "values": ["inbound"]},
|
||||
],
|
||||
})
|
||||
|
||||
|
||||
def _ensure_evidence_source():
|
||||
"""保证 DSV360_AWSBI 来源存在(压缩包路径用这个编码)。"""
|
||||
from tests.services.in_transit_transfer.factories import seed_inbound_reparse_source
|
||||
|
||||
source, _profile = seed_inbound_reparse_source(EVIDENCE_SOURCE)
|
||||
return source
|
||||
|
||||
|
||||
def _seed_evidence_file(
|
||||
source,
|
||||
*,
|
||||
kind: str,
|
||||
filename: str,
|
||||
storage_key: str,
|
||||
sha: str,
|
||||
file_size: int,
|
||||
created_at: datetime,
|
||||
deleted: bool = False,
|
||||
):
|
||||
"""写入一条入站或出站归档。created_at 决定是否落在当天可用窗口。"""
|
||||
from app.models import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
)
|
||||
|
||||
if kind == "outbound":
|
||||
unit_model, file_model = FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile
|
||||
else:
|
||||
unit_model, file_model = FreightRpaInboundUnitRun, FreightRpaInboundReportFile
|
||||
unit = unit_model(
|
||||
source_id=source.id,
|
||||
source_code=source.source_code,
|
||||
connector_type=source.connector_type,
|
||||
warehouse_id=source.fixed_warehouse_id,
|
||||
callback_id=f"{kind}-{sha[:16]}",
|
||||
status="success",
|
||||
config_snapshot_json={},
|
||||
trigger_snapshot_json={},
|
||||
result_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = file_model(
|
||||
unit_run_id=unit.id,
|
||||
storage_provider="minio",
|
||||
storage_bucket="test",
|
||||
storage_key=storage_key,
|
||||
original_filename=filename,
|
||||
file_size=file_size,
|
||||
sha256=sha,
|
||||
created_at=created_at,
|
||||
archive_deleted_at=created_at if deleted else None,
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
return report
|
||||
|
||||
|
||||
def _patch_archive_bytes(monkeypatch, objects: dict[str, bytes]) -> None:
|
||||
"""用内存字节替换对象存储读取,避免下载测试连接 MinIO。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes",
|
||||
lambda storage_key: objects[storage_key],
|
||||
)
|
||||
|
||||
|
||||
def _zip_entries(response) -> dict[str, bytes]:
|
||||
"""用 zipfile 读响应体,返回归档路径到原始字节。"""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(response.data)) as archive:
|
||||
return {name: archive.read(name) for name in archive.namelist()}
|
||||
|
||||
|
||||
def test_evidence_zip_packs_inbound_only_when_scope_rule_equals_inbound(
|
||||
app, client, admin_headers, monkeypatch,
|
||||
):
|
||||
"""范围规则 record_kind equals inbound 时,压缩包只有入站最新文件。"""
|
||||
from datetime import timedelta
|
||||
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
_ensure_inbound_only_type()
|
||||
_seed_evidence_file(
|
||||
source, kind="inbound", filename="OldInbound.xlsx",
|
||||
storage_key="evidence/old-inbound", sha="31" * 32, file_size=10,
|
||||
created_at=now - timedelta(minutes=10),
|
||||
)
|
||||
_seed_evidence_file(
|
||||
source, kind="inbound", filename="Inbound.xlsx",
|
||||
storage_key="evidence/inbound", sha="11" * 32, file_size=12,
|
||||
created_at=now,
|
||||
)
|
||||
_seed_evidence_file(
|
||||
source, kind="outbound", filename="Outbound.xlsx",
|
||||
storage_key="evidence/outbound", sha="22" * 32, file_size=13,
|
||||
created_at=now,
|
||||
)
|
||||
_patch_archive_bytes(monkeypatch, {
|
||||
"evidence/old-inbound": b"OLD-INBOUND",
|
||||
"evidence/inbound": b"INBOUND-RAW",
|
||||
"evidence/outbound": b"OUTBOUND-RAW",
|
||||
})
|
||||
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/inbound-files",
|
||||
headers=admin_headers,
|
||||
json={"source_codes": [EVIDENCE_SOURCE], "transfer_type": _INBOUND_ONLY_TYPE},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
entries = _zip_entries(response)
|
||||
# 断言意图:目录是记录类型/来源/文件名,且只打最新一份入站,不打出站。
|
||||
assert entries == {f"inbound/{EVIDENCE_SOURCE}/Inbound.xlsx": b"INBOUND-RAW"}
|
||||
assert not any(name.startswith("outbound/") for name in entries)
|
||||
assert "evidence-files-1.zip" in response.headers.get("Content-Disposition", "")
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
).one()
|
||||
assert audit.aggregate_id == EVIDENCE_SOURCE
|
||||
|
||||
|
||||
def test_evidence_zip_packs_both_kinds_without_record_kind_rule(
|
||||
app, client, admin_headers, monkeypatch,
|
||||
):
|
||||
"""没有 record_kind 范围规则时,入站和出站就绪文件都打进包。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
_seed_evidence_file(
|
||||
source, kind="inbound", filename="Inbound.xlsx",
|
||||
storage_key="evidence/both-inbound", sha="41" * 32, file_size=12,
|
||||
created_at=now,
|
||||
)
|
||||
_seed_evidence_file(
|
||||
source, kind="outbound", filename="Outbound.xlsx",
|
||||
storage_key="evidence/both-outbound", sha="42" * 32, file_size=13,
|
||||
created_at=now,
|
||||
)
|
||||
_patch_archive_bytes(monkeypatch, {
|
||||
"evidence/both-inbound": b"INBOUND-RAW",
|
||||
"evidence/both-outbound": b"OUTBOUND-RAW",
|
||||
})
|
||||
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/inbound-files",
|
||||
headers=admin_headers,
|
||||
json={"source_codes": [EVIDENCE_SOURCE], "transfer_type": "in_transit_to_hub"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
entries = _zip_entries(response)
|
||||
# 断言意图:默认类型只有单号前缀规则,两种就绪文件都按记录类型分目录。
|
||||
assert entries == {
|
||||
f"inbound/{EVIDENCE_SOURCE}/Inbound.xlsx": b"INBOUND-RAW",
|
||||
f"outbound/{EVIDENCE_SOURCE}/Outbound.xlsx": b"OUTBOUND-RAW",
|
||||
}
|
||||
assert "evidence-files-2.zip" in response.headers.get("Content-Disposition", "")
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
).one()
|
||||
assert audit.event_type == "TRANSFER_INBOUND_FILES_DOWNLOADED"
|
||||
|
||||
|
||||
def test_evidence_files_list_returns_today_size_and_presigned_url(
|
||||
app, client, admin_headers, monkeypatch,
|
||||
):
|
||||
"""当天清单返回全部可用入站文件的大小与预签地址,不解析行数。"""
|
||||
from datetime import timedelta
|
||||
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
newer = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Inbound.xlsx",
|
||||
storage_key="evidence/list-new", sha="51" * 32, file_size=111,
|
||||
created_at=now,
|
||||
)
|
||||
older = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Older.xlsx",
|
||||
storage_key="evidence/list-old", sha="52" * 32, file_size=222,
|
||||
created_at=now - timedelta(minutes=20),
|
||||
)
|
||||
_seed_evidence_file(
|
||||
source, kind="inbound", filename="Yesterday.xlsx",
|
||||
storage_key="evidence/list-yesterday", sha="53" * 32, file_size=333,
|
||||
created_at=now - timedelta(days=2),
|
||||
)
|
||||
_seed_evidence_file(
|
||||
source, kind="inbound", filename="Deleted.xlsx",
|
||||
storage_key="evidence/list-deleted", sha="54" * 32, file_size=444,
|
||||
created_at=now, deleted=True,
|
||||
)
|
||||
signed = []
|
||||
|
||||
def _presign(storage_key, *, expires_seconds):
|
||||
signed.append((storage_key, expires_seconds))
|
||||
return f"https://files.test/{storage_key}"
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.presigned_get_url",
|
||||
_presign,
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
rows = response.get_json()["data"]
|
||||
# 断言意图:当天两份都在,隔日与已清理不在;字段是文件大小和预签地址,没有行数。
|
||||
assert [row["original_filename"] for row in rows] == ["Inbound.xlsx", "Older.xlsx"]
|
||||
assert rows[0]["file_id"] == newer.id
|
||||
assert rows[1]["file_id"] == older.id
|
||||
assert rows[0]["file_size"] == 111
|
||||
assert rows[1]["file_size"] == 222
|
||||
assert rows[0]["sha256"] == "51" * 32
|
||||
assert rows[0]["created_at"] == now.isoformat()
|
||||
assert rows[0]["presigned_url"] == "https://files.test/evidence/list-new"
|
||||
assert rows[1]["presigned_url"] == "https://files.test/evidence/list-old"
|
||||
for row in rows:
|
||||
assert set(row) == {
|
||||
"file_id", "original_filename", "created_at", "sha256", "file_size", "presigned_url",
|
||||
}
|
||||
assert "rows" not in row and "row_count" not in row
|
||||
assert signed == [
|
||||
("evidence/list-new", 300),
|
||||
("evidence/list-old", 300),
|
||||
]
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
).one()
|
||||
assert audit.aggregate_id == EVIDENCE_SOURCE
|
||||
@@ -267,9 +267,13 @@ def test_admin_create_rejects_non_object_body(app, client, admin_headers):
|
||||
def test_chat_transfer_types_returns_enabled_only_with_minimal_fields(
|
||||
app, client, warehouse_headers,
|
||||
):
|
||||
"""chat 列表:仅启用项、sort_order 升序、最小暴露(不含范围规则/仓库定义等)。"""
|
||||
"""chat 列表:仅启用项、sort_order 升序、最小暴露,并附推导出的 record_kinds。"""
|
||||
_seed_type(sort_order=20)
|
||||
_seed_type(code="hub_to_line", sort_order=10)
|
||||
_seed_type(
|
||||
code="hub_to_line",
|
||||
sort_order=10,
|
||||
scope_rules=[{"field": "record_kind", "match": "equals", "values": ["inbound"]}],
|
||||
)
|
||||
_seed_type(code="disabled_type", enabled=False, sort_order=1)
|
||||
response = client.get(CHAT_PREFIX, headers=warehouse_headers)
|
||||
assert response.status_code == 200
|
||||
@@ -279,9 +283,15 @@ def test_chat_transfer_types_returns_enabled_only_with_minimal_fields(
|
||||
# [断言意图] 仅 enabled 限定 + sort_order 升序是前端类型选择器的顺序契约。
|
||||
assert [item["code"] for item in data] == ["hub_to_line", "in_transit_to_hub"]
|
||||
for item in data:
|
||||
# [断言意图] 最小暴露硬契约:响应 key 集合恰为四键——scope_rules/
|
||||
# warehouse_config/description 属管理端配置资产,禁止泄露。
|
||||
assert set(item.keys()) == {"code", "names", "sort_order", "transform_rules"}
|
||||
# [断言意图] 最小暴露:在原四键上只增加 record_kinds。scope_rules /
|
||||
# warehouse_config / description 仍不回传。record_kinds 由
|
||||
# record_kinds_of 现算:hub_to_line 只写 inbound,另一条没有
|
||||
# 记录类型规则所以入站和出站都要。
|
||||
assert set(item.keys()) == {
|
||||
"code", "names", "sort_order", "transform_rules", "record_kinds",
|
||||
}
|
||||
assert data[0]["record_kinds"] == ["inbound"]
|
||||
assert data[1]["record_kinds"] == ["inbound", "outbound"]
|
||||
assert data[0]["transform_rules"] == [
|
||||
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
|
||||
]
|
||||
|
||||
@@ -700,6 +700,8 @@ def dbs_ready_file() -> dict:
|
||||
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
|
||||
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按
|
||||
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
|
||||
【T−2 成熟封顶 2026-10-21】rows 异动日期取 2026-08-04(= 业务日 08-06 的
|
||||
T−2 恰好成熟边界);更晚日期(T−1/当天)已被圈档封顶排除,不得再作夹具日期。
|
||||
"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
@@ -712,13 +714,13 @@ def dbs_ready_file() -> dict:
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-04", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-04", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
|
||||
"material_name": "控制器组件", "specification": "标准型 / 48V",
|
||||
"movement_date": "2026-08-05", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-04", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -728,6 +730,7 @@ def crane_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
|
||||
|
||||
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
|
||||
异动日期=T−2 成熟边界(见 dbs_ready_file 注释)。
|
||||
"""
|
||||
return {
|
||||
"source_code": "CRANE-SZ",
|
||||
@@ -740,14 +743,14 @@ def crane_ready_file() -> dict:
|
||||
"rows": [
|
||||
{"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200",
|
||||
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
|
||||
"movement_date": "2026-08-05", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
|
||||
"movement_date": "2026-08-04", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def same_day_inbound_file() -> dict:
|
||||
"""含业务日期当天异动数据的文件(成熟规则已退役:当天数据正常进匹配)。
|
||||
"""含业务日期当天异动数据的文件(T−2 成熟封顶 2026-10-21:当天未成熟不匹配)。
|
||||
|
||||
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
|
||||
"""
|
||||
|
||||
@@ -40,8 +40,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file):
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
# 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
|
||||
del record_kind
|
||||
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
|
||||
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -48,7 +48,7 @@ def test_bulk_matching_300_invoices(transfer_db):
|
||||
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
started = time.perf_counter()
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
elapsed = time.perf_counter() - started
|
||||
assert summary.counts.executable_count == 300
|
||||
assert summary.counts.file_invoice_count == 300
|
||||
|
||||
@@ -79,9 +79,10 @@ def wecom_fake() -> FakeWeCom:
|
||||
def patch_source_file_status(monkeypatch):
|
||||
"""执行文件对账门禁替身工厂:替换 execution_service 的来源文件状态投影。
|
||||
|
||||
用途:execute_items 门禁②按去重来源调 resolve_source_file_status(真实查询
|
||||
收料文件表);单元测试注入替身避免触碰表数据。缺省全部来源投影为
|
||||
ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file 行版本戳同源)。
|
||||
用途:execute_items 门禁②按 (来源, record_kind) 调 resolve_source_file_status
|
||||
(真实查询收料/出站文件表);单元测试注入替身避免触碰表数据。缺省全部
|
||||
来源投影为 ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file
|
||||
行版本戳同源)。record_kind 入参接受但不区分,存量用例仍按来源给 sha。
|
||||
|
||||
Args:
|
||||
mapping: source_code → sha 映射;值为 None 表示该来源无可用文件
|
||||
@@ -92,7 +93,8 @@ def patch_source_file_status(monkeypatch):
|
||||
def _patch(mapping: dict[str, str | None] | None = None) -> None:
|
||||
table = mapping or {}
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
del record_kind # 本替身按来源给 sha;出站分流用例自行覆盖本函数。
|
||||
if source_code in table:
|
||||
sha = table[source_code]
|
||||
if sha is None:
|
||||
|
||||
@@ -252,7 +252,8 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
|
||||
movement_date: str = "2026-08-05",
|
||||
transfer_executed: bool = False,
|
||||
executed_doc_no: str | None = None,
|
||||
updated_at: datetime | None = None):
|
||||
updated_at: datetime | None = None,
|
||||
record_kind: str = "inbound"):
|
||||
"""插一条旧映射库存异动档行(清空重建用例种子;业务值=旧映射形态)。
|
||||
|
||||
Args:
|
||||
@@ -263,6 +264,7 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
|
||||
quantity / material_code / material_name / movement_date: 旧业务值。
|
||||
transfer_executed / executed_doc_no: 封存形态注入。
|
||||
updated_at: 显式更新时间(封存不动行断言用)。
|
||||
record_kind: inbound(默认)或 outbound。
|
||||
Returns:
|
||||
已入库的 TransferMovementLedger。
|
||||
"""
|
||||
@@ -270,7 +272,7 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
row = TransferMovementLedger(
|
||||
source_code=source_code, record_kind="inbound",
|
||||
source_code=source_code, record_kind=record_kind,
|
||||
doc_no=doc_no, line_no=line_no, line_seq="", in_out_flag=in_out_flag,
|
||||
carton_id="", lot_no=lot_no,
|
||||
material_code=material_code, material_name=material_name,
|
||||
@@ -282,3 +284,79 @@ def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1"
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return row
|
||||
|
||||
|
||||
def seed_outbound_reparse_source(source_code: str, *, profile_code: str | None = None,
|
||||
version: int = 1, status: str = "published"):
|
||||
"""建「启用来源 + 已发布 outbound 解析规则 + 出站配置绑定」种子(幂等)。
|
||||
|
||||
用途:清空并重新解析出站流用例。若来源已存在则只补出站配置/规则。
|
||||
|
||||
Returns:
|
||||
(FreightRpaSource, FreightRpaParsingProfile) 元组。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
)
|
||||
|
||||
source, _inbound = seed_inbound_reparse_source(source_code)
|
||||
existing = source.outbound_report_config
|
||||
if existing is not None and existing.parsing_profile is not None:
|
||||
return source, existing.parsing_profile
|
||||
|
||||
resolved_code = profile_code or f"OUT_{source_code}"
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose="outbound", profile_code=resolved_code, display_name=resolved_code,
|
||||
version=version, status=status, file_format="xlsx",
|
||||
definition_json={
|
||||
"sheet_name": "Receipt", "header_row_index": 1,
|
||||
"field_mapping": dict(INBOUND_MOVEMENT_FIELD_MAPPING),
|
||||
},
|
||||
structure_definition_json={},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
if existing is None:
|
||||
db.session.add(FreightRpaOutboundReportConfig(
|
||||
source_id=source.id, parsing_profile_id=profile.id,
|
||||
report_path_json={"report_name": "Outbound"},
|
||||
query_parameters_json=[],
|
||||
))
|
||||
else:
|
||||
existing.parsing_profile_id = profile.id
|
||||
db.session.commit()
|
||||
return source, profile
|
||||
|
||||
|
||||
def seed_reparse_outbound_archive_file(source, *, sha: str, storage_key: str,
|
||||
created_at: datetime,
|
||||
archive_expires_at: datetime | None = None,
|
||||
callback_id: str | None = None):
|
||||
"""建一条出站执行单元 + 归档文件行(清空重建出站用例种子)。
|
||||
|
||||
Returns:
|
||||
已入库的 FreightRpaOutboundReportFile。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun
|
||||
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id="AWSDU",
|
||||
callback_id=callback_id or f"out-cb-{sha[:12]}",
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = FreightRpaOutboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=storage_key, original_filename=f"{callback_id or 'out'}.xlsx",
|
||||
file_size=16, sha256=sha, created_at=created_at,
|
||||
archive_expires_at=archive_expires_at,
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
return report
|
||||
@@ -6,7 +6,7 @@
|
||||
占用行幸存;④证据缺失(归档已清理/过保留期/无溯源)的行保留并计入
|
||||
kept_unrebuildable;⑤预检形状(files/profile/clearable_rows/kept_rows)。
|
||||
依赖:factories(来源/归档/档行种子 + FakeArchiveStorage + build_movement_xlsx)、
|
||||
app fixture。
|
||||
ledger_sync.movement_file_version、app fixture。
|
||||
逻辑:归档文件字节经假存储注入(monkeypatch file_asset_storage.get_bytes);
|
||||
归档文件 created_at 均早于 NOW 数日——若 repository 仍带运行期「当日抓取」
|
||||
门禁则清单为空,本套件即红(锁定维护路径无当日门禁)。
|
||||
@@ -27,6 +27,7 @@ from app.models import (
|
||||
TransferMovementLedger,
|
||||
)
|
||||
from app.services.in_transit_transfer import evidence_sync
|
||||
from app.services.in_transit_transfer.ledger_sync import movement_file_version
|
||||
from app.services.in_transit_transfer.backlog_reparse_service import (
|
||||
preview_pending_match_reparse,
|
||||
reparse_pending_match,
|
||||
@@ -107,7 +108,8 @@ def test_reparse_clears_and_relands(app, archive_storage):
|
||||
# (真实 source_file_id / sha256: 版本戳),不再是旧映射值。
|
||||
assert a1.quantity == "500" and a1.material_code == "MAT-1"
|
||||
assert a1.file_sha256 == SHA_A and a1.source_file_id == file_a.id
|
||||
assert str(a1.file_version).startswith("sha256:a")
|
||||
# [断言意图] 重建写入的版本戳走 movement_file_version,与运行期落档同一串。
|
||||
assert a1.file_version == movement_file_version(SHA_A)
|
||||
assert a1.movement_date == "2026-08-05"
|
||||
# [断言意图] 文件顺序:按归档时间升序逐文件重落(files 概要 A 在前)。
|
||||
assert [f["sha256"] for f in outcome.files] == [SHA_A, SHA_B]
|
||||
@@ -118,6 +120,7 @@ def test_reparse_clears_and_relands(app, archive_storage):
|
||||
assert event.aggregate_id == SOURCE
|
||||
payload = event.after_json
|
||||
assert payload["operator"] == "admin" and payload["source_code"] == SOURCE
|
||||
assert payload["record_kind"] == "inbound"
|
||||
assert payload["cleared"] == 3 and payload["reinserted"] == 3
|
||||
assert payload["date_skipped"] == 0 and payload["kept"] == 0
|
||||
assert payload["profile_code"] == profile.profile_code
|
||||
@@ -244,7 +247,10 @@ def test_preview_shape(app, archive_storage):
|
||||
|
||||
preview = preview_pending_match_reparse(source_code=SOURCE, now=NOW)
|
||||
|
||||
assert set(preview.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
|
||||
assert set(preview.keys()) == {
|
||||
"record_kind", "files", "profile", "clearable_rows", "kept_rows",
|
||||
}
|
||||
assert preview["record_kind"] == "inbound"
|
||||
assert preview["profile"] == {"code": profile.profile_code, "version": 1}
|
||||
assert [f["sha256"] for f in preview["files"]] == [SHA_A, SHA_B] # 归档时间升序
|
||||
assert preview["files"][0]["archived_at"] == datetime(2026, 10, 10, 8, 0, 0).isoformat()
|
||||
@@ -370,3 +376,66 @@ def test_reparse_writes_collapse_audit_for_multi_material_same_key(app, archive_
|
||||
# [断言意图] 重建概要事件携带坍缩计数(运维一眼判断本次重建是否有数据质量降级)。
|
||||
reparse_event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
|
||||
assert reparse_event.after_json["collapses"] == 1
|
||||
|
||||
|
||||
def test_outbound_reparse_clears_and_relands_without_touching_inbound(app, archive_storage):
|
||||
"""出站流清空重建:只动 record_kind=outbound,入站档行幸存。"""
|
||||
source, profile = factories.seed_outbound_reparse_source(SOURCE)
|
||||
out_file = factories.seed_reparse_outbound_archive_file(
|
||||
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-a.xlsx",
|
||||
created_at=datetime(2026, 10, 10, 8, 0, 0),
|
||||
)
|
||||
archive_storage.objects[f"archive/{SOURCE}/out-a.xlsx"] = factories.build_movement_xlsx([
|
||||
["HOX-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-08-05"],
|
||||
])
|
||||
# 入站旧行 + 出站旧行并存:出站重建不得误删入站。
|
||||
factories.seed_reparse_ledger_row(
|
||||
SOURCE, "ASN-IN1", source_file_id=None, sha=OLD_SHA, record_kind="inbound",
|
||||
)
|
||||
factories.seed_reparse_ledger_row(
|
||||
SOURCE, "HOX-O1", source_file_id=out_file.id, sha=OLD_SHA,
|
||||
quantity="1", record_kind="outbound", in_out_flag="O",
|
||||
)
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="inbound").count() == 1
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").count() == 1
|
||||
|
||||
outcome = reparse_pending_match(
|
||||
source_code=SOURCE, operator="admin", now=NOW, record_kind="outbound",
|
||||
)
|
||||
|
||||
assert outcome.record_kind == "outbound"
|
||||
assert (outcome.cleared, outcome.reinserted) == (1, 1)
|
||||
db.session.expire_all()
|
||||
# [断言意图] 入站行未动;出站行按新映射重落。
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="inbound", doc_no="ASN-IN1").count() == 1
|
||||
out_row = TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound", doc_no="HOX-O1").one()
|
||||
assert out_row.quantity == "120" and out_row.material_code == "MAT-O1"
|
||||
assert out_row.source_file_id == out_file.id and out_row.file_sha256 == SHA_A
|
||||
# [断言意图] 出站重建的版本戳同样走共享函数。
|
||||
assert out_row.file_version == movement_file_version(SHA_A)
|
||||
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
|
||||
assert event.after_json["record_kind"] == "outbound"
|
||||
assert event.after_json["profile_code"] == profile.profile_code
|
||||
|
||||
|
||||
def test_outbound_preview_uses_outbound_archives(app, archive_storage):
|
||||
"""出站预检只统计 outbound 归档与档行。"""
|
||||
source, profile = factories.seed_outbound_reparse_source(SOURCE)
|
||||
out_file = factories.seed_reparse_outbound_archive_file(
|
||||
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-preview.xlsx",
|
||||
created_at=datetime(2026, 10, 10, 8, 0, 0),
|
||||
)
|
||||
factories.seed_reparse_ledger_row(
|
||||
SOURCE, "HOX-P1", source_file_id=out_file.id, sha=SHA_A, record_kind="outbound",
|
||||
)
|
||||
preview = preview_pending_match_reparse(
|
||||
source_code=SOURCE, now=NOW, record_kind="outbound",
|
||||
)
|
||||
assert preview["record_kind"] == "outbound"
|
||||
assert preview["profile"] == {"code": profile.profile_code, "version": 1}
|
||||
assert preview["clearable_rows"] == 1
|
||||
assert len(preview["files"]) == 1 and preview["files"][0]["sha256"] == SHA_A
|
||||
@@ -59,7 +59,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
|
||||
updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。
|
||||
业务稳定键下,触碰前后列表顺序完全一致。
|
||||
"""
|
||||
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
|
||||
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-04)与 HOX-002 不进池,构造两笔 blocked
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
# 手工造第二笔 blocked:不同收料日期、更晚创建
|
||||
second = TransferInvoiceItem(
|
||||
@@ -75,7 +75,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
|
||||
db.session.commit()
|
||||
|
||||
invoices = [dto.invoice_no for dto in list_backlog()]
|
||||
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过
|
||||
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-04),尽管它刚被触碰过
|
||||
# (两行同来源,数据源键不改变先后)。
|
||||
assert invoices == ["HOM-002", "HOM-001"]
|
||||
|
||||
@@ -142,4 +142,5 @@ def test_backlog_summary_includes_pending_match_count(transfer_db, dbs_ready_fil
|
||||
summary = backlog_summary()
|
||||
|
||||
assert summary.pending_match_count == 1 # [断言意图] 待匹配桶计数独立于行桶
|
||||
assert summary.matchable_count == 1 # [断言意图] 范围内未匹配行同时计入可匹配
|
||||
assert summary.recoverable_count == 1 # [断言意图] 原行桶语义保持
|
||||
@@ -0,0 +1,277 @@
|
||||
"""current_file_reparse:当前归档重解析(不触发 RPA)守卫矩阵。
|
||||
|
||||
用途:锁定「当前最新可用入站/出站归档本地重解析落档」——成功落档、幂等跳过、
|
||||
入站/出站 schema 失败标 parse_failed、无规则/无文件 fail-closed、
|
||||
非 schema 异常与存储 AppError 回 ok=false 且不回标。
|
||||
依赖:factories、movement_file_version、app fixture、core.errors.ServiceUnavailableError;
|
||||
出站种子 DSV360_AWSDU,入站种子 seed_inbound_reparse_source。
|
||||
逻辑:归档字节经假存储注入;不新增 RPA 执行单元。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
FreightRpaParsingProfile,
|
||||
TransferAuditEvent,
|
||||
TransferMovementLedger,
|
||||
)
|
||||
from app.services.in_transit_transfer.current_file_reparse import reparse_current_file
|
||||
from app.services.in_transit_transfer.ledger_sync import movement_file_version
|
||||
from tests.services.in_transit_transfer import factories
|
||||
|
||||
pytestmark = [pytest.mark.usefixtures("app")]
|
||||
|
||||
SOURCE = "DSV360_AWSDU"
|
||||
STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def outbound_storage(monkeypatch):
|
||||
"""归档假存储:替换单例 get_bytes(所有引用方同源)。"""
|
||||
fake = factories.FakeArchiveStorage()
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
|
||||
return fake
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def archive_storage(monkeypatch):
|
||||
"""归档假存储:注入 FakeArchiveStorage 并替换单例 get_bytes(所有引用方同源)。"""
|
||||
fake = factories.FakeArchiveStorage()
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
|
||||
return fake
|
||||
|
||||
|
||||
def _seed_outbound_world(*, profile_status: str = "published") -> FreightRpaOutboundReportFile:
|
||||
"""出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。
|
||||
|
||||
Returns:
|
||||
已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。
|
||||
"""
|
||||
from app.models import FreightRpaSource
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=SOURCE).one()
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose="outbound", profile_code=f"OUT_{SOURCE}", display_name=SOURCE,
|
||||
version=1, status=profile_status, file_format="xlsx",
|
||||
definition_json={
|
||||
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
|
||||
"sheet_name": "Receipt", "header_row_index": 1,
|
||||
},
|
||||
structure_definition_json={},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
db.session.add(FreightRpaOutboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={"report_name": "Outbound"},
|
||||
query_parameters_json=[],
|
||||
parsing_profile_id=profile.id,
|
||||
))
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
schedule_run_id=None, source_id=source.id, source_code=SOURCE,
|
||||
connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001",
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
import hashlib
|
||||
|
||||
digest = hashlib.sha256(b"outbound evidence workbook").hexdigest()
|
||||
report = FreightRpaOutboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx",
|
||||
file_size=16, sha256=digest,
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
return report
|
||||
|
||||
|
||||
def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage):
|
||||
# [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。
|
||||
report = _seed_outbound_world()
|
||||
runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||||
])
|
||||
|
||||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert result.ok is True
|
||||
assert result.file_id == report.id
|
||||
assert result.inserted == 1
|
||||
assert result.file_status == "ready"
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1
|
||||
assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before
|
||||
assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1
|
||||
|
||||
|
||||
def test_reparse_same_outbound_file_skips_existing_row(outbound_storage):
|
||||
# [断言意图] 同一份摘要再解析一次不插入第二行。
|
||||
_seed_outbound_world()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||||
])
|
||||
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert again.ok is True
|
||||
assert again.inserted == 0
|
||||
assert again.skipped == 1
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").count() == 1
|
||||
|
||||
|
||||
def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage):
|
||||
# [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。
|
||||
report = _seed_outbound_world()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
|
||||
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
|
||||
|
||||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert result.ok is False
|
||||
assert result.file_status == "parse_failed"
|
||||
assert result.inserted == 0
|
||||
assert "missing_invoice_no" in (result.error_message or "")
|
||||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||||
assert marked.parse_failed_at is not None
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").count() == 0
|
||||
|
||||
|
||||
def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage):
|
||||
# [断言意图] 规则未发布不是文件错误,不写 parse_failed。
|
||||
report = _seed_outbound_world(profile_status="draft")
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||||
])
|
||||
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE"
|
||||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||||
assert marked.parse_failed_at is None
|
||||
|
||||
|
||||
def test_reparse_without_file_raises():
|
||||
# [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
reparse_current_file(
|
||||
source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE"
|
||||
assert exc_info.value.http_status == 422
|
||||
|
||||
|
||||
def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch, caplog):
|
||||
# [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。
|
||||
report = _seed_outbound_world()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||||
])
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError("value too long for varchar(64)")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows",
|
||||
_boom,
|
||||
)
|
||||
with caplog.at_level(logging.ERROR):
|
||||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
|
||||
assert "varchar(64)" in (result.error_message or "")
|
||||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||||
assert marked.parse_failed_at is None
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").count() == 0
|
||||
assert any(
|
||||
"TRANSFER_CURRENT_REPARSE_FAILED" in record.message and "kind=outbound" in record.message
|
||||
for record in caplog.records
|
||||
)
|
||||
|
||||
|
||||
def test_reparse_storage_unavailable_returns_ok_false(outbound_storage, monkeypatch):
|
||||
# [断言意图] 存储读抛 ServiceUnavailableError 时走 ok=false,不把文件标成解析失败。
|
||||
report = _seed_outbound_world()
|
||||
|
||||
def _unavailable(_storage_key: str) -> bytes:
|
||||
raise ServiceUnavailableError("object storage unreachable")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes",
|
||||
_unavailable,
|
||||
)
|
||||
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
|
||||
assert "object storage unreachable" in (result.error_message or "")
|
||||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||||
assert marked.parse_failed_at is None
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").count() == 0
|
||||
|
||||
|
||||
def test_reparse_inbound_inserts_ledger(archive_storage):
|
||||
# [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。
|
||||
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW")
|
||||
storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx"
|
||||
report = factories.seed_reparse_archive_file(
|
||||
source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow())
|
||||
archive_storage.objects[storage_key] = factories.build_movement_xlsx([
|
||||
["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"],
|
||||
])
|
||||
|
||||
result = reparse_current_file(
|
||||
source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow())
|
||||
|
||||
assert result.ok is True
|
||||
assert result.file_id == report.id
|
||||
assert result.inserted == 1
|
||||
row = TransferMovementLedger.query.filter_by(
|
||||
source_code="CRANE_REPARSE_NOW", record_kind="inbound").one()
|
||||
assert row.doc_no == "ASN-I1"
|
||||
assert row.file_version == movement_file_version("c" * 64)
|
||||
|
||||
|
||||
def test_reparse_inbound_schema_failure_marks_file_and_lands_nothing(archive_storage):
|
||||
# [断言意图] 入站单号缺失是结构失败:零档行,入站文件变为 parse_failed。
|
||||
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_SCHEMA")
|
||||
storage_key = "archive/CRANE_REPARSE_SCHEMA/current.xlsx"
|
||||
report = factories.seed_reparse_archive_file(
|
||||
source, sha="d" * 64, storage_key=storage_key, created_at=datetime.utcnow())
|
||||
archive_storage.objects[storage_key] = factories.build_movement_xlsx(
|
||||
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
|
||||
|
||||
result = reparse_current_file(
|
||||
source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound", now=datetime.utcnow())
|
||||
|
||||
assert result.ok is False
|
||||
assert result.file_status == "parse_failed"
|
||||
assert result.inserted == 0
|
||||
assert "missing_invoice_no" in (result.error_message or "")
|
||||
marked = FreightRpaInboundReportFile.query.filter_by(id=report.id).one()
|
||||
assert marked.parse_failed_at is not None
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound").count() == 0
|
||||
@@ -102,7 +102,7 @@ def test_sync_inserts_ledger_rows_without_erp(app, dbs_ready_file):
|
||||
# 数量真相源,与旧 items movement_quantity 等值)。
|
||||
assert hom.quantity == "1200"
|
||||
assert hom.material_code == "MAT-001" and hom.lot_no == "LOT-10"
|
||||
assert hom.movement_date == "2026-08-05"
|
||||
assert hom.movement_date == "2026-08-04"
|
||||
assert hom.file_version == "v3" and hom.file_sha256 == "d" * 64
|
||||
assert hom.sheet_name == "Receipt" and hom.row_no == 10 # 组内首行溯源
|
||||
assert TransferInvoiceItem.query.count() == 0 # [断言意图] 停写 items
|
||||
@@ -342,6 +342,38 @@ def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
|
||||
assert row.in_out_flag == "-1" # [断言意图] 原值落档不拒收
|
||||
|
||||
|
||||
def test_sync_lands_external_doc_line_and_expands_natural_key(app):
|
||||
# [断言意图] 外部单据身份(外部单号/外部项次=WMS Order #/行号)经落档链路
|
||||
# 写入档列并参与自然键:同单号同行不同外部单号 = 两行独立落档(2026-10-21
|
||||
# 档幂等主键管控扩维),外部身份列原值随行留存。
|
||||
deps, _, _ = make_transfer_deps({
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "inbound",
|
||||
"file_no": "REC-EXT",
|
||||
"file_version": "v1",
|
||||
"checksum": "e" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-E1", "line_no": "1",
|
||||
"external_doc_no": "WMS-001", "external_line_no": "10",
|
||||
"lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号",
|
||||
"movement_date": "2026-08-05", "quantity": "10", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-E1", "line_no": "1",
|
||||
"external_doc_no": "WMS-002", "external_line_no": "10",
|
||||
"lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号",
|
||||
"movement_date": "2026-08-05", "quantity": "20", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
})
|
||||
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
|
||||
business_date="2026-08-06", now=NOW)
|
||||
assert outcome is not None and outcome.inserted == 2 # [断言意图] 不同外部单号各自成行
|
||||
rows = TransferMovementLedger.query.filter_by(
|
||||
source_code="DBS-AWSBI", doc_no="HOM-E1").order_by(TransferMovementLedger.id).all()
|
||||
assert [(r.external_doc_no, r.external_line_no) for r in rows] == [
|
||||
("WMS-001", "10"), ("WMS-002", "10")] # [断言意图] 外部身份列原值落档
|
||||
|
||||
|
||||
def _collapsed_multi_material_file() -> dict:
|
||||
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空且 carton/lot 等值的坍缩形态文件。
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ def _ready_items(dbs_ready_file, *seeds) -> tuple:
|
||||
erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity)
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
items = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
@@ -76,7 +76,7 @@ def test_execute_items_writes_one_order_and_aggregates(transfer_db, dbs_ready_fi
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
|
||||
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first()
|
||||
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# Run 终态与单据聚合:同组两 Invoice 合并一张 ERP 单(D1 五元组一组一单),无异常。
|
||||
@@ -145,7 +145,7 @@ def _two_group_deps(dbs_ready_file, patch_source_file_status):
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, erp, _ = make_transfer_deps(file, capabilities=erp)
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
items = (
|
||||
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
|
||||
.order_by(TransferInvoiceItem.id)
|
||||
@@ -289,7 +289,7 @@ def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_read
|
||||
deps, erp, _ = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
|
||||
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first()
|
||||
|
||||
outcome = execute_matching_items(
|
||||
matching_id=matching.matching_no, deps=deps, invoice_nos=["HOM-001"],
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service、jobs.queue。
|
||||
逻辑:场景编号对应计划 Task 10 Step 1 场景①-⑪;SQLite 无 PG 序列,单号序列经
|
||||
monkeypatch execution_service._sequence_loader 注入替身;文件对账门禁经
|
||||
patch_source_file_status 夹具注入 ready 投影。
|
||||
patch_source_file_status 夹具注入 ready 投影。出站档行用例把入站/出站
|
||||
投影分成两个 sha,确认门禁与 file_current 读档上的 record_kind。
|
||||
【T−2 成熟封顶 2026-10-21】匹配 business_date 用 2026-08-07(行日期
|
||||
2026-08-04/08-05 均 ≤T−2 成熟可圈;文件/种子新鲜度仍用 2026-08-06)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,6 +35,7 @@ from app.models import (
|
||||
TransferDocument,
|
||||
TransferInvoiceItem,
|
||||
TransferMatching,
|
||||
TransferMovementLedger,
|
||||
TransferRun,
|
||||
)
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
@@ -41,7 +45,7 @@ from app.services.in_transit_transfer.execution_service import (
|
||||
retrigger_document,
|
||||
)
|
||||
from app.services.in_transit_transfer.serializers import serialize_order
|
||||
from app.services.in_transit_transfer.matching_service import create_matching
|
||||
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
||||
|
||||
READY_SHA = "d" * 64
|
||||
@@ -154,7 +158,7 @@ def test_two_movement_dates_create_two_documents(
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
assert outcome.status == "queued"
|
||||
@@ -185,7 +189,7 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line(
|
||||
])
|
||||
# 严格数量匹配逐 Invoice 核对:库存须等于单 Invoice 数量(聚合发生在执行组建单时)。
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500.5")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -212,7 +216,7 @@ def test_order_doc_date_equals_group_movement_date(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -237,7 +241,7 @@ def test_order_success_propagates_to_all_items(
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -274,7 +278,7 @@ def test_order_failure_isolates_to_its_items(
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
items = _ready_items()
|
||||
outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
@@ -310,7 +314,7 @@ def test_worker_reclaim_executing_stage_confirmed_runs_final_only(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -342,7 +346,7 @@ def test_failed_order_reused_with_new_row_full_rerun(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
|
||||
doc = _doc_for(run1)
|
||||
@@ -366,7 +370,7 @@ def test_failed_order_reused_with_new_row_full_rerun(
|
||||
erp2.seed_stock("MAT-003", "DBS-TRANSIT", "LOT-30", "300")
|
||||
patch_source_file_status()
|
||||
seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") # 新行 HOM-C 落地;HOM-A 幂等跳过
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps2, transfer_type="in_transit_to_hub")
|
||||
second = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps2)
|
||||
run2 = TransferRun.query.filter_by(run_no=second.run_no).first()
|
||||
|
||||
@@ -402,7 +406,7 @@ def test_result_unknown_order_blocks_new_rows(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
|
||||
doc = _doc_for(run1)
|
||||
@@ -461,7 +465,7 @@ def test_retrigger_document_full_chain(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=first.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -531,7 +535,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
items = _ready_items()
|
||||
|
||||
original_insert = execution_service._insert_document
|
||||
@@ -583,7 +587,7 @@ def test_prepare_enqueues_single_transfer_run_job(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
ids = [i.id for i in _ready_items()]
|
||||
|
||||
outcome = prepare_execution(item_ids=ids, deps=deps)
|
||||
@@ -618,7 +622,7 @@ def test_execute_run_rechecks_file_hash_fail_closed(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -646,7 +650,7 @@ def test_full_run_passes_stage_callback_and_marks_stage_confirmed(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -672,7 +676,7 @@ def test_retrigger_final_only_does_not_pass_stage_callback(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=first.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -706,7 +710,7 @@ def test_requeried_rows_reuse_order_without_new_rows(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
|
||||
doc = _doc_for(run1)
|
||||
@@ -799,7 +803,7 @@ def test_recheck_failure_marks_executing_order_technical_failed(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -832,7 +836,7 @@ def test_serialize_run_orders_projects_multi_status_order_list(
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
|
||||
_row("Receipt", 2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
docs = _docs_of(run)
|
||||
@@ -888,7 +892,7 @@ def test_order_lines_group_by_external_lot_form():
|
||||
# [出生翻转] 批号派生按行所属匹配快照的转换规则(scope_json.transform_rules):
|
||||
# 构造携带 WTP→HOW 规则的匹配对象并挂到两行(transient 赋值,不触库)。
|
||||
matching = TransferMatching(
|
||||
matching_no="MTG-LOT", business_date="2026-08-06", status="success",
|
||||
matching_no="MTG-LOT", business_date="2026-08-07", status="success",
|
||||
scope_json={"transform_rules": [
|
||||
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
|
||||
]},
|
||||
@@ -921,7 +925,7 @@ def test_serialize_order_reason_join_uses_external_lot_form():
|
||||
WTP 前缀行投影出空品名/空原因。
|
||||
"""
|
||||
matching = TransferMatching(
|
||||
matching_no="MTG-LOT-2", business_date="2026-08-06", status="success",
|
||||
matching_no="MTG-LOT-2", business_date="2026-08-07", status="success",
|
||||
scope_json={"transform_rules": [
|
||||
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
|
||||
]},
|
||||
@@ -956,7 +960,7 @@ def test_order_success_seals_ledger_records(
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -988,7 +992,7 @@ def test_order_success_seal_is_idempotent_and_stays_sealed_on_duplicate(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
@@ -1026,7 +1030,7 @@ def test_order_failure_does_not_seal_ledger_records(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
items = _ready_items()
|
||||
outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
@@ -1053,7 +1057,7 @@ def test_gate_anchors_to_ledger_record_version(
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
item = _ready_items()[0]
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
@@ -1082,3 +1086,61 @@ def test_gate_anchors_to_ledger_record_version(
|
||||
prepare_execution(item_ids=[item.id], deps=deps)
|
||||
assert exc.value.code == "TRANSFER.FILE_CHANGED" # [断言意图] 记录落后 → 拒绝执行
|
||||
db.session.expire_all()
|
||||
|
||||
|
||||
def test_execute_gate_compares_outbound_evidence_not_inbound(
|
||||
transfer_db, monkeypatch, seq_loader,
|
||||
):
|
||||
"""出站档行的 file_current 与执行门禁对出站文件 sha,不拿入站投影比较。
|
||||
|
||||
核心逻辑:同一来源入站投影 sha 与出站不同。出站档 file_sha256 等于出站投影。
|
||||
若门禁仍解析入站,file_current 为假且 prepare_execution 抛 FILE_CHANGED。
|
||||
"""
|
||||
del seq_loader # 夹具注入单号序列;本用例只确认门禁放行。
|
||||
out_sha = "o" * 64
|
||||
in_sha = "i" * 64
|
||||
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
"""入站与出站返回不同 sha,用来区分门禁读了哪一条流。"""
|
||||
del source_code
|
||||
sha = out_sha if record_kind == "outbound" else in_sha
|
||||
return {
|
||||
"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": f"{record_kind}-file", "file_sha256": sha,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
_resolve,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.execution_service.resolve_source_file_status",
|
||||
_resolve,
|
||||
)
|
||||
deps, erp, _rpa = make_transfer_deps()
|
||||
erp.seed_stock("MAT-OUT", "DBS-TRANSIT", "LOT-OUT", "100")
|
||||
db.session.add(TransferMovementLedger(
|
||||
source_code="DBS-AWSBI", record_kind="outbound",
|
||||
doc_no="HOX-OUT", line_no="1", line_seq="", in_out_flag="",
|
||||
material_code="MAT-OUT", material_name="出站物料", specification="",
|
||||
lot_no="LOT-OUT", quantity="100", unit="PCS",
|
||||
warehouse_code="", storage_code="", movement_date="2026-08-05",
|
||||
source_file_id=None, file_version="v1", file_sha256=out_sha,
|
||||
sheet_name="Shipment", row_no=1, updated_at=datetime.utcnow(),
|
||||
transfer_executed=False,
|
||||
))
|
||||
db.session.commit()
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
)
|
||||
restored = restore_matching(summary.matching_id, deps=deps)
|
||||
row = next(item for item in restored["items"] if item.invoice_no == "HOX-OUT")
|
||||
# [断言意图] 入站 sha 与档不同;file_current 仍为真,说明比的是出站证据文件。
|
||||
assert row.file_current is True
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOX-OUT").one()
|
||||
assert item.ledger_record.record_kind == "outbound"
|
||||
assert item.status == "ready_to_execute"
|
||||
outcome = prepare_execution(item_ids=[item.id], deps=deps)
|
||||
# [断言意图] 执行门禁放行。误用入站 sha 会以 FILE_CHANGED 拒绝。
|
||||
assert outcome.run_no
|
||||
@@ -61,15 +61,36 @@ def test_valid_rows_parse():
|
||||
|
||||
|
||||
def test_missing_invoice_no_rejected():
|
||||
"""单号(doc_no)缺失必须整行阻断。"""
|
||||
"""单号(doc_no)缺失必须整行阻断(管控保留:配置错列由解析失败暴露)。"""
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
|
||||
|
||||
|
||||
def test_missing_material_no_rejected():
|
||||
"""料号缺失必须整行阻断。"""
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
|
||||
def test_missing_material_no_row_skipped_not_blocked():
|
||||
"""料号空行=非可用异动行:静默跳过——不管控、不进异动表(2026-10-21 实测反转)。
|
||||
|
||||
Why: CRANE/Lognet 出站报告携带说明行/占位行(料号为空),旧逻辑按
|
||||
missing_material_no 整文件阻断致出站解析失败;此类行不是可用异动事实,
|
||||
跳过语义与零数量行同家族(_is_unusable_movement_row)。
|
||||
"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
|
||||
assert parsed == []
|
||||
|
||||
|
||||
def test_empty_material_rows_mixed_with_valid_rows_only_valid_parsed():
|
||||
"""料号空行与合法行混排:只放行有料号的行,空料号行不阻断整文件。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=2, material_code=""), # 说明/占位行:跳过
|
||||
dict(VALID_ROW, row_no=3, material_code="MAT-002", doc_no="INV-002"),
|
||||
]
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
assert [row.row_no for row in parsed] == [3]
|
||||
|
||||
|
||||
def test_material_and_invoice_both_empty_row_skipped():
|
||||
"""料号与单号双空行按料号空行处理:静默跳过而非 missing_invoice_no 阻断。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="", material_code=""))
|
||||
assert parsed == []
|
||||
|
||||
|
||||
def test_invalid_quantity_rejected():
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
(inbound 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
|
||||
审计事件且记录照常落档;shipment 预留合法值放行、同批自然键重复首见为准。
|
||||
依赖:app fixture(pytestmark)、models.TransferMovementLedger / TransferAuditEvent、
|
||||
ledger_sync.sync_ledger_rows / FileMeta。
|
||||
ledger_sync.sync_ledger_rows / FileMeta / movement_file_version。
|
||||
逻辑:parsed_rows 以「movement 契约 field code → 值」的领域行 dict 直接构造
|
||||
(扩展字段值从 dict 取,非 ParsedMovementRow 属性——Task 11 接线同形态);
|
||||
直连 SQLite 内存库断言行级状态与审计事件,全程零外部调用。
|
||||
@@ -22,6 +22,7 @@ from app import db
|
||||
from app.models import TransferAuditEvent, TransferMovementLedger
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
FileMeta,
|
||||
movement_file_version,
|
||||
sync_ledger_rows,
|
||||
)
|
||||
|
||||
@@ -211,6 +212,31 @@ def test_lot_no_expands_natural_key():
|
||||
assert outcome.inserted == 2
|
||||
|
||||
|
||||
def test_external_doc_line_expands_natural_key():
|
||||
# [断言意图] 外部单据身份(外部单号/外部项次)入自然键:同单号同行但外部单号
|
||||
# 不同 = 两行独立落档(2026-10-21 档幂等主键管控扩维,防外部身份塌缩丢行)。
|
||||
outcome = _sync([
|
||||
_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001", quantity="1"),
|
||||
_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-002", quantity="2"),
|
||||
], record_kind="inbound")
|
||||
assert outcome.inserted == 2
|
||||
assert outcome.skipped == 0
|
||||
|
||||
|
||||
def test_external_doc_line_same_identity_converges_to_one_row():
|
||||
# [断言意图] 主键管控收敛面:同外部单号+项次的重复落档收敛同一档行——
|
||||
# 证据变化走原行更新(不是插入第二行),与 tt14 箱号/批号扩维同语义。
|
||||
outcome = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001",
|
||||
external_line_no="5", quantity="1")])
|
||||
assert outcome.inserted == 1
|
||||
outcome2 = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001",
|
||||
external_line_no="5", quantity="3")], meta=_meta(sha=SHA_V2), now=NOW2)
|
||||
assert (outcome2.inserted, outcome2.updated, outcome2.skipped) == (0, 1, 0)
|
||||
row = TransferMovementLedger.query.one()
|
||||
assert row.quantity == "3"
|
||||
assert row.external_doc_no == "WMS-001" and row.external_line_no == "5"
|
||||
|
||||
|
||||
def test_empty_movement_date_rows_skipped():
|
||||
# [断言意图] movement_date 空 = 未发生异动:不落档、不计入其他分类(date_skipped 单列)。
|
||||
outcome = _sync([
|
||||
@@ -246,3 +272,12 @@ def test_batch_external_doc_no_row_untouched_by_landing():
|
||||
assert external.quantity == "7" and external.file_sha256 == SHA_V1 # 内容不变
|
||||
assert external.updated_at == external_at # 零触碰
|
||||
assert TransferMovementLedger.query.count() == 2 # 缺席不删:批外行留存
|
||||
|
||||
|
||||
def test_movement_file_version_fits_varchar64_column():
|
||||
# [断言意图] 64 位摘要加 sha256: 前缀共 71 字符;档列 file_version 是 varchar(64),
|
||||
# 戳必须是这一条已知截断值(2026-10-21 DSV 出站整批插入失败的摘要)。
|
||||
digest = "7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b7a11715"
|
||||
stamp = movement_file_version(digest)
|
||||
assert stamp == "sha256:7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b"
|
||||
assert len(stamp) == 64
|
||||
@@ -67,7 +67,7 @@ def test_items_are_born_bound_to_matching(transfer_db, dbs_ready_file):
|
||||
hom = next(row for row in rows if row.invoice_no == "HOM-001")
|
||||
# [断言意图] 业务字段=档原值:数量=档聚合值(500+700),批号/仓库/日期同档。
|
||||
assert hom.movement_quantity == "1200"
|
||||
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-05"
|
||||
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-04"
|
||||
assert hom.movement_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||
外部依赖注入 Fake 替身。
|
||||
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
|
||||
经 create_matching 断言 doc_no。入站 no_data / 仅出站类型断言不触发入站 RPA。
|
||||
确认匹配对 ready 出站归档幂等补落档后再圈行(空档窗口回归)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,6 +40,21 @@ def _deps(*files: dict, erp: FakeCapabilityClient | None = None, rpa: FakeRPA |
|
||||
return make_transfer_deps(*files, capabilities=erp, rpa=rpa)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def deps(app):
|
||||
"""圈档记录类型用例的匹配依赖(空文件仓库,DSV360_AWSBI 路由可解析)。
|
||||
|
||||
核心逻辑:请求 app 以建表并触发默认类型种子;路由只为评估链不中断,
|
||||
断言不看仓库。
|
||||
Returns:
|
||||
TransferDeps。
|
||||
"""
|
||||
built, _erp, _rpa = make_transfer_deps(
|
||||
routes={"DSV360_AWSBI": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
return built
|
||||
|
||||
|
||||
def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file):
|
||||
"""两个来源全部严格匹配 → executable_count 正确,无阻断。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file, crane_ready_file)
|
||||
@@ -88,7 +105,7 @@ def test_estimated_document_count_merges_same_group(dbs_ready_file):
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。
|
||||
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-04, DBS-TRANSIT, HUB-CN01)。
|
||||
assert result.summary.estimated_external_write_count == 1
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["HOM-001"].external_org == "HX-CN01"
|
||||
@@ -100,6 +117,8 @@ def test_estimated_document_count_splits_by_movement_date():
|
||||
|
||||
锁定分组的日期维度:execution_service.prepare_execution 以 movement_date 入键,
|
||||
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
|
||||
【T−2 成熟封顶 2026-10-21】两行均取 ≤ T−2(08-03/08-04)成熟日期,
|
||||
隔天分组语义不变。
|
||||
"""
|
||||
deps, erp, _ = _deps({
|
||||
"source_code": "DBS-AWSBI",
|
||||
@@ -112,10 +131,10 @@ def test_estimated_document_count_splits_by_movement_date():
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A",
|
||||
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-03", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B",
|
||||
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
})
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600")
|
||||
@@ -128,11 +147,13 @@ def test_estimated_document_count_splits_by_movement_date():
|
||||
assert result.summary.estimated_external_write_count == 2
|
||||
|
||||
|
||||
def test_same_day_data_reaches_erp_query(same_day_inbound_file):
|
||||
"""【成熟退役 2026-10-16】当天异动数据不再被成熟门禁跳过:正常进 ERP 查询。
|
||||
def test_same_day_data_not_matched_before_maturity(same_day_inbound_file):
|
||||
"""【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进匹配、不发起外部查询。
|
||||
|
||||
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
|
||||
网关调用必须发生(=1),证明日期不再构成评估前置过滤。
|
||||
[断言意图] 圈档封顶 movement_date ≤ T−2(T−2 之前数据全部成熟):当天行留在
|
||||
档内待成熟,不出生 item、不查外部系统(=0);成熟(≤T−2)数据的正常匹配由
|
||||
happy path 用例锁定。此前「成熟规则已退役 2026-10-16」放开的当天进匹配语义
|
||||
随 T−2 管控恢复一并收回。
|
||||
"""
|
||||
deps, erp, _ = _deps(same_day_inbound_file)
|
||||
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
|
||||
@@ -140,8 +161,8 @@ def test_same_day_data_reaches_erp_query(same_day_inbound_file):
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert result.summary.counts.executable_count == 0
|
||||
assert result.summary.counts.blocked_count == 1
|
||||
assert_erp_calls(erp, 1)
|
||||
assert result.summary.counts.blocked_count == 0
|
||||
assert_erp_calls(erp, 0)
|
||||
|
||||
|
||||
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
|
||||
@@ -173,7 +194,7 @@ def test_erp_inventory_not_found_blocked(dbs_ready_file):
|
||||
|
||||
|
||||
def _wtp_lot_file() -> dict:
|
||||
"""构造 WTP 前缀批号的单行收料文件(WMS 原形态落库口径)。"""
|
||||
"""构造 WTP 前缀批号的单行收料文件(WMS 原形态落库口径;异动日期=T−2 成熟边界)。"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -185,7 +206,7 @@ def _wtp_lot_file() -> dict:
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOX-900", "lot_no": "WTP26060612",
|
||||
"material_code": "MAT-900", "material_name": "汇流排", "specification": "48V",
|
||||
"movement_date": "2026-08-05", "quantity": "200", "unit": "PCS",
|
||||
"movement_date": "2026-08-04", "quantity": "200", "unit": "PCS",
|
||||
"source_code": "DBS-AWSBI"},
|
||||
],
|
||||
}
|
||||
@@ -284,7 +305,7 @@ def test_create_and_restore_matching(transfer_db, dbs_ready_file):
|
||||
# 落库数量与 DTO 一致(Decimal 文本持久化)
|
||||
assert str(restored_items["HOM-001"].to_quantity) == "1200"
|
||||
# [断言意图] 收料日期与批号必须随明细恢复——聊天卡片收料日期/拨出批号/拨入批号列的数据来源。
|
||||
assert restored_items["HOM-001"].movement_date == "2026-08-05"
|
||||
assert restored_items["HOM-001"].movement_date == "2026-08-04"
|
||||
assert restored_items["HOM-001"].lot_no == "LOT-10"
|
||||
assert restored_items["HOX-002"].lot_no == "LOT-20"
|
||||
|
||||
@@ -304,7 +325,7 @@ def test_parse_failed_file_reports_source_failure_on_restore(transfer_db, monkey
|
||||
# 来源阶段转 failed、错误码随 SourceProgress 透出;档照常圈定(无档行=全 0)。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "parse_failed", "has_ready_file": False,
|
||||
lambda *, source_code, record_kind="inbound": {"file_status": "parse_failed", "has_ready_file": False,
|
||||
"file_no": "F1", "file_sha256": "sha:x"},
|
||||
)
|
||||
summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
@@ -352,10 +373,10 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "ASN-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16"},
|
||||
"quantity": 5, "movement_date": "2026-09-15"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "HOX-2", "lot_no": "ASN-1",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 7, "movement_date": "2026-09-16"},
|
||||
"quantity": 7, "movement_date": "2026-09-15"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
@@ -368,46 +389,84 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
|
||||
|
||||
def test_movement_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
"""收料日期范围作为匹配查询范围:范围外发票不进入明细。"""
|
||||
"""收料日期范围作为匹配查询范围:范围外发票不进入明细(行日期=T−2 成熟边界)。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
movement_date_from="2026-08-05", movement_date_to="2026-08-05", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-04", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert summary.counts.file_invoice_count == 2
|
||||
|
||||
empty = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
movement_date_from="2026-08-01", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-01", movement_date_to="2026-08-03", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert empty.counts.file_invoice_count == 0
|
||||
|
||||
|
||||
def test_movement_date_range_end_beyond_business_date_rejected(transfer_db, dbs_ready_file):
|
||||
"""卡控(成熟退役后唯一日期校验):截止晚于业务日期(未来日期)必须拒绝。
|
||||
def test_movement_date_range_end_beyond_matured_boundary_rejected(transfer_db, dbs_ready_file):
|
||||
"""卡控(T−2 成熟封顶 2026-10-21):截止晚于 T−2 可匹配截止日必须拒绝。
|
||||
|
||||
[断言意图] 截止=业务日期当天(2026-08-06)现在合法(旧成熟规则会拒绝 T-1/
|
||||
当天);只有严格晚于业务日期才拒——未来日期无账可核。
|
||||
[断言意图] T−2 之前数据全部成熟(简化成熟边界,不回退退役决策)——范围
|
||||
截止 ≤ T−2(2026-08-04)合法,T−1/当天/未来(>T−2)无成熟数据不可选;
|
||||
与前端选择器上限(transferDate.ts defaultMovementDate)同口径,越界统一
|
||||
TRANSFER.MOVEMENT_DATE_RANGE_INVALID。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
movement_date_from="2026-08-04", movement_date_to="2026-08-07", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-04", movement_date_to="2026-08-05", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert exc_info.value.code == "TRANSFER.MOVEMENT_DATE_RANGE_INVALID"
|
||||
|
||||
# [边界反转] 截止=业务日期当天合法(旧行为 lag=1 下会被拒)。
|
||||
empty = create_matching(
|
||||
# [边界] 截止=T−2(2026-08-04)恰好合法:成熟行正常进匹配。
|
||||
bounded = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
movement_date_from="2026-08-06", movement_date_to="2026-08-06", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-04", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert empty.counts.file_invoice_count == 0
|
||||
assert bounded.counts.file_invoice_count == 2
|
||||
|
||||
|
||||
def test_circle_excludes_immature_rows_beyond_t_minus_2(transfer_db):
|
||||
"""圈档 T−2 成熟封顶:T−1/当天行不进匹配(留在档内待成熟),≤T−2 正常圈定。
|
||||
|
||||
[断言意图] 未传范围(积压模式)时 T−1(08-05)/当天(08-06)行也不被圈定
|
||||
——成熟封顶是圈档固定条件,不依赖调用方传范围;两行在次日(业务日前移)
|
||||
自然跨过 T−2 后即可进圈。
|
||||
"""
|
||||
deps, _erp, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-08-06",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-M", "lot_no": "LOT-M",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-08-04"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "HOM-Y", "lot_no": "LOT-Y",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 6, "movement_date": "2026-08-05"},
|
||||
{"sheet": "Movement", "row_no": 3, "doc_no": "HOM-T", "lot_no": "LOT-T",
|
||||
"material_code": "M3", "material_name": "物料3",
|
||||
"quantity": 7, "movement_date": "2026-08-06"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
seed_rows_from_file("DSV360_AWSDU", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
|
||||
)
|
||||
invoices = {item.invoice_no for item in result.items}
|
||||
# [断言意图] 只有 ≤T−2(08-04)的行出生 item;T−1/当天行被圈档封顶排除。
|
||||
assert invoices == {"HOM-M"}
|
||||
assert result.summary.counts.file_invoice_count == 1
|
||||
|
||||
|
||||
def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file):
|
||||
@@ -451,7 +510,7 @@ def test_run_matching_consumes_movement_field_rows(app):
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1,
|
||||
"doc_no": "WTP-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16", "unit": "PCS",
|
||||
"quantity": 5, "movement_date": "2026-09-15", "unit": "PCS",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
@@ -476,13 +535,13 @@ def test_type1_filters_invoices_by_prefix(app):
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-100", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16", "unit": "PCS"},
|
||||
"quantity": 5, "movement_date": "2026-09-15", "unit": "PCS"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "INV-9", "lot_no": "LOT-2",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 6, "movement_date": "2026-09-16", "unit": "PCS"},
|
||||
"quantity": 6, "movement_date": "2026-09-15", "unit": "PCS"},
|
||||
{"sheet": "Movement", "row_no": 3, "doc_no": "WTP-300", "lot_no": "LOT-3",
|
||||
"material_code": "M3", "material_name": "物料3",
|
||||
"quantity": 7, "movement_date": "2026-09-16", "unit": "PCS"},
|
||||
"quantity": 7, "movement_date": "2026-09-15", "unit": "PCS"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
@@ -506,7 +565,7 @@ def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1, "doc_no": "HOX-1", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
"quantity": 5, "movement_date": "2026-09-15",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
@@ -677,17 +736,28 @@ def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file
|
||||
|
||||
def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str = "100",
|
||||
movement_date: str = "2026-08-05", sealed: bool = False,
|
||||
source_code: str = "DSV360_AWSDU", row_no: int = 1):
|
||||
"""直接 ORM 种子一条收料档记录(单元测试圈档口径;不依赖文件落地链路)。"""
|
||||
source_code: str = "DSV360_AWSDU", row_no: int = 1,
|
||||
record_kind: str = "inbound", carton_id: str = "",
|
||||
lot_no: str | None = None, file_sha256: str | None = None):
|
||||
"""直接 ORM 种子一条异动档记录(单元测试圈档口径;不依赖文件落地链路)。
|
||||
|
||||
Args:
|
||||
record_kind: 档记录类型,缺省 inbound(存量圈档用例)。
|
||||
carton_id: 自然键成分(tt14);同 grain 不同 carton 可并存两条档。
|
||||
lot_no / file_sha256: 可选覆盖,便于构造 grain 分叉夹具。
|
||||
"""
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
record = TransferMovementLedger(
|
||||
source_code=source_code, record_kind="inbound",
|
||||
source_code=source_code, record_kind=record_kind,
|
||||
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
|
||||
carton_id=carton_id,
|
||||
material_code=material, material_name="档物料", specification="",
|
||||
lot_no=f"LOT-{doc_no}", quantity=quantity, unit="PCS",
|
||||
lot_no=lot_no if lot_no is not None else f"LOT-{doc_no}",
|
||||
quantity=quantity, unit="PCS",
|
||||
warehouse_code="", storage_code="", movement_date=movement_date,
|
||||
source_file_id=None, file_version="v1", file_sha256="a" * 64,
|
||||
source_file_id=None, file_version="v1",
|
||||
file_sha256=file_sha256 or ("a" * 64),
|
||||
sheet_name="Receipt", row_no=row_no, updated_at=datetime.utcnow(),
|
||||
transfer_executed=sealed,
|
||||
executed_doc_no="TRF-SEALED" if sealed else None,
|
||||
@@ -697,6 +767,252 @@ def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str
|
||||
return record
|
||||
|
||||
|
||||
def _insert_ledger(*, source_code: str, record_kind: str, doc_no: str, movement_date: str):
|
||||
"""直接 ORM 落一条异动档(圈档记录类型用例;不走文件落地)。
|
||||
|
||||
核心逻辑:复用 _seed_ledger_record 的列口径,只放开 record_kind / 来源 / 单号 / 日期。
|
||||
Returns:
|
||||
TransferMovementLedger 行。
|
||||
"""
|
||||
return _seed_ledger_record(
|
||||
doc_no, movement_date=movement_date, source_code=source_code, record_kind=record_kind,
|
||||
)
|
||||
|
||||
|
||||
def _prepare_record_kind_circle_types() -> None:
|
||||
"""启用 hub_to_hub(范围规则不含 record_kind),并给 in_transit_to_hub 写上只要 inbound。
|
||||
|
||||
核心逻辑:hub_to_hub 用默认前缀规则(无记录类型 → 入站+出站)。
|
||||
in_transit_to_hub 在既有前缀规则上追加 record_kind equals inbound,
|
||||
否则同一出站行也会被圈入。
|
||||
"""
|
||||
from app.models import TransferTypeConfig
|
||||
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
|
||||
|
||||
seed_transfer_type_config()
|
||||
seed_transfer_type_config("hub_to_hub")
|
||||
row = db.session.query(TransferTypeConfig).filter_by(code="in_transit_to_hub").one()
|
||||
rules = [dict(item) for item in (row.scope_rules_json or [])]
|
||||
if not any(item.get("field") == "record_kind" for item in rules):
|
||||
rules.append({"field": "record_kind", "match": "equals", "values": ["inbound"]})
|
||||
row.scope_rules_json = rules
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def items_of(summary):
|
||||
"""读取本次匹配已圈明细,只暴露 doc_no(行 invoice_no = 档单号)。
|
||||
|
||||
Args:
|
||||
summary: create_matching 返回的匹配摘要(matching_id 为匹配编号)。
|
||||
Returns:
|
||||
带 doc_no 属性的明细列表。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import TransferMatching
|
||||
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
|
||||
rows = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
return [SimpleNamespace(doc_no=row.invoice_no) for row in rows]
|
||||
|
||||
|
||||
def test_hub_to_hub_circles_outbound_ledger_rows(deps):
|
||||
"""没有记录类型规则的类型圈入出站档;范围规则写明只要 inbound 的类型不圈。"""
|
||||
_prepare_record_kind_circle_types()
|
||||
_insert_ledger(source_code="DSV360_AWSBI", record_kind="outbound", doc_no="HOX1", movement_date="2026-10-14")
|
||||
inbound_only = create_matching(
|
||||
source_codes=["DSV360_AWSBI"],
|
||||
business_date="2026-10-16",
|
||||
movement_date_from="2026-10-14",
|
||||
movement_date_to="2026-10-14",
|
||||
transfer_type="in_transit_to_hub",
|
||||
deps=deps,
|
||||
)
|
||||
# [断言意图] 先圈只要 inbound 的类型:行尚未被占用,HOX1 因记录类型被排除。
|
||||
assert "HOX1" not in {item.doc_no for item in items_of(inbound_only)}
|
||||
circled = create_matching(
|
||||
source_codes=["DSV360_AWSBI"],
|
||||
business_date="2026-10-16",
|
||||
movement_date_from="2026-10-14",
|
||||
movement_date_to="2026-10-14",
|
||||
transfer_type="hub_to_hub",
|
||||
deps=deps,
|
||||
)
|
||||
# [断言意图] 无 record_kind 规则的启用类型应圈入出站档 HOX1。
|
||||
assert "HOX1" in {item.doc_no for item in items_of(circled)}
|
||||
|
||||
|
||||
def test_no_data_or_outbound_only_does_not_trigger_inbound_rpa(deps, monkeypatch):
|
||||
"""入站 no_data、或类型不要求入站时,create_matching 不触发入站 RPA。
|
||||
|
||||
核心逻辑:投影替身按 record_kind 返回状态。先跑只要 inbound 且入站为
|
||||
no_data;再把 hub_to_hub 收成只要 outbound,入站投影改为 none(若入站仍被
|
||||
当作必需,none 会走 ensure 并写入 matching_missing_ready_file)。
|
||||
"""
|
||||
projection = {"inbound": "no_data", "outbound": "ready"}
|
||||
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
"""按当前 projection 返回该证据流的文件状态。"""
|
||||
del source_code
|
||||
state = projection.get(record_kind, "none")
|
||||
if state == "ready":
|
||||
return {
|
||||
"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": f"{record_kind}-file", "file_sha256": "b" * 64,
|
||||
}
|
||||
if state == "no_data":
|
||||
return {
|
||||
"file_status": "no_data", "has_ready_file": False,
|
||||
"file_no": None, "file_sha256": None,
|
||||
}
|
||||
return {
|
||||
"file_status": "none", "has_ready_file": False,
|
||||
"file_no": None, "file_sha256": None,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
_resolve,
|
||||
)
|
||||
_prepare_record_kind_circle_types()
|
||||
_insert_ledger(
|
||||
source_code="DSV360_AWSBI", record_kind="inbound",
|
||||
doc_no="HOM-ND", movement_date="2026-10-14",
|
||||
)
|
||||
inbound_only = create_matching(
|
||||
source_codes=["DSV360_AWSBI"],
|
||||
business_date="2026-10-16",
|
||||
movement_date_from="2026-10-14",
|
||||
movement_date_to="2026-10-14",
|
||||
transfer_type="in_transit_to_hub",
|
||||
deps=deps,
|
||||
)
|
||||
# [断言意图] 入站已确认 no_data:不得写 matching_missing_ready_file,档仍圈入。
|
||||
assert deps.rpa_trigger.triggered == []
|
||||
assert "HOM-ND" in {item.doc_no for item in items_of(inbound_only)}
|
||||
|
||||
from app.models import TransferTypeConfig
|
||||
|
||||
hub = db.session.query(TransferTypeConfig).filter_by(code="hub_to_hub").one()
|
||||
rules = [dict(item) for item in (hub.scope_rules_json or [])]
|
||||
rules.append({"field": "record_kind", "match": "equals", "values": ["outbound"]})
|
||||
hub.scope_rules_json = rules
|
||||
db.session.commit()
|
||||
projection["inbound"] = "none"
|
||||
projection["outbound"] = "no_data"
|
||||
deps.rpa_trigger.triggered.clear()
|
||||
_insert_ledger(
|
||||
source_code="DSV360_AWSBI", record_kind="outbound",
|
||||
doc_no="HOX-OD", movement_date="2026-10-14",
|
||||
)
|
||||
outbound_only = create_matching(
|
||||
source_codes=["DSV360_AWSBI"],
|
||||
business_date="2026-10-16",
|
||||
movement_date_from="2026-10-14",
|
||||
movement_date_to="2026-10-14",
|
||||
transfer_type="hub_to_hub",
|
||||
deps=deps,
|
||||
)
|
||||
# [断言意图] 只要出站、入站缺文件(none)时仍不触发入站 RPA,出站档照常圈入。
|
||||
assert deps.rpa_trigger.triggered == []
|
||||
assert "HOX-OD" in {item.doc_no for item in items_of(outbound_only)}
|
||||
|
||||
|
||||
def test_confirm_matching_syncs_ready_outbound_into_ledger_before_circle(deps, monkeypatch):
|
||||
"""确认匹配时:出站 ready 但档空 → 先幂等落档再圈行(补齐回调未落档窗口)。
|
||||
|
||||
[断言意图] 不再依赖「仅回调 success 才写档」;create_matching 对 ready 出站
|
||||
流调用 sync_outbound_source_rows,圈出 HOX-MATCH-O1(前缀落在类型范围规则内)。
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
from app.models import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
TransferMovementLedger,
|
||||
TransferTypeConfig,
|
||||
)
|
||||
from tests.services.in_transit_transfer import factories
|
||||
|
||||
source_code = "DSV360_AWSDU"
|
||||
storage_key = "shipping/outbound/match-sync.xlsx"
|
||||
now = datetime.utcnow()
|
||||
fake_storage = factories.FakeArchiveStorage()
|
||||
fake_storage.objects[storage_key] = factories.build_movement_xlsx([
|
||||
["HOX-MATCH-O1", "1", "O", "MAT-LED", "成品", "LOT-O1", 80, "2026-10-14"],
|
||||
])
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes",
|
||||
fake_storage.get_bytes,
|
||||
)
|
||||
# outbound_evidence_sync 直接 import 了 file_asset_storage 单例方法,需同补丁。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.outbound_evidence_sync.file_asset_storage.get_bytes",
|
||||
fake_storage.get_bytes,
|
||||
)
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=source_code).one()
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose="outbound", profile_code="OUT_MATCH_SYNC", display_name=source_code,
|
||||
version=1, status="published", file_format="xlsx",
|
||||
definition_json={
|
||||
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
|
||||
"sheet_name": "Receipt", "header_row_index": 1,
|
||||
},
|
||||
structure_definition_json={},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
db.session.add(FreightRpaOutboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={"report_name": "Outbound"},
|
||||
query_parameters_json=[],
|
||||
parsing_profile_id=profile.id,
|
||||
))
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
schedule_run_id=None, source_id=source.id, source_code=source_code,
|
||||
connector_type="dbs", warehouse_id="AWSDU", callback_id="match-sync-out-1",
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
digest = hashlib.sha256(b"match sync outbound workbook").hexdigest()
|
||||
db.session.add(FreightRpaOutboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=storage_key, original_filename="match-sync.xlsx",
|
||||
file_size=16, sha256=digest, created_at=now,
|
||||
))
|
||||
_prepare_record_kind_circle_types()
|
||||
hub = db.session.query(TransferTypeConfig).filter_by(code="hub_to_hub").one()
|
||||
# 保留默认前缀规则,只追加「只要 outbound」,避免 ASN 类单号被前缀滤掉。
|
||||
rules = [dict(item) for item in (hub.scope_rules_json or [])]
|
||||
rules = [item for item in rules if item.get("field") != "record_kind"]
|
||||
rules.append({"field": "record_kind", "match": "equals", "values": ["outbound"]})
|
||||
hub.scope_rules_json = rules
|
||||
db.session.commit()
|
||||
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=source_code, record_kind="outbound").count() == 0
|
||||
|
||||
summary = create_matching(
|
||||
source_codes=[source_code],
|
||||
business_date="2026-10-16",
|
||||
movement_date_from="2026-10-14",
|
||||
movement_date_to="2026-10-14",
|
||||
transfer_type="hub_to_hub",
|
||||
deps=deps,
|
||||
)
|
||||
|
||||
# [断言意图] 匹配前落档:异动档出现 outbound 行,并被圈入本次匹配。
|
||||
assert TransferMovementLedger.query.filter_by(
|
||||
source_code=source_code, record_kind="outbound", doc_no="HOX-MATCH-O1",
|
||||
).count() == 1
|
||||
assert "HOX-MATCH-O1" in {item.doc_no for item in items_of(summary)}
|
||||
|
||||
|
||||
def test_matching_circles_ledger_records_within_scope(transfer_db):
|
||||
"""圈档口径:范围外单(前缀不匹配)与已封存记录不入 items;圈内记录出生绑定档。"""
|
||||
from app.models import TransferMovementLedger
|
||||
@@ -730,6 +1046,53 @@ def test_matching_circles_ledger_records_within_scope(transfer_db):
|
||||
]
|
||||
|
||||
|
||||
def test_matching_birth_dedupes_same_grain_ledger_forks(transfer_db):
|
||||
"""同 grain 多档(空 carton + 有 carton 重解析分叉)只出生一行,不撞唯一约束、不翻倍数量。"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
deps, erp, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp.seed_stock("D4-A08AR12000002", "WH1", "HOX26021903", "30")
|
||||
older = _seed_ledger_record(
|
||||
"HOX26021903", material="D4-A08AR12000002", quantity="30",
|
||||
movement_date="2026-08-05", lot_no="HOX26021903", carton_id="",
|
||||
row_no=1, file_sha256="b" * 64,
|
||||
)
|
||||
newer = _seed_ledger_record(
|
||||
"HOX26021903", material="D4-A08AR12000002", quantity="30",
|
||||
movement_date="2026-08-05", lot_no="HOX26021903", carton_id="C260219121",
|
||||
row_no=2, file_sha256="c" * 64,
|
||||
)
|
||||
assert newer.id > older.id
|
||||
|
||||
summary = create_matching(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
)
|
||||
# [断言意图] grain 择优有 carton 的较新档;数量仍为 30(不把分叉双行相加)。
|
||||
# summary.matching_id 是 matching_no(MTG-…),行上 FK 是整数 matching.id。
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
|
||||
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
assert len(items) == 1, (summary.counts, TransferInvoiceItem.query.count())
|
||||
assert items[0].ledger_record_id == newer.id
|
||||
assert items[0].movement_quantity == "30"
|
||||
assert items[0].invoice_no == "HOX26021903"
|
||||
|
||||
# [断言意图] grain 占用互斥:二次匹配圈不到兄弟档,不累加行。
|
||||
create_matching(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
)
|
||||
assert TransferInvoiceItem.query.filter_by(invoice_no="HOX26021903").count() == 1
|
||||
assert TransferMatching.query.count() == 2
|
||||
|
||||
|
||||
def test_matching_routes_fixed_warehouse_from_type_config(transfer_db):
|
||||
"""仓库定义(规格 §7):fixed 角色按类型配置覆盖映射档仓库(from 仍走映射档)。"""
|
||||
from app import db as _db
|
||||
|
||||
@@ -61,12 +61,12 @@ def test_model_inbound_columns_and_ledger_key(app_ctx):
|
||||
)
|
||||
assert [col.name for col in ledger_uq.columns] == [
|
||||
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
|
||||
"in_out_flag", "carton_id", "lot_no",
|
||||
"in_out_flag", "carton_id", "lot_no", "external_doc_no", "external_line_no",
|
||||
]
|
||||
# R7 终审:进键维度列必须 NOT NULL + default ''(nullable 成分的 NULL 不参与
|
||||
# PG/SQLite 唯一比对,会逃逸唯一约束)。
|
||||
# R7 终审 + 2026-10-21 外部身份扩维:进键维度列必须 NOT NULL + default ''
|
||||
#(nullable 成分的 NULL 不参与 PG/SQLite 唯一比对,会逃逸唯一约束)。
|
||||
ledger_cols = {c.name: c for c in TransferMovementLedger.__table__.columns}
|
||||
for name in ("carton_id", "lot_no"):
|
||||
for name in ("carton_id", "lot_no", "external_doc_no", "external_line_no"):
|
||||
assert ledger_cols[name].nullable is False, f"{name} 进键即 NOT NULL"
|
||||
assert ledger_cols[name].default.arg == ''
|
||||
assert ledger_cols[name].server_default.arg == ''
|
||||
|
||||
@@ -33,16 +33,22 @@ pytestmark = pytest.mark.pure_unit
|
||||
EXTENSION_FIELD_CODES = (
|
||||
"line_seq", "specification", "order_type", "odm_id", "odm_name", "carton_id", "pallet_id",
|
||||
)
|
||||
# 2026-10-21 扩展追加的外部单据身份字段(外部单号/外部项次=WMS Order #/行号):
|
||||
# required=False, is_identity=False(不进匹配身份);但作为异动档自然键成分承担
|
||||
# 档幂等主键管控(模型 uq_transfer_movement_ledger_natural_key 10 成分)。
|
||||
EXTERNAL_IDENTITY_FIELD_CODES = ("external_doc_no", "external_line_no")
|
||||
|
||||
|
||||
def test_movement_fields_contract_is_frozen_and_complete():
|
||||
"""领域字段契约定死:既有 11 字段 + 2026-10-14 扩展 7 可选字段、名称唯一、不可变。"""
|
||||
assert len(MOVEMENT_FIELDS) == 18
|
||||
"""领域字段契约定死:既有 11 字段 + 2026-10-14 扩展 7 可选字段 + 2026-10-21
|
||||
外部单据身份 2 字段、名称唯一、不可变。"""
|
||||
assert len(MOVEMENT_FIELDS) == 20
|
||||
codes = {field.code for field in MOVEMENT_FIELDS}
|
||||
assert codes == {
|
||||
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
|
||||
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit",
|
||||
*EXTENSION_FIELD_CODES,
|
||||
*EXTERNAL_IDENTITY_FIELD_CODES,
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +75,7 @@ def test_movement_field_extension_codes_appended_optional_non_identity():
|
||||
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
|
||||
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit",
|
||||
*EXTENSION_FIELD_CODES,
|
||||
*EXTERNAL_IDENTITY_FIELD_CODES,
|
||||
]
|
||||
by_code = {field.code: field for field in MOVEMENT_FIELDS}
|
||||
expected_labels = {
|
||||
@@ -84,6 +91,27 @@ def test_movement_field_extension_codes_appended_optional_non_identity():
|
||||
assert field.is_identity is False, code
|
||||
|
||||
|
||||
def test_external_identity_fields_appended_optional_non_matching_identity():
|
||||
"""2026-10-21 外部单据身份 2 字段(外部单号/外部项次):追加尾部、可选、非匹配身份。
|
||||
|
||||
Why: CRANE/Lognet 出站报告携带 WMS 自己的单据+行身份,需要与调拨单号
|
||||
(doc_no)分开留存并作为异动档自然键成分(档幂等主键管控);匹配 grain
|
||||
仍=单号/料号/异动日期,不受外部身份扩维扰动(契约由
|
||||
test_identity_and_match_key_unchanged_by_extension 锁定)。
|
||||
"""
|
||||
by_code = {field.code: field for field in MOVEMENT_FIELDS}
|
||||
expected_labels = {"external_doc_no": "外部单号", "external_line_no": "外部项次"}
|
||||
# [断言意图] 只追加不重排:外部身份字段排在既有全部字段之后(文件列顺序契约)。
|
||||
assert [field.code for field in MOVEMENT_FIELDS][-2:] == list(EXTERNAL_IDENTITY_FIELD_CODES)
|
||||
for code in EXTERNAL_IDENTITY_FIELD_CODES:
|
||||
field = by_code[code]
|
||||
assert field.label == expected_labels[code], code
|
||||
assert field.value_type == "text", code
|
||||
# 解析放行空值(存量入站 Profile 未映射时不阻断);不进匹配身份集合。
|
||||
assert field.required is False, code
|
||||
assert field.is_identity is False, code
|
||||
|
||||
|
||||
def test_movement_field_codes_include_extension_codes():
|
||||
"""movement_field_codes() 自动包含全部扩展字段码(管理端字段目录/映射白名单数据源)。"""
|
||||
codes = movement_field_codes()
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""outbound_evidence_sync:出站证据同步(落档桥)守卫矩阵。
|
||||
|
||||
用途:锁定出站回调 success 后的解析落档链——①正常路径按 purpose=outbound 已发布
|
||||
规则解析归档、record_kind='outbound' 幂等落档 + 审计事件;②schema 类解析
|
||||
失败把 parse_failed 三列独立落到出站归档文件上(状态投影随之 parse_failed)、
|
||||
一行不落;③无配置/规则未发布或 purpose 不符 → no-op(fail-closed,不落失败
|
||||
标记——规则缺失不是文件错误);④handler 接线:success 事实触发同步。
|
||||
依赖:factories(build_movement_xlsx/INBOUND_MOVEMENT_FIELD_MAPPING + FakeArchiveStorage)、
|
||||
ledger_sync.movement_file_version、app fixture(全局种子含 DSV360_AWSDU 站点)。
|
||||
逻辑:归档字节经假存储注入(monkeypatch file_asset_storage.get_bytes);解析组装
|
||||
与落档口径全部复用入站同一实现(parse_archive_to_ledger_rows / sync_ledger_rows),
|
||||
差异仅 record_kind 与规则门禁 purpose='outbound'。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
FreightRpaParsingProfile,
|
||||
TransferAuditEvent,
|
||||
TransferMovementLedger,
|
||||
)
|
||||
from app.services.in_transit_transfer.ledger_sync import movement_file_version
|
||||
from app.services.in_transit_transfer.outbound_evidence_sync import (
|
||||
sync_and_commit_for_outbound_callback,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from tests.services.in_transit_transfer import factories
|
||||
|
||||
pytestmark = [pytest.mark.usefixtures("app")]
|
||||
|
||||
SOURCE = "DSV360_AWSDU"
|
||||
# 真实时钟基准:handler/状态投影内部固定取 utcnow(),种子必须同窗口。
|
||||
NOW = datetime.utcnow()
|
||||
STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def outbound_storage(monkeypatch):
|
||||
"""归档假存储:替换单例 get_bytes(所有引用方同源)。"""
|
||||
fake = factories.FakeArchiveStorage()
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
|
||||
return fake
|
||||
|
||||
|
||||
def _seed_outbound_world(*, profile_status: str = "published",
|
||||
profile_purpose: str = "outbound",
|
||||
bind_profile: bool = True) -> FreightRpaOutboundReportFile:
|
||||
"""出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。
|
||||
|
||||
Returns:
|
||||
已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。
|
||||
"""
|
||||
from app.models import FreightRpaSource
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=SOURCE).one()
|
||||
profile = None
|
||||
if bind_profile:
|
||||
profile = FreightRpaParsingProfile(
|
||||
purpose=profile_purpose, profile_code=f"OUT_{SOURCE}", display_name=SOURCE,
|
||||
version=1, status=profile_status, file_format="xlsx",
|
||||
definition_json={
|
||||
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
|
||||
"sheet_name": "Receipt", "header_row_index": 1,
|
||||
},
|
||||
structure_definition_json={},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
db.session.add(FreightRpaOutboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={"report_name": "Outbound"},
|
||||
query_parameters_json=[],
|
||||
parsing_profile_id=profile.id if profile is not None else None,
|
||||
))
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
schedule_run_id=None, source_id=source.id, source_code=SOURCE,
|
||||
connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001",
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
import hashlib
|
||||
|
||||
digest = hashlib.sha256(b"outbound evidence workbook").hexdigest()
|
||||
report = FreightRpaOutboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx",
|
||||
file_size=16, sha256=digest,
|
||||
# 与 NOW 同刻:保证落在真实业务日新鲜度窗口内(handler/投影同窗口)。
|
||||
created_at=NOW,
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
return report
|
||||
|
||||
|
||||
def _count_outbound_ledger(source_code: str = SOURCE) -> int:
|
||||
"""该来源 outbound 档行总数。"""
|
||||
return TransferMovementLedger.query.filter_by(
|
||||
source_code=source_code, record_kind="outbound").count()
|
||||
|
||||
|
||||
def test_outbound_callback_syncs_ledger_rows(outbound_storage):
|
||||
# [断言意图] 正常路径:success 回调桥把出站归档按 purpose=outbound 规则解析、
|
||||
# record_kind='outbound' 幂等落档;溯源(source_file_id/sha)与审计事件齐全。
|
||||
report = _seed_outbound_world()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||||
])
|
||||
|
||||
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
|
||||
|
||||
assert ok is True # [断言意图] 落档成功
|
||||
assert _count_outbound_ledger() == 1 # [断言意图] 出站行落异动档
|
||||
db.session.expire_all()
|
||||
row = TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").one()
|
||||
assert row.doc_no == "ASN-O1" and row.material_code == "MAT-O1"
|
||||
assert row.quantity == "120" and row.movement_date == "2026-10-16"
|
||||
assert row.source_file_id == report.id and row.file_sha256 == report.sha256
|
||||
# [断言意图] 审计事件带 record_kind=outbound(与入站同 kind、payload 区分流)。
|
||||
event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").one()
|
||||
assert event.after_json["record_kind"] == "outbound"
|
||||
assert event.after_json["inserted"] == 1
|
||||
|
||||
|
||||
def test_outbound_file_version_uses_shared_stamp(outbound_storage):
|
||||
"""出站落档的 file_version 必须是 movement_file_version,不能在本路径另拼。
|
||||
|
||||
Why: 2026-10-21 DSV AWSFRA01/AWSBICMH01 实测——本路径自行拼接 sha256: 前缀
|
||||
且未按列宽截断,71 字符整批 INSERT 失败,文件仍显示就绪但档里零记录。
|
||||
"""
|
||||
report = _seed_outbound_world()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
|
||||
])
|
||||
|
||||
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
|
||||
|
||||
assert ok is True # [断言意图] 落档成功(不再超长炸批)
|
||||
db.session.expire_all()
|
||||
row = TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, record_kind="outbound").one()
|
||||
# [断言意图] 落库版本戳等于共享函数对这份摘要的结果,且不超过列宽。
|
||||
assert row.file_version == movement_file_version(report.sha256)
|
||||
assert len(row.file_version) <= 64
|
||||
|
||||
|
||||
def test_outbound_parse_failure_marks_file_and_lands_nothing(outbound_storage):
|
||||
# [断言意图] 解析失败分层(出站补齐):schema 类失败 → parse_failed 三列独立
|
||||
# 落到出站归档文件、零档行;状态投影随之 parse_failed(文件仍可用、供诊断)。
|
||||
report = _seed_outbound_world()
|
||||
# 有料号但单号为空 → missing_invoice_no → 解析必失败(料号空行 2026-10-21
|
||||
# 起静默跳过放行,schema 失败路径改由仍受管控的单号缺失触发)。
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
|
||||
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
|
||||
|
||||
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
|
||||
|
||||
assert ok is False # [断言意图] 落档失败如实返回
|
||||
assert _count_outbound_ledger() == 0 # [断言意图] 一行不落
|
||||
db.session.expire_all()
|
||||
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
|
||||
assert marked.parse_failed_at is not None # [断言意图] 失败事实落到文件
|
||||
assert marked.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
status = resolve_source_file_status(source_code=SOURCE, record_kind="outbound")
|
||||
assert status["file_status"] == "parse_failed" # [断言意图] 投影不再当 ready
|
||||
assert status["file_sha256"] == report.sha256
|
||||
|
||||
|
||||
def test_outbound_without_published_outbound_profile_is_noop(outbound_storage):
|
||||
# [断言意图] 规则门禁(fail-closed):无绑定规则 / 规则未发布 / purpose 不符
|
||||
# → 桥 no-op(True=无事可做),零档行且不落解析失败标记——规则缺失不是文件错误。
|
||||
for kwargs in (
|
||||
{"bind_profile": False}, # 未绑定规则
|
||||
{"profile_status": "draft"}, # 规则未发布
|
||||
{"profile_purpose": "inbound"}, # purpose 不符(误绑入站规则)
|
||||
):
|
||||
report = _seed_outbound_world(**kwargs)
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O2", "1", "O", "MAT-O2", "成品", "LOT-O2", 30, "2026-10-16"],
|
||||
])
|
||||
|
||||
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
|
||||
|
||||
assert ok is True, kwargs # [断言意图] 无事可做≠失败
|
||||
assert _count_outbound_ledger() == 0, kwargs
|
||||
db.session.expire_all()
|
||||
assert FreightRpaOutboundReportFile.query.filter_by(
|
||||
id=report.id).one().parse_failed_at is None, kwargs
|
||||
# 清场(三门支共用全局种子,互不污染)。
|
||||
FreightRpaOutboundReportConfig.query.delete()
|
||||
FreightRpaOutboundReportFile.query.delete()
|
||||
FreightRpaOutboundUnitRun.query.delete()
|
||||
if kwargs.get("bind_profile", True):
|
||||
FreightRpaParsingProfile.query.filter(
|
||||
FreightRpaParsingProfile.profile_code == f"OUT_{SOURCE}").delete()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_outbound_handler_success_fact_triggers_sync(outbound_storage):
|
||||
# [断言意图] handler 接线:outbound success 事实(ok 且 file_id)在任务推进/
|
||||
# 提交之后触发证据同步(与入站 handle_inbound_report STEP 4 对称);失败事实
|
||||
# 不触发(无文件可解析,桥不得误读他源文件)。
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
|
||||
|
||||
report = _seed_outbound_world()
|
||||
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
|
||||
["ASN-O3", "1", "O", "MAT-O3", "成品", "LOT-O3", 55, "2026-10-16"],
|
||||
])
|
||||
|
||||
handle_outbound_report(ReportFact(
|
||||
report_kind="outbound", source_code=SOURCE, file_id=report.id,
|
||||
sha256=report.sha256, ok=True, error_code=None, error_message=None,
|
||||
unit_run_id=report.unit_run_id,
|
||||
))
|
||||
|
||||
assert _count_outbound_ledger() == 1 # [断言意图] 事实驱动落档
|
||||
# [断言意图] 失败事实(同一世界、新归档无字节解析路径不触发):行数不增。
|
||||
handle_outbound_report(ReportFact(
|
||||
report_kind="outbound", source_code=SOURCE, file_id=None,
|
||||
sha256=None, ok=False, error_code="RPA_OUTBOUND_CALLBACK_FAILED",
|
||||
error_message="export failed", unit_run_id=report.unit_run_id,
|
||||
))
|
||||
assert _count_outbound_ledger() == 1
|
||||
@@ -70,11 +70,11 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
assert item.from_quantity == Decimal("1200")
|
||||
|
||||
|
||||
def test_same_day_data_queried_through_gateway(app, same_day_inbound_file):
|
||||
"""【成熟退役 2026-10-16】当天异动数据照常经网关查询(无免查日期)。
|
||||
def test_same_day_data_not_queried_before_maturity(app, same_day_inbound_file):
|
||||
"""【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进圈档、不经网关查询。
|
||||
|
||||
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
|
||||
网关调用必须发生——日期不再构成评估前置过滤。
|
||||
[断言意图] 圈档封顶 movement_date ≤ T−2:当天行不出生 item,网关零调用——
|
||||
日期在圈档入口即构成过滤(此前「成熟退役 2026-10-16」的免查语义随之收回)。
|
||||
"""
|
||||
gw = FakeGateway(inventory={})
|
||||
deps = _cap_deps(same_day_inbound_file, gw)
|
||||
@@ -83,8 +83,8 @@ def test_same_day_data_queried_through_gateway(app, same_day_inbound_file):
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
|
||||
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
|
||||
assert result.items[0].result == "blocked_inventory_not_found"
|
||||
assert gw.calls == []
|
||||
assert result.items == ()
|
||||
|
||||
|
||||
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""首页队列「待匹配」桶与执行门禁改锚测试(Task 12,规格 §10,D16/D17)。
|
||||
|
||||
用途:锁定两块契约——
|
||||
①「待匹配」桶口径(D16):档记录 ∈ 启用类型范围并集、record_kind='inbound'、
|
||||
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致);
|
||||
匹配圈定后离开、取消匹配释放后回归;无 item_id 不可勾选执行;
|
||||
①「待匹配」桶口径:成熟未占用的出入站全量(不按类型范围过滤);
|
||||
可匹配=启用类型范围并集(matchable / matchable_count)。
|
||||
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致)、
|
||||
movement_date ≤ T−2;匹配圈定后离开、取消匹配释放后回归;无 item_id。
|
||||
②file_current 门禁改锚(规格 §10):行当前性 = item → 档记录 file_sha256 ==
|
||||
该来源最新可用文件 sha(档记录无变化即当前——档换版原行更新后行不再因
|
||||
出生戳陈旧误判);行无档关联回退 raw_lines 出生戳(存量兼容)。
|
||||
@@ -68,6 +69,11 @@ def _pending_doc_nos() -> set[str]:
|
||||
return {record.doc_no for record in list_pending_match_records()}
|
||||
|
||||
|
||||
def _matchable_doc_nos() -> set[str]:
|
||||
"""待匹配桶里启用类型现在圈得住的单号。"""
|
||||
return {record.doc_no for record in list_pending_match_records() if record.matchable}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ①「待匹配」桶口径(D16)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -104,12 +110,30 @@ def test_pending_match_bucket_summary_count():
|
||||
assert summary.pending_match_count == 2
|
||||
|
||||
|
||||
def test_pending_match_includes_mature_rows_outside_enabled_types():
|
||||
"""待匹配收全部成熟未占用记录;可匹配只计启用类型范围并集。"""
|
||||
_seed_ledger("HOM-1")
|
||||
_seed_ledger("QQQ-1", row_no=2)
|
||||
|
||||
pending = list_pending_match_records()
|
||||
summary = backlog_summary()
|
||||
|
||||
# [断言意图] 首页待匹配不再按类型范围收窄:范围外的成熟行仍在桶里。
|
||||
assert {record.doc_no for record in pending} == {"HOM-1", "QQQ-1"}
|
||||
# [断言意图] 库存匹配卡的可匹配数只含启用类型罩得住的行。
|
||||
assert {record.doc_no for record in pending if record.matchable} == {"HOM-1"}
|
||||
assert {record.doc_no for record in list_pending_match_records(segment="outside")} == {"QQQ-1"}
|
||||
assert {record.doc_no for record in list_pending_match_records(segment="matchable")} == {"HOM-1"}
|
||||
assert summary.pending_match_count == 2
|
||||
assert summary.matchable_count == 1
|
||||
|
||||
|
||||
def test_pending_match_bucket_leaves_once_matched():
|
||||
"""匹配圈定 → 记录被 items 占用,离开待匹配桶(数字卡回落)。"""
|
||||
_seed_ledger("HOM-1")
|
||||
deps = _match_defaults()
|
||||
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-14",
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15",
|
||||
deps=deps, transfer_type="in_transit_to_hub")
|
||||
|
||||
# [断言意图] 记录被匹配 items 占用(D17)→ 离开待匹配桶。
|
||||
@@ -120,7 +144,7 @@ def test_pending_match_bucket_returns_after_matching_cancelled():
|
||||
"""取消匹配释放占用(D17)→ 记录回归待匹配桶。"""
|
||||
_seed_ledger("HOM-1")
|
||||
deps = _match_defaults()
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-14",
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15",
|
||||
deps=deps, transfer_type="in_transit_to_hub")
|
||||
assert _pending_doc_nos() == set()
|
||||
|
||||
@@ -135,21 +159,22 @@ def test_pending_match_bucket_returns_after_matching_cancelled():
|
||||
assert _pending_doc_nos() == {"HOM-1"}
|
||||
|
||||
|
||||
def test_pending_match_bucket_excludes_sealed_shipment_and_out_of_scope():
|
||||
"""恒排除:已封存(transfer_executed)/ 出货记录 / 范围外 / movement_date 空值。"""
|
||||
_seed_ledger("HOM-1") # 在桶
|
||||
def test_pending_match_bucket_excludes_sealed_and_out_of_scope():
|
||||
"""恒排除已封存与空异动日期;范围外仍留在待匹配,但不算可匹配。"""
|
||||
_seed_ledger("HOM-1") # 在桶且可匹配
|
||||
_seed_ledger("HOM-SEALED", row_no=2, transfer_executed=True,
|
||||
executed_doc_no="ERP-1") # 已执行封存
|
||||
_seed_ledger("HOM-SHIP", row_no=3, record_kind="outbound") # 出货记录(一期不进桶)
|
||||
_seed_ledger("QQQ-1", row_no=4) # 范围外(无启用类型命中)
|
||||
_seed_ledger("HOM-NODATE", row_no=5, movement_date=None) # 收料日期空值(不进圈定)
|
||||
_seed_ledger("HOM-SHIP", row_no=3, record_kind="outbound") # 出站,默认类型未钉记录类型
|
||||
_seed_ledger("QQQ-1", row_no=4) # 范围外,仍在待匹配
|
||||
_seed_ledger("HOM-NODATE", row_no=5, movement_date=None) # 异动日期空值
|
||||
|
||||
# [断言意图] 桶只收「启用类型范围并集内、inbound、未封存、有异动日期、无 items」的档记录。
|
||||
assert _pending_doc_nos() == {"HOM-1"}
|
||||
# [断言意图] 待匹配收成熟未占用的出入站;可匹配才按启用类型范围并集收窄。
|
||||
assert _pending_doc_nos() == {"HOM-1", "HOM-SHIP", "QQQ-1"}
|
||||
assert _matchable_doc_nos() == {"HOM-1", "HOM-SHIP"}
|
||||
|
||||
|
||||
def test_pending_match_bucket_is_union_of_enabled_type_scopes():
|
||||
"""范围并集=对每个启用类型分别圈取后并集;停用类型即退出并集。"""
|
||||
"""可匹配=启用类型范围并集;停用类型不把已落档行移出待匹配。"""
|
||||
_seed_ledger("HOM-1") # 默认类型(HOM/HOX/WTP 前缀)
|
||||
_seed_ledger("ZZZ-1", row_no=2) # 第二类型范围
|
||||
_seed_ledger("QQQ-1", row_no=3) # 无类型覆盖
|
||||
@@ -157,19 +182,24 @@ def test_pending_match_bucket_is_union_of_enabled_type_scopes():
|
||||
{"field": "doc_no", "match": "prefix", "values": ["ZZZ"]},
|
||||
])
|
||||
|
||||
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1"}
|
||||
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
|
||||
assert _matchable_doc_nos() == {"HOM-1", "ZZZ-1"}
|
||||
|
||||
# [断言意图] 停用类型即刻退出并集(停用后新匹配不可选,队列口径同步收窄)。
|
||||
# [断言意图] 停用类型即刻退出可匹配并集,待匹配全量保持不变。
|
||||
row = db.session.query(TransferTypeConfig).filter_by(code="hub_repair_out").one()
|
||||
row.enabled = False
|
||||
db.session.commit()
|
||||
assert _pending_doc_nos() == {"HOM-1"}
|
||||
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
|
||||
assert _matchable_doc_nos() == {"HOM-1"}
|
||||
|
||||
# [断言意图] 无启用类型 → 空桶(fail-closed:无类型即无范围,与匹配创建一致)。
|
||||
# [断言意图] 无启用类型 → 可匹配为空;待匹配仍可见已落档行。
|
||||
for cfg in db.session.query(TransferTypeConfig).all():
|
||||
cfg.enabled = False
|
||||
db.session.commit()
|
||||
assert _pending_doc_nos() == set()
|
||||
assert _matchable_doc_nos() == set()
|
||||
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
|
||||
# [断言意图] 可匹配段在没有启用类型时走空查询,而不是把全量当成可匹配。
|
||||
assert list_pending_match_records(segment="matchable") == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -177,9 +207,13 @@ def test_pending_match_bucket_is_union_of_enabled_type_scopes():
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _patch_latest_file(monkeypatch, sha_by_source: dict[str, str]):
|
||||
"""注入 matching_service 的来源文件状态投影(source_code → 最新可用文件 sha)。"""
|
||||
"""注入 matching_service 的来源文件状态投影(source_code → 最新可用文件 sha)。
|
||||
|
||||
def _resolve(*, source_code: str) -> dict:
|
||||
record_kind 入参接受但不区分,存量断言仍按来源比对。
|
||||
"""
|
||||
|
||||
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
|
||||
del record_kind
|
||||
sha = sha_by_source.get(source_code)
|
||||
return {"file_status": "ready" if sha else "none", "has_ready_file": bool(sha),
|
||||
"file_no": "REC-TEST", "file_sha256": sha}
|
||||
|
||||
@@ -28,7 +28,7 @@ def _file_ready(monkeypatch, dbs_ready_file: dict) -> None:
|
||||
"""让来源文件状态投影返回 ready(sha 与 fixture 文件一致,不触碰真实文件表)。"""
|
||||
monkeypatch.setattr(
|
||||
matching_service, "resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
|
||||
lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": dbs_ready_file["file_no"],
|
||||
"file_sha256": dbs_ready_file["checksum"]},
|
||||
)
|
||||
@@ -114,7 +114,7 @@ def test_restore_marks_file_current_false_without_ready_file(transfer_db, dbs_re
|
||||
"""来源当前无可用文件 → 行 file_current=False(fail-safe,不得当作新鲜)。"""
|
||||
monkeypatch.setattr(
|
||||
matching_service, "resolve_source_file_status",
|
||||
lambda *, source_code: {"file_status": "none", "has_ready_file": False,
|
||||
lambda *, source_code, record_kind="inbound": {"file_status": "none", "has_ready_file": False,
|
||||
"file_no": None, "file_sha256": None},
|
||||
)
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
|
||||
@@ -25,7 +25,7 @@ def _mismatch_matching(dbs_ready_file):
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
return deps, erp, summary
|
||||
|
||||
|
||||
@@ -213,7 +213,7 @@ def test_requery_reaches_only_own_matching_rows(transfer_db, dbs_ready_file):
|
||||
assert row.matching_id == first_matching.id
|
||||
|
||||
# 第二次同 scope 匹配:圈档互斥 → 空壳(无自有行)。
|
||||
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
assert second.matching_id != first.matching_id
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
assert row.matching_id != second_matching.id
|
||||
@@ -285,7 +285,7 @@ def _wtp_lot_matching(transfer_db):
|
||||
}
|
||||
deps, erp, _ = make_transfer_deps(file_dict)
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
return deps, erp
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""范围规则引擎契约:规则间 AND、规则内多值 OR、受控词表、SQL 编译与内存求值同口径。
|
||||
|
||||
用途:锁定 scope_rules 引擎对外契约——受控字段白名单校验、evaluate/apply 双形态
|
||||
同口径(防谓词漂移)、审计说明文本格式;Task 11(圈档/重查)与 Task 5
|
||||
(API 校验)消费本契约。
|
||||
同口径(防谓词漂移)、record_kinds_of 证据流推导、审计说明文本格式;
|
||||
Task 11(圈档/重查)与 Task 5(API 校验)及证据流 UI 后续任务消费本契约。
|
||||
依赖:app.core.errors.ValidationError、scope_rules 引擎、SQLAlchemy、
|
||||
models/in_transit_transfer.TransferMovementLedger(SQL 编译断言与真库
|
||||
行集交叉验证均以真档表为对象,2026-10-14 Task 9 回补,探针模型退役)。
|
||||
@@ -19,7 +19,7 @@ from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.in_transit_transfer import TransferMovementLedger
|
||||
from app.services.in_transit_transfer.scope_rules import (
|
||||
apply_scope_filters, evaluate_scope, parse_scope_rules, scope_rules_note,
|
||||
apply_scope_filters, evaluate_scope, parse_scope_rules, record_kinds_of, scope_rules_note,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
@@ -31,6 +31,19 @@ RULES = parse_scope_rules([
|
||||
])
|
||||
|
||||
|
||||
def test_record_kinds_of_reads_existing_scope_rule():
|
||||
"""没有记录类型规则时入站和出站都要;只写 outbound 时只要出站。"""
|
||||
assert record_kinds_of(parse_scope_rules([
|
||||
{"field": "doc_no", "match": "prefix", "values": ["HOM"]},
|
||||
])) == ("inbound", "outbound")
|
||||
assert record_kinds_of(parse_scope_rules([
|
||||
{"field": "record_kind", "match": "equals", "values": ["outbound"]},
|
||||
])) == ("outbound",)
|
||||
assert record_kinds_of(parse_scope_rules([
|
||||
{"field": "record_kind", "match": "in", "values": ["outbound", "inbound"]},
|
||||
])) == ("inbound", "outbound")
|
||||
|
||||
|
||||
def test_rules_are_and_values_are_or():
|
||||
"""两条规则须同时满足;同一规则内任一前缀命中即可。"""
|
||||
assert evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-A"}, RULES)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""来源收料文件状态投影服务测试。
|
||||
"""来源证据文件状态投影服务测试。
|
||||
|
||||
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
|
||||
按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败
|
||||
标记 record/clear 的往返语义。调拨不维护独立抓取状态表。
|
||||
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
|
||||
逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed);
|
||||
有进行中单元→fetching;最新单元失败终态→failed;
|
||||
保留期已到或隔日旧文件(未清理)→expired;否则→none。
|
||||
用途:验证 resolve_source_file_status / resolve_source_file_statuses 只读货代入站/出站事实(UnitRun/ReportFile),
|
||||
按来源与 record_kind 投影 ready/fetching/failed/expired/parse_failed/none/
|
||||
unconfigured,并验证入站解析失败标记 record/clear 的往返语义。
|
||||
调拨不维护独立抓取状态表。
|
||||
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile;
|
||||
出站用例用 monkeypatch 注入配置与可用文件视图,不连对象存储。
|
||||
逻辑:入站既有用例保持:当天业务日且未过期文件→ready(解析失败→parse_failed);
|
||||
进行中单元→fetching;最新单元失败终态→failed;空数据→no_data;
|
||||
保留期已到或隔日旧文件→expired;否则→none。
|
||||
出站无配置→unconfigured;出站有可用文件视图→ready。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -247,3 +250,170 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
|
||||
assert recover_all_stale_orphan_inbound_units() == 1
|
||||
db.session.expire_all()
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'
|
||||
|
||||
|
||||
def test_outbound_without_config_is_unconfigured(monkeypatch):
|
||||
"""没有出站报表配置时,出站流是未配置,入站投影函数签名仍可只传来源。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
|
||||
lambda source_code: None,
|
||||
)
|
||||
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
|
||||
assert status["file_status"] == "unconfigured"
|
||||
assert status["has_ready_file"] is False
|
||||
|
||||
|
||||
def test_outbound_usable_file_is_ready(monkeypatch):
|
||||
"""出站已配置且存在可用归档时投影 ready;文件视图按入站可用文件形状注入,不读对象存储。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
|
||||
lambda source_code: object(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.source_file_status.latest_usable_outbound_file",
|
||||
lambda source_code: SimpleNamespace(
|
||||
file_id=7,
|
||||
original_filename="outbound.xlsx",
|
||||
sha256="ab" * 32,
|
||||
parse_failed_at=None,
|
||||
),
|
||||
)
|
||||
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
|
||||
# [断言意图] ready 必须读入站同形视图的文件名与摘要,而不是另查对象存储。
|
||||
assert status["file_status"] == "ready"
|
||||
assert status["has_ready_file"] is True
|
||||
assert status["file_no"] == "outbound.xlsx"
|
||||
assert status["file_sha256"] == "ab" * 32
|
||||
|
||||
|
||||
def test_unknown_record_kind_is_rejected():
|
||||
"""record_kind 只接受 inbound / outbound。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="onhand")
|
||||
|
||||
|
||||
def test_outbound_report_file_projects_ready(app):
|
||||
"""出站配置与当天可用归档都在库时,按出站文件表投影 ready,不读对象存储。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
FreightRpaSource,
|
||||
)
|
||||
|
||||
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(FreightRpaOutboundReportConfig(
|
||||
source_id=source.id,
|
||||
report_path_json={'report_name': 'Outbound'},
|
||||
query_parameters_json=[],
|
||||
))
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='outbound-status-ready',
|
||||
status='success', config_snapshot_json={}, trigger_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
digest = hashlib.sha256(b'outbound workbook').hexdigest()
|
||||
db.session.add(FreightRpaOutboundReportFile(
|
||||
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/outbound/test.xlsx', original_filename='outbound-real.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE, record_kind='outbound')
|
||||
# [断言意图] 出站 ready 走真实归档表与单元行,文件名/摘要来自行数据而非对象存储。
|
||||
assert status['file_status'] == 'ready'
|
||||
assert status['has_ready_file'] is True
|
||||
assert status['file_no'] == 'outbound-real.xlsx'
|
||||
assert status['file_sha256'] == digest
|
||||
|
||||
|
||||
def _clone_enabled_source(source_code: str):
|
||||
"""再造一个启用来源,复用种子站点的登录连接与模板,避免把查询次数测试绑在单来源上。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaSource
|
||||
|
||||
existing = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
source = FreightRpaSource(
|
||||
source_code=source_code,
|
||||
display_name=source_code,
|
||||
connector_type=existing.connector_type,
|
||||
rpa_profile_id=existing.rpa_profile_id,
|
||||
excel_template_id=existing.excel_template_id,
|
||||
warehouse_resolution_mode=existing.warehouse_resolution_mode,
|
||||
fixed_warehouse_id=existing.fixed_warehouse_id,
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_batch_status_matches_per_source_and_prefers_running_unit(app, receipt_unit_run):
|
||||
"""列表批量投影与逐来源投影一致;较新的失败单元不能盖住仍在进行的单元。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
|
||||
|
||||
db.session.add(FreightRpaInboundUnitRun(
|
||||
schedule_run_id=None,
|
||||
source_id=receipt_unit_run.source_id,
|
||||
source_code=SOURCE_CODE,
|
||||
connector_type='dbs',
|
||||
callback_id='inbound-newer-failed',
|
||||
status='failed',
|
||||
config_snapshot_json={},
|
||||
trigger_snapshot_json={},
|
||||
))
|
||||
extra = _clone_enabled_source('DSV360_BATCH_EXTRA')
|
||||
db.session.commit()
|
||||
|
||||
sources = FreightRpaSource.query.filter(
|
||||
FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]),
|
||||
).all()
|
||||
batched = resolve_source_file_statuses(sources)
|
||||
# [断言意图] 进行中单元优先于更新的失败单元,批量结果必须与逐条投影相同。
|
||||
assert batched[SOURCE_CODE]['inbound']['file_status'] == 'fetching'
|
||||
assert batched[SOURCE_CODE]['outbound']['file_status'] == 'unconfigured'
|
||||
assert batched[extra.source_code]['inbound']['file_status'] == 'none'
|
||||
for source in sources:
|
||||
assert batched[source.source_code]['inbound'] == resolve_source_file_status(
|
||||
source_code=source.source_code, record_kind='inbound',
|
||||
)
|
||||
assert batched[source.source_code]['outbound'] == resolve_source_file_status(
|
||||
source_code=source.source_code, record_kind='outbound',
|
||||
)
|
||||
|
||||
|
||||
def test_batch_status_query_count_stays_flat_for_two_sources(app, receipt_unit_run):
|
||||
"""两个来源的列表投影查询次数保持常数,不能按来源乘开。"""
|
||||
from sqlalchemy import event
|
||||
|
||||
from app import db
|
||||
from app.models import FreightRpaSource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
|
||||
|
||||
extra = _clone_enabled_source('DSV360_BATCH_COUNT')
|
||||
sources = FreightRpaSource.query.filter(
|
||||
FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]),
|
||||
).all()
|
||||
assert len(sources) == 2
|
||||
|
||||
count = {'n': 0}
|
||||
|
||||
def _count_query(*_args, **_kwargs):
|
||||
count['n'] += 1
|
||||
|
||||
event.listen(db.engine, 'before_cursor_execute', _count_query)
|
||||
try:
|
||||
resolve_source_file_statuses(sources)
|
||||
finally:
|
||||
event.remove(db.engine, 'before_cursor_execute', _count_query)
|
||||
# [断言意图] 逐来源投影约 7 次/来源;两个来源仍必须落在固定的几次批量查询里。
|
||||
assert count['n'] <= 8
|
||||
@@ -18,13 +18,14 @@ from app import db
|
||||
from app.models import FreightRpaInboundReportFile
|
||||
from app.models.in_transit_transfer import TransferMovementLedger
|
||||
|
||||
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维):8 成分全部 NOT NULL,
|
||||
# 可空语义成分(line_seq/in_out_flag/carton_id/lot_no)default ''(R7 终审:
|
||||
# carton_id/lot_no NOT NULL + default '',防 PG NULL 逃逸唯一比对)。
|
||||
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维 + 2026-10-21 外部身份
|
||||
# 扩维):10 成分全部 NOT NULL,可空语义成分(line_seq/in_out_flag/carton_id/
|
||||
# lot_no/external_doc_no/external_line_no)default ''(R7 终审:carton_id/lot_no
|
||||
# NOT NULL + default '',防 PG NULL 逃逸唯一比对;外部身份两列同口径)。
|
||||
NATURAL_KEY_COLUMNS = (
|
||||
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
|
||||
)
|
||||
NATURAL_KEY_DIMENSION_COLUMNS = ('carton_id', 'lot_no')
|
||||
NATURAL_KEY_DIMENSION_COLUMNS = ('carton_id', 'lot_no', 'external_doc_no', 'external_line_no')
|
||||
NATURAL_KEY_CONSTRAINT = 'uq_transfer_movement_ledger_natural_key'
|
||||
|
||||
# 规格 §4.2 全部业务/证据列(除自然键成分与回写布尔外一律 nullable)。
|
||||
@@ -49,7 +50,7 @@ def _column_map() -> dict:
|
||||
|
||||
|
||||
def test_table_name_and_natural_key_constraint(app_ctx):
|
||||
"""表名固定;自然键八成分(tt14 扩维 carton_id/lot_no)构成唯一约束。"""
|
||||
"""表名固定;自然键十成分(tt14 扩维 carton_id/lot_no + 2026-10-21 外部单据身份)构成唯一约束。"""
|
||||
assert TransferMovementLedger.__tablename__ == 'transfer_movement_ledger'
|
||||
constraints = {
|
||||
c.name: [col.name for col in c.columns]
|
||||
@@ -62,12 +63,13 @@ def test_table_name_and_natural_key_constraint(app_ctx):
|
||||
|
||||
|
||||
def test_natural_key_columns_not_null_with_empty_default(app_ctx):
|
||||
"""自然键 8 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
|
||||
"""自然键 10 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
|
||||
cols = _column_map()
|
||||
for name in NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS:
|
||||
assert cols[name].nullable is False, f"{name} 必须参与自然键即 NOT NULL"
|
||||
# 与落档链路同口径:可空语义成分以空串入库(唯一约束可比,防 PG NULL 逃逸)。
|
||||
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no'):
|
||||
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no',
|
||||
'external_doc_no', 'external_line_no'):
|
||||
assert cols[name].default.arg == ''
|
||||
assert cols[name].server_default.arg == ''
|
||||
|
||||
|
||||
@@ -43,8 +43,12 @@ def _file(*rows: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-05") -> dict:
|
||||
"""构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。"""
|
||||
def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-04") -> dict:
|
||||
"""构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。
|
||||
|
||||
movement_date 缺省取 2026-08-04(= 业务日 08-06 的 T−2 成熟边界;更晚日期
|
||||
会被圈档 T−2 封顶排除)。
|
||||
"""
|
||||
row = {
|
||||
"sheet": "Movement", "row_no": row_no, "doc_no": doc_no,
|
||||
"lot_no": f"LOT-{row_no}", "material_code": f"MAT-{row_no}",
|
||||
@@ -62,9 +66,10 @@ def test_movement_fields_contract_contains_unit_as_11th_field():
|
||||
"""契约定死且第 11 个为 unit:可选文本字段(空值由匹配阶段行级阻断,不产生解析失败)。
|
||||
|
||||
2026-10-14 扩展在 unit 之后追加 7 个可选维度字段(Task 8)——只追加、不重排,
|
||||
unit 的第 11 位契约不变。
|
||||
unit 的第 11 位契约不变;2026-10-21 再追加外部单据身份 2 字段(外部单号/
|
||||
外部项次),总数 11+7+2=20。
|
||||
"""
|
||||
assert len(MOVEMENT_FIELDS) == 18
|
||||
assert len(MOVEMENT_FIELDS) == 20
|
||||
unit = MOVEMENT_FIELDS[10]
|
||||
# [断言意图] unit 定死在第 11 位——movement 文件列顺序契约,解析/展示/ERP 写入共用。
|
||||
assert unit.code == "unit"
|
||||
@@ -73,7 +78,7 @@ def test_movement_fields_contract_contains_unit_as_11th_field():
|
||||
# unit 不是幂等/匹配身份,也不是必填(解析层放行空值,阻断留给匹配层)。
|
||||
assert unit.is_identity is False
|
||||
assert unit.required is False
|
||||
assert len({field.code for field in MOVEMENT_FIELDS}) == 18
|
||||
assert len({field.code for field in MOVEMENT_FIELDS}) == 20
|
||||
|
||||
|
||||
# ---- ② 解析:带出 unit 原值(仅 trim,不换算/不清洗) -----------------------
|
||||
@@ -189,10 +194,10 @@ def test_matching_hash_freezes_unit_value_out_of_snapshot(app):
|
||||
def test_matching_hash_unchanged_when_unit_backfilled(app):
|
||||
"""行补 unit 前后 Hash 不变:unit 是展示/写入列而非 Hash 入参(口径冻结)。"""
|
||||
deps_before, _erp_a, _rpa = make_transfer_deps(_file(
|
||||
_row(1, "HOM-901", movement_date="2026-08-06"),
|
||||
_row(1, "HOM-901", movement_date="2026-08-04"),
|
||||
))
|
||||
deps_after, _erp_b, _rpa = make_transfer_deps(_file(
|
||||
_row(1, "HOM-901", unit="KG", movement_date="2026-08-06"),
|
||||
_row(1, "HOM-901", unit="KG", movement_date="2026-08-04"),
|
||||
))
|
||||
seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次
|
||||
hash_before = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_before, transfer_type="in_transit_to_hub").summary.matching_hash
|
||||
|
||||
@@ -39,30 +39,48 @@ class _FakeLocator:
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
url: str = "https://wms-portal.craneww.com/#/",
|
||||
visible_tokens: tuple[str, ...] = ("on-hand-details-query", "On Hand Details", "Queries", "navbar"),
|
||||
visible_role_names: tuple[str, ...] = ("On Hand Details", "Queries"),
|
||||
) -> None:
|
||||
self.url = url
|
||||
self.frames: list[_FakePage] = []
|
||||
self.goto_calls: list[str] = []
|
||||
self.evaluate_calls: list[tuple[str, object]] = []
|
||||
self.reload_calls: list[int] = []
|
||||
self.locator_selectors: list[str] = []
|
||||
self._visible_tokens = visible_tokens
|
||||
self._visible_role_names = visible_role_names
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if "on-hand-details-query" in selector or "On Hand Details" in selector:
|
||||
return _FakeLocator(visible=True)
|
||||
if "Queries" in selector or "navbar" in selector:
|
||||
return _FakeLocator(visible=True)
|
||||
return _FakeLocator(visible=False)
|
||||
self.locator_selectors.append(selector)
|
||||
visible = any(token in selector for token in self._visible_tokens)
|
||||
return _FakeLocator(visible=visible)
|
||||
|
||||
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
|
||||
if role == "link" and name in {"On Hand Details", "Queries"}:
|
||||
return _FakeLocator(visible=True)
|
||||
return _FakeLocator(visible=False)
|
||||
return _FakeLocator(visible=name in self._visible_role_names)
|
||||
|
||||
def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None:
|
||||
self.goto_calls.append(url)
|
||||
self.url = url
|
||||
|
||||
def reload(self, wait_until: str = "", timeout: int = 0) -> None:
|
||||
self.reload_calls.append(1)
|
||||
|
||||
def evaluate(self, script: str, arg: object = None) -> None:
|
||||
self.evaluate_calls.append((script, arg))
|
||||
if isinstance(arg, str):
|
||||
self.url = f"https://wms-portal.craneww.com/#/{arg.lstrip('/')}"
|
||||
|
||||
def wait_for_load_state(self, state: str = "", timeout: int = 0) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def test_navigate_prefers_dashboard_tile(monkeypatch):
|
||||
"""应优先尝试首页 On Hand Details 卡片。"""
|
||||
"""应优先尝试首页目标报表卡片。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage()
|
||||
calls: list[str] = []
|
||||
@@ -70,10 +88,10 @@ def test_navigate_prefers_dashboard_tile(monkeypatch):
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_click_dashboard_on_hand_details",
|
||||
"_click_dashboard_report_tile",
|
||||
lambda *args, **kwargs: calls.append("dashboard") or True,
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True)
|
||||
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: calls.append("navbar") or True)
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
|
||||
|
||||
mode = module.navigate_to_crane_report(
|
||||
@@ -95,8 +113,8 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
|
||||
wait_calls = {"n": 0}
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
|
||||
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: True)
|
||||
|
||||
def _wait(page_arg, entry_url, *, browser_timeout_ms):
|
||||
wait_calls["n"] += 1
|
||||
@@ -115,22 +133,59 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
|
||||
assert wait_calls["n"] == 2
|
||||
|
||||
|
||||
def test_navigate_uses_direct_goto_as_last_resort(monkeypatch):
|
||||
"""卡片与菜单均失败时应 goto entry_url。"""
|
||||
def test_direct_goto_last_resort_assigns_hash_in_place(monkeypatch):
|
||||
"""卡片与菜单均失败后:goto entry_url 未就绪时只允许就地赋 hash,禁止回根地址。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage()
|
||||
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
|
||||
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
|
||||
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
|
||||
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False)
|
||||
|
||||
def _wait(page_arg, entry_url_arg, *, browser_timeout_ms):
|
||||
# [断言意图] 就地赋 hash 之后表单才视为就绪;此前一律未就绪
|
||||
return len(page.evaluate_calls) > 0
|
||||
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", _wait)
|
||||
|
||||
mode = module.navigate_to_crane_report(
|
||||
page,
|
||||
entry,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert mode == "direct_goto"
|
||||
assert page.goto_calls == [entry]
|
||||
assert page.reload_calls == []
|
||||
assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
|
||||
assert page.evaluate_calls and "outbound-details-query" in str(page.evaluate_calls[0][1])
|
||||
|
||||
|
||||
def test_navigation_never_lands_on_origin_when_form_never_ready(monkeypatch):
|
||||
"""表单始终未就绪也应抛 RuntimeError,且全程不得 goto 根地址或 reload(会强制登出)。"""
|
||||
module = _load_navigation()
|
||||
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
|
||||
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
|
||||
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False)
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False)
|
||||
|
||||
with pytest.raises(RuntimeError, match="navigation failed"):
|
||||
module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000)
|
||||
module.navigate_to_crane_report(
|
||||
page,
|
||||
entry,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert page.goto_calls[0] == entry
|
||||
assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
|
||||
# [断言意图] 失败收场也只允许一次 goto(entry):根地址/reload 一旦发生即登出
|
||||
assert page.goto_calls == [entry]
|
||||
assert page.reload_calls == []
|
||||
assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
|
||||
|
||||
|
||||
def test_is_crane_on_report_route_reads_entry_hash():
|
||||
@@ -157,3 +212,69 @@ def test_report_route_without_controls_is_not_ready(monkeypatch):
|
||||
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||||
monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False)
|
||||
assert module.is_crane_report_form_ready(page, entry) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("route", "label"),
|
||||
(
|
||||
("on-hand-details-query", "On Hand Details"),
|
||||
("inbound-details-query", "Inbound Details"),
|
||||
("outbound-details-query", "Outbound Details"),
|
||||
),
|
||||
)
|
||||
def test_navigate_targets_tile_by_entry_route(route, label, monkeypatch):
|
||||
"""首页卡片/菜单选择器必须由 entry 路由推导,禁止硬编码 On Hand Details。"""
|
||||
module = _load_navigation()
|
||||
# [构造] 门户对授权用户渲染目标报表卡片:当前路由/标签的选择器可见
|
||||
page = _FakePage(
|
||||
url="https://wms-portal.craneww.com/#/",
|
||||
visible_tokens=(route, label, "Queries"),
|
||||
)
|
||||
entry = f"https://wms-portal.craneww.com/#/{route}"
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
|
||||
|
||||
mode = module.navigate_to_crane_report(
|
||||
page,
|
||||
entry,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert mode == "dashboard_tile"
|
||||
joined = "\n".join(page.locator_selectors)
|
||||
assert label in joined
|
||||
# [断言意图] 出站/入站导航不得再查询 On Hand Details 选择器(2026-10-20 死循环根因之一);
|
||||
# 路由推导由 test_direct_goto_last_resort(evaluate 参数)单独覆盖
|
||||
for other in {"On Hand Details", "Inbound Details", "Outbound Details"} - {label}:
|
||||
assert other not in joined
|
||||
|
||||
|
||||
def test_navbar_fallback_uses_entry_route_label(monkeypatch):
|
||||
"""首页卡片不可见时,经 Queries 菜单点击的路由项也须由 entry 推导。"""
|
||||
module = _load_navigation()
|
||||
# [构造] 卡片全部不可见(token 只含 navbar),仅 Queries 下拉项可见;
|
||||
# 首页等待用短超时避免 shell 未就绪时白等 5s
|
||||
page = _FakePage(
|
||||
url="https://wms-portal.craneww.com/#/",
|
||||
visible_tokens=("navbar",),
|
||||
visible_role_names=("Queries",),
|
||||
)
|
||||
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
|
||||
|
||||
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
|
||||
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
|
||||
|
||||
mode = module.navigate_to_crane_report(
|
||||
page,
|
||||
entry,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
)
|
||||
|
||||
assert mode == "navbar_menu"
|
||||
joined = "\n".join(page.locator_selectors)
|
||||
# [断言意图] 菜单回退路径同样按 entry 推导标签,禁止再查询 On Hand Details 选择器
|
||||
assert '.navbar-dropdown a.navbar-item:has-text("Outbound Details")' in joined
|
||||
assert "On Hand Details" not in joined
|
||||
@@ -599,6 +599,29 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
|
||||
assert fallback_called["value"] is False
|
||||
|
||||
|
||||
def test_refresh_scheduled_reports_list_never_reloads_page(monkeypatch):
|
||||
"""列表 goto 刷新失败时就地重赋 hash;登录态下禁止 page.reload(Crane 门户刷新即登出)。"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
page.url = "https://wms-portal.craneww.com/#/scheduled-reports"
|
||||
page.goto.side_effect = RuntimeError("net::ERR_ABORTED")
|
||||
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_scheduled_reports_table_visible", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(module, "_wait_for_scheduled_reports_list_ready", lambda *_a, **_k: True)
|
||||
|
||||
module._refresh_scheduled_reports_list(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
entry_url="https://wms-portal.craneww.com/#/outbound-details-query",
|
||||
)
|
||||
|
||||
# [断言意图] goto 失败的兜底是就地 hash 重赋;reload 一次都不允许发生
|
||||
page.reload.assert_not_called()
|
||||
assert page.evaluate.called
|
||||
|
||||
|
||||
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
|
||||
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
|
||||
module = _load_export()
|
||||
|
||||
@@ -217,6 +217,26 @@ def test_resolve_parameter_controls_receipt_detail_awsrtm_warehouse_multi_value(
|
||||
assert module.resolve_parameter_controls("Receipt Detail", "Warehouse")["control"] == "select"
|
||||
|
||||
|
||||
def test_resolve_parameter_controls_shipment_order_detail_owner_and_warehouse():
|
||||
"""出站 Shipment Order Detail 的 Owner/Warehouse 应按实机 DOM 使用 multi_value,而不是库存默认 select。"""
|
||||
module = _load_module()
|
||||
owner = module.resolve_parameter_controls("Shipment Order Detail", "Owner")
|
||||
warehouse = module.resolve_parameter_controls("Shipment Order Detail", "Warehouse")
|
||||
# 关键断言:2026-10-19 AWS/Bison/AWSBI 实机——Owner ctl15、Warehouse ctl31,均为 txtValue 下拉。
|
||||
assert owner == {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
|
||||
}
|
||||
assert warehouse == {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl31_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl31_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl31_divDropDown",
|
||||
}
|
||||
|
||||
|
||||
def test_resolve_parameter_controls_unknown_report_empty():
|
||||
"""未登记报表名应返回空配置,由调用方回退参数名默认值(保持旧行为)。"""
|
||||
module = _load_module()
|
||||
@@ -326,10 +346,12 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
|
||||
assert payloads, "应进入多选框下拉填充路径而不是无痕失败"
|
||||
# payloads 会混入结构性解析传入的 label 字符串("Warehouse"),只断言 dict 载荷。
|
||||
dict_payloads = [p for p in payloads if isinstance(p, dict)]
|
||||
assert dict_payloads, "应进入多选框下拉填充路径而不是无痕失败"
|
||||
assert any(
|
||||
payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl17_divDropDown"
|
||||
for payload in payloads
|
||||
for payload in dict_payloads
|
||||
), f"应命中 JDA ctl17 multi_value dropdown,实际 payloads={payloads!r}"
|
||||
|
||||
|
||||
@@ -431,10 +453,12 @@ def test_fill_dsv_filter_if_needed_receipt_awsrtm_uses_ctl29_multi_value():
|
||||
program_label="AWSRTM",
|
||||
)
|
||||
|
||||
assert payloads, "应进入 AWSRTM multi_value 填充路径"
|
||||
# payloads 会混入结构性解析传入的 label 字符串,只断言 dict 载荷。
|
||||
dict_payloads = [p for p in payloads if isinstance(p, dict)]
|
||||
assert dict_payloads, "应进入 AWSRTM multi_value 填充路径"
|
||||
assert any(
|
||||
payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl29_divDropDown"
|
||||
for payload in payloads
|
||||
for payload in dict_payloads
|
||||
), f"应命中 ctl29 multi_value dropdown,实际 payloads={payloads!r}"
|
||||
|
||||
|
||||
@@ -471,14 +495,20 @@ class _RecordingPage:
|
||||
|
||||
|
||||
_STRUCTURAL_CONTROLS = {
|
||||
"control": "multi_value",
|
||||
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
|
||||
}
|
||||
|
||||
_STRUCTURAL_SELECT = {
|
||||
"control": "select",
|
||||
"selector": "#ReportViewerMain_ctl08_ctl19_ddValue",
|
||||
}
|
||||
|
||||
|
||||
def test_structural_resolver_hit_returns_controls_and_trims_label():
|
||||
"""命中 frame 返回三件套;label 先 trim 再传入页面脚本。"""
|
||||
"""命中 frame 返回 multi_value 三件套(含 control);label 先 trim 再传入页面脚本。"""
|
||||
module = _load_module()
|
||||
early = _RecordingFrame(result=None)
|
||||
hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
@@ -490,6 +520,22 @@ def test_structural_resolver_hit_returns_controls_and_trims_label():
|
||||
assert hit.calls == ["Owner"]
|
||||
|
||||
|
||||
def test_structural_resolver_select_via_label_for_returns_ddvalue():
|
||||
"""Cincinnati CVG611 形态:label[for]=ctl19_ddValue 时返回 select,禁止再当 multi_value。
|
||||
|
||||
[断言意图] 2026-10-20 事故回归——Warehouse 是原生 select,不得落到 ctl17_txtValue
|
||||
(已漂移为 Project ID)文本兜底。
|
||||
"""
|
||||
module = _load_module()
|
||||
hit = _RecordingFrame(result=dict(_STRUCTURAL_SELECT))
|
||||
page = _RecordingPage([hit])
|
||||
|
||||
got = module.resolve_parameter_controls_structural(page, "Warehouse")
|
||||
|
||||
assert got == _STRUCTURAL_SELECT
|
||||
assert hit.calls == ["Warehouse"]
|
||||
|
||||
|
||||
def test_structural_resolver_all_frames_miss_or_error_returns_none():
|
||||
"""全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。"""
|
||||
module = _load_module()
|
||||
@@ -596,6 +642,98 @@ def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch
|
||||
assert probed.calls == ["Warehouse"]
|
||||
|
||||
|
||||
def test_fill_warehouse_uses_structural_select_not_stale_txtvalue(monkeypatch, capsys):
|
||||
"""Warehouse 结构性命中 select 时走 ddValue,禁止 JDA 模板 ctl17_txtValue 文本兜底。
|
||||
|
||||
[断言意图] 复现 2026-10-20 Cincinnati:模板仍写 multi_value@ctl17,但页面 Warehouse
|
||||
是 ctl19_ddValue;不得把 BYAWSCV611 写进漂移后的 Project ID。
|
||||
"""
|
||||
module = _load_module()
|
||||
page = _RecordingPage([_RecordingFrame(result=dict(_STRUCTURAL_SELECT))])
|
||||
selected: dict[str, str] = {}
|
||||
|
||||
class _FakeText:
|
||||
first = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, timeout: int | None = None) -> bool:
|
||||
return False
|
||||
|
||||
page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined]
|
||||
|
||||
def _fake_select(page_obj, label, value, selector, *, timeout_ms):
|
||||
selected["selector"] = selector
|
||||
selected["value"] = value
|
||||
return True
|
||||
|
||||
def _fake_multi(*_a, **_k):
|
||||
raise AssertionError("select 形态不得走 multi_value")
|
||||
|
||||
monkeypatch.setattr(module, "_fill_select_parameter", _fake_select)
|
||||
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_multi)
|
||||
|
||||
ok = module.fill_dsv_filter_if_needed(
|
||||
page,
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"BYAWSCV611",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="On Hand Inventory By Location",
|
||||
program_label="CVG611",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
assert selected == {
|
||||
"selector": "#ReportViewerMain_ctl08_ctl19_ddValue",
|
||||
"value": "BYAWSCV611",
|
||||
}
|
||||
captured = capsys.readouterr()
|
||||
assert "ctl17_txtValue" not in captured.out + captured.err
|
||||
|
||||
|
||||
def test_fill_warehouse_refuses_stale_txtvalue_when_structural_miss(monkeypatch, capsys):
|
||||
"""结构性未命中且模板 multi_value 失败时:Warehouse 拒绝 txtValue 文本兜底并返回 False。"""
|
||||
module = _load_module()
|
||||
page = _RecordingPage([_RecordingFrame(result=None)])
|
||||
|
||||
class _FakeText:
|
||||
first = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, timeout: int | None = None) -> bool:
|
||||
return False
|
||||
|
||||
page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined]
|
||||
monkeypatch.setattr(module, "_fill_multi_value_parameter", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_probe_report_parameter_controls", lambda *_a, **_k: {"controls": []})
|
||||
filled_via_script: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_fill_input_via_script",
|
||||
lambda root, selector, text: filled_via_script.append(selector) or True,
|
||||
)
|
||||
|
||||
ok = module.fill_dsv_filter_if_needed(
|
||||
page,
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"BYAWSCV611",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="On Hand Inventory By Location",
|
||||
)
|
||||
|
||||
assert ok is False
|
||||
assert filled_via_script == []
|
||||
captured = capsys.readouterr()
|
||||
assert "refusing stale txtValue fallback" in captured.err
|
||||
|
||||
|
||||
def test_multi_value_already_set_set_equality_not_substring():
|
||||
"""2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV,
|
||||
目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。"""
|
||||
|
||||
@@ -76,6 +76,87 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
assert refreshed.response_summary_json['progress']['success_count'] == 1
|
||||
|
||||
|
||||
def test_inbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises(
|
||||
app, monkeypatch,
|
||||
):
|
||||
"""文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。
|
||||
|
||||
[断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_inbound_report 成功。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.rpa_sinks import _inbound_batch_ready_sink
|
||||
|
||||
with app.app_context():
|
||||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-INBOUND-FILE-FINAL',
|
||||
name='Inbound file finalize',
|
||||
schedule_type='platform_job',
|
||||
platform_api_path='freight-rpa-inbound',
|
||||
owner_user_id=1,
|
||||
cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-INBOUND-FILE-FINAL',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
total_count=1,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
response_summary_json={'awaiting_inbound_rpa': True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=run.id,
|
||||
source_id=source.id,
|
||||
source_code=source.source_code,
|
||||
connector_type='dbs',
|
||||
warehouse_id='AWSDU',
|
||||
callback_id='inbound-file-final-cb',
|
||||
status='awaiting_rpa',
|
||||
config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file',
|
||||
lambda _path: b'receipt-bytes',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
def _boom(_fact):
|
||||
raise RuntimeError('evidence sync exploded')
|
||||
|
||||
register_report_handler('inbound', _boom)
|
||||
payload = {
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'success',
|
||||
'file_path': 'Z:/receipt.xlsx',
|
||||
'original_filename': 'receipt.xlsx',
|
||||
'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(),
|
||||
}
|
||||
|
||||
with pytest.raises(RuntimeError, match='evidence sync exploded'):
|
||||
_inbound_batch_ready_sink(**payload)
|
||||
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(ScheduleRun, run.id)
|
||||
assert refreshed.status == 'success'
|
||||
assert (refreshed.response_summary_json or {}).get('awaiting_inbound_rpa') is False
|
||||
assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'success'
|
||||
|
||||
|
||||
def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
"""success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。"""
|
||||
from app import db
|
||||
|
||||
@@ -214,3 +214,20 @@ def test_receipt_worker_defaults_session_reuse_with_scoped_profiles():
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8')
|
||||
assert '[switch]$NoSessionReuse' in ps1
|
||||
assert "FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse" in ps1
|
||||
|
||||
|
||||
def test_receipt_worker_reports_remaining_units_on_batch_open_failure():
|
||||
"""批级浏览器打开失败须给剩余单元补 failed 回调,禁止只归档 trigger。
|
||||
|
||||
[断言意图] 2026-10-20 事故:launch_persistent_context TargetClosed 后 trigger 进
|
||||
failed/ 但单元无终态回调 → awaiting_rpa/抓取中永挂。契约要求
|
||||
`_report_group_open_failure` + `reported_callback_ids` 剩余补发。
|
||||
"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'def _report_group_open_failure(' in text
|
||||
assert 'reported_callback_ids' in text
|
||||
assert '_report_group_open_failure(remaining, exc)' in text
|
||||
assert 'open/group failed' in text
|
||||
@@ -101,6 +101,80 @@ def _awaiting_outbound_unit(*, callback_id: str):
|
||||
)
|
||||
|
||||
|
||||
def test_outbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises(
|
||||
tmp_path, app, monkeypatch,
|
||||
):
|
||||
"""文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。
|
||||
|
||||
[断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_outbound_report 成功。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaOutboundUnitRun
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.rpa_sinks import _outbound_batch_ready_sink
|
||||
|
||||
drop = tmp_path / "outbound_drop"
|
||||
drop.mkdir()
|
||||
payload_bytes = b"PK\x03\x04fake"
|
||||
(drop / "foo.xlsx").write_bytes(payload_bytes)
|
||||
|
||||
with app.app_context():
|
||||
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-OUTBOUND-FILE-FINAL",
|
||||
name="Outbound file finalize",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="freight-rpa-outbound",
|
||||
owner_user_id=1,
|
||||
cron_expr="0 8 * * *",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(
|
||||
run_no="RUN-OUTBOUND-FILE-FINAL",
|
||||
schedule_task_id=task.id,
|
||||
status="running",
|
||||
total_count=1,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
response_summary_json={"awaiting_outbound_rpa": True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = _awaiting_outbound_unit(callback_id="outbound-file-final-cb")
|
||||
unit.schedule_run_id = run.id
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.freight_rpa.outbound.report_archive.file_asset_storage.upload_bytes",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
def _boom(_fact):
|
||||
raise RuntimeError("evidence sync exploded")
|
||||
|
||||
register_report_handler("outbound", _boom)
|
||||
payload = {
|
||||
"schema_version": "freight_rpa.outbound.v1",
|
||||
"callback_id": unit.callback_id,
|
||||
"status": "success",
|
||||
"file_path": r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx",
|
||||
"original_filename": "foo.xlsx",
|
||||
"sha256": hashlib.sha256(payload_bytes).hexdigest(),
|
||||
}
|
||||
|
||||
with pytest.raises(RuntimeError, match="evidence sync exploded"):
|
||||
_outbound_batch_ready_sink(**payload)
|
||||
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(ScheduleRun, run.id)
|
||||
assert refreshed.status == "success"
|
||||
assert (refreshed.response_summary_json or {}).get("awaiting_outbound_rpa") is False
|
||||
assert db.session.get(FreightRpaOutboundUnitRun, unit.id).status == "success"
|
||||
|
||||
|
||||
def test_ingest_outbound_callback_archives_and_dispatches_fact(tmp_path, app, monkeypatch):
|
||||
"""success 回调按 Windows 绝对路径只认文件名归档,并投递 report_kind=outbound 事实。"""
|
||||
from app import db
|
||||
|
||||
@@ -146,3 +146,16 @@ def test_outbound_worker_ready_callback_outside_export_retry():
|
||||
progress_at = text.find("progress_counts['success'] += 1")
|
||||
ready_at = text.find("_post_unit_ready(unit, output)")
|
||||
assert progress_at > 0 and ready_at > progress_at
|
||||
|
||||
|
||||
def test_outbound_worker_reports_remaining_units_on_batch_open_failure():
|
||||
"""批级浏览器打开失败须给剩余单元补 failed 回调——与 inbound/onhand 同契约。
|
||||
|
||||
[断言意图] 禁止只归档 trigger 到 failed/ 而不收口单元;须有
|
||||
`_report_group_open_failure` + `reported_callback_ids` 剩余补发。
|
||||
"""
|
||||
text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "def _report_group_open_failure(" in text
|
||||
assert "reported_callback_ids" in text
|
||||
assert "_report_group_open_failure(remaining, exc)" in text
|
||||
assert "open/group failed" in text
|
||||
@@ -187,6 +187,83 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
}
|
||||
|
||||
|
||||
def test_batch_open_browser_failure_records_remaining_sources_as_profile_failed(monkeypatch, tmp_path):
|
||||
"""批级 launch_persistent_context 失败须为组内全部源记 rpa_profile_failed 并批末回调。
|
||||
|
||||
[断言意图] 与 inbound/outbound「剩余单元补 failed」同契约:浏览器未开时不得
|
||||
静默丢源;须进 results + ONHAND_BATCH_READY,error_code=rpa_profile_failed。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
trigger_path = trigger_dir / "inventory_export_batch_open_fail.json"
|
||||
sources = [
|
||||
{
|
||||
"source_code": code,
|
||||
"connector_type": "dbs",
|
||||
"warehouse_id": wh,
|
||||
"expected_warehouse_id": wh,
|
||||
"rpa_profile_code": "DBS_AR",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"task_no": "SN-OPEN-FAIL",
|
||||
"callback_id": f"PSR-OPEN-FAIL-{wh}:C1",
|
||||
"source_run_no": f"PSR-OPEN-FAIL-{wh}",
|
||||
"attempt_no": 1,
|
||||
"lease_token": f"lease-{wh}",
|
||||
"candidate_set_id": 12,
|
||||
"execution_id": 88,
|
||||
"gate_id": 901,
|
||||
}
|
||||
for code, wh in (("DSV360_AWSDU", "AWSDU"), ("DSV360_AWSRTM", "AWSRTM"))
|
||||
]
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-OPEN-FAIL:batch:C1",
|
||||
"batch_run_no": "BATCH-OPEN-FAIL",
|
||||
"task_no": "SN-OPEN-FAIL",
|
||||
"inventory_sources": sources,
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
def _boom(*_args, **_kwargs):
|
||||
raise RuntimeError("BrowserType.launch_persistent_context: Target page, context or browser has been closed")
|
||||
|
||||
monkeypatch.setattr(worker, "_open_browser", _boom)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_close_batch_browser_resources", lambda *_a, **_k: None)
|
||||
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
assert completed["failed_count"] == 2
|
||||
assert completed["success_count"] == 0
|
||||
assert len(completed["results"]) == 2
|
||||
assert {row["source_code"] for row in completed["results"]} == {"DSV360_AWSDU", "DSV360_AWSRTM"}
|
||||
assert all(row["error_code"] == "rpa_profile_failed" for row in completed["results"])
|
||||
assert all(row["status"] == "failed" for row in completed["results"])
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_onhand_batch_profile_failure_skips_already_recorded_sources_contract():
|
||||
"""组级补 failed 必须按 recorded_keys 跳过已入 results 的源(禁止二次追加)。
|
||||
|
||||
[断言意图] onhand 与 inbound/outbound 同契约:批级失败只收口「剩余」源;
|
||||
源码须含 recorded_keys / remaining / rpa_profile_failed 门禁。
|
||||
"""
|
||||
text = (
|
||||
_repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
).read_text(encoding="utf-8")
|
||||
assert "recorded_keys" in text
|
||||
assert "remaining" in text
|
||||
assert "rpa_profile_failed" in text
|
||||
assert "open/group failed" in text
|
||||
assert "尚未写入 results" in text or "not in recorded_keys" in text
|
||||
|
||||
|
||||
def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_path):
|
||||
"""Crane 动态 Warehouse 在导出前未知时,v2 trigger 不应被身份校验拒绝。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
backend/tests/test_schedule_run_list_filter.py
|
||||
|
||||
用途:断言排程执行记录日期窗包含尚未开始的排队 run。
|
||||
依赖:query_service.list_runs、ScheduleTask / ScheduleRun、User。
|
||||
逻辑:工作台默认按今天过滤;started_at 为空时必须以 created_at 落入同一窗口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
def test_list_runs_includes_queued_run_without_started_at(app):
|
||||
"""排队 run 的 started_at 为空时,仍按 created_at 出现在当天窗口。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.query_service import list_runs
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='sched-filter', email='sched-filter@example.com', role='admin')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-FILTER-QUEUED',
|
||||
name='filter queued',
|
||||
owner_user_id=owner.id,
|
||||
cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
now = datetime.utcnow()
|
||||
queued = ScheduleRun(
|
||||
run_no='RUN-FILTER-QUEUED',
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='manual',
|
||||
status='queued',
|
||||
started_at=None,
|
||||
created_at=now,
|
||||
)
|
||||
stale = ScheduleRun(
|
||||
run_no='RUN-FILTER-STALE',
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='manual',
|
||||
status='success',
|
||||
started_at=now - timedelta(days=2),
|
||||
created_at=now - timedelta(days=2),
|
||||
)
|
||||
db.session.add_all([queued, stale])
|
||||
db.session.commit()
|
||||
|
||||
rows = list_runs(
|
||||
task_id=task.id,
|
||||
started_after=now - timedelta(hours=1),
|
||||
started_before=now + timedelta(hours=1),
|
||||
)
|
||||
|
||||
# 断言:当天窗口只含排队中的本轮,不含两天前已开始的记录。
|
||||
assert [row['run_no'] for row in rows] == ['RUN-FILTER-QUEUED']
|
||||
@@ -1051,6 +1051,23 @@ def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_unique_hit_odm_bypasses_customer_range(app, tmp_path):
|
||||
"""唯一命中 ODM 免白名单:Excel 里只有一个 ODM 时直接取用,不拦客户口径漂移。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
task, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, odm_values=['ODM-1'], customer_odm_ids=['ODM-9'],
|
||||
)
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(task)
|
||||
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_export_applies_notice_odm_choice(app, tmp_path):
|
||||
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_shipping_notice_inventory_schedule.py
|
||||
|
||||
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
|
||||
依赖:ScheduleTask/ScheduleRun、freight_rpa_onhand_job、freight_rpa_onhand_finalize。
|
||||
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
|
||||
逻辑:覆盖 trigger 写入、awaiting、HTTP 文件返回即终态、解析 Job 后置入库、超时回收。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
@@ -30,13 +30,15 @@ from tests.conftest import v2_inventory_batch_payload
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _freeze_schedule_batch_callback_contract(monkeypatch):
|
||||
def _freeze_schedule_batch_callback_contract(request, monkeypatch):
|
||||
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。
|
||||
|
||||
排程终态化逻辑已从 HTTP 快速收件(rpa_report_inventory_batch,只入队异步 job)
|
||||
解耦到同步 process_rpa_report_inventory_batch(由异步 worker job 调用);单测保持
|
||||
同步断言,因此把旧入口重新指向同步处理函数。
|
||||
多数旧测把 HTTP 入口同步指到 process 以便断言终态;标注
|
||||
``real_http_batch_ready`` 的用例要验真实 HTTP「文件返回即终态」,跳过该包装。
|
||||
"""
|
||||
if request.node.get_closest_marker("real_http_batch_ready"):
|
||||
return
|
||||
|
||||
from app.services.shipping_notice import onhand_rpa_workflow
|
||||
import sys
|
||||
|
||||
@@ -1013,3 +1015,147 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon
|
||||
rpa_run_no=run.run_no,
|
||||
snapshot_status="ready",
|
||||
).count() == 1
|
||||
|
||||
|
||||
@pytest.mark.real_http_batch_ready
|
||||
def test_http_batch_ready_finalizes_schedule_on_rpa_file_return(app, tmp_path, monkeypatch):
|
||||
"""排程点执行:HTTP batch-ready 在文件成功返回时即终态化,不等解析 Job。
|
||||
|
||||
[断言意图] RPA 解耦阶段 B 契约——文件返回= RPA/排程结束;解析成败另算。
|
||||
本测绕过 autouse 同步 process 包装,直接打真实 HTTP 收件入口。
|
||||
"""
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory_batch as http_batch_ready
|
||||
from tests.conftest import v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "rpa_file_return.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
enqueued: list[dict] = []
|
||||
|
||||
def _fake_enqueue(job_type, payload, **kwargs):
|
||||
enqueued.append({"job_type": job_type, "payload": payload, **kwargs})
|
||||
return 99001
|
||||
|
||||
monkeypatch.setattr("app.jobs.queue.enqueue", _fake_enqueue)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
schedule_no="SCH-INV-HTTP-FINALIZE",
|
||||
username="schedule_inv_http_finalize_user",
|
||||
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
|
||||
)
|
||||
run = ScheduleRun(
|
||||
run_no="RUN20261020110500",
|
||||
schedule_task_id=task.id,
|
||||
status="running",
|
||||
started_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
response_summary_json={
|
||||
"awaiting_rpa": True,
|
||||
"pending_details": [{
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
"display_name": "CVG611",
|
||||
}],
|
||||
},
|
||||
step_logs=[{"step": "freight_rpa_onhand", "status": "awaiting_rpa_callback"}],
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
before_files = FreightRpaOnhandReportFile.query.count()
|
||||
result = http_batch_ready(v2_inventory_batch_payload({
|
||||
"run_no": run.run_no,
|
||||
"schedule_run_id": run.id,
|
||||
"trigger_type": "scheduled",
|
||||
"status": "success",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
"DSV360_AWSDU",
|
||||
success=True,
|
||||
file_path=str(sample),
|
||||
warehouse_id="AWSDU",
|
||||
)],
|
||||
}))
|
||||
|
||||
db.session.refresh(run)
|
||||
assert result["status"] == "ok"
|
||||
assert result["data"]["callback_result_status"] == "accepted"
|
||||
assert result["data"]["job_id"] == 99001
|
||||
assert result["data"]["schedule_finalize_status"] == "ok"
|
||||
assert run.status == "success"
|
||||
assert run.finished_at is not None
|
||||
assert run.success_count == 1
|
||||
assert run.failed_count == 0
|
||||
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
|
||||
# 解析尚未跑:不得要求已有 onhand 快照行
|
||||
assert FreightRpaOnhandReportFile.query.count() == before_files
|
||||
assert len(enqueued) == 1
|
||||
|
||||
|
||||
def test_process_after_rpa_finalize_still_ingests_without_reopening_awaiting(app, tmp_path, monkeypatch):
|
||||
"""排程已按 RPA 文件返回终态后,解析 Job 仍可入库,且不得把 awaiting_rpa 重新打开。"""
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "parse_after_finalize.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
schedule_no="SCH-INV-PARSE-AFTER",
|
||||
username="schedule_inv_parse_after_user",
|
||||
api_body_template='{"source_codes": ["DSV360_AWSDU"]}',
|
||||
)
|
||||
run = ScheduleRun(
|
||||
run_no="RUN20261020110501",
|
||||
schedule_task_id=task.id,
|
||||
status="success",
|
||||
started_at=datetime.utcnow(),
|
||||
finished_at=datetime.utcnow(),
|
||||
total_count=1,
|
||||
success_count=1,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
response_summary_json={
|
||||
"awaiting_rpa": False,
|
||||
"schedule_finalize_status": "ok",
|
||||
"pending_details": [{
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"warehouse_id": "AWSDU",
|
||||
"display_name": "CVG611",
|
||||
}],
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
finished_at = run.finished_at
|
||||
|
||||
before = FreightRpaOnhandReportFile.query.filter_by(snapshot_status="ready").count()
|
||||
result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
"run_no": run.run_no,
|
||||
"schedule_run_id": run.id,
|
||||
"trigger_type": "scheduled",
|
||||
"results": [scheduled_rpa_batch_item(
|
||||
"DSV360_AWSDU",
|
||||
success=True,
|
||||
file_path=str(sample),
|
||||
warehouse_id="AWSDU",
|
||||
)],
|
||||
}))
|
||||
|
||||
db.session.refresh(run)
|
||||
assert result["status"] == "ok"
|
||||
assert FreightRpaOnhandReportFile.query.filter_by(snapshot_status="ready").count() == before + 1
|
||||
assert run.status == "success"
|
||||
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
|
||||
assert run.finished_at == finished_at
|
||||
@@ -1136,6 +1136,63 @@ def test_auto_release_runs_after_match_when_part_total_satisfies(app, monkeypatc
|
||||
assert decision.snapshot_json['release_required_fields'] == []
|
||||
|
||||
|
||||
def test_auto_release_skips_when_hit_odm_multi_valued(app, monkeypatch):
|
||||
"""命中行 ODM 多值时不得自动放行:放行后导出无法唯一收敛,保持人工路径。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 同料号两行库存携带不同 ODM 值 → 命中行 ODM 非唯一。
|
||||
task, case, _odm_field = _seed_auto_release_fixture(app, inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV', 'odm': 'ODM-A'},
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV', 'odm': 'ODM-B'},
|
||||
])
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:料号总量满足也不放行(多值 ODM 放行后 Excel 必失败)。
|
||||
assert released == []
|
||||
assert _active_auto_release_decisions(case) == []
|
||||
|
||||
|
||||
def test_release_and_sufficiency_readers_resolve_via_notice_identity(app):
|
||||
"""放行/满足性读取按 OT 回链:Notice 对象复评必须与 OT 同判(键位断裂回归)。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderReviewLineDecision
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_closed_snapshot_line_ids_for_task,
|
||||
_released_snapshot_line_ids_for_task,
|
||||
match_completed,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task, case, _odm_field = _seed_auto_release_fixture(app)
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id), draft_line_id='line-1', line_index=0,
|
||||
decision_code=DECISION_RELEASE_SHORTAGE, decision_source='system',
|
||||
required_qty='8.0', available_qty='6.0', reservation_id='3000112934',
|
||||
part_number='ODM-001', snapshot_json={'auto_release': True},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-KEYSPLIT', source_type='manual',
|
||||
order_task_id=int(task.id), user_id=int(task.user_id),
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
|
||||
# 断言意图:以 Notice 身份读取放行/满足性事实与 OT 完全同判,
|
||||
# Excel 生成链换绑 Notice 后不再丢放行事实(回归 OT-20261017-364C7BF2)。
|
||||
assert _released_snapshot_line_ids_for_task(notice) == _released_snapshot_line_ids_for_task(task)
|
||||
assert _released_snapshot_line_ids_for_task(notice)
|
||||
assert _closed_snapshot_line_ids_for_task(notice) == set()
|
||||
assert match_completed(task) is True
|
||||
assert match_completed(notice) is True
|
||||
|
||||
|
||||
def test_auto_release_skips_when_part_total_below_required(app, monkeypatch):
|
||||
"""料号兜底量不足时不得自动放行,行保持人工待处置。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
|
||||
Reference in new issue
Block a user