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
@@ -10,7 +10,7 @@
|
||||
unconfigured 后再各写最多一个 batch;
|
||||
证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用
|
||||
入站/出站文件;当天清单(GET /sources/<code>/evidence-files)复用可用
|
||||
条件返回当天全部文件并签发预签地址;
|
||||
条件返回当天全部文件,并分别签发预览地址与带保存名的下载地址;
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
@@ -19,9 +19,11 @@
|
||||
D18 废单不废行); 调拨类型选择数据源(GET /transfer-types,仅启用、
|
||||
最小暴露,另附 record_kinds_of(scope_rules) 推导的 record_kinds,不回传
|
||||
scope_rules / warehouse_config / description);来源列表(GET /sources)
|
||||
一次批量投影全部启用来源的入站/出站文件状态;待匹配桶维护(spec §6):
|
||||
「清空并重新解析」预检(GET /backlog/pending-match/reparse-preview,只读)
|
||||
与执行(POST /backlog/pending-match/reparse,单事务由 service 提交并落审计)。
|
||||
一次批量投影全部启用来源的入站/出站文件状态。待匹配清单只读
|
||||
(GET /backlog/pending-match,含外部单号与外部项次)。
|
||||
2026-10-22 起不再挂「清空并重新解析」
|
||||
(原 GET/POST /backlog/pending-match/reparse*):该入口会重放保留期内
|
||||
全部归档。重解析只保留 POST /sources/<code>/reparse(当天最新一份)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -163,7 +165,10 @@ def create_matching_api():
|
||||
@in_transit_transfer_bp.route("/items/executable", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def executable_items_api():
|
||||
"""可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。"""
|
||||
"""可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。
|
||||
|
||||
行上 transfer_type 是出生匹配快照的类型 code,供跨类型队列显示类别。
|
||||
"""
|
||||
return _ok(list_executable_items())
|
||||
|
||||
|
||||
@@ -235,6 +240,38 @@ def _usable_archive_files(source_code: str, record_kind: str) -> list:
|
||||
)
|
||||
|
||||
|
||||
def evidence_download_filename(
|
||||
source_code: str,
|
||||
created_at: datetime | None,
|
||||
original_filename: str | None,
|
||||
) -> str:
|
||||
"""证据单文件的保存名:库存源编码加东八区抓取日期和时分。
|
||||
|
||||
核心逻辑:created_at 无时区时按 UTC 理解,转到 UTC+8 后取年月日和时分,
|
||||
与详情行展示的时刻一致。扩展名沿用归档原名,缺省 .xlsx。对象键哈希不进入文件名。
|
||||
|
||||
Args:
|
||||
source_code: 库存源实例编码。
|
||||
created_at: 归档创建时间;naive 视为 UTC。
|
||||
original_filename: 归档原名,只取其扩展名。
|
||||
|
||||
Returns:
|
||||
如 CRANE_20261022_1057.xlsx。来源编码会收成文件名安全字符。
|
||||
"""
|
||||
import re
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
suffix = Path(original_filename or "").suffix
|
||||
ext = suffix if suffix and re.fullmatch(r"\.[A-Za-z0-9]{1,8}", suffix) else ".xlsx"
|
||||
label = re.sub(r"[^\w.-]+", "_", source_code or "").strip("._") or "unknown"
|
||||
if created_at is None:
|
||||
return f"{label}{ext}"
|
||||
aware = created_at if created_at.tzinfo is not None else created_at.replace(tzinfo=timezone.utc)
|
||||
stamp = aware.astimezone(timezone(timedelta(hours=8))).strftime("%Y%m%d_%H%M")
|
||||
return f"{label}_{stamp}{ext}"
|
||||
|
||||
|
||||
def _record_evidence_download_audit(*, aggregate_id: str) -> None:
|
||||
"""写入证据文件访问审计,事件类型保持 TRANSFER_INBOUND_FILES_DOWNLOADED。
|
||||
|
||||
@@ -332,9 +369,10 @@ def list_source_evidence_files_api(source_code: str):
|
||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||
可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。
|
||||
每项含 file_id、original_filename、created_at、sha256、file_size、
|
||||
presigned_url。不解析 Excel,不含行数。预签调用
|
||||
presigned_get_url(storage_key, expires_seconds=300)。签发时写
|
||||
TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
||||
presigned_url、download_url。不解析 Excel,不含行数。预览与下载各签一次
|
||||
presigned_get_url(storage_key, expires_seconds=300);下载地址额外带
|
||||
download_name(库存源_东八区年月日_时分.扩展名),避免浏览器用对象键哈希当保存名。
|
||||
签发时写 TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
||||
"""
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
@@ -345,6 +383,7 @@ def list_source_evidence_files_api(source_code: str):
|
||||
payload = []
|
||||
for report in _usable_archive_files(code, kind):
|
||||
created = report.created_at.isoformat() if report.created_at is not None else None
|
||||
download_name = evidence_download_filename(code, report.created_at, report.original_filename)
|
||||
payload.append({
|
||||
"file_id": report.id,
|
||||
"original_filename": report.original_filename,
|
||||
@@ -354,6 +393,9 @@ def list_source_evidence_files_api(source_code: str):
|
||||
"presigned_url": file_asset_storage.presigned_get_url(
|
||||
report.storage_key, expires_seconds=300,
|
||||
),
|
||||
"download_url": file_asset_storage.presigned_get_url(
|
||||
report.storage_key, expires_seconds=300, download_name=download_name,
|
||||
),
|
||||
})
|
||||
_record_evidence_download_audit(aggregate_id=code)
|
||||
return _ok(payload)
|
||||
@@ -1208,6 +1250,8 @@ def retry_sources_rpa_batch_api():
|
||||
def backlog_api():
|
||||
"""待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。
|
||||
|
||||
行上 transfer_type 是出生匹配快照的类型 code。
|
||||
|
||||
Query(全部可选;不带 page/page_size 时保持历史行为返回全量数组——向后兼容):
|
||||
page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为
|
||||
分页 envelope {items, total, page, page_size}(2026-10-16 服务端分页:
|
||||
@@ -1272,6 +1316,36 @@ def backlog_api():
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/item-ids", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_item_ids_api():
|
||||
"""跨页全选支持(2026-10-22):当前筛选下全部待处理明细 id(轻量列表)。
|
||||
|
||||
Query:keyword / result_filter(与 /backlog 分页模式同口径、同白名单 400)。
|
||||
Returns:{ ids: [item_id...](升序,上限 BACKLOG_SELECT_ALL_MAX),
|
||||
total: 筛选后全量计数, truncated: total > len(ids) }。
|
||||
用途:待处理池「选择全部 N 行」——服务端分页下勾选集合默认只覆盖当前页,
|
||||
本端点按同一筛选口径取全量 id;批量端点(重查/恢复/关闭)本就按 item_ids
|
||||
列表逐行隔离,直接复用无需新批量契约。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_service import (
|
||||
BACKLOG_SELECT_ALL_MAX,
|
||||
RESULT_FILTER_CHOICES,
|
||||
list_backlog_item_ids,
|
||||
)
|
||||
|
||||
keyword = (request.args.get("keyword") or "").strip()
|
||||
result_filter = (request.args.get("result_filter") or "").strip() or "all"
|
||||
if result_filter not in RESULT_FILTER_CHOICES:
|
||||
raise ValidationError(
|
||||
f"result_filter must be one of {sorted(RESULT_FILTER_CHOICES)}",
|
||||
)
|
||||
ids, total = list_backlog_item_ids(
|
||||
keyword=keyword or None, result_filter=result_filter, limit=BACKLOG_SELECT_ALL_MAX,
|
||||
)
|
||||
return _ok({"ids": ids, "total": total, "truncated": total > len(ids)})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_summary_api():
|
||||
@@ -1283,9 +1357,9 @@ def backlog_summary_api():
|
||||
'recoverable': summary.recoverable_count,
|
||||
'closed': summary.closed_count,
|
||||
'unknown': summary.unknown_count,
|
||||
# 首页待办看板第 4 张数字卡(D16):已落档尚未匹配的外部入站记录数。
|
||||
# 首页待办看板第 4 张数字卡:与待匹配清单同一外部单号合并口径。
|
||||
'pending_match': summary.pending_match_count,
|
||||
# 库存匹配卡:启用类型现在圈得住的行数。待匹配卡用上面的全量。
|
||||
# 库存匹配卡:与清单「当前可匹配」同一合并口径。
|
||||
'matchable_count': summary.matchable_count,
|
||||
'aging': {
|
||||
'warn_3d': summary.warn_3d,
|
||||
@@ -1305,7 +1379,9 @@ def backlog_pending_match_api():
|
||||
page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为
|
||||
分页 envelope {records, total, page, page_size}。
|
||||
segment:all(默认,全量)/ matchable(启用类型现在圈得住)/
|
||||
outside(其余已落档)。每行带 matchable。
|
||||
outside(其余已落档)。每行带 matchable、external_doc_no。
|
||||
quantity 是同一来源、同一记录类型、同一外部单号下的数量合计;
|
||||
没有外部单号的档行仍逐行返回。不再返回 external_line_no。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_service import (
|
||||
BACKLOG_PAGE_DEFAULT,
|
||||
@@ -1339,10 +1415,11 @@ def backlog_pending_match_api():
|
||||
|
||||
|
||||
def _serialize_pending_match_record(record) -> dict[str, Any]:
|
||||
"""「待匹配」桶项序列化(档记录只读投影;含 record_kind;无 item_id)。"""
|
||||
"""「待匹配」桶项序列化(外部单号合计后的只读投影;无项次、无 item_id)。"""
|
||||
return {
|
||||
'ledger_record_id': record.ledger_record_id,
|
||||
'doc_no': record.doc_no,
|
||||
'external_doc_no': record.external_doc_no,
|
||||
'material_code': record.material_code,
|
||||
'material_name': record.material_name,
|
||||
'movement_date': record.movement_date,
|
||||
@@ -1353,65 +1430,6 @@ def _serialize_pending_match_record(record) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/pending-match/reparse-preview", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def pending_match_reparse_preview_api():
|
||||
"""待匹配桶「清空并重新解析」预检(只读;spec §6 确认弹窗数据源)。
|
||||
|
||||
【AI 触发时机】仅待匹配面板「清空并重新解析」确认弹窗加载预检结果时调用;
|
||||
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日 fail-closed 语义)。
|
||||
Query:source_code(必填)、record_kind(缺省 inbound;outbound=出站流)。
|
||||
响应 data:{record_kind, files, profile, clearable_rows, kept_rows}。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_reparse_service import preview_pending_match_reparse
|
||||
|
||||
source_code = str(request.args.get("source_code") or "").strip()
|
||||
if not source_code:
|
||||
raise ValidationError("source_code is required")
|
||||
record_kind = str(request.args.get("record_kind") or "inbound").strip() or "inbound"
|
||||
return _ok(preview_pending_match_reparse(
|
||||
source_code=source_code, now=datetime.utcnow(), record_kind=record_kind,
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/pending-match/reparse", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def pending_match_reparse_api():
|
||||
"""待匹配桶「清空并重新解析」执行(spec §6;单事务由 service 提交)。
|
||||
|
||||
【AI 触发时机】仅待匹配面板「清空并重新解析」确认提交时调用;
|
||||
禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日 fail-closed 语义)。
|
||||
请求体 {"source_code", "record_kind"?};record_kind 缺省 inbound。
|
||||
任一归档解析失败整体中止(TRANSFER.REPARSE_PARSE_FAILED,一行不删)。
|
||||
响应 data:含 record_kind 与 cleared/reinserted 等计数。
|
||||
"""
|
||||
from app.services.in_transit_transfer.backlog_reparse_service import reparse_pending_match
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_code = str(payload.get("source_code") or "").strip()
|
||||
if not source_code:
|
||||
raise ValidationError("source_code is required")
|
||||
record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound"
|
||||
user = _require_user()
|
||||
outcome = reparse_pending_match(
|
||||
source_code=source_code,
|
||||
operator=str(getattr(user, "username", "") or user.id),
|
||||
now=datetime.utcnow(),
|
||||
record_kind=record_kind,
|
||||
)
|
||||
return _ok({
|
||||
"source_code": outcome.source_code,
|
||||
"record_kind": outcome.record_kind,
|
||||
"cleared": outcome.cleared,
|
||||
"reinserted": outcome.reinserted,
|
||||
"date_skipped": outcome.date_skipped,
|
||||
"kept_unrebuildable": outcome.kept_unrebuildable,
|
||||
"unlinked_items": outcome.unlinked_items,
|
||||
"collapses": outcome.collapses,
|
||||
"files": list(outcome.files),
|
||||
})
|
||||
|
||||
|
||||
def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
|
||||
return {
|
||||
@@ -1432,4 +1450,5 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
'movement_quantity': item.movement_quantity,
|
||||
'external_quantity': item.external_quantity,
|
||||
'result_code': item.result_code,
|
||||
'transfer_type': item.transfer_type,
|
||||
}
|
||||
@@ -3,7 +3,8 @@ backend/app/services/file_assets/storage.py
|
||||
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
|
||||
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
||||
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -119,13 +120,39 @@ class FileAssetStorage:
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
|
||||
"""生成短期受控下载 URL。"""
|
||||
def presigned_get_url(
|
||||
self,
|
||||
storage_key: str,
|
||||
*,
|
||||
expires_seconds: int,
|
||||
download_name: str | None = None,
|
||||
) -> str:
|
||||
"""生成短期受控下载 URL。
|
||||
|
||||
核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
download_name 非空时把 response-content-disposition 签进 URL,
|
||||
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
||||
|
||||
Args:
|
||||
storage_key: MinIO 对象键。
|
||||
expires_seconds: 链接有效秒数,短于 60 秒时抬到 60。
|
||||
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
||||
|
||||
Returns:
|
||||
带过期签名的 GET URL。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
response_headers = None
|
||||
if download_name:
|
||||
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
||||
response_headers = {
|
||||
'response-content-disposition': f'attachment; filename="{safe}"',
|
||||
}
|
||||
return self.client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
response_headers=response_headers,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""[DEBUG-perf1] 首页 /summary 计时基线(临时,诊断后删除)。"""
|
||||
from time import perf_counter
|
||||
|
||||
from app import create_app
|
||||
from app.services.in_transit_transfer.backlog_service import (
|
||||
_pending_match_counts,
|
||||
backlog_summary,
|
||||
list_backlog,
|
||||
)
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
t0 = perf_counter()
|
||||
items = list_backlog()
|
||||
t1 = perf_counter()
|
||||
pm, m = _pending_match_counts()
|
||||
t2 = perf_counter()
|
||||
s = backlog_summary()
|
||||
t3 = perf_counter()
|
||||
print(f"[DEBUG-perf1] list_backlog rows={len(items)}: {t1 - t0:.2f}s")
|
||||
print(f"[DEBUG-perf1] _pending_match_counts pending={pm} matchable={m}: {t2 - t1:.2f}s")
|
||||
print(f"[DEBUG-perf1] backlog_summary total: {t3 - t2:.2f}s (pending={s.pending_match_count}, matchable={s.matchable_count})")
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与
|
||||
GET /matchings/{id} 进度恢复;无权限 403、未认证 401;
|
||||
待匹配桶「清空并重新解析」预检/执行端点(spec §6,Task 7);
|
||||
待匹配清单按外部单号合计数量,不再投影外部项次;
|
||||
证据压缩包路径与当天清单(Task 5)。
|
||||
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes、factories。
|
||||
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
|
||||
@@ -250,6 +250,8 @@ def test_executable_items_lists_ready_rows_with_decoration(
|
||||
assert item["stale"] is False
|
||||
assert item["file_current"] is True
|
||||
assert item["checked_at"]
|
||||
# [断言意图] 可调拨明细跨类型混排,行上要带回出生匹配的类型 code。
|
||||
assert item["transfer_type"] == "in_transit_to_hub"
|
||||
|
||||
|
||||
def test_executable_items_requires_authentication(client):
|
||||
@@ -506,6 +508,9 @@ def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, trans
|
||||
assert "HOM-001" in invoice_set
|
||||
assert "HOX-002" not in invoice_set # 可执行项不在待处理池
|
||||
assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"}
|
||||
blocked = next(entry for entry in listed.get_json()["data"] if entry["invoice_no"] == "HOM-001")
|
||||
# [断言意图] 待恢复行要带回出生匹配的类型 code,表格才能显示类别而不是只看仓库。
|
||||
assert blocked["transfer_type"] == "in_transit_to_hub"
|
||||
|
||||
summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers)
|
||||
assert summary.status_code == 200
|
||||
@@ -595,50 +600,61 @@ def test_backlog_result_filter_and_keyword_pushdown(app, transfer_db, client, ad
|
||||
assert invalid.status_code == 400
|
||||
|
||||
|
||||
def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client, admin_headers, monkeypatch):
|
||||
"""GET /backlog/pending-match 分页 envelope 与无参兼容:带参回
|
||||
{records,total,page,page_size},无参保持历史数组(圈档伪造 25 行验证切片)。"""
|
||||
from types import SimpleNamespace
|
||||
def test_backlog_item_ids_for_cross_page_select_all(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""GET /backlog/item-ids 跨页全选支持:按筛选口径回全量 item_id(升序)
|
||||
+ total + truncated 标记;result_filter 白名单外 400(与 /backlog 同口径)。"""
|
||||
_create_matching(client, admin_headers)
|
||||
with app.app_context():
|
||||
from app import db as _db
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
rows = [
|
||||
SimpleNamespace(
|
||||
ledger_record_id=None, id=i + 1, doc_no=f"HOM-{900 + i}",
|
||||
material_code=f"MAT-{i}", material_name="未匹配物料",
|
||||
movement_date="2026-08-05", source_code="DBS-AWSBI", quantity="1",
|
||||
first = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
first.status = "blocked_recoverable"
|
||||
first.result_code = "blocked_quantity_mismatch"
|
||||
second = TransferInvoiceItem.query.filter_by(invoice_no="HOX-002").first()
|
||||
second.status = "manually_closed"
|
||||
second.result_message = "线下处理"
|
||||
_db.session.commit()
|
||||
expected = sorted(
|
||||
item.id for item in TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.status.in_(["blocked_recoverable", "manually_closed"])
|
||||
).all()
|
||||
)
|
||||
for i in range(25)
|
||||
]
|
||||
class _Rows:
|
||||
"""分页测试用的查询替身:count/offset/limit/all 与 Query 同形。"""
|
||||
|
||||
def __init__(self, items):
|
||||
self._items = items
|
||||
self._offset = 0
|
||||
self._limit = None
|
||||
data = client.get(f"{API_PREFIX}/backlog/item-ids", headers=admin_headers).get_json()["data"]
|
||||
assert set(data.keys()) == {"ids", "total", "truncated"}
|
||||
assert data["ids"] == expected # [断言意图] 全量 id 升序(两态并集)
|
||||
assert data["total"] == len(expected) and data["truncated"] is False
|
||||
|
||||
def count(self):
|
||||
return len(self._items)
|
||||
# 切片口径:recoverable 只回可恢复行的 id。
|
||||
recoverable = client.get(
|
||||
f"{API_PREFIX}/backlog/item-ids?result_filter=recoverable", headers=admin_headers,
|
||||
).get_json()["data"]
|
||||
assert len(recoverable["ids"]) == 1 and recoverable["total"] == 1
|
||||
|
||||
def offset(self, start):
|
||||
self._offset = start
|
||||
return self
|
||||
invalid = client.get(f"{API_PREFIX}/backlog/item-ids?result_filter=bogus", headers=admin_headers)
|
||||
assert invalid.status_code == 400
|
||||
|
||||
def limit(self, size):
|
||||
self._limit = size
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
end = None if self._limit is None else self._offset + self._limit
|
||||
return self._items[self._offset:end]
|
||||
def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client, admin_headers):
|
||||
"""GET /backlog/pending-match 分页 envelope 与无参兼容:带参回
|
||||
{records,total,page,page_size},无参保持历史数组(真实落档 25 行走
|
||||
SQL 分页下推链路:GROUP BY 计数 + 组首行锚点切片,验证稳定排序)。"""
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.backlog_service.circle_ledger_records_scope_union",
|
||||
lambda: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.backlog_service.pending_ledger_query",
|
||||
lambda **_kwargs: _Rows(rows),
|
||||
)
|
||||
for i in range(25):
|
||||
transfer_db.session.add(TransferMovementLedger(
|
||||
source_code="DBS-AWSBI", record_kind="inbound",
|
||||
doc_no=f"HOM-{900 + i}", line_no=str(i + 1), line_seq="", in_out_flag="",
|
||||
material_code=f"MAT-{i}", material_name="未匹配物料", specification="",
|
||||
external_doc_no=f"EXT-{i}", external_line_no=str(i + 1),
|
||||
lot_no="LOT-1", quantity="1", unit="PCS",
|
||||
warehouse_code="", storage_code="", movement_date="2026-08-05",
|
||||
source_file_id=None, file_version="v1", file_sha256="a" * 64,
|
||||
sheet_name="Receipt", row_no=i + 1,
|
||||
transfer_executed=False, executed_doc_no=None,
|
||||
))
|
||||
transfer_db.session.flush()
|
||||
|
||||
legacy = client.get(f"{API_PREFIX}/backlog/pending-match", headers=admin_headers)
|
||||
assert legacy.status_code == 200
|
||||
@@ -655,6 +671,10 @@ def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client,
|
||||
assert len(data["records"]) == 5 # 25 行第 2 页余量
|
||||
assert data["total"] == 25 and data["page"] == 2 and data["page_size"] == 20
|
||||
assert data["records"][0]["doc_no"] == "HOM-920" # 第 21 行(稳定排序切片)
|
||||
# [断言意图] 清单带出外部单号和数量,不再返回外部项次。
|
||||
assert data["records"][0]["external_doc_no"] == "EXT-20"
|
||||
assert data["records"][0]["quantity"] == "1"
|
||||
assert "external_line_no" not in data["records"][0]
|
||||
|
||||
|
||||
def test_list_transfer_sources(app, client, admin_headers):
|
||||
@@ -1404,9 +1424,10 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
monkeypatch,
|
||||
rows=[
|
||||
# 三张单:收料日期入 D1 组键 → 三个组各一单(组建单按组键升序)。
|
||||
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
|
||||
_movement_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
|
||||
_movement_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-03", "300.25", unit="KG"),
|
||||
# 日期均 ≤ 业务日 08-06 的 T−2 成熟边界(08-05 为 T−1 会被圈档封顶排除)。
|
||||
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-04", "500", unit="个"),
|
||||
_movement_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-03", "700", unit="PCS"),
|
||||
_movement_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-02", "300.25", unit="KG"),
|
||||
],
|
||||
stocks=[("MAT-001", "LOT-10", "500"), ("MAT-002", "LOT-20", "700"),
|
||||
("MAT-003", "LOT-30", "300.25")],
|
||||
@@ -1428,7 +1449,7 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
assert len(orders) == 3
|
||||
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源,
|
||||
# 收料日期升序,与建单的组键序一致)。
|
||||
assert [t["movement_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"]
|
||||
assert [t["movement_date"] for t in orders] == ["2026-08-02", "2026-08-03", "2026-08-04"]
|
||||
|
||||
by_status = {t["status"]: t for t in orders}
|
||||
assert set(by_status) == {"success", "business_failed", "result_unknown"}
|
||||
@@ -1442,7 +1463,7 @@ def test_run_projection_returns_order_list_with_multi_status(
|
||||
"status", "erp_document_no", "error_message", "lines",
|
||||
}
|
||||
assert success["doc_no"].startswith("HX-CN01-OR-")
|
||||
assert success["movement_date"] == "2026-08-05"
|
||||
assert success["movement_date"] == "2026-08-04"
|
||||
assert success["from_warehouse"] == "DBS-TRANSIT"
|
||||
assert success["to_warehouse"] == "HUB-CN01"
|
||||
assert success["erp_document_no"]
|
||||
@@ -1488,7 +1509,7 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows(
|
||||
"""复用单行集全量投影:失败单复用后,旧行与新行都在 orders.lines(D7①②)。"""
|
||||
deps, erp = _custom_transfer_deps(
|
||||
monkeypatch,
|
||||
rows=[_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个")],
|
||||
rows=[_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-04", "500", unit="个")],
|
||||
stocks=[("MAT-001", "LOT-10", "500")],
|
||||
)
|
||||
erp.write_scenarios["HOM-A"] = "business_failed"
|
||||
@@ -1505,8 +1526,8 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows(
|
||||
_custom_transfer_deps(
|
||||
monkeypatch,
|
||||
rows=[
|
||||
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
|
||||
_movement_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-05", "300", unit="PCS"),
|
||||
_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-04", "500", unit="个"),
|
||||
_movement_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-04", "300", unit="PCS"),
|
||||
],
|
||||
stocks=[("MAT-001", "LOT-10", "500"), ("MAT-003", "LOT-30", "300")],
|
||||
)
|
||||
@@ -1942,121 +1963,6 @@ def test_document_run_no_projection_and_audit_with_real_run(
|
||||
assert event.run_no == "RUN-DOC-REAL-1"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 待匹配桶「清空并重新解析」(spec §6,Task 7):预检 + 执行端点
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
REPARSE_SOURCE = "CRANE_API"
|
||||
REPARSE_OLD_SHA = "9" * 64
|
||||
REPARSE_SHA_A = "a1" + "0" * 62
|
||||
|
||||
|
||||
def _seed_reparse_endpoint_world(app, monkeypatch):
|
||||
"""端点用例种子:来源+已发布入站规则+一份可用归档+一条旧映射档行。
|
||||
|
||||
归档字节经 FakeArchiveStorage 注入并替换 file_asset_storage.get_bytes
|
||||
(单例对象级替换,service/repository 引用同源生效)。
|
||||
Returns:
|
||||
(archive_file, fake_storage) 元组。
|
||||
"""
|
||||
from tests.services.in_transit_transfer import factories
|
||||
|
||||
fake = factories.FakeArchiveStorage()
|
||||
monkeypatch.setattr(
|
||||
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
|
||||
source, _profile = factories.seed_inbound_reparse_source(REPARSE_SOURCE)
|
||||
archive = factories.seed_reparse_archive_file(
|
||||
source, sha=REPARSE_SHA_A, storage_key=f"archive/{REPARSE_SOURCE}/a.xlsx",
|
||||
created_at=datetime(2026, 10, 10, 8, 0, 0))
|
||||
fake.objects[f"archive/{REPARSE_SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-P1", "1", "I", "MAT-P1", "连接器", "LOT-P1", 500, "2026-08-05"],
|
||||
])
|
||||
with app.app_context():
|
||||
factories.seed_reparse_ledger_row(
|
||||
REPARSE_SOURCE, "ASN-P1", source_file_id=archive.id, sha=REPARSE_OLD_SHA)
|
||||
return archive, fake
|
||||
|
||||
|
||||
def test_pending_match_reparse_preview_endpoint(app, transfer_db, client, admin_headers, monkeypatch):
|
||||
"""GET /backlog/pending-match/reparse-preview → 200 envelope,预检四键形状。"""
|
||||
_archive, _fake = _seed_reparse_endpoint_world(app, monkeypatch)
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code={REPARSE_SOURCE}",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["success"] is True and body.get("request_id")
|
||||
data = body["data"]
|
||||
assert set(data.keys()) == {"files", "profile", "clearable_rows", "kept_rows"}
|
||||
assert data["profile"]["version"] == 1 and data["profile"]["code"]
|
||||
assert data["clearable_rows"] == 1 and data["kept_rows"] == 0
|
||||
assert data["files"][0]["sha256"] == REPARSE_SHA_A
|
||||
assert data["files"][0]["rows"] == 1
|
||||
|
||||
|
||||
def test_pending_match_reparse_preview_requires_source_code(app, client, admin_headers):
|
||||
"""缺 source_code → 400(参数校验,envelope error)。"""
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/backlog/pending-match/reparse-preview", headers=admin_headers)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_pending_match_reparse_endpoint_executes_and_audits(app, transfer_db, client, admin_headers, monkeypatch):
|
||||
"""POST /backlog/pending-match/reparse → 200 envelope,清空重落计数 + 审计事件。"""
|
||||
from app.models import TransferAuditEvent, TransferMovementLedger
|
||||
|
||||
archive, _fake = _seed_reparse_endpoint_world(app, monkeypatch)
|
||||
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/backlog/pending-match/reparse", headers=admin_headers,
|
||||
json={"source_code": REPARSE_SOURCE},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["success"] is True
|
||||
data = body["data"]
|
||||
assert (data["cleared"], data["reinserted"]) == (1, 1)
|
||||
assert data["kept_unrebuildable"] == 0
|
||||
assert data["collapses"] == 0 # [断言意图] 坍缩计数随端点透出(无坍缩=0)
|
||||
assert data["files"][0]["sha256"] == REPARSE_SHA_A
|
||||
with app.app_context():
|
||||
transfer_db.session.expire_all()
|
||||
row = TransferMovementLedger.query.filter_by(
|
||||
source_code=REPARSE_SOURCE, doc_no="ASN-P1").one()
|
||||
# [断言意图] 新映射值随执行生效且溯源换新(真实 source_file_id/sha256)。
|
||||
assert row.quantity == "500" and row.file_sha256 == REPARSE_SHA_A
|
||||
assert row.source_file_id == archive.id
|
||||
event = TransferAuditEvent.query.filter_by(
|
||||
event_type="TRANSFER_PENDING_MATCH_REPARSED").one()
|
||||
assert event.aggregate_id == REPARSE_SOURCE
|
||||
assert event.after_json["operator"] == "admin"
|
||||
assert event.after_json["cleared"] == 1 and event.after_json["reinserted"] == 1
|
||||
|
||||
|
||||
def test_pending_match_reparse_requires_authentication(client):
|
||||
"""未认证:预检/执行均 401(envelope error)。"""
|
||||
preview = client.get(f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code=X")
|
||||
execute = client.post(f"{API_PREFIX}/backlog/pending-match/reparse", json={"source_code": "X"})
|
||||
assert preview.status_code == 401
|
||||
assert execute.status_code == 401
|
||||
|
||||
|
||||
def test_pending_match_reparse_forbidden_without_permission(app, client, unauthorized_headers):
|
||||
"""无 in_transit_transfer Agent 权限:预检/执行均 403(越权检查)。"""
|
||||
preview = client.get(
|
||||
f"{API_PREFIX}/backlog/pending-match/reparse-preview?source_code=X",
|
||||
headers=unauthorized_headers)
|
||||
execute = client.post(
|
||||
f"{API_PREFIX}/backlog/pending-match/reparse", headers=unauthorized_headers,
|
||||
json={"source_code": "X"})
|
||||
assert preview.status_code == 403
|
||||
assert execute.status_code == 403
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 5:证据压缩包按记录类型分目录;当天清单只列可用文件的大小与预签地址
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -2292,8 +2198,10 @@ def test_evidence_files_list_returns_today_size_and_presigned_url(
|
||||
)
|
||||
signed = []
|
||||
|
||||
def _presign(storage_key, *, expires_seconds):
|
||||
signed.append((storage_key, expires_seconds))
|
||||
def _presign(storage_key, *, expires_seconds, download_name=None):
|
||||
signed.append((storage_key, expires_seconds, download_name))
|
||||
if download_name:
|
||||
return f"https://files.test/{storage_key}?filename={download_name}"
|
||||
return f"https://files.test/{storage_key}"
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -2318,14 +2226,27 @@ def test_evidence_files_list_returns_today_size_and_presigned_url(
|
||||
assert rows[0]["created_at"] == now.isoformat()
|
||||
assert rows[0]["presigned_url"] == "https://files.test/evidence/list-new"
|
||||
assert rows[1]["presigned_url"] == "https://files.test/evidence/list-old"
|
||||
from app.api.in_transit_transfer import evidence_download_filename
|
||||
|
||||
# [断言意图] 保存名是库存源加东八区年月日和时分,不用对象键哈希。
|
||||
# 02:57 UTC 在上海是当天 10:57;16:30 UTC 已跨到上海次日 00:30。预览地址不带附件名。
|
||||
assert evidence_download_filename("CRANE", datetime(2026, 10, 22, 2, 57), "hash.xlsx") == "CRANE_20261022_1057.xlsx"
|
||||
assert evidence_download_filename("CRANE", datetime(2026, 10, 21, 16, 30), "a.csv") == "CRANE_20261022_0030.csv"
|
||||
newer_name = evidence_download_filename(EVIDENCE_SOURCE, now, "Inbound.xlsx")
|
||||
older_name = evidence_download_filename(EVIDENCE_SOURCE, now - timedelta(minutes=20), "Older.xlsx")
|
||||
assert rows[0]["download_url"] == f"https://files.test/evidence/list-new?filename={newer_name}"
|
||||
assert rows[1]["download_url"] == f"https://files.test/evidence/list-old?filename={older_name}"
|
||||
for row in rows:
|
||||
assert set(row) == {
|
||||
"file_id", "original_filename", "created_at", "sha256", "file_size", "presigned_url",
|
||||
"file_id", "original_filename", "created_at", "sha256", "file_size",
|
||||
"presigned_url", "download_url",
|
||||
}
|
||||
assert "rows" not in row and "row_count" not in row
|
||||
assert signed == [
|
||||
("evidence/list-new", 300),
|
||||
("evidence/list-old", 300),
|
||||
("evidence/list-new", 300, None),
|
||||
("evidence/list-new", 300, newer_name),
|
||||
("evidence/list-old", 300, None),
|
||||
("evidence/list-old", 300, older_name),
|
||||
]
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
@@ -135,9 +135,11 @@ def test_abort_on_parse_failure_deletes_nothing(app, archive_storage):
|
||||
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
|
||||
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
|
||||
])
|
||||
# 坏文件:表头与绑定别名全不匹配 → 数据行缺单号 → 解析必失败。
|
||||
# 坏文件:料号可映射但缺单号列 → 行级 missing_invoice_no → 解析必失败。
|
||||
# 【不能用全垃圾表头】料号空行按 2026-10-21 规则静默跳过(不做管控不进
|
||||
# 异动表),表头全不匹配的文件会以 0 行成功收场,不再触发中止。
|
||||
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx(
|
||||
[["X1", 100, "X2"]], headers=["只此一列", "随便", "没有映射"])
|
||||
[["MAT-BAD"]], headers=["料号"])
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, sha=OLD_SHA)
|
||||
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id, sha=OLD_SHA)
|
||||
|
||||
@@ -612,13 +612,18 @@ def test_prepare_enqueues_single_transfer_run_job(
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 补充:worker 二次门禁(Hash 失效 fail-closed,不触外部)
|
||||
# 补充:文件版本对账门禁退役(2026-10-22)——版本变化不再拦截 worker 执行
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_execute_run_rechecks_file_hash_fail_closed(
|
||||
def test_worker_executes_despite_file_version_change(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
|
||||
):
|
||||
"""worker 二次门禁:文件版本对账失败 → fail-closed(单置 technical_failed、行阻断、零写入)。"""
|
||||
"""文件版本对账门禁退役:最新文件 sha 变化后 worker 仍逐单执行到底。
|
||||
|
||||
[断言意图] 入站抓取是部分导出——新文件不含旧行 ≠ 旧行失效,按最新文件 sha
|
||||
对账会错误卡死未处理行(557 行积压实测);门禁退役后版本滞后的行照常执行,
|
||||
证据漂移的防护由写前库存复查(ERP 账面严格相等)承担。
|
||||
"""
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
@@ -626,16 +631,18 @@ def test_execute_run_rechecks_file_hash_fail_closed(
|
||||
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
doc = _doc_for(run)
|
||||
# 文件已更新未重新匹配:worker 复核必须拒绝执行。
|
||||
# 文件已更新(最新投影 sha=e,行/档仍持旧版本):旧门禁在此整 Run 落败。
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
|
||||
execute_run(run_id=run.id, deps=deps)
|
||||
db.session.expire_all()
|
||||
doc = db.session.get(TransferDocument, doc.id)
|
||||
assert doc.status == "technical_failed"
|
||||
# [断言意图] 版本滞后不再拦截:单成功、行成功、ERP 照常写入(写前复查因
|
||||
# 账面 500==500 通过)。
|
||||
assert doc.status == "success"
|
||||
linked = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
|
||||
assert all(item.status == "blocked_recoverable" for item in linked)
|
||||
assert erp.write_calls() == []
|
||||
assert all(item.status == "success" for item in linked)
|
||||
assert len(erp.write_calls()) == 1
|
||||
db.session.expire_all()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -706,7 +713,8 @@ def test_requeried_rows_reuse_order_without_new_rows(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status,
|
||||
):
|
||||
"""失败单 → 行重查回 ready(run_id 留旧 Run)→ 纯旧行再次提交新 Run:
|
||||
归属补齐进新 Run(attempt_no 防双跳)、二次门禁覆盖该行、复用同单、投影非空。"""
|
||||
归属补齐进新 Run(attempt_no 防双跳)、复用同单、执行到底、投影非空
|
||||
(原「二次门禁覆盖该行」段随文件版本对账门禁退役 2026-10-22 删除)。"""
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
@@ -747,38 +755,17 @@ def test_requeried_rows_reuse_order_without_new_rows(
|
||||
assert reused.submit_timestamp == old_ts
|
||||
assert reused.run_id == run2.id
|
||||
|
||||
# [二次门禁覆盖该行] 文件 Hash 失效 → 行被阻断(证明门禁按新 Run 行集复核)。
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
# [执行完成] 文件版本对账门禁退役(2026-10-22):重查回 ready 的旧行不再被
|
||||
# 版本戳拦截,直接执行到底——单/行/Run 同成功族,投影非空。
|
||||
execute_run(run_id=run2.id, deps=deps)
|
||||
db.session.expire_all()
|
||||
row = db.session.get(TransferInvoiceItem, row.id)
|
||||
reused = db.session.get(TransferDocument, doc.id)
|
||||
run2 = TransferRun.query.filter_by(run_no=run2.run_no).first()
|
||||
assert row.status == "blocked_recoverable"
|
||||
assert row.result_code == "file_changed"
|
||||
# 断言意图:P2-1——executing 单遇门禁失败统一落 technical_failed(不留组锁悬挂),
|
||||
# Run 终态与单一致(失败族)。
|
||||
assert reused.status == "technical_failed"
|
||||
assert run2.status == "failed"
|
||||
|
||||
# [修复后重跑] 行再次重查回 ready → 新 Run 复用同单全量重跑 → 投影非空。
|
||||
patch_source_file_status()
|
||||
row.status = "ready_to_execute"
|
||||
row.result_code = None
|
||||
row.result_message = None
|
||||
db.session.commit()
|
||||
third = prepare_execution(item_ids=[row.id], deps=deps)
|
||||
run3 = TransferRun.query.filter_by(run_no=third.run_no).first()
|
||||
execute_run(run_id=run3.id, deps=deps)
|
||||
db.session.expire_all()
|
||||
run3 = TransferRun.query.filter_by(run_no=run3.run_no).first()
|
||||
reused = db.session.get(TransferDocument, doc.id)
|
||||
row = db.session.get(TransferInvoiceItem, row.id)
|
||||
# 断言意图:终态与投影一致——单/行/Run 同成功族,_build_run_result 投影非空。
|
||||
assert reused.status == "success"
|
||||
assert run3.status == "success"
|
||||
assert run2.status == "success"
|
||||
assert row.status == "success"
|
||||
restored = get_run_projection(run3.run_no)
|
||||
restored = get_run_projection(run2.run_no)
|
||||
assert len(restored["result"]["external_documents"]) == 1
|
||||
assert restored["result"]["exceptions"] == []
|
||||
db.session.expire_all()
|
||||
@@ -792,14 +779,19 @@ def get_run_projection(run_no: str) -> dict:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 评审修正 P2-1:executing 单遇二次门禁失败 → technical_failed(不留组锁悬挂)
|
||||
# 评审修正 P2-1 历史段:executing 单遇门禁失败曾落 technical_failed——
|
||||
# 该门禁已随文件版本对账退役(2026-10-22),本用例改为锁定新行为
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_recheck_failure_marks_executing_order_technical_failed(
|
||||
def test_executing_stalled_order_executes_despite_file_version_change(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
|
||||
):
|
||||
"""上次 worker 中途搁浅的 executing 单,本次门禁复核失败 → 单 technical_failed
|
||||
(可被 D18 关闭释放组锁),行阻断、Run failed、零外部写入。"""
|
||||
"""上次 worker 中途搁浅的 executing 单,文件版本变化后重跑仍正常执行到底。
|
||||
|
||||
[断言意图] 门禁退役(2026-10-22):executing 搁浅单不再因文件 Hash 复核失败
|
||||
落 technical_failed——逐单执行照常走写前库存复查(账面 500==500 通过),
|
||||
单/行/Run 同成功族、ERP 恰一次写入。
|
||||
"""
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
@@ -815,12 +807,11 @@ def test_recheck_failure_marks_executing_order_technical_failed(
|
||||
execute_run(run_id=run.id, deps=deps)
|
||||
db.session.expire_all()
|
||||
doc = db.session.get(TransferDocument, doc.id)
|
||||
# 断言意图:P2-1——executing 单门禁失败同样落 technical_failed(而非停在 executing)。
|
||||
assert doc.status == "technical_failed"
|
||||
assert doc.error_code == "file_changed"
|
||||
# [断言意图] 版本变化不再拦截:搁浅单继续执行成功,行 success、ERP 恰一次写入。
|
||||
assert doc.status == "success"
|
||||
linked = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
|
||||
assert all(item.status == "blocked_recoverable" for item in linked)
|
||||
assert erp.write_calls() == []
|
||||
assert all(item.status == "success" for item in linked)
|
||||
assert len(erp.write_calls()) == 1
|
||||
db.session.expire_all()
|
||||
|
||||
|
||||
@@ -1050,51 +1041,47 @@ def test_order_failure_does_not_seal_ledger_records(
|
||||
db.session.expire_all()
|
||||
|
||||
|
||||
def test_gate_anchors_to_ledger_record_version(
|
||||
def test_file_version_change_no_longer_blocks_execution(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
|
||||
):
|
||||
"""执行门禁②改锚:档记录==最新文件 sha 即放行(出生戳陈旧不再误拒);记录滞后即拒。"""
|
||||
"""文件版本对账门禁退役(2026-10-22):档记录 sha 滞后最新文件不再拒绝执行
|
||||
(部分导出缺席≠失效);行级 file_current 徽标仍提示滞后,防护下沉写前库存复查。"""
|
||||
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
|
||||
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
|
||||
])
|
||||
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
|
||||
item = _ready_items()[0]
|
||||
from app.models import TransferMovementLedger
|
||||
|
||||
record = db.session.get(TransferMovementLedger, item.ledger_record_id)
|
||||
|
||||
# [改锚行为变更] 档换版原行更新(记录 sha→e)而行出生戳仍是旧值:
|
||||
# 新口径=档记录==最新文件 → 门禁放行(旧口径按出生戳误判 FILE_CHANGED)。
|
||||
# 档记录滞后最新文件(记录 e,最新投影 f):旧门禁在此抛 TRANSFER.FILE_CHANGED。
|
||||
record.file_sha256 = "e" * 64
|
||||
db.session.commit()
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
patch_source_file_status({"DBS-AWSBI": "f" * 64})
|
||||
outcome = prepare_execution(item_ids=[item.id], deps=deps)
|
||||
assert outcome.run_no # [断言意图] 档记录当前 → 可执行(不误拒)
|
||||
assert outcome.run_no # [断言意图] 版本滞后不再拒绝执行(不回退旧门禁)
|
||||
|
||||
# 档记录滞后最新文件(记录 e,最新 f)→ FILE_CHANGED fail-closed。
|
||||
db.session.expire_all()
|
||||
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
|
||||
execute_run(run_id=run.id, deps=deps)
|
||||
db.session.expire_all()
|
||||
item = db.session.get(TransferInvoiceItem, item.id)
|
||||
item.status = "ready_to_execute"
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
db.session.commit()
|
||||
patch_source_file_status({"DBS-AWSBI": "f" * 64})
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
prepare_execution(item_ids=[item.id], deps=deps)
|
||||
assert exc.value.code == "TRANSFER.FILE_CHANGED" # [断言意图] 记录落后 → 拒绝执行
|
||||
db.session.expire_all()
|
||||
assert item.status == "success" # 写前复查(账面 500==500)通过后正常写 ERP
|
||||
|
||||
# [断言意图] 行级「文件已更新」徽标仍提示滞后(提示不拦截,与门禁退役配套)。
|
||||
restored = restore_matching(summary.matching_id, deps=deps)
|
||||
restored_item = next(i for i in restored["items"] if i.invoice_no == "HOM-A")
|
||||
assert restored_item.file_current is False
|
||||
|
||||
|
||||
def test_execute_gate_compares_outbound_evidence_not_inbound(
|
||||
def test_file_current_badge_uses_outbound_evidence_for_outbound_rows(
|
||||
transfer_db, monkeypatch, seq_loader,
|
||||
):
|
||||
"""出站档行的 file_current 与执行门禁对出站文件 sha,不拿入站投影比较。
|
||||
"""出站档行的 file_current 徽标按出站文件 sha 计算,不拿入站投影比较。
|
||||
|
||||
核心逻辑:同一来源入站投影 sha 与出站不同。出站档 file_sha256 等于出站投影。
|
||||
若门禁仍解析入站,file_current 为假且 prepare_execution 抛 FILE_CHANGED。
|
||||
核心逻辑:同一来源入站投影 sha 与出站不同。出站档 file_sha256 等于出站投影
|
||||
→ 徽标 file_current=True(执行门禁已退役 2026-10-22,本用例只锁徽标口径;
|
||||
若徽标误用入站投影,file_current 为假)。
|
||||
"""
|
||||
del seq_loader # 夹具注入单号序列;本用例只确认门禁放行。
|
||||
out_sha = "o" * 64
|
||||
@@ -1142,5 +1129,5 @@ def test_execute_gate_compares_outbound_evidence_not_inbound(
|
||||
assert item.ledger_record.record_kind == "outbound"
|
||||
assert item.status == "ready_to_execute"
|
||||
outcome = prepare_execution(item_ids=[item.id], deps=deps)
|
||||
# [断言意图] 执行门禁放行。误用入站 sha 会以 FILE_CHANGED 拒绝。
|
||||
# [断言意图] 执行照常提交(门禁已退役,本行仅确认链路完好)。
|
||||
assert outcome.run_no
|
||||
@@ -24,6 +24,7 @@ from app.models import TransferInvoiceItem, TransferMovementLedger, TransferRun,
|
||||
from app.services.in_transit_transfer.backlog_service import (
|
||||
backlog_summary,
|
||||
list_pending_match_records,
|
||||
list_pending_match_records_page,
|
||||
)
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
_item_dto,
|
||||
@@ -40,12 +41,18 @@ NOW = datetime(2026, 10, 14, 12, 0, 0)
|
||||
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
|
||||
sha: str = "a" * 64, row_no: int = 1, source_code: str = "DBS-AWSBI",
|
||||
record_kind: str = "inbound", movement_date: str | None = "2026-10-13",
|
||||
transfer_executed: bool = False, executed_doc_no: str | None = None):
|
||||
"""种子一条档记录(缺省=默认类型范围内的收料记录,与 test_requery_scope 同款)。"""
|
||||
transfer_executed: bool = False, executed_doc_no: str | None = None,
|
||||
external_doc_no: str = "", external_line_no: str = "",
|
||||
material_code: str = "MAT-1", material_name: str = "物料1"):
|
||||
"""种子一条档记录(缺省=默认类型范围内的收料记录,与 test_requery_scope 同款)。
|
||||
|
||||
external_doc_no 为空时,待匹配清单不会把该行并进其他外部单。
|
||||
"""
|
||||
row = TransferMovementLedger(
|
||||
source_code=source_code, record_kind=record_kind,
|
||||
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
|
||||
material_code="MAT-1", material_name="物料1", specification="",
|
||||
material_code=material_code, material_name=material_name, specification="",
|
||||
external_doc_no=external_doc_no, external_line_no=external_line_no,
|
||||
lot_no=lot_no, quantity=quantity, unit="PCS",
|
||||
warehouse_code="", storage_code="", movement_date=movement_date,
|
||||
source_file_id=None, file_version="v1", file_sha256=sha,
|
||||
@@ -100,6 +107,55 @@ def test_pending_match_bucket_lists_unmatched_records():
|
||||
assert "item_id" not in type(first).__dataclass_fields__
|
||||
|
||||
|
||||
def test_pending_match_list_rolls_up_quantity_by_external_doc():
|
||||
"""同一外部单号的多项次合成一行,数量相加;没有外部单号的档行仍逐行留下。"""
|
||||
_seed_ledger("HOM-1", quantity="1.50", row_no=1, external_doc_no="5975091", external_line_no="0010")
|
||||
_seed_ledger(
|
||||
"HOM-1", quantity="2.50", row_no=2, external_doc_no=" 5975091 ", external_line_no="0020", lot_no="LOT-2",
|
||||
)
|
||||
_seed_ledger(
|
||||
"HOM-9", quantity="4", row_no=3, external_doc_no="5975091", external_line_no="0030",
|
||||
lot_no="LOT-3", material_code="MAT-9", material_name="另一物料", movement_date="2026-10-12",
|
||||
)
|
||||
_seed_ledger("HOM-2", quantity="7", row_no=4, external_doc_no="5976000", external_line_no="0010", lot_no="LOT-4")
|
||||
_seed_ledger("HOM-3", quantity="4", row_no=5, lot_no="LOT-5")
|
||||
_seed_ledger(
|
||||
"HOM-4", quantity="8", row_no=6, external_doc_no="5975091", external_line_no="0010",
|
||||
lot_no="LOT-6", source_code="OTHER-SRC",
|
||||
)
|
||||
|
||||
records = list_pending_match_records()
|
||||
rolled = next(
|
||||
record for record in records
|
||||
if record.external_doc_no == "5975091" and record.source_code == "DBS-AWSBI"
|
||||
)
|
||||
|
||||
# [断言意图] 同一来源、同一记录类型、同一外部单号的项次合成一行,数量相加。
|
||||
assert rolled.quantity == "8"
|
||||
# [断言意图] 内部单号、料号、异动日期在组内不一致时留空,避免显示成其中一笔。
|
||||
assert rolled.doc_no == ""
|
||||
assert rolled.material_code is None
|
||||
assert rolled.material_name is None
|
||||
assert rolled.movement_date is None
|
||||
assert "external_line_no" not in type(rolled).__dataclass_fields__
|
||||
assert next(record for record in records if record.external_doc_no == "5976000").quantity == "7"
|
||||
blank = [record for record in records if not record.external_doc_no]
|
||||
# [断言意图] 没有外部单号的档不并进别的单。
|
||||
assert len(blank) == 1 and blank[0].doc_no == "HOM-3" and blank[0].quantity == "4"
|
||||
other = next(record for record in records if record.source_code == "OTHER-SRC")
|
||||
# [断言意图] 不同来源的同一外部单号分开合计。
|
||||
assert other.external_doc_no == "5975091" and other.quantity == "8" and other.doc_no == "HOM-4"
|
||||
assert len(records) == 4
|
||||
summary = backlog_summary()
|
||||
# [断言意图] 首页待匹配、可匹配数字与清单合并后的行数一致,不再按档行计数。
|
||||
assert summary.pending_match_count == len(records)
|
||||
assert summary.matchable_count == len(list_pending_match_records(segment="matchable"))
|
||||
|
||||
page = list_pending_match_records_page(page=1, page_size=2)
|
||||
# [断言意图] 分页总数是合并后的行数,当前页按合并结果切片。
|
||||
assert page.total == 4 and len(page.records) == 2
|
||||
|
||||
|
||||
def test_pending_match_bucket_summary_count():
|
||||
"""backlog 汇总带 pending_match 计数(首页第 4 张数字卡数据源)。"""
|
||||
_seed_ledger("HOM-1")
|
||||
|
||||
Reference in new issue
Block a user