feat(in-transit-transfer): 自动调拨支持收料日期范围并收归排程通用通知

- 自动调拨任务新增收料日期范围动态参数(receipt_date_from/to):缩小匹配面便于测试与排障,非法范围由匹配层校验拒绝
- 排程动态参数表单支持占位文案 key 与空值归 null,日期筛选直达任务配置
- 执行结果通知统一走排程「启用通知」通用企微通知,任务不再自建领域通知
- 门禁契约澄清 retry_inventory_matching 语义:复用已抓库存重匹配不重抓;STP 多候选无匹配时阶段能力禁用、不隐式触发 RPA
- 同步匹配/自动调拨/排程测试、四语言文案与文档
This commit is contained in:
hugo committed 2026-10-12 21:25:35 +08:00
1 parent 34c3bfb254
commit a8d721e793
35 files changed
+863 -138

No files matched your search

@@ -32,6 +32,8 @@ class AutoTransferOutcome:
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
@@ -44,6 +46,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
Returns:
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
@@ -59,6 +63,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
)
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
@@ -112,17 +112,26 @@ class MatchingItemDTO:
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
unit: str = ""
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
# item_id=行主键(批量操作/待处理池回链);checked_at=行库存查得时刻(见 _item_dto);
# stale=距库存取数超过展示阈值;file_current=行评估版本戳仍是该来源当前可用文件。
item_id: int = 0
checked_at: str | None = None
stale: bool = False
file_current: bool = False
# [2026-10-12 单据数口径修正] 执行建单五元组首键:路由解析所得外部组织
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
external_org: str = ""
@dataclass(frozen=True)
class MatchingSummaryDTO:
"""匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。"""
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
"""
matching_id: str
status: str
@@ -389,6 +389,23 @@ def run_matching(
estimated_quantity = sum(
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
)
# [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组
# (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组,
# 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip()
# 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由
# 匹配评估随路由解析填齐(_matching_rows 评估分支)。原「= executable_count」
# 口径在多行同组时高估单据数,误导用户。
estimated_document_keys = {
(
item.external_org,
str(item.source_code or "").strip(),
str(item.receipt_date or "").strip(),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
for item in items
if item.result == RESULT_EXECUTABLE
}
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
@@ -433,7 +450,7 @@ def run_matching(
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_external_write_count=counts.executable_count,
estimated_external_write_count=len(estimated_document_keys),
matching_hash=matching_hash,
)
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
@@ -621,8 +638,11 @@ def _matching_rows(
row.result_code = match
row.result_message = "strict quantity mismatch"
row.updated_at = now
# 本行已完成路由解析:external_org 随行透出(执行建单五元组首键,
# 2026-10-12 单据数口径修正——预计单据数按五元组去重依赖本字段)。
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
int(deps.strategy.inventory_stale_ttl_seconds)))
int(deps.strategy.inventory_stale_ttl_seconds),
external_org=str(route.external_org or "").strip()))
return output, pending_count
@@ -944,6 +964,7 @@ def _item_dto(
latest: dict,
moment: datetime,
inventory_stale_ttl_seconds: int,
external_org: str = "",
) -> MatchingItemDTO:
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
@@ -953,8 +974,10 @@ def _item_dto(
moment: 新鲜度判定基准时间。
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数
口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。
Returns:
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。
"""
evaluated_sha = _item_evaluated_sha(item)
inventory_checked_at = item.inventory_checked_at
@@ -1002,6 +1025,7 @@ def _item_dto(
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"),
external_org=external_org,
)
@@ -81,6 +81,9 @@ def serialize_item(item) -> dict[str, Any]:
"to_quantity": str(item.to_quantity),
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
"unit": item.unit,
# [2026-10-12 单据数口径修正] 执行建单五元组首键透传:前端按勾选行
# 预估 ERP 单据数与后端同口径分组(匹配评估路径填齐,历史回放缺省 "")。
"external_org": item.external_org,
"result": item.result,
"reason": item.reason,
"raw_lines": [
@@ -344,8 +344,10 @@ def _register_headers_from_config() -> None:
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
register_inventory_rpa_excel_headers()
register_receipt_rpa_excel_headers()
def reload_config() -> dict[str, Any]:
@@ -9,16 +9,83 @@ backend/app/services/schedule/freight_receipt_rpa_finalize.py
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import ShippingReceiptRpaUnitRun
from app.services.schedule import normalize_platform_api_path
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_RECEIPT_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"connector_type",
"receipt_file_count",
"export_status",
"skip_reason",
"error_message",
]
_RECEIPT_RPA_HEADER_LABELS = {
"source_code": "收料源",
"warehouse_id": "仓库",
"connector_type": "连接器",
"receipt_file_count": "归档文件数",
"export_status": "导出状态",
"skip_reason": "跳过原因",
"error_message": "错误原因",
}
def register_receipt_rpa_excel_headers() -> None:
"""
注册货代收料 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
RECEIPT_RPA_JOB_KEY,
_RECEIPT_RPA_HEADER_ORDER,
_RECEIPT_RPA_HEADER_LABELS,
)
def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]:
"""
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致;
归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。
Args:
units: 该 run 的全部收料单元(已全部终态)。
Returns:
list[dict]: 按 unit.id 升序的明细行。
"""
rows: list[dict[str, Any]] = []
for unit in sorted(units, key=lambda item: item.id):
status = unit.status
if status == 'empty':
export_status = 'skipped'
elif status == 'cancelled':
export_status = 'failed'
else:
export_status = status
rows.append({
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id or '',
'connector_type': unit.connector_type or '',
'receipt_file_count': len(unit.files or []),
'export_status': export_status,
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
})
return rows
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
@@ -213,6 +280,44 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_receipt_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
try:
excel_data, _excel_name, excel_size = export_schedule_result_excel(
run_no=run.run_no,
summary={
'status': run.status,
'total_count': len(units),
'success_count': success_count,
'skipped_count': skipped_count,
'failed_count': failed_count,
'duration_ms': run.duration_ms,
},
details=_build_receipt_finalize_details(units),
header_order=header_order,
header_labels=header_labels,
)
except Exception as excel_exc:
excel_export_ok = False
current_app.logger.error(
'[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc,
)
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
if run.status == 'success':
run.status = 'partial_failed'
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name
excel_name = receipt_rpa_result_excel_name(run)
run.excel_file_data = excel_data
run.excel_file_name = excel_name if excel_data else None
run.excel_file_size = excel_size or 0
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
archive_summary = {
'raw_receipt_zip_available': False,
@@ -237,6 +342,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
'excel_export_status': 'ok' if excel_export_ok else 'failed',
'excel_failed': not excel_export_ok,
**archive_summary,
}
db.session.commit()
@@ -1,24 +1,27 @@
"""自动调拨排程。
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走
排程「启用通知」通用企微通知,本任务不自建领域通知。
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、
date_policy(业务日与日期解析)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造
sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed
抑制框架卡;硬失败不置标记以便框架兜底。
不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层;
空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持
静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
"""
from __future__ import annotations
from datetime import timedelta
from typing import Any
from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
from app.services.schedule.job_registry import ScheduleExecuteResult
@@ -45,41 +48,77 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
return codes
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer;
仅在返回后按结果决定是否置 domain_notification_managed——有 run_no
(成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡;
硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
"""把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。
Args:
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
business_date: 业务日期 T(YYYY-MM-DD)。
offset_days: 偏移天数(须为非负整数;None/空视为未配置)。
label: 参数中文名(写错误信息用)。
errors: 错误累积列表(非法配置写入后返回 None,由调用方快速失败)。
Returns:
'YYYY-MM-DD';未配置或非法时为 None(非法同时落错误)。
"""
if offset_days is None or offset_days == "":
return None
try:
days = int(offset_days)
except (TypeError, ValueError):
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
return None
if days < 0 or float(offset_days) != days:
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
return None
return (parse_date(business_date) - timedelta(days=days)).isoformat()
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层
ValidationError 落 errors 走硬失败路径。
Args:
task: 排程任务(job_params: source_codes/recover_history/
receipt_from_offset_days/receipt_to_offset_days)。
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
Returns:
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
"""
params = _task_params(task)
source_codes = _wanted_source_codes(task)
recover_history = bool(params.get("recover_history", True))
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
business_date = str(business_date_now())
# 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。
sender = WecomSummarySender() if recipients else None
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。
param_errors: list[str] = []
receipt_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors)
receipt_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors)
if param_errors:
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
deps = transfer_deps.get_transfer_dependencies()
outcome = run_auto_transfer(
business_date=str(business_date_now()),
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
sender=sender,
recipients=recipients,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
)
# [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日
# (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。
if recipients and (outcome.run_no or not outcome.errors):
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
if not outcome.run_no and not outcome.errors:
run.response_summary_json = {
**(run.response_summary_json or {}),
"domain_notification_managed": True,
@@ -94,7 +133,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
"notification_status": outcome.notification_status,
})
elif not outcome.errors:
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
+16 -11
View File
@@ -566,10 +566,8 @@ def _register_builtin_platform_jobs() -> None:
label="在途自动调拨",
handler=run_in_transit_transfer_schedule,
description=(
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
),
category="platform",
params_schema=(
@@ -591,16 +589,23 @@ def _register_builtin_platform_jobs() -> None:
"default": True,
},
{
"key": "notify_user_ids",
"type": "multi_select",
"label": "通知人",
"label_key": "admin.schedule.form.transferNotifyUsers",
"key": "receipt_from_offset_days",
"type": "number",
"label": "收料日期起(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateFrom",
"required": False,
"default": [],
"options_source": "users",
"help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。",
},
{
"key": "receipt_to_offset_days",
"type": "number",
"label": "收料日期止(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateTo",
"required": False,
"help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。",
},
),
defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []},
defaults={"source_codes": [], "recover_history": True},
))
@@ -110,6 +110,11 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。"""
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
@@ -478,17 +478,22 @@ def inventory_preparation_primary_action(
"""裁决库存准备 Gate 面向业务用户的主动作。
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching``
(优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。
``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching``
(复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
``retry_inventory_matching``。
边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。
因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用
(disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task),
重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。
"""
normalized_status = str(status or '').strip().lower()
normalized_reason = str(blocking_reason_code or '').strip().lower()
if normalized_status == 'waiting_external':
return 'poll_inventory_preparation'
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
# [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。
# [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力
# 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。
return 'retry_inventory_matching'
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
return 'retry_inventory_preparation'