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:
hugo committed 2026-10-16 19:43:49 +08:00
1 parent 43dceaf027
commit 8102a1fe44
151 files changed
+8057 -2382

No files matched your search

+265 -35
View File
@@ -1,14 +1,17 @@
"""在途调拨匹配 API 契约测试(L2,Flask test client)。
用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与
GET /matchings/{id} 进度恢复;无权限 403、未认证 401。
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。
GET /matchings/{id} 进度恢复;无权限 403、未认证 401;
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7)。
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes、factories。
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
in_transit_transfer Agent 授权校验。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
@@ -422,18 +425,18 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran
assert audit.run_no == run_no
def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
"""下载收料来源文件 → 200(zip),记录访问审计。"""
def test_inbound_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
"""下载出入站来源文件 → 200(zip),记录访问审计。"""
_create_matching(client, admin_headers)
executed = _execute_ready_items(app, client, admin_headers)
run_no = executed.get_json()["data"]["run_no"]
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
response = client.get(f"{API_PREFIX}/runs/{run_no}/inbound-files", headers=admin_headers)
assert response.status_code == 200
assert response.content_type.startswith("application/zip")
with app.app_context():
from app.models import TransferAuditEvent
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first()
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_INBOUND_FILES_DOWNLOADED").first()
assert audit is not None
@@ -458,7 +461,7 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_
_create_matching(client, admin_headers)
executed = _execute_ready_items(app, client, admin_headers)
run_no = executed.get_json()["data"]["run_no"]
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
for path in (f"{API_PREFIX}/runs/{run_no}/inbound-files",
f"{API_PREFIX}/runs/{run_no}/external-inventory",
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
response = client.get(path, headers=unauthorized_headers)
@@ -512,6 +515,118 @@ def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthor
assert response.status_code == 403
def test_backlog_pagination_envelope_and_compat(app, transfer_db, client, admin_headers, transfer_deps):
"""GET /backlog 分页 envelope 与无参兼容:带 page/page_size 回
{items,total,page,page_size},无参保持历史全量数组(向后兼容口径)。"""
_create_matching(client, admin_headers)
with app.app_context():
from app.models import TransferInvoiceItem
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
item.status = "blocked_recoverable"
item.result_code = "blocked_quantity_mismatch"
db.session.commit()
# 无参 → 历史数组形状(向后兼容;现有前端/测试依赖不破)。
legacy = client.get(f"{API_PREFIX}/backlog", headers=admin_headers)
assert legacy.status_code == 200
assert isinstance(legacy.get_json()["data"], list)
# 带分页参数 → envelope;单行池:首页 1 行、total=1。
paged = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=1&result_filter=recoverable",
headers=admin_headers,
)
assert paged.status_code == 200
data = paged.get_json()["data"]
assert set(data.keys()) == {"items", "total", "page", "page_size"}
assert len(data["items"]) == 1 and data["items"][0]["invoice_no"] == "HOM-001"
assert data["total"] == 1 and data["page"] == 1 and data["page_size"] == 1
# 越界页:offset 超出 total → 空切片(分页推进语义)。
page2 = client.get(
f"{API_PREFIX}/backlog?page=2&page_size=1&result_filter=recoverable",
headers=admin_headers,
).get_json()["data"]
assert page2["items"] == [] and page2["total"] == 1
def test_backlog_result_filter_and_keyword_pushdown(app, transfer_db, client, admin_headers, transfer_deps):
"""GET /backlog 筛选下推:result_filter 白名单切片、keyword 跨四字段子串、
白名单外 400(fail-closed)。"""
_create_matching(client, admin_headers)
with app.app_context():
from app.models import TransferInvoiceItem
first = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
first.status = "blocked_recoverable"
first.result_code = "blocked_quantity_mismatch"
# 第二种池内状态:把可执行行翻成人工关闭(进池、落 closed 切片)。
second = TransferInvoiceItem.query.filter_by(invoice_no="HOX-002").first()
second.status = "manually_closed"
second.result_message = "线下处理"
db.session.commit()
recoverable = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=50&result_filter=recoverable",
headers=admin_headers,
).get_json()["data"]
assert {entry["invoice_no"] for entry in recoverable["items"]} == {"HOM-001"}
assert recoverable["total"] == 1
closed = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=50&result_filter=closed",
headers=admin_headers,
).get_json()["data"]
assert {entry["invoice_no"] for entry in closed["items"]} == {"HOX-002"}
keyword = client.get(
f"{API_PREFIX}/backlog?page=1&page_size=50&keyword=HOX-002",
headers=admin_headers,
).get_json()["data"]
assert {entry["invoice_no"] for entry in keyword["items"]} == {"HOX-002"}
invalid = client.get(
f"{API_PREFIX}/backlog?page=1&result_filter=bogus",
headers=admin_headers,
)
assert invalid.status_code == 400
def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client, admin_headers, monkeypatch):
"""GET /backlog/pending-match 分页 envelope 与无参兼容:带参回
{records,total,page,page_size},无参保持历史数组(圈档伪造 25 行验证切片)。"""
from types import SimpleNamespace
rows = [
SimpleNamespace(
ledger_record_id=None, id=i + 1, doc_no=f"HOM-{900 + i}",
material_code=f"MAT-{i}", material_name="未匹配物料",
movement_date="2026-08-05", source_code="DBS-AWSBI", quantity="1",
)
for i in range(25)
]
monkeypatch.setattr(
"app.services.in_transit_transfer.backlog_service.circle_ledger_records_scope_union",
lambda: rows,
)
legacy = client.get(f"{API_PREFIX}/backlog/pending-match", headers=admin_headers)
assert legacy.status_code == 200
assert isinstance(legacy.get_json()["data"], list)
assert len(legacy.get_json()["data"]) == 25
paged = client.get(
f"{API_PREFIX}/backlog/pending-match?page=2&page_size=20",
headers=admin_headers,
)
assert paged.status_code == 200
data = paged.get_json()["data"]
assert set(data.keys()) == {"records", "total", "page", "page_size"}
assert len(data["records"]) == 5 # 25 行第 2 页余量
assert data["total"] == 25 and data["page"] == 2 and data["page_size"] == 20
assert data["records"][0]["doc_no"] == "HOM-920" # 第 21 行(稳定排序切片)
def test_list_transfer_sources(app, client, admin_headers):
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
@@ -537,7 +652,7 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
# 两条路径均不触发 RPA、不返回 202/fetching)
# ---------------------------------------------------------------------------
def _seed_parse_failed_receipt_file(source_code: str):
def _seed_parse_failed_inbound_file(source_code: str):
"""造一条「当日可用但解析失败」的收料归档文件(success 单元 + parse_failed 三列)。
与 tests/services/in_transit_transfer/test_source_file_status.py 同款最小造数:
@@ -579,13 +694,13 @@ def _seed_parse_failed_receipt_file(source_code: str):
def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_headers, monkeypatch):
"""parse_failed 且有可用文件 → retry 先本地重解析(sync),不触发 RPA(200 非 202)。"""
called = {"sync": 0, "rpa": 0}
_seed_parse_failed_receipt_file("DSV360_AWSDU")
_seed_parse_failed_inbound_file("DSV360_AWSDU")
def fake_sync(*, source_code, business_date, now):
# 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回
# ready(请求会话内重查后清除并 commit,保证端点再解析可见)。
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.source_file_status import clear_receipt_parse_failure
from app.services.in_transit_transfer.source_file_status import clear_inbound_parse_failure
called["sync"] += 1
file = (
@@ -595,7 +710,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
.first()
)
if file is not None:
clear_receipt_parse_failure(report=file)
clear_inbound_parse_failure(report=file)
db.session.commit()
return True
@@ -604,7 +719,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
)
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
@@ -623,7 +738,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header
def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_headers, monkeypatch):
"""sync 返回 True 但投影仍 parse_failed → ok=False(不触发 RPA、不回 202)。"""
called = {"sync": 0, "rpa": 0}
_seed_parse_failed_receipt_file("DSV360_AWSDU")
_seed_parse_failed_inbound_file("DSV360_AWSDU")
def fake_sync(*, source_code, business_date, now):
# 断言意图:sync 返回 True 不代表投影恢复——标记未清除时端点必须如实报
@@ -636,7 +751,7 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h
fake_sync,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa",
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa",
lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"},
)
response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers)
@@ -660,7 +775,7 @@ def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers):
def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch):
"""批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。"""
"""批量端点把 source_codes 原样交给 trigger_inbound_rpa_batch 并回传结果 envelope。"""
captured: dict = {}
def fake_batch(*, source_codes, business_date, reason):
@@ -671,7 +786,7 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h
}
monkeypatch.setattr(
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch,
"app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch", fake_batch,
)
response = client.post(
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers,
@@ -681,7 +796,7 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h
body = response.get_json()["data"]
# [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。
assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"]
assert captured["reason"] == "transfer_retry_receipt"
assert captured["reason"] == "transfer_retry_inbound"
assert body["ok"] is True and body["triggered"] is True
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
@@ -833,7 +948,7 @@ def test_retrigger_endpoint_requires_authentication(client):
# T11:202 契约收口 + GET /runs/{run_no} 调拨单清单(orders)投影(D9 融合卡数据源)
# ---------------------------------------------------------------------------
def _receipt_row(row_no: int, doc_no: str, lot_no: str, material: str,
def _movement_row(row_no: int, doc_no: str, lot_no: str, material: str,
movement_date: str, quantity: str, *, unit: str = "PCS",
material_name: str | None = None) -> dict:
"""构造一条收料文件行(movement 字段键;多单场景自定义行集用)。"""
@@ -853,7 +968,7 @@ def _custom_transfer_deps(monkeypatch, rows: list[dict], stocks: list[tuple[str,
"""
file_payload = {
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
"file_purpose": "receipt", "file_no": "REC-T11", "file_version": "v11",
"file_purpose": "inbound", "file_no": "REC-T11", "file_version": "v11",
"checksum": "d" * 64, "status": "ready", "rows": rows,
}
deps, erp, _ = make_transfer_deps(file_payload)
@@ -913,9 +1028,9 @@ def test_run_projection_returns_order_list_with_multi_status(
monkeypatch,
rows=[
# 三张单:收料日期入 D1 组键 → 三个组各一单(组建单按组键升序)。
_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_receipt_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
_receipt_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-03", "300.25", unit="KG"),
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_movement_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
_movement_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-03", "300.25", unit="KG"),
],
stocks=[("MAT-001", "LOT-10", "500"), ("MAT-002", "LOT-20", "700"),
("MAT-003", "LOT-30", "300.25")],
@@ -937,7 +1052,7 @@ def test_run_projection_returns_order_list_with_multi_status(
assert len(orders) == 3
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源,
# 收料日期升序,与建单的组键序一致)。
assert [t["receipt_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
assert [t["movement_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
by_status = {t["status"]: t for t in orders}
assert set(by_status) == {"success", "business_failed", "result_unknown"}
@@ -947,11 +1062,11 @@ def test_run_projection_returns_order_list_with_multi_status(
# (+invoice_no:行级溯源收料通知号 2026-09-29 契约扩充;含 reason:框线图
# 失败行原因展示契约,控制器裁决扩充,T13-3)。
assert set(success.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 success["doc_no"].startswith("HX-CN01-OR-")
assert success["receipt_date"] == "2026-08-05"
assert success["movement_date"] == "2026-08-05"
assert success["from_warehouse"] == "DBS-TRANSIT"
assert success["to_warehouse"] == "HUB-CN01"
assert success["erp_document_no"]
@@ -997,7 +1112,7 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows(
"""复用单行集全量投影:失败单复用后,旧行与新行都在 orders.lines(D7①②)。"""
deps, erp = _custom_transfer_deps(
monkeypatch,
rows=[_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个")],
rows=[_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个")],
stocks=[("MAT-001", "LOT-10", "500")],
)
erp.write_scenarios["HOM-A"] = "business_failed"
@@ -1014,8 +1129,8 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows(
_custom_transfer_deps(
monkeypatch,
rows=[
_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_receipt_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-05", "300", unit="PCS"),
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_movement_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-05", "300", unit="PCS"),
],
stocks=[("MAT-001", "LOT-10", "500"), ("MAT-003", "LOT-30", "300")],
)
@@ -1072,7 +1187,7 @@ def _seed_document(
five = {key: (group or {}).get(key) or default for key, default in (
("source_code", "DBS-AWSBI"),
("external_org", "ORGA"),
("receipt_date", "2026-08-05"),
("movement_date", "2026-08-05"),
("from_warehouse", "DBS-TRANSIT"),
("to_warehouse", f"HUB-{doc_no}"),
)}
@@ -1096,10 +1211,10 @@ def _seed_document(
material_no=spec.get("material_no", f"MAT-{index}"),
material_name=spec.get("material_name", f"物料{index}"),
lot_no=spec.get("lot_no", "LOT-1"),
receipt_date=five["receipt_date"],
movement_date=five["movement_date"],
from_warehouse=five["from_warehouse"],
to_warehouse=five["to_warehouse"],
receipt_quantity=spec.get("quantity", "10"),
movement_quantity=spec.get("quantity", "10"),
unit=spec.get("unit", "PCS"),
status=spec.get("status", "executing"),
result_code=spec.get("result_code"),
@@ -1195,7 +1310,7 @@ def test_list_documents_order_projection_and_items(app, transfer_db, client, adm
assert data["total"] == 1
order = data["orders"][0]
# 断言意图:计划 Task 17 响应契约逐键——单头字段 + items(invoice 粒度)。
for key in ("doc_no", "submit_timestamp", "status", "status_group", "receipt_date",
for key in ("doc_no", "submit_timestamp", "status", "status_group", "movement_date",
"from_warehouse", "to_warehouse", "erp_document_no", "error_message",
"created_at", "items"):
assert key in order
@@ -1262,10 +1377,10 @@ def test_list_documents_date_range_filters_list_only(app, transfer_db, client, a
with app.app_context():
now = datetime(2026, 9, 24, 10, 0, 0)
_seed_document(transfer_db, docs_matching, "D-OLD-1", "2026-08-06 09:00:00", "business_failed",
group={"receipt_date": "2026-08-25"},
group={"movement_date": "2026-08-25"},
created_at=now - timedelta(days=30))
_seed_document(transfer_db, docs_matching, "D-NEW-1", "2026-08-06 10:00:00", "business_failed",
group={"receipt_date": "2026-09-23"},
group={"movement_date": "2026-09-23"},
created_at=now - timedelta(days=1))
transfer_db.session.commit()
@@ -1310,7 +1425,7 @@ def test_close_document_detaches_items_and_releases_group_lock(
from app.models import TransferAuditEvent, TransferDocument, TransferInvoiceItem
group = {
"source_code": "DBS-AWSBI", "external_org": "ORGA", "receipt_date": "2026-08-05",
"source_code": "DBS-AWSBI", "external_org": "ORGA", "movement_date": "2026-08-05",
"from_warehouse": "DBS-TRANSIT", "to_warehouse": "HUB-CN01",
}
with app.app_context():
@@ -1449,3 +1564,118 @@ def test_document_run_no_projection_and_audit_with_real_run(
event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_DOCUMENT_CLOSED").one()
assert event.aggregate_id == "D-RUN-1"
assert event.run_no == "RUN-DOC-REAL-1"
# ---------------------------------------------------------------------------
# 待匹配桶「清空并重新解析」(spec §6,Task 7):预检 + 执行端点
# ---------------------------------------------------------------------------
REPARSE_SOURCE = "CRANE_API"
REPARSE_OLD_SHA = "9" * 64
REPARSE_SHA_A = "a1" + "0" * 62
def _seed_reparse_endpoint_world(app, monkeypatch):
"""端点用例种子:来源+已发布入站规则+一份可用归档+一条旧映射档行。
归档字节经 FakeArchiveStorage 注入并替换 file_asset_storage.get_bytes
(单例对象级替换,service/repository 引用同源生效)。
Returns:
(archive_file, fake_storage) 元组。
"""
from tests.services.in_transit_transfer import factories
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
source, _profile = factories.seed_inbound_reparse_source(REPARSE_SOURCE)
archive = factories.seed_reparse_archive_file(
source, sha=REPARSE_SHA_A, storage_key=f"archive/{REPARSE_SOURCE}/a.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0))
fake.objects[f"archive/{REPARSE_SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-P1", "1", "I", "MAT-P1", "连接器", "LOT-P1", 500, "2026-08-05"],
])
with app.app_context():
factories.seed_reparse_ledger_row(
REPARSE_SOURCE, "ASN-P1", source_file_id=archive.id, sha=REPARSE_OLD_SHA)
return archive, fake
def test_pending_match_reparse_preview_endpoint(app, transfer_db, client, admin_headers, monkeypatch):
"""GET /backlog/pending-match/reparse-preview → 200 envelope,预检四键形状。"""
_archive, _fake = _seed_reparse_endpoint_world(app, monkeypatch)
response = client.get(
f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code={REPARSE_SOURCE}",
headers=admin_headers,
)
assert response.status_code == 200
body = response.get_json()
assert body["success"] is True and body.get("request_id")
data = body["data"]
assert set(data.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
assert data["profile"]["version"] == 1 and data["profile"]["code"]
assert data["clearable_rows"] == 1 and data["kept_rows"] == 0
assert data["files"][0]["sha256"] == REPARSE_SHA_A
assert data["files"][0]["rows"] == 1
def test_pending_match_reparse_preview_requires_source_code(app, client, admin_headers):
"""缺 source_code → 400(参数校验,envelope error)。"""
response = client.get(
f"{API_PREFIX}/backlog/pending-match/reparse-preview", headers=admin_headers)
assert response.status_code == 400
def test_pending_match_reparse_endpoint_executes_and_audits(app, transfer_db, client, admin_headers, monkeypatch):
"""POST /backlog/pending-match/reparse → 200 envelope,清空重落计数 + 审计事件。"""
from app.models import TransferAuditEvent, TransferMovementLedger
archive, _fake = _seed_reparse_endpoint_world(app, monkeypatch)
response = client.post(
f"{API_PREFIX}/backlog/pending-match/reparse", headers=admin_headers,
json={"source_code": REPARSE_SOURCE},
)
assert response.status_code == 200
body = response.get_json()
assert body["success"] is True
data = body["data"]
assert (data["cleared"], data["reinserted"]) == (1, 1)
assert data["kept_unrebuildable"] == 0
assert data["collapses"] == 0 # [断言意图] 坍缩计数随端点透出(无坍缩=0)
assert data["files"][0]["sha256"] == REPARSE_SHA_A
with app.app_context():
transfer_db.session.expire_all()
row = TransferMovementLedger.query.filter_by(
source_code=REPARSE_SOURCE, doc_no="ASN-P1").one()
# [断言意图] 新映射值随执行生效且溯源换新(真实 source_file_id/sha256)。
assert row.quantity == "500" and row.file_sha256 == REPARSE_SHA_A
assert row.source_file_id == archive.id
event = TransferAuditEvent.query.filter_by(
event_type="TRANSFER_PENDING_MATCH_REPARSED").one()
assert event.aggregate_id == REPARSE_SOURCE
assert event.after_json["operator"] == "admin"
assert event.after_json["cleared"] == 1 and event.after_json["reinserted"] == 1
def test_pending_match_reparse_requires_authentication(client):
"""未认证:预检/执行均 401(envelope error)。"""
preview = client.get(f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code=X")
execute = client.post(f"{API_PREFIX}/backlog/pending-match/reparse", json={"source_code": "X"})
assert preview.status_code == 401
assert execute.status_code == 401
def test_pending_match_reparse_forbidden_without_permission(app, client, unauthorized_headers):
"""无 in_transit_transfer Agent 权限:预检/执行均 403(越权检查)。"""
preview = client.get(
f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code=X",
headers=unauthorized_headers)
execute = client.post(
f"{API_PREFIX}/backlog/pending-match/reparse", headers=unauthorized_headers,
json={"source_code": "X"})
assert preview.status_code == 403
assert execute.status_code == 403
+5 -5
View File
@@ -695,7 +695,7 @@ def dbs_ready_file() -> dict:
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-001",
"file_version": "v3",
"checksum": "d" * 64,
@@ -723,7 +723,7 @@ def crane_ready_file() -> dict:
return {
"source_code": "CRANE-SZ",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-002",
"file_version": "v4",
"checksum": "c" * 64,
@@ -737,15 +737,15 @@ def crane_ready_file() -> dict:
@pytest.fixture
def same_day_receipt_file() -> dict:
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。
def same_day_inbound_file() -> dict:
"""含业务日期当天异动数据的文件(成熟规则已退役:当天数据正常进匹配)。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
return {
"source_code": "DBS-AWSSG",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-003",
"file_version": "v2",
"checksum": "s" * 64,
+3 -3
View File
@@ -23,12 +23,12 @@ from app.services.schedule.queue_service import (
def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch):
"""关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。
[STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service
[STEP 1] 用计数桩替换 inbound_callback_bridge.recover_stale_waiting_source_jobs(queue_service
在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。
[STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。
[STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。
"""
from app.services.in_transit_transfer import receipt_callback_bridge
from app.services.in_transit_transfer import inbound_callback_bridge
from app.services.schedule import queue_service
from app.services.shipping_notice import rpa_worker_heartbeat_alert
@@ -41,7 +41,7 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
def _fake_heartbeat(**_kwargs):
return {"skipped": True, "reason": "test_stub"}
monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(inbound_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
monkeypatch.setattr(queue_service, "_worker_initialized", False)
@@ -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,
)
@@ -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"
@@ -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
@@ -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=[],
@@ -8,6 +8,8 @@
from __future__ import annotations
import pytest
from app.models import ShippingAuditEvent, ShippingInventorySource, User
from tests.conftest import parse_api_data, parse_api_error
@@ -156,8 +158,8 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
"""创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
def _create_parsing_profile(profile_code: str, *, status: str, purpose: str):
"""创建入站/在手解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
from app import db
from app.models import ShippingInventoryParsingProfile
@@ -174,14 +176,14 @@ def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
return profile
def test_receipt_config_binds_published_movement_profile(app, client):
"""绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
def test_receipt_config_binds_published_inbound_profile(app, client):
"""绑定已发布 inbound 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement')
profile = _create_parsing_profile('CRANE_MOVE_STD', status='published', purpose='inbound')
profile_id = profile.id
payload = {**_dbs_payload(), 'parsing_profile_id': profile_id}
@@ -203,16 +205,16 @@ def test_receipt_config_binds_published_movement_profile(app, client):
assert audit.metadata_json['parsing_profile_id'] == profile_id
def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
"""draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client):
"""draft/在手用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement')
inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory')
cases = [draft.id, inventory_profile.id, 999999]
draft = _create_parsing_profile('MOVE_DRAFT', status='draft', purpose='inbound')
onhand_profile = _create_parsing_profile('INV_PUBLISHED', status='published', purpose='onhand')
cases = [draft.id, onhand_profile.id, 999999]
for profile_id in cases:
response = client.put(
@@ -221,8 +223,8 @@ def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400, f'profile_id={profile_id}'
# 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID'
# 关键断言:非"已发布 inbound"绑定必须走统一错误码,fail-closed。
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_PROFILE_INVALID'
def test_receipt_config_empty_profile_id_unbinds(app, client):
@@ -232,7 +234,7 @@ def test_receipt_config_empty_profile_id_unbinds(app, client):
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement')
profile = _create_parsing_profile('MOVE_UNBIND', status='published', purpose='inbound')
profile_id = profile.id
bound = client.put(
@@ -292,3 +294,36 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
)
assert rejected.status_code == 400
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
def test_retire_rejects_profile_bound_by_receipt_report_config(app):
"""绑定收料报表配置的 published 解析 Profile 退役必须被拒(退役守卫补查)。
背景:retire 此前只核查库存源(ShippingInventorySource)绑定,遗漏了
收料报表配置(ShippingReceiptReportConfig.parsing_profile_id)——入站文件
解析链会因规则退役静默失去规则。守卫补查后两者任一绑定都返回
SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED。
"""
from app import db
from app.models import ShippingReceiptReportConfig
from app.services.shipping_notice import inventory_parsing_profile
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
profile = _create_parsing_profile('MOVE_RETIRE_GUARD', status='published', purpose='inbound')
db.session.add(ShippingReceiptReportConfig(
inventory_source_id=source.id, parsing_profile_id=profile.id,
report_path_json={}, query_parameters_json=[],
))
db.session.commit()
profile_id = profile.id
# 关键断言:仅绑定收料配置(无库存源绑定)也必须拒绝退役,沿用既有错误码。
with pytest.raises(Exception) as exc_info:
inventory_parsing_profile.retire(profile_id)
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED'
# 关键断言:被拒后 Profile 状态保持 published,不得被半退役。
assert ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1
@@ -268,3 +268,70 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
# 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init
assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source
def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
from app import db
from app.models import ShippingAuditEvent, 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='DSV360_AWSDU').one()
# 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后
# 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。
stale_queued = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-queued', status='queued', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(minutes=5),
)
stale_processing = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-processing', status='processing', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(minutes=6),
started_at=datetime.utcnow() - timedelta(minutes=5),
)
fresh_processing = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-fresh', status='processing', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(seconds=45),
started_at=datetime.utcnow() - timedelta(seconds=30),
)
db.session.add_all([stale_queued, stale_processing, fresh_processing])
db.session.commit()
# [断言意图] 调拨工作台按需触发单元 schedule_run_id=NULL,不在 run 级扫描
# (recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;网页异常
# 关闭后回调永不到达,必须由本扫描终态化(2026-10-16 事故回归),健康单元原样;
# 与 run 级回收同口径:只标失败、写审计,绝不自动创建重试单元。
assert recover_all_stale_orphan_receipt_units() == 2
db.session.refresh(stale_queued)
db.session.refresh(stale_processing)
db.session.refresh(fresh_processing)
assert stale_queued.status == 'failed'
assert stale_queued.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
assert stale_queued.finished_at is not None
assert stale_processing.status == 'failed'
assert fresh_processing.status == 'processing'
assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0
# [断言意图] 审计须含失败结果与 before/after 快照——与 run 级回收同语义由测试锁定。
timeout_event = ShippingAuditEvent.query.filter_by(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(stale_queued.id),
).one()
assert timeout_event.result == 'failure'
assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed'
def test_orphan_receipt_recovery_is_wired_into_per_tick_maintenance():
"""哨兵回归:孤儿单元回收必须挂在每轮领取维护区(与 run 级扫描同区同轮)。"""
import inspect
from app.services.schedule import queue_service
source = inspect.getsource(queue_service)
# [断言意图] 调用点必须与 run 级收料扫描同在每轮维护区且在其后;
# 缺席或回流启动一次性分支都会复现「长驻进程期间来源永久 fetching」事故。
marker_run_scan = source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()")
assert source.index("recover_all_stale_orphan_receipt_units()") > marker_run_scan
@@ -0,0 +1,121 @@
"""
tests/test_inventory_download_name.py
用途:锁定 build_inventory_download_name 的下载展示名规范化契约——
复用企微压缩包短名规则({seq}_{source}_{warehouse})并附加 exported_at
数据截止时间点;worker 原始登记名不受影响。
依赖:models.ShippingInventoryFile、inventory_file_store.build_inventory_download_name。
逻辑:pure_unit;长名规范化、规范名幂等、exported_at → rpa_run_no → mtime 回退链、
warehouse 连续重复段去重(AWSDU_AWSDU → AWSDU)、无 seq 前缀省略、
source/warehouse/时间点任一缺失时保持原名(禁止凭空造名)、空名回退 inventory_file_no。
"""
from __future__ import annotations
import os
from datetime import datetime
import pytest
from app.models import ShippingInventoryFile
from app.services.shipping_notice.inventory_file_store import (
build_inventory_download_name,
)
pytestmark = pytest.mark.pure_unit
_WORKER_LONG_NAME = '006_inventory_RUN2026101423006F54E_DSV360_AWSDU_AWSDU_20261014231148.xlsx'
def _inv_file(**overrides) -> ShippingInventoryFile:
"""构造不落库的快照行;默认字段对齐 prod 4510042199 批次的真实登记值。"""
defaults = dict(
inventory_file_no='INV-20261014-0001',
source_file_name=_WORKER_LONG_NAME,
source_code='DSV360',
warehouse_id='AWSDU',
warehouse_code='AWSDU',
exported_at=datetime(2026, 10, 14, 23, 11, 48),
rpa_run_no='RUN2026101423006F54E',
)
defaults.update(overrides)
return ShippingInventoryFile(**defaults)
def test_worker_long_name_normalized_with_exported_at():
"""worker 长名 + exported_at → 短名 + 数据截止时间点(到分钟)。"""
name = build_inventory_download_name(
_inv_file(), source_file_name=_WORKER_LONG_NAME,
)
# 关键断言:seq 保留与企微 zip 可对应;时间点来自 exported_at 而非尾部保存时刻
assert name == '006_DSV360_AWSDU_202610142311.xlsx'
def test_canonical_name_is_idempotent():
"""已是规范名的输入必须原样返回(幂等,不二次追加时间戳)。"""
canonical = '006_DSV360_AWSDU_202610142311.xlsx'
# 关键断言:规范形态命中 _DOWNLOAD_CANONICAL_RE 后零变化
assert build_inventory_download_name(
_inv_file(), source_file_name=canonical,
) == canonical
def test_exported_at_missing_falls_back_to_run_no_timestamp():
"""exported_at 缺失时回退 rpa_run_no 内嵌 RUN 时间戳(到分钟)。"""
name = build_inventory_download_name(
_inv_file(exported_at=None), source_file_name=_WORKER_LONG_NAME,
)
# 关键断言:RUN2026101423006F54E → 202610142300(截取 12 位到分钟)
assert name == '006_DSV360_AWSDU_202610142300.xlsx'
def test_time_falls_back_to_file_mtime(tmp_path):
"""exported_at 与 rpa_run_no 均缺失时回退托管文件 mtime。"""
target = tmp_path / 'worker.xlsx'
target.write_bytes(b'x')
os.utime(target, (1770000000, 1770000000))
name = build_inventory_download_name(
_inv_file(exported_at=None, rpa_run_no=None),
source_file_name=_WORKER_LONG_NAME, path=target,
)
# 关键断言:不抛错且生成带 12 位时间点的规范名(具体值随 mtime)
assert name.count('_') >= 3 and name.endswith('.xlsx')
assert 'DSV360' in name and 'AWSDU' in name
def test_warehouse_duplicated_segments_collapsed():
"""warehouse 值自身含连续重复段(AWSDU_AWSDU)时折叠为单段。"""
name = build_inventory_download_name(
_inv_file(warehouse_id='AWSDU_AWSDU'), source_file_name=_WORKER_LONG_NAME,
)
# 关键断言:token 级连续重复去重后不出现 AWSDU_AWSDU
assert name == '006_DSV360_AWSDU_202610142311.xlsx'
def test_missing_seq_prefix_omits_seq():
"""worker 原名无数字前缀时规范名省略 seq 段而非补 000。"""
name = build_inventory_download_name(
_inv_file(source_file_name='inventory_export.xlsx'),
source_file_name='inventory_export.xlsx',
)
# 关键断言:无 seq 时以 source 开头且不产生空段
assert name == 'DSV360_AWSDU_202610142311.xlsx'
def test_insufficient_info_keeps_original_name():
"""source 缺失等信息不足时保持 worker 原名(禁止凭空造名)。"""
original = _WORKER_LONG_NAME
name = build_inventory_download_name(
_inv_file(source_code=None), source_file_name=original,
)
# 关键断言:缺 source 时零变化,避免生成无法归因的文件名
assert name == original
def test_empty_source_file_name_falls_back_to_file_no():
"""空登记名回退 inventory_file_no + 小写后缀(既有行为不变)。"""
name = build_inventory_download_name(
_inv_file(source_file_name=None), source_file_name=None,
)
# 关键断言:与改造前 resolve_task_inventory_download 的兜底行为逐字一致
assert name == 'INV-20261014-0001.xlsx'
@@ -283,39 +283,39 @@ def test_sample_analysis_rejects_invalid_file(app, tmp_path):
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
def test_profile_draft_purpose_passthrough_creates_movement_profile(app, tmp_path):
"""purpose='movement' 必须透传到解析规则:异动草稿不依赖库存字段目录与匹配键。"""
def test_profile_draft_purpose_passthrough_creates_inbound_profile(app, tmp_path):
"""purpose='inbound' 必须透传到解析规则:入站草稿不依赖库存字段目录与匹配键。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
# 关键断言:movement 映射直接用定死领域字段码作键,不需要订单匹配键。
# 关键断言:inbound 映射直接用定死领域字段码作键,不需要订单匹配键。
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'MOVE_STD', 'display_name': '收料异动标准', 'purpose': 'movement',
'profile_code': 'MOVE_STD', 'display_name': '入站解析标准', 'purpose': 'inbound',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
'match_keys': None,
}, actor_id=None)
assert profile['purpose'] == 'movement'
assert profile['purpose'] == 'inbound'
assert profile['definition']['match_keys'] == []
assert set(profile['definition']['field_mapping']) == {'doc_no', 'material_code', 'quantity', 'movement_date'}
def test_publish_movement_profile_skips_order_match_key_contract(app, tmp_path):
"""发布 movement 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
def test_publish_inbound_profile_skips_order_match_key_contract(app, tmp_path):
"""发布 inbound 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
from app.services.shipping_notice import inventory_parsing_profile
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
'profile_code': 'MOVE_PUB', 'display_name': '收料异动发布', 'purpose': 'movement',
'profile_code': 'MOVE_PUB', 'display_name': '入站解析发布', 'purpose': 'inbound',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
'match_keys': None,
}, actor_id=None)
# 关键断言:movement 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
# 关键断言:inbound 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
published = inventory_parsing_profile.publish(profile['id'], actor_id=None)
assert published['status'] == 'published'
assert published['checksum']
+274 -23
View File
@@ -1,26 +1,46 @@
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验)。
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。
用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支——
movement 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);inventory 维持既有 match_keys 校验。
并用 app fixture 校验模型 purpose 列默认 'inventory'。
依赖:inventory_parsing_profile._validate_definition(纯)、app(SQLite)。
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值经 app fixture 校验。
inbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);onhand/outbound 维持既有库存字段目录 + match_keys
校验(outbound 出站文件结构就位,暂无运行时消费方)。并用 app fixture 校验模型
purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。
依赖:inventory_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app
fixture 上下文别名)。
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值/约束经 app fixture 校验;
迁移往返按 tt13/tt14 同款模式(手工复刻前置表结构 + upgrade→downgrade→upgrade)。
"""
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
from app.core.errors import ValidationError
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition, save_draft
pytestmark = pytest.mark.pure_unit
REVISION = "tt15b6a7b8c9d0"
DOWN_REVISION = "tt14a5f6a7b8c9"
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
def _movement_definition() -> dict:
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def _inbound_definition() -> dict:
return {
'sheet_name': 'Movement',
'sheet_name': 'Inbound',
'header_row_index': 1,
'field_mapping': {
'doc_no': '单据编号',
@@ -37,33 +57,264 @@ def _movement_definition() -> dict:
}
def test_movement_definition_validates_fixed_fields():
"""movement 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
definition = _validate_definition(_movement_definition(), purpose='movement')
def test_inbound_definition_validates_fixed_fields():
"""inbound 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
definition = _validate_definition(_inbound_definition(), purpose='inbound')
assert definition['field_mapping']['doc_no'] == '单据编号'
assert definition['field_mapping']['quantity'] == '数量'
assert definition['match_keys'] == []
def test_movement_definition_missing_fixed_field_rejected():
"""movement 缺 movement_date → 阻断。"""
raw = dict(_movement_definition())
def test_inbound_definition_missing_fixed_field_rejected():
"""inbound 缺 movement_date → 阻断。"""
raw = dict(_inbound_definition())
raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='movement')
_validate_definition(raw, purpose='inbound')
def test_movement_definition_rejects_unknown_field():
"""movement 引用非定死领域字段 → 阻断。"""
raw = dict(_movement_definition())
def test_inbound_definition_rejects_unknown_field():
"""inbound 引用非定死领域字段 → 阻断。"""
raw = dict(_inbound_definition())
raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='movement')
_validate_definition(raw, purpose='inbound')
def test_model_purpose_column_defaults_to_inventory(app):
"""模型 purpose 列默认 'inventory'(既有行不回填)。"""
def test_purpose_enum_values():
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 枚举恰为三元新枚举。"""
from app.models.shipping_inventory_config import ShippingInventoryParsingProfile
col = ShippingInventoryParsingProfile.__table__.columns["purpose"]
assert col.default.arg == "onhand" and col.server_default.arg == "onhand"
check = next(c for c in ShippingInventoryParsingProfile.__table__.constraints
if getattr(c, "name", "") == "ck_shipping_inventory_parsing_profiles_purpose")
sql = str(getattr(check, "sqltext", check))
for value in ("onhand", "inbound", "outbound"):
assert value in sql
for legacy in ("'inventory'", "'movement'"):
assert legacy not in sql
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
"""构造最小化样本结构证据,使 save_draft 遵循生产环境的表头绑定门禁。"""
from app import db
from app.models import ShippingInventoryStructureAnalysis
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
file_checksum='c' * 64, file_format=file_format, analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': sheet_name, 'header_row_index': 1, 'headers': headers,
'columns': [{'header': header, 'duplicate': False} for header in headers],
}]},
suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _catalog_mapping() -> dict[str, str]:
"""以库存字段目录 ID 构造 onhand/outbound 用解析映射(目录分支端点)。"""
from app.models import ShippingInventoryField
rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()}
return {
str(rows['part_number'].id): 'Supplier Sku',
str(rows['reservation_id'].id): 'Reservation ID',
str(rows['available_qty'].id): 'Qty Available',
}
def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.INVENTORY_PARSING_PROFILE_INVALID。"""
from app import db
from app.models import ShippingOrderField
# 出站文件结构就位:outbound 走库存字段目录分支(与 onhand 同构),需行级订单匹配键。
order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string')
db.session.add(order_field)
db.session.flush()
headers = ['Supplier Sku', 'Reservation ID', 'Qty Available']
outbound = save_draft({
'profile_code': 'OUT_STD', 'display_name': '出站结构就位', 'purpose': 'outbound',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {
'header_row_index': 1,
'field_mapping': _catalog_mapping(),
'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(_catalog_mapping()))}],
},
}, actor_id=None)
assert outbound['purpose'] == 'outbound'
with pytest.raises(ValidationError) as exc_info:
save_draft({
'profile_code': 'LEGACY_MOVE', 'display_name': '旧异动用途', 'purpose': 'movement',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {'header_row_index': 1, 'field_mapping': _catalog_mapping(), 'match_keys': []},
}, actor_id=None)
# 关键断言:旧枚举 movement 已从白名单移除,fail-closed 报统一错误码。
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
def test_model_purpose_column_defaults_to_onhand(app):
"""模型 purpose 列默认 'onhand'(存量 inventory 行由 tt15 数据迁移回填)。"""
from app.models import ShippingInventoryParsingProfile
existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
assert existing is not None and existing.purpose == 'inventory'
assert existing is not None and existing.purpose == 'onhand'
def _load_migration(revision: str):
"""按 revision 加载迁移模块(test_migration_widen_transfer_run_type 同款,不加载 Flask 应用)。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{revision}_"):
spec = importlib.util.spec_from_file_location(f"migration_{revision}", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
raise AssertionError(f"migration file for revision {revision} not found")
def test_tt15_revision_chains_from_tt14_head():
"""tt15 必须存在且挂在 tt14a5f6a7b8c9(实施时实际单 head)之后,且用 batch 模式保 SQLite 往返。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{REVISION}_"):
text = path.read_text(encoding="utf-8")
assert f"revision = '{REVISION}'" in text or f'revision = "{REVISION}"' in text
assert f"down_revision = '{DOWN_REVISION}'" in text or f'down_revision = "{DOWN_REVISION}"' in text
# SQLite 不支持裸 DROP CONSTRAINT / ALTER COLUMN SET DEFAULT:必须走 batch_alter_table。
assert "batch_alter_table" in text
return
raise AssertionError(f"migration file for revision {REVISION} not found")
def _prestate_metadata() -> sa.MetaData:
"""复刻 tt15 前置(tt14 末态)的 shipping_inventory_parsing_profiles 表结构。
按建表迁移 b17e3d4c5a60 与后续加列迁移(fc1d2e3f4a5b/f83d9e0f1a2b/a4c7e9f1b2d3/
if1b2c3d4e5g)汇总列集,purpose 保持旧枚举(default 'inventory' + 旧 CHECK),
作为 tt15 往返的真实前置。历史链祖先众多(a0b1c2d3e4f6…),整链重放不成比例,
手工复刻与 tt13 前置基线做法一致。
"""
md = sa.MetaData()
sa.Table("users", md, sa.Column("id", sa.Integer(), primary_key=True))
sa.Table(
"shipping_inventory_structure_analyses", md,
sa.Column("id", sa.Integer(), primary_key=True),
)
sa.Table(
"shipping_inventory_parsing_profiles", md,
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("purpose", sa.String(length=16), nullable=False, server_default="inventory"),
sa.Column("profile_code", sa.String(length=64), nullable=False),
sa.Column("display_name", sa.String(length=128), nullable=False),
sa.Column("version", sa.Integer(), server_default="1", nullable=False),
sa.Column("status", sa.String(length=16), server_default="draft", nullable=False),
sa.Column("file_format", sa.String(length=16), server_default="xlsx", nullable=False),
sa.Column("definition_json", sa.JSON(), nullable=False),
sa.Column("checksum", sa.String(length=64), nullable=True),
sa.Column("structure_definition_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
sa.Column("exact_structure_fingerprint", sa.String(length=64), nullable=True),
sa.Column("compatibility_fingerprint", sa.String(length=64), nullable=True),
sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
sa.Column("sample_analysis_id", sa.Integer(), nullable=True),
sa.Column("sample_evidence_history_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column("published_by", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("published_at", sa.DateTime(), nullable=True),
sa.UniqueConstraint("profile_code", "version", name="uq_inventory_parsing_profiles_code_version"),
sa.CheckConstraint(
"purpose IN ('inventory', 'movement')",
name="ck_shipping_inventory_parsing_profiles_purpose",
),
sa.ForeignKeyConstraint(["sample_analysis_id"], ["shipping_inventory_structure_analyses.id"]),
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
sa.ForeignKeyConstraint(["published_by"], ["users.id"]),
)
return md
_LEGACY_ROW_COLUMNS = (
"purpose, profile_code, display_name, version, status, file_format, "
"definition_json, structure_definition_json, sample_evidence_history_json, created_at"
)
def _insert_profile(connection, *, purpose: str, profile_code: str) -> None:
"""按旧枚举直接插入一条解析规则行(旧 CHECK 放行 inventory/movement)。"""
connection.execute(sa.text(
f"INSERT INTO shipping_inventory_parsing_profiles ({_LEGACY_ROW_COLUMNS}) "
f"VALUES ('{purpose}', '{profile_code}', '{profile_code} 规则', 1, 'published', 'xlsx', "
f"'{{}}', '{{}}', '[]', '2026-01-01 00:00:00')"
))
def _purpose_by_code(connection) -> dict[str, str]:
rows = connection.execute(sa.text(
"SELECT profile_code, purpose FROM shipping_inventory_parsing_profiles"
)).fetchall()
return {code: purpose for code, purpose in rows}
def _column_default(connection, column: str) -> str:
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("shipping_inventory_parsing_profiles")}
return str(columns[column].get("default") or "")
def test_tt15_sqlite_roundtrip_upgrade_downgrade_upgrade():
"""SQLite 真实往返:upgrade 换枚举并迁数据 / downgrade 对称还原 / 再 upgrade。
[断言意图] 前置表(旧枚举 default 'inventory' + 旧 CHECK)就位后,tt15 的
batch DROP CHECK → 数据 UPDATE → ADD CHECK → SET DEFAULT 不丢列、不丢数据;
存量 inventory→onhand、movement→inbound 精确映射;新 CHECK 真实生效
(outbound 放行、旧值拒写);downgrade 对称(outbound/inbound→movement 结构就位
语义最接近),default/CHECK 翻转可回滚。
"""
engine = sa.create_engine("sqlite:///:memory:")
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
_prestate_metadata().create_all(connection)
_insert_profile(connection, purpose='inventory', profile_code='LEG_INV')
_insert_profile(connection, purpose='movement', profile_code='LEG_MOVE')
# 前置基线:旧 CHECK 放行 inventory/movement、拒新枚举。
_insert_profile(connection, purpose='movement', profile_code='BASE_MOVE')
assert "inventory" in _column_default(connection, "purpose")
migration = _load_migration(REVISION)
migration.op = operations
migration.upgrade()
# [断言意图] 数据迁移:inventory→onhand、movement→inbound。
assert _purpose_by_code(connection) == {
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
}
# [断言意图] 列默认值翻转为 'onhand'。
assert "onhand" in _column_default(connection, "purpose")
# [断言意图] 新 CHECK 真实生效:outbound 放行、旧值 inventory 拒写。
_insert_profile(connection, purpose='outbound', profile_code='NEW_OUT')
with pytest.raises(sa.exc.IntegrityError):
_insert_profile(connection, purpose='inventory', profile_code='REJECT_OLD')
migration.downgrade()
# [断言意图] downgrade 对称:onhand→inventory,inbound/outbound→movement。
assert _purpose_by_code(connection) == {
'LEG_INV': 'inventory', 'LEG_MOVE': 'movement', 'BASE_MOVE': 'movement', 'NEW_OUT': 'movement',
}
assert "inventory" in _column_default(connection, "purpose")
# [断言意图] 旧 CHECK 还原:inventory 放行、新值 onhand 拒写。
_insert_profile(connection, purpose='inventory', profile_code='BACK_INV')
with pytest.raises(sa.exc.IntegrityError):
_insert_profile(connection, purpose='onhand', profile_code='REJECT_NEW')
migration.upgrade()
assert _purpose_by_code(connection) == {
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
'NEW_OUT': 'inbound', 'BACK_INV': 'onhand',
}
assert "onhand" in _column_default(connection, "purpose")
@@ -12,6 +12,7 @@ from __future__ import annotations
import uuid
import re
from datetime import datetime
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import patch
@@ -3483,3 +3484,168 @@ def test_summary_failed_run_does_not_project_document_completed_as_upload_comple
assert leaf['user_group'] == 'failed'
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert leaf['ui_state']['primary_action']['code'] == 'reparse'
def _seed_reparse_pending_case(suffix: str):
"""构造「reparse_pending Case + 在途/终态后继 Run」的重解析盲窗现场。
返回 (user, agent, session, intake, document, source_run, case, successor_run)。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewStream
from app.services.shipping_notice.order_extraction_plan import (
ensure_order_extraction_plan,
)
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, document = _seed_run_input(suffix=suffix)
intake.source_type = 'eml'
source_run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
source_run.status = 'review_required'
source_run.phase = 'review_required'
# 服务层终态转换会释放 Intake 链接(run 终态收口);直接改状态须同样释放,
# 否则 PDF 级重解析互斥会把该文档视为仍被源 Run 占用。
for member in source_run.intakes:
member.released_at = datetime.utcnow()
plan = ensure_order_extraction_plan(source_run)
case = ShippingOrderReviewCase(
case_no=f'SORC-{suffix}',
run_id=source_run.id,
unit_id=plan.units[0].id,
document_id=document.id,
owner_user_id=user.id,
status='reparse_pending',
)
stream = ShippingOrderReviewStream(
document_id=document.id,
content_identity=(document.content_hash or suffix)[:96],
owner_user_id=user.id,
)
db.session.add_all([case, stream])
db.session.flush()
stream.current_case_id = case.id
case.stream_id = stream.id
# create_order_extraction_run 会在快照写入 review_reparse 标记
# (document_id/source_case_no),探测查询直接消费该标记。
successor_run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
reparse_of_run=source_run,
selected_document_id=document.id,
reparse_case_no=case.case_no,
)
db.session.commit()
return user, agent, session, intake, document, source_run, case, successor_run
def test_summary_projects_inflight_reparse_as_processing(app) -> None:
"""[回归] 重解析盲窗:reparse_pending Case 的后继 Run 在途时,摘要必须判
processing(处理中组)并保留接收解析阶段入口,不得下发任何动作,
也不能退化成无五阶段按钮的 waiting_human(2026-10-14 批次中心缺陷)。
"""
with app.app_context():
(
user, _agent, session, intake, document,
_source_run, _case, successor_run,
) = _seed_reparse_pending_case(suffix='SUMMARY-REPARSE-INFLIGHT')
assert successor_run.status == 'queued'
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
conv = payload['conversation_processing']
leaves = [
child
for rows in conv['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
]
leaf = next(
child for child in leaves
if int(child['source_summary']['document_id']) == int(document.id)
)
# 关键断言 1:在途重解析 = 系统处理中,不是待人工。
assert leaf['user_status'] == 'running'
assert leaf['user_group'] == 'processing'
assert leaf['status'] == 'processing'
assert leaf['stage'] == 'document_parsing'
assert conv['summary']['processing_files'] == 1
# 关键断言 2:不下发任何动作(服务端幂等复用在途后继,禁止再次提交)。
assert leaf['available_actions'] == []
assert leaf['primary_action'] is None
assert leaf['blocking_reason'] is None
# 关键断言 3:五阶段入口保留(接收解析为 current),按钮不再整排消失。
assert leaf['intake_parse_authorized'] is True
entries = leaf['ui_state']['lifecycle_entries']
assert [entry['code'] for entry in entries] == [
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
]
assert entries[0]['state'] == 'current'
assert all(entry['state'] != 'current' for entry in entries[1:])
# 后继 Run 终态失败后(未收口前):无在途事实即回落 waiting_human 原判。
successor_run.status = 'failed'
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
leaves = [
child
for rows in payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
]
leaf = next(
child for child in leaves
if int(child['source_summary']['document_id']) == int(document.id)
)
assert leaf['user_status'] == 'waiting_human'
assert leaf['user_group'] == 'waiting_human'
assert leaf['intake_parse_authorized'] is False
def test_eml_leaf_projects_inflight_reparse_as_processing(app) -> None:
"""[回归] 全量投影同判词:reparse_pending 盲窗里的无 OT 叶子必须改判
processing 并保留接收解析入口,而不是按陈旧 Unit 事实投影成无入口待人工。
"""
from app.services.shipping_notice.shipping_processing_projection import (
_conversation_projection_load_context,
)
with app.app_context():
(
user, _agent, _session, intake, document,
source_run, _case, _successor_run,
) = _seed_reparse_pending_case(suffix='EML-REPARSE-INFLIGHT')
stale_unit = source_run.extraction_plan.units[0]
load_context = _conversation_projection_load_context([intake])
leaves = _eml_aggregate_document_children(
intake=intake,
order_task_children=[],
unit_by_document_id={document.id: stale_unit},
load_context=load_context,
)
assert document.id in load_context.active_reparse_document_ids
# 关键断言 1:与摘要同判词 —— 在途重识别 = 处理中。
assert leaves[0]['user_status'] == 'running'
assert leaves[0]['user_group'] == 'processing'
assert leaves[0]['stage'] == 'document_parsing'
# 关键断言 2:不下发动作,但接收解析阶段入口保留。
assert leaves[0]['available_actions'] == []
assert leaves[0]['primary_action'] is None
assert leaves[0]['intake_parse_authorized'] is True
entries = leaves[0]['ui_state']['lifecycle_entries']
assert len(entries) == 5
assert entries[0]['code'] == 'intake_parse'
assert entries[0]['state'] == 'current'