feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动

外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-22 00:48:37 +08:00
1 parent 911afa0f73
commit 4c2a7e2a23
145 files changed
+11695 -4214

No files matched your search

@@ -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