feat(in-transit-transfer): inbound/outbound 幂等重命名与解析用途分层
- receipt→inbound 三件套改名(回调桥/文件门禁/触发服务),回调链幂等去重,迁移 tt14 同步台账键与测试基建 - 库存解析用途分层 onhand/inbound/outbound(迁移 tt15):解析档案、文件存储与下载名按用途隔离,管理端表单同步 - 「成熟」概念退役(迁移 tt16):数据无成熟属性,日期边界由调用方入参严格判定 - backlog 新增重解析服务,在途重识别投影 processing,EML 父项不再停留处理中 - 收料 RPA 回调/归档/排程链路同步改名挂点,运维脚本复位假完成状态 - 文档随批:ADR 0003 模块边界决策、10-15/10-16 计划与设计、调拨文档族与 demand/tec/funclist - 同步 chat/errors 文案四语言、调拨前端卡片与 e2e、测试全家
This commit is contained in:
1 parent
43dceaf027
commit
8102a1fe44
151 files changed
+8057
-2382
No files matched your search
@@ -1,8 +1,8 @@
|
||||
"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。
|
||||
"""在途调拨测试固定夹具:时钟、入站文件样例、外部替身与数据库隔离。
|
||||
|
||||
用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入
|
||||
(fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、
|
||||
same_day_receipt_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
|
||||
same_day_inbound_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
|
||||
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
|
||||
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
|
||||
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
|
||||
@@ -34,22 +34,6 @@ def _stub_doc_sequence(monkeypatch):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _pin_maturity_lag_legacy(request):
|
||||
"""在途套件钉成熟滞后=1(T+1)。
|
||||
|
||||
用途:存量夹具生态按 T+1 语义构建(fixed_clock 业务日 2026-08-06、收料日期
|
||||
2026-08-05=T-1);生产默认 T+2(settings IN_TRANSIT_TRANSFER_MATURITY_
|
||||
LAG_DAYS=2)的边界行为由 test_matching_service / test_date_policy 专项
|
||||
用例显式覆盖,不被本钉值掩盖。
|
||||
逻辑:仅对已请求 app 的用例钉值(request.fixturenames 判定),pure_unit 用例
|
||||
(如 test_date_policy)不触碰 Flask,继续走 date_policy 的无上下文回退。
|
||||
"""
|
||||
if "app" in getattr(request, "fixturenames", []):
|
||||
app = request.getfixturevalue("app")
|
||||
app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_default_transfer_type(request):
|
||||
"""默认启用类型配置种子(autouse,出生翻转后匹配创建必填且配置驱动)。
|
||||
|
||||
@@ -1,67 +1,16 @@
|
||||
"""在途调拨领域测试的对象工厂。
|
||||
|
||||
用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。
|
||||
依赖:标准库(dataclasses / decimal)。
|
||||
用途:集中构造调拨类型配置种子与「清空并重新解析」(spec §6)用例种子
|
||||
(来源+入站解析规则+归档文件+档行),避免各测试重复内联样板。
|
||||
依赖:标准库(datetime)、openpyxl(内存 xlsx 构造)。
|
||||
逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。
|
||||
归档文件字节不落真存储:用例经 FakeArchiveStorage 注入并 monkeypatch
|
||||
file_asset_storage.get_bytes。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReceiptRow:
|
||||
"""单行收料文件记录(含 Sheet/行号追溯证据)。"""
|
||||
|
||||
sheet: str = "Receipt"
|
||||
row_no: int = 1
|
||||
invoice_no: str = "HOM-001"
|
||||
material_no: str = "MAT-001"
|
||||
material_name: str = "连接器组件"
|
||||
specification: str = "A 型 / 24PIN"
|
||||
receipt_date: str = "2026-08-05"
|
||||
receipt_quantity: str = "1200"
|
||||
source_code: str = "DBS-AWSBI"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""转 dict,供 parser/aggregator 输入。"""
|
||||
return {
|
||||
"sheet": self.sheet,
|
||||
"row_no": self.row_no,
|
||||
"invoice_no": self.invoice_no,
|
||||
"material_no": self.material_no,
|
||||
"material_name": self.material_name,
|
||||
"specification": self.specification,
|
||||
"receipt_date": self.receipt_date,
|
||||
"receipt_quantity": self.receipt_quantity,
|
||||
"source_code": self.source_code,
|
||||
}
|
||||
|
||||
|
||||
def make_invoice_item(
|
||||
*,
|
||||
invoice_no: str = "HOM-001",
|
||||
source_code: str = "DBS-AWSBI",
|
||||
material_no: str = "MAT-001",
|
||||
receipt_quantity: Decimal | str | int = "1200",
|
||||
external_quantity: Decimal | str | int | None = "1200",
|
||||
receipt_date: str = "2026-08-05",
|
||||
) -> dict[str, Any]:
|
||||
"""构造一条预检明细项(默认严格匹配、可执行)。"""
|
||||
return {
|
||||
"invoice_no": invoice_no,
|
||||
"source_code": source_code,
|
||||
"material_no": material_no,
|
||||
"material_name": "连接器组件",
|
||||
"specification": "A 型 / 24PIN",
|
||||
"receipt_date": receipt_date,
|
||||
"receipt_quantity": Decimal(str(receipt_quantity)),
|
||||
"external_quantity": None if external_quantity is None else Decimal(str(external_quantity)),
|
||||
}
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 调拨类型配置种子(出生翻转后匹配创建必填且配置驱动,Task 11)
|
||||
@@ -114,3 +63,215 @@ def seed_transfer_type_config(
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return row
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 清空并重新解析(spec §6,Task 7)用例种子
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# 入站解析规则缺省 field_mapping(movement 定死领域字段 → 表头别名,CRANE 风格)。
|
||||
INBOUND_MOVEMENT_FIELD_MAPPING = {
|
||||
"doc_no": "单据编号",
|
||||
"line_no": "项次",
|
||||
"in_out_flag": "进出库别",
|
||||
"material_code": "料号",
|
||||
"material_name": "品名",
|
||||
"lot_no": "批号",
|
||||
"quantity": "数量",
|
||||
"movement_date": "异动日期",
|
||||
}
|
||||
|
||||
# 与 INBOUND_MOVEMENT_FIELD_MAPPING 对齐的 xlsx 表头行(build_movement_xlsx 缺省表头)。
|
||||
INBOUND_MOVEMENT_HEADERS = ["单据编号", "项次", "进出库别", "料号", "品名", "批号", "数量", "异动日期"]
|
||||
|
||||
|
||||
def build_movement_xlsx(data_rows: list[list], *, sheet_name: str = "Receipt",
|
||||
headers: list[str] | None = None) -> bytes:
|
||||
"""构造内存 xlsx 字节(表头 + 数据行),供归档假存储注入。
|
||||
|
||||
Args:
|
||||
data_rows: 数据行(列序与 headers 一致;数量 int、日期 str)。
|
||||
sheet_name: 工作表标题(溯源 sheet 字段来源)。
|
||||
headers: 表头行;缺省 INBOUND_MOVEMENT_HEADERS。
|
||||
Returns:
|
||||
xlsx 原始字节。
|
||||
"""
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = sheet_name
|
||||
ws.append(list(headers if headers is not None else INBOUND_MOVEMENT_HEADERS))
|
||||
for row in data_rows:
|
||||
ws.append(list(row))
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class FakeArchiveStorage:
|
||||
"""file_asset_storage 内存假件(storage_key → bytes),按 repo_fakes 风格最小实现。"""
|
||||
|
||||
def __init__(self, objects: dict[str, bytes] | None = None) -> None:
|
||||
self.objects: dict[str, bytes] = dict(objects or {})
|
||||
|
||||
def get_bytes(self, storage_key: str) -> bytes:
|
||||
"""读取注入对象;缺失键抛 KeyError(用例内即失败,不静默)。"""
|
||||
return self.objects[storage_key]
|
||||
|
||||
|
||||
def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = None,
|
||||
version: int = 1, field_mapping: dict | None = None,
|
||||
sheet_name: str = "Receipt", header_row_index: int = 1,
|
||||
status: str = "published"):
|
||||
"""建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。
|
||||
|
||||
用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身
|
||||
parsing_profile(在手口径)按约束置最小占位行,真实重建规则挂
|
||||
ShippingReceiptReportConfig.parsing_profile_id(与运行期口径一致)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
profile_code: 入站解析规则 code(缺省 MV_<source_code>)。
|
||||
version: 入站解析规则版本。
|
||||
field_mapping: 领域字段→表头别名;缺省 INBOUND_MOVEMENT_FIELD_MAPPING。
|
||||
sheet_name / header_row_index: definition_json 结构参数。
|
||||
status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。
|
||||
Returns:
|
||||
(ShippingInventorySource, ShippingInventoryParsingProfile) 元组。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingRpaProfile,
|
||||
ShippingReceiptReportConfig,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
|
||||
if source is not None:
|
||||
config = source.receipt_report_config
|
||||
return source, (config.parsing_profile if config else None)
|
||||
|
||||
resolved_code = profile_code or f"MV_{source_code}"
|
||||
onhand = ShippingInventoryParsingProfile(
|
||||
purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code,
|
||||
version=1, status="published", file_format="xlsx",
|
||||
definition_json={}, structure_definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose="inbound", profile_code=resolved_code, display_name=resolved_code,
|
||||
version=version, status=status, file_format="xlsx",
|
||||
definition_json={
|
||||
"sheet_name": sheet_name, "header_row_index": header_row_index,
|
||||
"field_mapping": dict(
|
||||
INBOUND_MOVEMENT_FIELD_MAPPING if field_mapping is None else field_mapping),
|
||||
},
|
||||
structure_definition_json={},
|
||||
)
|
||||
rpa = ShippingRpaProfile(
|
||||
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs",
|
||||
login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"},
|
||||
)
|
||||
template = ShippingExcelTemplate(
|
||||
template_code=f"TPL_{source_code}", display_name=source_code, version=1,
|
||||
status="published", storage_provider="minio", storage_bucket="test",
|
||||
storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx",
|
||||
file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64,
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source_code=source_code, display_name=source_code, connector_type="dbs",
|
||||
rpa_profile=rpa, parsing_profile=onhand, excel_template=template,
|
||||
warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True,
|
||||
)
|
||||
db.session.add_all([onhand, profile, rpa, template, source])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, parsing_profile_id=profile.id))
|
||||
db.session.commit()
|
||||
return source, profile
|
||||
|
||||
|
||||
def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at: datetime,
|
||||
archive_expires_at: datetime | None = None,
|
||||
archive_deleted_at: datetime | None = None,
|
||||
callback_id: str | None = None):
|
||||
"""建一条收料执行单元 + 原样归档文件行(清空重建用例种子)。
|
||||
|
||||
字节不落真存储:用例把 build_movement_xlsx 产物注入 FakeArchiveStorage
|
||||
(键=storage_key)并 monkeypatch file_asset_storage.get_bytes。
|
||||
|
||||
Args:
|
||||
source: seed_inbound_reparse_source 返回的来源行。
|
||||
sha: 归档文件 sha256(唯一约束 unit_run+sha,用例间取不同值)。
|
||||
storage_key: 对象存储键(与假存储注入键一致)。
|
||||
created_at: 归档时间(= repository 的 archived_at,排序依据)。
|
||||
archive_expires_at: 保留期截止;None=长期有效。
|
||||
archive_deleted_at: 清理时间;None=未清理。
|
||||
callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。
|
||||
Returns:
|
||||
已入库的 ShippingReceiptReportFile。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type,
|
||||
callback_id=callback_id or f"cb-{sha[:12]}",
|
||||
status="success", config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
report = ShippingReceiptReportFile(
|
||||
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
|
||||
storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx",
|
||||
file_size=16, sha256=sha, created_at=created_at,
|
||||
archive_expires_at=archive_expires_at, archive_deleted_at=archive_deleted_at,
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
return report
|
||||
|
||||
|
||||
def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1",
|
||||
in_out_flag: str = "I", lot_no: str = "LOT-1",
|
||||
source_file_id: int | None = None,
|
||||
sha: str = "9" * 64, quantity: str = "1",
|
||||
material_code: str = "MAT-OLD", material_name: str = "旧映射名称",
|
||||
movement_date: str = "2026-08-05",
|
||||
transfer_executed: bool = False,
|
||||
executed_doc_no: str | None = None,
|
||||
updated_at: datetime | None = None):
|
||||
"""插一条旧映射库存异动档行(清空重建用例种子;业务值=旧映射形态)。
|
||||
|
||||
Args:
|
||||
source_code / doc_no: 来源与单号(自然键主干)。
|
||||
line_no / in_out_flag / lot_no: 自然键可变成分(与解析行对齐便于断言覆写)。
|
||||
source_file_id: 溯源归档文件 id;None=证据缺失行形态。
|
||||
sha: 档行 file_sha256(缺省 9*64 表示旧文件指纹)。
|
||||
quantity / material_code / material_name / movement_date: 旧业务值。
|
||||
transfer_executed / executed_doc_no: 封存形态注入。
|
||||
updated_at: 显式更新时间(封存不动行断言用)。
|
||||
Returns:
|
||||
已入库的 TransferMovementLedger。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
row = TransferMovementLedger(
|
||||
source_code=source_code, record_kind="inbound",
|
||||
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,
|
||||
quantity=quantity, movement_date=movement_date,
|
||||
source_file_id=source_file_id, file_version=None, file_sha256=sha,
|
||||
transfer_executed=transfer_executed, executed_doc_no=executed_doc_no,
|
||||
updated_at=updated_at or datetime(2026, 10, 1, 8, 0, 0),
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return row
|
||||
@@ -285,7 +285,7 @@ class FakeRPA:
|
||||
})
|
||||
if source_code in self.fail_on:
|
||||
return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"}
|
||||
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
|
||||
return {"ok": True, "callback_id": f"inbound:{source_code}:{business_date}"}
|
||||
|
||||
|
||||
class FakeWeCom:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨测试的仓库/路由/依赖替身。
|
||||
|
||||
用途:为 file_preparation / matching_service / API / Job 测试提供可注入的
|
||||
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps;
|
||||
InboundFileRepository、RouteResolver 与组装好的 TransferDeps;
|
||||
并提供 seed_rows_from_file 迁移桥(2026-09-25 起匹配不解析文件,
|
||||
行须经 evidence_sync 落地)。
|
||||
依赖:app.services.in_transit_transfer(仅类型)、fakes。
|
||||
@@ -13,15 +13,15 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
|
||||
from app.services.in_transit_transfer.matching_service import RouteMapping, TransferDeps
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
|
||||
|
||||
|
||||
class FakeReceiptFileRepository:
|
||||
class FakeInboundFileRepository:
|
||||
"""按 (source_code, business_date) 返回可注入 ready 文件。"""
|
||||
|
||||
def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None:
|
||||
def __init__(self, files: dict[tuple[str, str], ReadyInboundFile] | None = None) -> None:
|
||||
self.files = files or {}
|
||||
self.lookups: list[tuple[str, str]] = []
|
||||
# 一次性覆盖:下一次 latest_ready_file 对该来源返回此文件(用后即弃,
|
||||
@@ -34,7 +34,7 @@ class FakeReceiptFileRepository:
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(覆盖该来源的下一次查询)。
|
||||
rows: 文件原始行集(透传为 ReadyReceiptFile.rows)。
|
||||
rows: 文件原始行集(透传为 ReadyInboundFile.rows)。
|
||||
checksum: 文件 sha256 版本戳。
|
||||
file_version: 文件版本号(缺省 "override")。
|
||||
"""
|
||||
@@ -42,12 +42,12 @@ class FakeReceiptFileRepository:
|
||||
"rows": tuple(rows), "checksum": checksum, "file_version": file_version,
|
||||
}
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
|
||||
"""记录查询并返回匹配文件;有一次性覆盖时优先返回并消费之。"""
|
||||
self.lookups.append((source_code, business_date))
|
||||
override = self._next_files.pop(source_code, None)
|
||||
if override is not None:
|
||||
return ReadyReceiptFile(
|
||||
return ReadyInboundFile(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
file_no=f"REC-OVERRIDE-{source_code}",
|
||||
@@ -64,7 +64,7 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str
|
||||
【2026-09-25】匹配不再解析文件(行由 evidence_sync 落地);凡旧用例
|
||||
「文件夹具直接进 run_matching/create_matching」的,须先经本助手把文件行
|
||||
落成待查行(status='matching' + result_code='pending_stock_check'),
|
||||
再进入匹配管道(成熟过滤→查库存→落位)。须在 app/DB 上下文内调用。
|
||||
再进入匹配管道(未来日期阻断→查库存→落位)。须在 app/DB 上下文内调用。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须与 deps.file_repository 注入的文件一致)。
|
||||
@@ -82,11 +82,11 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str
|
||||
)
|
||||
|
||||
|
||||
def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
|
||||
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
def make_ready_repo(*files: dict) -> FakeInboundFileRepository:
|
||||
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyInboundFile.rows。"""
|
||||
repository = FakeInboundFileRepository()
|
||||
for item in files:
|
||||
repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile(
|
||||
repository.files[(item["source_code"], item["business_date"])] = ReadyInboundFile(
|
||||
source_code=item["source_code"],
|
||||
business_date=item["business_date"],
|
||||
file_no=item["file_no"],
|
||||
|
||||
@@ -20,7 +20,6 @@ def _summary(executable_count: int) -> MatchingSummaryDTO:
|
||||
matching_id="MTG-20260928-ABC123",
|
||||
status="matched",
|
||||
business_date="2026-09-28",
|
||||
eligible_receipt_date_to="2026-09-27",
|
||||
expires_at="2026-09-28T10:00:00",
|
||||
counts=MatchingCountsDTO(executable_count=executable_count),
|
||||
estimated_transfer_quantity="0",
|
||||
@@ -66,8 +65,8 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
|
||||
assert outcome.errors == []
|
||||
|
||||
|
||||
def test_passes_receipt_date_range_to_matching(monkeypatch):
|
||||
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
|
||||
def test_passes_movement_date_range_to_matching(monkeypatch):
|
||||
"""可选异动日期范围透传匹配层;缺省时为 None(=全部积压)。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
@@ -78,15 +77,15 @@ def test_passes_receipt_date_range_to_matching(monkeypatch):
|
||||
|
||||
at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
|
||||
movement_date_from="2026-09-01", movement_date_to="2026-09-05",
|
||||
)
|
||||
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
|
||||
assert captured["receipt_date_from"] == "2026-09-01"
|
||||
assert captured["receipt_date_to"] == "2026-09-05"
|
||||
# 断言:显式范围原样透传(起止合法性由匹配层 ValidationError 卡控)。
|
||||
assert captured["movement_date_from"] == "2026-09-01"
|
||||
assert captured["movement_date_to"] == "2026-09-05"
|
||||
|
||||
at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
)
|
||||
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
|
||||
assert captured["receipt_date_from"] is None
|
||||
assert captured["receipt_date_to"] is None
|
||||
assert captured["movement_date_from"] is None
|
||||
assert captured["movement_date_to"] is None
|
||||
@@ -0,0 +1,372 @@
|
||||
"""backlog_reparse_service:清空并重解析的守卫矩阵(spec §6,Task 7)。
|
||||
|
||||
用途:锁死「清空并重新解析」的安全不变量与五条守卫——①正常路径旧映射行被清、
|
||||
按当前模板重落、计数/溯源正确、审计事件落库;②任一归档解析失败整体中止
|
||||
一行不删(先解析后删除);③封存行(transfer_executed=true)与被有效 items
|
||||
占用行幸存;④证据缺失(归档已清理/过保留期/无溯源)的行保留并计入
|
||||
kept_unrebuildable;⑤预检形状(files/profile/clearable_rows/kept_rows)。
|
||||
依赖:factories(来源/归档/档行种子 + FakeArchiveStorage + build_movement_xlsx)、
|
||||
app fixture。
|
||||
逻辑:归档文件字节经假存储注入(monkeypatch file_asset_storage.get_bytes);
|
||||
归档文件 created_at 均早于 NOW 数日——若 repository 仍带运行期「当日抓取」
|
||||
门禁则清单为空,本套件即红(锁定维护路径无当日门禁)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import (
|
||||
TransferAuditEvent,
|
||||
TransferInvoiceItem,
|
||||
TransferMatching,
|
||||
TransferMovementLedger,
|
||||
)
|
||||
from app.services.in_transit_transfer import evidence_sync
|
||||
from app.services.in_transit_transfer.backlog_reparse_service import (
|
||||
preview_pending_match_reparse,
|
||||
reparse_pending_match,
|
||||
)
|
||||
from tests.services.in_transit_transfer import factories
|
||||
|
||||
pytestmark = [pytest.mark.usefixtures("app")]
|
||||
|
||||
SOURCE = "CRANE_NA"
|
||||
NOW = datetime(2026, 10, 15, 10, 0, 0)
|
||||
OLD_SHA = "9" * 64
|
||||
SHA_A = "a" * 64
|
||||
SHA_B = "b" * 64
|
||||
SHA_GONE = "e" * 64 # 已过保留期归档文件的 sha(证据缺失形态)
|
||||
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
|
||||
|
||||
|
||||
@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_world(*, profile_status: str = "published") -> tuple:
|
||||
"""标准场景种子:来源+已发布入站规则 + 两份可用归档(A 先 B 后)。
|
||||
|
||||
Returns:
|
||||
(source, profile, file_a, file_b) 元组。
|
||||
"""
|
||||
source, profile = factories.seed_inbound_reparse_source(SOURCE, status=profile_status)
|
||||
file_a = factories.seed_reparse_archive_file(
|
||||
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/a.xlsx",
|
||||
created_at=datetime(2026, 10, 10, 8, 0, 0))
|
||||
file_b = factories.seed_reparse_archive_file(
|
||||
source, sha=SHA_B, storage_key=f"archive/{SOURCE}/b.xlsx",
|
||||
created_at=datetime(2026, 10, 11, 8, 0, 0))
|
||||
return source, profile, file_a, file_b
|
||||
|
||||
|
||||
def _count_ledger(source_code: str = SOURCE) -> int:
|
||||
"""该来源 inbound 档行总数(中止/幸存断言主对象)。"""
|
||||
return TransferMovementLedger.query.filter_by(
|
||||
source_code=source_code, record_kind="inbound").count()
|
||||
|
||||
|
||||
def test_reparse_clears_and_relands(app, archive_storage):
|
||||
# [断言意图] 正常路径:旧映射行全清(3)、按当前模板重落(3)、date_skipped
|
||||
# 计入结果、审计事件 TRANSFER_PENDING_MATCH_REPARSED 落库且 payload 完整
|
||||
# (operator/source_code/files/profile/cleared/reinserted/date_skipped/kept)。
|
||||
source, profile, file_a, file_b = _seed_world()
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
|
||||
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 300, "2026-08-05"],
|
||||
])
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"],
|
||||
])
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id,
|
||||
sha=OLD_SHA, quantity="1")
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id,
|
||||
sha=OLD_SHA, quantity="2")
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id,
|
||||
sha=OLD_SHA, quantity="3")
|
||||
assert _count_ledger() == 3
|
||||
|
||||
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
assert (outcome.cleared, outcome.reinserted) == (3, 3) # [断言意图] 清 3 落 3
|
||||
assert outcome.date_skipped == 0 and outcome.kept_unrebuildable == 0
|
||||
assert _count_ledger() == 3 # [断言意图] 无重复无丢失
|
||||
db.session.expire_all()
|
||||
a1 = TransferMovementLedger.query.filter_by(
|
||||
source_code=SOURCE, doc_no="ASN-A1").one()
|
||||
# [断言意图] 新映射值生效:业务值来自当前归档重解析,溯源换新文件三元组
|
||||
# (真实 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")
|
||||
assert a1.movement_date == "2026-08-05"
|
||||
# [断言意图] 文件顺序:按归档时间升序逐文件重落(files 概要 A 在前)。
|
||||
assert [f["sha256"] for f in outcome.files] == [SHA_A, SHA_B]
|
||||
assert [f["inserted"] for f in outcome.files] == [2, 1]
|
||||
|
||||
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
|
||||
assert event.aggregate_type == "transfer_source"
|
||||
assert event.aggregate_id == SOURCE
|
||||
payload = event.after_json
|
||||
assert payload["operator"] == "admin" and payload["source_code"] == SOURCE
|
||||
assert payload["cleared"] == 3 and payload["reinserted"] == 3
|
||||
assert payload["date_skipped"] == 0 and payload["kept"] == 0
|
||||
assert payload["profile_code"] == profile.profile_code
|
||||
assert payload["profile_version"] == 1
|
||||
assert [f["sha256"] for f in payload["files"]] == [SHA_A, SHA_B]
|
||||
|
||||
|
||||
def test_abort_on_parse_failure_deletes_nothing(app, archive_storage):
|
||||
# [断言意图] 安全不变量:任一归档解析失败(坏表头→必填缺失)→ 整体中止
|
||||
# TRANSFER.REPARSE_PARSE_FAILED,一行未删、无审计事件(先解析后删除)。
|
||||
_source, _profile, file_a, file_b = _seed_world()
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
|
||||
])
|
||||
# 坏文件:表头与绑定别名全不匹配 → 数据行缺单号 → 解析必失败。
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx(
|
||||
[["X1", 100, "X2"]], headers=["只此一列", "随便", "没有映射"])
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id, sha=OLD_SHA)
|
||||
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED"
|
||||
# [断言意图] 中止详情可精确定位失败文件:details 逐项断言(来源/文件身份/
|
||||
# 失败原因),不得用 or 短路式恒真断言掩盖缺键。
|
||||
details = exc_info.value.details
|
||||
assert details["source_code"] == SOURCE
|
||||
assert details["sha256"] == SHA_B # 失败文件=坏表头那份
|
||||
assert details["storage_key"] == f"archive/{SOURCE}/b.xlsx"
|
||||
assert details["file_id"] == file_b.id
|
||||
assert "missing_invoice_no" in details["reason"] # 行级失败原因透传
|
||||
assert _count_ledger() == 3 # [断言意图] 一行未删
|
||||
assert TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).count() == 0
|
||||
|
||||
|
||||
def test_sealed_and_occupied_rows_survive(app, archive_storage):
|
||||
# [断言意图] 删除范围三重过滤:封存行(transfer_executed=true)不动不复活;
|
||||
# 被有效 items 占用行不被删除(item 引用保持有效),重落按常规幂等语义
|
||||
# 走原行更新(新映射值生效、无第二行)。
|
||||
_source, _profile, file_a, _file_b = _seed_world()
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
|
||||
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"],
|
||||
])
|
||||
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
|
||||
sealed_at = datetime(2026, 10, 2, 8, 0, 0)
|
||||
sealed = factories.seed_reparse_ledger_row(
|
||||
SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA, quantity="1",
|
||||
transfer_executed=True, executed_doc_no="TRF-9", updated_at=sealed_at)
|
||||
occupied = factories.seed_reparse_ledger_row(
|
||||
SOURCE, "ASN-A2", line_no="1", in_out_flag="I", lot_no="LOT-2",
|
||||
source_file_id=file_a.id, sha=OLD_SHA, quantity="2")
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, ledger_record_id=occupied.id, source_code=SOURCE,
|
||||
invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1",
|
||||
to_warehouse="W2", movement_quantity="2", status="matching",
|
||||
result_code="pending_stock_check",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
assert outcome.cleared == 0 # [断言意图] 无可删行
|
||||
assert outcome.reinserted == 0 # [断言意图] 封存跳过+占用原行更新
|
||||
assert _count_ledger() == 2 # [断言意图] 无新增行
|
||||
db.session.expire_all()
|
||||
sealed_after = TransferMovementLedger.query.filter_by(id=sealed.id).one()
|
||||
assert sealed_after.transfer_executed is True
|
||||
assert sealed_after.executed_doc_no == "TRF-9"
|
||||
assert sealed_after.quantity == "1" # [断言意图] 封存行零写入
|
||||
occupied_after = TransferMovementLedger.query.filter_by(id=occupied.id).one()
|
||||
assert occupied_after.quantity == "600" # [断言意图] 占用行走更新分支换新映射
|
||||
assert occupied_after.file_sha256 == SHA_A
|
||||
item = TransferInvoiceItem.query.filter_by(ledger_record_id=occupied.id).one()
|
||||
assert item.result_code == "pending_stock_check" # [断言意图] item 引用仍然有效
|
||||
|
||||
|
||||
def test_unrebuildable_rows_kept_and_reported(app, archive_storage):
|
||||
# [断言意图] 证据缺失行保留并计入 kept_unrebuildable:归档已过保留期
|
||||
# (repository 可用清单排除)或无溯源(source_file_id=NULL)的行原样留存。
|
||||
source, _profile, file_a, _file_b = _seed_world()
|
||||
expired = factories.seed_reparse_archive_file(
|
||||
source, sha=SHA_GONE, storage_key=f"archive/{SOURCE}/gone.xlsx",
|
||||
created_at=datetime(2026, 10, 9, 8, 0, 0),
|
||||
archive_expires_at=datetime(2026, 10, 14, 0, 0, 0)) # NOW 前已过保留期
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
|
||||
])
|
||||
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-X", source_file_id=expired.id,
|
||||
sha=SHA_GONE, quantity="9")
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None,
|
||||
sha=None, quantity="8")
|
||||
|
||||
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 仅可重建行被清/重落
|
||||
assert outcome.kept_unrebuildable == 2 # [断言意图] 证据缺失=2 行
|
||||
db.session.expire_all()
|
||||
kept_x = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-X").one()
|
||||
kept_y = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-Y").one()
|
||||
assert kept_x.quantity == "9" and kept_x.file_sha256 == SHA_GONE # [断言意图] 原样留存
|
||||
assert kept_y.quantity == "8" and kept_y.file_sha256 is None
|
||||
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
|
||||
assert event.after_json["kept"] == 2
|
||||
|
||||
|
||||
def test_preview_shape(app, archive_storage):
|
||||
# [断言意图] 预检形状:files(archived_at/sha256/预估行数,按归档时间升序)、
|
||||
# profile{code,version}、clearable_rows(可重建可清除)与 kept_rows(证据缺失
|
||||
# 保留)与执行口径 1:1;只读(不删行、不落审计、不重落)。
|
||||
source, profile, file_a, file_b = _seed_world()
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id,
|
||||
sha=OLD_SHA, transfer_executed=True,
|
||||
executed_doc_no="TRF-8")
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None,
|
||||
sha=None, quantity="8")
|
||||
|
||||
preview = preview_pending_match_reparse(source_code=SOURCE, now=NOW)
|
||||
|
||||
assert set(preview.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
|
||||
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()
|
||||
# [断言意图] 预估行数口径=现有档行按 source_file_id 计数(含封存;docstring 声明),
|
||||
# 不在预检里解析归档字节。
|
||||
assert preview["files"][0]["rows"] == 2 and preview["files"][1]["rows"] == 0
|
||||
assert preview["clearable_rows"] == 1 # [断言意图] 仅未封存未占用有据行
|
||||
assert preview["kept_rows"] == 1 # [断言意图] 证据缺失行计入保留
|
||||
assert _count_ledger() == 3 # [断言意图] 预检只读零副作用
|
||||
assert TransferAuditEvent.query.count() == 0
|
||||
|
||||
|
||||
def test_reparse_aborts_without_published_profile(app, archive_storage):
|
||||
# [断言意图] 无已发布入站规则=无重建通道:即使存在档行也整体中止
|
||||
# (REPARSE_PARSE_FAILED),一行不删——防「删了装不回去」。
|
||||
factories.seed_inbound_reparse_source(SOURCE, status="draft")
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=None, sha=None)
|
||||
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED"
|
||||
assert _count_ledger() == 1 # [断言意图] 一行未删
|
||||
|
||||
|
||||
def test_cancelled_and_isolated_items_unlinked_before_delete(app, archive_storage):
|
||||
# [断言意图] R9/方案 D(FK 悬挂修复):已取消匹配 items 与 blocked_file_removed
|
||||
# 隔离 items 仍持有待删档行的 ledger_record_id(普通 FK 无 ondelete)——删除前
|
||||
# 必须同事务置空,否则 PG flush 撞 IntegrityError 且此后每次重建复发。
|
||||
# 范围严格限于待删集合:有效占用行不在删除集,其 items 引用保持不变。
|
||||
_source, _profile, file_a, file_b = _seed_world()
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
|
||||
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"],
|
||||
])
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"],
|
||||
])
|
||||
row_a1 = factories.seed_reparse_ledger_row(
|
||||
SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
row_a2 = factories.seed_reparse_ledger_row(
|
||||
SOURCE, "ASN-A2", lot_no="LOT-2", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
row_b1 = factories.seed_reparse_ledger_row(
|
||||
SOURCE, "ASN-B1", lot_no="LOT-3", source_file_id=file_b.id, sha=OLD_SHA)
|
||||
# ① 已取消匹配的 item → 引用待删行 row_a1。
|
||||
matching = TransferMatching(
|
||||
matching_no="MTG-R9-1", business_date="2026-08-06", status="cancelled",
|
||||
scope_json={}, file_snapshot_json={}, counts_json={}, matching_hash="sha256:r9",
|
||||
)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
cancelled_item = TransferInvoiceItem(
|
||||
matching_id=matching.id, ledger_record_id=row_a1.id, source_code=SOURCE,
|
||||
invoice_no="ASN-A1", material_no="MAT-OLD", from_warehouse="W1",
|
||||
to_warehouse="W2", movement_quantity="1", status="cancelled",
|
||||
)
|
||||
# ② 失效隔离 item(blocked_file_removed 不构成占用)→ 引用待删行 row_a2。
|
||||
isolated_item = TransferInvoiceItem(
|
||||
matching_id=None, ledger_record_id=row_a2.id, source_code=SOURCE,
|
||||
invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1",
|
||||
to_warehouse="W2", movement_quantity="2", status="cancelled",
|
||||
result_code="blocked_file_removed",
|
||||
)
|
||||
# ③ 对照:有效占用 item(普通 pending 引用即占用)→ row_b1 不在删除集。
|
||||
occupied_item = TransferInvoiceItem(
|
||||
matching_id=None, ledger_record_id=row_b1.id, source_code=SOURCE,
|
||||
invoice_no="ASN-B1", material_no="MAT-OLD", from_warehouse="W1",
|
||||
to_warehouse="W2", movement_quantity="3", status="matching",
|
||||
result_code="pending_stock_check",
|
||||
)
|
||||
db.session.add_all([cancelled_item, isolated_item, occupied_item])
|
||||
db.session.commit()
|
||||
|
||||
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
# [断言意图] 删除成功(无 FK IntegrityError)且仅删未占用两行;解绑计数=2。
|
||||
assert (outcome.cleared, outcome.reinserted) == (2, 2)
|
||||
assert outcome.unlinked_items == 2
|
||||
db.session.expire_all()
|
||||
# [断言意图] 待删行的两枚废弃 items 引用被置空(溯源装饰让位于可重建性)。
|
||||
assert TransferInvoiceItem.query.filter_by(id=cancelled_item.id).one().ledger_record_id is None
|
||||
assert TransferInvoiceItem.query.filter_by(id=isolated_item.id).one().ledger_record_id is None
|
||||
# [断言意图] 占用行不在删除集:行原样幸存(原行更新换新映射),其 item 引用
|
||||
# 仍指向同一档行 id——有效匹配的圈定关系不受重建波及。
|
||||
row_b1_after = TransferMovementLedger.query.filter_by(id=row_b1.id).one()
|
||||
assert row_b1_after.quantity == "700" and row_b1_after.file_sha256 == SHA_B
|
||||
assert TransferInvoiceItem.query.filter_by(id=occupied_item.id).one().ledger_record_id == row_b1.id
|
||||
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
|
||||
assert event.after_json["unlinked_items"] == 2
|
||||
|
||||
|
||||
def test_reparse_writes_collapse_audit_for_multi_material_same_key(app, archive_storage):
|
||||
# [断言意图] 终审遗留(坍缩审计接重建路径):重建与运行期同一坍缩守卫——同自然键
|
||||
# 六成分批内双料号(行级项次全空)重落时第二料号行仍被幂等吞掉(首见为准,
|
||||
# 行为与运行期一致),但必须落 ledger_natural_key_collapse 审计事件——改模板
|
||||
# 后的清空重建恰是坍缩易发时刻,静默吞行必须显式可观测;重建概要审计携带
|
||||
# collapses 计数。
|
||||
_source, _profile, file_a, _file_b = _seed_world()
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-C1", "1", "I", "MAT-X", "物料甲", "LOT-9", 500, "2026-08-05"],
|
||||
["ASN-C1", "1", "I", "MAT-Y", "物料乙", "LOT-9", 300, "2026-08-05"],
|
||||
])
|
||||
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-C1", lot_no="LOT-9",
|
||||
source_file_id=file_a.id, sha=OLD_SHA)
|
||||
|
||||
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
|
||||
|
||||
assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 旧行清 1、重落仅首见 1 行
|
||||
assert outcome.collapses == 1 # [断言意图] 坍缩键计数进结果
|
||||
db.session.expire_all()
|
||||
rows = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-C1").all()
|
||||
assert len(rows) == 1 and rows[0].material_code == "MAT-X" # [断言意图] 首见为准吞行不丢账
|
||||
# [断言意图] 坍缩审计事件落库且与运行期同构造:定位单号、failure 级、料号可追溯。
|
||||
event = TransferAuditEvent.query.filter_by(
|
||||
event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).one()
|
||||
assert "ASN-C1" in event.aggregate_id
|
||||
assert event.result == "failure"
|
||||
assert event.after_json["material_codes"] == ["MAT-X", "MAT-Y"]
|
||||
assert event.after_json["dropped_material_codes"] == ["MAT-Y"]
|
||||
assert event.after_json["resolution"] == "first_seen_wins"
|
||||
# [断言意图] 重建概要事件携带坍缩计数(运维一眼判断本次重建是否有数据质量降级)。
|
||||
reparse_event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
|
||||
assert reparse_event.after_json["collapses"] == 1
|
||||
@@ -44,7 +44,7 @@ def test_aging_level_thresholds():
|
||||
|
||||
|
||||
def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
|
||||
"""待处理池收纳 blocked_recoverable,排除 success / not_matured。"""
|
||||
"""待处理池收纳 blocked_recoverable,排除 success(not_matured 已退役)。"""
|
||||
_blocked_matching(dbs_ready_file)
|
||||
items = list_backlog()
|
||||
invoice_set = {item.invoice_no for item in items}
|
||||
@@ -59,14 +59,14 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
|
||||
updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。
|
||||
业务稳定键下,触碰前后列表顺序完全一致。
|
||||
"""
|
||||
_blocked_matching(dbs_ready_file) # HOM-001(receipt 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
|
||||
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
# 手工造第二笔 blocked:不同收料日期、更晚创建
|
||||
second = TransferInvoiceItem(
|
||||
matching_id=item.matching_id, source_code=item.source_code,
|
||||
invoice_no="HOM-002", material_no="MAT-003", material_name="垫片",
|
||||
receipt_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
|
||||
movement_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
movement_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
@@ -129,7 +129,7 @@ def test_backlog_summary_includes_pending_match_count(transfer_db, dbs_ready_fil
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
db.session.add(TransferMovementLedger(
|
||||
source_code="DBS-AWSBI", record_kind="receipt",
|
||||
source_code="DBS-AWSBI", record_kind="inbound",
|
||||
doc_no="HOM-901", line_no="1", line_seq="", in_out_flag="",
|
||||
material_code="MAT-9", material_name="未匹配物料", specification="",
|
||||
lot_no="LOT-9", quantity="55", unit="PCS",
|
||||
|
||||
@@ -29,7 +29,6 @@ pytestmark = pytest.mark.pure_unit
|
||||
|
||||
EXPECTED_ERROR_CODES = {
|
||||
"TRANSFER_PERMISSION_DENIED",
|
||||
"TRANSFER_RECEIPT_NOT_MATURED",
|
||||
"TRANSFER_FILE_NOT_READY",
|
||||
"TRANSFER_FILE_SCHEMA_INVALID",
|
||||
"TRANSFER_INVOICE_CONFLICT",
|
||||
@@ -67,13 +66,13 @@ def test_require_known_error_code_rejects_unknown():
|
||||
|
||||
|
||||
def test_matching_counts_dto_fields():
|
||||
"""匹配计数 DTO 包含文件内/未成熟/已匹配/可执行/阻断五类计数。"""
|
||||
"""匹配计数 DTO 包含文件内/已匹配/可执行/阻断等计数(not_matured 已退役)。"""
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=40, not_matured_count=8, matched_count=32,
|
||||
file_invoice_count=40, matched_count=32,
|
||||
executable_count=27, blocked_count=5,
|
||||
)
|
||||
assert counts.executable_count == 27
|
||||
assert counts.not_matured_count == 8
|
||||
assert counts.matched_count == 32
|
||||
|
||||
|
||||
def test_matching_summary_dto_carries_estimate_and_hash():
|
||||
@@ -82,9 +81,8 @@ def test_matching_summary_dto_carries_estimate_and_hash():
|
||||
matching_id="MTG-20260806-001",
|
||||
status="ready_to_execute",
|
||||
business_date="2026-08-06",
|
||||
eligible_receipt_date_to="2026-08-05",
|
||||
expires_at="2026-08-06T09:20:00+08:00",
|
||||
counts=MatchingCountsDTO(40, 8, 32, 27, 5),
|
||||
counts=MatchingCountsDTO(40, 32, 27, 5),
|
||||
estimated_transfer_quantity="18460",
|
||||
estimated_external_write_count=27,
|
||||
matching_hash="sha256:abc",
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
"""在途调拨日期成熟度策略测试(L0 纯单元)。
|
||||
"""在途调拨业务日期与日期解析测试(L0 纯单元)。
|
||||
|
||||
用途:验证 T+lag 成熟规则(默认 T+2)、当天/T-1 not_matured、未来日期阻断与上海业务时区;
|
||||
以及 parse_date 对 ISO / 美式 MM/DD/YYYY 收料日期的归一化。
|
||||
用途:验证 parse_date 对 ISO / 美式 MM/DD/YYYY 异动日期的归一化与上海业务时区
|
||||
换算(business_date_now / business_date_utc_window)。
|
||||
依赖:app.services.in_transit_transfer.date_policy(纯函数)。
|
||||
逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。
|
||||
逻辑:全部断言只依赖入参日期,不接触 Flask/DB(pure_unit)。
|
||||
【成熟度规则已退役 2026-10-16】原 T+lag 成熟策略用例随概念一并删除;
|
||||
日期边界现在由调用方入参给定(交互=用户范围,排程=T−N 偏移参数),
|
||||
引擎仅保留「截止 ≤ 业务日期」入参校验(matching_service 用例覆盖)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,63 +19,11 @@ import pytest
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
business_date_now,
|
||||
business_date_utc_window,
|
||||
eligible_receipt_date_to,
|
||||
maturity_status,
|
||||
parse_date,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
BUSINESS_T = date(2026, 8, 6)
|
||||
|
||||
|
||||
def test_same_day_receipt_is_not_matured():
|
||||
"""当天收料必须返回 not_matured;成熟门禁不查询 外部系统(调用次数由服务层保证为 0)。"""
|
||||
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
|
||||
|
||||
|
||||
def test_yesterday_receipt_is_not_matured():
|
||||
"""T+2 默认:昨天(T-1)收料尚未成熟(海外时差:28 号最早处理 26 号)。"""
|
||||
assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "not_matured"
|
||||
|
||||
|
||||
def test_t_minus_2_receipt_is_eligible():
|
||||
"""T+2 默认:前天(T-2)收料起可预检(纯单元无 app 上下文 → 回退默认 lag=2)。"""
|
||||
assert maturity_status(date(2026, 8, 4), BUSINESS_T) == "eligible"
|
||||
|
||||
|
||||
def test_older_receipt_is_eligible():
|
||||
"""更早收料同样可预检。"""
|
||||
assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible"
|
||||
|
||||
|
||||
def test_future_receipt_is_blocked():
|
||||
"""未来日期收料返回结构化阻断值。"""
|
||||
assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future"
|
||||
|
||||
|
||||
def test_maturity_status_accepts_iso_strings():
|
||||
"""字符串日期与 date 对象等价。"""
|
||||
assert maturity_status("2026-08-04", "2026-08-06") == "eligible"
|
||||
assert maturity_status("2026-08-05", "2026-08-06") == "not_matured"
|
||||
assert maturity_status("2026-08-06", "2026-08-06") == "not_matured"
|
||||
|
||||
|
||||
def test_explicit_lag_days_overrides_default():
|
||||
"""显式 lag=1 复现旧 T+1 口径(兼容回滚与测试钉值场景)。"""
|
||||
assert maturity_status(date(2026, 8, 5), BUSINESS_T, lag_days=1) == "eligible"
|
||||
assert maturity_status(date(2026, 8, 6), BUSINESS_T, lag_days=1) == "not_matured"
|
||||
|
||||
|
||||
def test_eligible_receipt_date_to_is_t_minus_two():
|
||||
"""可调拨收料截止日期 = 业务日期 - 2 天(默认 lag)。"""
|
||||
assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 4)
|
||||
|
||||
|
||||
def test_eligible_receipt_date_to_explicit_lag():
|
||||
"""显式 lag=1 时截止 = 业务日期 - 1 天。"""
|
||||
assert eligible_receipt_date_to(BUSINESS_T, lag_days=1) == date(2026, 8, 5)
|
||||
|
||||
|
||||
def test_business_date_now_uses_shanghai_across_utc_midnight():
|
||||
"""UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。"""
|
||||
@@ -108,17 +59,11 @@ def test_business_date_utc_window_maps_shanghai_day_to_utc():
|
||||
assert (end_next - start_next).total_seconds() == 24 * 3600
|
||||
|
||||
|
||||
def test_invalid_date_string_raises():
|
||||
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
|
||||
with pytest.raises(ValueError):
|
||||
maturity_status("2026/13/99", BUSINESS_T)
|
||||
|
||||
|
||||
def test_parse_date_accepts_us_mdy_with_time():
|
||||
"""DSV SSRS Date Received(美式带时分秒)须解析为业务 date。
|
||||
|
||||
[断言意图] 收料文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致
|
||||
evidence_sync 整链 invalid_receipt_date,transfer_invoice_items 零写入。
|
||||
[断言意图] 异动文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致
|
||||
evidence_sync 整链 invalid_movement_date,transfer_invoice_items 零写入。
|
||||
"""
|
||||
assert parse_date("08/13/2026 13:08:00") == date(2026, 8, 13)
|
||||
assert parse_date("6/11/2026 08:37:07") == date(2026, 6, 11)
|
||||
|
||||
@@ -37,7 +37,7 @@ def _ledger_rows(source_code="DBS-AWSBI") -> list[TransferMovementLedger]:
|
||||
"""按自然键序取某来源全部档行(断言主对象)。"""
|
||||
return (
|
||||
TransferMovementLedger.query
|
||||
.filter_by(source_code=source_code, record_kind="receipt")
|
||||
.filter_by(source_code=source_code, record_kind="inbound")
|
||||
.order_by(TransferMovementLedger.doc_no.asc(), TransferMovementLedger.id.asc())
|
||||
.all()
|
||||
)
|
||||
@@ -96,10 +96,10 @@ def test_sync_inserts_ledger_rows_without_erp(app, dbs_ready_file):
|
||||
assert outcome is not None and outcome.inserted == 2 # [断言意图] 两张单各一条档行
|
||||
rows = _ledger_rows()
|
||||
assert len(rows) == 2
|
||||
assert all(row.record_kind == "receipt" for row in rows)
|
||||
assert all(row.record_kind == "inbound" for row in rows)
|
||||
hom = _by_doc("HOM-001")
|
||||
# [断言意图] 数量聚合等价于旧 items 汇总断言:500+700=1200(档是匹配圈定的
|
||||
# 数量真相源,与旧 items receipt_quantity 等值)。
|
||||
# 数量真相源,与旧 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"
|
||||
@@ -217,7 +217,7 @@ def test_sync_refreshes_display_fields_on_evidence_change(app, dbs_ready_file):
|
||||
assert hom.specification == "改规格 / NEW"
|
||||
|
||||
|
||||
def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
|
||||
def test_inbound_bridge_is_failure_isolated(app, monkeypatch, caplog):
|
||||
# [断言意图] 落档崩溃只记日志:异常绝不向收料回调链路传播。
|
||||
from app.services.in_transit_transfer import evidence_sync
|
||||
|
||||
@@ -233,7 +233,7 @@ def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
|
||||
assert any("TRANSFER_EVIDENCE_SYNC" in r.message for r in caplog.records)
|
||||
|
||||
|
||||
def test_receipt_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypatch):
|
||||
def test_inbound_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypatch):
|
||||
# [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机);
|
||||
# 端到端一遍:桥 → 解析 → 聚合落档(档行持久化,items 停写)。
|
||||
from app.services.in_transit_transfer import evidence_sync
|
||||
@@ -250,15 +250,15 @@ def test_receipt_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypat
|
||||
assert TransferInvoiceItem.query.count() == 0 # [断言意图] items 停写
|
||||
|
||||
|
||||
def test_receipt_bridge_skips_when_no_file(app):
|
||||
def test_inbound_bridge_skips_when_no_file(app):
|
||||
# [断言意图] 来源无可用文件:静默返回 True(无事发生,非错误)。
|
||||
from app.services.in_transit_transfer import evidence_sync
|
||||
assert evidence_sync.sync_and_commit_for_callback(
|
||||
source_code="NO-SUCH", business_date="2026-09-25", now=NOW) is True
|
||||
|
||||
|
||||
def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch):
|
||||
# [断言意图] 桥内同步抛 ReceiptFileSchemaError(schema 类解析失败)→ 失败事实
|
||||
def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch):
|
||||
# [断言意图] 桥内同步抛 MovementFileSchemaError(schema 类解析失败)→ 失败事实
|
||||
# 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed;
|
||||
# 同步数据已回滚(桥隔离保持)。
|
||||
from app import db
|
||||
@@ -269,7 +269,7 @@ def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
|
||||
report = _seed_usable_report_file(
|
||||
source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-bad")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file)
|
||||
# 行缺单号(doc_no 置空)→ 解析必抛 ReceiptFileSchemaError(行级 missing_invoice_no)。
|
||||
# 行缺单号(doc_no 置空)→ 解析必抛 MovementFileSchemaError(行级 missing_invoice_no)。
|
||||
bad_row = {**dbs_ready_file["rows"][0], "doc_no": ""}
|
||||
deps.file_repository.set_next_file(
|
||||
source_code="DBS-AWSBI", rows=[bad_row], checksum="d" * 64)
|
||||
@@ -294,13 +294,13 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file):
|
||||
# [断言意图] 同步成功 = 当前可用文件已成功解析:此前落下的 parse_failed 三列
|
||||
# 被清除,来源投影恢复 ready(只 flush 不 commit,事务归属调用方不变)。
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
record_receipt_parse_failure,
|
||||
record_inbound_parse_failure,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
|
||||
report = _seed_usable_report_file(
|
||||
source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-clear")
|
||||
record_receipt_parse_failure(
|
||||
record_inbound_parse_failure(
|
||||
report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="stale mark")
|
||||
assert resolve_source_file_status(
|
||||
source_code="DBS-AWSBI")["file_status"] == "parse_failed" # [断言意图] 前置:确已标记
|
||||
@@ -319,12 +319,12 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file):
|
||||
|
||||
|
||||
def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
|
||||
# [断言意图] record_kind='receipt' 行出现出库语义 '-1':照常落档 + 计
|
||||
# [断言意图] record_kind='inbound' 行出现出库语义 '-1':照常落档 + 计
|
||||
# cross_flagged(解析错位标记由 ledger_sync 落审计事件,档不拒收)。
|
||||
deps, _, _ = make_transfer_deps({
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_purpose": "inbound",
|
||||
"file_no": "REC-X",
|
||||
"file_version": "v1",
|
||||
"checksum": "x" * 64,
|
||||
@@ -343,15 +343,16 @@ def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
|
||||
|
||||
|
||||
def _collapsed_multi_material_file() -> dict:
|
||||
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空的坍缩形态文件。
|
||||
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空且 carton/lot 等值的坍缩形态文件。
|
||||
|
||||
档自然键 (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag)
|
||||
不含料号:两行在批内折叠为同一自然键,第二料号行会被幂等吞掉(首见为准)。
|
||||
档自然键 (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag,
|
||||
carton_id, lot_no) 不含料号(tt14 起含箱号/批号,批内等值才同键):两行在批内
|
||||
折叠为同一自然键,第二料号行会被幂等吞掉(首见为准)。
|
||||
"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_purpose": "inbound",
|
||||
"file_no": "REC-C1",
|
||||
"file_version": "v1",
|
||||
"checksum": "c1" + "0" * 62,
|
||||
@@ -360,7 +361,7 @@ def _collapsed_multi_material_file() -> dict:
|
||||
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-C1", "lot_no": "LOT-A",
|
||||
"material_code": "MAT-A", "movement_date": "2026-08-05", "quantity": "10",
|
||||
"source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-C1", "lot_no": "LOT-B",
|
||||
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-C1", "lot_no": "LOT-A",
|
||||
"material_code": "MAT-B", "movement_date": "2026-08-05", "quantity": "20",
|
||||
"source_code": "DBS-AWSBI"},
|
||||
],
|
||||
|
||||
@@ -63,7 +63,7 @@ def _file(rows: list[dict], *, checksum: str = READY_SHA) -> dict:
|
||||
"""由行构造 DBS-AWSBI ready 收料文件 dict。"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
|
||||
"file_purpose": "receipt", "file_no": "REC-TEST", "file_version": "v9",
|
||||
"file_purpose": "inbound", "file_no": "REC-TEST", "file_version": "v9",
|
||||
"checksum": checksum, "status": "ready", "rows": rows,
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ def _order_call(erp, doc: TransferDocument) -> dict:
|
||||
# 场景①:两单不同收料日期 → 两张单各一单号(D1 收料日期入组键)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_two_receipt_dates_create_two_documents(
|
||||
def test_two_movement_dates_create_two_documents(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
|
||||
):
|
||||
"""不同收料日期的同来源行必须拆为两张单,各自终身独立单号/时间戳。"""
|
||||
@@ -162,7 +162,7 @@ def test_two_receipt_dates_create_two_documents(
|
||||
docs = _docs_of(run)
|
||||
# 断言意图:收料日期入组键(D1)→ 两日期两单,且单初态 pending。
|
||||
assert len(docs) == 2
|
||||
assert {doc.receipt_date for doc in docs} == {"2026-08-05", "2026-08-04"}
|
||||
assert {doc.movement_date for doc in docs} == {"2026-08-05", "2026-08-04"}
|
||||
assert all(doc.status == "pending" for doc in docs)
|
||||
assert len({doc.doc_no for doc in docs}) == 2
|
||||
assert len({doc.submit_timestamp for doc in docs}) == 2
|
||||
@@ -205,7 +205,7 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line(
|
||||
# 场景③:制单日期=组收料日期(gls_cm06 必须等于 Excel 异动日期,D1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_order_doc_date_equals_group_receipt_date(
|
||||
def test_order_doc_date_equals_group_movement_date(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
|
||||
):
|
||||
"""单 doc_date 必须等于组收料日期;posting_date 为执行当天业务日。"""
|
||||
@@ -221,7 +221,7 @@ def test_order_doc_date_equals_group_receipt_date(
|
||||
call = _order_call(erp, doc)
|
||||
# 断言意图:制单日期=组收料日期(2026-08-05),过账日期=执行当天(run 业务日)。
|
||||
assert call.doc_date == "2026-08-05"
|
||||
assert doc.receipt_date == "2026-08-05"
|
||||
assert doc.movement_date == "2026-08-05"
|
||||
assert call.posting_date == run.business_date
|
||||
|
||||
|
||||
@@ -418,9 +418,9 @@ def test_result_unknown_order_blocks_new_rows(
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="HOM-NEW",
|
||||
material_no="MAT-009", material_name="新行", specification="",
|
||||
receipt_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="100", unit="PCS", status="ready_to_execute",
|
||||
receipt_warehouse_code="DBS-TRANSIT",
|
||||
movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
movement_quantity="100", unit="PCS", status="ready_to_execute",
|
||||
movement_warehouse_code="DBS-TRANSIT",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 9, "file_version": "v9", "file_sha256": READY_SHA}],
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -543,7 +543,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
|
||||
if state["called"] == 1:
|
||||
winner = TransferDocument(
|
||||
source_code=doc.source_code, external_org=doc.external_org,
|
||||
receipt_date=doc.receipt_date, from_warehouse=doc.from_warehouse,
|
||||
movement_date=doc.movement_date, from_warehouse=doc.from_warehouse,
|
||||
to_warehouse=doc.to_warehouse,
|
||||
doc_no="HX-CN01-OR-26099999999", submit_timestamp="concurrent" + "0" * 38,
|
||||
status="pending",
|
||||
@@ -560,7 +560,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
|
||||
|
||||
db.session.expire_all()
|
||||
docs = TransferDocument.query.filter_by(
|
||||
source_code="DBS-AWSBI", receipt_date="2026-08-05",
|
||||
source_code="DBS-AWSBI", movement_date="2026-08-05",
|
||||
).all()
|
||||
# 断言意图:竞态后同组仅一张单(DB 部分唯一索引兜底 + 复用重试成立)。
|
||||
assert len(docs) == 1
|
||||
@@ -838,7 +838,7 @@ def test_serialize_run_orders_projects_multi_status_order_list(
|
||||
docs = _docs_of(run)
|
||||
assert len(docs) == 2
|
||||
# 按单号注入写场景:收料日期 08-04 单失败、08-05 单成功(组建单按组键升序)。
|
||||
by_date = {doc.receipt_date: doc for doc in docs}
|
||||
by_date = {doc.movement_date: doc for doc in docs}
|
||||
erp.write_scenarios_by_doc[by_date["2026-08-04"].doc_no] = "business_failed"
|
||||
|
||||
execute_run(run_id=run.id, deps=deps)
|
||||
@@ -849,13 +849,13 @@ def test_serialize_run_orders_projects_multi_status_order_list(
|
||||
assert len(orders) == 2
|
||||
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位,跨数据源
|
||||
# 不再随建单序乱序;本例同数据源,收料日期升序)。
|
||||
assert [t["receipt_date"] for t in orders] == ["2026-08-04", "2026-08-05"]
|
||||
assert [t["movement_date"] for t in orders] == ["2026-08-04", "2026-08-05"]
|
||||
failed, success = orders
|
||||
# 断言意图:计划 Task 11 JSON 规格逐键——order 八键、line 七键(+invoice_no:
|
||||
# 行级溯源收料通知号 2026-09-29 契约扩充;+reason:框线图失败行原因展示契约,
|
||||
# 控制器裁决扩充,T13-3)。
|
||||
assert set(failed.keys()) == {
|
||||
"doc_no", "receipt_date", "from_warehouse", "to_warehouse",
|
||||
"doc_no", "movement_date", "from_warehouse", "to_warehouse",
|
||||
"status", "erp_document_no", "error_message", "lines",
|
||||
}
|
||||
assert failed["status"] == "business_failed"
|
||||
@@ -897,12 +897,12 @@ def test_order_lines_group_by_external_lot_form():
|
||||
item_wtp = TransferInvoiceItem(
|
||||
invoice_no="HOX-900", material_no="MAT-900", lot_no="WTP26060612",
|
||||
from_warehouse="W1", to_warehouse="W2",
|
||||
receipt_quantity="200", unit="PCS", matching=matching,
|
||||
movement_quantity="200", unit="PCS", matching=matching,
|
||||
)
|
||||
item_how = TransferInvoiceItem(
|
||||
invoice_no="HOX-901", material_no="MAT-900", lot_no="HOW26060612",
|
||||
from_warehouse="W1", to_warehouse="W2",
|
||||
receipt_quantity="50", unit="PCS", matching=matching,
|
||||
movement_quantity="50", unit="PCS", matching=matching,
|
||||
)
|
||||
lines = _build_order_lines([item_wtp, item_how])
|
||||
# [断言意图] WTP/HOW 两形态同属一个 ERP 批次 → 聚合为一行且数量相加,
|
||||
@@ -930,11 +930,11 @@ def test_serialize_order_reason_join_uses_external_lot_form():
|
||||
item = TransferInvoiceItem(
|
||||
invoice_no="HOX-900", material_no="MAT-900", material_name="汇流排",
|
||||
lot_no="WTP26060612", from_warehouse="W1", to_warehouse="W2",
|
||||
receipt_quantity="200", unit="PCS", result_message="strict quantity mismatch",
|
||||
movement_quantity="200", unit="PCS", result_message="strict quantity mismatch",
|
||||
matching=matching,
|
||||
)
|
||||
doc = SimpleNamespace(
|
||||
doc_no="DOC-1", receipt_date="2026-08-05", from_warehouse="W1",
|
||||
doc_no="DOC-1", movement_date="2026-08-05", from_warehouse="W1",
|
||||
to_warehouse="W2", status="failed", erp_document_no=None, error_message=None,
|
||||
)
|
||||
order = serialize_order(doc, [item])
|
||||
|
||||
@@ -12,16 +12,16 @@ import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_preparation import (
|
||||
FilePreparationResult,
|
||||
ReadyReceiptFile,
|
||||
ReceiptFileRepository,
|
||||
ensure_receipt_file_ready,
|
||||
ReadyInboundFile,
|
||||
InboundFileRepository,
|
||||
ensure_inbound_file_ready,
|
||||
)
|
||||
from tests.services.in_transit_transfer.fakes import FakeRPA
|
||||
from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository
|
||||
from tests.services.in_transit_transfer.repo_fakes import FakeInboundFileRepository
|
||||
|
||||
|
||||
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile:
|
||||
return ReadyReceiptFile(
|
||||
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyInboundFile:
|
||||
return ReadyInboundFile(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
file_no=f"REC-{source_code}-001",
|
||||
@@ -33,9 +33,9 @@ def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08
|
||||
|
||||
def test_ready_file_reused_without_rpa_trigger():
|
||||
"""当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。"""
|
||||
repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
|
||||
repository = FakeInboundFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
|
||||
rpa = FakeRPA()
|
||||
result = ensure_receipt_file_ready(
|
||||
result = ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
@@ -46,9 +46,9 @@ def test_ready_file_reused_without_rpa_trigger():
|
||||
|
||||
def test_missing_file_triggers_rpa_once():
|
||||
"""缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
repository = FakeInboundFileRepository()
|
||||
rpa = FakeRPA()
|
||||
result = ensure_receipt_file_ready(
|
||||
result = ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
@@ -60,9 +60,9 @@ def test_missing_file_triggers_rpa_once():
|
||||
|
||||
def test_active_source_job_binds_existing_task_no_new_trigger():
|
||||
"""存在活动 Source Job → 绑定已有任务,不重复触发 RPA。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
repository = FakeInboundFileRepository()
|
||||
rpa = FakeRPA()
|
||||
result = ensure_receipt_file_ready(
|
||||
result = ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
|
||||
)
|
||||
@@ -72,10 +72,10 @@ def test_active_source_job_binds_existing_task_no_new_trigger():
|
||||
|
||||
def test_concurrent_requests_share_one_trigger():
|
||||
"""并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
repository = FakeInboundFileRepository()
|
||||
rpa = FakeRPA()
|
||||
for _ in range(3):
|
||||
result = ensure_receipt_file_ready(
|
||||
result = ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
|
||||
)
|
||||
@@ -85,13 +85,13 @@ def test_concurrent_requests_share_one_trigger():
|
||||
|
||||
def test_without_active_key_each_call_triggers_once():
|
||||
"""无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
repository = FakeInboundFileRepository()
|
||||
rpa = FakeRPA()
|
||||
ensure_receipt_file_ready(
|
||||
ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
ensure_receipt_file_ready(
|
||||
ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
@@ -100,10 +100,10 @@ def test_without_active_key_each_call_triggers_once():
|
||||
|
||||
def test_rpa_trigger_failure_is_fail_closed():
|
||||
"""RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
repository = FakeInboundFileRepository()
|
||||
rpa = FakeRPA()
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
result = ensure_receipt_file_ready(
|
||||
result = ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
@@ -113,14 +113,14 @@ def test_rpa_trigger_failure_is_fail_closed():
|
||||
|
||||
def test_dbs_and_crane_sources_isolated():
|
||||
"""DBS 失败不影响 Crane 的文件准备(来源隔离)。"""
|
||||
repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
|
||||
repository = FakeInboundFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
|
||||
rpa = FakeRPA()
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
dbs_result = ensure_receipt_file_ready(
|
||||
dbs_result = ensure_inbound_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
crane_result = ensure_receipt_file_ready(
|
||||
crane_result = ensure_inbound_file_ready(
|
||||
source_code="CRANE-SZ", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
|
||||
+5
-5
@@ -12,8 +12,8 @@ from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import TransferSourceJob, TransferRun
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import (
|
||||
advance_source_job_from_receipt_callback,
|
||||
from app.services.in_transit_transfer.inbound_callback_bridge import (
|
||||
advance_source_job_from_inbound_callback,
|
||||
)
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> Transfe
|
||||
def test_success_callback_advances_job_to_file_ready(app):
|
||||
"""成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。"""
|
||||
job = _make_waiting_job("RUN-BRIDGE-1")
|
||||
advanced = advance_source_job_from_receipt_callback(
|
||||
advanced = advance_source_job_from_inbound_callback(
|
||||
source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True,
|
||||
)
|
||||
assert advanced is not None and advanced.status == "file_ready"
|
||||
@@ -41,7 +41,7 @@ def test_success_callback_advances_job_to_file_ready(app):
|
||||
|
||||
def test_recover_stale_waiting_source_jobs(app):
|
||||
"""超过收料回调超时的等待任务回收为 failed;新任务不动。"""
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
|
||||
from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs
|
||||
|
||||
stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU")
|
||||
stale.updated_at = datetime.utcnow() - timedelta(seconds=3600)
|
||||
@@ -51,5 +51,5 @@ def test_recover_stale_waiting_source_jobs(app):
|
||||
db.session.expire_all()
|
||||
assert recovered == 1
|
||||
assert db.session.get(TransferSourceJob, stale.id).status == "failed"
|
||||
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT"
|
||||
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_INBOUND_CALLBACK_TIMEOUT"
|
||||
assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback"
|
||||
+47
-44
@@ -1,9 +1,12 @@
|
||||
"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。
|
||||
"""在途调拨异动文件字段/结构校验测试(L0 纯单元)。
|
||||
|
||||
用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与
|
||||
来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。
|
||||
来源身份不一致均整行阻断并抛出 MovementFileSchemaError。
|
||||
依赖:app.services.in_transit_transfer.file_parser(纯函数)。
|
||||
逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。
|
||||
tt14 入站化后统一走 movement 契约行(parse_movement_rows 单一入口),
|
||||
本文件聚焦「原始行 → 调拨语义字段」投影后的校验行为(与
|
||||
test_movement_parser 的契约映射用例互补)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,22 +17,22 @@ from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_receipt_rows,
|
||||
MovementFileSchemaError,
|
||||
ParsedMovementRow,
|
||||
parse_movement_rows,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
VALID_ROW = {
|
||||
"sheet": "Receipt",
|
||||
"sheet": "Movement",
|
||||
"row_no": 10,
|
||||
"invoice_no": "INV-001",
|
||||
"material_no": "MAT-001",
|
||||
"doc_no": "INV-001",
|
||||
"material_code": "MAT-001",
|
||||
"material_name": "连接器组件",
|
||||
"specification": "A 型 / 24PIN",
|
||||
"receipt_date": "2026-08-05",
|
||||
"receipt_quantity": "500",
|
||||
"movement_date": "2026-08-05",
|
||||
"quantity": "500",
|
||||
"source_code": "DBS-AWSBI",
|
||||
}
|
||||
|
||||
@@ -43,83 +46,83 @@ def _rows(**overrides) -> list[dict]:
|
||||
|
||||
def test_valid_rows_parse():
|
||||
"""合法行解析出全部字段(数量 Decimal、日期 date)。"""
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert len(parsed) == 1
|
||||
row = parsed[0]
|
||||
assert isinstance(row, ParsedReceiptRow)
|
||||
assert isinstance(row, ParsedMovementRow)
|
||||
assert row.invoice_no == "INV-001"
|
||||
assert row.material_no == "MAT-001"
|
||||
assert row.material_name == "连接器组件"
|
||||
assert row.specification == "A 型 / 24PIN"
|
||||
assert row.receipt_date == date(2026, 8, 5)
|
||||
assert row.receipt_quantity == Decimal("500")
|
||||
assert row.sheet == "Receipt"
|
||||
assert row.movement_date == date(2026, 8, 5)
|
||||
assert row.movement_quantity == Decimal("500")
|
||||
assert row.sheet == "Movement"
|
||||
assert row.row_no == 10
|
||||
|
||||
|
||||
def test_missing_invoice_no_rejected():
|
||||
"""Invoice No 缺失必须整行阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_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(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no=""))
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
|
||||
|
||||
|
||||
def test_invalid_quantity_rejected():
|
||||
"""非数字数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
|
||||
|
||||
|
||||
def test_zero_quantity_stamped_row_skipped():
|
||||
"""零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||
"""零数量异动行(日期已盖章、数量 0)为非可用异动事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="0"))
|
||||
assert parsed == []
|
||||
|
||||
|
||||
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
|
||||
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0",
|
||||
receipt_date="2026-10-01 14:37:43"),
|
||||
dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"),
|
||||
dict(VALID_ROW, row_no=788, doc_no="WTP26082227", quantity="0",
|
||||
movement_date="2026-10-01 14:37:43"),
|
||||
dict(VALID_ROW, row_no=789, doc_no="INV-002", quantity="120"),
|
||||
]
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
assert [row.row_no for row in parsed] == [789]
|
||||
assert parsed[0].invoice_no == "INV-002"
|
||||
|
||||
|
||||
def test_negative_quantity_rejected():
|
||||
"""负数数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5"))
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="-5"))
|
||||
|
||||
|
||||
def test_invalid_date_rejected():
|
||||
"""非法日期必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99"))
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
|
||||
|
||||
|
||||
def test_source_identity_mismatch_rejected():
|
||||
"""行内来源与任务来源不一致(Callback 身份漂移)必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
|
||||
|
||||
|
||||
def test_missing_sheet_or_row_no_rejected():
|
||||
"""Sheet/原始行号缺失无法追溯,必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
|
||||
|
||||
|
||||
def test_material_name_and_specification_optional():
|
||||
"""品名/规格允许为空(后续由明细 DTO 展示空值)。"""
|
||||
parsed = parse_receipt_rows(
|
||||
parsed = parse_movement_rows(
|
||||
source_code="DBS-AWSBI",
|
||||
rows=_rows(material_name="", specification=""),
|
||||
)
|
||||
@@ -129,8 +132,8 @@ def test_material_name_and_specification_optional():
|
||||
|
||||
def test_error_carries_row_details():
|
||||
"""错误细节必须携带行号与原因,供页面定位。"""
|
||||
with pytest.raises(ReceiptFileSchemaError) as excinfo:
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
|
||||
with pytest.raises(MovementFileSchemaError) as excinfo:
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, quantity="abc"))
|
||||
details = excinfo.value.details
|
||||
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
|
||||
|
||||
@@ -138,12 +141,12 @@ def test_error_carries_row_details():
|
||||
def test_schema_error_message_carries_row_details():
|
||||
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=5, invoice_no=""),
|
||||
dict(VALID_ROW, row_no=9, receipt_quantity="abc"),
|
||||
dict(VALID_ROW, row_no=5, doc_no=""),
|
||||
dict(VALID_ROW, row_no=9, quantity="abc"),
|
||||
]
|
||||
with pytest.raises(ReceiptFileSchemaError) as exc_info:
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
# [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因;
|
||||
with pytest.raises(MovementFileSchemaError) as exc_info:
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
# [断言意图] 消息不再只是通用 "movement file schema invalid",须含行号与原因;
|
||||
# 明细同时保留在 details.rows 供管理端展示。
|
||||
text = str(exc_info.value) or (exc_info.value.message or "")
|
||||
assert "row 5" in text and "missing_invoice_no" in text
|
||||
+44
-44
@@ -1,9 +1,9 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit
|
||||
用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit
|
||||
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、
|
||||
依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
|
||||
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
|
||||
@@ -15,9 +15,9 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import (
|
||||
trigger_receipt_rpa,
|
||||
trigger_receipt_rpa_batch,
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import (
|
||||
trigger_inbound_rpa,
|
||||
trigger_inbound_rpa_batch,
|
||||
)
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ def receipt_source():
|
||||
return source
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
|
||||
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
|
||||
calls = {}
|
||||
|
||||
@@ -48,9 +48,9 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
calls['payload'] = payload or {}
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
result = trigger_receipt_rpa(
|
||||
result = trigger_inbound_rpa(
|
||||
source_code='DSV360_AWSDU', business_date='2026-08-06',
|
||||
reason='transfer_retry_receipt', writer=fake_writer,
|
||||
reason='transfer_retry_inbound', writer=fake_writer,
|
||||
)
|
||||
assert result['ok'] is True
|
||||
assert result['callback_id']
|
||||
@@ -65,25 +65,25 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_disabled_source_fails_closed(app):
|
||||
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
|
||||
"""来源停用 → ok=False,不写 trigger。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
source.enabled = False
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
assert result['ok'] is False
|
||||
assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
|
||||
assert result['error_code'] == 'RPA_INBOUND_CONFIG_MISSING'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_missing_config_fails_closed(app):
|
||||
def test_trigger_inbound_rpa_missing_config_fails_closed(app):
|
||||
"""来源启用但无收料配置 → ok=False。"""
|
||||
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
assert result['ok'] is False
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
|
||||
def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
|
||||
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
@@ -96,9 +96,9 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
|
||||
captured["units"] = units
|
||||
return "trigger.json"
|
||||
|
||||
outcome = trigger_receipt_rpa(
|
||||
outcome = trigger_inbound_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_receipt", writer=fake_writer,
|
||||
reason="transfer_retry_inbound", writer=fake_writer,
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
@@ -111,13 +111,13 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
|
||||
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
|
||||
|
||||
|
||||
def _bind_published_movement_profile(config: ShippingReceiptReportConfig) -> None:
|
||||
"""给收料配置绑定一条已发布 movement 规则(仅满足守卫校验,不参与解析)。"""
|
||||
def _bind_published_inbound_profile(config: ShippingReceiptReportConfig) -> None:
|
||||
"""给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose='movement', profile_code='MOVE_TRIGGER_STD', display_name='收料异动规则',
|
||||
purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则',
|
||||
version=1, status='published', file_format='xlsx',
|
||||
definition_json={'sheet_name': None, 'header_row_index': 1,
|
||||
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
|
||||
@@ -137,7 +137,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
with app.app_context():
|
||||
config = ShippingReceiptReportConfig.query.filter_by(
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
_bind_published_movement_profile(config)
|
||||
_bind_published_inbound_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
@@ -148,8 +148,8 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
@@ -158,27 +158,27 @@ def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING"
|
||||
assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
outcome = trigger_receipt_rpa(
|
||||
outcome = trigger_inbound_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_receipt", writer=lambda *a, **k: None,
|
||||
reason="transfer_retry_inbound", writer=lambda *a, **k: None,
|
||||
)
|
||||
assert outcome["ok"] is False
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
|
||||
ShippingReceiptRpaUnitRun.id.desc()).first()
|
||||
assert unit.status == "failed"
|
||||
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
||||
assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件,
|
||||
# 批量触发(trigger_inbound_rpa_batch):多来源合并一个 batch trigger 文件,
|
||||
# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -214,7 +214,7 @@ def second_receipt_source(app):
|
||||
return source
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
|
||||
def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
|
||||
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
@@ -224,9 +224,9 @@ def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt
|
||||
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
reason='transfer_retry_receipt', writer=fake_writer,
|
||||
reason='transfer_retry_inbound', writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。
|
||||
assert len(calls) == 1
|
||||
@@ -244,7 +244,7 @@ def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt
|
||||
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||
def test_trigger_inbound_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
|
||||
captured: dict = {}
|
||||
|
||||
@@ -252,7 +252,7 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||
captured['units'] = units
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09',
|
||||
writer=fake_writer,
|
||||
)
|
||||
@@ -262,36 +262,36 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||
by_code = {item['source_code']: item for item in outcome['results']}
|
||||
assert by_code['DSV360_AWSDU']['ok'] is True
|
||||
assert by_code['DSV360_NOPE']['ok'] is False
|
||||
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
|
||||
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_INBOUND_CONFIG_MISSING'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app):
|
||||
"""全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。"""
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app):
|
||||
"""全部来源无效 → 不写 trigger,ok=False + RPA_INBOUND_NO_TRIGGERABLE_SOURCE。"""
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=['DSV360_NOPE'], business_date='2026-10-09',
|
||||
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE'
|
||||
assert outcome['error_code'] == 'RPA_INBOUND_NO_TRIGGERABLE_SOURCE'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
|
||||
def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
|
||||
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
writer=lambda *a, **k: None,
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'failed'}
|
||||
assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'}
|
||||
assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'}
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
|
||||
def test_trigger_inbound_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
|
||||
"""parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。"""
|
||||
statuses = {
|
||||
'DSV360_AWSDU': [
|
||||
@@ -320,7 +320,7 @@ def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receip
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
raise AssertionError('reparsed source must not be triggered via RPA')
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
outcome = trigger_inbound_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。
|
||||
@@ -1,9 +1,10 @@
|
||||
"""在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。
|
||||
|
||||
用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯;
|
||||
同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。
|
||||
用途:验证相同 Invoice 多行只汇总异动数量并永久保留原始行追溯;
|
||||
同一 Invoice 出现多料号/多异动日期时自然拆分(InvoiceConflictError 保留为防御)。
|
||||
依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。
|
||||
逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。
|
||||
逻辑:汇总键为 (source_code, invoice_no);拆分维度为料号与异动日期。
|
||||
tt14 入站化后经 parse_movement_rows(movement 契约行)构造解析行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +14,7 @@ from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import parse_receipt_rows
|
||||
from app.services.in_transit_transfer.file_parser import parse_movement_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import (
|
||||
AggregatedInvoice,
|
||||
aggregate_invoices,
|
||||
@@ -23,19 +24,19 @@ pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _parsed(rows: list[dict]) -> list:
|
||||
"""将原始行解析为 ParsedReceiptRow。"""
|
||||
return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
"""将原始 movement 契约行解析为 ParsedMovementRow。"""
|
||||
return parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
|
||||
|
||||
def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件",
|
||||
specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05",
|
||||
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt",
|
||||
def _row(doc_no: str, *, material_code: str = "MAT-001", material_name: str = "连接器组件",
|
||||
specification: str = "A 型 / 24PIN", movement_date: str = "2026-08-05",
|
||||
quantity: str = "500", row_no: int = 10, sheet: str = "Movement",
|
||||
warehouse_code: str = "WMS-A") -> dict:
|
||||
return {
|
||||
"sheet": sheet, "row_no": row_no, "invoice_no": invoice_no,
|
||||
"material_no": material_no, "material_name": material_name,
|
||||
"specification": specification, "receipt_date": receipt_date,
|
||||
"receipt_quantity": quantity, "source_code": "DBS-AWSBI",
|
||||
"sheet": sheet, "row_no": row_no, "doc_no": doc_no,
|
||||
"material_code": material_code, "material_name": material_name,
|
||||
"specification": specification, "movement_date": movement_date,
|
||||
"quantity": quantity, "source_code": "DBS-AWSBI",
|
||||
"warehouse_code": warehouse_code,
|
||||
}
|
||||
|
||||
@@ -50,11 +51,11 @@ def test_same_invoice_multiple_rows_sum_quantity():
|
||||
assert len(invoices) == 1
|
||||
invoice = invoices[0]
|
||||
assert invoice.invoice_no == "INV-001"
|
||||
assert invoice.receipt_quantity == Decimal("1200")
|
||||
assert invoice.movement_quantity == Decimal("1200")
|
||||
assert len(invoice.raw_lines) == 2
|
||||
assert invoice.raw_lines[0].row_no == 10
|
||||
assert invoice.raw_lines[1].row_no == 11
|
||||
assert all(line.sheet == "Receipt" for line in invoice.raw_lines)
|
||||
assert all(line.sheet == "Movement" for line in invoice.raw_lines)
|
||||
|
||||
|
||||
def test_distinct_invoices_stay_separate_and_sorted():
|
||||
@@ -70,41 +71,41 @@ def test_distinct_invoices_stay_separate_and_sorted():
|
||||
def test_same_invoice_multiple_materials_split_into_separate_invoices():
|
||||
"""同一 Invoice(ASN)跨料号 → 按料号拆分为多张调拨发票,不再整单阻断。"""
|
||||
rows = [
|
||||
_row("ASN-001", material_no="MAT-001", row_no=1, quantity="100"),
|
||||
_row("ASN-001", material_no="MAT-002", row_no=2, quantity="200"),
|
||||
_row("ASN-001", material_code="MAT-001", row_no=1, quantity="100"),
|
||||
_row("ASN-001", material_code="MAT-002", row_no=2, quantity="200"),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
# [断言意图] Invoice 语义 = 调拨拨出单据号;料号维度自然拆分,保留各自数量与原始行。
|
||||
assert [(i.material_no, i.receipt_quantity) for i in invoices] == [
|
||||
assert [(i.material_no, i.movement_quantity) for i in invoices] == [
|
||||
("MAT-001", Decimal("100")), ("MAT-002", Decimal("200")),
|
||||
]
|
||||
assert all(i.invoice_no == "ASN-001" for i in invoices)
|
||||
|
||||
|
||||
def test_same_invoice_material_multiple_dates_split_by_date():
|
||||
"""同 Invoice 同料号跨收料日期(部分交付)→ 按日期拆分,不再整单阻断。"""
|
||||
"""同 Invoice 同料号跨异动日期(部分交付)→ 按日期拆分,不再整单阻断。"""
|
||||
rows = [
|
||||
_row("ASN-001", receipt_date="2026-08-05", row_no=1, quantity="100"),
|
||||
_row("ASN-001", receipt_date="2026-08-06", row_no=2, quantity="50"),
|
||||
_row("ASN-001", movement_date="2026-08-05", row_no=1, quantity="100"),
|
||||
_row("ASN-001", movement_date="2026-08-06", row_no=2, quantity="50"),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
assert [str(i.receipt_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
|
||||
assert [i.receipt_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
|
||||
assert [str(i.movement_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
|
||||
assert [i.movement_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
|
||||
|
||||
|
||||
def test_aggregated_invoice_keeps_material_identity():
|
||||
"""汇总结果保留料号、品名、规格与收料日期。"""
|
||||
"""汇总结果保留料号、品名、规格与异动日期。"""
|
||||
rows = [
|
||||
_row("INV-001", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1),
|
||||
_row("INV-001", material_no="MAT-001", row_no=2),
|
||||
_row("INV-001", material_code="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", movement_date="2026-08-05", row_no=1),
|
||||
_row("INV-001", material_code="MAT-001", row_no=2),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
invoice = invoices[0]
|
||||
assert invoice.material_no == "MAT-001"
|
||||
assert invoice.material_name == "连接器组件"
|
||||
assert invoice.specification == "A 型 / 24PIN"
|
||||
assert invoice.receipt_date == date(2026, 8, 5)
|
||||
assert invoice.movement_date == date(2026, 8, 5)
|
||||
|
||||
|
||||
def test_aggregated_invoice_keeps_first_row_warehouse_code():
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
用途:锁定 ledger_sync.sync_ledger_rows 的规格 §5 五条幂等语义——首落插入、
|
||||
同文件重落全跳过(完全不动行)、证据变原行更新+换溯源、缺席不删、
|
||||
封存行(transfer_executed=True)永不更新永不复活;以及交叉校验矛盾
|
||||
(receipt 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
|
||||
(inbound 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
|
||||
审计事件且记录照常落档;shipment 预留合法值放行、同批自然键重复首见为准。
|
||||
依赖:app fixture(pytestmark)、models.TransferMovementLedger / TransferAuditEvent、
|
||||
ledger_sync.sync_ledger_rows / FileMeta。
|
||||
逻辑:parsed_rows 以「movement 契约 field code → 值」的领域行 dict 直接构造
|
||||
(扩展字段值从 dict 取,非 ParsedReceiptRow 属性——Task 11 接线同形态);
|
||||
(扩展字段值从 dict 取,非 ParsedMovementRow 属性——Task 11 接线同形态);
|
||||
直连 SQLite 内存库断言行级状态与审计事件,全程零外部调用。
|
||||
"""
|
||||
|
||||
@@ -60,7 +60,7 @@ def _meta(*, sha: str = SHA_V1, version: str = "v1", file_id: int = 101) -> File
|
||||
return FileMeta(source_file_id=file_id, file_version=version, file_sha256=sha)
|
||||
|
||||
|
||||
def _sync(parsed_rows, *, record_kind: str = "receipt", meta: FileMeta | None = None, now=NOW):
|
||||
def _sync(parsed_rows, *, record_kind: str = "inbound", meta: FileMeta | None = None, now=NOW):
|
||||
"""按默认来源发起一次落档(省略重复实参)。"""
|
||||
return sync_ledger_rows(
|
||||
source_code=SOURCE, record_kind=record_kind,
|
||||
@@ -69,14 +69,14 @@ def _sync(parsed_rows, *, record_kind: str = "receipt", meta: FileMeta | None =
|
||||
|
||||
|
||||
def test_first_landing_inserts_rows_with_provenance():
|
||||
# [断言意图] 首落五分类归插入:业务镜像列(含扩展字段)与溯源五列随行写入。
|
||||
# [断言意图] 首落六分类归插入:业务镜像列(含扩展字段)与溯源五列随行写入。
|
||||
outcome = _sync([_row(), _row(doc_no="HOM-20261014-002", line_no="20")])
|
||||
assert (outcome.inserted, outcome.updated, outcome.skipped,
|
||||
outcome.sealed_skipped, outcome.cross_flagged) == (2, 0, 0, 0, 0)
|
||||
rows = TransferMovementLedger.query.order_by(TransferMovementLedger.doc_no).all()
|
||||
assert len(rows) == 2
|
||||
first = rows[0]
|
||||
assert (first.source_code, first.record_kind) == (SOURCE, "receipt")
|
||||
assert (first.source_code, first.record_kind) == (SOURCE, "inbound")
|
||||
assert first.quantity == "12.5" and first.lot_no == "WTP123"
|
||||
# 扩展字段取自领域行 dict(movement 契约 code ↔ 档列 1:1 镜像)。
|
||||
assert first.specification == "C 型" and first.order_type == "ZRO1"
|
||||
@@ -146,8 +146,8 @@ def test_sealed_row_never_updated_nor_revived():
|
||||
assert TransferMovementLedger.query.count() == 1 # 永不复活(同键无第二行)
|
||||
|
||||
|
||||
def test_receipt_outbound_flag_cross_flagged_but_landed():
|
||||
# [断言意图] receipt 行出库语义 '-1':计 cross_flagged、写审计事件,记录照常落档;
|
||||
def test_inbound_outbound_flag_cross_flagged_but_landed():
|
||||
# [断言意图] inbound 行出库语义 '-1':计 cross_flagged、写审计事件,记录照常落档;
|
||||
# 幂等重落同一矛盾文件不重复打事件(只追加审计表防刷爆)。
|
||||
outcome = _sync([_row(in_out_flag="-1"), _row(doc_no="HOM-20261014-002", line_no="20")])
|
||||
assert (outcome.cross_flagged, outcome.inserted) == (1, 2)
|
||||
@@ -167,10 +167,10 @@ def test_receipt_outbound_flag_cross_flagged_but_landed():
|
||||
|
||||
|
||||
def test_shipment_kind_is_legal_and_not_cross_flagged():
|
||||
# [断言意图] record_kind='shipment' 为预留合法值:校验放行、无 receipt 侧矛盾判定。
|
||||
outcome = _sync([_row(in_out_flag="-1")], record_kind="shipment")
|
||||
# [断言意图] record_kind='outbound'(出货侧,预留)为合法值:校验放行、无 inbound 侧矛盾判定。
|
||||
outcome = _sync([_row(in_out_flag="-1")], record_kind="outbound")
|
||||
assert (outcome.inserted, outcome.cross_flagged) == (1, 0)
|
||||
assert TransferMovementLedger.query.one().record_kind == "shipment"
|
||||
assert TransferMovementLedger.query.one().record_kind == "outbound"
|
||||
|
||||
|
||||
def test_sealed_row_dominates_even_when_sha_unchanged():
|
||||
@@ -193,11 +193,46 @@ def test_duplicate_natural_key_in_batch_first_wins():
|
||||
assert TransferMovementLedger.query.one().quantity == "12.5"
|
||||
|
||||
|
||||
def test_carton_dimension_expands_natural_key():
|
||||
# [断言意图] 同单号同行不同箱号=两行独立落档(旧四成分键会塌缩为首见为准丢行)。
|
||||
outcome = _sync([
|
||||
_row(doc_no="DUB1", line_no="10", carton_id="C1", quantity="5"),
|
||||
_row(doc_no="DUB1", line_no="10", carton_id="C2", quantity="7"),
|
||||
], record_kind="inbound")
|
||||
assert (outcome.inserted, outcome.date_skipped) == (2, 0)
|
||||
|
||||
|
||||
def test_lot_no_expands_natural_key():
|
||||
# [断言意图] 同单号同行不同批号=两行独立落档(tt14 键扩维防同批号塌缩丢行)。
|
||||
outcome = _sync([
|
||||
_row(doc_no="WTP1", line_no="1", lot_no="HOW001", quantity="1"),
|
||||
_row(doc_no="WTP1", line_no="1", lot_no="HOW002", quantity="2"),
|
||||
], record_kind="inbound")
|
||||
assert outcome.inserted == 2
|
||||
|
||||
|
||||
def test_empty_movement_date_rows_skipped():
|
||||
# [断言意图] movement_date 空 = 未发生异动:不落档、不计入其他分类(date_skipped 单列)。
|
||||
outcome = _sync([
|
||||
_row(doc_no="EXP1", line_no="1", movement_date="", quantity="3"),
|
||||
_row(doc_no="OK1", line_no="1", movement_date="2026-10-15", quantity="1"),
|
||||
], record_kind="inbound")
|
||||
assert (outcome.inserted, outcome.date_skipped) == (1, 1)
|
||||
|
||||
|
||||
def test_constants_inbound_outbound():
|
||||
# [断言意图] record_kind 常量契约:说辞清扫(Task 3)以这些常量名为准,不再散落字面量。
|
||||
from app.services.in_transit_transfer import ledger_sync
|
||||
assert ledger_sync.RECORD_KIND_INBOUND == "inbound"
|
||||
assert ledger_sync.RECORD_KIND_OUTBOUND == "outbound"
|
||||
assert ledger_sync.INBOUND_CONTRADICTORY_FLAGS == frozenset({"-1"})
|
||||
|
||||
|
||||
def test_batch_external_doc_no_row_untouched_by_landing():
|
||||
# [断言意图] 评审 Important 回归(STEP 1 只圈批内 doc_no):同来源同种类的批外
|
||||
# 档行不被水化、不被触碰(updated_at/内容不变),outcome 计数只反映批内。
|
||||
db.session.add(TransferMovementLedger(
|
||||
source_code=SOURCE, record_kind="receipt",
|
||||
source_code=SOURCE, record_kind="inbound",
|
||||
doc_no="HOM-20261013-999", line_no="1", line_seq="", in_out_flag="1",
|
||||
quantity="7", file_sha256=SHA_V1, file_version="v0", source_file_id=201,
|
||||
updated_at=NOW,
|
||||
|
||||
@@ -66,9 +66,9 @@ def test_items_are_born_bound_to_matching(transfer_db, dbs_ready_file):
|
||||
assert row.ledger_record_id is not None
|
||||
hom = next(row for row in rows if row.invoice_no == "HOM-001")
|
||||
# [断言意图] 业务字段=档原值:数量=档聚合值(500+700),批号/仓库/日期同档。
|
||||
assert hom.receipt_quantity == "1200"
|
||||
assert hom.lot_no == "LOT-10" and hom.receipt_date == "2026-08-05"
|
||||
assert hom.receipt_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
|
||||
assert hom.movement_quantity == "1200"
|
||||
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-05"
|
||||
assert hom.movement_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
|
||||
|
||||
|
||||
def test_rematching_never_accumulates_or_steals_rows(transfer_db, dbs_ready_file):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证 T+lag 成熟过滤(套件钉 lag=1)、严格数量匹配、来源隔离、
|
||||
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||
@@ -55,7 +55,6 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
)
|
||||
summary = result.summary
|
||||
assert summary.counts.executable_count == 3
|
||||
assert summary.counts.not_matured_count == 0
|
||||
assert summary.counts.blocked_count == 0
|
||||
assert summary.status == "ready_to_execute"
|
||||
assert summary.matching_hash.startswith("sha256:")
|
||||
@@ -77,7 +76,7 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
def test_estimated_document_count_merges_same_group(dbs_ready_file):
|
||||
"""[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
|
||||
|
||||
场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to)
|
||||
场景:同源同日两张 Invoice,五元组(org, source, movement_date, from, to)
|
||||
全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2;
|
||||
并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。
|
||||
"""
|
||||
@@ -96,16 +95,16 @@ def test_estimated_document_count_merges_same_group(dbs_ready_file):
|
||||
assert items["HOX-002"].external_org == "HX-CN01"
|
||||
|
||||
|
||||
def test_estimated_document_count_splits_by_receipt_date():
|
||||
def test_estimated_document_count_splits_by_movement_date():
|
||||
"""[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。
|
||||
|
||||
锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键,
|
||||
锁定分组的日期维度:execution_service.prepare_execution 以 movement_date 入键,
|
||||
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
|
||||
"""
|
||||
deps, erp, _ = _deps({
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_purpose": "inbound",
|
||||
"file_no": "REC-20260806-009",
|
||||
"file_version": "v9",
|
||||
"checksum": "e" * 64,
|
||||
@@ -129,17 +128,20 @@ def test_estimated_document_count_splits_by_receipt_date():
|
||||
assert result.summary.estimated_external_write_count == 2
|
||||
|
||||
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
||||
deps, erp, _ = _deps(same_day_receipt_file)
|
||||
def test_same_day_data_reaches_erp_query(same_day_inbound_file):
|
||||
"""【成熟退役 2026-10-16】当天异动数据不再被成熟门禁跳过:正常进 ERP 查询。
|
||||
|
||||
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
|
||||
网关调用必须发生(=1),证明日期不再构成评估前置过滤。
|
||||
"""
|
||||
deps, erp, _ = _deps(same_day_inbound_file)
|
||||
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert result.summary.counts.not_matured_count == 1
|
||||
assert result.summary.counts.executable_count == 0
|
||||
assert result.summary.estimated_external_write_count == 0
|
||||
assert_erp_calls(erp, 0)
|
||||
assert result.summary.counts.blocked_count == 1
|
||||
assert_erp_calls(erp, 1)
|
||||
|
||||
|
||||
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
|
||||
@@ -175,7 +177,7 @@ def _wtp_lot_file() -> dict:
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_purpose": "inbound",
|
||||
"file_no": "REC-20260806-900",
|
||||
"file_version": "v9",
|
||||
"checksum": "e" * 64,
|
||||
@@ -282,7 +284,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"].receipt_date == "2026-08-05"
|
||||
assert restored_items["HOM-001"].movement_date == "2026-08-05"
|
||||
assert restored_items["HOM-001"].lot_no == "LOT-10"
|
||||
assert restored_items["HOX-002"].lot_no == "LOT-20"
|
||||
|
||||
@@ -365,7 +367,7 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
assert summary.counts.file_invoice_count == 2
|
||||
|
||||
|
||||
def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
def test_movement_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
"""收料日期范围作为匹配查询范围:范围外发票不进入明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
@@ -373,63 +375,39 @@ def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-05", movement_date_to="2026-08-05", 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,
|
||||
receipt_date_from="2026-08-01", receipt_date_to="2026-08-04", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-01", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert empty.counts.file_invoice_count == 0
|
||||
|
||||
|
||||
def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file):
|
||||
"""卡控:截止日期超出成熟规则(业务日期-lag,套件钉值 lag=1)必须拒绝。"""
|
||||
def test_movement_date_range_end_beyond_business_date_rejected(transfer_db, dbs_ready_file):
|
||||
"""卡控(成熟退役后唯一日期校验):截止晚于业务日期(未来日期)必须拒绝。
|
||||
|
||||
[断言意图] 截止=业务日期当天(2026-08-06)现在合法(旧成熟规则会拒绝 T-1/
|
||||
当天);只有严格晚于业务日期才拒——未来日期无账可核。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-04", receipt_date_to="2026-08-06", transfer_type="in_transit_to_hub"
|
||||
movement_date_from="2026-08-04", movement_date_to="2026-08-07", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert exc_info.value.code == "TRANSFER.RECEIPT_DATE_RANGE_INVALID"
|
||||
assert exc_info.value.code == "TRANSFER.MOVEMENT_DATE_RANGE_INVALID"
|
||||
|
||||
|
||||
def test_t_plus_2_default_boundary_yesterday_not_matured(app, dbs_ready_file):
|
||||
"""生产默认 lag=2 边界:昨天(T-1)收料 not_matured,改到 T-2 后可预检。
|
||||
|
||||
[断言意图] 套件 conftest 把 lag 钉为 1(存量夹具语义);本用例显式恢复生产
|
||||
默认 2,锁定真实默认口径不被钉值掩盖(海外时差:28 号最早处理 26 号)。
|
||||
"""
|
||||
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")
|
||||
app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 2 # 覆盖套件钉值,锁生产默认
|
||||
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
|
||||
# [边界反转] 截止=业务日期当天合法(旧行为 lag=1 下会被拒)。
|
||||
empty = 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"
|
||||
)
|
||||
# [断言意图] 夹具行收料 2026-08-05(T-1):默认 lag=2 下全部未成熟,零 ERP 调用。
|
||||
assert result.summary.counts.not_matured_count == 2
|
||||
assert result.summary.counts.executable_count == 0
|
||||
assert_erp_calls(erp, 0)
|
||||
|
||||
# [边界] 收料日期改到 T-2(2026-08-04)后即可进入匹配并严格匹配成功。
|
||||
# [出生翻转] 成熟基准在档(movement_date):改档记录日期,并释放首跑占用
|
||||
#(管道直调行无匹配归属,测试直接清空=释放;生产释放走取消匹配)后重跑。
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
for record in TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI").all():
|
||||
record.movement_date = "2026-08-04"
|
||||
TransferInvoiceItem.query.delete()
|
||||
db.session.flush()
|
||||
result2 = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert result2.summary.counts.executable_count == 2
|
||||
assert empty.counts.file_invoice_count == 0
|
||||
|
||||
|
||||
def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file):
|
||||
@@ -464,7 +442,7 @@ def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file):
|
||||
def test_run_matching_consumes_movement_field_rows(app):
|
||||
"""run_matching 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
|
||||
# [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键;
|
||||
# 匹配应正确产出 executable 明细而非 ReceiptFileSchemaError
|
||||
# 匹配应正确产出 executable 明细而非 MovementFileSchemaError
|
||||
# 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
@@ -490,7 +468,7 @@ def test_run_matching_consumes_movement_field_rows(app):
|
||||
def test_type1_filters_invoices_by_prefix(app):
|
||||
"""类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的单,范围外静默排除。"""
|
||||
# [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行;
|
||||
# HOM/HOX/WTP 前缀单正常走完整匹配(成熟 + 外部系统 匹配)。
|
||||
# HOM/HOX/WTP 前缀单正常走完整匹配(日期圈定 + 外部系统 匹配)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
@@ -549,7 +527,7 @@ def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
# 随匹配落库(快照自足,展示/重跑/审计不查配置表)。
|
||||
assert scope["transfer_type"] == "in_transit_to_hub"
|
||||
assert scope["source_codes"] == ["DSV360_AWSDU"]
|
||||
assert scope["receipt_date_from"] is None and scope["receipt_date_to"] is None
|
||||
assert scope["movement_date_from"] is None and scope["movement_date_to"] is None
|
||||
assert scope["scope_rules"] == [
|
||||
{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]},
|
||||
]
|
||||
@@ -672,19 +650,19 @@ def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-OLD",
|
||||
material_no="MAT-001", material_name="n", specification="",
|
||||
receipt_date="2026-09-01", status="ready_to_execute", result_code=None,
|
||||
movement_date="2026-09-01", status="ready_to_execute", result_code=None,
|
||||
result_message=None, from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200", external_quantity="1200", lot_no="LOT-10",
|
||||
receipt_warehouse_code="W1", unit="PCS", raw_lines_json=[],
|
||||
movement_quantity="1200", external_quantity="1200", lot_no="LOT-10",
|
||||
movement_warehouse_code="W1", unit="PCS", raw_lines_json=[],
|
||||
inventory_checked_at=old_ts,
|
||||
))
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-NOCHK",
|
||||
material_no="MAT-001", material_name="n", specification="",
|
||||
receipt_date="2026-09-01", status="ready_to_execute", result_code=None,
|
||||
movement_date="2026-09-01", status="ready_to_execute", result_code=None,
|
||||
result_message=None, from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200", external_quantity=None, lot_no="LOT-10",
|
||||
receipt_warehouse_code="W1", unit="PCS", raw_lines_json=[],
|
||||
movement_quantity="1200", external_quantity=None, lot_no="LOT-10",
|
||||
movement_warehouse_code="W1", unit="PCS", raw_lines_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
payload = list_executable_items()
|
||||
@@ -704,7 +682,7 @@ def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
record = TransferMovementLedger(
|
||||
source_code=source_code, record_kind="receipt",
|
||||
source_code=source_code, record_kind="inbound",
|
||||
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
|
||||
material_code=material, material_name="档物料", specification="",
|
||||
lot_no=f"LOT-{doc_no}", quantity=quantity, unit="PCS",
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""tt14a5f6a7b8c9 入站化迁移契约测试。
|
||||
|
||||
用途:锁定 tt14 迁移与模型两侧契约——transfer_invoice_items/transfer_documents
|
||||
receipt_* 列更名 movement_*(明细/单据方向中立,与异动档 movement_date
|
||||
对齐);transfer_movement_ledger.record_kind 值迁移 receipt→inbound /
|
||||
shipment→outbound;自然键唯一约束重建为 8 成分(追加 carton_id/lot_no)。
|
||||
依赖:migrations/versions(it1a2b3c4d5e 建表 → it2c3d4e5f6a7 → tt0d1e2f3a4b →
|
||||
tt11b2c3d4e5f → tt14)、app_ctx(根 conftest app fixture 上下文别名)。
|
||||
逻辑:revision 链断言 + 模型属性/约束成分断言 + SQLite 真实 upgrade/downgrade/
|
||||
upgrade 往返(test_migration_widen_transfer_run_type 同款模式)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_ctx(app):
|
||||
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
|
||||
return app
|
||||
|
||||
|
||||
def _load(revision_prefix: str):
|
||||
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
|
||||
spec = importlib.util.spec_from_file_location(path.stem, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
raise AssertionError(f"migration {revision_prefix} not found")
|
||||
|
||||
|
||||
def test_revision_chains_from_mh15_head():
|
||||
migration = _load("tt14a5f6a7b8c9")
|
||||
assert migration.down_revision == "mh15f6a7b8c9"
|
||||
|
||||
|
||||
def test_model_inbound_columns_and_ledger_key(app_ctx):
|
||||
from app.models.in_transit_transfer import (
|
||||
TransferDocument, TransferInvoiceItem, TransferMovementLedger,
|
||||
)
|
||||
|
||||
item_cols = {c.name for c in TransferInvoiceItem.__table__.columns}
|
||||
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols
|
||||
assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols
|
||||
doc_cols = {c.name for c in TransferDocument.__table__.columns}
|
||||
assert "movement_date" in doc_cols and "receipt_date" not in doc_cols
|
||||
ledger_uq = next(
|
||||
c for c in TransferMovementLedger.__table__.constraints
|
||||
if getattr(c, "name", "") == "uq_transfer_movement_ledger_natural_key"
|
||||
)
|
||||
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",
|
||||
]
|
||||
# R7 终审:进键维度列必须 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"):
|
||||
assert ledger_cols[name].nullable is False, f"{name} 进键即 NOT NULL"
|
||||
assert ledger_cols[name].default.arg == ''
|
||||
assert ledger_cols[name].server_default.arg == ''
|
||||
|
||||
|
||||
def _ledger_natural_key(connection) -> list[str]:
|
||||
"""从 SQLite 反射 transfer_movement_ledger 自然键唯一约束的列序。"""
|
||||
constraints = sa.inspect(connection).get_unique_constraints("transfer_movement_ledger")
|
||||
for constraint in constraints:
|
||||
if constraint.get("name") == "uq_transfer_movement_ledger_natural_key":
|
||||
return list(constraint["column_names"])
|
||||
raise AssertionError("uq_transfer_movement_ledger_natural_key not found in SQLite schema")
|
||||
|
||||
|
||||
def _item_column_names(connection) -> set[str]:
|
||||
return {c["name"] for c in sa.inspect(connection).get_columns("transfer_invoice_items")}
|
||||
|
||||
|
||||
def _doc_column_names(connection) -> set[str]:
|
||||
return {c["name"] for c in sa.inspect(connection).get_columns("transfer_documents")}
|
||||
|
||||
|
||||
def _ledger_dimension_column(connection, name: str) -> dict:
|
||||
"""从 SQLite 反射 transfer_movement_ledger 维度列(DDL 往返断言用)。"""
|
||||
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("transfer_movement_ledger")}
|
||||
assert name in columns
|
||||
return columns[name]
|
||||
|
||||
|
||||
def test_sqlite_roundtrip_upgrade_downgrade_upgrade():
|
||||
"""SQLite 真实往返:upgrade 更名+扩键 / downgrade 精确还原 / 再 upgrade。
|
||||
|
||||
[断言意图] 前置链(it1a2b3c4d5e 建表 + it2c3d4e5f6a7 加仓库列 + tt0d1e2f3a4b
|
||||
建单表 + tt11b2c3d4e5f 建档表)就位后,tt14 的 batch RENAME 不丢列、自然键
|
||||
唯一约束随往返在 6/8 成分间精确翻转,证明 DDL 可回滚且与模型同构。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
|
||||
# batch copy-and-move 反射时按 FK autoload 目标表:内存库无 Flask 全量
|
||||
# 元数据,先建最小 users / shipping_receipt_report_files 桩表满足反射。
|
||||
sa.Table(
|
||||
"users", sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
sa.Table(
|
||||
"shipping_receipt_report_files", sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
# it2c3d4e5f6a7 同时给库存来源映射表加列(与调拨列无关):建最小桩表承接。
|
||||
sa.Table(
|
||||
"shipping_inventory_external_mappings", sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
).create(connection)
|
||||
|
||||
for revision in ("it1a2b3c4d5e", "it2c3d4e5f6a7", "tt0d1e2f3a4b", "tt11b2c3d4e5f"):
|
||||
base = _load(revision)
|
||||
base.op = operations
|
||||
base.upgrade()
|
||||
|
||||
# 前置基线:items/documents 仍是 receipt_* 列,档自然键为 6 成分。
|
||||
assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection)
|
||||
assert "receipt_date" in _doc_column_names(connection)
|
||||
assert _ledger_natural_key(connection) == [
|
||||
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
|
||||
]
|
||||
|
||||
migration = _load("tt14a5f6a7b8c9")
|
||||
migration.op = operations
|
||||
|
||||
migration.upgrade()
|
||||
item_cols = _item_column_names(connection)
|
||||
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols
|
||||
assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols
|
||||
assert "movement_date" in _doc_column_names(connection)
|
||||
assert "receipt_date" not in _doc_column_names(connection)
|
||||
# [断言意图] 自然键扩 8 成分(真实 WMS 行身份=单据+行+箱/批)。
|
||||
assert _ledger_natural_key(connection) == [
|
||||
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
|
||||
"in_out_flag", "carton_id", "lot_no",
|
||||
]
|
||||
# [断言意图] 维度列 NOT NULL + default ''(R7:防 NULL 逃逸唯一比对)。
|
||||
for name in ("carton_id", "lot_no"):
|
||||
column = _ledger_dimension_column(connection, name)
|
||||
assert column["nullable"] is False
|
||||
assert "''" in str(column.get("default") or "")
|
||||
|
||||
migration.downgrade()
|
||||
assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection)
|
||||
assert "movement_date" not in _item_column_names(connection)
|
||||
assert "receipt_date" in _doc_column_names(connection)
|
||||
assert _ledger_natural_key(connection) == [
|
||||
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
|
||||
]
|
||||
# [断言意图] downgrade 对称还原:维度列回 nullable=True 且默认值移除。
|
||||
for name in ("carton_id", "lot_no"):
|
||||
column = _ledger_dimension_column(connection, name)
|
||||
assert column["nullable"] is True
|
||||
assert "''" not in str(column.get("default") or "")
|
||||
|
||||
migration.upgrade()
|
||||
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= _item_column_names(connection)
|
||||
assert _ledger_natural_key(connection) == [
|
||||
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
|
||||
"in_out_flag", "carton_id", "lot_no",
|
||||
]
|
||||
@@ -73,10 +73,10 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
material_no="MAT-001",
|
||||
material_name="连接器组件",
|
||||
specification="A 型 / 24PIN",
|
||||
receipt_date="2026-08-05",
|
||||
movement_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
movement_quantity="1200",
|
||||
external_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
|
||||
@@ -123,10 +123,10 @@ def test_invoice_item_unique_per_matching(transfer_db):
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no=invoice_no,
|
||||
material_no="MAT-001",
|
||||
receipt_date="2026-08-05",
|
||||
movement_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
movement_quantity="1200",
|
||||
external_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[],
|
||||
@@ -162,9 +162,9 @@ def test_invoice_item_status_check_constraint(transfer_db):
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.add(TransferInvoiceItem(
|
||||
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="INV-999",
|
||||
material_no="MAT-9", receipt_date="2026-08-05",
|
||||
material_no="MAT-9", movement_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1", external_quantity="1",
|
||||
movement_quantity="1", external_quantity="1",
|
||||
status="no_such_status", raw_lines_json=[],
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:锁定调拨定死的通用异动/移动字段契约(领域定死、不配置化;D4 追加第 11 字段
|
||||
unit;2026-10-14 调拨类型配置化+库存异动档项目追加 7 个可选维度字段——
|
||||
line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id),
|
||||
以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedReceiptRow。
|
||||
以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedMovementRow。
|
||||
依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。
|
||||
逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用;
|
||||
追加字段全部可选非身份,缺列容忍语义由既有 row.get 投影自动继承。
|
||||
@@ -16,7 +16,7 @@ from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow, parse_movement_rows
|
||||
from app.services.in_transit_transfer.file_parser import ParsedMovementRow, parse_movement_rows
|
||||
from app.services.in_transit_transfer.movement_contract import (
|
||||
MOVEMENT_FIELDS,
|
||||
MovementField,
|
||||
|
||||
@@ -180,4 +180,4 @@ def test_extract_movement_rows_normalizes_ssrs_wrapped_headers():
|
||||
assert rows[0]['row_no'] == 3
|
||||
parsed = parse_movement_rows(source_code='DSV360_AWSBI_BYAWSPHX01', rows=rows)
|
||||
assert parsed[0].invoice_no == 'ASN-PHX-1'
|
||||
assert parsed[0].receipt_quantity == 24
|
||||
assert parsed[0].movement_quantity == 24
|
||||
@@ -1,9 +1,9 @@
|
||||
"""通用异动表解析器测试(L0 纯单元)。
|
||||
|
||||
用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到
|
||||
调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity,
|
||||
receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
|
||||
依赖:app.services.in_transit_transfer.movement_parser(纯函数)。
|
||||
调拨 ParsedMovementRow(invoice_no=doc_no, movement_quantity=quantity,
|
||||
movement_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
|
||||
依赖:app.services.in_transit_transfer.file_parser.parse_movement_rows(纯函数)。
|
||||
逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。
|
||||
"""
|
||||
|
||||
@@ -15,8 +15,8 @@ from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
ParsedMovementRow,
|
||||
MovementFileSchemaError,
|
||||
parse_movement_rows,
|
||||
)
|
||||
|
||||
@@ -46,41 +46,41 @@ def _rows(**overrides) -> list[dict]:
|
||||
|
||||
|
||||
def test_valid_movement_row_maps_to_parsed_rows():
|
||||
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。"""
|
||||
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→movement_quantity、movement_date→movement_date(tt14 入站化后明细侧同名对齐)。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert len(parsed) == 1
|
||||
row = parsed[0]
|
||||
assert isinstance(row, ParsedReceiptRow)
|
||||
assert isinstance(row, ParsedMovementRow)
|
||||
assert row.invoice_no == "MOV-001"
|
||||
assert row.material_no == "MAT-001"
|
||||
assert row.material_name == "连接器组件"
|
||||
assert row.receipt_date == date(2026, 8, 5)
|
||||
assert row.receipt_quantity == Decimal("500")
|
||||
assert row.movement_date == date(2026, 8, 5)
|
||||
assert row.movement_quantity == Decimal("500")
|
||||
assert row.sheet == "Movement"
|
||||
assert row.row_no == 7
|
||||
|
||||
|
||||
def test_missing_doc_no_rejected():
|
||||
"""单号缺失阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
|
||||
|
||||
|
||||
def test_invalid_quantity_rejected():
|
||||
"""非数字数量阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
|
||||
|
||||
|
||||
def test_invalid_movement_date_rejected():
|
||||
"""非法异动日期阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
|
||||
|
||||
|
||||
def test_source_identity_mismatch_rejected():
|
||||
"""来源身份漂移阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
with pytest.raises(MovementFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
|
||||
|
||||
|
||||
@@ -124,9 +124,9 @@ def test_receiving_in_progress_rows_are_skipped():
|
||||
def test_unparseable_date_still_fails():
|
||||
"""日期有值但不可解析仍是数据损坏——跳过守卫不得吞掉真正的脏数据。"""
|
||||
corrupted = dict(VALID_MOVEMENT_ROW, row_no=5, doc_no="MOV-300", movement_date="not-a-date")
|
||||
with pytest.raises(ReceiptFileSchemaError) as exc_info:
|
||||
with pytest.raises(MovementFileSchemaError) as exc_info:
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=[corrupted])
|
||||
assert any("invalid_receipt_date" in error.get("reason", "")
|
||||
assert any("invalid_movement_date" in error.get("reason", "")
|
||||
for error in exc_info.value.details["rows"])
|
||||
|
||||
|
||||
@@ -140,4 +140,4 @@ def test_datetime_cell_and_timed_string_dates_are_accepted():
|
||||
movement_date="2026-09-08 00:00:00")
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[datetime_cell, timed_string])
|
||||
# [断言意图] WMS 报表真实日期形态不能被 ISO 纯日期校验误杀。
|
||||
assert [row.receipt_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
|
||||
assert [row.movement_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
|
||||
@@ -16,7 +16,7 @@ from app.services.in_transit_transfer.quantity import (
|
||||
QuantityValidationError,
|
||||
classify_quantity_match,
|
||||
strict_quantities_equal,
|
||||
validate_receipt_quantity,
|
||||
validate_inbound_quantity,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
@@ -27,12 +27,12 @@ def test_equal_quantities_are_executable():
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable"
|
||||
|
||||
|
||||
def test_erp_greater_than_receipt_is_blocked():
|
||||
def test_erp_greater_than_inbound_is_blocked():
|
||||
"""外部系统 库存大于收料数量 → 阻断(不允许部分调拨)。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_erp_less_than_receipt_is_blocked():
|
||||
def test_erp_less_than_inbound_is_blocked():
|
||||
"""外部系统 库存小于收料数量 → 阻断。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch"
|
||||
|
||||
@@ -47,27 +47,27 @@ def test_decimal_scale_equality_is_exact():
|
||||
assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00"))
|
||||
|
||||
|
||||
def test_zero_receipt_quantity_rejected():
|
||||
def test_zero_movement_quantity_rejected():
|
||||
"""收料数量为 0 非法。"""
|
||||
with pytest.raises(QuantityValidationError):
|
||||
validate_receipt_quantity(Decimal("0"))
|
||||
validate_inbound_quantity(Decimal("0"))
|
||||
|
||||
|
||||
def test_negative_receipt_quantity_rejected():
|
||||
def test_negative_movement_quantity_rejected():
|
||||
"""收料数量为负数非法。"""
|
||||
with pytest.raises(QuantityValidationError):
|
||||
validate_receipt_quantity(Decimal("-5"))
|
||||
validate_inbound_quantity(Decimal("-5"))
|
||||
|
||||
|
||||
def test_non_numeric_quantity_rejected():
|
||||
"""非数字数量非法(解析层不得静默截断)。"""
|
||||
with pytest.raises(QuantityValidationError):
|
||||
validate_receipt_quantity("abc")
|
||||
validate_inbound_quantity("abc")
|
||||
|
||||
|
||||
def test_string_numeric_quantity_normalized():
|
||||
"""字符串数字归一化为 Decimal 后参与严格比较。"""
|
||||
assert validate_receipt_quantity("1200") == Decimal("1200")
|
||||
assert validate_inbound_quantity("1200") == Decimal("1200")
|
||||
assert strict_quantities_equal("1200", Decimal("1200"))
|
||||
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ def _cap_deps(file, gw):
|
||||
|
||||
|
||||
def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
"""成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。"""
|
||||
"""圈中行的库存查询经网关;严格数量匹配仍由领域控制。"""
|
||||
gw = FakeGateway(inventory={
|
||||
("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200",
|
||||
("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200",
|
||||
@@ -70,17 +70,21 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
assert item.from_quantity == Decimal("1200")
|
||||
|
||||
|
||||
def test_not_matured_not_queried(app, same_day_receipt_file):
|
||||
"""当天收料(not_matured)不查外部系统——网关零调用。"""
|
||||
def test_same_day_data_queried_through_gateway(app, same_day_inbound_file):
|
||||
"""【成熟退役 2026-10-16】当天异动数据照常经网关查询(无免查日期)。
|
||||
|
||||
[断言意图] 夹具未种库存 → 行落 blocked_inventory_not_found;关键契约是
|
||||
网关调用必须发生——日期不再构成评估前置过滤。
|
||||
"""
|
||||
gw = FakeGateway(inventory={})
|
||||
deps = _cap_deps(same_day_receipt_file, gw)
|
||||
deps = _cap_deps(same_day_inbound_file, gw)
|
||||
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
|
||||
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
|
||||
)
|
||||
assert gw.calls == []
|
||||
assert result.items[0].result == "not_matured"
|
||||
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
|
||||
assert result.items[0].result == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""首页队列「待匹配」桶与执行门禁改锚测试(Task 12,规格 §10,D16/D17)。
|
||||
|
||||
用途:锁定两块契约——
|
||||
①「待匹配」桶口径(D16):档记录 ∈ 启用类型范围并集、record_kind='receipt'、
|
||||
①「待匹配」桶口径(D16):档记录 ∈ 启用类型范围并集、record_kind='inbound'、
|
||||
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致);
|
||||
匹配圈定后离开、取消匹配释放后回归;无 item_id 不可勾选执行;
|
||||
②file_current 门禁改锚(规格 §10):行当前性 = item → 档记录 file_sha256 ==
|
||||
@@ -38,7 +38,7 @@ NOW = datetime(2026, 10, 14, 12, 0, 0)
|
||||
|
||||
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
|
||||
sha: str = "a" * 64, row_no: int = 1, source_code: str = "DBS-AWSBI",
|
||||
record_kind: str = "receipt", movement_date: str | None = "2026-10-13",
|
||||
record_kind: str = "inbound", movement_date: str | None = "2026-10-13",
|
||||
transfer_executed: bool = False, executed_doc_no: str | None = None):
|
||||
"""种子一条档记录(缺省=默认类型范围内的收料记录,与 test_requery_scope 同款)。"""
|
||||
row = TransferMovementLedger(
|
||||
@@ -140,11 +140,11 @@ def test_pending_match_bucket_excludes_sealed_shipment_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="shipment") # 出货记录(一期不进桶)
|
||||
_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) # 收料日期空值(不进圈定)
|
||||
|
||||
# [断言意图] 桶只收「启用类型范围并集内、receipt、未封存、有收料日期、无 items」的档记录。
|
||||
# [断言意图] 桶只收「启用类型范围并集内、inbound、未封存、有异动日期、无 items」的档记录。
|
||||
assert _pending_doc_nos() == {"HOM-1"}
|
||||
|
||||
|
||||
@@ -197,10 +197,10 @@ def _seed_ready_item_with_ledger(sha: str = "a" * 64):
|
||||
matching_id=None, run_id=None, ledger_record_id=record.id,
|
||||
source_code="DBS-AWSBI", invoice_no=record.doc_no,
|
||||
material_no="MAT-1", material_name="物料1", specification="",
|
||||
receipt_date="2026-10-13", status="ready_to_execute", result_code=None,
|
||||
movement_date="2026-10-13", status="ready_to_execute", result_code=None,
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="100", external_quantity="100",
|
||||
lot_no="LOT-1", receipt_warehouse_code="", unit="PCS",
|
||||
movement_quantity="100", external_quantity="100",
|
||||
lot_no="LOT-1", movement_warehouse_code="", unit="PCS",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 1,
|
||||
"file_version": "v1", "file_sha256": sha}],
|
||||
inventory_checked_at=NOW,
|
||||
|
||||
@@ -35,8 +35,8 @@ def _seed(scope_sources, matching_no):
|
||||
matching = TransferMatching(
|
||||
matching_no=matching_no, run_id=run.id, business_date="2026-09-24",
|
||||
status="success",
|
||||
scope_json={"source_codes": scope_sources, "receipt_date_from": None,
|
||||
"receipt_date_to": None, "transfer_type": "in_transit_to_hub"},
|
||||
scope_json={"source_codes": scope_sources, "movement_date_from": None,
|
||||
"movement_date_to": None, "transfer_type": "in_transit_to_hub"},
|
||||
file_snapshot_json={}, mapping_version="v0", strategy_version="v0",
|
||||
counts_json={}, estimated_transfer_quantity="0",
|
||||
estimated_external_write_count=0, matching_hash="sha256:x",
|
||||
@@ -53,10 +53,10 @@ def _seed_row(source_code, invoice_no, lot_no, matching=None):
|
||||
matching_id=matching.id if matching is not None else None,
|
||||
source_code=source_code, invoice_no=invoice_no,
|
||||
material_no="MAT-1", material_name="n", specification="",
|
||||
receipt_date="2026-09-20", status="blocked_recoverable",
|
||||
movement_date="2026-09-20", status="blocked_recoverable",
|
||||
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
|
||||
from_warehouse="W-FROM", to_warehouse="W-TO", receipt_quantity="36",
|
||||
external_quantity="30", lot_no=lot_no, receipt_warehouse_code="W1",
|
||||
from_warehouse="W-FROM", to_warehouse="W-TO", movement_quantity="36",
|
||||
external_quantity="30", lot_no=lot_no, movement_warehouse_code="W1",
|
||||
unit="PCS", raw_lines_json=[],
|
||||
)
|
||||
db.session.add(row)
|
||||
|
||||
@@ -39,9 +39,9 @@ NOW = datetime(2026, 10, 14, 12, 0, 0)
|
||||
|
||||
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
|
||||
sha: str = "a" * 64, row_no: int = 1) -> TransferMovementLedger:
|
||||
"""种子一条收料档记录(DBS-AWSBI / receipt / 2026-10-13)。"""
|
||||
"""种子一条入站档记录(DBS-AWSBI / inbound / 2026-10-13)。"""
|
||||
row = TransferMovementLedger(
|
||||
source_code="DBS-AWSBI", record_kind="receipt",
|
||||
source_code="DBS-AWSBI", record_kind="inbound",
|
||||
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
|
||||
material_code="MAT-1", material_name="物料1", specification="",
|
||||
lot_no=lot_no, quantity=quantity, unit="PCS",
|
||||
@@ -69,8 +69,8 @@ def _seed_matching(matching_no: str) -> TransferMatching:
|
||||
scope_json={
|
||||
"transfer_type": "in_transit_to_hub",
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"receipt_date_from": None,
|
||||
"receipt_date_to": None,
|
||||
"movement_date_from": None,
|
||||
"movement_date_to": None,
|
||||
"scope_rules": [{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}],
|
||||
"scope_note": "doc_no prefix HOM|HOX|WTP",
|
||||
"transform_rules": [],
|
||||
@@ -91,10 +91,10 @@ def _seed_own_item(matching: TransferMatching, ledger: TransferMovementLedger) -
|
||||
matching_id=matching.id, run_id=matching.run_id, ledger_record_id=ledger.id,
|
||||
source_code="DBS-AWSBI", invoice_no=ledger.doc_no,
|
||||
material_no="MAT-1", material_name="物料1", specification="",
|
||||
receipt_date="2026-10-13", status="blocked_recoverable",
|
||||
movement_date="2026-10-13", status="blocked_recoverable",
|
||||
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", receipt_quantity=ledger.quantity,
|
||||
external_quantity="30", lot_no=ledger.lot_no, receipt_warehouse_code="",
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", movement_quantity=ledger.quantity,
|
||||
external_quantity="30", lot_no=ledger.lot_no, movement_warehouse_code="",
|
||||
unit="PCS", raw_lines_json=[{"sheet": "Receipt", "row_no": ledger.row_no,
|
||||
"file_version": "v1", "file_sha256": ledger.file_sha256}],
|
||||
)
|
||||
@@ -118,7 +118,7 @@ def test_requery_births_item_for_new_ledger_record(app):
|
||||
assert born.matching_id == matching.id
|
||||
assert born.run_id is None # 执行 Run 关联归 orchestrator
|
||||
assert born.ledger_record_id == new_record.id
|
||||
assert born.receipt_quantity == "50"
|
||||
assert born.movement_quantity == "50"
|
||||
assert born.status == "matching" and born.result_code == "pending_stock_check" # 待查态
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ def test_requery_refreshes_item_when_ledger_evidence_changed(app):
|
||||
requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1")
|
||||
|
||||
db.session.refresh(item)
|
||||
assert item.receipt_quantity == "180" # [断言意图] 证据刷新
|
||||
assert item.movement_quantity == "180" # [断言意图] 证据刷新
|
||||
assert item.material_name == "改名物料" # [断言意图] 展示字段随档换新
|
||||
assert item.status == "matching" and item.result_code == "pending_stock_check" # 重置待查
|
||||
assert item.external_quantity is None and item.inventory_checked_at is None # 旧库存作废
|
||||
@@ -172,7 +172,7 @@ def test_requery_skips_file_removed_rows(app):
|
||||
record = _seed_ledger("HOM-1")
|
||||
removed = _seed_own_item(matching, record)
|
||||
removed.result_code = "blocked_file_removed"
|
||||
removed.result_message = "receipt row removed from latest file"
|
||||
removed.result_message = "inbound row removed from latest file"
|
||||
db.session.flush()
|
||||
deps, _, _ = make_transfer_deps()
|
||||
|
||||
@@ -198,7 +198,7 @@ def test_retry_item_rejects_file_removed_row(app):
|
||||
record = _seed_ledger("HOM-1")
|
||||
row = _seed_own_item(matching, record)
|
||||
row.result_code = "blocked_file_removed"
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
row.result_message = "inbound row removed from latest file"
|
||||
db.session.flush()
|
||||
deps, _, _ = make_transfer_deps()
|
||||
|
||||
@@ -215,7 +215,7 @@ def test_requery_by_ids_rejects_file_removed_row(app):
|
||||
record = _seed_ledger("HOM-1")
|
||||
row = _seed_own_item(matching, record)
|
||||
row.result_code = "blocked_file_removed"
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
row.result_message = "inbound row removed from latest file"
|
||||
db.session.flush()
|
||||
deps, _, _ = make_transfer_deps()
|
||||
|
||||
@@ -227,7 +227,7 @@ def test_requery_by_ids_rejects_file_removed_row(app):
|
||||
|
||||
def test_requery_never_touches_terminal_rows(app):
|
||||
# [断言意图·Critical-1] 部分行已 SUCCESS 的匹配 + 档证据变化 + 重查:
|
||||
# SUCCESS 行原样(status/result/updated_at/receipt_quantity 均不变,防已执行
|
||||
# SUCCESS 行原样(status/result/updated_at/movement_quantity 均不变,防已执行
|
||||
# 行被重置复活 → 二次写 ERP);非终态行照常刷新重置。
|
||||
matching = _seed_matching("MTG-T1")
|
||||
rec1 = _seed_ledger("HOM-1", quantity="100")
|
||||
@@ -239,7 +239,7 @@ def test_requery_never_touches_terminal_rows(app):
|
||||
done.result_message = None
|
||||
db.session.flush()
|
||||
frozen = (done.status, done.result_code, done.result_message,
|
||||
done.updated_at, done.receipt_quantity, done.external_quantity)
|
||||
done.updated_at, done.movement_quantity, done.external_quantity)
|
||||
|
||||
rec1.quantity = "150" # 档证据变化(两行同批)
|
||||
rec2.quantity = "999"
|
||||
@@ -253,10 +253,10 @@ def test_requery_never_touches_terminal_rows(app):
|
||||
blocked = db.session.get(TransferInvoiceItem, blocked.id)
|
||||
# [断言意图] 终态行零写入:含 updated_at 在内全部字段保持原值。
|
||||
assert (done.status, done.result_code, done.result_message,
|
||||
done.updated_at, done.receipt_quantity, done.external_quantity) == frozen
|
||||
done.updated_at, done.movement_quantity, done.external_quantity) == frozen
|
||||
assert done.status == "success"
|
||||
# [断言意图] 非终态行正常对账:证据刷新 + 重置待查。
|
||||
assert blocked.receipt_quantity == "150"
|
||||
assert blocked.movement_quantity == "150"
|
||||
assert blocked.status == "matching" and blocked.result_code == "pending_stock_check"
|
||||
assert blocked.external_quantity is None and blocked.inventory_checked_at is None
|
||||
|
||||
|
||||
@@ -271,7 +271,7 @@ def _wtp_lot_matching(transfer_db):
|
||||
file_dict = {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_purpose": "inbound",
|
||||
"file_no": "REC-20260806-900",
|
||||
"file_version": "v9",
|
||||
"checksum": "e" * 64,
|
||||
|
||||
@@ -63,7 +63,7 @@ def test_fixed_source_uses_single_mapping_in_transit_code(app):
|
||||
assert route.external_org == 'TGHX'
|
||||
|
||||
|
||||
def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
|
||||
def test_inventory_match_prefers_inbound_warehouse_exact_mapping(app):
|
||||
"""inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
||||
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
||||
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
||||
依赖:schedule.job_registry、receipt_trigger_service、in_transit_transfer_job。
|
||||
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
||||
"""
|
||||
|
||||
@@ -89,10 +89,10 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
|
||||
return source
|
||||
|
||||
|
||||
def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
|
||||
def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
|
||||
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
|
||||
from app.models import ShippingReceiptReportConfig
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
||||
|
||||
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
|
||||
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
|
||||
@@ -103,7 +103,7 @@ def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, tr
|
||||
))
|
||||
transfer_db.session.commit()
|
||||
|
||||
result = list_receipt_capable_source_codes()
|
||||
result = list_inbound_capable_source_codes()
|
||||
assert "CRANE_SGP" in result
|
||||
assert "DBS_OFF" not in result
|
||||
assert "CRANE_NOCONF" not in result
|
||||
@@ -116,7 +116,7 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
from app.models import ScheduleTask
|
||||
from app.services.schedule.in_transit_transfer_job import _wanted_source_codes
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
|
||||
empty = ScheduleTask(job_params={"source_codes": []})
|
||||
assert _wanted_source_codes(empty) == ["CRANE_SGP", "DBS_HUB"]
|
||||
explicit = ScheduleTask(job_params={"source_codes": ["DBS_HUB"]})
|
||||
@@ -130,7 +130,7 @@ def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
@@ -147,8 +147,8 @@ def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
assert captured["receipt_date_from"] is None
|
||||
assert captured["receipt_date_to"] is None
|
||||
assert captured["movement_date_from"] is None
|
||||
assert captured["movement_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recover_history"] is True
|
||||
assert run.response_summary_json["domain_notification_managed"] is True
|
||||
@@ -164,7 +164,7 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
@@ -181,8 +181,8 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
|
||||
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
|
||||
assert captured["business_date"] == "2026-10-12"
|
||||
assert captured["receipt_date_from"] == "2026-10-08"
|
||||
assert captured["receipt_date_to"] == "2026-10-10"
|
||||
assert captured["movement_date_from"] == "2026-10-08"
|
||||
assert captured["movement_date_to"] == "2026-10-10"
|
||||
|
||||
|
||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
@@ -190,7 +190,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||
@@ -205,7 +205,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
assert results == []
|
||||
assert any("收料日期起点" in e for e in errors)
|
||||
assert any("异动日期起点" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||
@@ -213,7 +213,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:小数偏移同样快速失败。
|
||||
assert any("收料日期终点" in e for e in errors)
|
||||
assert any("异动日期终点" in e for e in errors)
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
@@ -221,7 +221,7 @@ def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
@@ -245,7 +245,7 @@ def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
|
||||
@@ -185,8 +185,8 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
clear_receipt_parse_failure,
|
||||
record_receipt_parse_failure,
|
||||
clear_inbound_parse_failure,
|
||||
record_inbound_parse_failure,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
|
||||
@@ -199,12 +199,12 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
||||
)
|
||||
db.session.add(report)
|
||||
db.session.commit()
|
||||
record_receipt_parse_failure(
|
||||
record_inbound_parse_failure(
|
||||
report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="bad",
|
||||
)
|
||||
db.session.commit()
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "parse_failed"
|
||||
clear_receipt_parse_failure(report=report)
|
||||
clear_inbound_parse_failure(report=report)
|
||||
db.session.commit()
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
|
||||
|
||||
@@ -218,3 +218,32 @@ def test_empty_unit_is_no_data(app, receipt_unit_run):
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'no_data'
|
||||
assert status['has_ready_file'] is False
|
||||
|
||||
|
||||
def test_stale_orphan_unit_sweeps_projection_to_failed(app):
|
||||
"""孤儿单元(按需触发无排程)超时回收后,投影 fetching 翻转为 failed。
|
||||
|
||||
网页异常关闭事故回归(2026-10-16):按需触发的单元 schedule_run_id=NULL,
|
||||
回收扫描覆盖前投影永久 fetching、前端重试按钮(file_status !== 'fetching'
|
||||
门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa',
|
||||
config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5),
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching'
|
||||
# [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁
|
||||
# (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。
|
||||
assert recover_all_stale_orphan_receipt_units() == 1
|
||||
db.session.expire_all()
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'
|
||||
@@ -26,7 +26,7 @@ pytestmark = pytest.mark.pure_unit
|
||||
|
||||
PROMPT_STATUSES = {
|
||||
"file_pending", "file_ready", "matching", "ready_to_execute", "executing",
|
||||
"success", "duplicate_success", "blocked_recoverable", "not_matured",
|
||||
"success", "duplicate_success", "blocked_recoverable",
|
||||
"result_unknown", "manually_closed", "cancelled", "notification_failed",
|
||||
}
|
||||
|
||||
@@ -102,11 +102,6 @@ def test_unknown_status_rejected():
|
||||
assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value)
|
||||
|
||||
|
||||
def test_not_matured_has_no_outgoing_edges():
|
||||
"""not_matured 无出边:当天不得查询 外部系统、不得生成调拨单。"""
|
||||
assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset()
|
||||
|
||||
|
||||
def test_run_transition_queued_to_executing_path():
|
||||
"""Run 生命周期:queued → preparing_files → matching → ready_to_execute → executing。"""
|
||||
assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS)
|
||||
|
||||
@@ -18,17 +18,20 @@ from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.models.in_transit_transfer import TransferMovementLedger
|
||||
|
||||
# 自然键成分(幂等增量落地的去重键,规格 §4.2):全部 NOT NULL,可空成分 default ''。
|
||||
# 自然键成分(幂等增量落地的去重键,规格 §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 逃逸唯一比对)。
|
||||
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_CONSTRAINT = 'uq_transfer_movement_ledger_natural_key'
|
||||
|
||||
# 规格 §4.2 全部业务/证据列(除自然键成分与回写布尔外一律 nullable)。
|
||||
NULLABLE_BUSINESS_COLUMNS = (
|
||||
'material_code', 'material_name', 'specification', 'lot_no', 'quantity', 'unit',
|
||||
'material_code', 'material_name', 'specification', 'quantity', 'unit',
|
||||
'warehouse_code', 'storage_code', 'movement_date',
|
||||
'order_type', 'odm_id', 'odm_name', 'carton_id', 'pallet_id',
|
||||
'order_type', 'odm_id', 'odm_name', 'pallet_id',
|
||||
'doc_nature', 'movement_type', 'reason_code', 'source_ref_no', 'partner_code', 'remark',
|
||||
'source_file_id', 'file_version', 'file_sha256', 'sheet_name', 'row_no',
|
||||
'executed_doc_no',
|
||||
@@ -46,26 +49,27 @@ def _column_map() -> dict:
|
||||
|
||||
|
||||
def test_table_name_and_natural_key_constraint(app_ctx):
|
||||
"""表名固定;自然键六成分构成 uq_transfer_movement_ledger_natural_key 唯一约束。"""
|
||||
"""表名固定;自然键八成分(tt14 扩维 carton_id/lot_no)构成唯一约束。"""
|
||||
assert TransferMovementLedger.__tablename__ == 'transfer_movement_ledger'
|
||||
constraints = {
|
||||
c.name: [col.name for col in c.columns]
|
||||
for c in TransferMovementLedger.__table__.constraints
|
||||
if c.name
|
||||
}
|
||||
assert constraints[NATURAL_KEY_CONSTRAINT] == list(NATURAL_KEY_COLUMNS)
|
||||
assert constraints[NATURAL_KEY_CONSTRAINT] == list(
|
||||
NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS,
|
||||
)
|
||||
|
||||
|
||||
def test_natural_key_columns_not_null_with_empty_default(app_ctx):
|
||||
"""自然键成分全部 NOT NULL;line_seq/in_out_flag 等可空成分 default ''。"""
|
||||
"""自然键 8 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
|
||||
cols = _column_map()
|
||||
for name in NATURAL_KEY_COLUMNS:
|
||||
for name in NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS:
|
||||
assert cols[name].nullable is False, f"{name} 必须参与自然键即 NOT NULL"
|
||||
assert cols['line_seq'].default.arg == ''
|
||||
assert cols['in_out_flag'].default.arg == ''
|
||||
# 与 TransferInvoiceItem 同约定:空值成分以空串入库(唯一约束可比)。
|
||||
assert cols['line_seq'].server_default.arg == ''
|
||||
assert cols['in_out_flag'].server_default.arg == ''
|
||||
# 与落档链路同口径:可空语义成分以空串入库(唯一约束可比,防 PG NULL 逃逸)。
|
||||
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no'):
|
||||
assert cols[name].default.arg == ''
|
||||
assert cols[name].server_default.arg == ''
|
||||
|
||||
|
||||
def test_business_columns_nullable_and_types(app_ctx):
|
||||
@@ -74,7 +78,7 @@ def test_business_columns_nullable_and_types(app_ctx):
|
||||
for name in NULLABLE_BUSINESS_COLUMNS:
|
||||
assert cols[name].nullable is True, f"{name} 为可空业务列"
|
||||
assert cols['quantity'].type.length == 40 # 数量 Decimal 文本,与 items 同约定
|
||||
assert cols['movement_date'].type.length == 16 # 日期文本,与 items.receipt_date 同约定
|
||||
assert cols['movement_date'].type.length == 16 # 日期文本,与 items.movement_date 同约定
|
||||
assert cols['remark'].type.python_type is str # 预留列 remark 为 Text
|
||||
|
||||
|
||||
@@ -137,7 +141,11 @@ def test_ledger_roundtrip_with_defaults(transfer_db):
|
||||
|
||||
|
||||
def test_duplicate_natural_key_rejected(transfer_db):
|
||||
"""自然键唯一约束 DB 兜底:同 (source, kind, doc, line, seq, flag) 二次落地必须失败。"""
|
||||
"""自然键唯一约束 DB 兜底:同八成分二次落地必须失败。
|
||||
|
||||
carton_id/lot_no(R7)与 line_seq/in_out_flag 同口径:ORM default '' + DB
|
||||
server_default '',未传维度列的行以空串入键即可触发约束。
|
||||
"""
|
||||
def _make() -> TransferMovementLedger:
|
||||
return TransferMovementLedger(
|
||||
source_code='DBS-AWSBI',
|
||||
|
||||
@@ -95,7 +95,7 @@ def test_missing_unit_still_parses():
|
||||
_row(1, "HOM-901"),
|
||||
_row(2, "HOM-902", unit=" "),
|
||||
])
|
||||
# [断言意图] 缺列与纯空白等价归一为空串,解析不抛 ReceiptFileSchemaError。
|
||||
# [断言意图] 缺列与纯空白等价归一为空串,解析不抛 MovementFileSchemaError。
|
||||
assert [row.unit for row in parsed] == ["", ""]
|
||||
assert [row.invoice_no for row in parsed] == ["HOM-901", "HOM-902"]
|
||||
|
||||
@@ -186,15 +186,15 @@ def test_matching_hash_freezes_unit_value_out_of_snapshot(app):
|
||||
assert hash_kg == hash_pcs
|
||||
|
||||
|
||||
def test_matching_hash_unchanged_when_unit_backfilled_on_not_matured_rows(app):
|
||||
"""未成熟行补 unit 前后 Hash 不变:既有成熟过滤先行,unit 追加校验不扰动历史行结果。"""
|
||||
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"),
|
||||
))
|
||||
deps_after, _erp_b, _rpa = make_transfer_deps(_file(
|
||||
_row(1, "HOM-901", unit="KG", movement_date="2026-08-06"),
|
||||
))
|
||||
seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次(当日收料 → 未成熟)
|
||||
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
|
||||
hash_after = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_after, transfer_type="in_transit_to_hub").summary.matching_hash
|
||||
# [断言意图] 口径冻结锁定:对同一行集补 unit 列,历史预检(匹配)哈希不变。
|
||||
@@ -222,10 +222,10 @@ def test_invoice_item_unit_column_roundtrip(transfer_db):
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no=invoice_no,
|
||||
material_no="MAT-001",
|
||||
receipt_date="2026-08-05",
|
||||
movement_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="100",
|
||||
movement_quantity="100",
|
||||
status="ready_to_execute",
|
||||
unit=unit,
|
||||
raw_lines_json=[],
|
||||
|
||||
Reference in new issue
Block a user