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

@@ -44,6 +44,7 @@ from app.core.errors import NotFoundError
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
FreightRpaOnhandReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
@@ -659,6 +660,72 @@ def latest_usable_inbound_file(
return _inbound_file_view(report)
def latest_usable_inbound_files_by_source(
source_ids: list[int],
*,
now: datetime | None = None,
) -> dict[str, InboundFileView]:
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
Args:
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
只留 created_at/id 最新一条。
"""
rows = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
usable_inbound_file_condition(now=now),
)
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
.all()
)
picked: dict[str, InboundFileView] = {}
for report in rows:
view = _inbound_file_view(report)
if view.source_code not in picked:
picked[view.source_code] = view
return picked
def expired_inbound_source_codes(
source_ids: list[int],
*,
now: datetime | None = None,
) -> set[str]:
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
Args:
source_ids: 来源主键集合。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
至少有一份失效未清理入站归档的 source_code 集合。
"""
rows = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
expired_inbound_file_condition(now=now),
)
.with_entities(FreightRpaInboundUnitRun.source_code)
.distinct()
.all()
)
return {str(row[0]) for row in rows}
def read_inbound_file_bytes(file_id: int) -> bytes:
"""按 file_id 读取入站归档文件的对象字节。
@@ -4,10 +4,11 @@
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
调拨不维护独立抓取状态表(低耦合)。
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
入站可用条件同口径)。
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
@@ -28,10 +29,9 @@ from typing import Any, Callable
from sqlalchemy import and_, not_, or_
from app.core.errors import ValidationError
from app.models.freight_rpa_inbound_report import (
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
from app.models.freight_rpa_outbound_report import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
@@ -39,12 +39,12 @@ from app.models.freight_rpa_outbound_report import (
)
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure as _clear_parse_failure_by_id,
expired_inbound_file_condition,
expired_inbound_source_codes,
get_outbound_config,
has_expired_inbound_file,
latest_usable_inbound_file,
latest_usable_inbound_files_by_source,
mark_inbound_parse_failure as _mark_parse_failure_by_id,
usable_inbound_file_condition,
)
from app.services.in_transit_transfer.date_policy import business_date_utc_window
@@ -288,13 +288,13 @@ def _project_file_status(
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
"""一次取出这批来源各自最新的可用归档。
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
Args:
file_model: 入站或出站归档文件模型。
file_model: 出站归档文件模型。
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
source_ids: 要投影的来源主键。
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
@@ -359,13 +359,13 @@ def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str,
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
"""一次找出仍有失效未清理归档的来源编码。
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
Args:
file_model: 入站或出站归档文件模型。
file_model: 出站归档文件模型。
unit_model: 对应的执行单元模型。
source_ids: 要投影的来源主键。
filters: 失效文件条件。
@@ -412,19 +412,17 @@ def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict
.all()
)
}
inbound_files = _latest_files_by_source(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
usable_inbound_file_condition(now=now),
)
inbound_files = {
code: _FileFact(
file_id=view.file_id,
original_filename=view.original_filename,
sha256=view.sha256,
parse_failed_at=view.parse_failed_at,
)
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
}
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
inbound_expired = _expired_source_codes(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
expired_inbound_file_condition(now=now),
)
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
outbound_files = _latest_files_by_source(
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
@@ -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",