feat(shipping-notice): 增加 RPA Worker 心跳上报与状态查询功能

This commit is contained in:
hugo committed 2026-07-12 12:52:01 +08:00
1 parent c3f05ba96b
commit 5a147c4d85
49 files changed
+4032 -1500

No files matched your search

@@ -9,6 +9,7 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -59,6 +60,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
def serialize_run(run: ScheduleRun) -> dict:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return {
'id': run.id,
'run_no': run.run_no,
@@ -82,6 +84,7 @@ def serialize_run(run: ScheduleRun) -> dict:
'error_message': run.error_message,
'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),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
@@ -76,11 +76,30 @@ _WECOM_STATUS_LABEL = {
_WECOM_EVENT_TYPE = 'schedule_completed'
def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) -> dict[str, Any]:
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 供深链展示下载入口。
"""
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
'task_id': task.id,
'run_id': run.id,
}
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
return params
def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
"""
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存归档时提示点击卡片进入 HXOPS(URL 仅放 jump_url,不写进正文)。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
@@ -93,6 +112,10 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知进入 HXOPS 下载'
return description
@@ -125,7 +148,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
return
title = f'排程执行结果: {task.name}'
description = _build_schedule_run_wecom_description(run)
jump_params = _build_schedule_run_wecom_jump_params(task, run)
media_id = None
if run.excel_file_data and run.excel_file_name:
@@ -142,7 +165,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
for u in wecom_users:
trace_id = uuid.uuid4().hex
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
jump_url = _build_jump_url('/admin/schedules', trace_id, jump_params)
description = _build_schedule_run_wecom_description(run)
try:
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
@@ -617,8 +641,17 @@ def start_scheduler(app):
recovered_awaiting,
)
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=True)
while True:
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
maybe_alert_rpa_worker_status,
)
maybe_alert_rpa_worker_status()
now = utc_now_naive()
due_tasks = db.session.query(ScheduleTask).filter(
ScheduleTask.enabled.is_(True),
@@ -0,0 +1,269 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
"""
from __future__ import annotations
import json
import re
import zipfile
from pathlib import Path
from typing import Any
from flask import current_app
from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
"raw_inventory_zip_available": False,
"raw_inventory_zip_path": None,
"raw_inventory_file_count": 0,
"raw_inventory_file_nos": [],
"raw_inventory_zip_size": 0,
}
def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path(
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
if current_app
else ""
)
if not str(archive_dir):
from app.core.config.settings import Config
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
def inventory_raw_zip_download_name(run_no: str) -> str:
"""浏览器下载时使用的 ZIP 文件名。"""
return f"inventory-rpa-raw-{run_no}.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_inventory_archive_dir()) / f"{run_no}.zip"
def _api_response_created(run: ScheduleRun) -> list[dict[str, Any]]:
"""从 run.api_response_json 提取 created 列表。"""
api_resp = run.api_response_json if isinstance(run.api_response_json, dict) else {}
created = api_resp.get("created")
if not isinstance(created, list):
return []
return [item for item in created if isinstance(item, dict)]
def _normalize_created_items(created: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
"""过滤并规范化 created 列表。"""
if not isinstance(created, list):
return []
return [item for item in created if isinstance(item, dict)]
def _iter_packable_inventory_files(
run: ScheduleRun,
*,
created: list[dict[str, Any]] | None = None,
):
"""
遍历可实际打包的库存快照。
核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。
Yields:
tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。
"""
if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
return
items = _normalize_created_items(created) if created is not None else _api_response_created(run)
for item in items:
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
if not inventory_file_no:
continue
inv_file = (
db.session.query(ShippingInventoryFile)
.filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
.first()
)
if not inv_file:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
def inventory_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_inventory_zip_available"))
def persist_inventory_rpa_raw_zip_archive(
run: ScheduleRun,
*,
created: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
finalize 阶段预生成原始库存 ZIP 归档并返回 summary 字段。
核心逻辑:收集可读快照 → 写入 <archive_dir>/<run_no>.zip(含 manifest.json);
无可用文件时返回 raw_inventory_zip_available=false。
Args:
run: 库存 RPA ScheduleRun。
created: 可选回调 created 列表;finalize 时传入避免依赖尚未落库的 api_response_json。
Returns:
dict: raw_inventory_zip_available / raw_inventory_zip_path / raw_inventory_file_count /
raw_inventory_file_nos / raw_inventory_zip_size。
"""
packable_files = list(_iter_packable_inventory_files(run, created=created))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _inventory_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, str]] = []
with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1):
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
source_code = str(item.get("source_code") or inv_file.source_code or "").strip()
warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip()
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
inventory_file_no=inventory_file_no,
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
files_manifest.append({
"inventory_file_no": inventory_file_no,
"source_code": source_code,
"warehouse_id": warehouse_id,
"file_name": entry_name,
"original_file_name": inv_file.source_file_name or storage_path.name,
})
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_inventory_zip_available": True,
"raw_inventory_zip_path": str(archive_path.resolve()),
"raw_inventory_file_count": len(files_manifest),
"raw_inventory_file_nos": [item["inventory_file_no"] for item in files_manifest],
"raw_inventory_zip_size": int(archive_path.stat().st_size),
}
def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip":
return False
if not resolved.is_file():
return False
archive_dir = Path(get_inventory_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
return False
return True
def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
Raises:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not inventory_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get("raw_inventory_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_inventory_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
def _sanitize_zip_segment(value: str) -> str:
"""ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
cleaned = re.sub(r"[^\w\-.]+", "_", str(value or "").strip())
return cleaned or "unknown"
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
inventory_file_no: str,
original_suffix: str,
) -> str:
"""生成 ZIP 内单文件条目名(不含目录)。"""
base = "_".join(
filter(
None,
[
f"{index:03d}",
_sanitize_zip_segment(source_code),
_sanitize_zip_segment(warehouse_id),
_sanitize_zip_segment(inventory_file_no),
],
)
)
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
return f"{base}{suffix}"
@@ -529,6 +529,27 @@ def _finalize_shipping_inventory_schedule_run_impl(
"skipped": skipped,
"failed": failed,
}
archive_summary: dict[str, Any] = {
"raw_inventory_zip_available": False,
"raw_inventory_zip_path": None,
"raw_inventory_file_count": 0,
"raw_inventory_file_nos": [],
"raw_inventory_zip_size": 0,
}
try:
from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive
archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
except Exception as archive_exc:
if current_app:
current_app.logger.error(
"[schedule-run] inventory RPA raw zip archive failed run_no=%s: %s",
run.run_no,
archive_exc,
exc_info=True,
)
run.response_summary_json = {
"awaiting_rpa": False,
"total_count": total_count,
@@ -548,6 +569,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"failed_count": failed_count,
"excel_failed": not excel_export_ok,
},
**archive_summary,
}
run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data
@@ -14,10 +14,12 @@ from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -137,19 +139,34 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
return 0, 0, 0, 1, [], [message], step_logs
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
payload={
"trigger_type": "scheduled",
"schedule_run_id": run.id,
"schedule_task_id": task.id,
},
)
try:
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
payload={
"trigger_type": "scheduled",
"schedule_run_id": run.id,
"schedule_task_id": task.id,
},
)
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get("detail_message") or message)
step_logs.append({
"step": "shipping_inventory_rpa",
"status": "failed",
"detail": {
"message": message,
"detail_message": detail_message,
"error_code": exc.code,
"reasons": (exc.details or {}).get("reasons") or [],
},
})
return len(sources), 0, len(sources), 0, [], [detail_message], step_logs
if not trigger_path:
message = "inventory RPA trigger dir not configured"
step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}})
return len(sources), 0, 0, len(sources), [], [message], step_logs
return len(sources), 0, len(sources), 0, [], [message], step_logs
run.api_request_json = {
"run_no": run_no,