清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
372 lines
17 KiB
Python
372 lines
17 KiB
Python
"""
|
||
backend/app/services/schedule/job_registry.py
|
||
|
||
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
|
||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。
|
||
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
|
||
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Callable
|
||
|
||
from app.models import ScheduleRun, ScheduleTask
|
||
from app.services.schedule.schedule_contract import normalize_job_key
|
||
|
||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||
PlatformJobHandler = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||
|
||
_REGISTRY: dict[str, "PlatformJobDefinition"] = {}
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class PlatformJobDefinition:
|
||
"""
|
||
平台内置 Job 的完整任务契约:执行入口 + 展示信息 + 参数 schema + 默认值。
|
||
|
||
params_schema 字段通用结构(前端 DynamicTaskParamsForm 按 type 渲染,不认识具体任务):
|
||
{
|
||
"key": "source_codes", # job_params 中的键名
|
||
"type": "multi_select", # text|textarea|number|boolean|select|multi_select|date|datetime|cron|json|info
|
||
"label": "库存源", # 中文 fallback;前端优先 $t(label_key)
|
||
"label_key": "...", # 前端 i18n key(可选)
|
||
"required": False,
|
||
"default": [],
|
||
"options_source": "shipping_inventory_sources", # select/multi_select 动态选项来源(可选)
|
||
"placeholder": "...", "placeholder_key": "...",
|
||
"help": "...", "help_key": "...",
|
||
}
|
||
"""
|
||
|
||
key: str
|
||
label: str
|
||
handler: PlatformJobHandler
|
||
description: str = ""
|
||
# 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory);
|
||
# 前端下拉优先 $t(label_key),label 仅作 fallback/debug。
|
||
label_key: str = ""
|
||
description_key: str = ""
|
||
category: str = "platform"
|
||
# 任务停用开关:False 时列表不下发、契约校验拒绝创建/改指向、执行入口拒绝运行
|
||
enabled: bool = True
|
||
# 参数契约:字段 schema 列表(tuple 保持 frozen dataclass 不可变)与默认值
|
||
params_schema: tuple[dict[str, Any], ...] = ()
|
||
defaults: dict[str, Any] = field(default_factory=dict)
|
||
|
||
|
||
def register_platform_job(definition: PlatformJobDefinition) -> None:
|
||
"""注册平台 Job;重复 key 覆盖(便于热重载测试)。"""
|
||
key = normalize_job_key(definition.key)
|
||
if not key:
|
||
raise ValueError("platform job key is required")
|
||
_REGISTRY[key] = PlatformJobDefinition(
|
||
key=key,
|
||
label=definition.label,
|
||
handler=definition.handler,
|
||
description=definition.description,
|
||
label_key=definition.label_key,
|
||
description_key=definition.description_key,
|
||
category=definition.category,
|
||
enabled=definition.enabled,
|
||
params_schema=tuple(definition.params_schema or ()),
|
||
defaults=dict(definition.defaults or {}),
|
||
)
|
||
|
||
|
||
def get_platform_job(key: str) -> PlatformJobDefinition | None:
|
||
"""按 key 查询已注册 Job。"""
|
||
return _REGISTRY.get(normalize_job_key(key))
|
||
|
||
|
||
def list_platform_jobs() -> list[PlatformJobDefinition]:
|
||
"""返回全部已注册 Job(按 key 排序)。"""
|
||
return [_REGISTRY[k] for k in sorted(_REGISTRY)]
|
||
|
||
|
||
def is_registered_platform_job(key: str) -> bool:
|
||
"""判断 key 是否已注册。"""
|
||
return normalize_job_key(key) in _REGISTRY
|
||
|
||
|
||
def run_platform_job(
|
||
key: str,
|
||
task: ScheduleTask,
|
||
run: ScheduleRun,
|
||
payload: dict[str, Any] | None = None,
|
||
) -> ScheduleExecuteResult:
|
||
"""
|
||
执行已注册平台 Job。
|
||
核心逻辑:执行前按注册表 params_schema 再校验一次 task.job_params
|
||
(check_options=False:选项集合可能随时间漂移,运行期只校验类型与必填),
|
||
校验失败直接抛错终止本次 run。
|
||
Args:
|
||
key: platform_api_path job key
|
||
task: 排程任务(结构化参数存 task.job_params)
|
||
run: 执行批次
|
||
payload: internal API 请求体(部分 handler 可读 agent_id 等)
|
||
Returns:
|
||
ScheduleExecuteResult 七元组
|
||
Raises:
|
||
KeyError: 未注册 key
|
||
ValueError: 任务已停用,或 job_params 不满足 params_schema
|
||
"""
|
||
definition = get_platform_job(key)
|
||
if not definition:
|
||
raise KeyError(f"Unknown platform job: {key}")
|
||
if not definition.enabled:
|
||
raise ValueError(f"Platform job is disabled: {definition.key}")
|
||
_ = payload # 预留扩展;handler 从 task.job_params(已归一化)/ legacy 字段读取参数
|
||
if definition.params_schema:
|
||
from app.services.schedule.job_params import validate_task_params
|
||
|
||
# [STEP 1] 执行前再校验;归一化结果写回 task,handler 读到的是契约后的参数
|
||
task.job_params = validate_task_params(key, task.job_params or {}, check_options=False)
|
||
return definition.handler(task, run)
|
||
|
||
|
||
def _register_builtin_platform_jobs() -> None:
|
||
"""模块加载时注册内置平台 Job(含参数契约)。"""
|
||
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
|
||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule
|
||
from app.services.schedule.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,
|
||
)
|
||
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
|
||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
|
||
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="shipping-order-extraction-progress-cleanup",
|
||
label="订单识别进度清理",
|
||
handler=run_shipping_order_extraction_progress_cleanup_schedule,
|
||
description="按90天保留期分批清理订单识别脱敏进度事件,不删除Run、Job或诊断审计。",
|
||
category="shipping",
|
||
params_schema=({"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},),
|
||
defaults={"limit": 1000},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="shipping-post-ot-auto-fulfill-compensation",
|
||
label="OT 后行级自动履约补偿",
|
||
handler=run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||
description=(
|
||
"每 15 分钟扫描正式 OT 上尚未入波次且匹配 ready 的行,"
|
||
"复用 coordinate_post_ot_auto_fulfill(trigger=compensation)。"
|
||
"SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false 时空跑。"
|
||
),
|
||
category="shipping",
|
||
params_schema=({"key": "limit", "type": "number", "label": "单批 Case 上限", "required": False, "default": 50},),
|
||
defaults={"limit": 50},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="shipping-audit-retention",
|
||
label="货代审计到期清理与哈希校验",
|
||
handler=run_shipping_audit_retention_schedule,
|
||
description=(
|
||
"分批清理 retention_expires_at 已到期的历史审计行(新写入永久保留);"
|
||
"并按 SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED 抽样校验近期聚合哈希链。"
|
||
"建议每日调度一次。"
|
||
),
|
||
category="shipping",
|
||
params_schema=(
|
||
{"key": "limit", "type": "number", "label": "清理单批上限", "required": False, "default": 1000},
|
||
{"key": "dry_run", "type": "boolean", "label": "仅演练", "required": False, "default": False},
|
||
{
|
||
"key": "hash_sample_limit",
|
||
"type": "number",
|
||
"label": "哈希链抽样条数",
|
||
"required": False,
|
||
"default": 200,
|
||
},
|
||
),
|
||
defaults={"limit": 1000, "dry_run": False, "hash_sample_limit": 200},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="shipping-audit-hash-verify",
|
||
label="货代审计哈希链日检",
|
||
handler=run_shipping_audit_retention_schedule,
|
||
description=(
|
||
"每日抽样校验货代统一审计 previous_event_hash / event_hash 链完整性;"
|
||
"默认 dry_run=true 不执行清理,仅返回 hash_verify 结果。"
|
||
),
|
||
category="shipping",
|
||
params_schema=(
|
||
{
|
||
"key": "hash_sample_limit",
|
||
"type": "number",
|
||
"label": "哈希链抽样条数",
|
||
"required": False,
|
||
"default": 500,
|
||
},
|
||
{"key": "dry_run", "type": "boolean", "label": "仅演练(建议 true)", "required": False, "default": True},
|
||
{"key": "limit", "type": "number", "label": "清理单批上限", "required": False, "default": 1},
|
||
),
|
||
defaults={"hash_sample_limit": 500, "dry_run": True, "limit": 1},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="shipping-inventory-rpa",
|
||
label="货代库存 RPA",
|
||
label_key="admin.schedule.form.platformJobShippingInventory",
|
||
handler=run_shipping_inventory_rpa_schedule,
|
||
description="按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。",
|
||
description_key="admin.schedule.form.shippingInventoryJobHint",
|
||
category="shipping",
|
||
params_schema=(
|
||
{
|
||
"key": "source_codes",
|
||
"type": "multi_select",
|
||
"label": "库存源",
|
||
"label_key": "admin.schedule.form.shippingInventorySources",
|
||
# 兼容历史任务语义:留空 = 导出全部启用库存源,故不设 required
|
||
"required": False,
|
||
"default": [],
|
||
"options_source": "shipping_inventory_sources",
|
||
"placeholder": "留空则导出全部启用库存源",
|
||
"placeholder_key": "admin.schedule.form.shippingInventorySourcesPlaceholder",
|
||
"help": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。",
|
||
"help_key": "admin.schedule.form.shippingInventorySourcesHelp",
|
||
},
|
||
),
|
||
defaults={"source_codes": []},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="freight-receipt-rpa",
|
||
label="货代收料 RPA",
|
||
handler=run_freight_receipt_rpa_schedule,
|
||
description="按计划从已配置收料报表的站点导出并归档收料文件。",
|
||
category="shipping",
|
||
params_schema=({
|
||
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
|
||
"default": [], "options_source": "shipping_receipt_sources",
|
||
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
|
||
},),
|
||
defaults={"source_codes": []},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
|
||
handler=run_freight_receipt_rpa_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 热点聚合",
|
||
label_key="admin.schedule.form.platformJobFaqHotAggregate",
|
||
handler=run_faq_hot_aggregate_schedule,
|
||
description="按 Cron 自动执行 ChatLog 热点发现,结果写入 faq_hot_candidates。",
|
||
description_key="admin.schedule.form.faqHotAggregateHint",
|
||
category="faq",
|
||
params_schema=(
|
||
{
|
||
"key": "app_id",
|
||
"type": "select",
|
||
"label": "限定应用",
|
||
"label_key": "admin.schedule.form.faqHotAgentFilter",
|
||
"required": False,
|
||
"default": None,
|
||
"options_source": "agent_apps",
|
||
"placeholder": "全部应用",
|
||
"placeholder_key": "admin.schedule.form.faqHotAllAgents",
|
||
"help": "留空则聚合所有 Agent;选定后仅统计该应用的 ChatLog。",
|
||
"help_key": "admin.schedule.form.faqHotAgentFilterHelp",
|
||
},
|
||
),
|
||
defaults={"app_id": None},
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="fixed-assets-snapshot",
|
||
label="固资快照",
|
||
label_key="admin.schedule.form.platformJobFixedAssetsSnapshot",
|
||
handler=run_fixed_assets_snapshot_schedule,
|
||
description="同步 PLM 固资快照至本地 manifest。",
|
||
category="assets",
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="file-asset-cleanup",
|
||
label="临时文件资产清理",
|
||
label_key="admin.schedule.form.platformJobFileAssetCleanup",
|
||
handler=run_file_asset_cleanup_schedule,
|
||
description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。",
|
||
category="files",
|
||
))
|
||
register_platform_job(PlatformJobDefinition(
|
||
key="accounting-voucher-check",
|
||
label="立账凭证检核",
|
||
label_key="admin.schedule.form.platformJobAccountingVoucherCheck",
|
||
handler=run_voucher_check_schedule,
|
||
description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
|
||
description_key="admin.schedule.form.accountingVoucherCheckHint",
|
||
category="finance",
|
||
params_schema=(
|
||
{
|
||
"key": "scope_code",
|
||
"type": "select",
|
||
"label": "账套",
|
||
"label_key": "admin.schedule.form.voucherCheckScope",
|
||
"required": True,
|
||
"default": "HXJM",
|
||
"options": [{"value": "HXJM", "label": "HXJM"}],
|
||
},
|
||
{
|
||
"key": "directory_template",
|
||
"type": "text",
|
||
"label": "目录模板",
|
||
"label_key": "admin.schedule.form.voucherCheckDirTemplate",
|
||
"required": True,
|
||
"default": "{root}/{YYYY}/{MM}/{invoice_no}",
|
||
"help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}",
|
||
"help_key": "admin.schedule.form.voucherCheckDirTemplateHelp",
|
||
},
|
||
{
|
||
"key": "required_files",
|
||
"type": "json",
|
||
"label": "必检材料",
|
||
"label_key": "admin.schedule.form.voucherCheckRequiredFiles",
|
||
"required": True,
|
||
"default": DEFAULT_REQUIRED_FILES,
|
||
},
|
||
{
|
||
"key": "filename_case_sensitive",
|
||
"type": "boolean",
|
||
"label": "文件名区分大小写",
|
||
"label_key": "admin.schedule.form.voucherCheckCaseSensitive",
|
||
"required": True,
|
||
"default": True,
|
||
},
|
||
{
|
||
"key": "notify_missing_enabled",
|
||
"type": "boolean",
|
||
"label": "缺资料通知",
|
||
"label_key": "admin.schedule.form.voucherCheckNotifyMissing",
|
||
"required": False,
|
||
"default": True,
|
||
},
|
||
{
|
||
"key": "notify_failure_enabled",
|
||
"type": "boolean",
|
||
"label": "失败告警",
|
||
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
|
||
"required": False,
|
||
"default": True,
|
||
},
|
||
{
|
||
"key": "same_day_dedup_enabled",
|
||
"type": "boolean",
|
||
"label": "同票同日去重",
|
||
"label_key": "admin.schedule.form.voucherCheckSameDayDedup",
|
||
"required": False,
|
||
"default": True,
|
||
},
|
||
),
|
||
defaults=dict(DEFAULT_JOB_PARAMS),
|
||
))
|
||
|
||
|
||
_register_builtin_platform_jobs()
|