feat(in-transit-transfer): 增强调拨类型管理与调度逻辑
- 新增批量获取最新可用入站文件的功能,支持按来源主键集合查询。 - 实现失效入站来源编码的批量查询,优化调拨状态投影。 - 更新调拨任务调度逻辑,支持动态选择调拨类型,留空时默认为全部启用类型。 - 调整相关文档,确保调拨类型配置的清晰性与一致性。
This commit is contained in:
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},
|
||||
],
|
||||
)
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
|
||||
|
||||
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
|
||||
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
|
||||
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
|
||||
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
|
||||
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
|
||||
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
|
||||
外部系统 单号投影。
|
||||
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
|
||||
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
|
||||
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
|
||||
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
|
||||
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
|
||||
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
|
||||
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
|
||||
执行入口(execute_matching_items)与按外部系统单号投影。
|
||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
||||
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
|
||||
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
|
||||
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
|
||||
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
|
||||
matching_service 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
)
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
||||
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
|
||||
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
|
||||
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
|
||||
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
|
||||
):
|
||||
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
|
||||
|
||||
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
|
||||
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
|
||||
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
|
||||
# 消费方),此处同步打桩保持与执行侧替身同源。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": {
|
||||
"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "e" * 64,
|
||||
},
|
||||
)
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
|
||||
listing = list_executable_items(deps=deps)
|
||||
decorated = {row.item_id: row for row in listing["items"]}
|
||||
assert all(decorated[item.id].file_current is False for item in items)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
|
||||
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
|
||||
|
||||
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": None})
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
||||
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
||||
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
||||
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
||||
依赖:schedule.job_registry、job_options、inbound_trigger_service、
|
||||
transfer_type_config_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
|
||||
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
|
||||
skipped, results, errors, step_logs),errors 位只放真实错误。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
|
||||
from app.services.schedule.job_options import is_known_options_source
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
|
||||
|
||||
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
|
||||
|
||||
|
||||
def test_transfer_job_registered_with_schedule_defaults():
|
||||
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
import re
|
||||
|
||||
job = get_platform_job("in-transit-transfer")
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||
assert {
|
||||
"transfer_types", "source_codes", "recover_history",
|
||||
"receipt_from_offset_days", "receipt_to_offset_days",
|
||||
} <= keys
|
||||
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
|
||||
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
|
||||
assert types_field.get("type") == "multi_select"
|
||||
assert types_field.get("options_source") == "transfer_types"
|
||||
assert types_field.get("default") == []
|
||||
assert is_known_options_source("transfer_types")
|
||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||
assert "notify_user_ids" not in keys
|
||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
|
||||
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
|
||||
|
||||
errors: list[str] = []
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
|
||||
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
|
||||
])
|
||||
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert errors == []
|
||||
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
|
||||
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
|
||||
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
|
||||
assert _wanted_transfer_types({}, errors) == []
|
||||
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
|
||||
assert errors and "调拨类型" in errors[-1]
|
||||
|
||||
|
||||
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
|
||||
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
|
||||
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
seed_transfer_type_config("in_transit_to_hub", enabled=True)
|
||||
seed_transfer_type_config("hub_repair_out", enabled=False)
|
||||
transfer_db.session.commit()
|
||||
|
||||
options = list_job_options("transfer_types")
|
||||
codes = {option["value"] for option in options}
|
||||
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
|
||||
assert "in_transit_to_hub" in codes
|
||||
assert "hub_repair_out" not in codes
|
||||
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
|
||||
assert label == "类型 in_transit_to_hub"
|
||||
|
||||
|
||||
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
|
||||
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
monkeypatch.setattr(
|
||||
type_mod, "get_enabled",
|
||||
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
|
||||
)
|
||||
return job_mod
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
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={"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)
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
|
||||
assert captured["recover_history"] is False
|
||||
assert captured["movement_date_from"] is None
|
||||
assert captured["movement_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recover_history"] is True
|
||||
assert captured["transfer_type"] == "in_transit_to_hub"
|
||||
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)
|
||||
assert results == [] and errors == []
|
||||
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert any(item.get("step") == "auto_transfer" for item in step_logs)
|
||||
|
||||
|
||||
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_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
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")
|
||||
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
|
||||
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_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
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 = (
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
|
||||
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
|
||||
assert (total, failed) == (1, 1)
|
||||
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 = (
|
||||
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
|
||||
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
|
||||
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
|
||||
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
|
||||
recovery_calls: list[dict] = []
|
||||
|
||||
def _fake_recovery(**kwargs):
|
||||
recovery_calls.append(kwargs)
|
||||
return RecoveryOutcome(recovered_count=2)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
|
||||
calls: list[dict] = []
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
calls.append(kwargs)
|
||||
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
|
||||
run = ScheduleRun(run_no="RUNR-6", status="running")
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
|
||||
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert all(c["recover_history"] is False for c in calls)
|
||||
assert len(recovery_calls) == 1
|
||||
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
|
||||
assert (total, success, failed, skipped) == (4, 2, 0, 0)
|
||||
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
|
||||
assert errors == []
|
||||
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert step_logs[0]["detail"]["recovered"] == 2
|
||||
|
||||
|
||||
def test_handler_empty_type_config_fails_hard(monkeypatch):
|
||||
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=[])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run without transfer types")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-7", status="running")
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("调拨类型" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return 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")
|
||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||
# 断言:有 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 results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||
assert errors == []
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
|
||||
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError("stock source offline")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-9", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
|
||||
# 恢复 step_log 标 failed;不置静默标记。
|
||||
assert (total, success, failed) == (1, 0, 1)
|
||||
assert results == []
|
||||
assert errors == ["recovery_failed: stock source offline"]
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
|
||||
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_recover(**_kwargs):
|
||||
raise AssertionError("run_daily_recovery must not run when recover_history is false")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
|
||||
monkeypatch.setattr(
|
||||
job_mod, "run_auto_transfer",
|
||||
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
|
||||
)
|
||||
|
||||
task = ScheduleTask(job_params={"recover_history": False})
|
||||
run = ScheduleRun(run_no="RUNR-10", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
|
||||
assert (total, success, failed) == (1, 1, 0)
|
||||
assert results and results[0]["run_no"] == "TR-10"
|
||||
assert errors == []
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return 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))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
_total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
|
||||
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results == []
|
||||
assert errors == ["match pipeline boom"]
|
||||
assert failed == 1
|
||||
|
||||
|
||||
def test_handler_type_failure_isolated_per_type(monkeypatch):
|
||||
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
if kwargs["transfer_type"] == "bad_type":
|
||||
return AutoTransferOutcome(errors=["type config disabled"])
|
||||
return AutoTransferOutcome(run_no="TR-9", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-8", status="running")
|
||||
total, success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
|
||||
assert (total, success, failed) == (2, 1, 1)
|
||||
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert errors == ["type config disabled"]
|
||||
@@ -0,0 +1,20 @@
|
||||
# 调拨对话只解释规则并带路
|
||||
|
||||
状态:被 [ADR 0006](0006-defer-transfer-conversation.md) 取代(2026-10-26)。下文保留当时的取舍,不再作为实施依据。
|
||||
|
||||
手工调拨已由卡片按钮测通,自动调拨另案验收。2026-10-26 决定:在途调拨的第一刀对话只做简体中文的规则说明,并按固定带路表打开已有视图、指出按钮。生成调拨单、勾选、关闭、重查、重新触发仍由那些按钮提交。首页已经显示的数量不在对话里重报。Dify 1.16.1 Chatflow 只交回一句中文和一个可选视图代码;未知代码或只问数量时留在首页。提示词以仓库文本为唯一口径,从仓库发布到 Dify。
|
||||
|
||||
这样做是因为写接口一旦成为模型工具,就会绕开卡片上已经测过的门禁(看见的行、关闭必填原因、结果未知只能重新触发)。气泡图平台把写操作做成确认后的工具,是因为那里没有这套卡片。首页数字在能打字时已经可见,再查一套没有意义。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Dify 直接调用写接口,或用 Human Input 再确认一次**:被否——同一件提交会有两扇门,Human Input 与匹配卡、执行看板重复。
|
||||
- **每轮把首页计数塞进提示词,由模型报数**:被否——能对话时人就在首页,卡片已经是这套数字的呈现。
|
||||
- **自研多轮工具循环**:被否——HXOPS 的 hybrid 运行时已经只接 Dify Chatflow。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 带路表:规则或数量留在首页;库存匹配打开来源选择(确认范围并匹配);待匹配只读;生成、勾选、可调拨明细打开可调拨明细(生成调拨单);重查、恢复处理、关闭异常行打开待恢复异常(重查库存,或关闭且须填原因);已人工关闭只查看原因;结果未知打开执行看板对应分组(重新触发);关闭调拨单或看失败单打开执行看板的失败分组(关闭调拨单)。没分清是待恢复异常还是失败调拨单时先问,不猜。
|
||||
- 提示词只陈述八条:执行边界是出入站来源实例;数量必须与 ERP 严格相等;恢复处理就是重查库存;人工关闭只保留原因;结果未知只能在执行看板重新触发;写操作在卡片按钮上完成;数量以首页卡片为准;不讲述某一次自动调拨,也不解释某一张发票为什么被挡住。点名发票、追问某次自动运行或要求直接生成时,只说明并打开对应类别的视图。
|
||||
- 界面四语言卡片不变。自动调拨的测试、排程和 ERP 写路径不在本决策内。按发票解释阻断原因、讲述最近一次自动运行、在对话里填好来源和日期并创建匹配,留到下一刀。
|
||||
- 术语见 `docs/features/in-transit-transfer/GLOSSARY.md` 的调拨对话、恢复处理、人工关闭、结果未知。
|
||||
@@ -0,0 +1,18 @@
|
||||
# 调拨对话先不做
|
||||
|
||||
状态:accepted,取代 [ADR 0005](0005-transfer-conversation-explains-and-routes.md)。
|
||||
|
||||
2026-10-26 决定先不做在途调拨对话。匹配、勾选、生成调拨单、重查库存、人工关闭和重新触发都是确定动作,现有卡片已经是最短路径。再加一轮 Chatflow,只是在同一次点击之前多一次等待。规则说明也不在这轮写成卡片旁的固定文字。
|
||||
|
||||
按某张发票解释阻断原因,留到卡片上的现有文字确实答不清时再单独立项。在那之前不接 Chatflow,不发布提示词,不增加视图代码。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **按 ADR 0005 做解释加带路**:被否——带路的终点仍是现有按钮,对话比直接点卡片更慢。
|
||||
- **现在就把规则写进卡片文案**:被否——这轮连说明文案也不加,避免借停对话之机扩大改动。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 不写规格,不改聊天回合,不改首页视图切换。
|
||||
- 自动调拨的测试、排程和 ERP 写路径仍按原案,与本决定无关。
|
||||
- 术语表不保留「调拨对话」。恢复处理、人工关闭、结果未知仍是现行卡片上的概念。
|
||||
@@ -75,6 +75,18 @@ _Avoid_: 数据源、站点、Inbound Source Instance
|
||||
一个出入站来源实例上、按记录类型分开的一条抓取与文件状态。同一来源实例可同时有入站证据流和出站证据流。
|
||||
_Avoid_: 来源状态、部分就绪
|
||||
|
||||
**恢复处理 (Recovery Requery)**:
|
||||
对待恢复异常重新核对 ERP 库存的那一次查询。与「重查库存」是同一件事。
|
||||
_Avoid_: 把已人工关闭的记录重新打开
|
||||
|
||||
**人工关闭 (Manual Close)**:
|
||||
仓库人员判定某条明细不再继续调拨,并留下原因之后的状态。该状态只保留原因供查看。
|
||||
_Avoid_: 删除、恢复处理
|
||||
|
||||
**结果未知 (Result Unknown)**:
|
||||
一次调拨写入之后,ERP 是否已经生成单据仍不能确定的状态。
|
||||
_Avoid_: 失败、待恢复异常
|
||||
|
||||
**收料 RPA (Receipt RPA · 旧名保留)**:
|
||||
入站证据抓取链路的**实现载体**:在途调拨的入站抓取复用货代 shipping_notice 域的 ShippingReceiptReport RPA,故该域内的数据表名(`shipping_receipt_report_*`)、RPA 契约(`shipping_receipt_rpa.v1` / `receipt_export_batch`)、目录(`freight_rpa/receipt/`)与环境变量(`FREIGHT_RPA_RECEIPT_*`)保留「收料/receipt」旧名,默认不改(与运行期收敛口径一致;如后续确需更名须单独立项评估)。它与在途调拨域所说的「入站(链路/文件/抓取)」是**同一条物理链路**——域内业务说辞(代码、API、前端文案)一律用「入站」,读代码遇到 receipt 旧名时按本条映射理解。
|
||||
_Avoid_: 把「收料」当作独立业务概念(在途调拨域已统一为入站);未经立项更名 shipping_notice 域保留的 receipt 旧名;新增代码用「收料」指代在途调拨业务
|
||||
@@ -12,7 +12,7 @@
|
||||
- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 入站文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。入站文件仓库列原值随明细落库于 `transfer_invoice_items.movement_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把入站文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
|
||||
- **调拨业务类型(2026-10-14 配置化,取代 2026-09-22 代码枚举)**:调拨类型来自平台配置(表 `transfer_type_configs`,管理端「在途调拨类型」页维护),代码不再枚举类型——类型决定匹配数据范围(范围规则引擎)、仓库取值(仓库定义)与字段转换(如批号前缀替换)。`transfer_runs.transfer_type` CHECK 约束已放开,类型合法性由配置表校验;`transfer_type` 在匹配创建**必填**(缺省/未配置/停用 fail-closed)。配置为空时前端空态 + 匹配 fail-closed(「暂无可用调拨类型」是设计行为,见 §11)。类型、范围规则与转换规则随匹配快照进 `scope_json` 参与匹配 Hash。历史:原三类型枚举(`in_transit_to_hub` 唯一开放 / `hub_repair_out`、`hub_to_hub` 占位「即将上线」)已整体退役,无兼容层。完整模型与上线 SOP 见 §11。
|
||||
- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费匹配/执行 Run/执行 Item 三类 Job。
|
||||
- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。
|
||||
- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。job_params:`transfer_types`(multi_select,选项源 `transfer_types`=启用中的类型配置,**留空=全部启用类型逐轮执行**,恢复复核与类型无关循环外只跑一次,类型配置为空/读取失败 fail-closed 硬失败)、`source_codes`(留空=全部启用入站来源)、`recover_history`(默认开)、`receipt_from/to_offset_days`(T−N 偏移,留空=全部成熟积压,T−2 成熟封顶由匹配层把关)。执行结果通知统一走排程「启用通知」框架完成卡,空数据日(全部类型均无 Run 且无错误)置 `domain_notification_managed` 静默(C5);历史任务级通知人参数 `notify_user_ids` 已移除。
|
||||
|
||||
## 2. 数据库
|
||||
|
||||
|
||||
Reference in new issue
Block a user