feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务

- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
hugo committed 2026-10-19 18:45:16 +08:00
1 parent 39fe3c05f2
commit 911afa0f73
152 files changed
+9861 -2984

No files matched your search

+4 -2
View File
@@ -344,10 +344,12 @@ def _register_headers_from_config() -> None:
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_rpa_inbound_finalize import register_receipt_rpa_excel_headers
from app.services.schedule.freight_rpa_inbound_finalize import register_inbound_rpa_excel_headers
from app.services.schedule.freight_rpa_outbound_finalize import register_outbound_rpa_excel_headers
register_inventory_rpa_excel_headers()
register_receipt_rpa_excel_headers()
register_inbound_rpa_excel_headers()
register_outbound_rpa_excel_headers()
def reload_config() -> dict[str, Any]:
@@ -1,11 +1,11 @@
"""
backend/app/services/schedule/freight_rpa_inbound_archive.py
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
用途:货代入站 RPA 排程 run 的原始入站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、FreightRpaInboundReportFile / FreightRpaInboundUnitRun、
file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_receipt_rpa_task。
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_inbound_rpa_task。
逻辑:finalize 调用 persist_inbound_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「入站RPA-日期-时刻-入站」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
"""
@@ -23,23 +23,23 @@ from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_rpa_inbound_finalize import is_freight_receipt_rpa_task
from app.services.schedule.freight_rpa_inbound_finalize import is_freight_inbound_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始入站包不存在,请重新执行或联系管理员'
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
'raw_receipt_zip_available': False,
'raw_receipt_zip_path': None,
'raw_receipt_file_count': 0,
'raw_receipt_file_ids': [],
'raw_receipt_zip_size': 0,
'raw_inbound_zip_available': False,
'raw_inbound_zip_path': None,
'raw_inbound_file_count': 0,
'raw_inbound_file_ids': [],
'raw_inbound_zip_size': 0,
}
def get_receipt_archive_dir() -> str:
def get_inbound_archive_dir() -> str:
"""
返回收料 RPA 原始 ZIP 归档根目录(自动创建)。
返回入站 RPA 原始 ZIP 归档根目录(自动创建)。
核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径,
避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。
@@ -87,9 +87,9 @@ def _attachment_when_from_run(run: ScheduleRun) -> datetime:
return when_utc.astimezone(tz)
def receipt_rpa_attachment_stem(run: ScheduleRun) -> str:
def inbound_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
收料 RPA 企微附件共用前缀:收料RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
入站 RPA 企微附件共用前缀:入站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
@@ -98,29 +98,29 @@ def receipt_rpa_attachment_stem(run: ScheduleRun) -> str:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"收料RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
return f"入站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
def inbound_raw_zip_download_name(run: ScheduleRun) -> str:
"""
收料 ZIP 的企微/浏览器下载展示名。
入站 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
return f'{inbound_rpa_attachment_stem(run)}-入站.zip'
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。"""
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
def inbound_rpa_result_excel_name(run: ScheduleRun) -> str:
"""入站 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。"""
return f'{inbound_rpa_attachment_stem(run)}-结果.xlsx'
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
def _inbound_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
return Path(get_inbound_archive_dir()) / f'{run_no}.zip'
def _iter_packable_receipt_files(run: ScheduleRun):
def _iter_packable_inbound_files(run: ScheduleRun):
"""
遍历该 run 下可打包的收料归档文件。
@@ -129,7 +129,7 @@ def _iter_packable_receipt_files(run: ScheduleRun):
Yields:
FreightRpaInboundReportFile: 可从 MinIO 读取的归档记录。
"""
if not is_freight_receipt_rpa_task(getattr(run, 'task', None)):
if not is_freight_inbound_rpa_task(getattr(run, 'task', None)):
return
rows = (
FreightRpaInboundReportFile.query.join(
@@ -147,35 +147,35 @@ def _iter_packable_receipt_files(run: ScheduleRun):
yield report_file
def receipt_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
def inbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
"""
从 response_summary_json 读取原始收料 ZIP 是否可下载。
从 response_summary_json 读取原始入站 ZIP 是否可下载。
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
"""
if not isinstance(summary, dict):
return False
return bool(summary.get('raw_receipt_zip_available'))
return bool(summary.get('raw_inbound_zip_available'))
def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
def persist_inbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
"""
finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。
finalize 阶段预生成原始入站 ZIP 归档并返回 summary 字段。
核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 <archive_dir>/<run_no>.zip
(含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。
(含 manifest.json);无可用文件时返回 raw_inbound_zip_available=false。
Args:
run: 收料 RPA ScheduleRun。
run: 入站 RPA ScheduleRun。
Returns:
dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。
dict: raw_inbound_zip_available / path / file_count / file_ids / zip_size。
"""
packable_files = list(_iter_packable_receipt_files(run))
packable_files = list(_iter_packable_inbound_files(run))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _receipt_raw_zip_archive_path(run.run_no)
archive_path = _inbound_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, Any]] = []
with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
@@ -217,15 +217,15 @@ def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
)
return {
'raw_receipt_zip_available': True,
'raw_receipt_zip_path': str(archive_path.resolve()),
'raw_receipt_file_count': len(files_manifest),
'raw_receipt_file_ids': [item['file_id'] for item in files_manifest],
'raw_receipt_zip_size': int(archive_path.stat().st_size),
'raw_inbound_zip_available': True,
'raw_inbound_zip_path': str(archive_path.resolve()),
'raw_inbound_file_count': len(files_manifest),
'raw_inbound_file_ids': [item['file_id'] for item in files_manifest],
'raw_inbound_zip_size': int(archive_path.stat().st_size),
}
def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
def _is_allowed_inbound_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
@@ -237,7 +237,7 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
if not resolved.is_file():
return False
archive_dir = Path(get_receipt_archive_dir()).resolve()
archive_dir = Path(get_inbound_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
@@ -245,11 +245,11 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
return True
def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
def resolve_inbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。
解析 run 已归档的原始入站 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、
核心逻辑:读取 summary.raw_inbound_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
@@ -259,18 +259,18 @@ def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not receipt_raw_zip_available_from_summary(summary):
if not inbound_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get('raw_receipt_zip_path') or '').strip()
zip_path_raw = str(summary.get('raw_inbound_zip_path') or '').strip()
if not zip_path_raw:
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path = Path(zip_path_raw)
if not _is_allowed_receipt_archive_path(zip_path):
if not _is_allowed_inbound_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), receipt_raw_zip_download_name(run)
return zip_path.resolve(), inbound_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
@@ -1,7 +1,7 @@
"""
backend/app/services/schedule/freight_rpa_inbound_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
用途:独立入站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
@@ -21,7 +21,7 @@ from app.models import ScheduleRun, ScheduleTask
from app.models import FreightRpaInboundUnitRun
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_rpa_inbound_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_rpa_inbound_job import AWAITING_INBOUND_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
@@ -29,25 +29,25 @@ _RECEIPT_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"connector_type",
"receipt_file_count",
"inbound_file_count",
"export_status",
"skip_reason",
"error_message",
]
_RECEIPT_RPA_HEADER_LABELS = {
"source_code": "收料源",
"source_code": "入站源",
"warehouse_id": "仓库",
"connector_type": "连接器",
"receipt_file_count": "归档文件数",
"inbound_file_count": "归档文件数",
"export_status": "导出状态",
"skip_reason": "跳过原因",
"error_message": "错误原因",
}
def register_receipt_rpa_excel_headers() -> None:
def register_inbound_rpa_excel_headers() -> None:
"""
注册货代收料 RPA 排程 Excel 列头(幂等)。
注册货代入站 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
@@ -57,15 +57,15 @@ def register_receipt_rpa_excel_headers() -> None:
)
def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]:
def _build_inbound_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]:
"""
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
入站单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致;
归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。
归档文件数便于与原始入站包内 {序号}_{source_code}.xlsx 条目对账。
Args:
units: 该 run 的全部收料单元(已全部终态)。
units: 该 run 的全部入站单元(已全部终态)。
Returns:
list[dict]: 按 unit.id 升序的明细行。
@@ -83,7 +83,7 @@ def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> li
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id or '',
'connector_type': unit.connector_type or '',
'receipt_file_count': len(unit.files or []),
'inbound_file_count': len(unit.files or []),
'export_status': export_status,
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
@@ -91,25 +91,25 @@ def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> li
return rows
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
def should_defer_inbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立入站 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
return bool(
task.schedule_type == 'platform_job'
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 [])
and any(isinstance(row, dict) and row.get('status') == AWAITING_INBOUND_RPA_CALLBACK_STATUS for row in step_logs or [])
)
def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。"""
def is_awaiting_inbound_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立入站 callback 等待态,供 worker 启动恢复时保护。"""
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa'))
return bool(run is not None and run.status == 'running' and summary.get('awaiting_inbound_rpa'))
def apply_deferred_receipt_schedule_run_state(
def apply_deferred_inbound_schedule_run_state(
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
) -> ScheduleRun:
"""将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。"""
"""将收料 run 保持为 awaiting callback,终态由所有入站单元回调完成后专用服务写入。"""
run.status = 'running'
run.started_at = run.started_at or datetime.utcnow()
run.total_count = total_count
@@ -118,18 +118,18 @@ def apply_deferred_receipt_schedule_run_state(
run.skipped_count = 0
run.finished_at = None
run.step_logs = step_logs
run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]}
run.response_summary_json = {'awaiting_inbound_rpa': True, 'pending_details': details, 'errors': errors[:20]}
db.session.commit()
return run
def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
def refresh_inbound_schedule_run_progress(schedule_run_id: int) -> dict:
"""
收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
入站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入
核心逻辑:仅在 awaiting_inbound_rpa 时,按已终态单元聚合 success/empty/failed 写入
ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at,
终态仍由 finalize_receipt_schedule_run_if_complete 负责。
终态仍由 finalize_inbound_schedule_run_if_complete 负责。
Args:
schedule_run_id: 排程执行记录主键。
@@ -141,8 +141,8 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
if run.status != 'running' or not summary.get('awaiting_inbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_inbound_callback'}
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
success_count = sum(unit.status == 'success' for unit in units)
@@ -173,11 +173,11 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
}
def report_receipt_batch_progress(payload: dict) -> dict:
def report_inbound_batch_progress(payload: dict) -> dict:
"""
Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
Worker 每完成一笔入站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_inbound_rpa 时抬升
ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。
Args:
@@ -199,8 +199,8 @@ def report_receipt_batch_progress(payload: dict) -> dict:
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
if run.status != 'running' or not summary.get('awaiting_inbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_inbound_callback'}
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
@@ -228,9 +228,9 @@ def report_receipt_batch_progress(payload: dict) -> dict:
}
def mark_receipt_unit_processing(payload: dict) -> dict:
def mark_inbound_unit_processing(payload: dict) -> dict:
"""
Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。
Worker 开始导出某入站单元时标记 processing(对齐库存 claimed / rpa_exporting)。
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
"""
@@ -247,27 +247,27 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
# started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有
# started_at 是入站超时对账的活动锚(_inbound_last_activity):在飞单元必须有
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
unit.started_at = datetime.utcnow()
db.session.commit()
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
refresh_inbound_schedule_run_progress(unit.schedule_run_id)
return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id}
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
def finalize_inbound_schedule_run_if_complete(schedule_run_id: int) -> dict:
"""
当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。
核心逻辑:聚合单元计数 → 预生成原始收料 ZIP 写入 summary → 企微发 textcard+单 ZIP。
核心逻辑:聚合单元计数 → 预生成原始入站 ZIP 写入 summary → 企微发 textcard+单 ZIP。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'finalized': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
if not summary.get('awaiting_inbound_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_inbound_callback'}
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
terminal = {'success', 'empty', 'failed', 'cancelled'}
if any(unit.status not in terminal for unit in units):
@@ -284,8 +284,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_receipt_rpa_excel_headers()
# [STEP] 对齐库存 finalize:终态前生成入站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_inbound_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(INBOUND_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
@@ -300,49 +300,49 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
'failed_count': failed_count,
'duration_ms': run.duration_ms,
},
details=_build_receipt_finalize_details(units),
details=_build_inbound_finalize_details(units),
header_order=header_order,
header_labels=header_labels,
)
except Exception as excel_exc:
excel_export_ok = False
current_app.logger.error(
'[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc,
'[schedule-run] inbound RPA excel export failed for run %s: %s', run.run_no, excel_exc,
)
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
if run.status == 'success':
run.status = 'partial_failed'
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_rpa_inbound_archive import receipt_rpa_result_excel_name
# 企微/下载展示名:入站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_rpa_inbound_archive import inbound_rpa_result_excel_name
excel_name = receipt_rpa_result_excel_name(run)
excel_name = inbound_rpa_result_excel_name(run)
run.excel_file_data = excel_data
run.excel_file_name = excel_name if excel_data else None
run.excel_file_size = excel_size or 0
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
# [STEP] 对齐库存:终态前预生成原始入站 ZIP,企微只发一个包。
archive_summary = {
'raw_receipt_zip_available': False,
'raw_receipt_zip_path': None,
'raw_receipt_file_count': 0,
'raw_receipt_file_ids': [],
'raw_receipt_zip_size': 0,
'raw_inbound_zip_available': False,
'raw_inbound_zip_path': None,
'raw_inbound_file_count': 0,
'raw_inbound_file_ids': [],
'raw_inbound_zip_size': 0,
}
try:
from app.services.schedule.freight_rpa_inbound_archive import persist_receipt_rpa_raw_zip_archive
from app.services.schedule.freight_rpa_inbound_archive import persist_inbound_rpa_raw_zip_archive
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
archive_summary = persist_inbound_rpa_raw_zip_archive(run)
except Exception as archive_exc:
current_app.logger.error(
'[schedule-run] receipt RPA zip archive failed for run %s: %s',
'[schedule-run] inbound RPA zip archive failed for run %s: %s',
run.run_no, archive_exc,
)
run.response_summary_json = {
**summary,
'awaiting_receipt_rpa': False,
'awaiting_inbound_rpa': False,
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
@@ -351,7 +351,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
**archive_summary,
}
db.session.commit()
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+入站 ZIP。
try:
task = run.task
if task is not None and task.notify_enabled:
@@ -360,20 +360,20 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
_notify_schedule_run_wecom(task, run)
db.session.commit()
except Exception as wecom_exc:
current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc)
current_app.logger.error('[schedule-run] inbound RPA wecom notify failed: %s', wecom_exc)
return {'finalized': True, 'status': run.status}
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
def _inbound_timeout_seconds() -> int:
"""读取入站回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。"""
def is_freight_inbound_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立入站 RPA 排程,避免超时回收影响库存或其他平台任务。"""
return bool(
task
and task.schedule_type == 'platform_job'
@@ -381,7 +381,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
)
def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime:
def _inbound_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime:
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
@@ -398,18 +398,18 @@ def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRu
return max(stamps)
def _fail_receipt_unit_with_timeout(
def _fail_inbound_unit_with_timeout(
unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个收料单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
"""单个入站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿
单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit,
事务归属调用方。
Args:
unit: 待收口的非终态收料单元。
unit: 待收口的非终态入站单元。
now: 收口时刻(同批单元共享同一时间戳)。
timeout_seconds: 超时窗(写入错误文案与审计 metadata)。
run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。
@@ -418,8 +418,8 @@ def _fail_receipt_unit_with_timeout(
"""
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
unit.error_code = 'RPA.INBOUND_CALLBACK_TIMEOUT'
unit.error_message = f'Inbound RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_inbound_rpa_callback_timeout', aggregate_type='shipping_inbound_unit',
@@ -430,46 +430,46 @@ def _fail_receipt_unit_with_timeout(
)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
def _recover_stale_inbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立入站运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at——
截止判据为最后活动锚(_inbound_last_activity)而非 run.started_at——
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at:
if not summary.get('awaiting_inbound_rpa') or run.status != 'running' or not run.started_at:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_receipt_rpa_task(task):
if not is_freight_inbound_rpa_task(task):
return False
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _receipt_last_activity(run, units) > cutoff:
if _inbound_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
_fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
_fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
run.status = 'failed'
run.finished_at = now
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)'
run.error_message = f'入站 RPA 回调等待超时({timeout_seconds} 秒)'
run.step_logs = [*(run.step_logs or []), {
'step': 'freight_receipt_rpa', 'status': 'failed',
'step': 'freight_inbound_rpa', 'status': 'failed',
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
}]
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'}
run.response_summary_json = {**summary, 'awaiting_inbound_rpa': False, 'recovered_reason': 'inbound_rpa_callback_timeout'}
return True
def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_receipt_rpa_task(task):
def recover_stale_inbound_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一入站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_inbound_rpa_task(task):
return 0
timeout_seconds = _receipt_timeout_seconds()
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
_recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
)
if recovered:
@@ -477,12 +477,12 @@ def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
return recovered
def recover_all_stale_receipt_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。"""
timeout_seconds = _receipt_timeout_seconds()
def recover_all_stale_inbound_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时入站回调,避免重启后运行永久卡住。"""
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
_recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(status='running').all()
)
if recovered:
@@ -490,30 +490,30 @@ def recover_all_stale_receipt_rpa_schedule_runs() -> int:
return recovered
def recover_all_stale_orphan_receipt_units() -> int:
"""回收按需触发(无排程绑定)的超时收料单元,解除来源投影永久 fetching。
def recover_all_stale_orphan_inbound_units() -> int:
"""回收按需触发(无排程绑定)的超时入站单元,解除来源投影永久 fetching。
【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台
重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 inbound_trigger_service),
不在 run 级扫描(recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;
不在 run 级扫描(recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内;
Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status)
永久 fetching、前端重试按钮永久锁死(2026-10-16 事故根因)。
核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
无 started_at 时以 created_at 兜底;注意 run 级 _receipt_last_activity 是
无 started_at 时以 created_at 兜底;注意 run 级 _inbound_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_inbound_rpa_unit)
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_receipt_unit_with_timeout 收口(failed +
RPA.RECEIPT_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
[STEP 2] 逐单元经 _fail_inbound_unit_with_timeout 收口(failed +
RPA.INBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」
(与 recover_stale_waiting_source_jobs 口径一致)。
Returns:
本次回收的单元数。
"""
timeout_seconds = _receipt_timeout_seconds()
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
FreightRpaInboundUnitRun.query
@@ -528,6 +528,6 @@ def recover_all_stale_orphan_receipt_units() -> int:
return 0
now = datetime.utcnow()
for unit in orphans:
_fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
_fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
db.session.commit()
return len(orphans)
@@ -1,12 +1,12 @@
"""
backend/app/services/schedule/freight_rpa_inbound_job.py
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_receipt_rpa_worker_ready、
用途:独立入站 RPA 排程——按勾选来源站点一对一冻结执行单元并写 inbound trigger。
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_inbound_rpa_worker_ready、
FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaInboundUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast;
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
口径与 onhand 排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
from __future__ import annotations
@@ -20,16 +20,16 @@ from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaIn
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,
assert_inbound_rpa_worker_ready,
)
INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
AWAITING_INBOUND_RPA_CALLBACK_STATUS = 'awaiting_inbound_rpa_callback'
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _wanted_source_codes(task: ScheduleTask) -> set[str]:
"""提取结构化 source_codes;留空代表全部具备有效收料配置的站点。"""
"""提取结构化 source_codes;留空代表全部具备有效入站配置的站点。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
values = params.get('source_codes') or []
if isinstance(values, str):
@@ -38,7 +38,7 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]:
def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]:
"""读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
"""读取已启用且已配置入站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
@@ -47,7 +47,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, Freigh
def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]:
"""浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
"""浅拷贝入站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
if isinstance(item, dict)
@@ -57,8 +57,8 @@ def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[s
def _build_unit(
source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int,
) -> FreightRpaInboundUnitRun:
"""冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
"""冻结可审计的入站执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'inbound:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
@@ -98,27 +98,27 @@ def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]:
}
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
def run_freight_rpa_inbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。
写独立入站 trigger;每个勾选站点对应一个执行单元(与 onhand RPA 同口径)。
核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_receipt_rpa。
核心逻辑:写 trigger 前 assert_inbound_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_inbound_rpa。
"""
units: list[FreightRpaInboundUnitRun] = [
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
]
if not units:
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
return 0, 0, 0, 1, [], ['no enabled inbound report sources'], [{'step': 'freight_inbound_rpa', 'status': 'skipped'}]
# [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。
try:
assert_receipt_rpa_worker_ready()
assert_inbound_rpa_worker_ready()
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get('detail_message') or message)
return len(units), 0, len(units), 0, [], [detail_message], [{
'step': 'freight_receipt_rpa',
'step': 'freight_inbound_rpa',
'status': 'failed',
'detail': {
'message': message,
@@ -134,9 +134,9 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
except RuntimeError as exc:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
db.session.commit()
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_inbound_rpa', 'status': 'failed'}]
for unit, trigger_unit in zip(units, trigger_units):
unit.trigger_snapshot_json = trigger_unit
trigger_path = write_inbound_export_batch_trigger(run.run_no, trigger_units, {
@@ -144,13 +144,13 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
})
if not trigger_path:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable'
unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'inbound trigger directory unavailable'
db.session.commit()
return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
return len(units), 0, len(units), 0, [], ['inbound trigger directory unavailable'], [{'step': 'freight_inbound_rpa', 'status': 'failed'}]
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
db.session.commit()
return len(units), 0, 0, 0, details, [], [{
'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS,
'step': 'freight_inbound_rpa', 'status': AWAITING_INBOUND_RPA_CALLBACK_STATUS,
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
}]
@@ -11,8 +11,13 @@ 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_rpa_inbound_retention_schedule
def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。
return run_freight_rpa_inbound_retention_schedule(task, run)
核心逻辑:本函数与 archive 同名;必须 as 别名导入,避免递归调用自身。
"""
from app.services.freight_rpa.inbound.report_archive import (
run_freight_rpa_inbound_retention_schedule as _run_inbound_archive_retention,
)
return _run_inbound_archive_retention(task, run)
@@ -0,0 +1,311 @@
"""
backend/app/services/schedule/freight_rpa_outbound_archive.py
用途:货代出站 RPA 排程 run 的原始出站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun、
file_asset_storage、timezone_util、freight_rpa_outbound_finalize.is_freight_outbound_rpa_task。
逻辑:finalize 调用 persist_outbound_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「出站RPA-日期-时刻-出站」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
"""
from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_rpa_outbound_finalize import is_freight_outbound_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始出站包不存在,请重新执行或联系管理员'
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
'raw_outbound_zip_available': False,
'raw_outbound_zip_path': None,
'raw_outbound_file_count': 0,
'raw_outbound_file_ids': [],
'raw_outbound_zip_size': 0,
}
def get_outbound_archive_dir() -> str:
"""
返回出站 RPA 原始 ZIP 归档根目录(自动创建)。
核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径,
避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。
"""
configured = ''
if current_app:
raw = current_app.config.get('FREIGHT_RPA_OUTBOUND_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_OUTBOUND_ARCHIVE_DIR or '').strip()
archive_dir = Path(configured)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的当地时刻。
核心逻辑:与库存归档同构——started_at → created_at → finished_at →
解析 RUN{yyyyMMddHHmmss}* → utcnow;再转到任务 schedule_timezone。
"""
when_utc: datetime | None = None
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
when_utc = value
break
if when_utc is None:
match = re.match(r'^RUN(\d{14})', str(run.run_no or '').strip())
if match:
try:
when_utc = datetime.strptime(match.group(1), '%Y%m%d%H%M%S')
except ValueError:
when_utc = None
if when_utc is None:
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
task = getattr(run, 'task', None)
tz_name = getattr(task, 'schedule_timezone', None) if task is not None else None
tz = resolve_schedule_tzinfo(tz_name)
if when_utc.tzinfo is None:
when_utc = when_utc.replace(tzinfo=timezone.utc)
return when_utc.astimezone(tz)
def outbound_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
出站 RPA 企微附件共用前缀:出站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
Returns:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"出站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def outbound_raw_zip_download_name(run: ScheduleRun) -> str:
"""
出站 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f'{outbound_rpa_attachment_stem(run)}-出站.zip'
def outbound_rpa_result_excel_name(run: ScheduleRun) -> str:
"""出站 RPA 结果 Excel 的企微/下载展示名(对齐入站 inbound_rpa_result_excel_name)。"""
return f'{outbound_rpa_attachment_stem(run)}-结果.xlsx'
def _outbound_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_outbound_archive_dir()) / f'{run_no}.zip'
def _iter_packable_outbound_files(run: ScheduleRun):
"""
遍历该 run 下可打包的出站归档文件。
核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。
Yields:
FreightRpaOutboundReportFile: 可从 MinIO 读取的归档记录。
"""
if not is_freight_outbound_rpa_task(getattr(run, 'task', None)):
return
rows = (
FreightRpaOutboundReportFile.query.join(
FreightRpaOutboundUnitRun,
FreightRpaOutboundReportFile.unit_run_id == FreightRpaOutboundUnitRun.id,
)
.filter(
FreightRpaOutboundUnitRun.schedule_run_id == run.id,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
)
.order_by(FreightRpaOutboundReportFile.id.asc())
.all()
)
for report_file in rows:
yield report_file
def outbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
"""
从 response_summary_json 读取原始出站 ZIP 是否可下载。
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
"""
if not isinstance(summary, dict):
return False
return bool(summary.get('raw_outbound_zip_available'))
def persist_outbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
"""
finalize 阶段预生成原始出站 ZIP 归档并返回 summary 字段。
核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 <archive_dir>/<run_no>.zip
(含 manifest.json);无可用文件时返回 raw_outbound_zip_available=false。
Args:
run: 出站 RPA ScheduleRun。
Returns:
dict: raw_outbound_zip_available / path / file_count / file_ids / zip_size。
"""
packable_files = list(_iter_packable_outbound_files(run))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _outbound_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, Any]] = []
with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, report_file in enumerate(packable_files, start=1):
unit = report_file.unit_run
source_code = str(getattr(unit, 'source_code', None) or '').strip()
warehouse_id = str(getattr(unit, 'warehouse_id', None) or '').strip()
original_name = str(report_file.original_filename or '').strip() or 'outbound.xlsx'
suffix = Path(original_name).suffix or '.xlsx'
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
original_suffix=suffix,
)
# [STEP] 出站归档在 MinIO:读字节后 writestr,不依赖本地 storage_path。
data = file_asset_storage.get_bytes(report_file.storage_key)
archive.writestr(entry_name, data)
files_manifest.append({
'file_id': report_file.id,
'source_code': source_code,
'warehouse_id': warehouse_id,
'file_name': entry_name,
'original_file_name': original_name,
'sha256': report_file.sha256,
})
manifest = {
'run_no': run.run_no,
'total_count': int(run.total_count or 0),
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'files': files_manifest,
}
archive.writestr(
'manifest.json',
json.dumps(manifest, ensure_ascii=False, indent=2),
)
return {
'raw_outbound_zip_available': True,
'raw_outbound_zip_path': str(archive_path.resolve()),
'raw_outbound_file_count': len(files_manifest),
'raw_outbound_file_ids': [item['file_id'] for item in files_manifest],
'raw_outbound_zip_size': int(archive_path.stat().st_size),
}
def _is_allowed_outbound_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != '.zip':
return False
if not resolved.is_file():
return False
archive_dir = Path(get_outbound_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
return False
return True
def resolve_outbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始出站 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_outbound_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
Raises:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not outbound_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get('raw_outbound_zip_path') or '').strip()
if not zip_path_raw:
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path = Path(zip_path_raw)
if not _is_allowed_outbound_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), outbound_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
"""ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
cleaned = re.sub(r'[^\w\-.]+', '_', str(value or '').strip())
return cleaned or 'unknown'
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
"""
包内短标签:优先 source_code;无则回退仓码;再否则 outbound。
warehouse_id / file_id 已写入 manifest.json;条目名不必再叠仓码。
"""
source = str(source_code or '').strip()
if source:
return source
warehouse = str(warehouse_id or '').strip()
if warehouse and warehouse.lower() not in {'unknown', 'na'}:
return warehouse
return 'outbound'
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
original_suffix: str,
) -> str:
"""
生成 ZIP 内单文件条目名(不含目录)。
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
"""
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
suffix = original_suffix if original_suffix.startswith('.') else f'.{original_suffix}'
return f'{index:03d}_{label}{suffix}'
@@ -0,0 +1,532 @@
"""
backend/app/services/schedule/freight_rpa_outbound_finalize.py
用途:独立出站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:FreightRpaOutboundUnitRun、freight_rpa_outbound_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy import func
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import FreightRpaOutboundUnitRun
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_rpa_outbound_job import AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, OUTBOUND_RPA_JOB_KEY
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_OUTBOUND_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"connector_type",
"outbound_file_count",
"export_status",
"skip_reason",
"error_message",
]
_OUTBOUND_RPA_HEADER_LABELS = {
"source_code": "出站源",
"warehouse_id": "仓库",
"connector_type": "连接器",
"outbound_file_count": "归档文件数",
"export_status": "导出状态",
"skip_reason": "跳过原因",
"error_message": "错误原因",
}
def register_outbound_rpa_excel_headers() -> None:
"""
注册货代出站 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
OUTBOUND_RPA_JOB_KEY,
_OUTBOUND_RPA_HEADER_ORDER,
_OUTBOUND_RPA_HEADER_LABELS,
)
def _build_outbound_finalize_details(units: list[FreightRpaOutboundUnitRun]) -> list[dict[str, Any]]:
"""
出站单元 → 排程 Excel 明细行(对齐入站 finalize 的行结构)。
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片计数口径一致;
归档文件数便于与原始出站包内 {序号}_{source_code}.xlsx 条目对账。
Args:
units: 该 run 的全部出站单元(已全部终态)。
Returns:
list[dict]: 按 unit.id 升序的明细行。
"""
rows: list[dict[str, Any]] = []
for unit in sorted(units, key=lambda item: item.id):
status = unit.status
if status == 'empty':
export_status = 'skipped'
elif status == 'cancelled':
export_status = 'failed'
else:
export_status = status
rows.append({
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id or '',
'connector_type': unit.connector_type or '',
'outbound_file_count': len(unit.files or []),
'export_status': export_status,
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
})
return rows
def should_defer_outbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立出站 job 成功写入 trigger 后延后终态,避免影响库存/入站 job 判断。"""
return bool(
task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY
and any(isinstance(row, dict) and row.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS for row in step_logs or [])
)
def is_awaiting_outbound_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立出站 callback 等待态,供 worker 启动恢复时保护。"""
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
return bool(run is not None and run.status == 'running' and summary.get('awaiting_outbound_rpa'))
def apply_deferred_outbound_schedule_run_state(
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
) -> ScheduleRun:
"""将出站 run 保持为 awaiting callback,终态由所有出站单元回调完成后专用服务写入。"""
run.status = 'running'
run.started_at = run.started_at or datetime.utcnow()
run.total_count = total_count
run.success_count = 0
run.failed_count = 0
run.skipped_count = 0
run.finished_at = None
run.step_logs = step_logs
run.response_summary_json = {'awaiting_outbound_rpa': True, 'pending_details': details, 'errors': errors[:20]}
db.session.commit()
return run
def refresh_outbound_schedule_run_progress(schedule_run_id: int) -> dict:
"""
出站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
核心逻辑:仅在 awaiting_outbound_rpa 时,按已终态单元聚合 success/empty/failed 写入
ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at,
终态仍由 finalize_outbound_schedule_run_if_complete 负责。
Args:
schedule_run_id: 排程执行记录主键。
Returns:
dict: updated=True/False 及当前计数;非等待态返回 reason。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_outbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_outbound_callback'}
units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
# [STEP] 与库存进度同口径:只抬升计数,防乱序回调把笔数打回去。
run.success_count = max(int(run.success_count or 0), success_count)
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
run.failed_count = max(int(run.failed_count or 0), failed_count)
if run.total_count is None or int(run.total_count or 0) < len(units):
run.total_count = len(units)
summary = dict(summary)
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'processing_count': sum(unit.status == 'processing' for unit in units),
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return {
'updated': True,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def report_outbound_batch_progress(payload: dict) -> dict:
"""
Worker 每完成一笔出站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_outbound_rpa 时抬升
ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。
Args:
payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。
Returns:
dict: updated / rejected 及当前计数。
"""
if payload.get('schema_version') != OUTBOUND_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
except (TypeError, ValueError):
schedule_run_id = None
if not schedule_run_id:
return {'updated': False, 'reason': 'schedule_run_id_required'}
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_outbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_outbound_callback'}
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
'failed_count': max(0, int(payload.get('failed_count') or 0)),
}
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
summary = dict(summary)
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': str(payload.get('batch_run_no') or payload.get('run_no') or ''),
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return {
'updated': True,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def mark_outbound_unit_processing(payload: dict) -> dict:
"""
Worker 开始导出某出站单元时标记 processing(对齐库存 claimed / rpa_exporting)。
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
"""
if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA:
return {'updated': False, 'reason': 'callback_schema_invalid'}
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return {'updated': False, 'reason': 'callback_id_required'}
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
return {'updated': False, 'reason': 'unit_not_found'}
if unit.status in {'success', 'empty', 'failed', 'cancelled'}:
return {'updated': False, 'reason': 'already_terminal', 'status': unit.status}
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
# started_at 是出站超时对账的活动锚(_outbound_last_activity):在飞单元必须有
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
unit.started_at = datetime.utcnow()
db.session.commit()
if unit.schedule_run_id:
refresh_outbound_schedule_run_progress(unit.schedule_run_id)
return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id}
def finalize_outbound_schedule_run_if_complete(schedule_run_id: int) -> dict:
"""
当出站 run 的全部单元已回调后写入独立排程终态,不读取库存/入站回调结果。
核心逻辑:聚合单元计数 → 预生成原始出站 ZIP 写入 summary → 企微发 textcard+单 ZIP。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'finalized': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_outbound_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_outbound_callback'}
units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
terminal = {'success', 'empty', 'failed', 'cancelled'}
if any(unit.status not in terminal for unit in units):
return {'finalized': False, 'reason': 'units_pending'}
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
run.total_count = len(units)
run.success_count = success_count
run.skipped_count = skipped_count
run.failed_count = failed_count
run.finished_at = datetime.utcnow()
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
# [STEP] 对齐入站 finalize:终态前生成出站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_outbound_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(OUTBOUND_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
try:
excel_data, _excel_name, excel_size = export_schedule_result_excel(
run_no=run.run_no,
summary={
'status': run.status,
'total_count': len(units),
'success_count': success_count,
'skipped_count': skipped_count,
'failed_count': failed_count,
'duration_ms': run.duration_ms,
},
details=_build_outbound_finalize_details(units),
header_order=header_order,
header_labels=header_labels,
)
except Exception as excel_exc:
excel_export_ok = False
current_app.logger.error(
'[schedule-run] outbound RPA excel export failed for run %s: %s', run.run_no, excel_exc,
)
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
if run.status == 'success':
run.status = 'partial_failed'
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:出站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_rpa_outbound_archive import outbound_rpa_result_excel_name
excel_name = outbound_rpa_result_excel_name(run)
run.excel_file_data = excel_data
run.excel_file_name = excel_name if excel_data else None
run.excel_file_size = excel_size or 0
# [STEP] 对齐入站:终态前预生成原始出站 ZIP,企微只发一个包。
archive_summary = {
'raw_outbound_zip_available': False,
'raw_outbound_zip_path': None,
'raw_outbound_file_count': 0,
'raw_outbound_file_ids': [],
'raw_outbound_zip_size': 0,
}
try:
from app.services.schedule.freight_rpa_outbound_archive import persist_outbound_rpa_raw_zip_archive
archive_summary = persist_outbound_rpa_raw_zip_archive(run)
except Exception as archive_exc:
current_app.logger.error(
'[schedule-run] outbound RPA zip archive failed for run %s: %s',
run.run_no, archive_exc,
)
run.response_summary_json = {
**summary,
'awaiting_outbound_rpa': False,
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
'excel_export_status': 'ok' if excel_export_ok else 'failed',
'excel_failed': not excel_export_ok,
**archive_summary,
}
db.session.commit()
# 通知与入站 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+出站 ZIP。
try:
task = run.task
if task is not None and task.notify_enabled:
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
_notify_schedule_run_wecom(task, run)
db.session.commit()
except Exception as wecom_exc:
current_app.logger.error('[schedule-run] outbound RPA wecom notify failed: %s', wecom_exc)
return {'finalized': True, 'status': run.status}
def _outbound_timeout_seconds() -> int:
"""读取出站回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
def is_freight_outbound_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立出站 RPA 排程,避免超时回收影响库存或其他平台任务。"""
return bool(
task
and task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY
)
def _outbound_last_activity(run: ScheduleRun, units: list[FreightRpaOutboundUnitRun]) -> datetime:
"""出站 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
"""
stamps = [run.started_at] if run.started_at else []
for unit in units:
if unit.started_at:
stamps.append(unit.started_at)
if unit.finished_at:
stamps.append(unit.finished_at)
return max(stamps)
def _fail_outbound_unit_with_timeout(
unit: FreightRpaOutboundUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个出站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿
单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit,
事务归属调用方。
Args:
unit: 待收口的非终态出站单元。
now: 收口时刻(同批单元共享同一时间戳)。
timeout_seconds: 超时窗(写入错误文案与审计 metadata)。
run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。
Returns:
None。
"""
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.OUTBOUND_CALLBACK_TIMEOUT'
unit.error_message = f'Outbound RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_outbound_rpa_callback_timeout', aggregate_type='shipping_outbound_unit',
aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery',
unit_id=unit.id, result='failure', before=before,
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'timeout_seconds': timeout_seconds},
)
def _recover_stale_outbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立出站运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_outbound_last_activity)而非 run.started_at——
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_outbound_rpa') or run.status != 'running' or not run.started_at:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_outbound_rpa_task(task):
return False
units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _outbound_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
_fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
run.status = 'failed'
run.finished_at = now
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
run.error_message = f'出站 RPA 回调等待超时({timeout_seconds} 秒)'
run.step_logs = [*(run.step_logs or []), {
'step': 'freight_outbound_rpa', 'status': 'failed',
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
}]
run.response_summary_json = {**summary, 'awaiting_outbound_rpa': False, 'recovered_reason': 'outbound_rpa_callback_timeout'}
return True
def recover_stale_outbound_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一出站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_outbound_rpa_task(task):
return 0
timeout_seconds = _outbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
)
if recovered:
db.session.commit()
return recovered
def recover_all_stale_outbound_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时出站回调,避免重启后运行永久卡住。"""
timeout_seconds = _outbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(status='running').all()
)
if recovered:
db.session.commit()
return recovered
def recover_all_stale_orphan_outbound_units() -> int:
"""回收按需触发(无排程绑定)的超时出站单元,解除来源投影永久 fetching。
【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台
重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 outbound_trigger_service),
不在 run 级扫描(recover_all_stale_outbound_rpa_schedule_runs 按 run 遍历)范围内;
Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status)
永久 fetching、前端重试按钮永久锁死。
核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
无 started_at 时以 created_at 兜底;注意 run 级 _outbound_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_outbound_unit_with_timeout 收口(failed +
RPA.OUTBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」。
Returns:
本次回收的单元数。
"""
timeout_seconds = _outbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
FreightRpaOutboundUnitRun.query
.filter(
FreightRpaOutboundUnitRun.schedule_run_id.is_(None),
FreightRpaOutboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')),
func.coalesce(FreightRpaOutboundUnitRun.started_at, FreightRpaOutboundUnitRun.created_at) < cutoff,
)
.all()
)
if not orphans:
return 0
now = datetime.utcnow()
for unit in orphans:
_fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
db.session.commit()
return len(orphans)
@@ -0,0 +1,156 @@
"""
backend/app/services/schedule/freight_rpa_outbound_job.py
用途:独立出站 RPA 排程——按勾选库存源一对一冻结执行单元并写 outbound trigger。
依赖:freight_rpa.outbound.trigger_io.write_outbound_export_batch_trigger、assert_outbound_rpa_worker_ready、
FreightRpaSource / FreightRpaOutboundReportConfig / FreightRpaOutboundUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-rpa-outbound 调用本 handler;写 trigger 前 fail-fast;
口径与入站排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
from __future__ import annotations
import uuid
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun
from app.services.freight_rpa.outbound.trigger_io import SCHEMA, write_outbound_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_outbound_rpa_worker_ready,
)
OUTBOUND_RPA_JOB_KEY = 'freight-rpa-outbound'
AWAITING_OUTBOUND_RPA_CALLBACK_STATUS = 'awaiting_outbound_rpa_callback'
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _wanted_source_codes(task: ScheduleTask) -> set[str]:
"""提取结构化 source_codes;留空代表全部具备有效出站配置的站点。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
values = params.get('source_codes') or []
if isinstance(values, str):
values = [values]
return {str(value).strip().upper() for value in values if str(value).strip()}
def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaOutboundReportConfig]]:
"""读取已启用且已配置出站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join(
FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
def _copy_query_parameters(config: FreightRpaOutboundReportConfig) -> list[dict[str, Any]]:
"""浅拷贝出站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
if isinstance(item, dict)
]
def _build_unit(
source: FreightRpaSource, config: FreightRpaOutboundReportConfig, schedule_run_id: int,
) -> FreightRpaOutboundUnitRun:
"""冻结可审计的出站执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'outbound:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
}
return FreightRpaOutboundUnitRun(
schedule_run_id=schedule_run_id, source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id,
status='awaiting_rpa', config_snapshot_json=snapshot,
)
def _serialize_trigger_unit(unit: FreightRpaOutboundUnitRun) -> dict[str, Any]:
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 outbound trigger 下发。"""
source = unit.source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
raise RuntimeError(f'outbound source profile unavailable: {unit.source_code}')
snapshot = dict(unit.config_snapshot_json or {})
return {
'unit_run_id': unit.id,
'callback_id': unit.callback_id,
'source_code': unit.source_code,
'connector_type': unit.connector_type,
'warehouse_id': unit.warehouse_id,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'config_snapshot': snapshot,
}
def run_freight_rpa_outbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写独立出站 trigger;每个勾选站点对应一个执行单元(与入站 RPA 同口径)。
核心逻辑:写 trigger 前 assert_outbound_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_outbound_rpa_callback。
"""
units: list[FreightRpaOutboundUnitRun] = [
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
]
if not units:
return 0, 0, 0, 1, [], ['no enabled outbound report sources'], [{'step': 'freight_outbound_rpa', 'status': 'skipped'}]
# [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。
try:
assert_outbound_rpa_worker_ready()
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get('detail_message') or message)
return len(units), 0, len(units), 0, [], [detail_message], [{
'step': 'freight_outbound_rpa',
'status': 'failed',
'detail': {
'message': message,
'detail_message': detail_message,
'error_code': exc.code,
'reasons': (exc.details or {}).get('reasons') or [],
},
}]
db.session.add_all(units)
db.session.flush()
try:
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
except RuntimeError as exc:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
db.session.commit()
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_outbound_rpa', 'status': 'failed'}]
for unit, trigger_unit in zip(units, trigger_units):
unit.trigger_snapshot_json = trigger_unit
trigger_path = write_outbound_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:
unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'outbound trigger directory unavailable'
db.session.commit()
return len(units), 0, len(units), 0, [], ['outbound trigger directory unavailable'], [{'step': 'freight_outbound_rpa', 'status': 'failed'}]
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
db.session.commit()
return len(units), 0, 0, 0, details, [], [{
'step': 'freight_outbound_rpa', 'status': AWAITING_OUTBOUND_RPA_CALLBACK_STATUS,
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
}]
@@ -0,0 +1,66 @@
"""
backend/app/services/schedule/freight_rpa_outbound_retention.py
用途:出站原样归档三年到期对象清理(排程壳 + 本阶段清理本体)。
依赖:FreightRpaOutboundReportFile、file_asset_storage、freight_rpa.common.report_audit。
逻辑:job_registry 的 freight-rpa-outbound-retention 调用本 handler;仅删除已过保留期的
MinIO 对象,保留运行、文件事实和审计记录。Task 9 可将本体下沉 outbound.report_archive,
本文件届时改回薄接缝(对照 inbound_retention)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import FreightRpaOutboundReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
OUTBOUND_RETENTION_JOB_KEY = 'freight-rpa-outbound-retention'
def run_freight_rpa_outbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
Args:
task: 排程任务行(job_params.limit 提供单批上限,1..1000)。
run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。
Returns:
排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。
"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = FreightRpaOutboundReportFile.query.filter(
FreightRpaOutboundReportFile.archive_expires_at.is_not(None),
FreightRpaOutboundReportFile.archive_expires_at <= now,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaOutboundReportFile.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_rpa_report_event(
event_type='shipping_outbound_report_archive_deleted', aggregate_type='shipping_outbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_rpa_report_event(
event_type='shipping_outbound_report_archive_delete_attempted', aggregate_type='shipping_outbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'outbound_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': 'outbound_retention', 'status': 'completed'}]
+22 -8
View File
@@ -5,7 +5,7 @@ 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。
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
"""
from __future__ import annotations
@@ -34,8 +34,8 @@ def _agent_apps_options() -> list[dict[str, Any]]:
]
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
"""启用中的货代库存源(value=source_code,来自数据库主数据)。"""
def _freight_rpa_sources_options() -> list[dict[str, Any]]:
"""启用中的货代来源站点(value=source_code,来自数据库主数据;供 onhand 排程选源)。"""
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
return [
@@ -52,8 +52,8 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
]
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
def _freight_rpa_inbound_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置入站报表的站点,供独立入站排程选择。"""
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
@@ -61,7 +61,20 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
).filter(FreightRpaSource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 收料已配置',
'description': f'{source.connector_type} · 入站已配置',
} for source, _config in rows]
def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置出站报表的站点,供独立出站排程选择。"""
from app.models import FreightRpaSource, FreightRpaOutboundReportConfig
rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join(
FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 出站已配置',
} for source, _config in rows]
@@ -102,8 +115,9 @@ def _users_options() -> list[dict[str, Any]]:
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"agent_apps": _agent_apps_options,
"freight_rpa_sources": _shipping_inventory_sources_options,
"freight_rpa_inbound_sources": _shipping_receipt_sources_options,
"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,
"hxops_users": _hxops_users_options,
"users": _users_options,
}
+28 -7
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:freight_rpa_onhand_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
依赖:freight_rpa_onhand_job、freight_rpa_inbound_job、freight_rpa_outbound_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 通用渲染。
"""
@@ -133,8 +133,10 @@ def _register_builtin_platform_jobs() -> None:
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.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_rpa_inbound_retention import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule
from app.services.schedule.freight_rpa_inbound_retention import run_freight_rpa_inbound_retention_schedule
from app.services.schedule.freight_rpa_outbound_job import run_freight_rpa_outbound_schedule
from app.services.schedule.freight_rpa_outbound_retention import run_freight_rpa_outbound_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,
@@ -399,22 +401,41 @@ def _register_builtin_platform_jobs() -> None:
register_platform_job(PlatformJobDefinition(
key="freight-rpa-inbound",
label="货代入站 RPA",
handler=run_freight_receipt_rpa_schedule,
handler=run_freight_rpa_inbound_schedule,
description="按计划从已配置入站报表的站点导出并归档入站文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
"key": "source_codes", "type": "multi_select", "label": "入站站点", "required": False,
"default": [], "options_source": "freight_rpa_inbound_sources",
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
"help": "选择需要执行的入站站点;留空则执行所有已启用入站配置。",
},),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-rpa-inbound-retention', label='货代入站归档到期清理',
handler=run_freight_receipt_rpa_retention_schedule,
handler=run_freight_rpa_inbound_retention_schedule,
description='仅删除已过三年保留期的入站对象,保留运行、文件事实和审计记录。', category='shipping',
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
))
register_platform_job(PlatformJobDefinition(
key="freight-rpa-outbound",
label="货代出站 RPA",
handler=run_freight_rpa_outbound_schedule,
description="按计划从已配置出站报表的站点导出并归档出站文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "出站站点", "required": False,
"default": [], "options_source": "freight_rpa_outbound_sources",
"help": "选择需要执行的出站站点;留空则执行所有已启用出站配置。",
},),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-rpa-outbound-retention', label='货代出站归档到期清理',
handler=run_freight_rpa_outbound_retention_schedule,
description='仅删除已过三年保留期的出站对象,保留运行、文件事实和审计记录。', category='shipping',
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
))
register_platform_job(PlatformJobDefinition(
key="faq-aggregate-hot",
label="FAQ 热点聚合",
+12 -2
View File
@@ -1,3 +1,10 @@
"""
backend/app/services/schedule/query_service.py
用途:排程任务与运行记录的查询/序列化。
依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。
逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。
"""
from __future__ import annotations
from datetime import datetime, timezone
@@ -10,7 +17,8 @@ from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -61,6 +69,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
def serialize_run(run: ScheduleRun) -> dict:
"""序列化单条运行记录;附带库存/入站/出站 raw-zip 是否可下载。"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return {
'id': run.id,
@@ -86,7 +95,8 @@ def serialize_run(run: ScheduleRun) -> dict:
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
'receipt_raw_zip_available': receipt_raw_zip_available_from_summary(summary),
'inbound_raw_zip_available': inbound_raw_zip_available_from_summary(summary),
'outbound_raw_zip_available': outbound_raw_zip_available_from_summary(summary),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
+29 -13
View File
@@ -2,7 +2,8 @@
backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务
(onhand / inbound / outbound finalize 超时回收)。
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入
business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。
@@ -24,10 +25,15 @@ from app.services.schedule.freight_rpa_onhand_finalize import (
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_rpa_inbound_finalize import (
recover_all_stale_orphan_receipt_units,
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
is_awaiting_receipt_rpa_schedule_run,
recover_all_stale_orphan_inbound_units,
recover_all_stale_inbound_rpa_schedule_runs,
recover_stale_inbound_rpa_schedule_runs,
is_awaiting_inbound_rpa_schedule_run,
)
from app.services.schedule.freight_rpa_outbound_finalize import (
recover_all_stale_orphan_outbound_units,
recover_all_stale_outbound_rpa_schedule_runs,
recover_stale_outbound_rpa_schedule_runs,
)
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
@@ -233,7 +239,8 @@ def enqueue_manual_schedule_run(
if task is None:
raise LookupError(f"schedule task {task_id} not found")
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
active = _active_run(task.id)
if active is not None:
job = (
@@ -287,7 +294,8 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
# 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次;
# 这只是终态化失败,不会自动重新导出。
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
if _active_run(task.id) is None:
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
_advance_next_run(task)
@@ -337,7 +345,7 @@ def prepare_schedule_queue() -> int:
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
for run in legacy_running:
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
if is_awaiting_rpa_schedule_run(run) or is_awaiting_inbound_rpa_schedule_run(run):
continue
active_job = (
query_jobs_for_schedule_run(run.id)
@@ -380,16 +388,24 @@ def prepare_schedule_queue() -> int:
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_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)
inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()
if inbound_stale:
current_app.logger.info("[schedule-worker] recovered %d stale inbound RPA runs", inbound_stale)
# 按需触发(无排程)孤儿单元同口径回收(2026-10-16):调拨工作台重试/自动调拨
# 补抓创建的单元 schedule_run_id 为 NULL,上方 run 级扫描按 run 遍历覆盖不到;
# 网页异常关闭后回调永不到达,不回收则来源投影永久 fetching、重试按钮永久锁死。
orphan_stale = recover_all_stale_orphan_receipt_units()
orphan_stale = recover_all_stale_orphan_inbound_units()
if orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan receipt RPA units", orphan_stale)
current_app.logger.info("[schedule-worker] recovered %d stale orphan inbound RPA units", orphan_stale)
# 出站 run / 孤儿单元超时对账与入站同属每轮领取维护,不得挂启动一次性分支。
outbound_stale = recover_all_stale_outbound_rpa_schedule_runs()
if outbound_stale:
current_app.logger.info("[schedule-worker] recovered %d stale outbound RPA runs", outbound_stale)
outbound_orphan_stale = recover_all_stale_orphan_outbound_units()
if outbound_orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan outbound RPA units", outbound_orphan_stale)
try:
from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -2,7 +2,9 @@
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新)与单次运行执行器。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync、
freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态与超时回收)、
onhand / inbound / outbound archive raw-zip 可用性(企微深链 download 意图)。
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
@@ -31,9 +33,14 @@ from app.services.schedule.freight_rpa_onhand_finalize import (
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_rpa_inbound_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
apply_deferred_inbound_schedule_run_state,
recover_stale_inbound_rpa_schedule_runs,
should_defer_inbound_schedule_run,
)
from app.services.schedule.freight_rpa_outbound_finalize import (
apply_deferred_outbound_schedule_run_state,
recover_stale_outbound_rpa_schedule_runs,
should_defer_outbound_schedule_run,
)
from app.services.schedule.job_params import normalize_job_params_for_contract
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
@@ -103,11 +110,12 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
核心逻辑:指向管理端 /admin/schedules;有原始库存/入站/出站归档时附加 raw_zip=1
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
"""
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
@@ -117,17 +125,20 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'inventory_raw_zip'
elif receipt_raw_zip_available_from_summary(summary):
elif inbound_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'receipt_raw_zip'
params['download'] = 'inbound_raw_zip'
elif outbound_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'outbound_raw_zip'
return params
def _receipt_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]:
def _inbound_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]:
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
收集入站排程 run 名下可投递的入站报表文件;非收料任务返回空列表。
核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且
核心逻辑:按 platform_api_path 识别入站排程,返回该 run 全部单元已归档且
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
本函数保留给管理员单文件重发等旁路读取。
"""
@@ -158,7 +169,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存/收料归档时提示包已随通知发送或可点击下载。
有原始库存/入站/出站归档时提示包已随通知发送或可点击下载。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
@@ -172,12 +183,15 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
if receipt_raw_zip_available_from_summary(summary):
description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载'
if inbound_raw_zip_available_from_summary(summary):
description += '\n原始入站包:已随本通知发送;亦可点击本通知登录后下载'
if outbound_raw_zip_available_from_summary(summary):
description += '\n原始出站包:已随本通知发送;亦可点击本通知登录后下载'
return description
@@ -186,8 +200,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
收料附加该 run 的原始收料 ZIP(不再逐文件推送)。
库存、入站、出站 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
入站/出站附加该 run 的原始 ZIP(不再逐文件推送)。
"""
from app.services.integrations.wecom.notify import (
upload_wecom_temp_media,
@@ -248,18 +262,33 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.run_no, exc,
)
receipt_zip_media_id = None
receipt_zip_file_name = None
inbound_zip_media_id = None
inbound_zip_file_name = None
try:
from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download
from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
receipt_zip_media_id = upload_wecom_temp_media(
receipt_zip_path.read_bytes(), receipt_zip_file_name,
inbound_zip_path, inbound_zip_file_name = resolve_inbound_raw_zip_download(run)
inbound_zip_media_id = upload_wecom_temp_media(
inbound_zip_path.read_bytes(), inbound_zip_file_name,
)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw receipt zip media skipped for run %s: %s',
'[wecom-schedule] raw inbound zip media skipped for run %s: %s',
run.run_no, exc,
)
outbound_zip_media_id = None
outbound_zip_file_name = None
try:
from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download
outbound_zip_path, outbound_zip_file_name = resolve_outbound_raw_zip_download(run)
outbound_zip_media_id = upload_wecom_temp_media(
outbound_zip_path.read_bytes(), outbound_zip_file_name,
)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw outbound zip media skipped for run %s: %s',
run.run_no, exc,
)
@@ -318,23 +347,41 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
except Exception as exc:
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
if receipt_zip_media_id:
if inbound_zip_media_id:
try:
receipt_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u,
title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex,
inbound_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_inbound_raw_zip', u,
title, f'[原始入站包] {inbound_zip_file_name}', uuid.uuid4().hex,
)
receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id)
if receipt_zip_data.get('errcode') == 0:
receipt_zip_audit.status = 'sent'
inbound_zip_data = send_wecom_file_message(u.wecom_userid, inbound_zip_media_id)
if inbound_zip_data.get('errcode') == 0:
inbound_zip_audit.status = 'sent'
else:
receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode'))
receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255]
inbound_zip_audit.error_code = str(inbound_zip_data.get('errcode'))
inbound_zip_audit.error_message = str(inbound_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(
f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}'
f'{u.real_name or u.username}: inbound zip errcode={inbound_zip_data.get("errcode")}'
)
except Exception as exc:
errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}')
errors.append(f'{u.real_name or u.username}: inbound zip exception={exc}')
if outbound_zip_media_id:
try:
outbound_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_outbound_raw_zip', u,
title, f'[原始出站包] {outbound_zip_file_name}', uuid.uuid4().hex,
)
outbound_zip_data = send_wecom_file_message(u.wecom_userid, outbound_zip_media_id)
if outbound_zip_data.get('errcode') == 0:
outbound_zip_audit.status = 'sent'
else:
outbound_zip_audit.error_code = str(outbound_zip_data.get('errcode'))
outbound_zip_audit.error_message = str(outbound_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(
f'{u.real_name or u.username}: outbound zip errcode={outbound_zip_data.get("errcode")}'
)
except Exception as exc:
errors.append(f'{u.real_name or u.username}: outbound zip exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
@@ -570,7 +617,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
该路径原先只写库不打日志,worker 汇总行看不到失败原因。
"""
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
if run is None:
existing = db.session.query(ScheduleRun).filter(
@@ -640,8 +688,12 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
errors=errors,
step_logs=step_logs,
)
if should_defer_receipt_schedule_run(task, step_logs):
return apply_deferred_receipt_schedule_run_state(
if should_defer_inbound_schedule_run(task, step_logs):
return apply_deferred_inbound_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
if should_defer_outbound_schedule_run(task, step_logs):
return apply_deferred_outbound_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)