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'
@@ -122,7 +122,8 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he
data = body["data"]
assert data["matching_id"].startswith("MTG-")
assert data["matching_hash"].startswith("sha256:")
assert data["estimated_external_write_count"] == 2
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
assert data["estimated_external_write_count"] == 1
assert body.get("request_id")
@@ -64,3 +64,29 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
assert outcome.run_no == "RUN-20260928-XYZ789"
assert outcome.run_status == "success"
assert outcome.errors == []
def test_passes_receipt_date_range_to_matching(monkeypatch):
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
captured = {}
def _fake_create(**kwargs):
captured.update(kwargs)
return _summary(0)
monkeypatch.setattr(at, "create_matching", _fake_create)
at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
)
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
assert captured["receipt_date_from"] == "2026-09-01"
assert captured["receipt_date_to"] == "2026-09-05"
at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
)
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
assert captured["receipt_date_from"] is None
assert captured["receipt_date_to"] is None
@@ -85,7 +85,8 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
assert event.data["message_type"] == "transfer-match"
payload = event.data["payload"]
assert payload["kind"] == "match"
assert payload["summary"]["estimated_external_write_count"] == 2
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
assert payload["summary"]["estimated_external_write_count"] == 1
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
@@ -57,7 +57,9 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
assert summary.counts.blocked_count == 0
assert summary.status == "ready_to_execute"
assert summary.matching_hash.startswith("sha256:")
assert summary.estimated_external_write_count == 3
# [2026-10-12 单据数口径修正] 3 行可执行按执行建单五元组去重:DBS 两行
# 同(org,source,date,from,to)合并 1 张 + CRANE 1 行 1 张 = 2(原口径=行数 3)。
assert summary.estimated_external_write_count == 2
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
items = {item.invoice_no: item for item in result.items}
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
@@ -66,6 +68,61 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
def test_estimated_document_count_merges_same_group(dbs_ready_file):
"""[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to)
全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2;
并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。
"""
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
)
assert result.summary.counts.executable_count == 2
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。
assert result.summary.estimated_external_write_count == 1
items = {item.invoice_no: item for item in result.items}
assert items["HOM-001"].external_org == "HX-CN01"
assert items["HOX-002"].external_org == "HX-CN01"
def test_estimated_document_count_splits_by_receipt_date():
"""[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。
锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键,
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
"""
deps, erp, _ = _deps({
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_no": "REC-20260806-009",
"file_version": "v9",
"checksum": "e" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A",
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B",
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
],
})
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600")
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-B", "600")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
)
assert result.summary.counts.executable_count == 2
assert result.summary.estimated_external_write_count == 2
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
deps, erp, _ = _deps(same_day_receipt_file)
@@ -29,7 +29,9 @@ def test_transfer_job_registered_with_schedule_defaults():
assert job is not None
assert job.enabled
keys = {field.get("key") for field in job.params_schema}
assert {"source_codes", "recover_history"} <= keys
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
assert "notify_user_ids" not in keys
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
@@ -123,17 +125,8 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
class _FakeSender:
"""记录实例化的发送器替身(断言 handler 接线,不发真实消息)。"""
instantiated = 0
def __init__(self):
type(self).instantiated += 1
def test_handler_wires_sender_and_domain_notification(monkeypatch):
"""配了通知人:构造 sender、置领域自管标记、recipients 透传。"""
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
@@ -147,28 +140,32 @@ def test_handler_wires_sender_and_domain_notification(monkeypatch):
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
class _FakeSenderInner:
pass
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]})
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
run = ScheduleRun(run_no="RUNR-1", status="running")
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
assert "sender" not in captured
assert "recipients" not in captured
assert captured["receipt_date_from"] is None
assert captured["receipt_date_to"] is None
assert captured["source_codes"] == ["CRANE_SGP"]
assert captured["recipients"] == ["7"]
assert isinstance(captured["sender"], _FakeSenderInner)
assert captured["recover_history"] is True
assert run.response_summary_json["domain_notification_managed"] is True
assert (total, success, failed, skipped) == (0, 0, 0, 0)
assert results == []
assert any("no executable items" in w for w in warnings)
def test_handler_without_recipients_skips_domain_notification(monkeypatch):
"""未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。"""
def test_handler_converts_t_minus_offsets(monkeypatch):
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
from datetime import date
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
captured = {}
def _fake_auto_transfer(**kwargs):
@@ -178,43 +175,91 @@ def test_handler_without_recipients_skips_domain_notification(monkeypatch):
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
run = ScheduleRun(run_no="RUNR-4", status="running")
job_mod.run_in_transit_transfer_schedule(task, run)
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
assert captured["business_date"] == "2026-10-12"
assert captured["receipt_date_from"] == "2026-10-08"
assert captured["receipt_date_to"] == "2026-10-10"
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run with invalid offsets")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
run = ScheduleRun(run_no="RUNR-5", status="running")
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
_total, _success, _failed, _skipped, results, _warnings, errors = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
assert results == []
assert any("收料日期起点" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
_total, _success, _failed, _skipped, _results, _warnings, errors = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:小数偏移同样快速失败。
assert any("收料日期终点" in e for e in errors)
def test_handler_run_day_uses_framework_notification(monkeypatch):
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-2", status="running")
job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
assert captured["sender"] is None
assert captured["recipients"] == []
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results and results[0]["run_no"] == "TR-1"
assert (total, success, failed, skipped) == (1, 1, 0, 0)
assert errors == []
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(有通知人、无 run_no、有 errors):仍构造并传入 sender,但不置自管标记。"""
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
class _FakeSenderInner:
pass
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
task = ScheduleTask(job_params={"notify_user_ids": ["7"]})
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-3", status="running")
_total, _success, _failed, _skipped, _results, _warnings, errors = (
_total, _success, _failed, _skipped, results, _warnings, errors = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:sender 已构造并透传;硬失败不抑制框架完成卡。
assert isinstance(captured["sender"], _FakeSenderInner)
assert captured["recipients"] == ["7"]
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results == []
assert errors == ["match pipeline boom"]
@@ -132,20 +132,68 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
outcome = finalize_receipt_schedule_run_if_complete(run.id)
# [断言意图] 一次性出口:单条 textcard + 单个收料 ZIP,与库存排程同通道同门禁。
# [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。
assert outcome == {'finalized': True, 'status': 'success'}
assert len(textcards) == 1
assert '原始收料包:已随本通知发送' in textcards[0][1]
assert len(media_uploads) == 1
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-收料.zip')
assert file_sends == ['media-1']
assert len(media_uploads) == 2
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx')
assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip')
assert file_sends == ['media-1', 'media-2']
assert run.wecom_notified is True
assert run.response_summary_json.get('raw_receipt_zip_available') is True
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
assert len(textcards) == 1 and len(file_sends) == 1
assert len(textcards) == 1 and len(file_sends) == 2
def test_receipt_finalize_generates_summary_excel(app, tmp_path):
"""收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。"""
from io import BytesIO
from openpyxl import load_workbook
from app import db
from app.models import (
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
)
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
with app.app_context():
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
db.session.add(run); db.session.flush()
unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
db.session.commit()
outcome = finalize_receipt_schedule_run_if_complete(run.id)
# [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。
assert outcome == {'finalized': True, 'status': 'partial_failed'}
assert run.excel_file_data
assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx')
assert run.response_summary_json['excel_export_status'] == 'ok'
assert run.response_summary_json['excel_failed'] is False
# [断言意图] 行结构对齐库存:中文表头 + empty→skipped / failed 保持 failed,与卡片计数口径一致。
workbook = load_workbook(BytesIO(run.excel_file_data))
sheet = workbook.active
header = [cell.value for cell in sheet[1]]
assert header[:2] == ['收料源', '仓库']
rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)}
assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success'
assert rows['DSV360_AWSCV'][4] == 'skipped'
assert rows['CRANE_WH1'][4] == 'failed' and rows['CRANE_WH1'][6] == 'download timeout'
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
@@ -50,7 +50,7 @@
| --- | --- | --- |
| POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 必填,可选 `business_date`/`receipt_date_from`/`receipt_date_to`/`transfer_type`,缺省 `in_transit_to_hub`;响应含 matching_id/hash/计数/来源进度) |
| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→数据源→Invoice→created_at,2026-09-29 与待处理池/匹配卡视图统一为同一口径;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 |
| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`,counts 实时聚合) |
| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`/`external_org`(执行建单五元组首键,2026-10-12 起),counts 实时聚合) |
| POST | `/matchings/{no}/items/requery` | 批量重查 ERP 库存——圈行口径=匹配 scope(与匹配卡实时视图同源谓词,行归属 matching_id 不参与;2026-09-24 修复:旧按 matching_id 圈行致历史行重查不可达);body 可选 `invoice_nos` 限定范围;库存查询按组织批量(2026-09-29:每组织一次 `query_stock`,N 行=N 组织内 1 次调用,行级评估/Attempt/审计保持单行粒度) |
| POST | `/sources/receipt-files` | 按选中来源打包下载各自最新归档收料文件 zip(下载留审计) |
| GET | `/runs/{run_no}` | Run 结果(`orders` 调拨单清单=进度=结果,逐单八键/行六键含 reason;+ 按 ERP 单号聚合 external_documents + 未落单异常 exceptions) |
@@ -189,6 +189,7 @@ cd backend && flask db upgrade
- 端到端场景清单(前端实施后落 Playwright/Vitest 契约):人工执行主路径、自动排程、异常恢复、刷新恢复、权限越权、ERP 沙箱真实单据(创建/审核/过账/作废)。
- 本期功能验收项(2026-09-24 ERP 建单写路径,配置见 §10):
- **五元组建单**:按五元组(external_org / source_code / 收料日期 / 拨出库位 / 拨入库位,全 .strip() 规范化)聚合明细建一张单,单号 `HX-<org>-OR-*`;同组失败单复用单号/时间戳全量重跑、result_unknown/executing 单阻断新行(group_ticket_unresolved)。
- **预计 ERP 单据数口径(2026-10-12 修正)**:匹配摘要 `estimated_external_write_count` = 可执行行按同款五元组去重后的组数(同组多行合并一张,原「=可执行行数」口径高估);匹配卡上该数(计数卡=全部可执行行、生成按钮旁=勾选可执行行,随勾选联动)由前端按行上 `external_org` 实时分组计算,历史快照中旧口径持久值不再上屏。
- **融合卡**:`GET /runs/{run_no}` orders 逐单亮态(成功/失败/未知三态+ERP 单号回显),202 提交后 4s 轮询至严格终态;retrigger 受理窗口不误停轮询。
- **retrigger**:result_unknown 单复用 doc_no/submit_timestamp 只触发末步,ERP 幂等回原单号;非 result_unknown 400。
- **关闭单**:business_failed/technical_failed 人工关闭(原因必填),单 cancelled、行脱离回可执行、组锁释放可另开新单;result_unknown 无关闭入口(SOP 红线 §10.8)。
+1 -1
View File
@@ -3064,7 +3064,7 @@ FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900
- 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。
- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。
- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **汇总结果 Excel** `收料RPA-{yyyyMMdd}-{HHmm}-结果.xlsx`(2026-10-12 对齐库存补齐;列头 收料源/仓库/连接器/归档文件数/导出状态/跳过原因/错误原因,`empty→skipped`、`cancelled→failed` 与卡片计数同口径,导出失败降级 success→partial_failed 并记 `excel_export_status/excel_failed`)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_receipt_rpa_worker_ready`:心跳 TTL + 收料 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\receipt\logs\worker.log` 巡检。
+1 -1
View File
@@ -799,7 +799,7 @@
| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) |
| 收料文件准备与只读匹配(原"预检") | 后端已实现 | 收料文件落地即同步待办行(RPA 回调桥 → evidence_sync 三分类写入:新行待查/证据变化刷新重置/缺席行存续只换戳);匹配=证据对齐兜底(align_scope_rows,sha 一致直通零解析)+ 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/T+lag 成熟(默认 T+2)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 |
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) |
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) |
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;任务参数=来源实例/历史可恢复异常复核/可选收料日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,越界由匹配层卡控成熟上限);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) |
| 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md |
| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) |
@@ -261,7 +261,7 @@ watch(
type="date"
:value="params[field.key] ?? ''"
class="input-field w-full !text-sm !leading-5"
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
@input="setField(field.key, ($event.target as HTMLInputElement).value === '' ? null : ($event.target as HTMLInputElement).value)"
/>
<input
v-else-if="field.type === 'datetime'"
@@ -341,7 +341,7 @@ watch(
v-model="multiSearch[field.key]"
type="text"
class="mb-1 w-full rounded-lg border border-default px-2 py-1.5 text-sm outline-none focus:border-blue-500"
:placeholder="$t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
:placeholder="resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
/>
<p v-if="optionsLoading[field.options_source || '']" class="px-2 py-1 text-xs text-muted">
{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}
@@ -1,12 +1,14 @@
<!--
features/chat/components/messages/TransferBacklogSummaryCard.vue
用途:待处理异常卡(可恢复/已关闭/结果未知三组)——列与匹配窗口一致,
支持关键字/结果筛选、多选批量操作(重查/恢复处理/标记无需处理)与行级快捷操作。
支持关键字/结果筛选、多选批量操作(重查/恢复/关闭)与行级快捷操作。
依赖:props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo、transferFormat.formatQuantity。
逻辑:仅 blocked_recoverable 可勾选与操作;result_unknown / manually_closed 只读;
可恢复行按 result_code 细分徽标(blocked_file_removed=文件已移除);
blocked_file_removed 行行内仅留「标记无需继续处理」(重查不可恢复——消失证据
blocked_file_removed 行行内仅留「关闭」(重查不可恢复——消失证据
无法由重查翻回,唯一出口=人工关闭或等文件重新同步);
批量按钮与行内按钮同用短文案键(重查/恢复/关闭,2026-10-12 文案一致化,
完整语义经 title 悬浮),勾选计数保留;
勾选集合为卡片本地态,操作经 emit 交父组件调用批量端点并刷新。
-->
<script setup lang="ts">
@@ -157,18 +159,22 @@ function resultLabelKey(item: TransferBacklogItem): string {
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-resume"
:disabled="busy"
:title="$t('chat.transfer.resumeAction')"
@click="emit('resume', selectedActionableIds)"
>
{{ $t('chat.transfer.resumeAction') }}({{ selectedActionableIds.length }})
<!-- [2026-10-12 文案一致化] 批量按钮与行内按钮同用短文案键(恢复/关闭),
勾选计数保留;完整语义经 title 悬浮透出(与行内按钮同模式) -->
{{ $t('chat.transfer.resumeActionShort') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
class="rounded-lg border border-red-200 bg-red-50 px-3 py-1 text-xs font-bold text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-40"
data-testid="transfer-backlog-batch-close"
:disabled="busy"
:title="$t('chat.transfer.manualClose')"
@click="emit('batchClose', selectedActionableIds)"
>
{{ $t('chat.transfer.manualClose') }}({{ selectedActionableIds.length }})
{{ $t('chat.transfer.manualCloseShort') }}({{ selectedActionableIds.length }})
</button>
<button
type="button"
@@ -10,7 +10,7 @@ import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import TransferMatchCard from './TransferMatchCard.vue';
import type { TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
/** 最小合法匹配摘要(TransferMatchingSummary 全必填字段齐备,计数为 0) */
function buildSummary(): TransferMatchingSummary {
@@ -70,3 +70,81 @@ describe('TransferMatchCard 来源失败顶栏', () => {
expect(wrapper.find('[data-testid="transfer-match-failed-sources"]').exists()).toBe(false);
});
});
/** [2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
* 行分组键 = (external_org, source_code, receipt_date, from_warehouse,
* to_warehouse),与后端 execution_service.prepare_execution 同口径:
* 同组多行执行期合并一张 ERP 单,预估数不得等于可执行行数。 */
function buildItem(overrides: Partial<TransferMatchingItem>): TransferMatchingItem {
return {
item_id: 1,
source_code: 'DBS-AWSBI',
material_no: 'MAT-001',
material_name: '连接器组件',
specification: 'A 型',
invoice_no: 'HOM-001',
receipt_date: '2026-08-05',
from_warehouse: 'DBS-TRANSIT',
from_quantity: '100',
to_warehouse: 'HUB-CN01',
to_quantity: '100',
result: 'executable',
external_org: 'HX-CN01',
...overrides,
};
}
/** 计数卡第 5 格 = 预计 ERP 单据(可执行/未成熟/阻断/数量/单据/待查/失效)。 */
function estimateCardText(wrapper: ReturnType<typeof mount>): string {
const cells = wrapper.find('[data-testid="transfer-match-counts"]').findAll('div.rounded-lg');
return cells[4]?.text() ?? '';
}
describe('TransferMatchCard 预计 ERP 单据数(五元组去重)', () => {
const sameGroupA = buildItem({ item_id: 1, invoice_no: 'HOM-001' });
const sameGroupB = buildItem({ item_id: 2, invoice_no: 'HOX-002' });
const crossDate = buildItem({ item_id: 3, invoice_no: 'HOM-003', receipt_date: '2026-08-04' });
it('计数卡:同组两行 + 跨日一行 → 预估 2(不等于可执行行数 3)', () => {
// [断言意图] 锁定五元组去重口径:receipt_date 入键,同组合并、跨组拆分,
// 历史快照旧口径(=行数)持久值不再上屏。
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, sameGroupB, crossDate],
selected: new Set<number>(),
},
global: { plugins: [i18n] },
});
expect(estimateCardText(wrapper).replace(/\D/g, '')).toBe('2');
});
it('生成按钮旁预估随勾选联动:勾选同组两行仍为 1,跨组勾选后为 2', async () => {
// [断言意图] 底部预估回答「点生成会出几张单」:仅统计勾选的可执行行并
// 按五元组分组;同组两行勾选=1 张(合并),追加跨日行勾选=2 张。
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, sameGroupB, crossDate],
selected: new Set<number>([1, 2]),
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
await wrapper.setProps({ selected: new Set<number>([1, 2, 3]) });
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':2');
});
it('阻断行不参与预估:勾选阻断行不改变单据数', () => {
const blocked = buildItem({ item_id: 4, invoice_no: 'HOM-BLOCKED', result: 'blocked_quantity_mismatch' });
const wrapper = mount(TransferMatchCard, {
props: {
summary: buildSummary(),
items: [sameGroupA, blocked],
selected: new Set<number>([1, 4]),
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
});
});
@@ -15,7 +15,12 @@
emit execute(itemIds);来源级解析/文件失败经 sources.error_code 透出
(防"安静全 0"),但路由未解析失败(TRANSFER.ROUTE_NOT_RESOLVED)不进顶栏
——路由失败保持行级(result=blocked_route_not_resolved 行内展示),
顶栏按 error_code 客户端排除,历史卡片回放同样生效。
顶栏按 error_code 客户端排除,历史卡片回放同样生效;
[2026-10-12 单据数口径修正] 预计 ERP 单据数(计数卡=全部可执行行、
生成按钮旁=勾选可执行行)按执行建单五元组 (external_org, source_code,
receipt_date, from_warehouse, to_warehouse) 去重实时计算(与后端
execution_service 同键),同组多行合并一张单——原「=可执行行数」口径
高估单据数误导用户。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -144,6 +149,34 @@ const executableCheckedItemIds = computed(() =>
props.items.filter((item) => isSelectable(item) && isChecked(item)).map((item) => item.item_id as number),
);
/** [2026-10-12 单据数口径修正] 执行建单五元组键(与后端 execution_service.
* prepare_execution 分组建单同键同 .trim() 规范化):(external_org, source_code,
* receipt_date, from_warehouse, to_warehouse),同组多行执行期合并一张 ERP 单。
* 老卡片行缺 external_org 按 '' 参与(分组退化为四元组,仅跨组织同仓库配置下有差异)。 */
function documentGroupKey(item: TransferMatchingItem): string {
return [
(item.external_org ?? '').trim(),
(item.source_code ?? '').trim(),
(item.receipt_date ?? '').trim(),
(item.from_warehouse ?? '').trim(),
(item.to_warehouse ?? '').trim(),
].join('\u001f');
}
/** 预计 ERP 单据数(计数卡):全部可执行行按五元组去重的组数。客户端实时计算,
* 使历史快照中旧口径(=可执行行数)的持久化估计值不再上屏误导。 */
const estimatedDocumentCountAll = computed(
() => new Set(props.items.filter((item) => item.result === 'executable').map(documentGroupKey)).size,
);
/** 预计 ERP 单据数(生成按钮旁):按当前勾选的可执行行分组计数,回答
* 「点生成会出几张单」;未勾选为 0。 */
const estimatedDocumentCountSelected = computed(
() => new Set(
props.items.filter((item) => item.result === 'executable' && isChecked(item)).map(documentGroupKey),
).size,
);
/**
* 库存查询时刻小字(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);
@@ -220,7 +253,9 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedQuantity') }}</div>
</div>
<div class="rounded-lg bg-surface-soft p-2 text-center">
<div class="text-lg font-black text-brand-600">{{ summary.estimated_external_write_count }}</div>
<!-- [2026-10-12 单据数口径修正] 按执行建单五元组去重(客户端计算),
不再透传旧口径持久值(=可执行行数)——同组多行合并一张 ERP 单 -->
<div class="text-lg font-black text-brand-600">{{ estimatedDocumentCountAll }}</div>
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedExternalWrites') }}</div>
</div>
<!-- 待查库存:文件已落地、尚未查过 ERP 库存的行数(历史回放缺省 0) -->
@@ -393,9 +428,10 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
</div>
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
<span class="text-xs text-muted">
<span class="text-xs text-muted" data-testid="transfer-estimate-selected">
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ summary.estimated_external_write_count }}
<!-- [2026-10-12 单据数口径修正] 随勾选联动:按勾选可执行行五元组分组计数 -->
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ estimatedDocumentCountSelected }}
</span>
<button
type="button"
@@ -5,6 +5,9 @@
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
主动作按钮文案 fail-closed:后端下发动作码但无受控 i18n 文案时整体隐藏该按钮(含图标),禁止渲染无文字裸按钮;
阶段能力禁用态:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象
(capabilityDisabledReason),命中时按钮渲染 disabled + 原因 tooltip(capabilityDisabled 命名空间),
与 submitFormalGateAction 的点击拦截同源(展示=执行同源),禁止可点样式诱导用户点击后才被拦截;
loading 仅代表「权威投影读取中」而非系统运行态:已知阶段/状态/阻断仍照常展示
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
@@ -45,12 +48,17 @@ const props = defineProps<{
| null;
retryable?: boolean;
blockingReason?: ShippingProcessingBlockingReason | null;
primaryAction?: ShippingProcessingPrimaryAction | null;
primaryAction?: (ShippingProcessingPrimaryAction & {
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
capabilityDisabledReason?: string | null;
}) | null;
recoveryActions?: Array<{
code: string;
i18nKey?: string | null;
label_key?: string | null;
parameters?: Record<string, unknown>;
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
capabilityDisabledReason?: string | null;
}>;
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
gateStatus?: string | null;
@@ -296,6 +304,11 @@ const businessActionLabel = computed(() => {
});
const businessActionTitle = computed(() => {
// 能力禁用原因优先于重试中提示:禁用态按钮的 tooltip 必须解释"为什么不可点"。
const capabilityText = capabilityDisabledText(
props.primaryAction ? capabilityDisabledReasonOf(props.primaryAction) : null,
);
if (capabilityText) return capabilityText;
const retryingFlag = Boolean(props.retrying);
if (retryingFlag) {
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
@@ -305,6 +318,29 @@ const businessActionTitle = computed(() => {
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
/**
* 阶段能力禁用态裁决:与视图层 submitFormalGateAction 的点击拦截同源(展示=执行同源)。
* 核心逻辑:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象;本卡只负责
* 渲染禁用态与原因 tooltip,不自行推断业务能力。原因文案复用 capabilityDisabled 命名空间,
* 未登记的 reason fail-closed 禁用但不给 tooltip(禁止裸露内部原因码)。
*/
function capabilityDisabledReasonOf(action: { capabilityDisabledReason?: string | null }): string | null {
const reason = String(action.capabilityDisabledReason || '').trim();
return reason || null;
}
function capabilityDisabledText(reason: string | null | undefined): string {
const normalized = String(reason || '').trim();
if (!normalized) return '';
const key = `chat.shippingOrderReview.lifecycle.prepare.capabilityDisabled.${normalized}`;
return te(key) ? t(key) : '';
}
const businessActionCapabilityDisabled = computed(() => (
Boolean(props.primaryAction && capabilityDisabledReasonOf(props.primaryAction))
));
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
const code = String(action.code || '').trim();
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
@@ -329,6 +365,8 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
}
function handleBusinessActionClick() {
// 能力禁用态兜底:disabled 按钮通常不派发 click,此处防御键盘等旁路触发。
if (businessActionCapabilityDisabled.value) return;
const primaryActionCode = String(props.primaryAction?.code || '').trim();
if (!primaryActionCode || primaryActionCode === 'retry') return;
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
@@ -464,9 +502,10 @@ type ReviewCurrentUserStatus =
<button
v-if="showBusinessAction"
type="button"
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 dark:bg-sky-600 dark:hover:bg-sky-500"
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-sky-600 dark:hover:bg-sky-500"
:data-testid="actionIsRetry ? 'review-current-processing-retry' : 'review-current-task-primary-action'"
:disabled="retrying || locating"
:data-capability-disabled="businessActionCapabilityDisabled ? 'true' : undefined"
:disabled="retrying || locating || businessActionCapabilityDisabled"
:title="businessActionTitle"
@click="handleBusinessActionClick"
>
@@ -482,9 +521,11 @@ type ReviewCurrentUserStatus =
v-for="action in recoveryActions"
:key="action.code"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
:data-testid="`review-current-task-recovery-${action.code}`"
:disabled="retrying || locating"
:data-capability-disabled="capabilityDisabledReasonOf(action) ? 'true' : undefined"
:disabled="retrying || locating || Boolean(capabilityDisabledReasonOf(action))"
:title="capabilityDisabledText(capabilityDisabledReasonOf(action))"
@click="$emit('action', action.code, action.parameters || {})"
>
{{ recoveryActionLabel(action) }}
@@ -67,6 +67,9 @@ export interface TransferMatchingItem {
stale?: boolean;
/** 行评估所用收料文件版本与来源最新可用文件是否一致;false = 文件已更新需重新匹配 */
file_current?: boolean;
/** [2026-10-12 单据数口径修正] 执行建单五元组首键(路由解析所得外部组织);
* 匹配评估路径透出,历史回放缺省——预估 ERP 单据数按五元组去重的分组输入 */
external_org?: string;
}
/** 来源实例级进度(决策 18:来源隔离展示) */
@@ -705,6 +705,9 @@ async function mountView(query: Record<string, string> = {}) {
partAvailableQty: '可用数量',
shortage: '库存不足',
pending: '库存匹配或通知文件尚未生成。',
capabilityDisabled: {
no_match_result: '暂无库存匹配结果,请先重新获取库存',
},
},
uploadComplete: {
title: '通知完成',
@@ -761,6 +764,8 @@ async function mountView(query: Record<string, string> = {}) {
actionCodes: {
confirm_customer: '确认客户',
resolve_field_conflicts: '处理字段冲突',
retry_inventory_preparation: '重新获取库存',
retry_inventory_matching: '重新匹配库存',
},
},
},
@@ -1622,6 +1627,81 @@ describe('ShippingOrderReviewView layout phase 1', () => {
);
});
it('renders capability-disabled actions as disabled buttons with reason tooltip', async () => {
// 回归(展示=执行同源):A 渲染的 retry_inventory_matching 命中阶段能力 disabled
// (no_match_result)时,右卡必须直接渲染禁用态 + 原因 tooltip;
// 禁止可点样式诱导用户点击后才被 submitFormalGateAction 弹提示拦截。
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
confirmed_task_id: 906, confirmed_task_no: 'SN-RPA-CAP-DISABLED',
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-RPA-CAP-DISABLED',
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
progressVersion: 5, currentGate: { status: 'blocked_retryable' },
uiState: {
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
primary_action: { code: 'retry_inventory_matching' },
secondary_actions: [{ code: 'retry_inventory_preparation', enabled: true }],
},
} as any;
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-RPA-CAP-DISABLED', status: 'processing', lines: [], events: [],
ui_state: {
actions: { primary: null, secondary: [] },
process_gate: {
execution_no: 'EXEC-RPA-CAP-DISABLED',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
},
allowed_actions: ['retry_inventory_matching', 'retry_inventory_preparation'],
},
stage_context: {
preparation: {
status: 'blocked', source_locked: false,
source_options: [{ source_code: 'DSV' }],
failed_source_codes: ['DSV'],
capabilities: [
{
code: 'retry_inventory_matching', scope: 'task',
action_code: 'retry_inventory_matching', enabled: false,
disabled_reason: 'no_match_result',
},
{
code: 'retry_inventory_preparation', scope: 'task',
action_code: 'retry_inventory_preparation', enabled: true,
disabled_reason: null,
},
],
frozen_order_lines: [], lines: [],
},
},
summary: {}, steps: [],
},
} as any);
submitProcessGatePrimaryActionMock.mockClear();
messageMocks.info.mockClear();
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 主按钮:能力禁用 → disabled + 原因 tooltip(复用 capabilityDisabled.no_match_result 文案)。
const primary = wrapper.get('[data-testid="review-current-processing-retry"]');
expect(primary.attributes('disabled')).toBeDefined();
expect(primary.attributes('data-capability-disabled')).toBe('true');
expect(primary.attributes('title')).toContain('暂无库存匹配结果');
// 侧路按钮:能力 enabled → 保持可点,不受主按钮禁用影响。
const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]');
expect(recovery.attributes('disabled')).toBeUndefined();
// 点击禁用按钮不得触发提交,也不得弹任何 info 提示(此前会弹未翻译 key)。
await primary.trigger('click');
await flushPromises();
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
expect(messageMocks.info).not.toHaveBeenCalled();
});
it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => {
activeCase.value = {
...activeCase.value,
@@ -2024,6 +2104,65 @@ describe('ShippingOrderReviewView layout phase 1', () => {
}
});
it('does not auto-advance when switching formal-downstream files without an activeCase identity', async () => {
// 回归:正式下游(通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,
// 切换前后 activeCase 身份(case_no/document_id)恒为空值;自动推进守卫若用
// activeCase 做“同一文件”判据,会把目标文件更晚的阶段误判成当前文件被推进,
// 弹出“已自动推进到货代上传”。文件身份必须用 requestedCaseNo(与阶段解析同源,
// selectCase/beginCrossRunSwitch 同步块内更新):切换必变更 → 静默;真实推进
// 不触碰 requestedCaseNo → 提示行为不变。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
items: [
{
...reviewQueue.value.items[0],
has_formal_ot: true,
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
{
case_no: 'CASE-2', source_run_no: 'RUN-1', document_id: 2, file_name: 'po-2.pdf',
status: 'confirmed', has_formal_ot: true, issue_count: 0,
lifecycle_stage: 'freight_upload',
lifecycle_entries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
],
};
// 选法 2 盲区:源文件无复核 Case 快照(懒加载失败/未完成时生产即如此),
// 此刻文件身份只剩 requestedCaseNo。
activeCase.value = null;
requestedCaseNo.value = 'CASE-1';
const wrapper = await mountView({ case_no: 'CASE-1', lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
messageMocks.success.mockClear();
// 模拟真实 selectCase 正式下游分支的同步块:更新 requestedCaseNo + activeCase 保持 null。
requestedCaseNo.value = 'CASE-2';
await nextTick();
await flushPromises();
expect(messageMocks.success).not.toHaveBeenCalledWith('已自动推进到货代上传');
// 守卫不得替用户改写深链:切文件是展示上下文切换,不是流程推进。
expect((wrapper.vm as any).$route.query.lifecycle_stage).toBe('fulfillment_prep');
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not open a lifecycle stage before the backend authorizes lifecycle entries', async () => {
// 未收到正式 ui_state.lifecycle_entries 时,前端只能等待实时裁决,
// 不能因页面默认值自行开放订单复核或其他生命周期阶段。
@@ -817,6 +817,33 @@ const LINE_SCOPE_INVENTORY_ACTIONS = new Set([
'override_line_inventory_source',
]);
/**
* 阶段能力按执行动作码索引(preparation.capabilities)。
* 核心逻辑:右卡按钮的禁用态渲染必须与 submitFormalGateAction 的点击拦截消费同一份
* 能力投影,保证「展示=执行同源」——禁止按钮渲染成可点、点击才被能力门禁弹提示。
*/
const stageCapabilityByActionCode = computed(() => {
const map = new Map<string, { enabled: boolean; disabled_reason?: string | null }>();
for (const cap of formalPreparationContext.value?.capabilities || []) {
const code = String(cap.action_code || '').trim();
if (code) map.set(code, cap);
}
return map;
});
/**
* 给右卡动作附加阶段能力禁用原因。
* @param action - 已统一到卡片域的动作对象(须含 code)
* @returns 原对象浅拷贝;能力禁用时带 capabilityDisabledReason,否则该字段为 null
*/
function withStageCapabilityState<T extends { code: string }>(
action: T,
): T & { capabilityDisabledReason?: string | null } {
const cap = stageCapabilityByActionCode.value.get(String(action.code || '').trim());
if (!cap || cap.enabled) return { ...action, capabilityDisabledReason: null };
return { ...action, capabilityDisabledReason: String(cap.disabled_reason || '').trim() || null };
}
const currentTaskPrimaryAction = computed(() => {
if (formalTaskProjectionPending.value) return null;
if (hasFormalOt.value) {
@@ -828,10 +855,10 @@ const currentTaskPrimaryAction = computed(() => {
// 故必须统一映射到卡片域,否则按钮会因 businessActionLabel 为空而 fail-closed 消失。
const action = currentTaskUiState.value?.primary_action ?? null;
if (!action?.code || LINE_SCOPE_INVENTORY_ACTIONS.has(action.code)) return null;
return {
return withStageCapabilityState({
code: String(action.code).trim(),
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
};
});
}
const projection = shippingProcessingProjection.value;
if (projection) {
@@ -914,6 +941,8 @@ const currentTaskRecoveryActions = computed(() => {
// [§2.4 单源] 任务级恢复按钮只读 A.secondary_actions;不再叠加 B.capabilities。
// capabilities 仍可作点击执行的 stageCapabilityBypass 查找(见 handleCurrentTaskAction),
// 但不得单独渲成右卡按钮——能力要展示须先并进 A。行级选源禁止出现在右卡。
// [展示=执行同源] A 已渲染的按钮若命中阶段能力 disabled(capabilityDisabledReason
// 非空),右卡必须渲染禁用态 + 原因 tooltip,禁止可点样式诱导用户点击后才被拦截。
return (currentTaskUiState.value?.secondary_actions || [])
.filter((action) => action.enabled
&& String(action.code || '').trim() !== 'download_excel'
@@ -923,7 +952,8 @@ const currentTaskRecoveryActions = computed(() => {
// 统一右卡 domain:actionCodes.<code>(见 currentTaskPrimaryAction 注;A 的 i18nKey 可能是 chat 域)。
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${String(action.code || '').trim()}`,
}))
.filter((action): action is { code: string; i18nKey: string } => {
.map((action) => withStageCapabilityState(action))
.filter((action): action is { code: string; i18nKey: string; capabilityDisabledReason?: string | null } => {
const code = String(action.code || '').trim();
return Boolean(code) && !LINE_SCOPE_INVENTORY_ACTIONS.has(code);
});
@@ -4879,20 +4909,21 @@ watch(
watch(
() => [
lifecycleCurrentStageCode.value,
String(activeCase.value?.case_no || '').trim(),
activeReviewDocumentId(),
// 文件身份必须用 requestedCaseNo(与 lifecycleUiState 解析阶段同源):正式下游
// (通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,其 case_no/document_id
// 在这些文件之间恒为空值,用 activeCase 做身份会让"切换文件"被误判成"同一文件的
// 阶段推进"而弹出"已自动推进"。requestedCaseNo 在 selectCase/beginCrossRunSwitch/
// load 里与阶段重算同一同步块内更新,切换文件时本 watcher 必然看到变化而静默;
// 真正的自动推进只改队列投影、不触碰 requestedCaseNo,提示行为不变。
String(requestedCaseNo.value || activeCase.value?.case_no || '').trim(),
] as const,
async (current, previous) => {
const [currentStage, currentCaseNo, currentDocumentId] = current;
const [previousStage, previousCaseNo, previousDocumentId] = previous || [];
const [currentStage, currentFileKey] = current;
const [previousStage, previousFileKey] = previous || [];
if (await syncPendingReleaseAutoAdvance()) return;
// 切换文件时生命周期阶段会随新 Case 一起变更;这不是当前文件的自动推进,
// 切换文件时生命周期阶段会随新文件身份一起变更;这不是当前文件的自动推进,
// 不能跳转或弹出“已自动推进”提示。
if (
!previous
|| currentCaseNo !== previousCaseNo
|| currentDocumentId !== previousDocumentId
) return;
if (!previous || currentFileKey !== previousFileKey) return;
if (!currentStage || !previousStage || currentStage === previousStage) return;
const pendingReparse = pendingReparseNavigation.value;
if (
+3 -2
View File
@@ -2560,7 +2560,8 @@
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
"transferSourceCodes": "Source instances",
"transferRecoverHistory": "Recover retryable history",
"transferNotifyUsers": "Notify users",
"transferReceiptDateFrom": "Receipt date from (T-N)",
"transferReceiptDateTo": "Receipt date to (T-N)",
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
"shippingInventoryJobHint": "Fetches inventory data from configured sources on schedule; exported asynchronously by the RPA worker.",
"shippingInventoryJobParams": "Job parameters (optional)",
@@ -2693,7 +2694,7 @@
"voucherCheckNotifyMissingHint": "Master switch. Set missing-file recipients in Chat “Accounting voucher check → Notification config” by file type. The schedule people picker is only for failure alerts.",
"voucherCheckNotifyFailure": "Failure alert",
"voucherCheckNotifyFailureHint": "Technical failures go to the people selected below.",
"dynamicParamsSearchPlaceholder": "Search options (name / ID / dept)…",
"dynamicParamsSearchPlaceholder": "Search options…",
"dynamicParamsSearchNoMatch": "No matching options"
},
"testRun": {
+2 -1
View File
@@ -1726,7 +1726,8 @@
"capabilityDisabled": {
"excel_locked": "Notice Excel generated; inventory source is locked",
"no_candidates": "No available inventory source candidates",
"no_prior_result": "No prior inventory result"
"no_prior_result": "No prior inventory result",
"no_match_result": "No inventory match result yet; re-fetch inventory first"
},
"status": {
"ready": "Match ready",
+3 -2
View File
@@ -2465,7 +2465,8 @@
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
"transferSourceCodes": "Source instances",
"transferRecoverHistory": "Recover retryable history",
"transferNotifyUsers": "Notify users",
"transferReceiptDateFrom": "Receipt date from (T-N)",
"transferReceiptDateTo": "Receipt date to (T-N)",
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
"shippingInventoryJobHint": "ดึงข้อมูลสต็อกจากแหล่งที่กำหนดตามกำหนดเวลา โดย RPA worker ส่งออกแบบอะซิงโครนัส",
"shippingInventoryJobParams": "พารามิเตอร์ Job (ไม่บังคับ)",
@@ -2606,7 +2607,7 @@
"saving": "Saving...",
"saveChanges": "Save changes",
"createSchedule": "Create schedule",
"dynamicParamsSearchPlaceholder": "ค้นหาตัวเลือก (ชื่อ/รหัส/แผนก)…",
"dynamicParamsSearchPlaceholder": "ค้นหาตัวเลือก…",
"dynamicParamsSearchNoMatch": "ไม่มีตัวเลือกที่ตรง"
},
"status": {
+2 -1
View File
@@ -1726,7 +1726,8 @@
"capabilityDisabled": {
"excel_locked": "สร้าง Excel แจ้งเตือนแล้ว แหล่งสินค้าถูกล็อก",
"no_candidates": "ยังไม่มีตัวเลือกแหล่งสต็อกที่พร้อมใช้",
"no_prior_result": "ยังไม่มีผลลัพธ์สต็อกในประวัติ"
"no_prior_result": "ยังไม่มีผลลัพธ์สต็อกในประวัติ",
"no_match_result": "ยังไม่มีผลการจับคู่สต็อก โปรดดึงข้อมูลสต็อกอีกครั้งก่อน"
},
"status": {
"ready": "จับคู่พร้อมแล้ว",
+3 -2
View File
@@ -2688,7 +2688,8 @@
"platformJobFileAssetCleanup": "临时文件资产清理",
"transferSourceCodes": "来源实例",
"transferRecoverHistory": "历史可恢复异常复核",
"transferNotifyUsers": "通知人",
"transferReceiptDateFrom": "收料日期起(T-N)",
"transferReceiptDateTo": "收料日期止(T-N)",
"platformJobFixedAssetsSnapshot": "固资快照",
"shippingInventoryJobHint": "按计划从配置的库存源抓取库存数据,由 RPA Worker 异步导出。",
"shippingInventoryJobParams": "Job 参数(可选)",
@@ -2821,7 +2822,7 @@
"voucherCheckNotifyMissingHint": "总开关。缺件接收人请到 Chat「立账凭证 → 通知配置」按文件类型设置;排程选人只用于技术失败告警。",
"voucherCheckNotifyFailure": "失败告警",
"voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。",
"dynamicParamsSearchPlaceholder": "搜索选项(姓名/工号/部门)…",
"dynamicParamsSearchPlaceholder": "搜索选项…",
"dynamicParamsSearchNoMatch": "没有匹配的选项"
},
"testRun": {
+2 -1
View File
@@ -1760,7 +1760,8 @@
"capabilityDisabled": {
"excel_locked": "通知 Excel 已生成,库存源已锁定",
"no_candidates": "暂无可用库存源候选",
"no_prior_result": "暂无历史库存结果"
"no_prior_result": "暂无历史库存结果",
"no_match_result": "暂无库存匹配结果,请先重新获取库存"
},
"status": {
"ready": "匹配完成",
+3 -2
View File
@@ -2465,7 +2465,8 @@
"platformJobFileAssetCleanup": "暫存檔案資產清理",
"transferSourceCodes": "來源實例",
"transferRecoverHistory": "歷史可復原異常複核",
"transferNotifyUsers": "通知人",
"transferReceiptDateFrom": "收料日期起(T-N)",
"transferReceiptDateTo": "收料日期止(T-N)",
"platformJobFixedAssetsSnapshot": "固資快照",
"shippingInventoryJobHint": "按計畫從配置的庫存來源抓取庫存資料,由 RPA Worker 非同步匯出。",
"shippingInventoryJobParams": "Job 參數(可選)",
@@ -2606,7 +2607,7 @@
"saving": "Saving...",
"saveChanges": "Save changes",
"createSchedule": "Create schedule",
"dynamicParamsSearchPlaceholder": "搜尋選項(姓名/工號/部門)…",
"dynamicParamsSearchPlaceholder": "搜尋選項…",
"dynamicParamsSearchNoMatch": "沒有符合的選項"
},
"status": {
+2 -1
View File
@@ -1726,7 +1726,8 @@
"capabilityDisabled": {
"excel_locked": "通知 Excel 已生成,庫存源已鎖定",
"no_candidates": "暫無可用庫存來源候選",
"no_prior_result": "暫無歷史庫存結果"
"no_prior_result": "暫無歷史庫存結果",
"no_match_result": "暫無庫存匹配結果,請先重新取得庫存"
},
"status": {
"ready": "匹配完成",