feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误

- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一
- 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单
- worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步
- 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5)
- 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6)
- 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果
- 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
This commit is contained in:
hugo committed 2026-09-30 00:20:06 +08:00
1 parent 993e581135
commit abf3d48927
144 files changed
+10161 -2132

No files matched your search

@@ -36,14 +36,17 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
核心逻辑:可选恢复 → 自动匹配 → 若 executable_count>0 则执行并写 run_no;
空数据日(匹配后无可执行行)直接返回,不执行、不通知、不记 error(C5)。
Args:
business_date: 业务日期。
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
sender / recipients: 企微通知(None 则跳过通知)。
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
Returns:
AutoTransferOutcome。
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
"""
outcome = AutoTransferOutcome()
if recover_history:
@@ -57,10 +60,12 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
business_date=business_date,
deps=deps,
)
# 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役);
# 无可执行行时门禁抛错,
# 与旧流程一致记入 errors 不阻断通知阶段。
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
if summary.counts.executable_count == 0:
return outcome
# [STEP 3] 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)。
executed = execute_matching_items(matching_id=summary.matching_id, deps=deps)
outcome.run_no = executed.run_no
outcome.run_status = executed.status
@@ -13,6 +13,9 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from sqlalchemy import func
from app import db
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer.status import TransferStatus
@@ -73,24 +76,35 @@ def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical
return AGING_NORMAL
def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]:
"""返回明细最近一次 Attempt(无则 None)。"""
return TransferAttempt.query.filter_by(item_id=item.id).order_by(
TransferAttempt.created_at.desc(),
).first()
def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
"""批量取每行最近一次 Attempt 时间(单条 GROUP BY 聚合)。
【为什么批量】待处理池历史行持续累积,旧实现逐行 `_latest_attempt` 子查询
在列表接口放大为 2N+1 条 SQL(age 判定一次、DTO 组装各一次),是
backlog / backlog/summary 接口 4s+ 响应的根因(2026-09-29 修复);
分组聚合后整池仅 1 条。
def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int:
"""按最近 Attempt 或明细更新时间计算积压天数。"""
latest = _latest_attempt(item)
base = latest.created_at if latest is not None else item.updated_at
return max(0, int((now - base).total_seconds() // 86400))
Args:
item_ids: 池内明细 id 列表(空列表直接返回空表,不发查询)。
Returns:
{item_id: 最近 Attempt 的 created_at};无 Attempt 的行不在表中。
"""
if not item_ids:
return {}
rows = (
db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at))
.filter(TransferAttempt.item_id.in_(item_ids))
.group_by(TransferAttempt.item_id)
.all()
)
return {item_id: latest for item_id, latest in rows}
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
排序:收料日期 → Invoice → 创建时间(业务稳定键,与重查/恢复等操作无关)。
排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
以此排序会让正在处理的行在列表中跳位。
@@ -110,15 +124,19 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
)
if source_code:
query = query.filter_by(source_code=source_code)
output: list[BacklogItemDTO] = []
for item in query.order_by(
pool_rows = query.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
).all():
age = _item_age_days(item, current)
latest = _latest_attempt(item)
).all()
latest_map = _latest_attempt_times([row.id for row in pool_rows])
output: list[BacklogItemDTO] = []
for item in pool_rows:
latest = latest_map.get(item.id)
base = latest if latest is not None else item.updated_at
age = max(0, int((current - base).total_seconds() // 86400))
if item.status == TransferStatus.RESULT_UNKNOWN.value:
level = AGING_UNKNOWN
elif item.status == TransferStatus.MANUALLY_CLOSED.value:
@@ -134,7 +152,7 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
reason=item.result_message or item.result_code or "",
age_days=age,
aging_level=level,
last_attempt_at=latest.created_at.isoformat() if latest is not None else None,
last_attempt_at=latest.isoformat() if latest is not None else None,
receipt_date=item.receipt_date,
material_name=item.material_name,
from_warehouse=item.from_warehouse,
@@ -74,7 +74,7 @@ class MatchingCountsDTO:
# 文件已落地、尚未查 ERP 库存的待查行(status='matching' +
# result_code='pending_stock_check',evidence_sync 落地态)。
pending_stock_check_count: int = 0
# blocked_file_removed 行数(文件新版本中消失,已出清,不进默认视图/明细)。
# blocked_file_removed 行数(历史残留:存续语义上线前误标;不进默认视图/明细,修复脚本恢复后归零)。
invalid_count: int = 0
@@ -162,13 +162,16 @@ class ExternalDocumentDTO:
@dataclass(frozen=True)
class TransferExceptionDTO:
"""未生成 外部系统 单据的异常项(单独展示)。"""
"""未生成 外部系统 单据的异常项(单独展示;仅收未建单被阻断的行)。"""
source_code: str
invoice_no: str
material_no: str
reason: str
facts: str
# 行级人话原因(= 行 result_message,2026-09-29 契约扩充):前端展示优先于
# reason 状态码标签(分组阻断时携带阻断单号等可行动信息),空则标签兜底。
message: str = ""
@dataclass(frozen=True)
@@ -1,10 +1,11 @@
"""在途调拨业务日期与成熟度策略。
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
昨天及更早可匹配,未来日期阻断)。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 matching_service / recovery_service 复用,
避免各服务各自计算导致口径漂移。
用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2
可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期
(ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。
依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
复用,避免各服务各自计算导致口径漂移。
"""
from __future__ import annotations
@@ -19,15 +20,29 @@ MATURITY_ELIGIBLE = "eligible"
MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。
# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。
DEFAULT_MATURITY_LAG_DAYS = 2
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
_US_DATE_FORMATS = (
"%m/%d/%Y %H:%M:%S",
"%m/%d/%Y %H:%M",
"%m/%d/%Y",
)
def parse_date(value: date | datetime | str) -> date:
"""将 date/datetime 或日期字符串归一化为 date。
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料);
均失败则 ValueError(fail-closed)。
Args:
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
value: date/datetime 对象,或日期字符串(ISO 如 '2026-08-26 17:38:38';
美式如 '08/13/2026 13:08:00')。
Returns:
归一化后的 date。
归一化后的 date(忽略时分秒)。
Raises:
ValueError: 字符串不是可识别的日期/日期时间。
"""
@@ -42,8 +57,15 @@ def parse_date(value: date | datetime | str) -> date:
pass
try:
return datetime.fromisoformat(text).date()
except ValueError as exc:
raise ValueError(f"Invalid date value: {value!r}") from exc
except ValueError:
pass
# [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。
for fmt in _US_DATE_FORMATS:
try:
return datetime.strptime(text, fmt).date()
except ValueError:
continue
raise ValueError(f"Invalid date value: {value!r}")
def business_date_now(moment: datetime | None = None) -> date:
@@ -85,31 +107,51 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat
return start_utc, start_utc + timedelta(hours=24)
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
"""按 D+1 规则判定收料日期成熟度。
def maturity_lag_days() -> int:
"""读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。
Returns:
成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值,
保持策略函数可纯调用。
"""
try:
from flask import current_app
return int(current_app.config.get(
"IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS)
except RuntimeError: # 无 app 上下文
return DEFAULT_MATURITY_LAG_DAYS
def maturity_status(receipt_date: date | str, business_date: date | str,
lag_days: int | None = None) -> str:
"""按 T+lag 规则判定收料日期成熟度(默认 lag=2)。
Args:
receipt_date: 收料日期。
business_date: 当前业务日期 T。
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
Returns:
'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或
'future'(receipt_date > T,结构化阻断)。
'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或
'future'(receipt > T,结构化阻断)。
"""
receipt = parse_date(receipt_date)
business = parse_date(business_date)
if receipt == business:
return MATURITY_NOT_MATURED
lag = maturity_lag_days() if lag_days is None else int(lag_days)
if receipt > business:
return MATURITY_FUTURE
if receipt > business - timedelta(days=lag):
return MATURITY_NOT_MATURED
return MATURITY_ELIGIBLE
def eligible_receipt_date_to(business_date: date | str) -> date:
"""返回可进入匹配的收料截止日期(业务日期 T - 1 天)。
def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date:
"""返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。
Args:
business_date: 当前业务日期。
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
Returns:
T - 1 天。
T - lag 天。
"""
return parse_date(business_date) - timedelta(days=1)
lag = maturity_lag_days() if lag_days is None else int(lag_days)
return parse_date(business_date) - timedelta(days=lag)
@@ -29,6 +29,7 @@ from app.services.in_transit_transfer.matching_service import (
)
from app.services.in_transit_transfer.strategy import (
DEFAULT_CONFIRM_TTL_SECONDS,
DEFAULT_INVENTORY_STALE_TTL_SECONDS,
default_strategy,
)
@@ -107,6 +108,18 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
_override = deps
def _ttl_from_config(key: str, default: int) -> int:
"""读取整型 TTL 配置(无应用上下文/非法值回落代码默认,下限 1 秒)。"""
try:
raw = current_app.config.get(key, default)
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
raw = default
try:
return max(1, int(raw))
except (TypeError, ValueError):
return default
def _strategy_from_config():
"""从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。
@@ -115,19 +128,18 @@ def _strategy_from_config():
无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。
Returns:
TransferStrategyPolicy(confirm_ttl_seconds=max(1, 配置值),禁令项沿用默认)。
TransferStrategyPolicy(confirm_ttl_seconds / inventory_stale_ttl_seconds
=max(1, 配置值),禁令项沿用默认)。
"""
try:
raw = current_app.config.get(
return replace(
default_strategy(),
confirm_ttl_seconds=_ttl_from_config(
"IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS,
)
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
raw = DEFAULT_CONFIRM_TTL_SECONDS
try:
ttl = int(raw)
except (TypeError, ValueError):
ttl = DEFAULT_CONFIRM_TTL_SECONDS
return replace(default_strategy(), confirm_ttl_seconds=max(1, ttl))
),
inventory_stale_ttl_seconds=_ttl_from_config(
"IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS", DEFAULT_INVENTORY_STALE_TTL_SECONDS,
),
)
def get_transfer_dependencies() -> TransferDeps:
@@ -3,16 +3,22 @@
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
matching_service(_item_evaluated_sha 复用)/ models / audit。
逻辑:一次解析三分类写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/
contracts / models / audit。
逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
查的,作废);消失标记行复现 → 无论证据变化与否无条件恢复待查(防复现行卡死
隐藏);文件里消失 → blocked_file_removed 且换戳到最新 sha(保证对齐入口
row_shas 收敛直通)。全程零外部调用(不查 ERP、不触发 RPA);终态行绝不触碰,
终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
查的,作废);历史残留 blocked_file_removed 行复现 → 无论证据变化与否无条件
恢复待查(防御路径,2026-09-28 起同步不再新产生该码);缺席存续(只换版本戳
到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行
复现时经 STEP 2 正常刷新)。全程零外部调用(不查 ERP、不触发 RPA);终态行
绝不触碰,终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析失败
标记(parse_failed 三列置空,投影恢复 ready);桥入口同步失败先 rollback
(保持桥隔离),仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID /
ReceiptFileSchemaError)把失败事实独立 commit 落到当前可用文件上。
"""
from __future__ import annotations
@@ -24,14 +30,20 @@ from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.file_parser import parse_movement_rows
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError, parse_movement_rows
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
from app.services.in_transit_transfer.matching_service import (
RESULT_FILE_REMOVED,
RouteNotResolvedError,
_item_evaluated_sha,
_latest_usable_report_file,
)
from app.services.in_transit_transfer.source_file_status import (
clear_receipt_parse_failure,
record_receipt_parse_failure,
resolve_source_file_status,
)
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
from app.services.in_transit_transfer.transfer_type import (
TransferType,
filter_invoices_for_type,
@@ -61,20 +73,25 @@ class SyncOutcome:
inserted: int = 0 # 文件有、本地无 → 插入待查行
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
removed: int = 0 # 文件里消失 → blocked_file_removed
absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28)
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记
(parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该
文件已成功解析;无标记时为 no-op。
Args:
source_code: 来源实例编码。
deps: TransferDeps(只用 file_repository 与 route_resolver)。
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
Returns:
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None。
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支
不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
"""
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is None:
@@ -112,7 +129,7 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
).all()
}
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "removed": 0, "skipped": 0}
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0}
incoming_keys: set[tuple] = set()
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
@@ -166,10 +183,10 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
))
counters["inserted"] += 1
continue
# [Important② 复现行] 消失标记行(blocked_file_removed)重新出现在最新
# 文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)已
# 失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
# 非终态行恢复不违反终态冻结。
# [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现
# 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)
# 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
# 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
# 据此收敛直通)。
@@ -195,27 +212,32 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
row.result_code = SYNC_RESULT_PENDING
row.result_message = None
row.external_quantity = None # 旧库存对旧数量,作废待重查
# [库存查得时刻] 库存作废即置空取数时刻(不变式:本字段=当前
# external_quantity 的取数时间;NULL=无库存数据,stale 不判定)。
row.inventory_checked_at = None
counters["reset_pending"] += 1
else:
counters["refreshed"] += 1
# refreshed/absent_kept 只换文件版本戳——本分支不续期 inventory_checked_at
#(2026-09-29 起 stale 判定时钟,换戳≠查过库存),仅 updated_at 照常续期。
row.updated_at = now
# [STEP 4] 文件里消失的非终态行 → blocked_file_removed(终态行不在 by_key,绝不触碰)。
# [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA
# 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message,
# 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas
# 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。
# 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实
# 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key,
# 绝不触碰。
for key, row in by_key.items():
if key in incoming_keys:
continue
# [版本戳] 消失标记行同样换戳到最新文件 sha(保留原 sheet/row_no 行定位,
# 只更新版本号与 sha):否则行版本戳停在旧文件,align 判据 row_shas 永不
# 收敛为 {latest_sha},每次兜底都会空转重解析。
row.raw_lines_json = [
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
for line in (row.raw_lines_json or [])
]
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
row.result_code = RESULT_FILE_REMOVED
row.result_message = "receipt row removed from latest file"
row.updated_at = now
counters["removed"] += 1
counters["absent_kept"] += 1
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
db.session.flush()
@@ -229,10 +251,18 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
after={
"file_sha256": outcome.file_sha256,
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
"reset_pending": outcome.reset_pending, "removed": outcome.removed,
"reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept,
"skipped": outcome.skipped,
},
))
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。查询口径与
# source_file_status 一致(_latest_usable_report_file);只 flush 不 commit,
# 提交归调用方(桥自行 commit / 匹配随主事务)。无可用 ORM 文件(Fake
# 仓库测试场景/文件已清理)时为 no-op。
report = _latest_usable_report_file(source_code)
if report is not None and report.parse_failed_at is not None:
clear_receipt_parse_failure(report=report)
return outcome
@@ -296,13 +326,16 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。
Args:
source_code: 来源实例编码(收料单元行上的 source_code)。
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
now: 新鲜度基准(显式续 updated_at)。
Returns:
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志)。
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志;
schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。
"""
from flask import current_app
@@ -315,9 +348,9 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
db.session.commit()
if outcome is not None:
current_app.logger.info(
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s removed=%s skipped=%s",
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s absent=%s skipped=%s",
source_code, outcome.inserted, outcome.refreshed,
outcome.reset_pending, outcome.removed, outcome.skipped)
outcome.reset_pending, outcome.absent_kept, outcome.skipped)
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
@@ -325,6 +358,30 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
current_app.logger.warning(
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
# [解析失败分层 2026-09-29] rollback 之后再写标记,避免脏会话污染写路径;
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
# 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后
# 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败
# 事实),桥隔离语义保持,仍返回 False。
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
# B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
report = _latest_usable_report_file(source_code)
if report is not None:
record_receipt_parse_failure(
report=report,
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
)
db.session.commit()
except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志,仍返回 False
current_app.logger.warning(
"TRANSFER_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc)
return False
@@ -634,6 +634,9 @@ def _recheck_stock_for_document(
material_no=item.material_no,
warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no),
)
# [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的
# external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。
item.inventory_checked_at = datetime.utcnow()
if row is None:
# 查无账面:原位刷新最新事实(账面按 0 留痕)并移出本单。
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
@@ -1248,7 +1251,8 @@ def get_run(run_no: str) -> dict[str, Any]:
"""按 run_no 恢复 Run 结果(result 单号聚合/异常 + orders 调拨单清单投影)。
orders 为 D9 融合卡数据源(调拨单清单=进度=结果),结构与行集口径见
serialize_run_orders;result.exceptions 既有口径不变。
serialize_run_orders;result.exceptions 仅收未建单阻断行(2026-09-29 收窄,
已建单失败/未知行的原因与动作由 orders 卡片承载,不再重复进异常区)。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
@@ -1285,12 +1289,22 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
# T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。
unit=str(item.unit or ""),
))
if result not in {"success", "duplicate_success"}:
# [2026-09-29 口径收窄] exceptions 仅收「未落入任何调拨单」的阻断行
# (如分组单冲突 group_order_unresolved):已建单的失败/未知行由 orders
# 卡片展示行级原因与动作;关闭单脱离回 ready 的行(result=executable)
# 回到待执行池,同样不算异常。Excel 异常下载(excel_export)仍走全量
# 行集,审计口径不受本投影收窄影响。
if (
item.document_id is None
and result not in {"success", "duplicate_success", RESULT_EXECUTABLE}
):
exceptions.append(TransferExceptionDTO(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
reason=result,
# 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。
message=str(item.result_message or "").strip(),
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
))
return RunResultDTO(
@@ -1333,6 +1347,8 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
"invoice_no": exc.invoice_no,
"material_no": exc.material_no,
"reason": exc.reason,
# 行级人话原因(2026-09-29):前端优先展示,状态码标签兜底。
"message": exc.message,
"facts": exc.facts,
}
for exc in result.exceptions
@@ -1347,7 +1363,9 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
(D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。
核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢),
created_at/id 升序稳定排序;[STEP 2] 每单行集取自单挂接行(document_id →
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 →
拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现
日期乱序);[STEP 2] 每单行集取自单挂接行(document_id →
items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与
_build_order_lines 同键同序)聚合:数量 Decimal 相加取 6 位小数字符串
(D14 快照口径),unit/material_name 取组内首个非空原值。
@@ -1358,16 +1376,24 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
Returns:
orders 数组(计划 Task 11 JSON 规格逐键 + T13-3 控制器裁决扩充):
[{doc_no, receipt_date, from_warehouse, to_warehouse, status,
erp_document_no, error_message, lines: [{material_no, material_name,
lot_no, quantity(6 位小数字符串), unit, reason}]}]。
erp_document_no, error_message, lines: [{invoice_no, material_no,
material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。
行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决):
键恒出现——失败/未知行 = 组内首个非空行级 result_message,成功行/无原因为
None(前端按「reason ?? 单 error_message」展示);ERP 写入行(
_build_order_lines)不携带该键,投影层专属。
"""
# [2026-09-29 排序对齐] 仅投影层展示序,建单/执行顺序(组键序)不变。
docs = (
TransferDocument.query.filter_by(run_id=run.id)
.order_by(TransferDocument.created_at.asc(), TransferDocument.id.asc())
.order_by(
TransferDocument.receipt_date.asc(),
TransferDocument.source_code.asc(),
TransferDocument.from_warehouse.asc(),
TransferDocument.to_warehouse.asc(),
TransferDocument.created_at.asc(),
TransferDocument.id.asc(),
)
.all()
)
# [Task 17 重构] 行聚合与 reason 契约统一收敛到 serializers.serialize_order
@@ -1,6 +1,6 @@
"""在途调拨匹配服务。
用途:编排「证据兜底对齐 → 圈行 → D+1 成熟过滤 → 路由分组批量查 外部系统 库存 →
用途:编排「证据兜底对齐 → 圈行 → T+lag 成熟过滤(默认 T+2)→ 路由分组批量查 外部系统 库存 →
严格数量比对落位 → 匹配快照与 Hash」,并支持匹配进度恢复(restore)。
依赖:evidence_sync(STEP 0 兜底对齐)/ file_preparation(缺文件 RPA 分支)/
source_file_status / capability_client / date_policy / quantity / contracts /
@@ -10,13 +10,18 @@
匹配只读 DB 行并写库存侧字段(status/result_code/result_message/
external_quantity/from_warehouse/to_warehouse/unit/updated_at),
raw_lines 版本戳归 evidence_sync 所有,匹配不碰。来源实例独立处理,
任一来源失败不阻断其他来源;当天收料不查询 外部系统;匹配 Hash 由冻结
任一来源失败不阻断其他来源;【失败分层 2026-09-29】路由不可解析只落
行级 blocked_route_not_resolved(来源保持 file_ready 不整源抬升),
align 的 schema 类解析失败把失败事实落到来源可用文件(parse_failed
三列,record_receipt_parse_failure),投影转 parse_failed 阻止下游当
ready 使用;当天收料不查询 外部系统;匹配 Hash 由冻结
快照复算;create_matching 只落 Run + SourceJob + Matching 留痕(行落位
已由 run_matching 完成,行归属 matching_id 保持首次创建值不迁移);
restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行;
restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合,
blocked_file_removed 行不进明细与常规 counts(只进 invalid_count);
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合;
历史残留 blocked_file_removed(2026-09-28 起不再新产生)仅过滤进
invalid_count,不进明细与常规 counts;
行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的
stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列):
命中库存但 ERP 未给单位 → 行级 blocked_missing_unit(拨出/拨入仓库
@@ -35,10 +40,11 @@ from sqlalchemy import func, false, or_
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
from app.models import ShippingReceiptReportFile, TransferInvoiceItem, TransferMatching, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import canonical_hash
from app.services.in_transit_transfer.contracts import (
TRANSFER_FILE_SCHEMA_INVALID,
MatchingCountsDTO,
MatchingItemDTO,
MatchingSummaryDTO,
@@ -60,7 +66,11 @@ from app.services.in_transit_transfer.file_preparation import (
)
from app.services.in_transit_transfer.movement_contract import external_lot_no
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
from app.services.in_transit_transfer.source_file_status import (
record_receipt_parse_failure,
resolve_source_file_status,
)
from app.services.in_transit_transfer.strategy import (
TransferStrategyPolicy,
default_strategy,
@@ -83,14 +93,15 @@ RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
# 文件新版本缺失该行(上一版本可执行、最新文件中消失)。
# 历史残留结果码(2026-09-28 前按"文件新版本缺失该行"自动标记;存续语义上线后不再新产生,仅作历史数据防御识别)。
RESULT_FILE_REMOVED = "blocked_file_removed"
# 交易单位缺失:ERP 库存行未返回单位(stock_unit 空,img09 契约恒非空——出现即
# ERP 侧数据异常):行级数据质量阻断。行在此前已完成路由解析,拨出/拨入仓库
# 已落列(可解释、可重查);blocked_ 前缀计入 blocked_count(既有 blocked_* 契约)。
RESULT_MISSING_UNIT = "blocked_missing_unit"
# 路由不可解析(2026-09-25 行级化):行落 blocked 可解释、可重查(路由配置修复后
# 重跑匹配/重查即恢复);同时来源级 stage 仍标 failed(fail-closed 语义保留)。
# 路由不可解析(2026-09-25 行级化;【2026-09-29 失败分层】取消来源级整源抬升):
# 行落 blocked 可解释、可重查(路由配置修复后重跑匹配/重查即恢复);来源级
# stage 保持 file_ready(有可用文件时),失败事实只落在行上。
RESULT_ROUTE_NOT_RESOLVED = "blocked_route_not_resolved"
# 匹配不触碰的行终态集合(与 evidence_sync._TERMINAL_ITEM_STATUSES 同口径):
@@ -176,6 +187,36 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun
return "success"
def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None:
"""返回某来源当前「可用」(当天抓取且未清理未过期)的收料归档文件,最新优先。
【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用
文件上(parse_failed 三列)、或同步成功后清除其标记时调用——查询口径与
source_file_status.resolve_source_file_status 的可用文件判定一致
(receipt_file_gate.usable_receipt_file_condition),防止两处口径漂移。
核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run
关联 ShippingReceiptRpaUnitRun.source_code)+ 可用门禁过滤;[STEP 2] 按
created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(收料执行单元行上的 source_code)。
Returns:
最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/
已清理)返回 None。
"""
return (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_receipt_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
def run_matching(
*,
source_codes: list[str],
@@ -192,7 +233,10 @@ def run_matching(
【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(收料回调桥,
主链路)或 STEP 0 兜底对齐(备)写入 DB;本函数只做「成熟过滤 → 路由分组
批量查库存 → 数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取
并按准备结果标来源阶段。落库写入不在此 commit(随调用方事务:create_matching
并按准备结果标来源阶段。【失败分层 2026-09-29】路由不可解析只落行级
blocked_route_not_resolved(来源有可用文件时 stage 保持 file_ready,不再整源
抬升 failed);align 的 schema 类解析失败额外把失败事实落到来源可用文件
(parse_failed 三列)。落库写入不在此 commit(随调用方事务:create_matching
末尾统一提交 / 异步 Job handler 回写后提交)。
Args:
@@ -212,7 +256,7 @@ def run_matching(
raise ValidationError("source_codes is required")
resolved_transfer_type = normalize_transfer_type(transfer_type)
ensure_transfer_type_supported(resolved_transfer_type)
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
# [日期范围] 可选收料日期过滤;卡控:截止不得超出成熟规则(业务日期-lag,默认 T-2),起始不得晚于截止。
range_from = parse_date(receipt_date_from) if receipt_date_from else None
range_to = parse_date(receipt_date_to) if receipt_date_to else None
if range_from and range_to and range_from > range_to:
@@ -221,7 +265,7 @@ def run_matching(
)
if range_to and range_to > eligible_receipt_date_to(business_date):
raise ValidationError(
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
"receipt date range end exceeds receipt maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
now = datetime.utcnow()
@@ -250,6 +294,19 @@ def run_matching(
for source_code in source_codes:
if source_code in align_errors:
error_code, error_message = align_errors[source_code]
# [解析失败分层 2026-09-29] 仅 schema 类解析失败把失败事实落到该来源
# 当前可用文件(parse_failed 三列,只 flush;随 create_matching 主事务
# 统一提交)——来源状态投影随之转 parse_failed,阻止下游把坏文件当
# ready 使用。TRANSFER.SOURCE_MATCH_ERROR 是通用匹配层错误(网络/依赖
# 异常等),不代表文件解析失败,不落文件标记。
if error_code == TRANSFER_FILE_SCHEMA_INVALID:
report = _latest_usable_report_file(source_code)
if report is not None:
record_receipt_parse_failure(
report=report,
error_code=error_code,
error_message=error_message[:2000],
)
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=error_code, error_message=error_message,
@@ -299,25 +356,15 @@ def run_matching(
))
pipeline_codes.append(source_code)
items, pending_stock_check_count, route_failed_sources = _matching_rows(
# [失败分层 2026-09-29] _matching_rows 不再回传路由失败来源集合:路由不可
# 解析只落行级 blocked_route_not_resolved(行可解释、可重查),来源级 stage
# 保持 file_ready(有可用文件时),不再整源抬升 failed——顶栏匹配状态由行
# blocked_count 呈现,来源错误码不再被路由问题污染。
items, pending_stock_check_count = _matching_rows(
source_codes=pipeline_codes, business_date=business_date, deps=deps,
receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to,
file_snapshot=file_snapshot, now=now,
)
# [来源级 fail-closed] 路由不可解析的来源整源标 failed(行级已落
# blocked_route_not_resolved,二者同源不同层:行可解释可重查,来源状态
# 提示配置缺漏需人工处理)。
for failed_code in route_failed_sources:
sources = [
SourceProgressDTO(
source_code=stage.source_code, stage="failed",
file_no=stage.file_no, file_version=stage.file_version,
checksum=stage.checksum,
error_code=ROUTE_NOT_RESOLVED_CODE,
error_message=f"route not resolved for source {stage.source_code}",
) if stage.source_code == failed_code else stage
for stage in sources
]
# [失效行计数] 同口径独立计数:blocked_file_removed 行不进明细与常规 counts,
# 只以 invalid_count 透出(范围过滤与 _matching_rows 一致)。
@@ -401,13 +448,15 @@ def _matching_rows(
receipt_date_to: str | None,
file_snapshot: dict[str, Any],
now: datetime,
) -> tuple[list[MatchingItemDTO], int, set[str]]:
) -> tuple[list[MatchingItemDTO], int]:
"""对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。
【2026-09-25】替代旧 _matching_invoices(按文件 Invoice 内存匹配):行已在
DB(evidence_sync 落地),本函数只写库存侧字段(status/result_code/
result_message/external_quantity/from_warehouse/to_warehouse/unit/
updated_at);raw_lines 版本戳归 evidence_sync 所有,匹配不碰。
【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_resolved,
不再回传失败来源集合(run_matching 不再整源抬升 failed)。
Args:
source_codes: 本轮有可用文件的来源(无文件来源不圈行,行保持既有状态)。
@@ -417,9 +466,8 @@ def _matching_rows(
file_snapshot: {source_code: 文件留痕}(行 DTO 文件对账装饰输入)。
now: 落位时间(updated_at 新鲜度基准)。
Returns:
(items DTO 列表, pending_count, route_failed_sources)——pending_count=
落位前的待查行数(counts 桶);route_failed_sources=路由不可解析的来源
集合(run_matching 据此整源标 failed)。
(items DTO 列表, pending_count)——pending_count=落位前的待查行数
(counts 桶)。
"""
# 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
@@ -427,7 +475,7 @@ def _matching_rows(
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code.in_(source_codes),
TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES),
# 失效行(文件新版本消失)不参与匹配,也不进明细(invalid_count 单独计数)。
# 失效行(历史残留 blocked_file_removed 行防御过滤)不参与匹配,也不进明细(invalid_count 单独计数)。
or_(TransferInvoiceItem.result_code.is_(None),
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
)
@@ -435,14 +483,19 @@ def _matching_rows(
query = query.filter(TransferInvoiceItem.receipt_date >= str(receipt_date_from))
if receipt_date_to:
query = query.filter(TransferInvoiceItem.receipt_date <= str(receipt_date_to))
# [统一排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与可调拨
# 明细队列/待处理池同口径的业务稳定键(2026-09-29 统一),行不因重查/恢复跳位。
scope_rows_all = query.order_by(
TransferInvoiceItem.receipt_date.asc(), TransferInvoiceItem.id.asc(),
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
).all()
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行
# 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。
pending_count = 0
route_failed_sources: set[str] = set()
matured: list[tuple[TransferInvoiceItem, RouteMapping]] = []
output: list[MatchingItemDTO] = []
for row in scope_rows_all:
@@ -454,10 +507,10 @@ def _matching_rows(
if maturity == MATURITY_NOT_MATURED:
row.status = status_machine.TransferStatus.NOT_MATURED.value
row.result_code = RESULT_NOT_MATURED
row.result_message = "receipt not matured until next business day"
row.result_message = f"receipt not matured before {eligible_receipt_date_to(business_date).isoformat()}"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.confirm_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
if maturity == MATURITY_FUTURE:
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
@@ -465,7 +518,7 @@ def _matching_rows(
row.result_message = "future receipt date"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.confirm_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
try:
route = deps.route_resolver.resolve(
@@ -473,15 +526,16 @@ def _matching_rows(
warehouse_code=row.receipt_warehouse_code or "",
)
except RouteNotResolvedError:
# [2026-09-25 行级化] 路由不可解析:行落 blocked(可解释、可重查),
# 来源级 stage 由调用方标 failed;不炸整批(原「来源级中断」语义)。
# [2026-09-25 行级化 / 2026-09-29 失败分层] 路由不可解析:行落
# blocked(可解释、可重查);来源级 stage 保持 file_ready 不整源
# 抬升(失败事实只在行上,匹配卡顶栏由 blocked_count 呈现);
# 不炸整批(原「来源级中断」语义)。
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
row.result_code = RESULT_ROUTE_NOT_RESOLVED
row.result_message = f"route not resolved for source {row.source_code}"
row.updated_at = now
route_failed_sources.add(row.source_code)
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.confirm_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse
matured.append((row, route))
@@ -512,7 +566,7 @@ def _matching_rows(
row.result_message = "external query timeout"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.confirm_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
@@ -524,7 +578,7 @@ def _matching_rows(
row.result_message = f"external query failed: {detail}"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.confirm_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds)))
continue
for row, route in entries:
stock_row = stock.lookup_row(
@@ -538,6 +592,8 @@ def _matching_rows(
row.result_code = RESULT_INVENTORY_NOT_FOUND
row.result_message = "external inventory not found"
row.external_quantity = "0"
# [库存查得时刻] 查无记录也是一次真实取数(按 0 落痕)。
row.inventory_checked_at = now
row.unit = ""
else:
stock_unit = (stock_row.stock_unit or "").strip()
@@ -549,10 +605,12 @@ def _matching_rows(
row.result_code = RESULT_MISSING_UNIT
row.result_message = "external inventory unit is missing"
row.external_quantity = str(stock_row.quantity)
row.inventory_checked_at = now
row.unit = ""
else:
match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity)
row.external_quantity = str(stock_row.quantity)
row.inventory_checked_at = now
row.unit = stock_unit
if match == RESULT_EXECUTABLE:
row.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
@@ -564,8 +622,8 @@ def _matching_rows(
row.result_message = "strict quantity mismatch"
row.updated_at = now
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.confirm_ttl_seconds)))
return output, pending_count, route_failed_sources
int(deps.strategy.inventory_stale_ttl_seconds)))
return output, pending_count
def _generate_no(prefix: str, business_date: str) -> str:
@@ -577,9 +635,10 @@ def _generate_no(prefix: str, business_date: str) -> str:
def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
"""读取行的文件版本戳(评估该行时所用的收料文件 checksum)。
用途:消失行标记(create_matching)与文件对账(restore 展示 / execute_items
执行门禁②)据此判断"行的评估版本是否仍是最新文件版本"。
两个消费方对 None(未知版本)口径不同:
用途:文件对账(restore 展示 / execute_items 执行门禁②)据此判断
"行的评估版本是否仍是最新文件版本"。2026-09-28 起不再用于
消失行标记(blocked_file_removed 仅历史残留防御,匹配侧只过滤/
invalid_count)。两个消费方对 None(未知版本)口径不同:
- restore 展示:None → file_current=False(仅展示不可执行原因,不阻断);
- execute_items 门禁②:None 按"评估版本缺失"fail-closed 拒绝执行
(TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。
@@ -610,9 +669,10 @@ def create_matching(
【语义变更 2026-09-25】行落位已全部由 run_matching 完成(证据同步落地 +
库存比对落位),本函数只负责留痕:Run / 来源级 SourceJob / Matching 记录
(scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」
——消失行标记(blocked_file_removed)归 evidence_sync;行归属 matching_id
保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。
(scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」。
【2026-09-28】evidence_sync 对缺席行改为存续只换戳,不再新产生
blocked_file_removed(该码仅历史残留防御;匹配侧过滤/invalid_count);
行归属 matching_id 保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。
Args:
source_codes / business_date / deps: 同 run_matching。
@@ -722,14 +782,14 @@ def restore_matching(
匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与
匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行
实时聚合;blocked_file_removed 行不进明细与常规 counts(只计入
counts.invalid_count,2026-09-25);estimated_* 与 expires_at /
实时聚合;历史残留 blocked_file_removed(2026-09-28 起不再新产生)不进
明细与常规 counts(只计入 counts.invalid_count);estimated_* 与 expires_at /
matching_hash 沿用匹配记录留痕展示。
Args:
matching_id: 匹配编号(MTG-...)。
deps: 注入依赖(缺省内部取 deps.get_transfer_dependencies();restore
只读 strategy.confirm_ttl_seconds,不产生外部调用)。
只读 strategy.inventory_stale_ttl_seconds,不产生外部调用)。
now: 新鲜度判定基准时间(缺省 datetime.utcnow(),测试注入冻结时钟)。
Returns:
{"summary": {...}, "items": [...], "sources": [...]};items 每行额外装饰
@@ -742,7 +802,7 @@ def restore_matching(
from app.services.in_transit_transfer import deps as transfer_deps
deps = transfer_deps.get_transfer_dependencies()
moment = now or datetime.utcnow()
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds)
matching = db.session.query(TransferMatching).filter_by(
matching_no=str(matching_id).strip()
@@ -752,13 +812,22 @@ def restore_matching(
# [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属
# (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。
# [统一排序] 与可调拨明细队列/待处理池同口径(2026-09-29 统一),
# 同一批行在匹配卡/可调拨明细/待处理池三处视图顺序一致。
rows_all = (
scope_item_query(matching)
.order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc())
.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
)
.all()
)
# [失效行分层]【2026-09-25】blocked_file_removed 行已出清:不进明细与常规
# counts(与 _matching_rows 圈行口径一致),只计入 invalid_count。
# [失效行分层]【2026-09-28】历史残留 blocked_file_removed(存续语义上线后
# 不再新产生)防御过滤:不进明细与常规 counts(与 _matching_rows 圈行
# 口径一致),只计入 invalid_count。
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED]
@@ -874,7 +943,7 @@ def _item_dto(
item: TransferInvoiceItem,
latest: dict,
moment: datetime,
ttl_seconds: int,
inventory_stale_ttl_seconds: int,
) -> MatchingItemDTO:
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
@@ -882,13 +951,13 @@ def _item_dto(
item: 明细行。
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
moment: 新鲜度判定基准时间。
ttl_seconds: 行级 stale 展示阈值(strategy.confirm_ttl_seconds;仅驱动
stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
Returns:
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
"""
evaluated_sha = _item_evaluated_sha(item)
updated_at = item.updated_at
inventory_checked_at = item.inventory_checked_at
return MatchingItemDTO(
source_code=item.source_code,
material_no=item.material_no,
@@ -919,15 +988,19 @@ def _item_dto(
)
for line in (item.raw_lines_json or [])
),
# [行装饰] 行级新鲜度与文件对账(均纯展示,不阻断执行):
# [行装饰] 库存时效与文件对账(均纯展示,不阻断执行):
# [2026-09-25 TTL 退役] stale 仅是「库存数据已过期,请重查」展示徽标
# (原 TTL 执行门禁已删除,防错由文件版本对账 + worker 写前库存复查
# 承担):stale=距上次评估超过展示阈值(confirm_ttl_seconds);
# 承担)。[2026-09-29 时钟换源] stale/checked_at 挂 inventory_checked_at
# (库存查得时刻,仅匹配评估/重查/写前复查写入)——原 updated_at 时钟
# 被证据同步换戳每日续期,徽标对老行永不触发;stale=距库存取数超过
# 展示阈值(inventory_stale_ttl_seconds),无库存数据(NULL)不判定;
# file_current=行评估版本戳仍是该来源当前可用文件 sha
# (无版本戳或无可用文件均视为不一致 → False)。
item_id=item.id,
checked_at=updated_at.isoformat() if updated_at else None,
stale=bool(updated_at) and (moment - updated_at).total_seconds() > ttl_seconds,
checked_at=inventory_checked_at.isoformat() if inventory_checked_at else None,
stale=bool(inventory_checked_at)
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
)
@@ -950,16 +1023,18 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
from app.services.in_transit_transfer import deps as transfer_deps
deps = transfer_deps.get_transfer_dependencies()
moment = now or datetime.utcnow()
ttl_seconds = int(deps.strategy.confirm_ttl_seconds)
ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds)
# [稳定排序] 收料日期(空值最后)→ Invoice → 创建时间:与重查/恢复等操作
# 无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位。
# [稳定排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复
# 等操作无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位;
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
rows = (
TransferInvoiceItem.query.filter(
TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value,
)
.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
@@ -8,11 +8,13 @@
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
"""
from __future__ import annotations
import re
from io import BytesIO
from typing import Any, Mapping
@@ -20,6 +22,20 @@ from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
_HEADER_WS_RE = re.compile(r"\s+")
def _normalize_header_label(value: Any) -> str:
"""归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。
Args:
value: 原始表头单元格或 field_mapping 别名。
Returns:
归一化后的字符串;空输入返回空串。
"""
return _HEADER_WS_RE.sub(" ", str(value or "").strip())
class ShippingReceiptFileRepository:
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
@@ -89,9 +105,16 @@ def _extract_movement_rows(
) -> list[dict[str, Any]]:
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
核心逻辑:定位表头行 → 别名/表头归一化后建反查表 → 逐数据行映射领域字段 + 溯源。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
Args:
data: xlsx 原始字节。
field_mapping: 领域字段 → 表头别名(来自站点绑定的 movement profile)。
sheet_name: 工作表名;空则取 active。
header_row_index: 1-based 表头行;空则自动探测。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
@@ -114,14 +137,17 @@ def _extract_movement_rows(
header_idx = idx
if header_idx is None:
header_idx = find_inventory_header_row_index(raw_rows)
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
# [STEP] 别名与表头均经 _normalize_header_label,抗 SSRS 单元格内换行。
header_to_code: dict[str, list[str]] = {}
for code, alias in field_mapping.items():
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
# 反查必须是 一别名→多字段,不得互相覆盖。
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
key = _normalize_header_label(alias)
if not key:
continue
header_to_code.setdefault(key, []).append(str(code).strip())
headers = [_normalize_header_label(c) for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
@@ -136,6 +162,7 @@ def _extract_movement_rows(
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
headers / header_to_code 的键须已由 _normalize_header_label 归一化。
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
"""
@@ -5,8 +5,9 @@
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
"""
from __future__ import annotations
@@ -22,9 +23,11 @@ RouteTriggerWriter = Callable[..., str | None]
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
@@ -35,22 +38,22 @@ def _build_trigger_unit(
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
query_parameters = [
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
]
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
'query_parameters_json': query_parameters,
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'inventory_source_id': source.id,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'warehouse_id': warehouse_id,
'warehouse_id': None,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
@@ -60,13 +63,31 @@ def _build_trigger_unit(
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'query_parameters_json': list(query_parameters),
'config_snapshot': snapshot,
'business_date': business_date,
'reason': reason,
}
def list_receipt_capable_source_codes() -> list[str]:
"""列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能
来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
rows = db.session.query(ShippingInventorySource.source_code).join(
ShippingReceiptReportConfig,
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
return [str(code) for (code,) in rows]
def trigger_receipt_rpa(
*,
source_code: str,
@@ -2,8 +2,9 @@
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新匹配并创建新 Attempt;
result_unknown / manually_closed / success 不自动写入。
依赖:models、retry_service._recheck_item、TransferDeps。
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
依赖:models、retry_service._recheck_items_batch、TransferDeps。
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变;
库存查询与人工重查共用按组织批量核心(一组一次外部调用,2026-09-29)。
"""
from __future__ import annotations
@@ -14,7 +15,7 @@ from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.matching_service import TransferDeps
from app.services.in_transit_transfer.retry_service import _recheck_item
from app.services.in_transit_transfer.retry_service import _recheck_items_batch
@dataclass
@@ -45,6 +46,7 @@ def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOut
status_machine.TransferStatus.MANUALLY_CLOSED.value,
]),
).all()
eligible: list[TransferInvoiceItem] = []
for item in items:
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
# 只读隔离:不查询、不写入、不创建 Attempt。
@@ -54,13 +56,19 @@ def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOut
# 永久排除。
outcome.skipped_manually_closed += 1
continue
before_attempt = item.attempt_no
new_status = _recheck_item(item, deps=deps, request_id=None)
if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
outcome.recovered_count += 1
eligible.append(item)
# [按组织批量查询] 恢复与人工重查共用批量核心:每组织一次外部调用,行级
# Attempt/审计/新鲜度语义与人工重查完全一致;路由解析失败行未建 Attempt、
# 保持阻断原状(计入 still_blocked)。
statuses, _row_errors = _recheck_items_batch(eligible, deps=deps, request_id=None)
for item in eligible:
if item.id in statuses:
outcome.attempts_created += 1
if statuses[item.id] == status_machine.TransferStatus.READY_TO_EXECUTE.value:
outcome.recovered_count += 1
else:
outcome.still_blocked_count += 1
else:
outcome.still_blocked_count += 1
if item.attempt_no > before_attempt:
outcome.attempts_created += 1
db.session.commit()
return outcome
@@ -7,9 +7,14 @@
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经
_recheck_items_batch——路由解析按 external_org 分组,一组一次
capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt /
审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用,
禁止回退逐行单查(N 行 N 次调用会打崩外部系统);
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
单行入口由 retry_item 的 result_code 兜底拒绝(拒绝逻辑单点闭环,消失证据
不可用旧库存翻回可执行);
单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失
证据不可用旧库存翻回可执行);
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
"""
@@ -36,6 +41,7 @@ from app.services.in_transit_transfer.matching_service import (
RESULT_EXECUTABLE,
RESULT_FILE_REMOVED,
RESULT_MISSING_UNIT,
RouteMapping,
TransferDeps,
scope_item_query,
)
@@ -56,86 +62,98 @@ _RETRYABLE_STATUSES = {
logger = logging.getLogger(__name__)
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
"""单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。
Args:
item_id: TransferInvoiceItem.id。
Returns:
重检后的 item 状态。
通过门禁的行(本函数不触碰任何字段)。
Raises:
NotFoundError: item 不存在。
ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行
不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失,
重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 /
等重新同步恢复该行)。
"""
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
# [口径] 重查按当前路由配置发查询,行上仓库字段同步刷新为本次解析值——
# 查询与后续执行写路径必须用同一仓库值:行上旧值可能来自更早配置(路由
# 已漂移),也可能为空(如 blocked_missing_unit 行在路由解析前被阻断)。
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
item.from_warehouse = route.from_warehouse
item.to_warehouse = route.to_warehouse
operation_id = f"op-{uuid.uuid4().hex[:12]}"
receipt_qty = Decimal(item.receipt_quantity)
item.attempt_no += 1
before_status = item.status
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
status="running", operation_id=operation_id,
request_snapshot_json={
"invoice_no": item.invoice_no, "external_org": route.external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status not in _RETRYABLE_STATUSES:
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
# [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope
# 谓词排除失效行,但按 id 直取(requery_items_by_ids)与单行入口绕过该谓词
# ——拒绝逻辑只落在此单点,三条入口同时闭环。
if item.result_code == RESULT_FILE_REMOVED:
raise ValidationError(
"removed rows cannot be requeried; close manually or wait for re-sync",
code="TRANSFER.RETRY_NOT_ALLOWED",
)
return item
def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt,
before_status: str, detail: str,
operation_id: str, request_id: str | None) -> str:
"""行级降级收口:外部查询故障 → blocked_external_query_failed + 原因。
与单行历史语义一致:网关/绑定故障不向调用方抛基础设施异常(避免全局错误
弹窗);本次失败也是一次真实评估,行级 TTL 照常续期。
Args:
item: 重查行(Attempt 已创建并 flush)。
attempt: 该行本次 external_query Attempt(running 态)。
before_status: 重查前状态(审计 before)。
detail: 外部异常摘要(落 result_message 与审计)。
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
Returns:
降级后的行状态。
"""
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
item.result_message = f"external query failed: {detail}"
attempt.status = "failed"
attempt.completed_at = datetime.utcnow()
# [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
item.updated_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
))
db.session.flush()
# [降级] 与 matching 逐单语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
try:
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=route.external_org,
targets=[StockTarget(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
)],
)
stock_row = stock.lookup_row(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
)
stock_qty = stock_row.quantity if stock_row is not None else None
except Exception as exc: # noqa: BLE001
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
logger.warning(
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
item.invoice_no, item.id, item.attempt_no, detail,
)
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
item.result_message = f"external query failed: {detail}"
attempt.status = "failed"
attempt.completed_at = datetime.utcnow()
# [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
item.updated_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
))
db.session.flush()
return item.status
return item.status
def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt,
before_status: str, receipt_qty: Decimal, stock_row,
operation_id: str, request_id: str | None) -> str:
"""行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。
Args:
item: 重查行(Attempt 已创建并 flush)。
attempt: 该行本次 external_query Attempt(running 态)。
before_status: 重查前状态(审计 before)。
receipt_qty: 行收料数量(严格相等判定的基准)。
stock_row: 批量查询结果中该行的账面行(StockRow);查无记录为 None。
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
Returns:
重查后的行状态。
"""
stock_qty = stock_row.quantity if stock_row is not None else None
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
@@ -162,8 +180,12 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
item.unit = (stock_row.stock_unit or "").strip()
attempt.status = "success"
attempt.completed_at = datetime.utcnow()
# [行级 TTL 续期] 重查即续新鲜度:状态落定后显式刷新 updated_at(执行门禁
# TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。
# [库存查得时刻] 重查是真实取数:三个分支(查无按 0/单位缺失/正常)落定的
# external_quantity 都以本次取数为准,同步刷新其取数时间戳——stale 徽标
# 判定时钟(2026-09-29 起挂本字段,不再依赖 updated_at,见 _item_dto)。
item.inventory_checked_at = datetime.utcnow()
# [行级新鲜度续期] 重查显式刷新 updated_at(行新鲜度口径),不依赖
# attempt_no 变更间接触发 onupdate 的隐式行为。
item.updated_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
@@ -184,9 +206,133 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
return item.status
def _recheck_items_batch(
items: list[TransferInvoiceItem], *, deps: TransferDeps, request_id: str | None = None,
) -> tuple[dict[int, str], dict[int, Exception]]:
"""按组织批量重查核心:一组(external_org)一次 capabilities.query_stock。
【AI 触发时机】:全部重查/恢复/单据重试入口(retry_item / requery_items /
requery_items_by_ids / retry_document / run_daily_recovery)圈定行集并过完
资格门禁后统一调用;本函数不再校验状态与 file_removed。
【为什么按组织批量】重查面向整批行(可调拨清单「重查选中」可达数百行),
逐行单查会把 N 行放大成 N 次外部调用,外部系统不可承受;外部访问按
(料号, 仓库, 批号) 元组天然支持批量,执行链写前复查已按组织批量——本函数
与其同形态。行级粒度保留:评估/Attempt/审计/新鲜度续期仍逐行落库,
单行路由解析失败只跳过该行。
Args:
items: 已过资格门禁的可重查行。
deps: 注入依赖(capabilities = 外部系统网关客户端)。
request_id: 审计上下文。
Returns:
(statuses, row_errors):
statuses = {item_id: 重查后状态}(进入查询的行,含降级为 blocked 的行);
row_errors = {item_id: 原始异常}(路由/数量前置解析失败行:未发起查询、
行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛
保持历史 fail-closed 行为)。
"""
# [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位
# 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须
# 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如
# blocked_missing_unit 行在路由解析前被阻断)。
resolved: list[tuple[TransferInvoiceItem, RouteMapping, Decimal]] = []
row_errors: dict[int, Exception] = {}
for item in items:
try:
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
receipt_qty = Decimal(item.receipt_quantity)
except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行
row_errors[item.id] = exc
logger.warning(
"transfer recheck row skipped (pre-resolve failed): invoice=%s item=%s error=%s",
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
)
continue
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
item.from_warehouse = route.from_warehouse
item.to_warehouse = route.to_warehouse
resolved.append((item, route, receipt_qty))
# [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享
# 一次批量查询,N 行 = 每组织 1 次外部调用。
groups: dict[str, list[tuple[TransferInvoiceItem, RouteMapping, Decimal]]] = {}
for entry in resolved:
groups.setdefault(str(entry[1].external_org or "").strip(), []).append(entry)
statuses: dict[int, str] = {}
# [STEP 3] 每组织:行级 Attempt(running)→ 一次批量查询 → 行级收口(评估或
# 降级)→ 组粒度提交(一组落库即一组持久,后续组故障不回滚已落组)。组内
# Attempt 共享查询 operation_id,与 IntegrationCall 调用审计可互查。
for external_org, entries in groups.items():
operation_id = f"op-{uuid.uuid4().hex[:12]}"
attempts: dict[int, TransferAttempt] = {}
before_statuses: dict[int, str] = {}
for item, route, receipt_qty in entries:
item.attempt_no += 1
before_statuses[item.id] = item.status
attempts[item.id] = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
status="running", operation_id=operation_id,
request_snapshot_json={
"invoice_no": item.invoice_no, "external_org": external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempts[item.id])
db.session.flush()
try:
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=external_org,
targets=[StockTarget(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
) for item, route, _receipt_qty in entries],
)
except Exception as exc: # noqa: BLE001
# [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为
# blocked_external_query_failed + 原因(逐行查询时同样会全部失败,
# 语义一致只是不再慢速放大),不中断批次、不向调用方抛异常。
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
logger.warning(
"transfer recheck org query failed (degrade rows): org=%s rows=%s error=%s",
external_org, len(entries), detail,
)
for item, route, receipt_qty in entries:
statuses[item.id] = _degrade_recheck_row(
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
detail=detail, operation_id=operation_id, request_id=request_id,
)
db.session.commit()
continue
for item, route, receipt_qty in entries:
# [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。
stock_row = stock.lookup_row(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
)
statuses[item.id] = _apply_recheck_outcome(
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
receipt_qty=receipt_qty, stock_row=stock_row,
operation_id=operation_id, request_id=request_id,
)
db.session.commit()
return statuses, row_errors
def _row_error_text(exc: Exception) -> str:
"""行级异常 → 用户可见错误文本(AppError 取 message,其余取 str/类名)。"""
return str(getattr(exc, "message", "") or "").strip() or str(exc).strip() or exc.__class__.__name__
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工重试异常项。
"""人工重试异常项(单行入口:资格门禁 + 按组织批量核心的单行特例)。
Args:
item_id: TransferInvoiceItem.id。
@@ -197,37 +343,20 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
{"item_id": ..., "status": ..., "attempt_no": ...}。
Raises:
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读 /
file_removed 行不可重查(消失证据不可恢复:证据行的源单已从最新
收料文件中消失,重查只会用外部系统旧库存把行翻回可执行,唯一出口
= 人工关闭 / 等重新同步恢复)。
file_removed 行不可重查(资格门禁,见 _gate_retryable_item)。
NotFoundError: item 不存在。
Exception: 路由/数量前置解析失败原样上抛(fail-closed,保持单行历史行为)。
"""
kind_value = str(kind or "").strip()
if kind_value == RETRY_KIND_RPA_REFETCH:
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
if kind_value != RETRY_KIND_EXTERNAL_RECHECK:
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status not in _RETRYABLE_STATUSES:
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
# [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope
# 谓词排除失效行,但按 id 直取(requery_items_by_ids 循环)与单行入口都绕过
# 该谓词——拒绝逻辑只落在此单点,三条入口同时闭环。为什么拒绝:消失证据
# 不可恢复,重查会用外部系统旧库存把行翻回可执行(虚假放行),唯一出口
# = 人工关闭 / 等重新同步恢复该行。
if item.result_code == RESULT_FILE_REMOVED:
raise ValidationError(
"removed rows cannot be requeried; close manually or wait for re-sync",
code="TRANSFER.RETRY_NOT_ALLOWED",
)
status = _recheck_item(item, deps=deps, request_id=request_id)
db.session.commit()
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
item = _gate_retryable_item(item_id)
statuses, row_errors = _recheck_items_batch([item], deps=deps, request_id=request_id)
if item.id in row_errors:
raise row_errors[item.id]
return {"item_id": item.id, "status": statuses[item.id], "attempt_no": item.attempt_no}
def requery_items_by_ids(
@@ -237,8 +366,8 @@ def requery_items_by_ids(
"""按明细 id 批量重查外部系统库存(待处理池批量「重查」入口)。
与 requery_items(匹配号定位)的差异:待处理池的行可能分散在多份历史
匹配,只能按 id 直取。单行失败(状态不允许/不存在/异常)不影响其余行,
隔离语义与 requery_items 一致。
匹配,只能按 id 直取。单行门禁失败(状态不允许/不存在/file_removed)不
影响其余行;库存查询按组织批量(每组织一次外部调用)。
Args:
item_ids: TransferInvoiceItem.id 列表(非空)。
@@ -263,29 +392,28 @@ def requery_items_by_ids(
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
align_scope_rows(source_codes=affected_sources, deps=deps,
business_date=str(business_date_now()), now=datetime.utcnow())
results: list[dict] = []
results_by_id: dict[int, dict] = {}
eligible: list[TransferInvoiceItem] = []
for item_id in ids:
try:
retry_item(item_id=item_id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
actor_id=actor_id, request_id=request_id)
item = db.session.get(TransferInvoiceItem, item_id)
results.append({"item_id": item_id, "invoice_no": item.invoice_no if item else "",
"ok": True, "status": item.status if item else ""})
eligible.append(_gate_retryable_item(item_id))
except (ValidationError, NotFoundError) as exc:
results.append({"item_id": item_id, "invoice_no": "", "ok": False, "error": exc.message})
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批
logger.warning(
"transfer batch requery row crashed (skipped): item=%s error=%s",
item_id, str(exc).strip() or exc.__class__.__name__,
)
results.append({"item_id": item_id, "invoice_no": "", "ok": False,
"error": str(exc).strip() or exc.__class__.__name__})
return {"total": len(ids), "results": results}
results_by_id[item_id] = {"item_id": item_id, "invoice_no": "",
"ok": False, "error": exc.message}
statuses, row_errors = _recheck_items_batch(eligible, deps=deps, request_id=request_id)
for item in eligible:
if item.id in row_errors:
results_by_id[item.id] = {"item_id": item.id, "invoice_no": item.invoice_no,
"ok": False, "error": _row_error_text(row_errors[item.id])}
else:
results_by_id[item.id] = {"item_id": item.id, "invoice_no": item.invoice_no,
"ok": True, "status": statuses[item.id]}
return {"total": len(ids), "results": [results_by_id[item_id] for item_id in ids]}
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行逐单重查并刷新。
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行,按组织批量查询并刷新。
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
@@ -299,7 +427,7 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
actor_id / request_id: 审计上下文。
Returns:
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
单行门禁/路由失败不影响其余行(来源级隔离同款语义)。
"""
from app.models import TransferMatching
@@ -333,25 +461,17 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
items = query.order_by(TransferInvoiceItem.id).all()
# [按组织批量查询] 圈定行集一次性交批量核心:每组织一次外部调用;
# 行级结果按输入行序(id 序)回报。
statuses, row_errors = _recheck_items_batch(items, deps=deps, request_id=request_id)
results: list[dict] = []
for item in items:
try:
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
actor_id=actor_id, request_id=request_id)
if item.id in row_errors:
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": True, "status": item.status})
except (ValidationError, NotFoundError) as exc:
"ok": False, "error": _row_error_text(row_errors[item.id])})
else:
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False, "error": exc.message})
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
logger.warning(
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
)
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False,
"error": str(exc).strip() or exc.__class__.__name__})
"ok": True, "status": statuses[item.id]})
return {"matching_no": matching_no, "total": len(items), "results": results}
@@ -359,7 +479,7 @@ def retry_document(
*, doc_no: str, deps: TransferDeps,
actor_id: int | None = None, request_id: str | None = None,
) -> dict:
"""调拨单级重试(失败单一键恢复,主路径):圈单内行 → 逐行重查 → 全 ready 自动重跑。
"""调拨单级重试(失败单一键恢复,主路径):圈单内行 → 按组织批量重查 → 全 ready 自动重跑。
【AI 触发时机】:用户在失败调拨单上点「重试」——替代旧的单据级重查(其按
可执行池关联行,对 blocked 行必报"未能关联");本函数按单圈行(单是行权威
@@ -367,10 +487,11 @@ def retry_document(
核心逻辑:[STEP 1] 状态门禁——仅 failed 族(business/technical_failed)可重试;
result_unknown 唯一出口=重新触发(D11),pending/executing 在飞拒绝,终态拒绝。
[STEP 2] 单内 blocked 行逐行重查(复用 retry_item:单行隔离、file_removed 拒绝、
每行落 Attempt);ready 行原样保留。 [STEP 3] 全部行 ready → 自动建新 Run 重跑
(prepare_execution:门禁②文件对账 + D7①分支②复用原单号,写前复查兜底);
任一行仍阻断 → 不重跑(单是原子单位,缺行不跑),阻断明细原样返回由池子兜底。
[STEP 2] 单内 blocked 行批量重查(按组织一次外部查询;file_removed 行不可
重查、保持阻断——消失证据不可恢复,拒绝语义同资格门禁);ready 行原样保留。
[STEP 3] 全部行 ready → 自动建新 Run 重跑(prepare_execution:门禁②文件对账
+ D7①分支②复用原单号,写前复查兜底);任一行仍阻断 → 不重跑(单是原子单位,
缺行不跑),阻断明细原样返回由池子兜底。
Args:
doc_no: TransferDocument.doc_no。
@@ -404,16 +525,15 @@ def retry_document(
"document has no attached items", code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
)
# [STEP 2] 单内 blocked 行逐行重查(行级隔离,单行失败不炸整单)。
for item in items:
if item.status != status_machine.TransferStatus.BLOCKED_RECOVERABLE.value:
continue
try:
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
actor_id=actor_id, request_id=request_id)
except (ValidationError, NotFoundError):
# file_removed 等拒绝语义:行保持阻断,原因随结果返回。
continue
# [STEP 2] 单内 blocked 行批量重查(按组织一次外部查询,行级隔离语义不变;
# file_removed 行直接排除——消失证据不可恢复,保持阻断原样)。
eligible = [
item for item in items
if item.status == status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
and item.result_code != RESULT_FILE_REMOVED
]
if eligible:
_recheck_items_batch(eligible, deps=deps, request_id=request_id)
for item in items:
db.session.expire(item)
@@ -124,7 +124,8 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
核心逻辑:[STEP 1] 行集按 ERP 行粒度(物料+批号+拨出/拨入库位)聚合,数量
Decimal 相加取 6 位小数字符串(D14 快照口径),unit/material_name 取组内首个
非空原值;[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内
非空原值,行级 invoice_no 随 ERP 写入行同款口径透传(2026-09-29 契约扩充);
[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内
首个非空行级 result_message,成功行/无原因为 None(前端按
「reason ?? 单 error_message」展示)。
@@ -170,6 +171,9 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
"error_message": doc.error_message,
"lines": [
{
# 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
"invoice_no": line["invoice_no"],
"material_no": line["material_no"],
"material_name": name_by_key.get(
(line["material_no"], line["lot_no"],
@@ -217,10 +221,14 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
"invoice_no": item.invoice_no,
"material_no": item.material_no,
"material_name": item.material_name,
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
# deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。
"lot_no": item.lot_no or "",
"quantity": item.receipt_quantity,
"unit": item.unit or "",
}
for item in sorted(items, key=lambda row: row.id)
# 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同
# (组键含两者),按 invoice_no 升序、id 兜底稳定排序。
for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id))
],
}
@@ -1,17 +1,24 @@
"""在途调拨来源收料文件状态投影服务。
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
receipt_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
见 receipt_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
有进行中单元 → fetching;最新单元为失败终态 → failed;
文件仍在但已失效 → expired;否则 → none。
record_receipt_parse_failure / clear_receipt_parse_failure 维护解析失败三列
(写入与清除均只 flush 不 commit,事务归属调用方)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.in_transit_transfer.receipt_file_gate import (
expired_receipt_file_condition,
@@ -30,7 +37,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'};
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
"""
report = (
ShippingReceiptReportFile.query
@@ -43,6 +52,15 @@ def resolve_source_file_status(*, source_code: str) -> dict:
.first()
)
if report is not None:
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
if report.parse_failed_at is not None:
return {
'file_status': 'parse_failed',
'has_ready_file': False,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
}
return {
'file_status': 'ready',
'has_ready_file': True,
@@ -83,3 +101,55 @@ def resolve_source_file_status(*, source_code: str) -> dict:
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
def record_receipt_parse_failure(
*,
report: ShippingReceiptReportFile,
error_code: str,
error_message: str,
now: datetime | None = None,
) -> None:
"""标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
【AI 触发时机】收料归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
改调 clear_receipt_parse_failure。
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。
Args:
report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。
Returns:
None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
"""
report.parse_failed_at = now or datetime.utcnow()
report.parse_error_code = (error_code or '')[:64]
report.parse_error_message = (error_message or '')[:2000]
db.session.flush()
def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None:
"""清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message
三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内
投影立即可见。只 flush 不 commit,事务提交时机归调用方。
Args:
report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。
Returns:
None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
"""
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
@@ -1,8 +1,10 @@
"""在途调拨策略硬门禁。
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试;
confirm_ttl_seconds 为纯展示阈值(默认 10 分钟 stale 徽标判定窗口,
不再作为执行门禁——2026-09-25 退役)。
confirm_ttl_seconds 与 inventory_stale_ttl_seconds 均为纯展示阈值
(stale 徽标判定窗口,不再作为执行门禁——2026-09-25 退役);
2026-09-29 起 stale 时钟换源:挂 inventory_checked_at(库存查得
时刻),阈值默认 24 小时——证据同步换戳不续期该时钟。
依赖:app.core.errors.AppError、standard decimal。
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
阻止发布/执行(fail-closed)。
@@ -17,6 +19,7 @@ from app.core.errors import AppError
STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION"
DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟
DEFAULT_INVENTORY_STALE_TTL_SECONDS = 86400 # 24 小时
@dataclass(frozen=True)
@@ -30,6 +33,10 @@ class TransferStrategyPolicy:
# 不再作为执行门禁(2026-09-25 退役)——防错由文件版本对账 + worker 写前
# 库存复查承担(见 execution_service)。
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
# 纯展示阈值:stale 徽标判定窗口,时钟=inventory_checked_at(库存查得
# 时刻,仅匹配评估/重查/写前复查写入;2026-09-29 起替换原 updated_at
# 时钟——后者被证据同步换戳每日续期,徽标对老行永不触发)。
inventory_stale_ttl_seconds: int = DEFAULT_INVENTORY_STALE_TTL_SECONDS
class StrategyViolationError(AppError):
@@ -61,5 +68,6 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
def default_strategy() -> TransferStrategyPolicy:
"""返回一期默认策略(全部禁令关闭,stale 展示阈值 600 秒)。"""
"""返回一期默认策略(全部禁令关闭;stale 展示阈值:行新鲜度 600 秒 /
库存查得时刻 24 小时)。"""
return TransferStrategyPolicy()
@@ -0,0 +1,97 @@
"""在途调拨企微汇总通知的真实通道适配(notification.WeComSender 协议实现)。
用途:把自动调拨 Run 汇总经企微 textcard 发给通知人,替代排程 handler 的
sender=None 占位;通知失败只落 run.notification_status,不影响 ERP 结果。
依赖:integrations.wecom.notify.send_wecom_event_message(事件门禁+审计)、models.User。
逻辑:逐收件人解析 wecom_userid 后发送;复用 schedule_completed 事件开关(与排程
通用通知同一启停入口,不新增 WECOM_NOTIFY_EVENTS 事件名);至少一人送达即
success,无可用收件人或全部失败为 failed,由 notify_run_summary 统一落库。
"""
from __future__ import annotations
from typing import Any
from app.services.integrations.wecom.notify import send_wecom_event_message
# 复用排程完成事件开关:运维通过 WECOM_NOTIFY_EVENTS 的 schedule_completed
# 统一启停排程类通知,本发送器不引入独立事件名(避免各环境事件表漂移)。
WECOM_EVENT_TYPE = "schedule_completed"
_STATUS_LABELS = {
"success": "全部成功",
"partial_failed": "部分失败",
"failed": "失败",
"matching": "匹配中",
}
class WecomSummarySender:
"""企微汇总通知发送器(协议见 notification.WeComSender)。
Args 约定:recipients 为 HXOPS 用户 id 列表(字符串/整数均可),由排程参数
notify_user_ids(options_source=users)下发;未绑定企微的用户跳过。
excel_path 为协议占位,当前不发送附件(异常明细以管理端已执行区块为准)。
"""
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""向通知人逐一发送一条 Run 汇总 textcard。
Args:
run_no: 调拨 Run 编号(RUN-YYYYMMDD-XXXXXX)。
summary: notify_run_summary 组装的汇总(run_no/status/business_date/counts)。
recipients: 用户 id 列表。
excel_path: 协议占位;当前不发送附件。
Returns:
{"status": "success", "delivered": n} 或
{"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str};
由 notify_run_summary 写入 run.notification_* 字段。
"""
counts = summary.get("counts") if isinstance(summary.get("counts"), dict) else {}
status = str(summary.get("status") or "")
title = f"在途自动调拨 {run_no}"
content = "\n".join([
f"状态: {_STATUS_LABELS.get(status, status or '未知')}",
f"业务日期: {summary.get('business_date') or '-'}",
"文件票数: {tickets} 已匹配: {matched} 待查库存: {pending}".format(
tickets=counts.get("file_invoice_count", 0),
matched=counts.get("matched_count", 0),
pending=counts.get("pending_stock_check_count", 0),
),
"可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format(
executable=counts.get("executable_count", 0),
blocked=counts.get("blocked_count", 0),
not_matured=counts.get("not_matured_count", 0),
),
])
user_ids = [int(item) for item in (recipients or []) if str(item).strip().isdigit()]
users = []
if user_ids:
from app.models import User
users = User.query.filter(User.id.in_(user_ids)).all()
# [STEP 1] 逐收件人投递;send_wecom_event_message 内部完成事件门禁与审计落库。
delivered = 0
last_error = ""
for user in users:
if not user.wecom_userid:
continue
outcome = send_wecom_event_message(
event_type=WECOM_EVENT_TYPE, user=user, title=title, content=content,
jump_path="/workspace",
)
if outcome.get("ok"):
delivered += 1
else:
last_error = str(outcome.get("reason") or "send_failed")
if delivered:
return {"status": "success", "delivered": delivered}
return {
"status": "failed",
"error_code": "WECOM_SEND_FAILED",
"error_message": last_error or "no wecom-bound recipients",
}