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"},
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user