feat(in-transit-transfer): 增强调拨类型管理与调度逻辑

- 新增批量获取最新可用入站文件的功能,支持按来源主键集合查询。
- 实现失效入站来源编码的批量查询,优化调拨状态投影。
- 更新调拨任务调度逻辑,支持动态选择调拨类型,留空时默认为全部启用类型。
- 调整相关文档,确保调拨类型配置的清晰性与一致性。
This commit is contained in:
hugo committed 2026-10-26 17:36:14 +08:00
1 parent 3bb9938c05
commit 0331029ead
11 files changed
+609 -150

No files matched your search

@@ -2,18 +2,24 @@
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
排程「启用通知」通用企微通知,本任务不自建领域通知。
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
依赖:auto_transfer、recovery_service、transfer deps、job_registry.ScheduleExecuteResult、
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
transfer_type_config_service.get_enabled(缺省类型口径)、
date_policy(业务日与日期解析)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
不依赖其他排程成功;来源留空兜底为全部启用入站来源;【调拨类型 2026-10-23】
job_params.transfer_types 为 multi_select,留空=全部启用中的类型配置,
按类型逐轮 run_auto_transfer(恢复复核与类型无关,循环外只跑一次);
类型配置为空/读取失败 fail-closed 硬失败,不静默跳过;可选异动日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(全部
类型均无 run_no 且无 errors)置 domain_notification_managed 保持静默
(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
返回:七元组位序=(total, success, failed, skipped, details, errors, step_logs),
warnings 无对应槽位——恢复/来源汇总写 step_logs(dict),不得挤占 errors 位。
"""
from __future__ import annotations
@@ -21,11 +27,13 @@ from __future__ import annotations
from datetime import timedelta
from typing import Any
from app.core.errors import AppError
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.auto_transfer import run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
from app.services.schedule.job_registry import ScheduleExecuteResult
@@ -52,6 +60,33 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
return codes
def _wanted_transfer_types(params: dict[str, Any], errors: list[str]) -> list[str]:
"""提取结构化 transfer_types;留空回落为全部启用中的类型配置(fail-closed)。
Args:
params: 排程结构化参数(job_params.transfer_types 可为列表/字符串/缺省)。
errors: 错误累积列表(类型配置读取失败/为空时写入,由调用方硬失败)。
Returns:
去空白后的类型编码列表;配置为空或脏配置读取失败时为空列表(已落错误)。
"""
values = params.get("transfer_types") or []
if isinstance(values, str):
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if codes:
return codes
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
try:
codes = [dto.code for dto in get_enabled()]
except AppError as exc:
errors.append(f"调拨类型配置读取失败: {exc}")
return []
if not codes:
errors.append("无启用中的调拨类型配置(须先在管理端调拨类型页创建并启用)")
return codes
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
@@ -77,12 +112,14 @@ def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: li
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
"""自动调拨:恢复(一次)→ 按类型逐轮「匹配(严格相等)+ 执行」;通知走排程「启用通知」。
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
核心逻辑:不自建领域汇总通知(收件人取排程表单底部「启用通知」配置);
仅在空数据日(全部类型均无 run_no 且无 errors)置 domain_notification_managed
抑制框架完成卡(C5 空数据日静默);有 run_no 或硬失败时框架卡照常发送/兜底。
调拨类型留空=全部启用类型逐轮执行(D8:类型=平台配置,排程不隐式假设单一
类型;配置为空/读取失败 fail-closed 硬失败);历史恢复与类型无关,循环外
只跑一次(重复恢复会对同一批行重复建 Attempt 并重复外部查询)。
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
@@ -90,7 +127,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
Args:
task: 排程任务(job_params: source_codes/recover_history/
task: 排程任务(job_params: transfer_types/source_codes/recover_history/
receipt_from_offset_days/receipt_to_offset_days)。
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
Returns:
@@ -101,60 +138,99 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
recover_history = bool(params.get("recover_history", True))
business_date = str(business_date_now())
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。
param_errors: list[str] = []
# [STEP 1] 配置解析与 T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。硬失败以 failed_count=1 落终态
# failed(total=0 且 errors 非空会被框架判 success「无待处理数据」,不可用)。
errors: list[str] = []
transfer_types = _wanted_transfer_types(params, errors)
movement_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
business_date, params.get("receipt_from_offset_days"), "异动日期起点", errors)
movement_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)
business_date, params.get("receipt_to_offset_days"), "异动日期终点", errors)
if errors:
return (1, 0, 1, 0, [], errors, [
{"step": "config", "status": "failed", "detail": f"sources={len(source_codes)}"},
])
deps = transfer_deps.get_transfer_dependencies()
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
transfer_type = str(params.get("transfer_type") or "").strip() or None
outcome = run_auto_transfer(
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=transfer_type,
)
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
if not outcome.run_no and not outcome.errors:
# [STEP 2] 恢复复核只跑一次:扫全部 blocked_recoverable 行(与类型无关),
# result_unknown / manually_closed 在服务内只读隔离/永久排除。恢复失败计一个
# failed 单元——否则「恢复失败+各类型均空数据日」total=0 会被框架判 success。
recovery = RecoveryOutcome()
recovery_failed = False
if recover_history:
try:
recovery = run_daily_recovery(business_date=business_date, deps=deps)
except Exception as exc: # noqa: BLE001
recovery_failed = True
errors.append(f"recovery_failed: {exc}")
step_logs: list[dict[str, Any]] = [{
"step": "recovery",
"status": "failed" if recovery_failed else ("success" if recover_history else "skipped"),
"detail": {
"recovered": recovery.recovered_count,
"still_blocked": recovery.still_blocked_count,
"skipped_result_unknown": recovery.skipped_result_unknown,
"skipped_manually_closed": recovery.skipped_manually_closed,
},
}]
failed_units = 1 if recovery_failed else 0
# [STEP 3] 按类型逐轮自动调拨:单类型失败不阻断其余类型(run_auto_transfer
# 内部捕获进 outcome.errors)。
results: list[dict[str, Any]] = []
success_runs = 0
failed_runs = 0
for code in transfer_types:
outcome = run_auto_transfer(
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=False,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=code,
)
errors.extend(outcome.errors)
if outcome.run_no:
results.append({
"transfer_type": code,
"run_no": outcome.run_no,
"status": outcome.run_status,
})
if outcome.run_status in {"success", "partial_failed"}:
success_runs += 1
else:
failed_runs += 1
elif outcome.errors:
failed_runs += 1
# [STEP 4] 空数据日静默门禁:全部类型均无 run 且无错误(C5)时置标记抑制
# 框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
if not results and not errors:
run.response_summary_json = {
**(run.response_summary_json or {}),
"domain_notification_managed": True,
}
results: list[dict[str, Any]] = []
errors: list[str] = list(outcome.errors)
recovery = outcome.recovery
warnings: list[str] = [
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
]
if outcome.run_no:
results.append({
"run_no": outcome.run_no,
"status": outcome.run_status,
step_logs.append({
"step": "auto_transfer", "status": "skipped",
"detail": "no executable items; execution and notification skipped",
})
elif not outcome.errors:
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
warnings.append("no executable items; execution and notification skipped")
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
summary_text = (
f"sources={len(source_codes)} types={len(transfer_types)} "
f"runs={len(results)} recovered={recovery.recovered_count} "
f"still_blocked={recovery.still_blocked_count}"
)
return (
success + recovery.recovered_count,
success,
recovery.still_blocked_count,
success_runs + failed_runs + recovery.recovered_count + failed_units,
success_runs,
failed_runs + failed_units + recovery.still_blocked_count,
0,
results,
warnings,
errors,
step_logs + [
{"step": "summary", "status": "failed" if errors else "success", "detail": summary_text},
],
)
+17 -1
View File
@@ -5,7 +5,8 @@ backend/app/services/schedule/job_options.py
依赖:models.Agent、shipping_notice.onhand_source_repository。
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources;
在途调拨注册键为 transfer_types(启用中的调拨类型配置)。
"""
from __future__ import annotations
@@ -78,6 +79,20 @@ def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
} for source, _config in rows]
def _transfer_types_options() -> list[dict[str, Any]]:
"""启用中的调拨类型(value=类型编码;供在途自动调拨排程选类型,留空=全部)。"""
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
return [
{
"label": (dto.names or {}).get("zh-CN") or dto.code,
"value": dto.code,
"description": dto.description or None,
}
for dto in get_enabled()
]
def _hxops_users_options() -> list[dict[str, Any]]:
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
from app.models import User
@@ -118,6 +133,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"freight_rpa_sources": _freight_rpa_sources_options,
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
"transfer_types": _transfer_types_options,
"hxops_users": _hxops_users_options,
"users": _users_options,
}
+12 -1
View File
@@ -606,10 +606,21 @@ def _register_builtin_platform_jobs() -> None:
handler=run_in_transit_transfer_schedule,
description=(
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
"缺收料文件时自动触发收料 RPA。调拨类型留空=全部启用类型逐轮执行。"
"执行时间建议配置在期望调拨时点之前。"
),
category="platform",
params_schema=(
{
"key": "transfer_types",
"type": "multi_select",
"label": "调拨类型",
"label_key": "admin.schedule.form.transferTypeCodes",
"required": False,
"default": [],
"options_source": "transfer_types",
"help": "留空=全部启用中的调拨类型;按类型逐轮匹配并执行,恢复复核只跑一次。",
},
{
"key": "source_codes",
"type": "multi_select",