feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动

外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-22 00:48:37 +08:00
1 parent 911afa0f73
commit 4c2a7e2a23
145 files changed
+11695 -4214

No files matched your search

@@ -98,7 +98,7 @@ def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
return f"{onhand_rpa_attachment_stem(run)}-结果.xlsx"
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
@@ -107,7 +107,7 @@ def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f"{onhand_rpa_attachment_stem(run)}-库存.zip"
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
@@ -137,12 +137,13 @@ def _iter_packable_inventory_files(
created: list[dict[str, Any]] | None = None,
):
"""
遍历可实际打包的库存快照。
遍历可实际打包的库存文件。
核心逻辑:需存在 FreightRpaOnhandReportFile 且 storage_path 指向可读文件。
核心逻辑:优先 FreightRpaOnhandReportFile(解析入库后);若无 inventory_file_no
则回退 created.file_path(HTTP 文件返回即终态时的收件副本)。
Yields:
tuple[dict, FreightRpaOnhandReportFile, Path]: created 项、快照记录、可读路径。
tuple[dict, FreightRpaOnhandReportFile | None, Path]: created 项、快照记录(可空)、可读路径。
"""
if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
return
@@ -150,22 +151,28 @@ def _iter_packable_inventory_files(
items = _normalize_created_items(created) if created is not None else _api_response_created(run)
for item in items:
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
if not inventory_file_no:
if inventory_file_no:
inv_file = (
db.session.query(FreightRpaOnhandReportFile)
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
.first()
)
if not inv_file:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
continue
inv_file = (
db.session.query(FreightRpaOnhandReportFile)
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
.first()
)
if not inv_file:
# RPA 文件返回即终态:尚无快照号时用回调/收件副本路径打包。
file_path = str(item.get("file_path") or "").strip()
if not file_path:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
storage_path = Path(file_path)
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
yield item, None, storage_path
def inventory_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
@@ -208,8 +215,12 @@ def persist_inventory_rpa_raw_zip_archive(
with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1):
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
source_code = str(item.get("source_code") or inv_file.source_code or "").strip()
warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip()
source_code = str(
item.get("source_code") or (getattr(inv_file, "source_code", None) or "")
).strip()
warehouse_id = str(
item.get("warehouse_id") or (getattr(inv_file, "warehouse_id", None) or "")
).strip()
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
@@ -217,12 +228,16 @@ def persist_inventory_rpa_raw_zip_archive(
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
original_name = (
str(getattr(inv_file, "source_file_name", None) or "").strip()
or storage_path.name
)
files_manifest.append({
"inventory_file_no": inventory_file_no,
"source_code": source_code,
"warehouse_id": warehouse_id,
"file_name": entry_name,
"original_file_name": inv_file.source_file_name or storage_path.name,
"original_file_name": original_name,
})
manifest = {
@@ -2,9 +2,11 @@
backend/app/services/schedule/freight_rpa_onhand_finalize.py
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
逻辑:freight_rpa_onhand_job 写 trigger 后 defer;onhand_rpa_workflow 回调后 finalize;
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common、
freight_rpa.onhand.workflow_protocol(结果状态归一)。
逻辑:freight_rpa_onhand_job 写 trigger 后 defer;HTTP batch-ready 按 RPA 导出结果 finalize
(文件返回即 RPA/排程结束);解析 Job 可后置且不得重新打开 awaiting;
run_task_now / cron 启动前回收超时 awaiting run。
"""
from __future__ import annotations
@@ -111,6 +113,82 @@ def _compute_run_status(*, total_count: int, success_count: int, failed_count: i
return "partial_failed"
def map_rpa_batch_results_for_schedule_finalize(
results: list[Any] | None,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
"""把 Worker batch results 映射为排程 finalize 的 created/failed/skipped。
【AI 触发时机】:HTTP onhand-batch-ready 收件后、入队解析 Job 前调用;
只认 RPA 导出成败(含 file_path),不依赖解析入库后的 inventory_file_no。
Args:
results: Worker 回调 results 列表。
Returns:
(created, failed, skipped):供 finalize_shipping_inventory_schedule_run 使用。
"""
from app.services.freight_rpa.onhand.workflow_protocol import normalize_inventory_batch_item_status
created: list[dict[str, Any]] = []
failed: list[dict[str, Any]] = []
skipped: list[dict[str, Any]] = []
for raw in results or []:
if not isinstance(raw, dict):
continue
source_code = str(raw.get("source_code") or "").strip().upper()
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
status = normalize_inventory_batch_item_status(raw)
if status == "success":
created.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"inventory_file_no": str(raw.get("inventory_file_no") or "").strip(),
"file_path": str(raw.get("file_path") or "").strip(),
})
continue
if status == "skipped":
skipped.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"skip_reason": str(raw.get("skip_reason") or raw.get("reason") or "skipped")[:200],
"message": str(raw.get("message") or raw.get("error_message") or "")[:500],
})
continue
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"error": str(
raw.get("error") or raw.get("error_message") or raw.get("message") or "rpa_export_failed"
)[:500],
})
return created, failed, skipped
def finalize_shipping_inventory_schedule_run_from_rpa_results(
schedule_run_id: int,
payload: dict[str, Any],
) -> FinalizeScheduleRunResult:
"""按 RPA 导出结果终态化排程(文件返回即结束,不等解析)。
核心逻辑:map Worker results → finalize;解析 Job 稍后仍可入库,但不得重新 awaiting。
Args:
schedule_run_id: ScheduleRun 主键。
payload: 已收件的 batch-ready 载荷(含 results)。
Returns:
FinalizeScheduleRunResult: 与 finalize_shipping_inventory_schedule_run 同形。
"""
created, failed, skipped = map_rpa_batch_results_for_schedule_finalize(payload.get("results"))
return finalize_shipping_inventory_schedule_run(
schedule_run_id,
created=created,
failed=failed,
skipped=skipped,
payload=payload,
)
def _build_finalize_details(
pending_details: list[dict[str, Any]],
*,
@@ -8,9 +8,12 @@
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
该偏移参数是自动处理面的唯一日期边界(成熟规则已退役 2026-10-16,
未配置即处理全部圈中数据);空数据日(无 run_no 且无 errors)置
domain_notification_managed 保持静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
该偏移参数是自动处理面的唯一日期边界;【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 或硬失败交由框架完成卡按排程「启用通知」发送。
"""
from __future__ import annotations
@@ -81,9 +84,10 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面
(成熟规则已退役:未配置偏移即处理全部圈中数据);偏移非法(负数/小数/
非数字)快速失败不执行;范围越界由匹配层 ValidationError 落 errors 走硬失败路径。
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
成熟积压,偏移终点 0/1(T−1/当天)由匹配层 ValidationError 落 errors 走
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
Args:
task: 排程任务(job_params: source_codes/recover_history/
+14 -2
View File
@@ -4,6 +4,7 @@ backend/app/services/schedule/query_service.py
用途:排程任务与运行记录的查询/序列化。
依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。
逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。
执行记录日期窗用 coalesce(started_at, created_at),排队中尚未开始的 run 仍落在创建日。
"""
from __future__ import annotations
@@ -159,6 +160,15 @@ def list_runs(
started_before: Optional[datetime] = None,
limit: int = 100,
) -> list[dict]:
"""
按任务、状态与时间窗列出执行记录。
核心逻辑:时间窗比较 coalesce(started_at, created_at)。手动入队时 started_at 仍为空,
若只比 started_at,工作台默认「今天」会把排队中的 run 滤掉,再次点击则因活动 run 冲突。
Returns:
序列化后的运行记录,按 created_at 倒序,最多 500 条。
"""
query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
if task_id is not None:
query = query.filter(ScheduleRun.schedule_task_id == task_id)
@@ -166,10 +176,12 @@ def list_runs(
query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%'))
if status:
query = query.filter(ScheduleRun.status == status)
# 排队 run 还没有 started_at,用创建时间落入同一日期窗,避免工作台看起来像没触发。
activity_at = func.coalesce(ScheduleRun.started_at, ScheduleRun.created_at)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
query = query.filter(activity_at >= _as_naive_utc(started_after))
if started_before is not None:
query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before))
query = query.filter(activity_at < _as_naive_utc(started_before))
if owner_user_id is not None:
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
if notify_user_id is not None: