feat(in-transit-transfer): 更新证据下载与待匹配清单逻辑
- 修改证据下载接口,分别签发预览地址与带保存名的下载地址,避免浏览器使用对象键哈希作为保存名。 - 待匹配清单接口调整,按外部单号合计数量,不再返回外部项次,提升数据展示的清晰度。 - 移除待匹配桶的「清空并重新解析」功能,简化操作流程,确保用户体验一致性。 - 新增跨页全选支持的 API,允许用户在待处理池中选择全部待处理明细 ID,优化批量操作体验。
This commit is contained in:
1 parent
4c2a7e2a23
commit
663f401873
50 files changed
+2156
-1309
No files matched your search
@@ -1,9 +1,12 @@
|
||||
"""services/in_transit_transfer/backlog_reparse_service.py
|
||||
|
||||
用途:待匹配桶「清空并重新解析」(spec §6/D7,维护链路)——解析规则修改后,
|
||||
按来源 + 记录类型(inbound/outbound)把旧映射档行清空、以当前绑定解析规则
|
||||
重解析全部可重建归档、走常规 sync_ledger_rows 幂等重落;另提供只读预检供
|
||||
确认弹窗展示。
|
||||
用途:待匹配桶整桶重建的内部实现(spec §6/D7)。2026-10-22 起不再挂 HTTP:
|
||||
预检/执行路由已下线,待匹配界面不再提供入口。本模块仅保留给既有单测,
|
||||
锁住「先全量解析、失败一行不删」;禁止重新挂回
|
||||
/backlog/pending-match/reparse*。重解析产品入口只有当天最新归档
|
||||
(current_file_reparse)。
|
||||
历史语义:按来源 + 记录类型把旧映射档行清空,并以当前规则重解析全部
|
||||
可重建归档后幂等重落。
|
||||
依赖:movement_file_repository(ReparseableArchiveFile + _extract_movement_rows)、
|
||||
evidence_sync.parse_archive_to_ledger_rows(解析+组装单一口径)与
|
||||
_detect_natural_key_collapses/_natural_key_collapse_event、ledger_sync
|
||||
@@ -165,8 +168,7 @@ def preview_pending_match_reparse(
|
||||
) -> dict:
|
||||
"""清空并重新解析预检(只读;按 record_kind 分流入站/出站归档与档行)。
|
||||
|
||||
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」确认弹窗展示预检结果
|
||||
时调用;不要在运行期落地链路调用。
|
||||
【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
@@ -224,7 +226,7 @@ def reparse_pending_match(
|
||||
) -> ReparseOutcome:
|
||||
"""清空并重新解析一个来源指定记录类型的待匹配桶(单事务,本函数提交)。
|
||||
|
||||
【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用。
|
||||
【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。
|
||||
record_kind=outbound 时清出站档、用 purpose=outbound 规则与出站归档重建。
|
||||
|
||||
Raises:
|
||||
|
||||
@@ -10,24 +10,33 @@
|
||||
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
|
||||
manually_closed / success / duplicate_success 永久排除。
|
||||
待匹配桶=成熟未占用的出入站全量(pending_ledger_query:未封存/有异动日期/
|
||||
未被有效 items 占用/T−2,不按调拨类型范围过滤)。可匹配=启用类型范围并集,
|
||||
未被有效 items 占用/T−2,不按调拨类型范围过滤)。清单再按来源+记录类型+
|
||||
外部单号合计数量,不再展开外部项次;没有外部单号的档行仍逐行返回。
|
||||
首页待匹配、可匹配计数与清单行数同一合并口径。【2026-10-22 SQL 下推】
|
||||
计数=合并键 GROUP BY 计数、清单分页=组首行锚点 OFFSET/LIMIT 后只召回
|
||||
本页档行、行桶汇总=轻量元组单条查询;口径不变,禁止再整段装载内存切片。池行带出生匹配的
|
||||
transfer_type,供待恢复/已关闭/结果未知表展示调拨类别。可匹配=启用类型范围并集,
|
||||
供库存匹配卡计数,并给清单行打 matchable。无 item_id 不可执行;
|
||||
匹配圈定后记录离开本桶,取消匹配释放后回归。
|
||||
匹配圈定后记录离开本桶,
|
||||
取消匹配释放后回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy import String, and_, case, cast, func, literal, or_
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLedger
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_records_scope_union,
|
||||
circle_ledger_record_ids_scope_union,
|
||||
pending_ledger_query,
|
||||
transfer_type_code_of,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
|
||||
@@ -62,6 +71,9 @@ RESULT_FILTER_CHOICES = (RESULT_FILTER_ALL, *_RESULT_FILTER_STATUSES.keys())
|
||||
BACKLOG_PAGE_DEFAULT = 1
|
||||
BACKLOG_PAGE_SIZE_DEFAULT = 20
|
||||
BACKLOG_PAGE_SIZE_MAX = 100
|
||||
# 跨页全选 id 上限(2026-10-22):防误拉超大规模池;超出截断并由 API 透出
|
||||
# truncated 标记(千行级池单次全量 id 拉取成本可忽略,上限为防御性兜底)。
|
||||
BACKLOG_SELECT_ALL_MAX = 5000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -86,14 +98,18 @@ class BacklogItemDTO:
|
||||
external_quantity: Optional[str] = None
|
||||
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
|
||||
result_code: Optional[str] = None
|
||||
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
||||
transfer_type: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingMatchRecordDTO:
|
||||
"""「待匹配」桶单项(D16):档记录只读投影——无 item_id,不可勾选执行。
|
||||
"""「待匹配」桶单项(D16):按外部单号收口后的只读投影——无 item_id,不可勾选执行。
|
||||
|
||||
字段与规格 §12.3 只读清单列一致(单号/料号/品名/异动日期/来源/数量);
|
||||
quantity 为档原值文本(Decimal 文本,与 items.movement_quantity 同约定)。
|
||||
有外部单号时,同一来源、同一记录类型下的多项次合成一行。quantity 为这些档行
|
||||
数量之和(Decimal 文本,与 items.movement_quantity 同约定)。没有外部单号的
|
||||
档行仍逐行返回。单号/料号/品名/异动日期在组内不一致时为空,前端显示占位。
|
||||
ledger_record_id 是组内最小档 id,只作行键,不代表整组只有这一条档。
|
||||
"""
|
||||
|
||||
ledger_record_id: int
|
||||
@@ -102,10 +118,12 @@ class PendingMatchRecordDTO:
|
||||
material_name: Optional[str] = None
|
||||
movement_date: Optional[str] = None
|
||||
source_code: str = ""
|
||||
# 档记录类型(inbound/outbound);前端「清空重解析」按行传入,避免出站行误清入站档。
|
||||
# 档记录类型(inbound/outbound)。
|
||||
record_kind: str = "inbound"
|
||||
# 外部单号(WMS Order #)。空串=该行没有外部单号,未与其他行合并。
|
||||
external_doc_no: str = ""
|
||||
quantity: Optional[str] = None
|
||||
# 当前启用类型范围并集罩得住。首页待匹配清单据此分出「当前可匹配」。
|
||||
# 当前启用类型范围并集罩得住。分段查询里同一组的标记一致。
|
||||
matchable: bool = False
|
||||
|
||||
|
||||
@@ -119,9 +137,9 @@ class BacklogSummaryDTO:
|
||||
warn_3d: int = 0
|
||||
escalate_5d: int = 0
|
||||
critical_7d: int = 0
|
||||
# 首页「待匹配」卡:已落档、尚未匹配的成熟出入站记录数(不含类型范围)。
|
||||
# 首页「待匹配」卡:与待匹配清单同一合并口径的行数(不含类型范围)。
|
||||
pending_match_count: int = 0
|
||||
# 首页「匹配可调拨库存」卡:启用类型范围并集现在圈得住的记录数。
|
||||
# 首页「匹配可调拨库存」卡:与清单「当前可匹配」同一合并口径的行数。
|
||||
matchable_count: int = 0
|
||||
|
||||
|
||||
@@ -142,8 +160,8 @@ _PENDING_SEGMENTS = ("all", "matchable", "outside")
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingMatchPageDTO:
|
||||
"""「待匹配」桶分页结果。all/outside 走 SQL 计数与切片;
|
||||
matchable 与 all 使用同一排序,只是 id 集合不同。"""
|
||||
"""「待匹配」桶分页结果。total 与 records 都是外部单号合并后的行,
|
||||
不是档行数。没有外部单号的档行仍各占一行。"""
|
||||
|
||||
records: list[PendingMatchRecordDTO]
|
||||
total: int
|
||||
@@ -262,6 +280,7 @@ def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[Ba
|
||||
movement_quantity=str(item.movement_quantity) if item.movement_quantity is not None else None,
|
||||
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
|
||||
result_code=item.result_code,
|
||||
transfer_type=transfer_type_code_of(item),
|
||||
))
|
||||
return output
|
||||
|
||||
@@ -282,9 +301,12 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
BacklogItemDTO 列表。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
rows = _backlog_base_query(
|
||||
_ALL_BACKLOG_STATUSES, source_code=source_code
|
||||
).order_by(*_BACKLOG_ORDER_BY).all()
|
||||
rows = (
|
||||
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.all()
|
||||
)
|
||||
return _backlog_dtos(rows, current)
|
||||
|
||||
|
||||
@@ -323,7 +345,8 @@ def list_backlog_page(
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.order_by(*_BACKLOG_ORDER_BY)
|
||||
base.options(joinedload(TransferInvoiceItem.matching))
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
@@ -331,12 +354,51 @@ def list_backlog_page(
|
||||
return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
def list_backlog_item_ids(
|
||||
*,
|
||||
source_code: str | None = None,
|
||||
keyword: str | None = None,
|
||||
result_filter: str = RESULT_FILTER_ALL,
|
||||
limit: int = BACKLOG_SELECT_ALL_MAX,
|
||||
) -> tuple[list[int], int]:
|
||||
"""跨页全选支持(2026-10-22):当前筛选下全部待处理明细 id(轻量 id 列表)。
|
||||
|
||||
【AI 触发时机】前端待处理池「选择全部 N 行」时经 API 调用——服务端分页下
|
||||
勾选集合只能覆盖当前页,本函数按同一筛选口径取全量 id 供批量操作
|
||||
(重查/恢复/关闭端点本就按 item_ids 列表逐行隔离,无需新批量契约)。
|
||||
|
||||
Args:
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(与 list_backlog_page 同字段集)。
|
||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||
limit: id 上限(防误拉超大规模池;超出截断,truncated 标记随 API 透出)。
|
||||
Returns:
|
||||
(ids, total):ids=item_id 升序列表(≤limit),total=筛选后全量计数
|
||||
(含未返回部分,供前端提示截断)。
|
||||
"""
|
||||
statuses = _RESULT_FILTER_STATUSES.get(result_filter)
|
||||
if statuses is None:
|
||||
# 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸)
|
||||
statuses = _ALL_BACKLOG_STATUSES
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.order_by(TransferInvoiceItem.id.asc())
|
||||
.limit(limit)
|
||||
.with_entities(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
return [int(row[0]) for row in rows], total
|
||||
|
||||
|
||||
def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecordDTO:
|
||||
"""把档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。
|
||||
"""把单条档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。
|
||||
|
||||
本函数不做外部单号合并。合并在 _aggregate_pending_match_records。
|
||||
|
||||
Args:
|
||||
record: TransferMovementLedger 或带同名字段的行。
|
||||
matchable_ids: circle_ledger_records_scope_union 的 id 集合。
|
||||
matchable_ids: circle_ledger_record_ids_scope_union 的 id 集合。
|
||||
Returns:
|
||||
只读 PendingMatchRecordDTO。无 item_id。
|
||||
"""
|
||||
@@ -348,14 +410,180 @@ def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecord
|
||||
movement_date=record.movement_date,
|
||||
source_code=record.source_code,
|
||||
record_kind=str(getattr(record, "record_kind", None) or "inbound"),
|
||||
external_doc_no=str(getattr(record, "external_doc_no", None) or ""),
|
||||
quantity=record.quantity,
|
||||
matchable=record.id in matchable_ids,
|
||||
)
|
||||
|
||||
|
||||
def _uniform_text(values: list[object]) -> str | None:
|
||||
"""组内去掉空白后只有一个取值时返回它。
|
||||
|
||||
核心逻辑:空串不参与比较;出现第二个不同取值即视为不一致。
|
||||
|
||||
Args:
|
||||
values: 档行上的文本字段。None 与空白视为没有值。
|
||||
Returns:
|
||||
唯一非空文本;没有值或取值不一致时返回 None。
|
||||
"""
|
||||
seen: list[str] = []
|
||||
for raw in values:
|
||||
text = str(raw or "").strip()
|
||||
if not text or text in seen:
|
||||
continue
|
||||
seen.append(text)
|
||||
if len(seen) > 1:
|
||||
return None
|
||||
return seen[0] if seen else None
|
||||
|
||||
|
||||
def _sum_quantity_text(values: list[object]) -> str | None:
|
||||
"""把一组数量文本相加,输出不带多余尾零的十进制文本。
|
||||
|
||||
核心逻辑:能解析的按 Decimal 相加;全组都无法解析时保留第一条非空原文,
|
||||
避免把脏数据收成空白。
|
||||
|
||||
Args:
|
||||
values: 档上的 quantity 文本。
|
||||
Returns:
|
||||
合计文本;全空时返回 None。
|
||||
"""
|
||||
total = Decimal(0)
|
||||
seen = False
|
||||
fallback: str | None = None
|
||||
for raw in values:
|
||||
text = str(raw or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
if fallback is None:
|
||||
fallback = text
|
||||
try:
|
||||
total += Decimal(text)
|
||||
except InvalidOperation:
|
||||
continue
|
||||
seen = True
|
||||
if not seen:
|
||||
return fallback
|
||||
rendered = format(total, "f")
|
||||
if "." in rendered:
|
||||
rendered = rendered.rstrip("0").rstrip(".")
|
||||
return rendered or "0"
|
||||
|
||||
|
||||
def _pending_match_group_key(record: PendingMatchRecordDTO) -> tuple:
|
||||
"""待匹配清单的合并键。
|
||||
|
||||
有外部单号时按来源、记录类型、外部单号合并,项次不进键。
|
||||
没有外部单号时每条档单独成组,避免把互无关的行加成一笔。
|
||||
|
||||
Args:
|
||||
record: 尚未合并的单条档投影。
|
||||
Returns:
|
||||
可哈希分组键。
|
||||
"""
|
||||
external_doc_no = record.external_doc_no.strip()
|
||||
if external_doc_no:
|
||||
return ("external", record.source_code, record.record_kind, external_doc_no)
|
||||
return ("line", record.ledger_record_id)
|
||||
|
||||
|
||||
def _collapse_pending_match_group(rows: list[PendingMatchRecordDTO]) -> PendingMatchRecordDTO:
|
||||
"""把同一合并键下的档行收成清单上的一行。
|
||||
|
||||
核心逻辑:数量相加;单号、料号、品名、异动日期只在组内一致时保留。
|
||||
行键用最小档 id,保证翻页和表格行键稳定。
|
||||
|
||||
Args:
|
||||
rows: 同一组合并键下的档投影,至少一条。
|
||||
Returns:
|
||||
合并后的 PendingMatchRecordDTO。
|
||||
"""
|
||||
head = rows[0]
|
||||
external_doc_no = head.external_doc_no.strip()
|
||||
return PendingMatchRecordDTO(
|
||||
ledger_record_id=min(row.ledger_record_id for row in rows),
|
||||
doc_no=_uniform_text([row.doc_no for row in rows]) or "",
|
||||
material_code=_uniform_text([row.material_code for row in rows]),
|
||||
material_name=_uniform_text([row.material_name for row in rows]),
|
||||
movement_date=_uniform_text([row.movement_date for row in rows]),
|
||||
source_code=head.source_code,
|
||||
record_kind=head.record_kind,
|
||||
external_doc_no=external_doc_no,
|
||||
quantity=_sum_quantity_text([row.quantity for row in rows]),
|
||||
matchable=all(row.matchable for row in rows),
|
||||
)
|
||||
|
||||
|
||||
def _aggregate_pending_match_records(records: list[PendingMatchRecordDTO]) -> list[PendingMatchRecordDTO]:
|
||||
"""按外部单号合并待匹配清单,并保持档查询的先后顺序。
|
||||
|
||||
核心逻辑:沿用 pending_ledger_query 的排序(异动日期 → 来源 → 单号 → id)。
|
||||
一组的位置取该组第一条档的位置,这样同一外部单号不会被分页切开后再加总。
|
||||
|
||||
Args:
|
||||
records: 未合并的档投影,已按圈档稳定排序。
|
||||
Returns:
|
||||
合并后的清单。没有外部单号的行原样留下。
|
||||
"""
|
||||
grouped: dict[tuple, list[PendingMatchRecordDTO]] = {}
|
||||
order: list[tuple] = []
|
||||
for record in records:
|
||||
key = _pending_match_group_key(record)
|
||||
bucket = grouped.get(key)
|
||||
if bucket is None:
|
||||
grouped[key] = [record]
|
||||
order.append(key)
|
||||
else:
|
||||
bucket.append(record)
|
||||
return [_collapse_pending_match_group(grouped[key]) for key in order]
|
||||
|
||||
|
||||
def _load_pending_match_records(*, segment: str, matchable_ids: set[int]) -> list[PendingMatchRecordDTO]:
|
||||
"""读取一段待匹配档并按外部单号合并。
|
||||
|
||||
分页单位是合并后的外部单,所以这里先取整段再合并,不能先按档行 limit。
|
||||
|
||||
Args:
|
||||
segment: all、matchable 或 outside。调用方已校验。
|
||||
matchable_ids: 启用类型范围并集的档 id。
|
||||
Returns:
|
||||
该段合并后的全量清单。
|
||||
"""
|
||||
rows = pending_ledger_query(matchable_ids=matchable_ids, segment=segment).all()
|
||||
return _aggregate_pending_match_records([
|
||||
_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows
|
||||
])
|
||||
|
||||
|
||||
def _count_pending_match_groups(query) -> int:
|
||||
"""按清单合并键计数,不把档行装进内存。
|
||||
|
||||
核心逻辑:有外部单号(去掉首尾空白后非空)时按来源、记录类型、外部单号分组;
|
||||
没有外部单号时一行一组。分组键与 _pending_match_group_key 一致。
|
||||
查询上的排序会拿掉,否则数据库拒绝按非分组列排序。
|
||||
|
||||
Args:
|
||||
query: pending_ledger_query 的某一段。
|
||||
Returns:
|
||||
合并后的行数。
|
||||
"""
|
||||
external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, ""))
|
||||
grouped_kind = case((external != "", literal("external")), else_=literal("line"))
|
||||
grouped_source = case((external != "", TransferMovementLedger.source_code), else_=literal(""))
|
||||
grouped_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal(""))
|
||||
grouped_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String))
|
||||
grouped = (
|
||||
query.order_by(None)
|
||||
.with_entities(grouped_kind, grouped_source, grouped_record_kind, grouped_doc)
|
||||
.group_by(grouped_kind, grouped_source, grouped_record_kind, grouped_doc)
|
||||
.subquery()
|
||||
)
|
||||
return int(db.session.query(func.count()).select_from(grouped).scalar() or 0)
|
||||
|
||||
|
||||
def _matchable_ids() -> set[int]:
|
||||
"""启用类型现在圈得住的档 id。无启用类型时为空集。"""
|
||||
return {record.id for record in circle_ledger_records_scope_union()}
|
||||
"""启用类型现在圈得住的档 id。无启用类型时为空集。只取 id,不装载整行。"""
|
||||
return circle_ledger_record_ids_scope_union()
|
||||
|
||||
|
||||
def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchRecordDTO]:
|
||||
@@ -365,6 +593,8 @@ def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchReco
|
||||
movement_date ≤ T−2 的出入站记录,不按调拨类型范围过滤。
|
||||
segment=matchable 只留启用类型范围并集;segment=outside 是其余已落档。
|
||||
每行 matchable 标记并集成员,供清单把「当前可匹配」和其余行分开。
|
||||
【2026-10-22 清单收口】返回前按来源 + 记录类型 + 外部单号合并,quantity
|
||||
为组内数量之和;没有外部单号的档行不合并。首页计数走同一合并。
|
||||
数字变化口径:文件落地→涨;被匹配圈定→离开(占用);取消匹配→回归;
|
||||
执行成功→封存恒排除。停用类型只减少可匹配行,不把其余行移出本桶。
|
||||
|
||||
@@ -374,7 +604,8 @@ def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchReco
|
||||
Args:
|
||||
segment: all、matchable 或 outside。
|
||||
Returns:
|
||||
PendingMatchRecordDTO 列表(圈档稳定排序:异动日期 → 来源 → 单号 → id)。
|
||||
合并后的 PendingMatchRecordDTO 列表。一组的位置取其最早一条档
|
||||
(异动日期 → 来源 → 单号 → id)。
|
||||
Raises:
|
||||
ValidationError: segment 不是上述三值。
|
||||
"""
|
||||
@@ -382,9 +613,7 @@ def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchReco
|
||||
|
||||
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]
|
||||
return _load_pending_match_records(segment=segment, matchable_ids=_matchable_ids())
|
||||
|
||||
|
||||
def list_pending_match_records_page(
|
||||
@@ -395,15 +624,19 @@ def list_pending_match_records_page(
|
||||
) -> PendingMatchPageDTO:
|
||||
"""「待匹配」桶分页清单(服务端分页;只读语义与全量版一致)。
|
||||
|
||||
all 与 outside 按 SQL count/limit 切片,避免把整桶载入内存后再切页。
|
||||
matchable 使用同一查询,只保留启用类型范围并集的 id。
|
||||
【2026-10-22 分页下推】总数与页圈定都在 SQL 完成:total=合并键 GROUP BY
|
||||
计数(_count_pending_match_groups);本页组经 row_number 组首行锚点
|
||||
OFFSET/LIMIT 圈定(_pending_group_anchor_rows),再只召回本页组的档行做
|
||||
合并投影(_load_page_group_records)——分页单位仍是外部单,但不能先按档行
|
||||
limit(同一外部单号会被切进两页),也不能整段装载后内存切片(千行级池上
|
||||
每页都 O(全池))。
|
||||
|
||||
Args:
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
segment: all、matchable 或 outside。
|
||||
Returns:
|
||||
PendingMatchPageDTO(records=当前页切片,total=该段全量计数)。
|
||||
PendingMatchPageDTO(records=当前页切片,total=该段合并后的行数)。
|
||||
Raises:
|
||||
ValidationError: segment 不是上述三值。
|
||||
"""
|
||||
@@ -412,36 +645,226 @@ def list_pending_match_records_page(
|
||||
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()
|
||||
base = pending_ledger_query(matchable_ids=matchable_ids, segment=segment)
|
||||
total = _count_pending_match_groups(base)
|
||||
start = (page - 1) * page_size
|
||||
anchors = _pending_group_anchor_rows(base, offset=start, limit=page_size) if total > start else []
|
||||
records = _load_page_group_records(base, anchors, matchable_ids=matchable_ids) if anchors else []
|
||||
return PendingMatchPageDTO(
|
||||
records=[_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows],
|
||||
records=records,
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
"""计算待处理池汇总计数、老化分级与待匹配桶计数。"""
|
||||
items = list_backlog(now=now)
|
||||
summary = BacklogSummaryDTO()
|
||||
for item in items:
|
||||
if item.status == TransferStatus.MANUALLY_CLOSED.value:
|
||||
summary.closed_count += 1
|
||||
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
summary.unknown_count += 1
|
||||
def _pending_group_anchor_rows(base, *, offset: int, limit: int) -> list[Any]:
|
||||
"""按合并键取一页「组首行」锚点(row_number 窗口下推,不装载整段档行)。
|
||||
|
||||
核心逻辑:分区键与 _count_pending_match_groups / _pending_match_group_key
|
||||
同一口径(外部单号去空白非空=来源+记录类型+外部单号一组;否则每行一组);
|
||||
分区排序与 pending_ledger_query 的圈档稳定排序一致(异动日期→来源→单号→
|
||||
id),rn=1 即该组在清单上的第一条档——组位置语义与
|
||||
_aggregate_pending_match_records「一组的位置取其第一条档」完全一致,
|
||||
翻页顺序与全量版逐行相同。
|
||||
|
||||
Args:
|
||||
base: pending_ledger_query 的某一段(已含固定条件与分段过滤)。
|
||||
offset: 起始组数((page-1)*page_size)。
|
||||
limit: 本页组数(page_size)。
|
||||
Returns:
|
||||
锚点行列表(属性 id/movement_date/source_code/doc_no/group_kind/
|
||||
group_source/group_record_kind/group_doc),按组首行位置排序。
|
||||
"""
|
||||
external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, ""))
|
||||
group_kind = case((external != "", literal("external")), else_=literal("line"))
|
||||
group_source = case((external != "", TransferMovementLedger.source_code), else_=literal(""))
|
||||
group_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal(""))
|
||||
group_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String))
|
||||
ledger_order = (
|
||||
TransferMovementLedger.movement_date.asc(),
|
||||
TransferMovementLedger.source_code.asc(),
|
||||
TransferMovementLedger.doc_no.asc(),
|
||||
TransferMovementLedger.id.asc(),
|
||||
)
|
||||
ranked = (
|
||||
base.order_by(None)
|
||||
.with_entities(
|
||||
TransferMovementLedger.id.label("id"),
|
||||
TransferMovementLedger.movement_date.label("movement_date"),
|
||||
TransferMovementLedger.source_code.label("source_code"),
|
||||
TransferMovementLedger.doc_no.label("doc_no"),
|
||||
group_kind.label("group_kind"),
|
||||
group_source.label("group_source"),
|
||||
group_record_kind.label("group_record_kind"),
|
||||
group_doc.label("group_doc"),
|
||||
func.row_number().over(
|
||||
partition_by=(group_kind, group_source, group_record_kind, group_doc),
|
||||
order_by=ledger_order,
|
||||
).label("rn"),
|
||||
)
|
||||
.subquery()
|
||||
)
|
||||
return (
|
||||
db.session.query(
|
||||
ranked.c.id,
|
||||
ranked.c.movement_date,
|
||||
ranked.c.source_code,
|
||||
ranked.c.doc_no,
|
||||
ranked.c.group_kind,
|
||||
ranked.c.group_source,
|
||||
ranked.c.group_record_kind,
|
||||
ranked.c.group_doc,
|
||||
)
|
||||
.filter(ranked.c.rn == 1)
|
||||
.order_by(
|
||||
ranked.c.movement_date.asc(),
|
||||
ranked.c.source_code.asc(),
|
||||
ranked.c.doc_no.asc(),
|
||||
ranked.c.id.asc(),
|
||||
)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _load_page_group_records(
|
||||
base,
|
||||
anchors: list[Any],
|
||||
*,
|
||||
matchable_ids: set[int],
|
||||
) -> list[PendingMatchRecordDTO]:
|
||||
"""只召回本页各组涉及的档行,复用 Python 合并投影出页内清单。
|
||||
|
||||
核心逻辑:外部单号组按 (来源, 记录类型, trim(外部单号)) 条件召回兄弟行,
|
||||
行组按锚点 id 召回;装载量只随本页组数与组内项次数增长,不受池规模影响。
|
||||
召回行沿用 _pending_match_dto + _aggregate_pending_match_records 收口,
|
||||
口径与全量版完全一致(含 matchable=组内全部行可匹配);最后按锚点顺序
|
||||
还原页序(召回顺序是档序,不是组序)。
|
||||
|
||||
Args:
|
||||
base: pending_ledger_query 的某一段(与锚点同一查询,口径天然一致)。
|
||||
anchors: _pending_group_anchor_rows 的本页锚点,非空。
|
||||
matchable_ids: 启用类型范围并集的档 id(matchable 标记用)。
|
||||
Returns:
|
||||
本页合并后的清单,顺序与锚点(组首行位置)一致。
|
||||
"""
|
||||
external_keys: list[tuple[str, str, str]] = []
|
||||
line_ids: list[int] = []
|
||||
for anchor in anchors:
|
||||
if anchor.group_kind == "external":
|
||||
external_keys.append((anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc))
|
||||
else:
|
||||
summary.recoverable_count += 1
|
||||
if item.aging_level == AGING_WARN_3D:
|
||||
line_ids.append(anchor.id)
|
||||
conds = []
|
||||
if external_keys:
|
||||
conds.append(or_(*[
|
||||
and_(
|
||||
TransferMovementLedger.source_code == source,
|
||||
TransferMovementLedger.record_kind == record_kind,
|
||||
func.trim(func.coalesce(TransferMovementLedger.external_doc_no, "")) == doc,
|
||||
)
|
||||
for source, record_kind, doc in external_keys
|
||||
]))
|
||||
if line_ids:
|
||||
conds.append(TransferMovementLedger.id.in_(line_ids))
|
||||
rows = (
|
||||
base.filter(or_(*conds))
|
||||
.order_by(
|
||||
TransferMovementLedger.movement_date.asc(),
|
||||
TransferMovementLedger.source_code.asc(),
|
||||
TransferMovementLedger.doc_no.asc(),
|
||||
TransferMovementLedger.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
merged = _aggregate_pending_match_records([
|
||||
_pending_match_dto(row, matchable_ids=matchable_ids) for row in rows
|
||||
])
|
||||
# 页序还原:合并键与锚点分区键同构(record_kind 与 DTO 投影同样取
|
||||
# 「空回退 inbound」),据此把组序从档序纠正回组首行位置序。
|
||||
position = {
|
||||
(("external", anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc)
|
||||
if anchor.group_kind == "external" else ("line", anchor.id)): index
|
||||
for index, anchor in enumerate(anchors)
|
||||
}
|
||||
return sorted(merged, key=lambda record: position[_pending_match_group_key(record)])
|
||||
|
||||
|
||||
def _pending_match_counts() -> tuple[int, int]:
|
||||
"""首页待匹配、可匹配计数,与清单合并后的行数一致。
|
||||
|
||||
核心逻辑:在数据库里按外部单号合并键计数,不把整段档行装进 Python。
|
||||
可匹配 id 为空时直接记 0,不再扫一遍全量。
|
||||
|
||||
Returns:
|
||||
(pending_match_count, matchable_count)。
|
||||
"""
|
||||
matchable_ids = _matchable_ids()
|
||||
pending_count = _count_pending_match_groups(
|
||||
pending_ledger_query(matchable_ids=matchable_ids, segment="all"),
|
||||
)
|
||||
if not matchable_ids:
|
||||
return pending_count, 0
|
||||
matchable_count = _count_pending_match_groups(
|
||||
pending_ledger_query(matchable_ids=matchable_ids, segment="matchable"),
|
||||
)
|
||||
return pending_count, matchable_count
|
||||
|
||||
|
||||
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
"""计算待处理池汇总计数、老化分级与待匹配桶计数。
|
||||
|
||||
【2026-10-22 汇总下推】行桶汇总单条查询取 (status, 老化基准时刻) 轻量元组:
|
||||
老化基准=最近 Attempt 时刻(LEFT JOIN GROUP BY 子查询,与
|
||||
_latest_attempt_times 同口径),无 Attempt 回退 updated_at;三态计数与
|
||||
老化分级在 Python 单趟折叠。不再经 list_backlog 整池装载 ORM 实体(含
|
||||
matching joinedload)——千行级池上 summary 的行桶部分从 O(池) 实体 +
|
||||
Attempt 批查降到 1 条轻量查询。待匹配/可匹配计数走 _pending_match_counts
|
||||
(SQL 按外部单号合并键计数),与清单合并后的行数一致。
|
||||
|
||||
Args:
|
||||
now: 老化判定的当前时刻(默认当前时间;测试注入用)。
|
||||
Returns:
|
||||
BacklogSummaryDTO(三态计数 + warn_3d/escalate_5d/critical_7d +
|
||||
pending_match_count/matchable_count)。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
summary = BacklogSummaryDTO()
|
||||
latest_attempt = (
|
||||
db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at).label("latest"))
|
||||
.group_by(TransferAttempt.item_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = (
|
||||
db.session.query(
|
||||
TransferInvoiceItem.status,
|
||||
func.coalesce(latest_attempt.c.latest, TransferInvoiceItem.updated_at),
|
||||
)
|
||||
.outerjoin(latest_attempt, latest_attempt.c.item_id == TransferInvoiceItem.id)
|
||||
.filter(TransferInvoiceItem.status.in_(_ALL_BACKLOG_STATUSES))
|
||||
.all()
|
||||
)
|
||||
for status, base_time in rows:
|
||||
# [STEP 1] 三态计数:closed/unknown 单独计数且不进老化桶(与
|
||||
# _backlog_dtos 的 AGING_CLOSED/AGING_UNKNOWN 口径一致)。
|
||||
if status == TransferStatus.MANUALLY_CLOSED.value:
|
||||
summary.closed_count += 1
|
||||
continue
|
||||
if status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
summary.unknown_count += 1
|
||||
continue
|
||||
# [STEP 2] 可恢复行的老化分级(天数算法与 _backlog_dtos 一致)。
|
||||
summary.recoverable_count += 1
|
||||
age = max(0, int((current - base_time).total_seconds() // 86400))
|
||||
level = aging_level_for(age)
|
||||
if level == AGING_WARN_3D:
|
||||
summary.warn_3d += 1
|
||||
elif item.aging_level == AGING_ESCALATE_5D:
|
||||
elif level == AGING_ESCALATE_5D:
|
||||
summary.escalate_5d += 1
|
||||
elif item.aging_level == AGING_CRITICAL_7D:
|
||||
elif level == AGING_CRITICAL_7D:
|
||||
summary.critical_7d += 1
|
||||
# [待匹配桶计数] 与行桶相互独立:成熟未占用的出入站全量。
|
||||
# 可匹配计数是其中启用类型现在圈得住的子集,供库存匹配卡单独展示。
|
||||
summary.pending_match_count = pending_ledger_query().count()
|
||||
summary.matchable_count = len(_matchable_ids())
|
||||
# [待匹配桶计数] 与行桶相互独立,并与清单外部单号合并后的行数一致。
|
||||
summary.pending_match_count, summary.matchable_count = _pending_match_counts()
|
||||
return summary
|
||||
@@ -121,6 +121,9 @@ class MatchingItemDTO:
|
||||
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
|
||||
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
|
||||
external_org: str = ""
|
||||
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||
# 无匹配或快照未写类型时为空串。
|
||||
transfer_type: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -2,15 +2,19 @@
|
||||
|
||||
用途:在途调拨执行服务(单据级重构 + D8 异步拆分):API 同步段 prepare_execution
|
||||
只做门禁 + 建 queued Run + D1 五元组分组建单 + 一次入队;worker 段
|
||||
execute_run 二次门禁复核后逐单执行(final_only 判定 → 非 final_only 写前
|
||||
execute_run 逐单执行(final_only 判定 → 非 final_only 写前
|
||||
库存复查(漂移行 fail-closed 移出本单)→ create_transfer(business_ref=doc_no
|
||||
透传,调用日志按单号锚定)→ 六态落位);
|
||||
retrigger_document 是 result_unknown 单的唯一人工出口(D11)。
|
||||
依赖:orchestrator、capability_client(TransferOrder/StockTarget)、quantity
|
||||
(classify_quantity_match)、document_id、contracts、audit、status、
|
||||
source_file_status、matching_service(门禁/scope/路由契约)、
|
||||
jobs.queue(TRANSFER_RUN 入队)、models。
|
||||
逻辑:执行门禁与 worker 复核按档记录 record_kind 对证据文件 sha(无档回落入站)。
|
||||
matching_service(scope/路由契约)、jobs.queue(TRANSFER_RUN 入队)、models。
|
||||
逻辑:执行门禁只做存在性校验(行可执行 + 匹配未取消)。文件版本对账门禁
|
||||
(TRANSFER.FILE_CHANGED,API 侧整批拒绝 + worker 侧整 Run 落败)已于
|
||||
2026-10-22 退役——入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按
|
||||
最新文件 sha 对账会错误卡死未处理行;写前安全由逐单执行的写前库存
|
||||
复查(_recheck_stock_for_document,按实时 ERP 账面严格相等核对)承担,
|
||||
行级「文件已更新」徽标保留为纯提示(matching_service._item_dto)。
|
||||
防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
|
||||
五元组建单,同组存在失败单则复用其单号/时间戳全量重跑(doc.run_id 改指新
|
||||
Run,现任归属语义),存在 result_unknown/executing 单则阻断新行
|
||||
@@ -58,9 +62,6 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXECUTABLE,
|
||||
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
|
||||
@@ -71,7 +72,11 @@ from app.services.in_transit_transfer.orchestrator import (
|
||||
# 单投影统一走公共序列化(Task 17 重构:serializers.serialize_order 为唯一契约源;
|
||||
# serializers 不再顶层引用本模块,无循环导入)。
|
||||
from app.services.in_transit_transfer.serializers import serialize_order
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
# [测试补丁锚点] 文件版本对账门禁已退役(2026-10-22),本模块不再消费此符号;
|
||||
# 保留导入仅为存量测试替身(conftest.patch_source_file_status 等 monkeypatch)
|
||||
# 的目标地址不变。新代码禁止再消费——门禁语义见 _gated_items docstring。
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status # noqa: F401
|
||||
|
||||
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
|
||||
# D7① 附加守卫:同组存在未了结单时新行的阻断原因码。
|
||||
@@ -125,20 +130,23 @@ def _item_result_of(item: TransferInvoiceItem) -> str:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInvoiceItem]:
|
||||
"""执行两道门禁(顺序校验,命中即抛、后续不执行,fail-closed 零写入)。
|
||||
"""执行存在性门禁(命中即抛、后续不执行,fail-closed 零写入)。
|
||||
|
||||
门禁:
|
||||
① 存在且可执行:id 存在且 status == ready_to_execute,否则
|
||||
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID")。
|
||||
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 该行证据流最新可用
|
||||
文件 sha。证据流取档记录 record_kind,无档关联回落入站。来源无可用文件
|
||||
或行无版本戳 → ValidationError(code="TRANSFER.FILE_CHANGED")。
|
||||
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID");所属匹配已
|
||||
取消的行一并拒绝(防御性双保险,规格 §9)。
|
||||
|
||||
[2026-09-25 TTL 退役] 原门禁②「行级新鲜度(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」已删除:匹配 10 分钟后必被拒
|
||||
是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标,见
|
||||
matching_service._item_dto),防错由本函数门禁②的文件版本对账 + worker
|
||||
写前库存复查(_execute_document 的 _recheck_stock_for_document)承担。
|
||||
[2026-09-25 TTL 退役] 原门禁「行级新鲜度(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」删除:匹配 10 分钟后必被拒
|
||||
是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标)。
|
||||
[2026-10-22 文件版本对账门禁退役] 原「行评估 sha ≠ 证据流最新可用文件 sha
|
||||
→ TRANSFER.FILE_CHANGED 整批拒绝」删除:入站抓取是**部分导出**——新文件
|
||||
不含某行 ≠ 该行失效/已处理,按「最新文件 sha」对账会把大量未处理行错误
|
||||
卡死(业务实测 557 行积压被卡)。证据变化的保护下沉两层:①行级「文件
|
||||
已更新」徽标(file_current=false,仅提示不拦截,见 matching_service
|
||||
_item_dto);②worker 写前库存复查(_recheck_stock_for_document)——按
|
||||
实时 ERP 账面严格相等核对,数量/批号漂移的行在写前被行级阻断,不会错写。
|
||||
|
||||
Returns:
|
||||
去重并保持首现顺序的可执行行列表。
|
||||
@@ -180,22 +188,7 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
|
||||
"items not executable", code="TRANSFER.EXECUTE_ITEMS_INVALID",
|
||||
details={"invalid_item_ids": invalid},
|
||||
)
|
||||
items = [by_id[i] for i in ordered_ids]
|
||||
|
||||
# [门禁②] 文件版本对账:按 (来源, 档 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, _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 evidence file changed since evaluation", code="TRANSFER.FILE_CHANGED",
|
||||
details={"changed_item_ids": changed},
|
||||
)
|
||||
return items
|
||||
return [by_id[i] for i in ordered_ids]
|
||||
|
||||
|
||||
def prepare_execution(
|
||||
@@ -502,13 +495,12 @@ def execute_run(
|
||||
run.status = status_machine.TransferRunStatus.EXECUTING.value
|
||||
run.started_at = run.started_at or datetime.utcnow()
|
||||
db.session.flush()
|
||||
if doc_id is None:
|
||||
# [二次门禁] 文件 Hash 复核(fail-closed):失败则整 Run 落败,零外部写入。
|
||||
failure = _recheck_gates(run, deps)
|
||||
if failure is not None:
|
||||
_mark_recheck_failed(run, docs, failure)
|
||||
db.session.commit()
|
||||
return run.status
|
||||
# [2026-10-22 文件版本对账门禁退役] 原 worker 二次门禁 _recheck_gates(文件
|
||||
# Hash 复核失败 → 整 Run technical_failed 零写入)随 API 侧门禁②一并退役:
|
||||
# 入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按最新文件 sha 对账会错误
|
||||
# 卡死未处理行。写前安全由逐单执行的写前库存复查(_execute_document 的
|
||||
# _recheck_stock_for_document)独立承担——按实时 ERP 账面严格相等核对,
|
||||
# 数量/批号漂移的行在写前被行级阻断,不会错写。
|
||||
# [逐单执行] 单间失败隔离:单单异常落 technical_failed,不影响其他单。
|
||||
for doc in docs:
|
||||
try:
|
||||
@@ -530,59 +522,6 @@ def execute_run(
|
||||
return run.status
|
||||
|
||||
|
||||
def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | None: # noqa: ARG001 —— 本函数只做文件 Hash 门禁;库存写前复查在 _execute_document(_recheck_stock_for_document)
|
||||
"""worker 二次门禁复核(文件 Hash),返回 None 表示通过。
|
||||
|
||||
[2026-09-25 TTL 退役] 原新鲜度复核(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → items_stale 整 Run 落败)已删除:worker 排队/等待
|
||||
超 10 分钟即被拒是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值
|
||||
(stale 徽标),写前安全由文件版本对账(本函数)+ 逐单执行的写前库存
|
||||
复查(_recheck_stock_for_document)承担。
|
||||
|
||||
Args:
|
||||
run: 执行 Run(其关联行即本次执行范围)。
|
||||
deps: 注入依赖(文件门禁不消费外部能力,仅为签名对称保留)。
|
||||
Returns:
|
||||
None=通过;否则 (原因码, 原因消息)。
|
||||
"""
|
||||
items = [
|
||||
item for item in run.items
|
||||
if item.status in (
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
)
|
||||
]
|
||||
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, _item_evidence_kind(item))) or {}
|
||||
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
|
||||
return ("file_changed", "source evidence file changed since evaluation")
|
||||
return None
|
||||
|
||||
|
||||
def _mark_recheck_failed(run: TransferRun, docs: list[TransferDocument], failure: tuple[str, str]) -> None:
|
||||
"""二次门禁失败落位(fail-closed):单 technical_failed、行阻断、Run failed。"""
|
||||
code, message = failure
|
||||
for doc in docs:
|
||||
# [P2-1] pending(未起跑)与 executing(上次 worker 中途搁浅)统一落
|
||||
# technical_failed:零外部写入;stage 已成的单后续全量重跑由 stage SQL
|
||||
# DELETE 同时间戳幂等兜底;落失败态使其可被 D18 关闭释放组锁,不留悬挂。
|
||||
if doc.status in ("pending", "executing"):
|
||||
doc.status = "technical_failed"
|
||||
doc.error_code = code
|
||||
doc.error_message = message
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
for item in run.items:
|
||||
if item.status not in _PROTECTED_ITEM_STATUSES and item.status != blocked_status:
|
||||
item.status = blocked_status
|
||||
item.result_code = code
|
||||
item.result_message = message
|
||||
run.status = status_machine.TransferRunStatus.FAILED.value
|
||||
run.completed_at = run.completed_at or datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 逐单执行(计划 [STEP 1-4] 伪码逐字落实)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -37,6 +37,7 @@ from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import and_, false, func, or_
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
@@ -394,12 +395,41 @@ def _order_circled_ledger(query):
|
||||
)
|
||||
|
||||
|
||||
def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
|
||||
"""启用类型范围并集圈档(首页待办看板「待匹配」桶数据源,D16/规格 §10)。
|
||||
def _scope_union_queries():
|
||||
"""范围并集的逐启用类型圈档查询生成器(行版/ID 版并集共享的唯一底座)。
|
||||
|
||||
【AI 触发时机】首页待办看板需要「已抓取尚未匹配的出入站记录」清单/计数时
|
||||
调用(backlog_service.list_pending_match_records);匹配创建圈档不要用本函数
|
||||
(匹配按所选类型单范围圈定,不经并集)。
|
||||
核心逻辑:对每个启用调拨类型按现行范围规则各建一条查询——复用
|
||||
_circle_ledger_base_query 固定条件(record_kinds_of(该类型范围规则)/
|
||||
未封存/有异动日期/未被有效 items 占用/T−2 成熟封顶)+ apply_scope_filters
|
||||
单一编译器,与匹配创建圈档同口径,杜绝谓词漂移。无启用类型 → 空序列
|
||||
(fail-closed:无类型即无范围,与匹配创建 NOT_CONFIGURED 语义一致)。
|
||||
get_enabled 延迟导入:配置服务与本模块互相引用,顶层引入成环。
|
||||
"""
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
matured_date_to = eligible_movement_date_to(business_date_now())
|
||||
for config in get_enabled():
|
||||
yield 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,
|
||||
)
|
||||
|
||||
|
||||
def circle_ledger_record_ids_scope_union() -> set[int]:
|
||||
"""启用类型范围并集圈档(只取 id;首页汇总/待匹配清单 matchable 标记用)。
|
||||
|
||||
【AI 触发时机】只需要「启用类型并集现在圈得住哪些档」的 id 集合做成员
|
||||
判断/分段计数(backlog_service._matchable_ids → 待匹配清单 matchable
|
||||
标记、segment 计数与分页召回)时调用;需要整行清单不要用并集——首页
|
||||
待匹配桶清单/计数走 pending_ledger_query(不按类型范围过滤,matchable
|
||||
只作标记),匹配创建圈档按所选类型单范围走 _circle_ledger_records。
|
||||
【2026-10-22 行版退役】整行版随首页 SQL 下推退役(唯一消费方改取 id 集,
|
||||
整行装载曾是 /summary 33s 的根因之一);需要整行时经 _scope_union_queries
|
||||
自行投影,禁止复活全量 .all()。
|
||||
|
||||
范围并集=对每个启用类型分别按其现行规则圈取后按 id 去重并集(等价实现):
|
||||
每类型查询复用 _circle_ledger_base_query 固定条件(record_kinds_of(该类型
|
||||
@@ -413,29 +443,12 @@ def circle_ledger_records_scope_union() -> list[TransferMovementLedger]:
|
||||
NOT_CONFIGURED 语义一致)。已封存记录恒不在结果中(固定条件)。
|
||||
|
||||
Returns:
|
||||
档记录列表(异动日期 → 来源 → 单号 → id 稳定排序)。
|
||||
档 id 集合;无启用类型时空集(fail-closed,与匹配创建语义一致)。
|
||||
"""
|
||||
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(
|
||||
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:
|
||||
return []
|
||||
# 去重后按圈档稳定排序统一投影(单条 IN 查询;行已在 session 身份映射内)。
|
||||
return _order_circled_ledger(
|
||||
TransferMovementLedger.query.filter(TransferMovementLedger.id.in_(list(by_id))),
|
||||
).all()
|
||||
ids: set[int] = set()
|
||||
for query in _scope_union_queries():
|
||||
ids.update(row[0] for row in query.with_entities(TransferMovementLedger.id))
|
||||
return ids
|
||||
|
||||
|
||||
def pending_ledger_query(*, matchable_ids: set[int] | None = None, segment: str = "all"):
|
||||
@@ -575,8 +588,8 @@ def _born_item_from_record(
|
||||
status=status_machine.TransferStatus.MATCHING.value,
|
||||
result_code=SYNC_RESULT_PENDING,
|
||||
result_message=None,
|
||||
# 行级溯源单行(档记录的 sheet/row + 文件版本戳):file_sha256 供执行
|
||||
# 门禁②文件对账(_item_evaluated_sha)读取。
|
||||
# 行级溯源单行(档记录的 sheet/row + 文件版本戳):file_sha256 供
|
||||
# 行当前性徽标(file_current)读取(执行门禁已退役 2026-10-22)。
|
||||
raw_lines_json=[{
|
||||
"sheet": record.sheet_name or "",
|
||||
"row_no": int(record.row_no or 0),
|
||||
@@ -1198,18 +1211,18 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
记录 file_sha256 == 该来源最新可用文件 sha」:档记录是证据权威,记录被
|
||||
新版文件原行更新(file_sha256 换新)后行经档即见新版本——档记录无变化
|
||||
(仍持最新文件 sha)即当前,不再因行出生戳陈旧误判过期(入站 RPA 非全
|
||||
量导出,证据未变的行重落后出生戳恒滞后,旧口径会把可执行行永久卡死在
|
||||
FILE_CHANGED)。行无档关联(隔离的历史行)回读 raw_lines_json 首条
|
||||
量导出,证据未变的行重落后出生戳恒滞后)。行无档关联(隔离的历史行)回读
|
||||
raw_lines_json 首条
|
||||
file_sha256(存量兼容);档记录存在但无 sha → None(版本未知,消费方
|
||||
按各自口径 fail-closed)。
|
||||
按各自口径处理)。
|
||||
|
||||
用途:文件对账(restore 展示 / execute_items 执行门禁②)据此判断
|
||||
用途:行当前性徽标(file_current,restore/明细展示)据此判断
|
||||
"行所锚定的档记录是否仍在最新文件版本上"。2026-09-28 起不再用于
|
||||
消失行标记(blocked_file_removed 仅重查对账的隔离出口与历史防御)。
|
||||
两个消费方对 None(未知版本)口径不同:
|
||||
- restore 展示:None → file_current=False(仅展示不可执行原因,不阻断);
|
||||
- execute_items 门禁②:None 按"评估版本缺失"fail-closed 拒绝执行
|
||||
(TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。
|
||||
【2026-10-22 执行门禁②退役】原 execute_items 门禁②消费方删除——
|
||||
部分导出下按最新文件 sha 对账会错误卡死未处理行(缺席≠失效),
|
||||
本函数现仅剩展示消费方:None → file_current=False(仅提示不拦截),
|
||||
行级「文件已更新」徽标引导重查/重新匹配。
|
||||
行新鲜度 TTL(updated_at / inventory_checked_at)机制不受本改锚影响。
|
||||
|
||||
Args:
|
||||
@@ -1471,6 +1484,24 @@ def restore_matching(
|
||||
}
|
||||
|
||||
|
||||
def transfer_type_code_of(item: TransferInvoiceItem) -> str:
|
||||
"""读取明细行所属调拨类型编码。
|
||||
|
||||
核心逻辑:类型写在出生匹配的 scope_json.transfer_type,不在行上。
|
||||
无匹配、快照不是对象或未写类型时返回空串,列表显示占位。
|
||||
|
||||
Args:
|
||||
item: 明细行。matching 关系可已预加载;未预加载时按外键懒加载。
|
||||
Returns:
|
||||
调拨类型 code;没有则空串。
|
||||
"""
|
||||
matching = item.matching
|
||||
scope = matching.scope_json if matching is not None else None
|
||||
if not isinstance(scope, dict):
|
||||
return ""
|
||||
return str(scope.get("transfer_type") or "").strip()
|
||||
|
||||
|
||||
def _item_dto(
|
||||
item: TransferInvoiceItem,
|
||||
latest: dict,
|
||||
@@ -1489,7 +1520,8 @@ def _item_dto(
|
||||
external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数
|
||||
口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。
|
||||
Returns:
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org /
|
||||
transfer_type)。
|
||||
"""
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
inventory_checked_at = item.inventory_checked_at
|
||||
@@ -1538,6 +1570,7 @@ def _item_dto(
|
||||
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
|
||||
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
||||
external_org=external_org,
|
||||
transfer_type=transfer_type_code_of(item),
|
||||
)
|
||||
|
||||
|
||||
@@ -1548,7 +1581,7 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
(execute_items 按行 ID 工作不变,规格 §10)——本查询给出全部
|
||||
ready_to_execute 行(业务稳定排序),供前端勾选后按行执行生成调拨单;
|
||||
行装饰(item_id / checked_at / stale / file_current)与 restore 实时
|
||||
视图同一口径。
|
||||
视图同一口径。transfer_type 取自出生匹配快照,供跨类型队列展示类别。
|
||||
|
||||
Args:
|
||||
deps: 注入依赖(缺省内部取 get_transfer_dependencies;只读 TTL 配置)。
|
||||
@@ -1567,6 +1600,7 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
||||
rows = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
|
||||
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
|
||||
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
|
||||
|
||||
@@ -92,6 +92,8 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"checked_at": item.checked_at,
|
||||
"stale": item.stale,
|
||||
"file_current": item.file_current,
|
||||
# 出生匹配的调拨类型 code。可调拨明细跨类型混排时前端据此显示类别名称。
|
||||
"transfer_type": item.transfer_type,
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user