feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动
外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
911afa0f73
commit
4c2a7e2a23
145 files changed
+11695
-4214
No files matched your search
@@ -1,36 +1,22 @@
|
||||
"""services/in_transit_transfer/backlog_reparse_service.py
|
||||
|
||||
用途:待匹配桶「清空并重新解析」(spec §6/D7,维护链路)——解析规则修改后,
|
||||
按来源把旧映射档行清空、以当前绑定入站解析规则重解析全部可重建归档、
|
||||
走常规 sync_ledger_rows 幂等重落;另提供只读预检供确认弹窗展示。
|
||||
依赖:movement_file_repository(list_reparseable_archived_files 维护通道 +
|
||||
_extract_movement_rows 归档字节提取)、evidence_sync.parse_archive_to_ledger_rows
|
||||
(解析+组装单一口径)与 _detect_natural_key_collapses/_natural_key_collapse_event
|
||||
(档自然键坍缩守卫与运行期同口径复用)、ledger_sync(sync_ledger_rows /
|
||||
RECORD_KIND_INBOUND / FileMeta)、matching_service._effective_occupancy_filter
|
||||
(占用排除口径,只读引用)、freight_rpa.reports.queries(站点与入站解析方案
|
||||
只读入口——阶段 B Task 4 收敛)、file_asset_storage、audit。
|
||||
逻辑:桶数据 100% 可由 MinIO 归档重建(原件长期保留 + 档行 sheet/row_no 溯源),
|
||||
清空不是破坏性操作而是「从证据重建」。安全不变量:先全量预解析入内存,
|
||||
按来源 + 记录类型(inbound/outbound)把旧映射档行清空、以当前绑定解析规则
|
||||
重解析全部可重建归档、走常规 sync_ledger_rows 幂等重落;另提供只读预检供
|
||||
确认弹窗展示。
|
||||
依赖:movement_file_repository(ReparseableArchiveFile + _extract_movement_rows)、
|
||||
evidence_sync.parse_archive_to_ledger_rows(解析+组装单一口径)与
|
||||
_detect_natural_key_collapses/_natural_key_collapse_event、ledger_sync
|
||||
(sync_ledger_rows / RECORD_KIND_* / FileMeta / movement_file_version)、
|
||||
matching_service.
|
||||
_effective_occupancy_filter、freight_rpa.reports.queries(站点与入站/出站
|
||||
解析方案、可重建归档清单)、file_asset_storage、audit。
|
||||
逻辑:桶数据 100% 可由 MinIO 归档重建。安全不变量:先全量预解析入内存,
|
||||
任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED),
|
||||
一行不删——解析阶段只读,删除永远发生在全部文件解析成功之后。
|
||||
删除范围三重过滤(分辨率裁决 #2):source_code + record_kind=inbound +
|
||||
transfer_executed=false + 未被有效 items 占用 + source_file_id ∈ 可重建
|
||||
归档;证据缺失行(归档已清理/过保留期/无溯源)保留并计入
|
||||
kept_unrebuildable。删除前同事务把指向待删集合的 items 的 ledger_record_id
|
||||
置 NULL(R9/方案 D:该列是普通 FK 无 ondelete,已取消匹配/已隔离 items 的
|
||||
陈旧引用会让 PG flush 撞 IntegrityError 且此后每次重建复发;置空范围严格
|
||||
限于待删集合——有效占用行的 items 不受影响,仅损失已废弃行的溯源装饰),
|
||||
计数入审计 payload unlinked_items。重落按归档时间升序逐文件
|
||||
sync_ledger_rows(FileMeta 带真实 source_file_id/file_version/sha256),
|
||||
commit 在本服务内做一次(提交归属模式同
|
||||
evidence_sync.sync_and_commit_for_callback)。审计事件
|
||||
TRANSFER_PENDING_MATCH_REPARSED:operator/source_code/files 概要/profile
|
||||
code+version/cleared/reinserted/date_skipped/kept/unlinked_items/collapses;
|
||||
坍缩键另逐条落 ledger_natural_key_collapse(与运行期 evidence_sync 同构造)。
|
||||
与运行期(evidence_sync)的边界:运行期取数带「当日 fail-closed」门禁且
|
||||
缺席不删;本服务是显式的历史重建通道,仅管理端「清空并重新解析」动作
|
||||
触发,禁止在运行期收料落地链路调用。
|
||||
一行不删。删除范围:source_code + record_kind + transfer_executed=false +
|
||||
未被有效 items 占用 + source_file_id ∈ 可重建归档。入站/出站分流仅体现在
|
||||
规则门禁(published purpose)、归档清单表与落档 record_kind;其余步骤同源。
|
||||
commit 在本服务内做一次。审计 TRANSFER_PENDING_MATCH_REPARSED 含 record_kind。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,12 +28,15 @@ from typing import Any
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferMovementLedger
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
get_inbound_parsing_profile,
|
||||
get_outbound_parsing_profile,
|
||||
get_site,
|
||||
list_reparseable_inbound_files,
|
||||
list_reparseable_outbound_files,
|
||||
)
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.evidence_sync import (
|
||||
@@ -57,23 +46,20 @@ from app.services.in_transit_transfer.evidence_sync import (
|
||||
)
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
RECORD_KIND_INBOUND,
|
||||
RECORD_KIND_OUTBOUND,
|
||||
FileMeta,
|
||||
movement_file_version,
|
||||
sync_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.matching_service import _effective_occupancy_filter
|
||||
from app.services.in_transit_transfer.movement_file_repository import (
|
||||
ReparseableArchiveFile,
|
||||
ShippingInboundFileRepository,
|
||||
_extract_movement_rows,
|
||||
)
|
||||
|
||||
# 审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内常量惯例
|
||||
# ——ledger_sync.LEDGER_CROSS_CHECK_EVENT 同款)。
|
||||
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
|
||||
# 重建中止错误码(走通用兜底文案,不新增四语言 errors.json 键——参照
|
||||
# TRANSFER.MOVEMENT_DATE_RANGE_INVALID 先例):覆盖「任一归档解析失败」与
|
||||
# 「无已发布入站解析规则(无重建通道)」两类中止。
|
||||
REPARSE_PARSE_FAILED = "TRANSFER.REPARSE_PARSE_FAILED"
|
||||
_RECORD_KINDS = frozenset({RECORD_KIND_INBOUND, RECORD_KIND_OUTBOUND})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -82,17 +68,13 @@ class ReparseOutcome:
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
cleared: 删除的旧映射档行数(三重过滤口径)。
|
||||
reinserted: 重落新插入档行数(各文件 sync_ledger_rows inserted 之和)。
|
||||
date_skipped: 重落时异动日期空值被滤行数(六分类透传,常规为 0)。
|
||||
kept_unrebuildable: 证据缺失保留行数(不可重建,原样留存)。
|
||||
unlinked_items: 删除前被置空 ledger_record_id 的废弃 items 数(R9)。
|
||||
collapses: 重落批内档自然键坍缩键数(同键异料号,第二料号行被吞——
|
||||
与运行期 evidence_sync 同一守卫口径,改模板重建恰是坍缩易发时刻)。
|
||||
files: 逐文件概要(file_id/sha256/archived_at/inserted,归档时间升序)。
|
||||
record_kind: inbound 或 outbound。
|
||||
cleared / reinserted / date_skipped / kept_unrebuildable / unlinked_items /
|
||||
collapses / files: 同入站重建语义。
|
||||
"""
|
||||
|
||||
source_code: str
|
||||
record_kind: str = RECORD_KIND_INBOUND
|
||||
cleared: int = 0
|
||||
reinserted: int = 0
|
||||
date_skipped: int = 0
|
||||
@@ -102,55 +84,73 @@ class ReparseOutcome:
|
||||
files: tuple[dict, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def _load_published_inbound_profile(source_code: str):
|
||||
"""加载来源当前绑定的「已发布 inbound」解析规则(与运行期取数同口径)。
|
||||
def _normalize_record_kind(record_kind: str | None) -> str:
|
||||
"""规范化记录类型;非法值 fail-closed。"""
|
||||
kind = str(record_kind or RECORD_KIND_INBOUND).strip() or RECORD_KIND_INBOUND
|
||||
if kind not in _RECORD_KINDS:
|
||||
raise ValidationError(
|
||||
"record_kind must be inbound or outbound",
|
||||
details={"record_kind": kind},
|
||||
)
|
||||
return kind
|
||||
|
||||
核心逻辑:来源(enabled)→ 入站配置 → parsing_profile,须 published 且
|
||||
purpose='inbound'——与 latest_ready_file 的规则门禁一致,防止重建用了
|
||||
运行期不会使用的规则口径。只读查询。
|
||||
【阶段 B Task 4】读取改经 freight_rpa.reports.queries 只读入口
|
||||
(get_site / get_inbound_parsing_profile),不再引用站点/报表模型;返回
|
||||
InboundProfileView(code/version/definition 消费面不变)。
|
||||
|
||||
def _load_published_profile(source_code: str, record_kind: str):
|
||||
"""加载来源当前绑定的「已发布」解析规则(与运行期取数同口径)。
|
||||
|
||||
核心逻辑:来源 enabled → 入站/出站配置绑定方案;须 published 且
|
||||
purpose 等于 record_kind。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
Returns:
|
||||
InboundProfileView;无启用来源/无入站配置/规则缺失或
|
||||
非 published inbound 时返回 None(=无重建通道)。
|
||||
解析方案视图;无通道时 None。
|
||||
"""
|
||||
site = get_site(source_code)
|
||||
if site is None or not site.enabled:
|
||||
return None
|
||||
profile = get_inbound_parsing_profile(source_code)
|
||||
if profile is None or profile.status != "published" or profile.purpose != "inbound":
|
||||
if record_kind == RECORD_KIND_OUTBOUND:
|
||||
profile = get_outbound_parsing_profile(source_code)
|
||||
else:
|
||||
profile = get_inbound_parsing_profile(source_code)
|
||||
if profile is None or profile.status != "published" or profile.purpose != record_kind:
|
||||
return None
|
||||
return profile
|
||||
|
||||
|
||||
def _list_reparseable_files(
|
||||
source_code: str, now: datetime, record_kind: str,
|
||||
) -> list[ReparseableArchiveFile]:
|
||||
"""按记录类型列出可重建归档,映射为维护契约 ReparseableArchiveFile。"""
|
||||
if record_kind == RECORD_KIND_OUTBOUND:
|
||||
views = list_reparseable_outbound_files(source_code, now=now)
|
||||
else:
|
||||
views = list_reparseable_inbound_files(source_code, now=now)
|
||||
return [
|
||||
ReparseableArchiveFile(
|
||||
file_id=view.file_id,
|
||||
storage_key=view.storage_key,
|
||||
sha256=view.sha256,
|
||||
file_version=movement_file_version(view.sha256),
|
||||
archived_at=view.created_at,
|
||||
original_filename=view.original_filename,
|
||||
)
|
||||
for view in views
|
||||
]
|
||||
|
||||
|
||||
def _partition_deletable(
|
||||
source_code: str, files: list[ReparseableArchiveFile],
|
||||
source_code: str,
|
||||
files: list[ReparseableArchiveFile],
|
||||
record_kind: str,
|
||||
) -> tuple[list[TransferMovementLedger], list[TransferMovementLedger]]:
|
||||
"""把「未封存且未被占用」的 inbound 档行按证据可得性分成 可删/证据缺失 两组。
|
||||
|
||||
删除候选三重过滤(分辨率裁决 #2):source_code + record_kind=inbound +
|
||||
transfer_executed=false + 未被有效 items 占用(复用
|
||||
matching_service._effective_occupancy_filter 的 NOT EXISTS 口径,只读引用);
|
||||
其中 source_file_id ∈ 可重建归档者为「可删可重建」,其余(归档已清理/
|
||||
过保留期/无溯源)为「证据缺失保留」。preview 与执行共用本口径,保证
|
||||
clearable_rows/kept_rows 与 cleared/kept_unrebuildable 1:1。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
files: list_reparseable_archived_files 产物(可重建归档清单)。
|
||||
Returns:
|
||||
(candidates, deletable)——candidates=全部未封存未占用行,deletable=其中
|
||||
证据可得(可删可重建)子集。
|
||||
"""
|
||||
"""把「未封存且未被占用」的指定 record_kind 档行按证据可得性分成两组。"""
|
||||
available_ids = {record.file_id for record in files}
|
||||
candidates = (
|
||||
TransferMovementLedger.query.filter(
|
||||
TransferMovementLedger.source_code == source_code,
|
||||
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
|
||||
TransferMovementLedger.record_kind == record_kind,
|
||||
TransferMovementLedger.transfer_executed.is_(False),
|
||||
_effective_occupancy_filter(),
|
||||
)
|
||||
@@ -160,29 +160,25 @@ def _partition_deletable(
|
||||
return candidates, deletable
|
||||
|
||||
|
||||
def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
|
||||
"""清空并重新解析预检(只读,确认弹窗数据源,spec §6 入口)。
|
||||
def preview_pending_match_reparse(
|
||||
*, source_code: str, now: datetime, record_kind: str = RECORD_KIND_INBOUND,
|
||||
) -> dict:
|
||||
"""清空并重新解析预检(只读;按 record_kind 分流入站/出站归档与档行)。
|
||||
|
||||
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」确认弹窗展示预检结果
|
||||
时调用;不要在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。
|
||||
|
||||
files[].rows 预估口径(分辨率裁决 #5,取实现简单者):现有档行按
|
||||
source_file_id 计数近似(含封存/占用行),不在预检里解析归档字节——预检
|
||||
只读零副作用,行数仅供弹窗展示,精确值以执行结果为准。
|
||||
时调用;不要在运行期落地链路调用。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 保留期判定时刻(与执行时刻口径一致)。
|
||||
now: 保留期判定时刻。
|
||||
record_kind: inbound(默认,兼容旧调用)或 outbound。
|
||||
Returns:
|
||||
{files: [{archived_at, sha256, rows}(归档时间升序)],
|
||||
profile: {code, version} | None,
|
||||
clearable_rows: 可删可重建行数,
|
||||
kept_rows: 证据缺失保留行数}
|
||||
{record_kind, files, profile, clearable_rows, kept_rows}
|
||||
"""
|
||||
files = ShippingInboundFileRepository().list_reparseable_archived_files(source_code, now)
|
||||
profile = _load_published_inbound_profile(source_code)
|
||||
_candidates, deletable = _partition_deletable(source_code, files)
|
||||
# 预估行数:现有档行按溯源文件计数(单查询分组;档行与归档文件多对一)。
|
||||
kind = _normalize_record_kind(record_kind)
|
||||
files = _list_reparseable_files(source_code, now, kind)
|
||||
profile = _load_published_profile(source_code, kind)
|
||||
_candidates, deletable = _partition_deletable(source_code, files, kind)
|
||||
file_ids = [record.file_id for record in files]
|
||||
counts: dict[int, int] = {}
|
||||
if file_ids:
|
||||
@@ -194,13 +190,14 @@ def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
|
||||
)
|
||||
.filter(
|
||||
TransferMovementLedger.source_code == source_code,
|
||||
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
|
||||
TransferMovementLedger.record_kind == kind,
|
||||
TransferMovementLedger.source_file_id.in_(file_ids),
|
||||
)
|
||||
.group_by(TransferMovementLedger.source_file_id)
|
||||
.all()
|
||||
}
|
||||
return {
|
||||
"record_kind": kind,
|
||||
"files": [
|
||||
{
|
||||
"archived_at": record.archived_at.isoformat(),
|
||||
@@ -218,40 +215,44 @@ def preview_pending_match_reparse(*, source_code: str, now: datetime) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def reparse_pending_match(*, source_code: str, operator: str, now: datetime) -> ReparseOutcome:
|
||||
"""清空并重新解析一个来源的待匹配桶(spec §6;单事务,本函数提交)。
|
||||
def reparse_pending_match(
|
||||
*,
|
||||
source_code: str,
|
||||
operator: str,
|
||||
now: datetime,
|
||||
record_kind: str = RECORD_KIND_INBOUND,
|
||||
) -> ReparseOutcome:
|
||||
"""清空并重新解析一个来源指定记录类型的待匹配桶(单事务,本函数提交)。
|
||||
|
||||
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用;
|
||||
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。
|
||||
|
||||
删除前置动作(R9/方案 D):指向待删集合的 items(已取消匹配/已隔离的废弃
|
||||
行)先同事务置空 ledger_record_id 再删行——普通 FK 无 ondelete,不置空则
|
||||
PG flush 撞 IntegrityError 且每次重建复发;有效占用行的 items 不受影响。
|
||||
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用。
|
||||
record_kind=outbound 时清出站档、用 purpose=outbound 规则与出站归档重建。
|
||||
|
||||
Raises:
|
||||
AppError: TRANSFER.REPARSE_PARSE_FAILED——①无已发布入站解析规则
|
||||
(无重建通道,删了装不回去故拒绝执行);②任一归档文件解析
|
||||
失败。两种情况整体中止且未删除任何行(先解析后删除是本函数
|
||||
的安全不变量;解析阶段只读,中止时不 rollback 不触碰调用方
|
||||
事务状态)。
|
||||
ValidationError: record_kind 非法。
|
||||
AppError: TRANSFER.REPARSE_PARSE_FAILED——无已发布对应流解析规则,或
|
||||
任一归档解析失败(整体中止且未删除任何行)。
|
||||
"""
|
||||
# [STEP 1] 重建通道与可重建文件清单(维护路径,无当日门禁;规则门禁与
|
||||
# 运行期同口径——published inbound)。无规则=无重建通道,拒绝执行。
|
||||
profile = _load_published_inbound_profile(source_code)
|
||||
kind = _normalize_record_kind(record_kind)
|
||||
# [STEP 1] 重建通道与可重建文件清单。
|
||||
profile = _load_published_profile(source_code, kind)
|
||||
if profile is None:
|
||||
raise AppError(
|
||||
code=REPARSE_PARSE_FAILED,
|
||||
message=f"reparse aborted: no published inbound parsing profile (source={source_code})",
|
||||
message=(
|
||||
f"reparse aborted: no published {kind} parsing profile "
|
||||
f"(source={source_code})"
|
||||
),
|
||||
http_status=422,
|
||||
details={"source_code": source_code, "reason": "no_published_inbound_profile"},
|
||||
details={
|
||||
"source_code": source_code,
|
||||
"record_kind": kind,
|
||||
"reason": f"no_published_{kind}_profile",
|
||||
},
|
||||
)
|
||||
repository = ShippingInboundFileRepository()
|
||||
files = repository.list_reparseable_archived_files(source_code, now)
|
||||
files = _list_reparseable_files(source_code, now, kind)
|
||||
definition = profile.definition_json or {}
|
||||
|
||||
# [STEP 2] 全量预解析入内存(归档字节→原始行经仓库 _extract_movement_rows,
|
||||
# 原始行→档行经 evidence_sync.parse_archive_to_ledger_rows 单一口径);
|
||||
# 任一失败 → AppError 整体中止(此时未执行任何删除,一行未删)。
|
||||
# [STEP 2] 全量预解析入内存;任一失败整体中止。
|
||||
prepared: list[tuple[ReparseableArchiveFile, list[dict]]] = []
|
||||
for record in files:
|
||||
try:
|
||||
@@ -263,13 +264,14 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
header_row_index=definition.get("header_row_index"),
|
||||
)
|
||||
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
|
||||
except Exception as exc: # noqa: BLE001 —— 安全不变量:任何预解析异常都不得进入删除阶段
|
||||
except Exception as exc: # noqa: BLE001 —— 安全不变量
|
||||
raise AppError(
|
||||
code=REPARSE_PARSE_FAILED,
|
||||
message=f"reparse aborted: archive file failed to parse (source={source_code})",
|
||||
http_status=422,
|
||||
details={
|
||||
"source_code": source_code,
|
||||
"record_kind": kind,
|
||||
"file_id": record.file_id,
|
||||
"storage_key": record.storage_key,
|
||||
"sha256": record.sha256,
|
||||
@@ -278,17 +280,8 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
) from exc
|
||||
prepared.append((record, assembled))
|
||||
|
||||
# [STEP 3] 删除可重建且未封存、未被有效 items 占用的 inbound 行;证据缺失
|
||||
# 行保留(kept_unrebuildable 只计数,不动行)。
|
||||
# [R9 解引用前置] 待删行的 items 解引用必须先于删除、同事务完成:
|
||||
# transfer_movement_ledger.source_file_id 有 ondelete,但
|
||||
# transfer_invoice_items.ledger_record_id 是普通 FK(无 ondelete)——已取消
|
||||
# 匹配的 items 与 blocked_file_removed 隔离 items 仍持有该引用,直接删除会
|
||||
# 在 PG flush 撞 IntegrityError,且该来源此后每次重建都撞同一堵墙。置空范围
|
||||
# 严格限于待删集合:能指向待删行的 items 必然是已取消/已隔离的废弃行
|
||||
#(被有效占用排除的行不在删除集,其 items 不受影响)——陈旧可匹配行是数据
|
||||
# 正确性风险,置空仅损失已废弃行的溯源装饰(处置见审计 unlinked_items)。
|
||||
candidates, deletable = _partition_deletable(source_code, files)
|
||||
# [STEP 3] 删除可重建未占用行(先解引用废弃 items)。
|
||||
candidates, deletable = _partition_deletable(source_code, files, kind)
|
||||
kept_unrebuildable = len(candidates) - len(deletable)
|
||||
deletable_ids = [row.id for row in deletable]
|
||||
unlinked_items = 0
|
||||
@@ -302,12 +295,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
db.session.delete(row)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 4] 按归档时间升序逐文件 sync_ledger_rows 重落(FileMeta 带真实
|
||||
# source_file_id/file_version/sha256;date_skipped 等六分类随 outcome 汇总)。
|
||||
# [档自然键坍缩守卫·重建路径] 每文件批内复检与运行期 evidence_sync 同一口径:
|
||||
# 同六成分键异料号(项次全空)→ 第二料号行必被幂等吞掉,行处理不变(首见为准)
|
||||
# 但每个坍缩键写一条 ledger_natural_key_collapse 审计事件——静默吞行变显式
|
||||
# 可观测;仅在该文件实际落档(inserted/updated)时记,防重放刷事件。
|
||||
# [STEP 4] 按归档时间升序逐文件重落。
|
||||
reinserted = 0
|
||||
date_skipped = 0
|
||||
collapses = 0
|
||||
@@ -315,7 +303,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
for record, assembled in prepared:
|
||||
outcome = sync_ledger_rows(
|
||||
source_code=source_code,
|
||||
record_kind=RECORD_KIND_INBOUND,
|
||||
record_kind=kind,
|
||||
parsed_rows=assembled,
|
||||
file_meta=FileMeta(
|
||||
source_file_id=record.file_id,
|
||||
@@ -326,11 +314,12 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
)
|
||||
reinserted += outcome.inserted
|
||||
date_skipped += outcome.date_skipped
|
||||
if (outcome.inserted or outcome.updated):
|
||||
if outcome.inserted or outcome.updated:
|
||||
file_collapses = _detect_natural_key_collapses(assembled)
|
||||
for collapse in file_collapses:
|
||||
db.session.add(_natural_key_collapse_event(
|
||||
source_code=source_code, collapse=collapse))
|
||||
source_code=source_code, collapse=collapse, record_kind=kind,
|
||||
))
|
||||
collapses += len(file_collapses)
|
||||
file_summaries.append({
|
||||
"file_id": record.file_id,
|
||||
@@ -339,8 +328,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
"inserted": outcome.inserted,
|
||||
})
|
||||
|
||||
# [STEP 5] 审计事件 + 单次 commit(提交归属模式同 evidence_sync 桥:调用方
|
||||
# 不感知事务时机;payload=操作人/来源/文件概要/规则 code+version/前后计数)。
|
||||
# [STEP 5] 审计 + commit。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type=REPARSE_EVENT,
|
||||
aggregate_type="transfer_source",
|
||||
@@ -352,6 +340,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
after={
|
||||
"operator": operator,
|
||||
"source_code": source_code,
|
||||
"record_kind": kind,
|
||||
"files": [
|
||||
{"file_id": record.file_id, "sha256": record.sha256}
|
||||
for record, _assembled in prepared
|
||||
@@ -369,6 +358,7 @@ def reparse_pending_match(*, source_code: str, operator: str, now: datetime) ->
|
||||
db.session.commit()
|
||||
return ReparseOutcome(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
cleared=len(deletable),
|
||||
reinserted=reinserted,
|
||||
date_skipped=date_skipped,
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
|
||||
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
|
||||
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
|
||||
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部入站记录,
|
||||
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部出入站记录,
|
||||
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
|
||||
依赖:models、status、matching_service(启用类型范围并集圈档)。
|
||||
依赖:models、status、matching_service(待匹配全量圈档 + 启用类型范围并集)。
|
||||
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
|
||||
manually_closed / success / duplicate_success 永久排除。
|
||||
待匹配桶=启用类型范围并集圈档(复用匹配创建的固定条件底座:inbound/
|
||||
未封存/有异动日期/未被有效 items 占用——D17 占用判定一致),无 item_id
|
||||
不可执行;匹配圈定后记录离开本桶,取消匹配释放后回归。
|
||||
待匹配桶=成熟未占用的出入站全量(pending_ledger_query:未封存/有异动日期/
|
||||
未被有效 items 占用/T−2,不按调拨类型范围过滤)。可匹配=启用类型范围并集,
|
||||
供库存匹配卡计数,并给清单行打 matchable。无 item_id 不可执行;
|
||||
匹配圈定后记录离开本桶,取消匹配释放后回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,6 +27,7 @@ from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_records_scope_union,
|
||||
pending_ledger_query,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
|
||||
@@ -100,7 +102,11 @@ class PendingMatchRecordDTO:
|
||||
material_name: Optional[str] = None
|
||||
movement_date: Optional[str] = None
|
||||
source_code: str = ""
|
||||
# 档记录类型(inbound/outbound);前端「清空重解析」按行传入,避免出站行误清入站档。
|
||||
record_kind: str = "inbound"
|
||||
quantity: Optional[str] = None
|
||||
# 当前启用类型范围并集罩得住。首页待匹配清单据此分出「当前可匹配」。
|
||||
matchable: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -113,8 +119,10 @@ class BacklogSummaryDTO:
|
||||
warn_3d: int = 0
|
||||
escalate_5d: int = 0
|
||||
critical_7d: int = 0
|
||||
# 首页第 4 张数字卡(D16):已落档尚未匹配的外部入站记录数。
|
||||
# 首页「待匹配」卡:已落档、尚未匹配的成熟出入站记录数(不含类型范围)。
|
||||
pending_match_count: int = 0
|
||||
# 首页「匹配可调拨库存」卡:启用类型范围并集现在圈得住的记录数。
|
||||
matchable_count: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -129,10 +137,13 @@ class BacklogPageDTO:
|
||||
page_size: int
|
||||
|
||||
|
||||
_PENDING_SEGMENTS = ("all", "matchable", "outside")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingMatchPageDTO:
|
||||
"""「待匹配」桶分页结果(951 行级大池;圈档并集无法合成单查询,
|
||||
计数在 Python 侧取 len,但序列化/传输只出当前页)。"""
|
||||
"""「待匹配」桶分页结果。all/outside 走 SQL 计数与切片;
|
||||
matchable 与 all 使用同一排序,只是 id 集合不同。"""
|
||||
|
||||
records: list[PendingMatchRecordDTO]
|
||||
total: int
|
||||
@@ -320,67 +331,93 @@ def list_backlog_page(
|
||||
return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
def list_pending_match_records() -> list[PendingMatchRecordDTO]:
|
||||
"""首页待办看板「待匹配」桶清单(D16:已抓取尚未匹配的外部入站记录,只读)。
|
||||
def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecordDTO:
|
||||
"""把档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。
|
||||
|
||||
数据源=启用类型范围并集圈档(matching_service.circle_ledger_records_scope_union:
|
||||
固定条件 inbound/未封存/有异动日期/未被有效 items 占用,与匹配创建圈档和 D17
|
||||
占用判定同一实现)。数字变化口径:文件落地→涨;被匹配圈定→离开(占用);
|
||||
取消匹配→回归(释放占用);执行成功→封存恒排除。
|
||||
Args:
|
||||
record: TransferMovementLedger 或带同名字段的行。
|
||||
matchable_ids: circle_ledger_records_scope_union 的 id 集合。
|
||||
Returns:
|
||||
只读 PendingMatchRecordDTO。无 item_id。
|
||||
"""
|
||||
return PendingMatchRecordDTO(
|
||||
ledger_record_id=record.id,
|
||||
doc_no=record.doc_no,
|
||||
material_code=record.material_code,
|
||||
material_name=record.material_name,
|
||||
movement_date=record.movement_date,
|
||||
source_code=record.source_code,
|
||||
record_kind=str(getattr(record, "record_kind", None) or "inbound"),
|
||||
quantity=record.quantity,
|
||||
matchable=record.id in matchable_ids,
|
||||
)
|
||||
|
||||
|
||||
def _matchable_ids() -> set[int]:
|
||||
"""启用类型现在圈得住的档 id。无启用类型时为空集。"""
|
||||
return {record.id for record in circle_ledger_records_scope_union()}
|
||||
|
||||
|
||||
def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchRecordDTO]:
|
||||
"""首页待办看板「待匹配」桶清单(已抓取尚未匹配的外部异动记录,只读)。
|
||||
|
||||
数据源=pending_ledger_query:未封存、有异动日期、未被有效 items 占用、
|
||||
movement_date ≤ T−2 的出入站记录,不按调拨类型范围过滤。
|
||||
segment=matchable 只留启用类型范围并集;segment=outside 是其余已落档。
|
||||
每行 matchable 标记并集成员,供清单把「当前可匹配」和其余行分开。
|
||||
数字变化口径:文件落地→涨;被匹配圈定→离开(占用);取消匹配→回归;
|
||||
执行成功→封存恒排除。停用类型只减少可匹配行,不把其余行移出本桶。
|
||||
|
||||
不可执行:记录尚未经匹配/库存核对(无 items),本桶仅提供只读清单与
|
||||
「去匹配」引导,禁止任何勾选执行入口。
|
||||
|
||||
Args:
|
||||
segment: all、matchable 或 outside。
|
||||
Returns:
|
||||
PendingMatchRecordDTO 列表(圈档稳定排序:异动日期 → 来源 → 单号 → id)。
|
||||
Raises:
|
||||
ValidationError: segment 不是上述三值。
|
||||
"""
|
||||
return [
|
||||
PendingMatchRecordDTO(
|
||||
ledger_record_id=record.id,
|
||||
doc_no=record.doc_no,
|
||||
material_code=record.material_code,
|
||||
material_name=record.material_name,
|
||||
movement_date=record.movement_date,
|
||||
source_code=record.source_code,
|
||||
quantity=record.quantity,
|
||||
)
|
||||
for record in circle_ledger_records_scope_union()
|
||||
]
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
if segment not in _PENDING_SEGMENTS:
|
||||
raise ValidationError("segment must be all, matchable, or outside")
|
||||
matchable_ids = _matchable_ids()
|
||||
rows = pending_ledger_query(matchable_ids=matchable_ids, segment=segment).all()
|
||||
return [_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows]
|
||||
|
||||
|
||||
def list_pending_match_records_page(
|
||||
*,
|
||||
page: int = BACKLOG_PAGE_DEFAULT,
|
||||
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
|
||||
segment: str = "all",
|
||||
) -> PendingMatchPageDTO:
|
||||
"""「待匹配」桶分页清单(2026-10-16 服务端分页;只读语义与全量版一致)。
|
||||
"""「待匹配」桶分页清单(服务端分页;只读语义与全量版一致)。
|
||||
|
||||
圈档=启用类型范围并集(多类型逐范围圈取后按 id 去重,无法合成单查询),
|
||||
故 total 在 Python 侧取 len;切片后仅当前页做 DTO 投影/序列化,
|
||||
951 行级大池的响应规模从 O(桶) 降到 O(页)。
|
||||
all 与 outside 按 SQL count/limit 切片,避免把整桶载入内存后再切页。
|
||||
matchable 使用同一查询,只保留启用类型范围并集的 id。
|
||||
|
||||
Args:
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
segment: all、matchable 或 outside。
|
||||
Returns:
|
||||
PendingMatchPageDTO(records=当前页切片,total=桶全量计数)。
|
||||
PendingMatchPageDTO(records=当前页切片,total=该段全量计数)。
|
||||
Raises:
|
||||
ValidationError: segment 不是上述三值。
|
||||
"""
|
||||
rows = circle_ledger_records_scope_union()
|
||||
start = (page - 1) * page_size
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
if segment not in _PENDING_SEGMENTS:
|
||||
raise ValidationError("segment must be all, matchable, or outside")
|
||||
matchable_ids = _matchable_ids()
|
||||
query = pending_ledger_query(matchable_ids=matchable_ids, segment=segment)
|
||||
total = query.count()
|
||||
rows = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return PendingMatchPageDTO(
|
||||
records=[
|
||||
PendingMatchRecordDTO(
|
||||
ledger_record_id=record.id,
|
||||
doc_no=record.doc_no,
|
||||
material_code=record.material_code,
|
||||
material_name=record.material_name,
|
||||
movement_date=record.movement_date,
|
||||
source_code=record.source_code,
|
||||
quantity=record.quantity,
|
||||
)
|
||||
for record in rows[start:start + page_size]
|
||||
],
|
||||
total=len(rows),
|
||||
records=[_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
@@ -403,7 +440,8 @@ def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
summary.escalate_5d += 1
|
||||
elif item.aging_level == AGING_CRITICAL_7D:
|
||||
summary.critical_7d += 1
|
||||
# [待匹配桶计数(D16)] 与行桶相互独立:档记录尚无 items 不进任何行桶,
|
||||
# 只有本计数可见(出生翻转后「抓到了没匹配」的唯一可见位)。
|
||||
summary.pending_match_count = len(list_pending_match_records())
|
||||
# [待匹配桶计数] 与行桶相互独立:成熟未占用的出入站全量。
|
||||
# 可匹配计数是其中启用类型现在圈得住的子集,供库存匹配卡单独展示。
|
||||
summary.pending_match_count = pending_ledger_query().count()
|
||||
summary.matchable_count = len(_matchable_ids())
|
||||
return summary
|
||||
@@ -0,0 +1,171 @@
|
||||
"""services/in_transit_transfer/current_file_reparse.py
|
||||
|
||||
用途:对当前最新可用入站/出站归档做一次本地重解析并落档(不触发 RPA)。
|
||||
依赖:evidence_sync.sync_source_rows、outbound_evidence_sync.sync_outbound_source_rows、
|
||||
source_file_status(latest_usable_outbound_file、resolve_source_file_status)、
|
||||
freight_rpa.reports.queries(latest_usable_inbound_file、mark_inbound_parse_failure、
|
||||
mark_outbound_parse_failure)、date_policy.business_date_now、deps.get_transfer_dependencies、
|
||||
file_parser.MovementFileSchemaError、core.errors、flask.current_app(非 schema 失败记日志)。
|
||||
逻辑:先确认可用归档与已发布规则门禁,再委托既有 sync_*_source_rows 落档并 commit;
|
||||
schema 失败 rollback 后 mark 解析失败并单独 commit;无规则/无文件 fail-closed;
|
||||
其他异常(含非 NO_PROFILE 的 AppError)rollback、记日志、不标 parse_failed,返回 ok=False。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
latest_usable_inbound_file,
|
||||
mark_inbound_parse_failure,
|
||||
mark_outbound_parse_failure,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.deps import get_transfer_dependencies
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
|
||||
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
|
||||
from app.services.in_transit_transfer.outbound_evidence_sync import sync_outbound_source_rows
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
latest_usable_outbound_file,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
|
||||
_RECORD_KINDS = frozenset({"inbound", "outbound"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CurrentReparseResult:
|
||||
"""一次当前归档重解析的返回。"""
|
||||
|
||||
source_code: str
|
||||
record_kind: str
|
||||
ok: bool
|
||||
file_status: str
|
||||
file_id: int | None
|
||||
inserted: int = 0
|
||||
updated: int = 0
|
||||
skipped: int = 0
|
||||
sealed_skipped: int = 0
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult:
|
||||
"""重解析该来源当前最新可用归档并提交。
|
||||
|
||||
核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。
|
||||
有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛
|
||||
CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure
|
||||
并单独提交。其他异常(含非 NO_PROFILE 的 AppError,如存储不可用)只回滚、
|
||||
记 TRANSFER_CURRENT_REPARSE_FAILED 日志,不标解析失败,返回 ok=False。
|
||||
error_message 取异常 message,为空再退回 str(exc)。成功路径由 sync 函数里的
|
||||
movement_file_version 写版本戳,本函数不拼 sha256: 前缀。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
now: 落档与新鲜度判定时刻。
|
||||
Returns:
|
||||
CurrentReparseResult。结构错误和其他落档异常(含非 NO_PROFILE 的 AppError)时 ok 为 False。
|
||||
Raises:
|
||||
ValidationError: record_kind 不是 inbound 或 outbound。
|
||||
AppError: 仅 TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。
|
||||
"""
|
||||
kind = record_kind.strip()
|
||||
if kind not in _RECORD_KINDS:
|
||||
raise ValidationError("record_kind must be inbound or outbound")
|
||||
|
||||
if kind == "outbound":
|
||||
file_view = latest_usable_outbound_file(source_code, now=now)
|
||||
else:
|
||||
file_view = latest_usable_inbound_file(source_code, now=now)
|
||||
|
||||
if file_view is None:
|
||||
raise AppError(
|
||||
code="TRANSFER.CURRENT_REPARSE_NO_FILE",
|
||||
message="no usable archive file",
|
||||
http_status=422,
|
||||
details={"source_code": source_code, "record_kind": kind},
|
||||
)
|
||||
|
||||
file_id = file_view.file_id
|
||||
|
||||
try:
|
||||
if kind == "outbound":
|
||||
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
|
||||
else:
|
||||
outcome = sync_source_rows(
|
||||
source_code=source_code,
|
||||
deps=get_transfer_dependencies(),
|
||||
business_date=business_date_now(),
|
||||
now=now,
|
||||
)
|
||||
|
||||
if outcome is None:
|
||||
raise AppError(
|
||||
code="TRANSFER.CURRENT_REPARSE_NO_PROFILE",
|
||||
message="no published parsing profile",
|
||||
http_status=422,
|
||||
details={"source_code": source_code, "record_kind": kind},
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
|
||||
return CurrentReparseResult(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
ok=True,
|
||||
file_status=str(status["file_status"]),
|
||||
file_id=file_id,
|
||||
inserted=outcome.inserted,
|
||||
updated=outcome.updated,
|
||||
skipped=outcome.skipped,
|
||||
sealed_skipped=outcome.sealed_skipped,
|
||||
)
|
||||
except MovementFileSchemaError as exc:
|
||||
db.session.rollback()
|
||||
error_message = (getattr(exc, "message", "") or str(exc))[:2000]
|
||||
error_code = exc.code
|
||||
if kind == "outbound":
|
||||
mark_outbound_parse_failure(
|
||||
file_id, error_code=error_code, error_message=error_message)
|
||||
else:
|
||||
mark_inbound_parse_failure(
|
||||
file_id, error_code=error_code, error_message=error_message)
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
|
||||
return CurrentReparseResult(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
ok=False,
|
||||
file_status=str(status["file_status"]),
|
||||
file_id=file_id,
|
||||
error_code=error_code,
|
||||
error_message=error_message,
|
||||
)
|
||||
except Exception as exc:
|
||||
# 无已发布规则仍是 422;其余 AppError(存储不可用等)与普通异常同一失败分支。
|
||||
if isinstance(exc, AppError) and exc.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE":
|
||||
raise
|
||||
db.session.rollback()
|
||||
current_app.logger.exception(
|
||||
"TRANSFER_CURRENT_REPARSE_FAILED source=%s kind=%s",
|
||||
source_code,
|
||||
kind,
|
||||
)
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
|
||||
error_message = (getattr(exc, "message", "") or str(exc))[:500]
|
||||
return CurrentReparseResult(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
ok=False,
|
||||
file_status=str(status["file_status"]),
|
||||
file_id=file_id,
|
||||
error_code="TRANSFER.CURRENT_REPARSE_FAILED",
|
||||
error_message=error_message,
|
||||
)
|
||||
@@ -1,13 +1,15 @@
|
||||
"""在途调拨业务日期与日期解析。
|
||||
|
||||
用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS
|
||||
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算与 UTC 存储窗口换算。
|
||||
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算、UTC 存储窗口换算与可匹配
|
||||
截止日(T−2)换算。
|
||||
依赖:标准库 zoneinfo / datetime。
|
||||
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
|
||||
复用,避免各服务各自计算导致口径漂移。
|
||||
【成熟度规则已退役 2026-10-16】数据无成熟属性——日期边界由调用方入参严格
|
||||
给定(交互匹配=用户选择的范围;自动排程=任务 T−N 偏移参数);引擎只保留
|
||||
「截止 ≤ 业务日期」的入参合法性与未来日期阻断(数据错误)。
|
||||
【T−2 管控恢复 2026-10-21】T−2 之前的数据全部成熟,T−2 之后(T−1/当天/
|
||||
未来)无成熟数据不可进入异动日期范围——matching_service 以
|
||||
eligible_movement_date_to 卡控范围截止;未来日期阻断(数据错误)保留。
|
||||
(2026-10-16 曾随成熟规则退役放开到「截止 ≤ 业务日期」,本次按业务口径收回。)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +19,10 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
# 可匹配截止滞后天数:T−2 之前数据全部成熟(与前端 transferDate.ts
|
||||
# DEFAULT_LOOKBACK_DAYS 同口径,两侧须同步调整)。
|
||||
MOVEMENT_DATE_MAX_LAG_DAYS = 2
|
||||
|
||||
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
|
||||
_US_DATE_FORMATS = (
|
||||
"%m/%d/%Y %H:%M:%S",
|
||||
@@ -77,6 +83,22 @@ def business_date_now(moment: datetime | None = None) -> date:
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def eligible_movement_date_to(business_date: date | str,
|
||||
lag_days: int = MOVEMENT_DATE_MAX_LAG_DAYS) -> date:
|
||||
"""返回可进入异动日期范围的截止日(业务日期 T − lag 天,默认 T−2)。
|
||||
|
||||
【AI 触发时机】matching_service 校验异动日期范围、或任何需要「最远可选到
|
||||
哪天」的场景;与前端 transferDate.ts defaultMovementDate 同口径。
|
||||
|
||||
Args:
|
||||
business_date: 当前业务日期 T。
|
||||
lag_days: 截止滞后天数;缺省 MOVEMENT_DATE_MAX_LAG_DAYS。
|
||||
Returns:
|
||||
T − lag 天。
|
||||
"""
|
||||
return parse_date(business_date) - timedelta(days=lag_days)
|
||||
|
||||
|
||||
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
|
||||
@@ -101,10 +101,13 @@ def _assemble_ledger_rows(
|
||||
|
||||
核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedMovementRow 无扩展
|
||||
字段槽位(Task 8 事实),扩展 7 字段(line_no/line_seq/in_out_flag/order_type/
|
||||
odm_*/carton_id/pallet_id 及 🔖预留)从原始领域行 dict 取。[STEP 2] 按调拨明细
|
||||
粒度 (doc_no, material_code, movement_date) 聚合:数量 Decimal 相加,其余字段
|
||||
取组内首行,sheet_name/row_no 取首行——与旧 aggregate_invoices 汇总键一致,
|
||||
保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变。
|
||||
odm_*/carton_id/pallet_id 及 🔖预留)与外部单据身份(external_doc_no/
|
||||
external_line_no,2026-10-21 扩展)从原始领域行 dict 取。[STEP 2] 按调拨明细
|
||||
粒度 (doc_no, material_code, movement_date, 外部单号, 外部项次) 聚合:数量
|
||||
Decimal 相加,其余字段取组内首行,sheet_name/row_no 取首行——与旧 aggregate_
|
||||
invoices 汇总键一致,保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变;
|
||||
外部单据身份入聚合键(2026-10-21):不同 WMS 单号/项次的行不得数量相加折叠
|
||||
(外部身份是档自然键成分,折叠即丢行)。
|
||||
注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ...,
|
||||
carton_id 等值, lot_no 等值) 会折叠多料号行为一条档记录(档自然键不含料号,
|
||||
规格 §4.2;carton_id/lot_no 为键成分,批内等值才折叠)——真实 WMS 导出
|
||||
@@ -124,11 +127,14 @@ def _assemble_ledger_rows(
|
||||
continue
|
||||
raw_by_key[(str(raw.get("sheet") or "").strip(), raw.get("row_no"))] = raw
|
||||
|
||||
groups: dict[tuple[str, str, str], dict] = {}
|
||||
groups: dict[tuple[str, str, str, str, str], dict] = {}
|
||||
ordered: list[dict] = []
|
||||
for row in parsed:
|
||||
raw = raw_by_key.get((row.sheet, row.row_no)) or {}
|
||||
key = (row.invoice_no, row.material_no, row.movement_date.isoformat())
|
||||
# 聚合键含外部单据身份(2026-10-21):不同外部单号/项次不折叠、不数量相加。
|
||||
key = (row.invoice_no, row.material_no, row.movement_date.isoformat(),
|
||||
_natural_key_text(raw.get("external_doc_no")),
|
||||
_natural_key_text(raw.get("external_line_no")))
|
||||
group = groups.get(key)
|
||||
if group is None:
|
||||
group = {
|
||||
@@ -151,6 +157,10 @@ def _assemble_ledger_rows(
|
||||
"odm_name": str(raw.get("odm_name") or "").strip(),
|
||||
"carton_id": str(raw.get("carton_id") or "").strip(),
|
||||
"pallet_id": str(raw.get("pallet_id") or "").strip(),
|
||||
# 外部单据身份(2026-10-21 扩展:外部单号/外部项次=WMS Order #/
|
||||
# 行号)——异动档自然键成分(档幂等主键管控),缺列按空串落键。
|
||||
"external_doc_no": str(raw.get("external_doc_no") or "").strip(),
|
||||
"external_line_no": str(raw.get("external_line_no") or "").strip(),
|
||||
# 🔖预留列(出货报告确认后直接映射):入站侧照常透传原值。
|
||||
"doc_nature": str(raw.get("doc_nature") or "").strip(),
|
||||
"movement_type": str(raw.get("movement_type") or "").strip(),
|
||||
@@ -190,9 +200,10 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
|
||||
"""检测批内档自然键坍缩(终审 I3,纯函数不改行)。
|
||||
|
||||
【AI 触发时机】sync_source_rows 组装落档前调用;不要在匹配/执行链路调用。
|
||||
判定:档自然键行级六成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
|
||||
lot_no)(source_code/record_kind 整批恒定不入键;carton_id/lot_no 随 tt14
|
||||
键扩维入检——两列批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code
|
||||
判定:档自然键行级八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
|
||||
lot_no, external_doc_no, external_line_no)(source_code/record_kind 整批恒定
|
||||
不入键;carton_id/lot_no 随 tt14 键扩维入检;外部单据身份随 2026-10-21 键
|
||||
扩维入检——批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code
|
||||
不同 → 该键坍缩(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量
|
||||
聚合合法形态,且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。
|
||||
|
||||
@@ -200,10 +211,10 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
|
||||
rows: _assemble_ledger_rows 产物(成分已归一化)。
|
||||
Returns:
|
||||
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag/
|
||||
carton_id/lot_no + material_codes(首见序全量料号)+ dropped_material_codes
|
||||
(首见后被吞料号)。
|
||||
carton_id/lot_no/external_doc_no/external_line_no + material_codes
|
||||
(首见序全量料号)+ dropped_material_codes(首见后被吞料号)。
|
||||
"""
|
||||
seen: dict[tuple[str, str, str, str, str, str], dict] = {}
|
||||
seen: dict[tuple[str, ...], dict] = {}
|
||||
for row in rows:
|
||||
key = (
|
||||
_natural_key_text(row.get("doc_no")),
|
||||
@@ -212,6 +223,8 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
|
||||
_natural_key_text(row.get("in_out_flag")),
|
||||
_natural_key_text(row.get("carton_id")),
|
||||
_natural_key_text(row.get("lot_no")),
|
||||
_natural_key_text(row.get("external_doc_no")),
|
||||
_natural_key_text(row.get("external_line_no")),
|
||||
)
|
||||
material = _natural_key_text(row.get("material_code"))
|
||||
entry = seen.get(key)
|
||||
@@ -225,6 +238,7 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
|
||||
"doc_no": entry["key"][0], "line_no": entry["key"][1],
|
||||
"line_seq": entry["key"][2], "in_out_flag": entry["key"][3],
|
||||
"carton_id": entry["key"][4], "lot_no": entry["key"][5],
|
||||
"external_doc_no": entry["key"][6], "external_line_no": entry["key"][7],
|
||||
"material_codes": entry["materials"],
|
||||
"dropped_material_codes": entry["dropped"],
|
||||
}
|
||||
@@ -232,20 +246,23 @@ def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def _natural_key_collapse_event(*, source_code: str, collapse: dict):
|
||||
def _natural_key_collapse_event(*, source_code: str, collapse: dict,
|
||||
record_kind: str = RECORD_KIND_INBOUND):
|
||||
"""构造档自然键坍缩审计事件(未落库,由调用方 add——build 契约同 ledger_sync)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(自然键成分,整批一致)。
|
||||
collapse: _detect_natural_key_collapses 的单条坍缩键信息。
|
||||
record_kind: 记录类型(入站/出站共用检测口径;聚合键与快照随流声明)。
|
||||
Returns:
|
||||
已计算 Hash 的 TransferAuditEvent(event_type=ledger_natural_key_collapse,
|
||||
result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。
|
||||
"""
|
||||
natural_key = "/".join((
|
||||
source_code, RECORD_KIND_INBOUND,
|
||||
source_code, record_kind,
|
||||
collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"],
|
||||
collapse["carton_id"], collapse["lot_no"],
|
||||
collapse["external_doc_no"], collapse["external_line_no"],
|
||||
))
|
||||
return build_transfer_audit_event(
|
||||
event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT,
|
||||
@@ -256,10 +273,12 @@ def _natural_key_collapse_event(*, source_code: str, collapse: dict):
|
||||
actor_type="system",
|
||||
result="failure",
|
||||
after={
|
||||
"source_code": source_code, "record_kind": RECORD_KIND_INBOUND,
|
||||
"source_code": source_code, "record_kind": record_kind,
|
||||
"doc_no": collapse["doc_no"], "line_no": collapse["line_no"],
|
||||
"line_seq": collapse["line_seq"], "in_out_flag": collapse["in_out_flag"],
|
||||
"carton_id": collapse["carton_id"], "lot_no": collapse["lot_no"],
|
||||
"external_doc_no": collapse["external_doc_no"],
|
||||
"external_line_no": collapse["external_line_no"],
|
||||
"material_codes": collapse["material_codes"],
|
||||
"dropped_material_codes": collapse["dropped_material_codes"],
|
||||
"resolution": "first_seen_wins",
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
(classify_quantity_match)、document_id、contracts、audit、status、
|
||||
source_file_status、matching_service(门禁/scope/路由契约)、
|
||||
jobs.queue(TRANSFER_RUN 入队)、models。
|
||||
逻辑:防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
|
||||
逻辑:执行门禁与 worker 复核按档记录 record_kind 对证据文件 sha(无档回落入站)。
|
||||
防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
|
||||
五元组建单,同组存在失败单则复用其单号/时间戳全量重跑(doc.run_id 改指新
|
||||
Run,现任归属语义),存在 result_unknown/executing 单则阻断新行
|
||||
(group_order_unresolved);部分唯一索引竞态以 SAVEPOINT + 复用重查重试
|
||||
@@ -58,6 +59,8 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
_item_evaluated_sha,
|
||||
_item_evidence_kind,
|
||||
_latest_evidence_files,
|
||||
item_external_lot_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
@@ -127,8 +130,9 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
|
||||
门禁:
|
||||
① 存在且可执行:id 存在且 status == ready_to_execute,否则
|
||||
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID")。
|
||||
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 来源最新可用文件
|
||||
sha(含来源无可用文件/行无版本戳)→ ValidationError(code="TRANSFER.FILE_CHANGED")。
|
||||
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 该行证据流最新可用
|
||||
文件 sha。证据流取档记录 record_kind,无档关联回落入站。来源无可用文件
|
||||
或行无版本戳 → ValidationError(code="TRANSFER.FILE_CHANGED")。
|
||||
|
||||
[2026-09-25 TTL 退役] 原门禁②「行级新鲜度(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」已删除:匹配 10 分钟后必被拒
|
||||
@@ -178,20 +182,17 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
|
||||
)
|
||||
items = [by_id[i] for i in ordered_ids]
|
||||
|
||||
# [门禁②] 文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致)。
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({item.source_code for item in items})
|
||||
}
|
||||
# [门禁②] 文件版本对账:按 (来源, 档 record_kind) 投影最新证据文件,行评估 sha 必须一致。
|
||||
latest_files = _latest_evidence_files(items, resolve=resolve_source_file_status)
|
||||
changed = []
|
||||
for item in items:
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
latest = latest_files.get(item.source_code) or {}
|
||||
latest = latest_files.get((item.source_code, _item_evidence_kind(item))) or {}
|
||||
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
|
||||
changed.append(item.id)
|
||||
if changed:
|
||||
raise ValidationError(
|
||||
"source inbound file changed since evaluation", code="TRANSFER.FILE_CHANGED",
|
||||
"source evidence file changed since evaluation", code="TRANSFER.FILE_CHANGED",
|
||||
details={"changed_item_ids": changed},
|
||||
)
|
||||
return items
|
||||
@@ -551,15 +552,12 @@ def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | No
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
)
|
||||
]
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({item.source_code for item in items})
|
||||
}
|
||||
latest_files = _latest_evidence_files(items, resolve=resolve_source_file_status)
|
||||
for item in items:
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
latest = latest_files.get(item.source_code) or {}
|
||||
latest = latest_files.get((item.source_code, _item_evidence_kind(item))) or {}
|
||||
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
|
||||
return ("file_changed", "source inbound file changed since evaluation")
|
||||
return ("file_changed", "source evidence file changed since evaluation")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""在途调拨异动文件字段/结构校验。
|
||||
|
||||
用途:校验异动文件必填列(单号/料号/异动日期/异动数量)、数量与日期合法性、
|
||||
来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
|
||||
用途:校验异动文件必填列(单号/异动日期/异动数量;料号为空的行静默跳过)、
|
||||
数量与日期合法性、来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
|
||||
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_inbound_quantity。
|
||||
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
|
||||
逻辑:必填缺失或非法值整行阻断并携带行号细节;料号空行跳过不管控不落档
|
||||
(2026-10-21 CRANE/Lognet 出站报告实测);本模块不接触文件存储。
|
||||
tt14 入站化后统一走 movement 契约字段(parse_movement_rows 单一入口,
|
||||
旧字段投影链路已并入,无兼容层)。
|
||||
"""
|
||||
@@ -92,6 +93,9 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
warehouse_code 透传至 ParsedMovementRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
unit 原值透传至 ParsedMovementRow.unit(movement 契约第 11 字段,仅 trim,
|
||||
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
|
||||
external_doc_no/external_line_no(2026-10-21 扩展:外部单号/外部项次)经原始行
|
||||
透传至落档组装(_assemble_ledger_rows 从原始行取扩展字段,解析行不设槽位),
|
||||
作为异动档自然键成分承担档幂等主键管控;
|
||||
storage_code 仍仅展示保留。旧字段名投影链路(tt14 前的直连列名解析)已并入
|
||||
本函数(入站化,无兼容层),校验逻辑一致。
|
||||
|
||||
@@ -152,12 +156,15 @@ def _parse_rows(
|
||||
if not sheet or not row_no:
|
||||
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
|
||||
continue
|
||||
if not material_no:
|
||||
# [料号空行跳过 2026-10-21] 料号为空=非可用异动行(CRANE/Lognet 出站
|
||||
# 报告的说明行/占位行实测):不做必填管控、不进异动表,静默跳过——
|
||||
# 与 _is_unusable_movement_row 同家族(跳过不阻断整文件)。其余必填
|
||||
#(单号)管控不变,仅对有料号的行生效。
|
||||
continue
|
||||
if not invoice_no:
|
||||
_fail(errors, row_no=row_no, reason="missing_invoice_no")
|
||||
continue
|
||||
if not material_no:
|
||||
_fail(errors, row_no=row_no, reason="missing_material_no")
|
||||
continue
|
||||
row_source = str(row.get("source_code") or "").strip()
|
||||
if row_source and row_source.upper() != str(source_code).upper():
|
||||
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
||||
|
||||
@@ -7,11 +7,15 @@
|
||||
依赖:models/in_transit_transfer.TransferMovementLedger、audit.build_transfer_audit_event、
|
||||
movement_contract.MOVEMENT_FIELDS(档列镜像取值的唯一字段来源)。不解析文件
|
||||
(parsed_rows 由调用方/Task 11 接线从解析产物组装)、不查外部系统、零外部调用。
|
||||
逻辑:落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行),
|
||||
逻辑:file_version 戳由 movement_file_version 统一生成(sha256: 前缀按档列宽度截断),
|
||||
入站仓库、出站落档、清空重建、匹配进度快照都调用它,禁止各处自行拼接。
|
||||
落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行),
|
||||
落档即幽灵行,计入 date_skipped(解析层已滤一轮,此处为映射无关第二道防线)。
|
||||
规格 §5 五条幂等语义——①自然键 (doc_no, line_no, line_seq, in_out_flag,
|
||||
carton_id, lot_no)(source_code/record_kind 整批恒定不入行内键;tt14 扩维
|
||||
箱号/批号)查档不存在 → 插入(record_kind/溯源五列随行写入);②行
|
||||
carton_id, lot_no, external_doc_no, external_line_no)(source_code/
|
||||
record_kind 整批恒定不入行内键;tt14 扩维箱号/批号;2026-10-21 扩维外部
|
||||
单据身份=外部单号+外部项次,作档幂等主键管控)查档不存在 → 插入
|
||||
(record_kind/溯源五列随行写入);②行
|
||||
file_sha256 与来件一致 → 跳过(完全不动行,不续 updated_at——档无 TTL,
|
||||
无新鲜度概念);③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/
|
||||
file_version/file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行
|
||||
@@ -45,6 +49,12 @@ assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__
|
||||
|
||||
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
|
||||
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
|
||||
# 自然键 NOT NULL 成分(行级 8 成分;source_code/record_kind 整批恒定不入行内键):
|
||||
# 镜像取值时缺值以空串落库(防 NULL 违反非空约束/逃逸唯一比对,与模型 default '' 同口径)。
|
||||
_NOT_NULL_KEY_CODES: tuple[str, ...] = (
|
||||
"doc_no", "line_no", "line_seq", "in_out_flag",
|
||||
"carton_id", "lot_no", "external_doc_no", "external_line_no",
|
||||
)
|
||||
# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留);
|
||||
# outbound=出站(出货侧结构就位)。
|
||||
RECORD_KIND_INBOUND = "inbound"
|
||||
@@ -69,6 +79,23 @@ class FileMeta:
|
||||
file_sha256: str | None = None
|
||||
|
||||
|
||||
def movement_file_version(sha256: str) -> str:
|
||||
"""把文件 SHA-256 摘要打成异动档 file_version 戳。
|
||||
|
||||
核心逻辑:前缀 sha256: 加摘要后,按 TransferMovementLedger.file_version 列宽截断。
|
||||
64 位摘要加前缀共 71 字符,超出 varchar(64) 时 PostgreSQL 会整批拒绝插入。
|
||||
列宽取自模型,避免戳长和列定义各写一个 64。
|
||||
|
||||
Args:
|
||||
sha256: 文件 SHA-256 十六进制摘要,不含前缀。
|
||||
|
||||
Returns:
|
||||
以 sha256: 开头、长度不超过档列宽度的版本戳。
|
||||
"""
|
||||
limit = TransferMovementLedger.__table__.c.file_version.type.length
|
||||
return f"sha256:{sha256}"[:limit]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LedgerSyncOutcome:
|
||||
"""一次落档的结果计数(审计与兜底日志的数据源;字段名为冻结契约,顺序自 date_skipped 引入后不再承诺)。"""
|
||||
@@ -105,7 +132,7 @@ def _cross_check_event(
|
||||
*,
|
||||
source_code: str,
|
||||
record_kind: str,
|
||||
key: tuple[str, str, str, str, str, str],
|
||||
key: tuple[str, str, str, str, str, str, str, str],
|
||||
sheet_name: str | None,
|
||||
row_no: int | None,
|
||||
file_meta: FileMeta,
|
||||
@@ -114,16 +141,20 @@ def _cross_check_event(
|
||||
|
||||
Args:
|
||||
source_code / record_kind: 来源实例编码与记录种类。
|
||||
key: 自然键六成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
|
||||
lot_no)(已归一化;箱号/批号随 tt14 键扩维入事件,保证矛盾行可唯一定位)。
|
||||
key: 自然键八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
|
||||
lot_no, external_doc_no, external_line_no)(已归一化;箱号/批号随
|
||||
tt14 键扩维入事件,外部单据身份随 2026-10-21 键扩维入事件,保证
|
||||
矛盾行可唯一定位)。
|
||||
sheet_name / row_no: 行级溯源(入事件快照辅助定位来源行)。
|
||||
file_meta: 来源文件证据三元组。
|
||||
Returns:
|
||||
已计算 Hash 的 TransferAuditEvent(event_type=ledger_cross_check_failed)。
|
||||
"""
|
||||
doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no = key
|
||||
(doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
|
||||
external_doc_no, external_line_no) = key
|
||||
natural_key = "/".join((
|
||||
source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
|
||||
external_doc_no, external_line_no,
|
||||
))
|
||||
return build_transfer_audit_event(
|
||||
event_type=LEDGER_CROSS_CHECK_EVENT,
|
||||
@@ -136,6 +167,7 @@ def _cross_check_event(
|
||||
"source_code": source_code, "record_kind": record_kind,
|
||||
"doc_no": doc_no, "line_no": line_no, "line_seq": line_seq,
|
||||
"in_out_flag": in_out_flag, "carton_id": carton_id, "lot_no": lot_no,
|
||||
"external_doc_no": external_doc_no, "external_line_no": external_line_no,
|
||||
"file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256,
|
||||
"sheet_name": sheet_name, "row_no": row_no,
|
||||
},
|
||||
@@ -189,12 +221,13 @@ def sync_ledger_rows(
|
||||
counters["date_skipped"] = total_in - len(parsed_rows)
|
||||
|
||||
# [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键
|
||||
# 建索引;source_code/record_kind 整批恒定,键只留行级六成分(tt14 扩维:
|
||||
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批)。档「缺席不删、永不
|
||||
# 删除」行数单调增长(评审 Important 修复):按 source+kind 全量水化会使每次
|
||||
# 落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加 doc_no IN 批内
|
||||
# 过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100% 等价;
|
||||
# in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
|
||||
# 建索引;source_code/record_kind 整批恒定,键只留行级八成分(tt14 扩维:
|
||||
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批;2026-10-21 扩维:
|
||||
# external_doc_no/external_line_no——外部单据身份作档幂等主键管控)。档「缺席
|
||||
# 不删、永不删除」行数单调增长(评审 Important 修复):按 source+kind 全量
|
||||
# 水化会使每次落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加
|
||||
# doc_no IN 批内过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100%
|
||||
# 等价;in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
|
||||
doc_nos = sorted({_key_text(raw.get("doc_no")) for raw in parsed_rows})
|
||||
existing = (
|
||||
TransferMovementLedger.query.filter_by(
|
||||
@@ -204,12 +237,13 @@ def sync_ledger_rows(
|
||||
.all()
|
||||
)
|
||||
by_key = {
|
||||
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no): r
|
||||
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no,
|
||||
r.external_doc_no, r.external_line_no): r
|
||||
for r in existing
|
||||
}
|
||||
# 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞
|
||||
# uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。
|
||||
landed: dict[tuple[str, str, str, str, str, str], TransferMovementLedger] = {}
|
||||
landed: dict[tuple[str, str, str, str, str, str, str, str], TransferMovementLedger] = {}
|
||||
|
||||
# [STEP 2] 逐行六分类:日期空 → 封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。
|
||||
for raw in parsed_rows:
|
||||
@@ -219,7 +253,10 @@ def sync_ledger_rows(
|
||||
in_out_flag = _key_text(raw.get("in_out_flag"))
|
||||
carton_id = _key_text(raw.get("carton_id"))
|
||||
lot_no = _key_text(raw.get("lot_no"))
|
||||
key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no)
|
||||
external_doc_no = _key_text(raw.get("external_doc_no"))
|
||||
external_line_no = _key_text(raw.get("external_line_no"))
|
||||
key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
|
||||
external_doc_no, external_line_no)
|
||||
sheet_name = _mirror_text(raw.get("sheet_name"))
|
||||
row_no = _opt_int(raw.get("row_no"))
|
||||
|
||||
@@ -250,9 +287,16 @@ def sync_ledger_rows(
|
||||
))
|
||||
|
||||
# [镜像取值] 业务值一律从领域行 dict 按契约 code 取(扩展字段无独立槽位);
|
||||
# 自然键成分同源同值,插入/更新统一按全字段镜像写入(更新时键成分等值重写
|
||||
# 为无操作,SQLAlchemy 等值列不入 UPDATE)。
|
||||
mirror = {code: _mirror_text(raw.get(code)) for code in _MOVEMENT_CODES}
|
||||
# 自然键 NOT NULL 成分缺值以空串落库(_key_text,防 NULL 违反非空约束/
|
||||
# 逃逸唯一比对——2026-10-21 外部身份扩维时修复的潜在缺陷:此前镜像缺值
|
||||
# 即 None,仅因各组装方恒给空串而未暴露)。自然键成分同源同值,插入/更新
|
||||
# 统一按全字段镜像写入(更新时键成分等值重写为无操作,SQLAlchemy 等值列
|
||||
# 不入 UPDATE)。
|
||||
mirror = {
|
||||
code: (_key_text(raw.get(code)) if code in _NOT_NULL_KEY_CODES
|
||||
else _mirror_text(raw.get(code)))
|
||||
for code in _MOVEMENT_CODES
|
||||
}
|
||||
if row is None:
|
||||
# [插入] 自然键不存在:新档行,record_kind + 溯源五列随行写入。
|
||||
row = TransferMovementLedger(
|
||||
|
||||
@@ -6,27 +6,26 @@
|
||||
依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/
|
||||
scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/
|
||||
source_file_status / capability_client / date_policy / quantity / contracts /
|
||||
audit / models。【阶段 B Task 4】取可用入站归档文件的查询已删除并收口到
|
||||
freight_rpa.reports.queries.latest_usable_inbound_file(匹配不再引用
|
||||
freight_rpa 报表模型;证据链消费方见 evidence_sync)。
|
||||
audit / models / evidence_sync(入站 ready 补落档)/
|
||||
outbound_evidence_sync(出站 ready 补落档)/
|
||||
ledger_sync.movement_file_version(进度快照的 file_version 戳)。【阶段 B Task 4】取可用入站
|
||||
归档文件的查询已删除并收口到 freight_rpa.reports.queries;匹配不再引用
|
||||
freight_rpa 报表模型。
|
||||
逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由
|
||||
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind=
|
||||
'inbound' + 来源 IN + movement_date 范围 + transfer_executed=false +
|
||||
本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind
|
||||
∈ record_kinds_of(类型.scope_rules);无类型对象的调用点显式 inbound +
|
||||
来源 IN + movement_date 范围 + transfer_executed=false +
|
||||
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
|
||||
未被有效 items 占用(D17:不存在所属匹配未取消且未被失效隔离的 item 引用;
|
||||
取消匹配即释放占用)。逐记录建 item(ledger_record_id 外键、业务字段=档
|
||||
原值、movement_quantity=record.quantity、raw_lines 单行溯源);仓库经
|
||||
resolve_warehouse 按类型定义(mapped/fixed)落 from/to;既有库存评估链
|
||||
不变(继续以 items 为工作单元)。来源实例独立处理,任一来源失败不阻断
|
||||
其他来源;【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_
|
||||
resolved;当天入站不查询 外部系统;匹配 Hash 从 scope_json 快照内容 +
|
||||
business_date + file_snapshot 计算(无环境变量/全局态,2026-09-22 陷阱
|
||||
根因防御);create_matching 先落 Run + Matching 再驱动管道(行出生即绑定
|
||||
matching_id),末尾统一提交;restore 与可调拨明细按匹配自有 items 圈行
|
||||
(行归属=匹配绑定,scope_item_query 已随翻转退役);
|
||||
行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的
|
||||
stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列):
|
||||
命中库存但 ERP 未给单位 → 行级 blocked_missing_unit;unit 不参与匹配 Hash。
|
||||
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
|
||||
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
|
||||
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
|
||||
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
|
||||
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
|
||||
【确认匹配落档补齐 2026-10-20】UI ready≠档已写入:圈档前对所需流为 ready
|
||||
的来源做幂等落档(入站 sync_source_rows / 出站 sync_outbound_source_rows,
|
||||
只 flush 随主事务),补齐「回调落档桥未跑或部署前已就绪」的空档窗口;
|
||||
parse_failed(入站/出站)均记 failed 进度,不阻断其他来源圈档。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,7 +36,7 @@ from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy import and_, false, func, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
@@ -57,6 +56,8 @@ from app.services.in_transit_transfer.contracts import (
|
||||
RawLineRefDTO,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
business_date_now,
|
||||
eligible_movement_date_to,
|
||||
parse_date,
|
||||
)
|
||||
from app.services.in_transit_transfer.field_transforms import (
|
||||
@@ -69,12 +70,13 @@ from app.services.in_transit_transfer.file_preparation import (
|
||||
RpaTrigger,
|
||||
ensure_inbound_file_ready,
|
||||
)
|
||||
from app.services.in_transit_transfer.ledger_sync import RECORD_KIND_INBOUND
|
||||
from app.services.in_transit_transfer.ledger_sync import movement_file_version
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.scope_rules import (
|
||||
ScopeRule,
|
||||
apply_scope_filters,
|
||||
parse_scope_rules,
|
||||
record_kinds_of,
|
||||
scope_rules_note,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
@@ -91,6 +93,8 @@ from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
)
|
||||
|
||||
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
|
||||
# ready 流在圈档前补落档:与回调桥共用解析/落档实现,匹配路径只 flush 不 commit。
|
||||
_CONFIRMABLE_SYNC_STATUSES = frozenset({"ready"})
|
||||
|
||||
# 明细结果值(对应 Invoice 项状态)
|
||||
# 【RESULT_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线不设兼容层)。
|
||||
@@ -206,16 +210,18 @@ def _validate_movement_date_range(
|
||||
) -> tuple[date | None, date | None]:
|
||||
"""校验可选异动日期范围(纯校验无副作用;run_matching / create_matching 共用)。
|
||||
|
||||
【成熟规则已退役 2026-10-16】日期边界由调用方入参严格给定(交互=用户选择;
|
||||
排程=任务 T−N 偏移参数),引擎只做入参合法性校验。
|
||||
【T−2 成熟封顶 2026-10-21】T−2 之前的数据全部成熟(简化成熟边界,不回退
|
||||
2026-10-16 退役决策——无成熟行级状态):范围截止不得晚于 T−2 可匹配截止日
|
||||
(eligible_movement_date_to),T−1/当天/未来无成熟数据不可选;与前端选择器
|
||||
上限(transferDate.ts defaultMovementDate)同口径。
|
||||
|
||||
Args:
|
||||
business_date: 业务日期 T(未来日期阻断的基准)。
|
||||
business_date: 业务日期 T(截止上限换算基准)。
|
||||
movement_date_from / movement_date_to: 可选异动日期范围(约束明细 movement_date)。
|
||||
Returns:
|
||||
(range_from, range_to) 解析后的日期(未提供为 None)。
|
||||
Raises:
|
||||
ValidationError: 起始晚于截止,或截止晚于业务日期(未来日期无账可核)。
|
||||
ValidationError: 起始晚于截止,或截止晚于 T−2 可匹配截止日。
|
||||
"""
|
||||
range_from = parse_date(movement_date_from) if movement_date_from else None
|
||||
range_to = parse_date(movement_date_to) if movement_date_to else None
|
||||
@@ -223,19 +229,76 @@ def _validate_movement_date_range(
|
||||
raise ValidationError(
|
||||
"movement date range is invalid", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
|
||||
)
|
||||
if range_to and range_to > parse_date(business_date):
|
||||
matured_date_to = eligible_movement_date_to(business_date)
|
||||
if range_to and range_to > matured_date_to:
|
||||
raise ValidationError(
|
||||
"movement date range end is later than business date", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
|
||||
f"movement date range end is later than matured boundary {matured_date_to.isoformat()}",
|
||||
code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID",
|
||||
)
|
||||
return range_from, range_to
|
||||
|
||||
|
||||
def _item_grain_of_ledger(record: TransferMovementLedger) -> tuple[str, str, str, str]:
|
||||
"""档记录对应的匹配明细 grain(与 uq_transfer_invoice_items_matching_grain 对齐)。
|
||||
|
||||
Args:
|
||||
record: 库存异动档行。
|
||||
Returns:
|
||||
(source_code, doc_no/invoice_no, material_no, movement_date) 四元组。
|
||||
"""
|
||||
return (
|
||||
str(record.source_code or ""),
|
||||
str(record.doc_no or ""),
|
||||
str(record.material_code or ""),
|
||||
str(record.movement_date or ""),
|
||||
)
|
||||
|
||||
|
||||
def _prefer_ledger_for_item_grain(
|
||||
current: TransferMovementLedger, candidate: TransferMovementLedger,
|
||||
) -> TransferMovementLedger:
|
||||
"""同 grain 多档择一:优先非空 carton_id(更完整自然键),再取更大 id(更新解析)。
|
||||
|
||||
不累加数量——同 grain 双行常见于重解析扩键(空 carton → 有 carton)的镜像分叉,
|
||||
相加会翻倍;合法同文件多箱数量已在 evidence_sync 组装期按 grain 汇总。
|
||||
"""
|
||||
cur_carton = str(getattr(current, "carton_id", None) or "").strip()
|
||||
cand_carton = str(getattr(candidate, "carton_id", None) or "").strip()
|
||||
if bool(cand_carton) != bool(cur_carton):
|
||||
return candidate if cand_carton else current
|
||||
return candidate if int(candidate.id or 0) >= int(current.id or 0) else current
|
||||
|
||||
|
||||
def _dedupe_ledger_records_for_item_birth(
|
||||
records: list[TransferMovementLedger],
|
||||
) -> list[TransferMovementLedger]:
|
||||
"""出生前按 item grain 去重,避免撞 uq_transfer_invoice_items_matching_grain。
|
||||
|
||||
Args:
|
||||
records: 圈档结果(可含同 grain 多档)。
|
||||
Returns:
|
||||
每 grain 一条档(稳定顺序:首次出现序,值已按 _prefer_ledger_for_item_grain 择优)。
|
||||
"""
|
||||
chosen: dict[tuple[str, str, str, str], TransferMovementLedger] = {}
|
||||
order: list[tuple[str, str, str, str]] = []
|
||||
for record in records:
|
||||
grain = _item_grain_of_ledger(record)
|
||||
if grain not in chosen:
|
||||
chosen[grain] = record
|
||||
order.append(grain)
|
||||
continue
|
||||
chosen[grain] = _prefer_ledger_for_item_grain(chosen[grain], record)
|
||||
return [chosen[grain] for grain in order]
|
||||
|
||||
|
||||
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
|
||||
|
||||
占用定义(规格 §9):存在任一 item 引用该档记录,且其所属匹配未取消、行未被
|
||||
失效隔离(blocked_file_removed)。取消匹配(items→cancelled / 匹配→cancelled)
|
||||
即释放占用;人工关闭/成功终态不释放(前者=业务裁定不拨;后者=档级封存)。
|
||||
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
|
||||
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
|
||||
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
|
||||
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
|
||||
|
||||
Args:
|
||||
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
|
||||
@@ -243,8 +306,22 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
Returns:
|
||||
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
|
||||
"""
|
||||
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
|
||||
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
|
||||
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
|
||||
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
|
||||
grain_match = and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
|
||||
TransferInvoiceItem.invoice_no == TransferMovementLedger.doc_no,
|
||||
TransferInvoiceItem.material_no == func.coalesce(TransferMovementLedger.material_code, ""),
|
||||
TransferInvoiceItem.movement_date == TransferMovementLedger.movement_date,
|
||||
)
|
||||
item_conditions = [
|
||||
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||
or_(
|
||||
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||
grain_match,
|
||||
),
|
||||
# 失效隔离行不占用(消失证据不可用,记录可被重新圈定修复)。
|
||||
or_(TransferInvoiceItem.result_code.is_(None),
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
@@ -271,22 +348,40 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
return ~occupancy
|
||||
|
||||
|
||||
def _circle_ledger_base_query(*, exclude_occupied_by_matching_id: int | None = None):
|
||||
def _circle_ledger_base_query(
|
||||
*,
|
||||
record_kinds: tuple[str, ...],
|
||||
exclude_occupied_by_matching_id: int | None = None,
|
||||
matured_date_to: date | None = None,
|
||||
):
|
||||
"""圈档固定条件底座(匹配创建圈档/重查对账/首页待匹配桶共享的唯一实现)。
|
||||
|
||||
固定条件(规格 §6/§9):record_kind='inbound'(一期入站)、transfer_executed=false
|
||||
(档级封存防二次执行——已执行记录永不再次被圈定)、movement_date 非空(可空
|
||||
记录照常落档但不进异动日期圈定)、未被有效 items 占用(D17,见
|
||||
_effective_occupancy_filter;取消匹配即释放占用)。
|
||||
固定条件(规格 §6/§9):record_kind ∈ record_kinds(由调用方按类型范围规则
|
||||
经 record_kinds_of 推导;没有类型对象时显式传入,禁止再把入站当隐式默认)、
|
||||
transfer_executed=false(档级封存防二次执行——已执行记录永不再次被圈定)、
|
||||
movement_date 非空(可空记录照常落档但不进异动日期圈定)、未被有效 items
|
||||
占用(D17,见 _effective_occupancy_filter;取消匹配即释放占用)。
|
||||
【T−2 成熟封顶 2026-10-21】matured_date_to 传入时只圈 movement_date ≤ T−2
|
||||
的成熟记录(T−2 之前数据全部成熟;T−1/当天未成熟不匹配,留在档内待成熟后
|
||||
自然进圈)。匹配创建圈档与首页待匹配桶传值;重查对账不传——对账只对既有
|
||||
items 与档证据对齐,新增封顶会把存量未成熟行误判「档消失」走失效隔离。
|
||||
【单一口径纪律】任何新的圈档消费方必须经本底座组合查询,禁止第三处手写
|
||||
固定条件(双份维护=谓词漂移温床)。
|
||||
|
||||
Args:
|
||||
record_kinds: 允许圈入的记录类型(inbound/outbound)。必传。
|
||||
exclude_occupied_by_matching_id: 重查对账时排除本匹配占用;创建圈档不传。
|
||||
matured_date_to: 可匹配截止日(eligible_movement_date_to 产物);None=不封顶。
|
||||
"""
|
||||
return TransferMovementLedger.query.filter(
|
||||
TransferMovementLedger.record_kind == RECORD_KIND_INBOUND,
|
||||
query = TransferMovementLedger.query.filter(
|
||||
TransferMovementLedger.record_kind.in_(record_kinds),
|
||||
TransferMovementLedger.transfer_executed.is_(False),
|
||||
TransferMovementLedger.movement_date.isnot(None),
|
||||
_effective_occupancy_filter(exclude_matching_id=exclude_occupied_by_matching_id),
|
||||
)
|
||||
if matured_date_to is not None:
|
||||
query = query.filter(TransferMovementLedger.movement_date <= str(matured_date_to))
|
||||
return query
|
||||
|
||||
|
||||
def _order_circled_ledger(query):
|
||||
@@ -302,14 +397,19 @@ def _order_circled_ledger(query):
|
||||
def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
|
||||
"""启用类型范围并集圈档(首页待办看板「待匹配」桶数据源,D16/规格 §10)。
|
||||
|
||||
【AI 触发时机】首页待办看板需要「已抓取尚未匹配的外部入站记录」清单/计数时
|
||||
【AI 触发时机】首页待办看板需要「已抓取尚未匹配的出入站记录」清单/计数时
|
||||
调用(backlog_service.list_pending_match_records);匹配创建圈档不要用本函数
|
||||
(匹配按所选类型单范围圈定,不经并集)。
|
||||
|
||||
范围并集=对每个启用类型分别按其现行规则圈取后按 id 去重并集(等价实现):
|
||||
每类型查询复用 _circle_ledger_base_query 固定条件(inbound/未封存/有异动日期/
|
||||
未被有效 items 占用)+ apply_scope_filters 单一编译器——与匹配创建圈档同口径,
|
||||
杜绝谓词漂移。无启用类型 → 空集(fail-closed:无类型即无范围,与匹配创建
|
||||
每类型查询复用 _circle_ledger_base_query 固定条件(record_kinds_of(该类型
|
||||
范围规则)/未封存/有异动日期/未被有效 items 占用/T−2 成熟封顶)+
|
||||
apply_scope_filters 单一编译器——与匹配创建圈档同口径,杜绝谓词漂移。
|
||||
【2026-10-21 桶口径放开】待匹配桶随类型规则推导记录类型(未钉 record_kind
|
||||
的类型=出入站双轨):出入站未匹配记录都在桶里可见(一期"只收收料记录"
|
||||
旧契约随类型配置化退役;桶=待办可见性清单,不影响各类型实际圈定匹配)。
|
||||
【T−2 成熟封顶 2026-10-21】待匹配=可匹配:未成熟行(>T−2)不进桶,待成熟后
|
||||
自然出现。无启用类型 → 空集(fail-closed:无类型即无范围,与匹配创建
|
||||
NOT_CONFIGURED 语义一致)。已封存记录恒不在结果中(固定条件)。
|
||||
|
||||
Returns:
|
||||
@@ -317,9 +417,17 @@ def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
|
||||
"""
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
matured_date_to = eligible_movement_date_to(business_date_now())
|
||||
by_id: dict[int, TransferMovementLedger] = {}
|
||||
for config in get_enabled():
|
||||
query = apply_scope_filters(_circle_ledger_base_query(), TransferMovementLedger, config.scope_rules)
|
||||
query = apply_scope_filters(
|
||||
_circle_ledger_base_query(
|
||||
record_kinds=record_kinds_of(config.scope_rules),
|
||||
matured_date_to=matured_date_to,
|
||||
),
|
||||
TransferMovementLedger,
|
||||
config.scope_rules,
|
||||
)
|
||||
for record in query.all():
|
||||
by_id.setdefault(record.id, record)
|
||||
if not by_id:
|
||||
@@ -330,35 +438,75 @@ def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
|
||||
).all()
|
||||
|
||||
|
||||
def pending_ledger_query(*, matchable_ids: set[int] | None = None, segment: str = "all"):
|
||||
"""待匹配圈档查询:固定条件与 T−2,出入站都收,不按调拨类型范围过滤。
|
||||
|
||||
【AI 触发时机】首页「待匹配」计数和清单需要「已落档、尚未匹配」的全量时调用。
|
||||
库存匹配卡上的「当前可匹配」不要用本查询的 all 段,那是启用类型范围并集。
|
||||
|
||||
核心逻辑:复用 _circle_ledger_base_query(未封存、异动日期非空、未被占用、
|
||||
movement_date ≤ T−2),record_kinds 固定为 inbound 与 outbound。
|
||||
segment=matchable 只留 matchable_ids;segment=outside 排除这些 id;
|
||||
并集为空时 matchable 段为空查询,outside 段等于 all。
|
||||
|
||||
Args:
|
||||
matchable_ids: 启用类型范围并集的档 id。all 段忽略。
|
||||
segment: all、matchable 或 outside。
|
||||
|
||||
Returns:
|
||||
已按异动日期、来源、单号、id 排序的 Query。
|
||||
"""
|
||||
matured_date_to = eligible_movement_date_to(business_date_now())
|
||||
query = _circle_ledger_base_query(
|
||||
record_kinds=("inbound", "outbound"),
|
||||
matured_date_to=matured_date_to,
|
||||
)
|
||||
# [STEP 1] 类型范围只用于把全量拆成「现在可匹配」和「其余已落档」。
|
||||
ids = matchable_ids or set()
|
||||
if segment == "matchable":
|
||||
query = query.filter(TransferMovementLedger.id.in_(ids) if ids else false())
|
||||
elif segment == "outside" and ids:
|
||||
query = query.filter(~TransferMovementLedger.id.in_(ids))
|
||||
return _order_circled_ledger(query)
|
||||
|
||||
|
||||
def _circle_ledger_records(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
rules: tuple[ScopeRule, ...],
|
||||
movement_date_from: str | None,
|
||||
movement_date_to: str | None,
|
||||
record_kinds: tuple[str, ...],
|
||||
exclude_occupied_by_matching_id: int | None = None,
|
||||
doc_nos: list[str] | None = None,
|
||||
matured_date_to: date | None = None,
|
||||
) -> list[TransferMovementLedger]:
|
||||
"""按快照规则+固定条件圈定档记录(匹配创建圈档与重查对账的共享底座/唯一实现)。
|
||||
|
||||
固定条件(规格 §6/§9)见 _circle_ledger_base_query(本函数叠加:来源 IN
|
||||
(所选来源)、movement_date 范围、快照范围规则(apply_scope_filters 单一
|
||||
编译器)、可选单号过滤)——两个调用方必须复用本函数,禁止各自手写固定条件
|
||||
(双份维护=谓词漂移温床)。
|
||||
(双份维护=谓词漂移温床)。record_kinds 原样传给底座,本函数不另给默认。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表。
|
||||
rules: 范围规则元组(parse_scope_rules 产物)。
|
||||
movement_date_from / movement_date_to: 可选异动日期范围(ISO 字符串)。
|
||||
record_kinds: 允许圈入的记录类型。有类型对象的调用方传
|
||||
record_kinds_of(config.scope_rules);没有类型对象时显式传入。必传。
|
||||
exclude_occupied_by_matching_id: 重查对账场景传入本匹配 id——本匹配自有
|
||||
items 不构成占用(允许刷新/补建);匹配创建圈档不传(任何有效占用
|
||||
都排除)。
|
||||
doc_nos: 可选单号过滤(重查 invoice_nos 限定范围时约束补圈)。
|
||||
matured_date_to: 可匹配截止日(T−2 成熟封顶,见底座);匹配创建圈档传值,
|
||||
重查对账不传(对账不做成熟裁剪,避免存量未成熟行误判档消失)。
|
||||
Returns:
|
||||
档记录列表(异动日期 → 来源 → 单号 → id 稳定排序,与明细视图同口径)。
|
||||
"""
|
||||
query = _circle_ledger_base_query(
|
||||
record_kinds=record_kinds,
|
||||
exclude_occupied_by_matching_id=exclude_occupied_by_matching_id,
|
||||
matured_date_to=matured_date_to,
|
||||
).filter(TransferMovementLedger.source_code.in_([str(code) for code in source_codes]))
|
||||
if movement_date_from:
|
||||
query = query.filter(TransferMovementLedger.movement_date >= str(movement_date_from))
|
||||
@@ -468,6 +616,61 @@ def item_external_lot_no(item: TransferInvoiceItem) -> str:
|
||||
return apply_field_transforms("lot_no", item.lot_no, rules) or ""
|
||||
|
||||
|
||||
def _sync_ready_evidence_before_circle(
|
||||
*,
|
||||
source_code: str,
|
||||
required_kinds: tuple[str, ...],
|
||||
kind_status: dict[str, dict],
|
||||
deps: TransferDeps,
|
||||
business_date: str,
|
||||
now: datetime,
|
||||
) -> None:
|
||||
"""确认匹配前:对所需流为 ready 的证据做幂等落档(只 flush,提交归调用方)。
|
||||
|
||||
【AI 触发时机】run_matching STEP 0 在圈档前调用——UI「就绪」只表示归档文件
|
||||
可用,不等于 transfer_movement_ledger 已有行(出站落档桥后部署、或回调桥
|
||||
失败时会出现空档);此处补一次与回调同口径的落档,sha 未变则幂等跳过。
|
||||
|
||||
核心逻辑:按 required_kinds 逐流;仅 file_status==ready 触发。入站走
|
||||
evidence_sync.sync_source_rows(deps + business_date);出站走
|
||||
outbound_evidence_sync.sync_outbound_source_rows。异常只打 warning,不抛——
|
||||
匹配主链路不得被单源落档失败整单炸掉(圈档仍按现有档事实进行;parse_failed
|
||||
由落档桥尽力标记后由下方状态分支反映)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
required_kinds: 本类型所需记录类型(inbound/outbound)。
|
||||
kind_status: 该来源各流的 resolve_source_file_status 投影。
|
||||
deps: 入站落档用的 TransferDeps(file_repository)。
|
||||
business_date: 业务日(入站新鲜度口径)。
|
||||
now: 落档时间基准。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
|
||||
from app.services.in_transit_transfer.outbound_evidence_sync import (
|
||||
sync_outbound_source_rows,
|
||||
)
|
||||
|
||||
for kind in required_kinds:
|
||||
status = kind_status.get(kind) or {}
|
||||
if status.get("file_status") not in _CONFIRMABLE_SYNC_STATUSES:
|
||||
continue
|
||||
try:
|
||||
if kind == "inbound":
|
||||
sync_source_rows(
|
||||
source_code=source_code, deps=deps,
|
||||
business_date=business_date, now=now,
|
||||
)
|
||||
elif kind == "outbound":
|
||||
sync_outbound_source_rows(source_code=source_code, now=now)
|
||||
except Exception as exc: # noqa: BLE001 —— 单源落档失败不阻断匹配
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_MATCH_EVIDENCE_SYNC_FAILED source=%s kind=%s error=%s",
|
||||
source_code, kind, exc,
|
||||
)
|
||||
|
||||
|
||||
def run_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
@@ -488,10 +691,14 @@ def run_matching(
|
||||
【出生翻转 2026-10-14】本函数不再做证据兜底对齐(align 已退役):STEP 0 改为
|
||||
「从档圈行建 items」——按类型快照范围规则+固定条件圈定档记录并逐记录创建
|
||||
item(创建即绑定 matching_id);随后既有库存评估链不变(以 items 为工作单元)。
|
||||
来源无可用文件时保留既有 UX:触发 RPA 抓取并按准备结果标来源阶段(来源阶段
|
||||
只影响进度展示,不阻断档圈定——档是镜像事实,不随当日文件可用性消失)。
|
||||
落库写入不在此 commit(随调用方事务:create_matching 末尾统一提交 / 异步
|
||||
Job handler 回写后提交)。
|
||||
来源阶段只影响进度展示,不阻断档圈定——档是镜像事实,不随当日文件可用性消失。
|
||||
入站 RPA 只在类型要求入站、且入站投影不是 ready / no_data / unconfigured /
|
||||
parse_failed 时触发;入站已确认无数据,或类型不要求入站,不得触发入站抓取。
|
||||
【确认匹配落档补齐】所需流为 ready 时先幂等落档再圈档(见
|
||||
_sync_ready_evidence_before_circle);所需流出站/入站 parse_failed 均记
|
||||
failed 进度。落库写入不在此 commit(随调用方事务:create_matching 末尾统一
|
||||
提交 / 异步 Job handler 回写后提交)。圈档记录类型取 record_kinds_of(本次
|
||||
已加载的 scope_rules):创建路径=类型现行规则,存量重跑=快照规则。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
@@ -528,23 +735,78 @@ def run_matching(
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
|
||||
# [STEP 0] 来源文件状态快照(进度展示与缺文件 RPA 触发;不阻断档圈定):
|
||||
# resolve 命中(含 sha)→ file_ready 留痕;未命中 → ensure_inbound_file_ready
|
||||
#(缺文件触发 RPA,既有 UX 保留);parse_failed 文件如实标 failed(解析失败
|
||||
# 分层:失败事实由落档桥落库,匹配不再解析)。
|
||||
# [STEP 0] 来源文件状态快照(进度展示;不阻断档圈定)。
|
||||
# 按类型所需证据流逐条投影。ensure_inbound_file_ready(reason=
|
||||
# matching_missing_ready_file)只在「inbound ∈ required_kinds」且入站投影
|
||||
# 不是 ready / no_data / unconfigured 时调用。所需流 parse_failed(入/出站)
|
||||
# 标 failed 并跳过该来源文件留痕。ready 流先幂等落档再圈档(补齐空档窗口)。
|
||||
# 入站 no_data、或不要求入站:不触发入站 RPA,进度记 file_ready(有 sha 则
|
||||
# 留痕,否则空 checksum),圈档照常进行。出站缺文件保持非阻断,这里不做出站 ensure。
|
||||
required_kinds = record_kinds_of(scope_rules)
|
||||
# ready=已有文件;no_data=确认当日无记录;unconfigured=该流未配置。三者都可确认,不抓取。
|
||||
skip_inbound_ensure = {"ready", "no_data", "unconfigured"}
|
||||
sources: list[SourceProgressDTO] = []
|
||||
file_snapshot: dict[str, Any] = {}
|
||||
|
||||
def _remember_ready(
|
||||
source_code: str, *, file_no: str | None, file_version: str | None, checksum: str,
|
||||
) -> None:
|
||||
"""把已有 checksum 的来源记入进度与 file_snapshot(不触发 RPA)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
file_no / file_version / checksum: 当前证据文件身份。
|
||||
"""
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": file_no,
|
||||
"file_version": file_version,
|
||||
"checksum": checksum,
|
||||
}
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=file_no, file_version=file_version, checksum=checksum,
|
||||
))
|
||||
|
||||
for source_code in source_codes:
|
||||
file_status = resolve_source_file_status(source_code=source_code) or {}
|
||||
checksum = file_status.get("file_sha256")
|
||||
if file_status.get("file_status") == "parse_failed":
|
||||
kind_status = {
|
||||
kind: resolve_source_file_status(source_code=source_code, record_kind=kind) or {}
|
||||
for kind in required_kinds
|
||||
}
|
||||
# [确认匹配落档补齐] ready → 幂等写入异动档(flush);失败仅日志,下方再投影。
|
||||
_sync_ready_evidence_before_circle(
|
||||
source_code=source_code,
|
||||
required_kinds=required_kinds,
|
||||
kind_status=kind_status,
|
||||
deps=deps,
|
||||
business_date=business_date,
|
||||
now=now,
|
||||
)
|
||||
# 落档可能把 ready 标成 parse_failed:补投影后再做门禁。
|
||||
kind_status = {
|
||||
kind: resolve_source_file_status(source_code=source_code, record_kind=kind) or {}
|
||||
for kind in required_kinds
|
||||
}
|
||||
inbound_required = "inbound" in required_kinds
|
||||
outbound_required = "outbound" in required_kinds
|
||||
inbound_status = kind_status.get("inbound") or {}
|
||||
outbound_status = kind_status.get("outbound") or {}
|
||||
inbound_state = inbound_status.get("file_status")
|
||||
outbound_state = outbound_status.get("file_status")
|
||||
if inbound_required and inbound_state == "parse_failed":
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code="TRANSFER_FILE_SCHEMA_INVALID",
|
||||
error_message="inbound file parse failed; see source file status",
|
||||
))
|
||||
continue
|
||||
if not checksum:
|
||||
if outbound_required and outbound_state == "parse_failed":
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code="TRANSFER_FILE_SCHEMA_INVALID",
|
||||
error_message="outbound file parse failed; see source file status",
|
||||
))
|
||||
continue
|
||||
if inbound_required and inbound_state not in skip_inbound_ensure:
|
||||
prepared = ensure_inbound_file_ready(
|
||||
source_code=source_code, business_date=business_date,
|
||||
repository=deps.file_repository, rpa_trigger=deps.rpa_trigger,
|
||||
@@ -552,18 +814,10 @@ def run_matching(
|
||||
)
|
||||
if prepared.stage == "file_ready" and prepared.file is not None:
|
||||
ready_file = prepared.file
|
||||
checksum = ready_file.checksum
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": ready_file.file_no,
|
||||
"file_version": ready_file.file_version,
|
||||
"checksum": ready_file.checksum,
|
||||
}
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=ready_file.file_no,
|
||||
file_version=ready_file.file_version,
|
||||
checksum=ready_file.checksum,
|
||||
))
|
||||
_remember_ready(
|
||||
source_code, file_no=ready_file.file_no,
|
||||
file_version=ready_file.file_version, checksum=ready_file.checksum,
|
||||
)
|
||||
else:
|
||||
# 等待 RPA 回调 / 触发失败:该来源本轮不阻断(档照常圈定)。
|
||||
sources.append(SourceProgressDTO(
|
||||
@@ -573,22 +827,36 @@ def run_matching(
|
||||
))
|
||||
continue
|
||||
else:
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": file_status.get("file_no"),
|
||||
"file_version": f"sha256:{checksum}"[:64],
|
||||
"checksum": checksum,
|
||||
}
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=file_status.get("file_no"),
|
||||
file_version=f"sha256:{checksum}"[:64],
|
||||
checksum=checksum,
|
||||
))
|
||||
# 不调用 ensure_inbound_file_ready。入站 ready 留入站 sha;仅出站且
|
||||
# 出站 ready 留出站 sha。no_data / 出站缺文件:空 checksum 的 file_ready。
|
||||
chosen: dict | None = None
|
||||
if inbound_required and inbound_state == "ready":
|
||||
chosen = inbound_status
|
||||
elif not inbound_required and outbound_state == "ready":
|
||||
chosen = outbound_status
|
||||
checksum = (chosen or {}).get("file_sha256")
|
||||
if checksum:
|
||||
_remember_ready(
|
||||
source_code,
|
||||
file_no=(chosen or {}).get("file_no"),
|
||||
file_version=movement_file_version(checksum),
|
||||
checksum=checksum,
|
||||
)
|
||||
else:
|
||||
sources.append(SourceProgressDTO(source_code=source_code, stage="file_ready"))
|
||||
|
||||
# [STEP 0b 圈档建 items(出生翻转核心)] 圈定未占用档记录并逐记录建 item。
|
||||
ledger_records = _circle_ledger_records(
|
||||
source_codes=list(source_codes), rules=scope_rules,
|
||||
movement_date_from=movement_date_from, movement_date_to=movement_date_to,
|
||||
# [STEP 0b 圈档建 items(出生翻转核心)] 圈定未占用档记录;同 grain 多档择一
|
||||
# 再建 item(uq_transfer_invoice_items_matching_grain;不累加防重解析翻倍)。
|
||||
# 【T−2 成熟封顶 2026-10-21】只圈 movement_date ≤ T−2 的成熟记录——T−1/当天
|
||||
# 未成熟不匹配,留在档内待成熟后自然进圈(「不回退退役决策,仅落简化成熟
|
||||
# 边界」:无成熟行级状态,不做逐行标记)。
|
||||
ledger_records = _dedupe_ledger_records_for_item_birth(
|
||||
_circle_ledger_records(
|
||||
source_codes=list(source_codes), rules=scope_rules,
|
||||
movement_date_from=movement_date_from, movement_date_to=movement_date_to,
|
||||
record_kinds=required_kinds,
|
||||
matured_date_to=eligible_movement_date_to(business_date),
|
||||
)
|
||||
)
|
||||
born: list[TransferInvoiceItem] = []
|
||||
for record in ledger_records:
|
||||
@@ -878,6 +1146,51 @@ def _generate_no(prefix: str, business_date: str) -> str:
|
||||
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
|
||||
|
||||
|
||||
def _item_evidence_kind(item: TransferInvoiceItem) -> str:
|
||||
"""行文件对账使用的证据流。
|
||||
|
||||
核心逻辑:有档关联时取档记录 record_kind(出站行对出站文件);无档关联回落
|
||||
入站,与 resolve_source_file_status 的缺省一致。
|
||||
|
||||
Args:
|
||||
item: 匹配明细行(ledger_record 可空)。
|
||||
Returns:
|
||||
inbound 或 outbound。
|
||||
"""
|
||||
record = item.ledger_record
|
||||
kind = record.record_kind if record is not None else None
|
||||
if kind in ("inbound", "outbound"):
|
||||
return kind
|
||||
return "inbound"
|
||||
|
||||
|
||||
def _latest_evidence_files(
|
||||
items: list[TransferInvoiceItem],
|
||||
*,
|
||||
resolve=None,
|
||||
) -> dict[tuple[str, str], dict]:
|
||||
"""按 (source_code, record_kind) 缓存当前可用证据文件投影。
|
||||
|
||||
核心逻辑:同一来源的入站与出站文件分开投影。resolve 缺省用本模块的
|
||||
resolve_source_file_status;执行门禁传入自己命名空间里的同名函数,这样
|
||||
测试替身打在调用方模块上仍然生效。
|
||||
|
||||
Args:
|
||||
items: 待装饰或待门禁的明细行。
|
||||
resolve: 状态投影函数,签名 (source_code, record_kind) → dict。
|
||||
Returns:
|
||||
(source_code, record_kind) → 文件状态投影。
|
||||
"""
|
||||
lookup = resolve or resolve_source_file_status
|
||||
keys = sorted({
|
||||
(item.source_code, _item_evidence_kind(item)) for item in items
|
||||
})
|
||||
return {
|
||||
(source_code, kind): lookup(source_code=source_code, record_kind=kind) or {}
|
||||
for source_code, kind in keys
|
||||
}
|
||||
|
||||
|
||||
def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
"""读取行的文件版本戳(行当前性判定锚点,规格 §10 改锚)。
|
||||
|
||||
@@ -931,7 +1244,8 @@ def create_matching(
|
||||
【出生翻转 2026-10-14】先落 Run + Matching(flush 取 id)再驱动 run_matching:
|
||||
圈档建行时 matching_id/run_id 出生即绑定(D17 占用互斥与取消释放的归属基础),
|
||||
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
|
||||
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。
|
||||
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
|
||||
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
@@ -1094,12 +1408,9 @@ def restore_matching(
|
||||
invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED]
|
||||
rows = [row for row in rows_all if row.result_code != RESULT_FILE_REMOVED]
|
||||
|
||||
# [STEP 2] 文件对账映射:自有行去重来源逐个投影当前可用文件版本,
|
||||
# 行评估版本戳与之比对得 file_current(来源无可用文件 → False)。
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({row.source_code for row in rows})
|
||||
}
|
||||
# [STEP 2] 文件对账映射:按 (来源, 档记录 record_kind) 投影当前可用文件。
|
||||
# 无档关联回落入站。行评估版本戳与之比对得 file_current(无可用文件 → False)。
|
||||
latest_files = _latest_evidence_files(rows)
|
||||
|
||||
# [STEP 3] counts 按自有行实时聚合。
|
||||
# pending/invalid 两桶为 2026-09-25 counts 契约扩展(同口径内存计算)。
|
||||
@@ -1131,7 +1442,11 @@ def restore_matching(
|
||||
items = []
|
||||
for item in rows:
|
||||
items.append(
|
||||
_item_dto(item, latest_files.get(item.source_code) or {}, moment, ttl_seconds)
|
||||
_item_dto(
|
||||
item,
|
||||
latest_files.get((item.source_code, _item_evidence_kind(item))) or {},
|
||||
moment, ttl_seconds,
|
||||
)
|
||||
)
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
@@ -1167,7 +1482,7 @@ def _item_dto(
|
||||
|
||||
Args:
|
||||
item: 明细行。
|
||||
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
|
||||
latest: 该行证据流的当前文件状态投影(按档 record_kind 解析;无档为入站)。
|
||||
moment: 新鲜度判定基准时间。
|
||||
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
|
||||
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||
@@ -1215,8 +1530,8 @@ def _item_dto(
|
||||
# (库存查得时刻,仅匹配评估/重查/写前复查写入)——原 updated_at 时钟
|
||||
# 被证据同步换戳每日续期,徽标对老行永不触发;stale=距库存取数超过
|
||||
# 展示阈值(inventory_stale_ttl_seconds),无库存数据(NULL)不判定;
|
||||
# file_current=行评估版本戳仍是该来源当前可用文件 sha
|
||||
# (无版本戳或无可用文件均视为不一致 → False)。
|
||||
# file_current=行评估版本戳仍是该行证据流(档 record_kind,无档则入站)
|
||||
# 当前可用文件 sha(无版本戳或无可用文件均视为不一致 → False)。
|
||||
item_id=item.id,
|
||||
checked_at=inventory_checked_at.isoformat() if inventory_checked_at else None,
|
||||
stale=bool(inventory_checked_at)
|
||||
@@ -1272,12 +1587,13 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
)
|
||||
.all()
|
||||
)
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({row.source_code for row in rows})
|
||||
}
|
||||
latest_files = _latest_evidence_files(rows)
|
||||
items = [
|
||||
_item_dto(row, latest_files.get(row.source_code) or {}, moment, ttl_seconds)
|
||||
_item_dto(
|
||||
row,
|
||||
latest_files.get((row.source_code, _item_evidence_kind(row))) or {},
|
||||
moment, ttl_seconds,
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
return {"items": items, "counts": {"executable_count": len(rows)}}
|
||||
@@ -76,6 +76,14 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("odm_name", "ODM名称", MovementFieldValueType.TEXT),
|
||||
MovementField("carton_id", "箱号", MovementFieldValueType.TEXT),
|
||||
MovementField("pallet_id", "栈板号", MovementFieldValueType.TEXT),
|
||||
# ---- 2026-10-21 扩展:外部单据身份(外部单号/外部项次;CRANE/Lognet 出站
|
||||
# 报告的 WMS Order #/行号)——解析放行空值(required=False),不进匹配身份
|
||||
#(is_identity=False:匹配 grain 仍=单号/料号/异动日期,契约测试钉死不受扰);
|
||||
# 但两字段自 2026-10-21 起作为库存异动档自然键成分(模型
|
||||
# uq_transfer_movement_ledger_natural_key + ledger_sync 行级键)承担档幂等
|
||||
# 主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。
|
||||
MovementField("external_doc_no", "外部单号", MovementFieldValueType.TEXT),
|
||||
MovementField("external_line_no", "外部项次", MovementFieldValueType.TEXT),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用
|
||||
归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes /
|
||||
维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、
|
||||
file_preparation(ReadyInboundFile 契约)、openpyxl。
|
||||
file_preparation(ReadyInboundFile 契约)、ledger_sync.movement_file_version
|
||||
(file_version 戳的唯一生成处)、openpyxl。
|
||||
逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新
|
||||
【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失
|
||||
或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
@@ -37,6 +38,7 @@ from app.services.freight_rpa.reports.queries import (
|
||||
read_inbound_file_bytes,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
|
||||
from app.services.in_transit_transfer.ledger_sync import movement_file_version
|
||||
|
||||
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
|
||||
_HEADER_WS_RE = re.compile(r"\s+")
|
||||
@@ -126,7 +128,7 @@ class ShippingInboundFileRepository:
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
file_no=view.original_filename or str(view.file_id),
|
||||
file_version=f"sha256:{view.sha256}"[:64],
|
||||
file_version=movement_file_version(view.sha256),
|
||||
checksum=view.sha256,
|
||||
rows=tuple(rows),
|
||||
)
|
||||
@@ -155,7 +157,7 @@ class ShippingInboundFileRepository:
|
||||
file_id=view.file_id,
|
||||
storage_key=view.storage_key,
|
||||
sha256=view.sha256,
|
||||
file_version=f"sha256:{view.sha256}"[:64],
|
||||
file_version=movement_file_version(view.sha256),
|
||||
archived_at=view.created_at,
|
||||
original_filename=view.original_filename,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""services/in_transit_transfer/outbound_evidence_sync.py
|
||||
|
||||
用途:出站证据同步——出站回调 success 后把该来源最新可用出站归档按
|
||||
purpose='outbound' 已发布解析规则解析、以 record_kind='outbound' 幂等落档
|
||||
(transfer_movement_ledger),与 evidence_sync(入站专用,record_kind='inbound')
|
||||
完全对称;解析失败把 parse_failed 三列独立落到出站归档文件上(2026-10-16
|
||||
出站落档桥补齐——此前出站链路止步于归档+状态投影,异动档恒无 outbound 行)。
|
||||
依赖:ledger_sync(sync_ledger_rows / RECORD_KIND_OUTBOUND / FileMeta /
|
||||
movement_file_version)、
|
||||
evidence_sync(parse_archive_to_ledger_rows 解析组装单一口径 +
|
||||
_detect_natural_key_collapses/_natural_key_collapse_event 坍缩守卫 + SyncOutcome)、
|
||||
movement_file_repository._extract_movement_rows(归档字节提取)、
|
||||
source_file_status.latest_usable_outbound_file(出站可用文件视图,当天新鲜度
|
||||
口径)、freight_rpa.reports.queries(get_outbound_config /
|
||||
mark_outbound_parse_failure / clear_outbound_parse_failure)、file_asset_storage、
|
||||
models、audit、db。
|
||||
逻辑:sync_outbound_source_rows 只 flush 不 commit(提交归属调用方,契约同入站
|
||||
sync_source_rows);sync_and_commit_for_outbound_callback 桥自行 commit +
|
||||
异常全吞(B3 桥隔离——出站归档主链路不得被落档失败波及),schema 类失败
|
||||
rollback 后把失败事实独立 commit 到当前可用文件(入站同款解析失败分层)。
|
||||
规则门禁 fail-closed:无配置 / 未绑定规则 / 规则未发布 / purpose≠outbound
|
||||
→ no-op(None)——规则缺失不是文件错误,不落解析失败标记(与入站仓库
|
||||
latest_ready_file 门禁同口径)。cross_flag 交叉校验沿用 ledger_sync 既有
|
||||
口径(当前仅 inbound 定义矛盾标志,outbound 行不计数)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import FreightRpaParsingProfile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_outbound_parse_failure,
|
||||
get_outbound_config,
|
||||
mark_outbound_parse_failure,
|
||||
)
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.evidence_sync import (
|
||||
SyncOutcome,
|
||||
_detect_natural_key_collapses,
|
||||
_natural_key_collapse_event,
|
||||
parse_archive_to_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
RECORD_KIND_OUTBOUND,
|
||||
FileMeta,
|
||||
movement_file_version,
|
||||
sync_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
|
||||
from app.services.in_transit_transfer.source_file_status import latest_usable_outbound_file
|
||||
|
||||
_TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
# schema 类解析失败判据与入站桥同一口径(code 或异常类型)。
|
||||
_SCHEMA_FAILURE_CODES = (_TRANSFER_FILE_SCHEMA_INVALID,)
|
||||
|
||||
|
||||
def _load_published_outbound_profile(source_code: str) -> FreightRpaParsingProfile | None:
|
||||
"""加载来源出站配置绑定的「已发布 purpose='outbound'」解析规则(fail-closed 门禁)。
|
||||
|
||||
核心逻辑:出站配置(get_outbound_config,缺失=None)→ parsing_profile_id →
|
||||
规则行须 published 且 purpose='outbound'——与运行期入站取数门禁
|
||||
(movement_file_repository.latest_ready_file 的 published inbound 校验)同构。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
Returns:
|
||||
FreightRpaParsingProfile;任一环节缺失或门禁不符返回 None。
|
||||
"""
|
||||
config = get_outbound_config(source_code)
|
||||
if config is None or config.parsing_profile_id is None:
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, config.parsing_profile_id)
|
||||
if profile is None or profile.status != "published" or profile.purpose != "outbound":
|
||||
return None
|
||||
return profile
|
||||
|
||||
|
||||
def sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用出站归档并幂等落档(零外部调用,flush 不 commit)。
|
||||
|
||||
【AI 触发时机】出站 RPA 回调桥(sync_and_commit_for_outbound_callback)调用;
|
||||
不要在匹配/重查链路调用(匹配从档圈定,不写档)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 落档时间基准(插入/更新显式续 updated_at;文件新鲜度判定时刻)。
|
||||
Returns:
|
||||
SyncOutcome;无可用出站文件或无 published outbound 规则返回 None
|
||||
(该分支不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
|
||||
Raises:
|
||||
MovementFileSchemaError: 行必填缺失/非法(schema 类失败原样上抛——桥内
|
||||
rollback + 落解析失败标记)。
|
||||
"""
|
||||
file_view = latest_usable_outbound_file(source_code, now=now)
|
||||
if file_view is None:
|
||||
return None
|
||||
profile = _load_published_outbound_profile(source_code)
|
||||
if profile is None:
|
||||
return None
|
||||
definition = profile.definition_json or {}
|
||||
|
||||
# [STEP 1] 归档字节 → 原始行(提取口径与运行期入站/清空重建同源)→ 档行
|
||||
# (parse_archive_to_ledger_rows 解析组装单一口径;schema 类失败原样上抛)。
|
||||
data = file_asset_storage.get_bytes(file_view.storage_key)
|
||||
raw_rows = _extract_movement_rows(
|
||||
data,
|
||||
field_mapping=dict(definition.get("field_mapping") or {}),
|
||||
sheet_name=str(definition.get("sheet_name") or "").strip() or None,
|
||||
header_row_index=definition.get("header_row_index"),
|
||||
)
|
||||
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
|
||||
|
||||
# [STEP 2] 幂等落档(record_kind='outbound');溯源文件三元组取当前可用归档。
|
||||
# file_version 走 movement_file_version:出站归档无独立版本列,戳与入站仓库、
|
||||
# 清空重建、匹配进度快照同一函数,避免再在此处自行拼接超长。
|
||||
outcome = sync_ledger_rows(
|
||||
source_code=source_code,
|
||||
record_kind=RECORD_KIND_OUTBOUND,
|
||||
parsed_rows=assembled,
|
||||
file_meta=FileMeta(
|
||||
source_file_id=file_view.file_id,
|
||||
file_version=movement_file_version(file_view.sha256),
|
||||
file_sha256=file_view.sha256,
|
||||
),
|
||||
now=now,
|
||||
)
|
||||
# [档自然键坍缩守卫] 与入站同口径复检(检测按行级六成分、record_kind 声明进
|
||||
# 审计聚合键);仅实际落档时打事件,幂等重落不刷审计。
|
||||
collapses = _detect_natural_key_collapses(assembled)
|
||||
if collapses and (outcome.inserted or outcome.updated):
|
||||
for collapse in collapses:
|
||||
db.session.add(_natural_key_collapse_event(
|
||||
source_code=source_code, collapse=collapse, record_kind=RECORD_KIND_OUTBOUND))
|
||||
result = SyncOutcome(
|
||||
source_code=source_code,
|
||||
file_sha256=file_view.sha256 or "",
|
||||
inserted=outcome.inserted,
|
||||
updated=outcome.updated,
|
||||
skipped=outcome.skipped,
|
||||
sealed_skipped=outcome.sealed_skipped,
|
||||
cross_flagged=outcome.cross_flagged,
|
||||
)
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EVIDENCE_SYNCED",
|
||||
aggregate_type="transfer_source",
|
||||
aggregate_id=source_code,
|
||||
actor_type="system",
|
||||
result="success",
|
||||
after={
|
||||
"file_sha256": result.file_sha256,
|
||||
"record_kind": RECORD_KIND_OUTBOUND,
|
||||
"inserted": result.inserted, "updated": result.updated,
|
||||
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
|
||||
"cross_flagged": result.cross_flagged,
|
||||
},
|
||||
))
|
||||
# [解析失败分层] 同步成功 = 当前可用文件已成功解析:清除失败标记(若此前
|
||||
# 失败过),出站流状态投影随之恢复 ready。只 flush 不 commit。
|
||||
if file_view.parse_failed_at is not None:
|
||||
clear_outbound_parse_failure(file_view.file_id)
|
||||
return result
|
||||
|
||||
|
||||
def sync_and_commit_for_outbound_callback(*, source_code: str, now: datetime) -> bool:
|
||||
"""出站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
|
||||
|
||||
【AI 触发时机】出站 RPA 回调 success 终态落文件后由
|
||||
handle_outbound_report(outbound_report_handler)调用——桥是记账不是出站
|
||||
链路的正确性依赖,任何异常不得向出站归档主链路传播(B3:必须自行 commit)。
|
||||
【解析失败分层】失败路径先 rollback(桥隔离),仅 schema 类解析失败把失败
|
||||
事实(parse_failed 三列)独立 commit 落到当前可用出站文件上;丢失的落档由
|
||||
回调重试/出站重抓兜底。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(出站单元行上的 source_code)。
|
||||
now: 落档时间基准。
|
||||
Returns:
|
||||
True=落档成功或无事可做(无可用文件/无可用规则);False=落档失败
|
||||
(已记日志;schema 类失败尽力把解析失败标记落库并独立提交,标记失败
|
||||
仅告警不影响返回)。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
|
||||
# [桥隔离] sync_outbound_source_rows 只 flush 不 commit;桥由回调事实
|
||||
# 处理在归档 commit 之后独立调用,必须在此自行提交(B3 持久性教训)。
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_OUTBOUND_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
|
||||
source_code, outcome.inserted, outcome.updated,
|
||||
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志
|
||||
# [桥隔离] 落档崩溃绝不波及出站归档终态;丢失的落档由回调重试/重抓兜底。
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_OUTBOUND_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
|
||||
db.session.rollback()
|
||||
# [解析失败分层] rollback 之后再写标记;仅 schema 类失败落库——通用异常
|
||||
# (网络/DB 故障等)不是文件解析问题,不落标记。标记写入后独立 commit
|
||||
# (落档数据已回滚,本次 commit 只持久化失败事实),仍返回 False。
|
||||
# 标记写入是尽力而为:再抛异常也必须吞掉(B3 优先),丢失标记由下次重试补。
|
||||
try:
|
||||
code = getattr(exc, "code", None) or ""
|
||||
if code in _SCHEMA_FAILURE_CODES or isinstance(exc, MovementFileSchemaError):
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
file_view = latest_usable_outbound_file(source_code, now=now)
|
||||
if file_view is not None:
|
||||
mark_outbound_parse_failure(
|
||||
file_view.file_id,
|
||||
error_code=str(code or _TRANSFER_FILE_SCHEMA_INVALID),
|
||||
error_message=str(detail)[:2000],
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_OUTBOUND_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc)
|
||||
return False
|
||||
@@ -15,6 +15,9 @@ services/in_transit_transfer/outbound_report_handler.py
|
||||
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
|
||||
状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed;
|
||||
无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。
|
||||
【STEP 4 出站证据同步 2026-10-16】success 事实把最新可用出站归档按
|
||||
purpose=outbound 规则解析、record_kind='outbound' 落异动档(与入站
|
||||
handle_inbound_report STEP 4 对称;桥内自吞异常并自行 commit)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -80,9 +83,10 @@ def handle_outbound_report(fact: ReportFact) -> None:
|
||||
核心逻辑:
|
||||
[STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改
|
||||
status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3]
|
||||
推进结果必须在此提交;[STEP 4] 精确定位本次回调收尾的执行单元并回写出站
|
||||
排程进度、归集终态。不调用入站 evidence_sync(record_kind=inbound 专用)。
|
||||
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
|
||||
推进结果必须在此提交;[STEP 4] success 事实触发出站证据同步
|
||||
(outbound_evidence_sync,record_kind='outbound',与入站 STEP 4 对称);
|
||||
[STEP 5] 精确定位本次回调收尾的执行单元并回写出站排程进度、归集终态。
|
||||
【不捕获异常】任何一步失败原样外抛供 Worker 重试(STEP 4 桥内自吞)。
|
||||
|
||||
Args:
|
||||
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
|
||||
@@ -122,7 +126,20 @@ def handle_outbound_report(fact: ReportFact) -> None:
|
||||
if advanced is not None:
|
||||
db.session.commit()
|
||||
|
||||
# [STEP 4] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
|
||||
# [STEP 4] 出站证据同步:success 事实(ok 且 file_id 有值)后把该来源最新
|
||||
# 可用出站归档按 purpose=outbound 规则解析、record_kind='outbound' 落异动档
|
||||
# (与入站 handle_inbound_report STEP 4 对称:按 ok 触发、不依赖等待任务存在;
|
||||
# 桥内自吞异常并自行 commit,本处不包 try——文件已提交,Worker 重试即可补齐)。
|
||||
if fact.ok and fact.file_id is not None:
|
||||
from app.services.in_transit_transfer.outbound_evidence_sync import (
|
||||
sync_and_commit_for_outbound_callback,
|
||||
)
|
||||
|
||||
sync_and_commit_for_outbound_callback(
|
||||
source_code=fact.source_code, now=datetime.utcnow(),
|
||||
)
|
||||
|
||||
# [STEP 5] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
|
||||
schedule_run_id: int | None = None
|
||||
if fact.unit_run_id is not None:
|
||||
unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id))
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps、
|
||||
scope_rules.parse_scope_rules、scope_rules.record_kinds_of。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
|
||||
【2026-10-14 对档对账(ADR 0001/规格 §9)】requery_items(匹配号入口)前置
|
||||
「对档重圈 → 与本匹配自有 items 对账」:档新增记录 → 补建 item(绑同一
|
||||
匹配);档证据变 → 刷新 item 证据并重置待查;档记录消失 → item 失效隔离
|
||||
(沿用 blocked_file_removed 语义退出主视图)。圈档复用匹配创建的同一函数
|
||||
(_circle_ledger_records:固定条件单点实现)+ 同一快照规则(scope_json),
|
||||
(_circle_ledger_records:固定条件单点实现;记录类型取
|
||||
record_kinds_of(快照 scope_rules))+ 同一快照规则(scope_json),
|
||||
D17 占用互斥排除「其他匹配」的有效占用(本匹配自有 items 不构成占用);
|
||||
终态行(已执行/人工关闭/取消/在流)绝不触碰——已执行行不得被证据刷新
|
||||
复活(防同批档证据更新促成二次写 ERP)。
|
||||
@@ -53,12 +55,14 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
TransferDeps,
|
||||
_born_item_from_record,
|
||||
_circle_ledger_records,
|
||||
_dedupe_ledger_records_for_item_birth,
|
||||
_item_grain_of_ledger,
|
||||
_resolve_route_with_config,
|
||||
_SYNC_TERMINAL_STATUSES,
|
||||
item_external_lot_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.scope_rules import parse_scope_rules
|
||||
from app.services.in_transit_transfer.scope_rules import parse_scope_rules, record_kinds_of
|
||||
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
|
||||
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
|
||||
|
||||
@@ -450,7 +454,9 @@ def _reconcile_items_with_ledger(
|
||||
|
||||
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 异动日期范围)圈定
|
||||
档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点
|
||||
实现,杜绝谓词漂移),排除已执行封存、其他匹配的有效占用(D17;本匹配自有
|
||||
实现,杜绝谓词漂移)。记录类型取 record_kinds_of(已解析的快照 rules)
|
||||
(仅没有范围规则、也没有类型对象的调用点才显式只圈 inbound)。
|
||||
排除已执行封存、其他匹配的有效占用(D17;本匹配自有
|
||||
items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_
|
||||
SUCCESS/MANUALLY_CLOSED/CANCELLED/EXECUTING/RESULT_UNKNOWN 行绝不触碰——
|
||||
已执行行不得被证据刷新复活,否则同批档证据更新会促成二次写 ERP**):
|
||||
@@ -483,13 +489,16 @@ def _reconcile_items_with_ledger(
|
||||
sources = [str(code) for code in (scope.get("source_codes") or [])]
|
||||
records: list = []
|
||||
if sources:
|
||||
records = _circle_ledger_records(
|
||||
source_codes=sources,
|
||||
rules=rules,
|
||||
movement_date_from=scope.get("movement_date_from"),
|
||||
movement_date_to=scope.get("movement_date_to"),
|
||||
exclude_occupied_by_matching_id=matching.id,
|
||||
doc_nos=wanted_doc_nos,
|
||||
records = _dedupe_ledger_records_for_item_birth(
|
||||
_circle_ledger_records(
|
||||
source_codes=sources,
|
||||
rules=rules,
|
||||
movement_date_from=scope.get("movement_date_from"),
|
||||
movement_date_to=scope.get("movement_date_to"),
|
||||
record_kinds=record_kinds_of(rules),
|
||||
exclude_occupied_by_matching_id=matching.id,
|
||||
doc_nos=wanted_doc_nos,
|
||||
)
|
||||
)
|
||||
|
||||
# 类型配置(仓库定义):从快照类型码读现行配置(存量不要求启用)。
|
||||
@@ -505,15 +514,24 @@ def _reconcile_items_with_ledger(
|
||||
|
||||
# [终态守卫·占用面] own_by_record 收全部自有行(含终态):档记录已被本匹配
|
||||
# 任一行(含已执行行)绑定时按「档有行有」处理——终态绑定永不补建第二个 item
|
||||
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。
|
||||
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。同 grain 兄弟档亦视为已绑。
|
||||
own_by_record = {
|
||||
item.ledger_record_id: item
|
||||
for item in matching.items
|
||||
if item.ledger_record_id is not None
|
||||
}
|
||||
own_grains = {
|
||||
(str(item.source_code or ""), str(item.invoice_no or ""),
|
||||
str(item.material_no or ""), str(item.movement_date or ""))
|
||||
for item in matching.items
|
||||
}
|
||||
for record in records:
|
||||
item = own_by_record.get(record.id)
|
||||
if item is None:
|
||||
grain = _item_grain_of_ledger(record)
|
||||
if grain in own_grains:
|
||||
# 同 grain 已有自有 item(兄弟档 / 择优后的另一 ledger_record_id)。
|
||||
continue
|
||||
# [①补建] 档新增记录:绑同一匹配(D17:本匹配占用即成立)。
|
||||
route = None
|
||||
route_failed = False
|
||||
@@ -541,6 +559,7 @@ def _reconcile_items_with_ledger(
|
||||
else f"route not resolved for source {record.source_code}"
|
||||
)
|
||||
db.session.add(born)
|
||||
own_grains.add(grain)
|
||||
continue
|
||||
# [②证据对账] 只比对异动事实(数量/批号/仓库);名称/规格为展示字段。
|
||||
# [终态守卫·刷新面] 终态行(已执行/人工关闭/取消/在流)绝不触碰(含
|
||||
|
||||
@@ -5,16 +5,22 @@ services/in_transit_transfer/rpa_sinks.py
|
||||
outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。
|
||||
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
|
||||
freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、
|
||||
inbound_report_handler / outbound_report_handler。
|
||||
inbound_report_handler / outbound_report_handler、models。
|
||||
逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。
|
||||
进度类 sink 复刻 {'success':True,'data':...} envelope;文件事实经
|
||||
register_report_handler 注册。不 import shipping_notice。
|
||||
batch-ready:归档单元终态后立即尝试排程 finalize(文件返回= RPA/排程结束),
|
||||
再投递事实;事实处理(证据同步等)失败不得挡排程收口。不 import shipping_notice。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
_INBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
|
||||
_OUTBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
|
||||
|
||||
|
||||
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。"""
|
||||
@@ -25,20 +31,102 @@ def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]])
|
||||
return _sink
|
||||
|
||||
|
||||
def _try_finalize_inbound_schedule_after_unit(payload: dict[str, Any]) -> None:
|
||||
"""单元已落终态后按文件返回收口入站排程;解析/证据失败不得阻塞。
|
||||
|
||||
核心逻辑:用 callback_id 定位单元;仅当 status 已终态且挂了 schedule_run_id
|
||||
时 refresh + finalize_if_complete(幂等)。异常只记日志,不回滚已提交单元。
|
||||
"""
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
if not callback_id:
|
||||
return
|
||||
try:
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||
finalize_inbound_schedule_run_if_complete,
|
||||
refresh_inbound_schedule_run_progress,
|
||||
)
|
||||
|
||||
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None or unit.schedule_run_id is None:
|
||||
return
|
||||
if str(unit.status or '') not in _INBOUND_UNIT_TERMINAL:
|
||||
return
|
||||
refresh_inbound_schedule_run_progress(int(unit.schedule_run_id))
|
||||
finalize_inbound_schedule_run_if_complete(int(unit.schedule_run_id))
|
||||
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
|
||||
_LOG.warning(
|
||||
'inbound schedule finalize after unit terminal failed callback_id=%s: %s',
|
||||
callback_id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
def _try_finalize_outbound_schedule_after_unit(payload: dict[str, Any]) -> None:
|
||||
"""单元已落终态后按文件返回收口出站排程;解析/证据失败不得阻塞。"""
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
if not callback_id:
|
||||
return
|
||||
try:
|
||||
from app.models import FreightRpaOutboundUnitRun
|
||||
from app.services.schedule.freight_rpa_outbound_finalize import (
|
||||
finalize_outbound_schedule_run_if_complete,
|
||||
refresh_outbound_schedule_run_progress,
|
||||
)
|
||||
|
||||
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None or unit.schedule_run_id is None:
|
||||
return
|
||||
if str(unit.status or '') not in _OUTBOUND_UNIT_TERMINAL:
|
||||
return
|
||||
refresh_outbound_schedule_run_progress(int(unit.schedule_run_id))
|
||||
finalize_outbound_schedule_run_if_complete(int(unit.schedule_run_id))
|
||||
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
|
||||
_LOG.warning(
|
||||
'outbound schedule finalize after unit terminal failed callback_id=%s: %s',
|
||||
callback_id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
def _inbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""入站 batch-ready:归档 →(单元终态后)排程收口 → 返回;事实投递异常仍尽量收口排程。"""
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
try:
|
||||
data = ingest_inbound_callback(payload)
|
||||
return {'success': True, 'data': data}
|
||||
finally:
|
||||
# 单元终态已 commit 后,无论事实处理是否抛错,都按文件返回尝试排程 finalize。
|
||||
_try_finalize_inbound_schedule_after_unit(payload)
|
||||
|
||||
|
||||
def _outbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""出站 batch-ready:归档 →(单元终态后)排程收口 → 返回。"""
|
||||
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
|
||||
|
||||
try:
|
||||
data = ingest_outbound_callback(payload)
|
||||
return {'success': True, 'data': data}
|
||||
finally:
|
||||
_try_finalize_outbound_schedule_after_unit(payload)
|
||||
|
||||
|
||||
def register_inbound_sinks() -> None:
|
||||
"""注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。
|
||||
|
||||
核心逻辑:inbound-batch-ready 直挂 freight_rpa.inbound.report_archive.ingest_inbound_callback
|
||||
(与 outbound 对称,无 shipping_notice 薄壳);unit/batch-progress 挂
|
||||
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report。
|
||||
核心逻辑:inbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
|
||||
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report(证据/
|
||||
调拨推进;排程收口已在 batch-ready 侧完成,handler 内 finalize 仍幂等兜底)。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
from app.services.schedule import freight_rpa_inbound_finalize
|
||||
|
||||
register_sink('inbound-batch-ready', _success_data_envelope(ingest_inbound_callback))
|
||||
register_sink('inbound-batch-ready', _inbound_batch_ready_sink)
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress))
|
||||
register_report_handler('inbound', handle_inbound_report)
|
||||
@@ -47,17 +135,15 @@ def register_inbound_sinks() -> None:
|
||||
def register_outbound_sinks() -> None:
|
||||
"""注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。
|
||||
|
||||
核心逻辑:outbound-batch-ready 直挂 freight_rpa.outbound.report_archive.ingest_outbound_callback;
|
||||
unit/batch-progress 挂 schedule.freight_rpa_outbound_finalize;事实处理函数挂
|
||||
handle_outbound_report。
|
||||
核心逻辑:outbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
|
||||
schedule.freight_rpa_outbound_finalize;事实处理函数挂 handle_outbound_report。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
|
||||
from app.services.schedule import freight_rpa_outbound_finalize
|
||||
|
||||
register_sink('outbound-batch-ready', _success_data_envelope(ingest_outbound_callback))
|
||||
register_sink('outbound-batch-ready', _outbound_batch_ready_sink)
|
||||
register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing))
|
||||
register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress))
|
||||
register_report_handler('outbound', handle_outbound_report)
|
||||
@@ -5,7 +5,8 @@
|
||||
供匹配创建圈档、重查对账、管理页校验三处单一口径。
|
||||
依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。
|
||||
逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、
|
||||
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL。
|
||||
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL;
|
||||
record_kinds_of 从 record_kind 范围规则推导证据流(入站/出站)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,6 +26,7 @@ SCOPE_FIELDS: frozenset[str] = frozenset({
|
||||
})
|
||||
|
||||
_MATCHES = ("prefix", "equals", "contains", "in")
|
||||
_RECORD_KINDS = ("inbound", "outbound")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -71,6 +73,30 @@ def _hit(value: str | None, rule: ScopeRule) -> bool:
|
||||
return text in {v.upper() for v in rule.values} # in
|
||||
|
||||
|
||||
def record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]:
|
||||
"""从范围规则推导调拨类型需要的证据流(入站/出站)。
|
||||
|
||||
核心逻辑:筛 field=record_kind 的规则;无则默认双轨。多条规则时,各规则
|
||||
允许的 inbound/outbound 集合(与 evaluate 同口径 _hit)逐条取交集;结果按
|
||||
inbound→outbound 顺序输出,交集为空则返回空元组。
|
||||
|
||||
Args:
|
||||
rules: parse_scope_rules 产出的 ScopeRule 元组。
|
||||
Returns:
|
||||
仅含 inbound/outbound 的去重元组。
|
||||
"""
|
||||
kind_rules = [rule for rule in rules if rule.field == "record_kind"]
|
||||
if not kind_rules:
|
||||
return _RECORD_KINDS
|
||||
allowed: set[str] | None = None
|
||||
for rule in kind_rules:
|
||||
rule_allowed = {kind for kind in _RECORD_KINDS if _hit(kind, rule)}
|
||||
allowed = rule_allowed if allowed is None else allowed & rule_allowed
|
||||
if not allowed:
|
||||
return ()
|
||||
return tuple(kind for kind in _RECORD_KINDS if kind in allowed)
|
||||
|
||||
|
||||
def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool:
|
||||
"""内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。"""
|
||||
return all(_hit(record.get(rule.field), rule) for rule in rules)
|
||||
|
||||
@@ -1,60 +1,214 @@
|
||||
"""在途调拨来源入站文件状态投影服务。
|
||||
"""在途调拨来源证据文件状态投影服务。
|
||||
|
||||
用途:只读货代入站链路已有事实(入站执行单元行 + freight_rpa 入站归档文件),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
|
||||
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:freight_rpa.reports.queries(最新可用入站归档 / 失效文件存在性 / 解析失败
|
||||
标记的只读写入口——口径唯一权威);入站执行单元行模型(经域内别名引用)。
|
||||
逻辑:【阶段 B Task 4】模型查询全部改走 freight_rpa.reports.queries 只读入口——
|
||||
可用文件命中(当天业务日抓取且未过期未清理,口径见
|
||||
queries.usable_inbound_file_condition)→ ready,但文件已标记解析失败
|
||||
(parse_failed_at 非空)→ parse_failed(不可当 ready,仍带 file_no/
|
||||
file_sha256 便于诊断);有进行中单元 → fetching;最新单元为失败终态 →
|
||||
failed;空数据单元 → no_data;文件仍在但已失效 → expired;否则 → none。
|
||||
record/clear_inbound_parse_failure 保留为兼容薄壳(既有调用方按 ORM 文件
|
||||
对象传参),内部按主键委托 queries.mark/clear 同一实现(写入与清除均只
|
||||
flush 不 commit,事务归属调用方)。
|
||||
用途:只读货代入站/出站链路已有事实(执行单元行 + freight_rpa 归档文件),
|
||||
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
||||
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
||||
调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
|
||||
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
|
||||
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
|
||||
入站可用条件同口径)。
|
||||
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
||||
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
||||
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
||||
最新单元失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
出站先查 get_outbound_config,缺失 → unconfigured;有配置则对出站文件表与
|
||||
FreightRpaOutboundUnitRun 走同一顺序。列表接口走
|
||||
resolve_source_file_statuses:同一顺序一次性投影全部来源,查询次数不随
|
||||
来源个数增长。record/clear_inbound_parse_failure 仍是入站解析失败标记的
|
||||
兼容薄壳(按主键委托 queries.mark/clear,只 flush 不 commit,事务归属调用方)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
|
||||
from sqlalchemy import and_, not_, or_
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.freight_rpa_inbound_report import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
from app.models.freight_rpa_outbound_report import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
||||
expired_inbound_file_condition,
|
||||
get_outbound_config,
|
||||
has_expired_inbound_file,
|
||||
latest_usable_inbound_file,
|
||||
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
|
||||
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无入站记录,
|
||||
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无记录,
|
||||
# 属业务结果而非故障,独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
|
||||
NO_DATA_UNIT_STATUSES = ('empty',)
|
||||
_RECORD_KINDS = ('inbound', 'outbound')
|
||||
|
||||
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的入站文件状态投影。
|
||||
@dataclass(frozen=True)
|
||||
class _FileFact:
|
||||
"""批量投影用的文件身份,字段与单来源文件视图中参与状态判断的部分一致。"""
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
|
||||
freight_rpa.reports.queries 的可用/失效条件):保留期已到 或 非当前业务日
|
||||
(Asia/Shanghai)抓取。
|
||||
file_id: int
|
||||
original_filename: str
|
||||
sha256: str
|
||||
parse_failed_at: datetime | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _UnitFact:
|
||||
"""批量投影用的执行单元,只保留状态判断需要的 status。"""
|
||||
|
||||
status: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _OutboundFileView:
|
||||
"""出站归档文件只读视图,字段与入站 InboundFileView 对齐,供同一投影顺序读取。"""
|
||||
|
||||
file_id: int
|
||||
source_code: str
|
||||
sha256: str
|
||||
storage_key: str
|
||||
original_filename: str
|
||||
created_at: datetime
|
||||
parse_failed_at: datetime | None = None
|
||||
|
||||
|
||||
def _outbound_fresh_and_retention_valid(now: datetime):
|
||||
"""出站归档的新鲜度 + 保留期条件,列与入站 _fresh_and_retention_valid 同口径。
|
||||
|
||||
核心逻辑:业务日窗口用 date_policy.business_date_utc_window(与 queries 内联
|
||||
数学一致);archive_expires_at 为空视为长期有效。
|
||||
"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
FreightRpaOutboundReportFile.created_at >= window_start,
|
||||
FreightRpaOutboundReportFile.created_at < window_end,
|
||||
or_(
|
||||
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaOutboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> _OutboundFileView:
|
||||
"""把出站归档 ORM 行映射为冻结只读视图。"""
|
||||
return _OutboundFileView(
|
||||
file_id=report.id,
|
||||
source_code=report.unit_run.source_code,
|
||||
sha256=report.sha256,
|
||||
storage_key=report.storage_key,
|
||||
original_filename=report.original_filename,
|
||||
created_at=report.created_at,
|
||||
parse_failed_at=report.parse_failed_at,
|
||||
)
|
||||
|
||||
|
||||
def latest_usable_outbound_file(
|
||||
source_code: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> _OutboundFileView | None:
|
||||
"""返回某来源当前可用的出站归档只读视图,最新优先。
|
||||
|
||||
用途:出站证据流状态投影取文件身份;口径与 latest_usable_inbound_file 相同
|
||||
(未删除 + 当天业务日抓取 + 未过期),不读取对象存储字节。
|
||||
|
||||
核心逻辑:经出站执行单元行的 source_code 过滤,按 created_at/id 倒序取第一条。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(写在 FreightRpaOutboundUnitRun.source_code 上)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
|
||||
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
|
||||
仍带 file_no/file_sha256 便于诊断与前端提示。
|
||||
_OutboundFileView;无可用文件返回 None。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
report = (
|
||||
FreightRpaOutboundReportFile.query
|
||||
.join(FreightRpaOutboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
_outbound_fresh_and_retention_valid(now),
|
||||
)
|
||||
.order_by(FreightRpaOutboundReportFile.created_at.desc(), FreightRpaOutboundReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
return None
|
||||
return _outbound_file_view(report)
|
||||
|
||||
|
||||
def has_expired_outbound_file(source_code: str, *, now: datetime | None = None) -> bool:
|
||||
"""返回某来源是否存在未删除但已失效的出站归档(expired 投影依据)。
|
||||
|
||||
用途:出站状态投影在无可用文件、无进行中/终态单元之后,判断是否因隔日旧文件
|
||||
或保留期已到而提示重抓。只读不写。
|
||||
|
||||
核心逻辑:未删除且新鲜度+保留期不成立,与 has_expired_inbound_file 同核。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
存在失效但未清理的出站归档 → True;否则 False。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
expired = (
|
||||
FreightRpaOutboundReportFile.query
|
||||
.join(FreightRpaOutboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
not_(_outbound_fresh_and_retention_valid(now)),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return expired is not None
|
||||
|
||||
|
||||
def _empty_status(file_status: str) -> dict:
|
||||
"""没有可用文件身份时的投影字典。"""
|
||||
return {'file_status': file_status, 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
|
||||
def _status_from_facts(
|
||||
*,
|
||||
file_view: Any | None,
|
||||
active_unit: Any | None,
|
||||
latest_unit: Any | None,
|
||||
expired: bool,
|
||||
) -> dict:
|
||||
"""按既定优先级把已取到的文件与单元事实收成状态字典。
|
||||
|
||||
核心逻辑:可用文件(解析失败优先于 ready)→ 进行中单元 → 最新单元空数据 →
|
||||
最新单元失败终态 → 失效文件 → none。单来源与批量投影共用,避免两条路径
|
||||
各写一套优先级。
|
||||
|
||||
Args:
|
||||
file_view: 可用文件视图;须有 original_filename、file_id、parse_failed_at、sha256。
|
||||
没有可用文件时为 None。
|
||||
active_unit: 仍在进行的执行单元;没有时为 None。只要求对象存在。
|
||||
latest_unit: id 最大的执行单元;没有时为 None。须有 status。
|
||||
expired: 是否仍有未清理的失效归档。
|
||||
Returns:
|
||||
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
|
||||
"""
|
||||
# 【阶段 B Task 4】可用文件读取经 freight_rpa.reports.queries 只读视图
|
||||
# (file_no/failure 事实列随视图一次取得,不再引用归档文件模型)。
|
||||
file_view = latest_usable_inbound_file(source_code)
|
||||
if file_view is not None:
|
||||
file_no = file_view.original_filename or str(file_view.file_id)
|
||||
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
|
||||
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
|
||||
# 解析失败分层:文件本身可用但解析失败,不得当 ready,保留文件身份供诊断。
|
||||
if file_view.parse_failed_at is not None:
|
||||
return {
|
||||
'file_status': 'parse_failed',
|
||||
@@ -68,35 +222,288 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
'file_no': file_no,
|
||||
'file_sha256': file_view.sha256,
|
||||
}
|
||||
|
||||
active_unit = (
|
||||
FreightRpaInboundUnitRun.query
|
||||
.filter_by(source_code=source_code)
|
||||
.filter(FreightRpaInboundUnitRun.status.in_(RUNNING_UNIT_STATUSES))
|
||||
.order_by(FreightRpaInboundUnitRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if active_unit is not None:
|
||||
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
latest_unit = (
|
||||
FreightRpaInboundUnitRun.query
|
||||
.filter_by(source_code=source_code)
|
||||
.order_by(FreightRpaInboundUnitRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
return _empty_status('fetching')
|
||||
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
|
||||
# 空数据:抓取成功但当日无入站记录——如实投影 no_data,不得与抓取失败混淆。
|
||||
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
# 空数据:抓取成功但当日无记录——如实投影 no_data,不得与抓取失败混淆。
|
||||
return _empty_status('no_data')
|
||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
return _empty_status('failed')
|
||||
if expired:
|
||||
return _empty_status('expired')
|
||||
return _empty_status('none')
|
||||
|
||||
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
|
||||
# 【阶段 B Task 4】失效存在性经 queries.has_expired_inbound_file(与可用条件同核)。
|
||||
if has_expired_inbound_file(source_code):
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
def _project_file_status(
|
||||
source_code: str,
|
||||
*,
|
||||
latest_file: Callable[..., Any],
|
||||
unit_model: type,
|
||||
has_expired: Callable[..., bool],
|
||||
) -> dict:
|
||||
"""按入站既有顺序把文件视图与执行单元投影成文件状态。
|
||||
|
||||
核心逻辑:有可用文件就不再查单元;没有进行中单元才看最新单元;最新单元
|
||||
已是空数据或失败终态就不再查失效文件。入站与出站共用,差异只在三个协作参数。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
latest_file: 返回可用文件视图或 None;视图须有 original_filename、file_id、
|
||||
parse_failed_at、sha256。
|
||||
unit_model: 带 query/status/id/source_code 的执行单元模型。
|
||||
has_expired: 该来源是否仍有失效未清理文件。
|
||||
Returns:
|
||||
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
|
||||
"""
|
||||
file_view = latest_file(source_code)
|
||||
active_unit = None
|
||||
latest_unit = None
|
||||
expired = False
|
||||
if file_view is None:
|
||||
active_unit = (
|
||||
unit_model.query
|
||||
.filter_by(source_code=source_code)
|
||||
.filter(unit_model.status.in_(RUNNING_UNIT_STATUSES))
|
||||
.order_by(unit_model.id.desc())
|
||||
.first()
|
||||
)
|
||||
if active_unit is None:
|
||||
latest_unit = (
|
||||
unit_model.query
|
||||
.filter_by(source_code=source_code)
|
||||
.order_by(unit_model.id.desc())
|
||||
.first()
|
||||
)
|
||||
terminal = latest_unit is not None and latest_unit.status in (
|
||||
*NO_DATA_UNIT_STATUSES, *FAILED_UNIT_STATUSES,
|
||||
)
|
||||
if not terminal:
|
||||
expired = has_expired(source_code)
|
||||
return _status_from_facts(
|
||||
file_view=file_view,
|
||||
active_unit=active_unit,
|
||||
latest_unit=latest_unit,
|
||||
expired=expired,
|
||||
)
|
||||
|
||||
|
||||
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
||||
"""一次取出这批来源各自最新的可用归档。
|
||||
|
||||
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
||||
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
||||
Returns:
|
||||
source_code 到文件事实的映射;没有可用文件的来源不出现。
|
||||
"""
|
||||
rows = (
|
||||
file_model.query
|
||||
.join(unit_model, file_model.unit_run_id == unit_model.id)
|
||||
.filter(unit_model.source_id.in_(source_ids), *filters)
|
||||
.with_entities(
|
||||
unit_model.source_code,
|
||||
file_model.id,
|
||||
file_model.original_filename,
|
||||
file_model.sha256,
|
||||
file_model.parse_failed_at,
|
||||
)
|
||||
.order_by(file_model.created_at.desc(), file_model.id.desc())
|
||||
.all()
|
||||
)
|
||||
picked: dict[str, _FileFact] = {}
|
||||
for source_code, file_id, filename, sha256, parse_failed_at in rows:
|
||||
if source_code in picked:
|
||||
continue
|
||||
picked[str(source_code)] = _FileFact(
|
||||
file_id=file_id,
|
||||
original_filename=filename,
|
||||
sha256=sha256,
|
||||
parse_failed_at=parse_failed_at,
|
||||
)
|
||||
return picked
|
||||
|
||||
|
||||
def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str, _UnitFact], dict[str, _UnitFact]]:
|
||||
"""一次取出这批来源的最新单元,以及仍在进行的最新单元。
|
||||
|
||||
核心逻辑:按 id 倒序扫描,每个来源遇到的第一行就是最新单元;状态属于进行中
|
||||
的第一行就是该来源仍在抓取的单元。较新的失败单元因此盖不住更早仍在进行的单元。
|
||||
|
||||
Args:
|
||||
unit_model: 入站或出站执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
Returns:
|
||||
(最新单元, 进行中单元),键都是 source_code。没有单元时对应字典为空。
|
||||
"""
|
||||
rows = (
|
||||
unit_model.query
|
||||
.filter(unit_model.source_id.in_(source_ids))
|
||||
.with_entities(unit_model.source_code, unit_model.id, unit_model.status)
|
||||
.order_by(unit_model.id.desc())
|
||||
.all()
|
||||
)
|
||||
latest: dict[str, _UnitFact] = {}
|
||||
active: dict[str, _UnitFact] = {}
|
||||
for source_code, _unit_id, status in rows:
|
||||
code = str(source_code)
|
||||
if code not in latest:
|
||||
latest[code] = _UnitFact(status=status)
|
||||
if status in RUNNING_UNIT_STATUSES and code not in active:
|
||||
active[code] = _UnitFact(status=status)
|
||||
return latest, active
|
||||
|
||||
|
||||
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
||||
"""一次找出仍有失效未清理归档的来源编码。
|
||||
|
||||
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
||||
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 失效文件条件。
|
||||
Returns:
|
||||
至少有一份失效未清理归档的 source_code 集合。
|
||||
"""
|
||||
rows = (
|
||||
file_model.query
|
||||
.join(unit_model, file_model.unit_run_id == unit_model.id)
|
||||
.filter(unit_model.source_id.in_(source_ids), *filters)
|
||||
.with_entities(unit_model.source_code)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]) for row in rows}
|
||||
|
||||
|
||||
def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict]]:
|
||||
"""批量投影一组来源的入站与出站证据文件状态。
|
||||
|
||||
用途:GET /sources 渲染来源选择卡。来源个数增加时仍只做固定几条查询,
|
||||
供页面同时展示调拨类型和数据源时不必按来源等待。
|
||||
|
||||
核心逻辑:出站配置、入站/出站的可用文件、执行单元、失效文件各查一次,
|
||||
再按与 resolve_source_file_status 相同的优先级收口。没有出站配置的来源
|
||||
直接记 unconfigured,不把入站状态抄到出站。
|
||||
|
||||
Args:
|
||||
sources: 已加载的来源行,须有 id 与 source_code。空列表不查库。
|
||||
Returns:
|
||||
{source_code: {"inbound": 状态字典, "outbound": 状态字典}}。
|
||||
状态字典键与 resolve_source_file_status 相同。
|
||||
"""
|
||||
if not sources:
|
||||
return {}
|
||||
now = datetime.utcnow()
|
||||
source_ids = [int(source.id) for source in sources]
|
||||
configured_outbound = {
|
||||
int(row[0])
|
||||
for row in (
|
||||
FreightRpaOutboundReportConfig.query
|
||||
.filter(FreightRpaOutboundReportConfig.source_id.in_(source_ids))
|
||||
.with_entities(FreightRpaOutboundReportConfig.source_id)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
inbound_files = _latest_files_by_source(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
||||
inbound_expired = _expired_source_codes(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
outbound_files = _latest_files_by_source(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
source_ids,
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
_outbound_fresh_and_retention_valid(now),
|
||||
)
|
||||
outbound_latest, outbound_active = _units_by_source(FreightRpaOutboundUnitRun, source_ids)
|
||||
outbound_expired = _expired_source_codes(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
source_ids,
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
not_(_outbound_fresh_and_retention_valid(now)),
|
||||
)
|
||||
projected: dict[str, dict[str, dict]] = {}
|
||||
for source in sources:
|
||||
code = str(source.source_code)
|
||||
inbound = _status_from_facts(
|
||||
file_view=inbound_files.get(code),
|
||||
active_unit=inbound_active.get(code),
|
||||
latest_unit=inbound_latest.get(code),
|
||||
expired=code in inbound_expired,
|
||||
)
|
||||
if int(source.id) not in configured_outbound:
|
||||
outbound = _empty_status('unconfigured')
|
||||
else:
|
||||
outbound = _status_from_facts(
|
||||
file_view=outbound_files.get(code),
|
||||
active_unit=outbound_active.get(code),
|
||||
latest_unit=outbound_latest.get(code),
|
||||
expired=code in outbound_expired,
|
||||
)
|
||||
projected[code] = {'inbound': inbound, 'outbound': outbound}
|
||||
return projected
|
||||
|
||||
|
||||
def resolve_source_file_status(*, source_code: str, record_kind: str = 'inbound') -> dict:
|
||||
"""返回某来源在指定记录类型上的证据文件状态投影。
|
||||
|
||||
用途:来源列表与重试门禁按流入站或出站询问文件是否就绪。缺省 record_kind
|
||||
为 inbound,既有只传来源的调用返回值与改造前相同。
|
||||
|
||||
核心逻辑:record_kind 不是 inbound/outbound 时抛 ValidationError。出站先查
|
||||
get_outbound_config,没有配置行则 unconfigured,不再往下看文件或单元。
|
||||
有配置(以及全部入站)再按同一顺序投影。失效判定不依赖保留期清理任务:
|
||||
保留期已到,或非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound,默认 inbound。
|
||||
Returns:
|
||||
{"file_status", "has_ready_file", "file_no", "file_sha256"}。
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data',
|
||||
'expired', 'none', 'unconfigured'}。parse_failed 时 has_ready_file=False,
|
||||
仍带 file_no/file_sha256。unconfigured 仅出站且无出站报表配置时出现。
|
||||
Raises:
|
||||
ValidationError: record_kind 不是 inbound 或 outbound。
|
||||
"""
|
||||
if record_kind not in _RECORD_KINDS:
|
||||
raise ValidationError(
|
||||
f'unsupported record_kind: {record_kind}',
|
||||
details={'record_kind': record_kind},
|
||||
)
|
||||
if record_kind == 'outbound':
|
||||
if get_outbound_config(source_code) is None:
|
||||
return _empty_status('unconfigured')
|
||||
return _project_file_status(
|
||||
source_code,
|
||||
latest_file=latest_usable_outbound_file,
|
||||
unit_model=FreightRpaOutboundUnitRun,
|
||||
has_expired=has_expired_outbound_file,
|
||||
)
|
||||
return _project_file_status(
|
||||
source_code,
|
||||
latest_file=latest_usable_inbound_file,
|
||||
unit_model=FreightRpaInboundUnitRun,
|
||||
has_expired=has_expired_inbound_file,
|
||||
)
|
||||
|
||||
|
||||
def record_inbound_parse_failure(
|
||||
|
||||
Reference in new issue
Block a user