feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约

将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。
共享目录与 Worker 契约一次切换至 onhand/inbound/upload,
并补 outbound 骨架与 tt16 排程 job key 迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-17 23:18:48 +08:00
1 parent bf3154033b
commit ffc0d4a430
147 files changed
+4221 -2678

No files matched your search

+2 -2
View File
@@ -343,8 +343,8 @@ def _register_headers_from_config() -> None:
for name, cfg in get_all_schedule_sql_configs().items():
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
from app.services.schedule.freight_onhand_rpa_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_inbound_rpa_finalize import register_receipt_rpa_excel_headers
register_inventory_rpa_excel_headers()
register_receipt_rpa_excel_headers()
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/shipping_receipt_rpa_archive.py
backend/app/services/schedule/freight_inbound_rpa_archive.py
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、
file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。
file_asset_storage、timezone_util、freight_inbound_rpa_finalize.is_freight_receipt_rpa_task。
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
@@ -23,7 +23,7 @@ from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_receipt_rpa_finalize import is_freight_receipt_rpa_task
from app.services.schedule.freight_inbound_rpa_finalize import is_freight_receipt_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
@@ -46,12 +46,12 @@ def get_receipt_archive_dir() -> str:
"""
configured = ''
if current_app:
raw = current_app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR')
raw = current_app.config.get('FREIGHT_RPA_INBOUND_ARCHIVE_DIR')
configured = str(raw).strip() if raw is not None else ''
if not configured:
from app.core.config.settings import Config
configured = str(Config.FREIGHT_RPA_RECEIPT_ARCHIVE_DIR or '').strip()
configured = str(Config.FREIGHT_RPA_INBOUND_ARCHIVE_DIR or '').strip()
archive_dir = Path(configured)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
@@ -229,7 +229,7 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != '.zip':
@@ -250,7 +250,7 @@ def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内;任一不满足则 404。
且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/freight_receipt_rpa_finalize.py
backend/app/services/schedule/freight_inbound_rpa_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。
依赖:ShippingReceiptRpaUnitRun、freight_inbound_rpa_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
"""
@@ -21,7 +21,8 @@ from app.models import ScheduleRun, ScheduleTask
from app.models import ShippingReceiptRpaUnitRun
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.schedule.freight_inbound_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_RECEIPT_RPA_HEADER_ORDER = [
@@ -50,7 +51,7 @@ def register_receipt_rpa_excel_headers() -> None:
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
RECEIPT_RPA_JOB_KEY,
INBOUND_RPA_JOB_KEY,
_RECEIPT_RPA_HEADER_ORDER,
_RECEIPT_RPA_HEADER_LABELS,
)
@@ -94,7 +95,7 @@ def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
return bool(
task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
)
@@ -185,7 +186,7 @@ def report_receipt_batch_progress(payload: dict) -> dict:
Returns:
dict: updated / rejected 及当前计数。
"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
return {'updated': False, 'reason': 'callback_schema_invalid'}
try:
schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None
@@ -233,7 +234,7 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
return {'updated': False, 'reason': 'callback_schema_invalid'}
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
@@ -285,7 +286,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_receipt_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
header_order, header_labels = resolve_schedule_header(INBOUND_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
try:
@@ -314,7 +315,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
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
from app.services.schedule.freight_inbound_rpa_archive import receipt_rpa_result_excel_name
excel_name = receipt_rpa_result_excel_name(run)
run.excel_file_data = excel_data
@@ -330,7 +331,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
'raw_receipt_zip_size': 0,
}
try:
from app.services.schedule.shipping_receipt_rpa_archive import persist_receipt_rpa_raw_zip_archive
from app.services.schedule.freight_inbound_rpa_archive import persist_receipt_rpa_raw_zip_archive
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
except Exception as archive_exc:
@@ -366,7 +367,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
return max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
@@ -376,7 +377,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
return bool(
task
and task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
)
@@ -384,7 +385,7 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
"""
@@ -502,7 +503,7 @@ def recover_all_stale_orphan_receipt_units() -> int:
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
无 started_at 时以 created_at 兜底;注意 run 级 _receipt_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_receipt_unit_with_timeout 收口(failed +
RPA.RECEIPT_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
@@ -1,11 +1,11 @@
"""
backend/app/services/schedule/freight_receipt_rpa_job.py
backend/app/services/schedule/freight_inbound_rpa_job.py
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_receipt_rpa_worker_ready、
ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-receipt-rpa 调用本 handler;写 trigger 前 fail-fast;
逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast;
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
@@ -17,13 +17,13 @@ from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_receipt_rpa_worker_ready,
)
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -139,8 +139,8 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
for unit, trigger_unit in zip(units, trigger_units):
unit.trigger_snapshot_json = trigger_unit
trigger_path = write_receipt_export_batch_trigger(run.run_no, trigger_units, {
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1',
trigger_path = write_inbound_export_batch_trigger(run.run_no, trigger_units, {
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': SCHEMA,
})
if not trigger_path:
for unit in units:
@@ -0,0 +1,18 @@
"""收料原样归档三年到期对象清理(排程壳)。
批次 R Task 10 起,清理能力本体已下沉 freight_rpa.inbound.report_archive
(run_freight_inbound_rpa_retention_schedule,函数名 receipt 词根→inbound);
本文件仅保留排程平台 Job 处理器接缝(job_registry 按 schedule 包路径注册,
Task 11 已随排程壳平移改名为 freight_inbound_rpa_retention,git mv 保留历史)。
"""
from __future__ import annotations
from typing import Any
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。"""
from app.services.freight_rpa.inbound.report_archive import run_freight_inbound_rpa_retention_schedule
return run_freight_inbound_rpa_retention_schedule(task, run)
@@ -1,8 +1,8 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_archive.py
backend/app/services/schedule/freight_onhand_rpa_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
依赖:ScheduleRun、ShippingInventoryFile、freight_onhand_rpa_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
@@ -22,7 +22,7 @@ from flask import current_app
from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.freight_onhand_rpa_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path(
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
current_app.config.get("FREIGHT_RPA_ONHAND_ARCHIVE_DIR")
if current_app
else ""
)
if not str(archive_dir):
from app.core.config.settings import Config
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir = Path(Config.FREIGHT_RPA_ONHAND_ARCHIVE_DIR)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
@@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip":
@@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
且真实路径位于 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -1,9 +1,9 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_finalize.py
backend/app/services/schedule/freight_onhand_rpa_finalize.py
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
逻辑:shipping_inventory_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
逻辑:freight_onhand_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
"""
@@ -21,7 +21,7 @@ from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import normalize_platform_api_path
from app.services.shipping_notice.tool_common import rpa_inventory_timeout_seconds
SHIPPING_INVENTORY_RPA_JOB_KEY = "shipping-inventory-rpa"
ONHAND_RPA_JOB_KEY = "freight-rpa-onhand"
AWAITING_RPA_CALLBACK_STATUS = "awaiting_rpa_callback"
FinalizeScheduleRunResult = dict[str, Any]
@@ -52,7 +52,7 @@ def register_inventory_rpa_excel_headers() -> None:
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
SHIPPING_INVENTORY_RPA_JOB_KEY,
ONHAND_RPA_JOB_KEY,
_INVENTORY_RPA_HEADER_ORDER,
_INVENTORY_RPA_HEADER_LABELS,
)
@@ -78,7 +78,7 @@ def is_shipping_inventory_rpa_task(task: ScheduleTask | None) -> bool:
"""判断是否为货代库存 RPA 平台排程任务。"""
if not task or task.schedule_type != "platform_job":
return False
return normalize_platform_api_path(task.platform_api_path) == SHIPPING_INVENTORY_RPA_JOB_KEY
return normalize_platform_api_path(task.platform_api_path) == ONHAND_RPA_JOB_KEY
def is_awaiting_rpa_callback(step_logs: list | None) -> bool:
@@ -468,7 +468,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
)
register_inventory_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(SHIPPING_INVENTORY_RPA_JOB_KEY)
header_order, header_labels = resolve_schedule_header(ONHAND_RPA_JOB_KEY)
excel_export_ok = True
try:
file_data, file_name, file_size = export_schedule_result_excel(
@@ -495,7 +495,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
status = "partial_failed"
else:
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
from app.services.schedule.freight_onhand_rpa_archive import inventory_rpa_result_excel_name
file_name = inventory_rpa_result_excel_name(run)
@@ -537,7 +537,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"raw_inventory_zip_size": 0,
}
try:
from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive
from app.services.schedule.freight_onhand_rpa_archive import persist_inventory_rpa_raw_zip_archive
archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
except Exception as archive_exc:
@@ -1,10 +1,10 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_job.py
backend/app/services/schedule/freight_onhand_rpa_job.py
用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。
依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用;
写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。
逻辑:platform_api_path=freight-rpa-onhand 时由 job_registry 调用;
写 trigger 后返回 awaiting_rpa_callback;终态由 freight_onhand_rpa_finalize 在 RPA 回调时写入。
"""
from __future__ import annotations
@@ -16,10 +16,10 @@ from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.schedule.freight_onhand_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_inventory_rpa_worker_ready,
)
@@ -1,49 +0,0 @@
"""收料原样归档三年到期对象清理。"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingReceiptReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_expires_at.is_not(None),
ShippingReceiptReportFile.archive_expires_at <= now,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
success = failed = 0
errors: list[str] = []
for report_file in rows:
try:
file_asset_storage.delete_object(report_file.storage_key)
report_file.archive_deleted_at = now
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
failed += 1
db.session.commit()
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
+1 -1
View File
@@ -133,7 +133,7 @@ def validate_task_params(
[STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。
Args:
task_type: platform job key(如 shipping-inventory-rpa)。
task_type: platform job key(如 freight-rpa-onhand)。
job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。
check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。
+10 -10
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
依赖:freight_onhand_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -132,9 +132,9 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_inbound_rpa_retention import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
run_shipping_post_ot_auto_fulfill_compensation_schedule,
@@ -371,7 +371,7 @@ def _register_builtin_platform_jobs() -> None:
defaults={"hash_sample_limit": 500, "dry_run": True, "limit": 1},
))
register_platform_job(PlatformJobDefinition(
key="shipping-inventory-rpa",
key="freight-rpa-onhand",
label="货代库存 RPA",
label_key="admin.schedule.form.platformJobShippingInventory",
handler=run_shipping_inventory_rpa_schedule,
@@ -397,10 +397,10 @@ def _register_builtin_platform_jobs() -> None:
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key="freight-receipt-rpa",
label="货代收料 RPA",
key="freight-rpa-inbound",
label="货代入站 RPA",
handler=run_freight_receipt_rpa_schedule,
description="按计划从已配置收料报表的站点导出并归档收料文件。",
description="按计划从已配置入站报表的站点导出并归档入站文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
@@ -410,9 +410,9 @@ def _register_builtin_platform_jobs() -> None:
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
key='freight-rpa-inbound-retention', label='货代入站归档到期清理',
handler=run_freight_receipt_rpa_retention_schedule,
description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping',
description='仅删除已过三年保留期的入站对象,保留运行、文件事实和审计记录。', category='shipping',
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
))
register_platform_job(PlatformJobDefinition(
@@ -9,8 +9,8 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -19,11 +19,11 @@ from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import (
from app.services.schedule.freight_onhand_rpa_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
from app.services.schedule.freight_inbound_rpa_finalize import (
recover_all_stale_orphan_receipt_units,
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
@@ -332,7 +332,7 @@ def prepare_schedule_queue() -> int:
if not _worker_initialized:
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run
from app.services.schedule.freight_onhand_rpa_finalize import is_awaiting_rpa_schedule_run
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
@@ -358,7 +358,7 @@ def prepare_schedule_queue() -> int:
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
from app.services.freight_rpa.onhand.callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
@@ -379,7 +379,7 @@ def prepare_schedule_queue() -> int:
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_finalize。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_inbound_rpa_finalize。
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_stale:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
@@ -392,7 +392,7 @@ def prepare_schedule_queue() -> int:
current_app.logger.info("[schedule-worker] recovered %d stale orphan receipt RPA units", orphan_stale)
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=False)
except Exception as exc:
@@ -24,12 +24,12 @@ VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTER
LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"})
LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = {
"shipping_inventory_rpa": "shipping-inventory-rpa",
"shipping_inventory_rpa": "freight-rpa-onhand",
"faq_hot_aggregate": "faq-aggregate-hot",
}
# 允许写 ScheduleTaskConfig 的 platform_job(其余平台任务仅存 cron + job key,禁配置)
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"freight-rpa-onhand"})
def platform_job_allows_config(key: str | None) -> bool:
@@ -23,14 +23,14 @@ from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY
from app.services.schedule.shipping_inventory_rpa_finalize import (
from app.services.schedule.freight_inbound_rpa_job import INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_onhand_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
from app.services.schedule.freight_inbound_rpa_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
@@ -106,8 +106,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
"""
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
@@ -137,7 +137,7 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor
if (
task is None
or task.schedule_type != 'platform_job'
or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY
or normalize_platform_api_path(task.platform_api_path) != INBOUND_RPA_JOB_KEY
):
return []
return (
@@ -171,8 +171,8 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
@@ -238,7 +238,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
raw_zip_media_id = None
raw_zip_file_name = None
try:
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
@@ -251,7 +251,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
receipt_zip_media_id = None
receipt_zip_file_name = None
try:
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
receipt_zip_media_id = upload_wecom_temp_media(