feat(schedule): 新增平台任务参数契约与动态选项支持
This commit is contained in:
1 parent
2ce1aca023
commit
8b5b0b49bf
76 files changed
+7103
-1203
No files matched your search
@@ -98,7 +98,7 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
"all uploaded files failed extraction or contained no parseable text",
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary},
|
||||
)
|
||||
payload["notice_items"] = notice_items
|
||||
@@ -138,10 +138,11 @@ def register_chat_turn_routes(chat_bp) -> None:
|
||||
|
||||
body, uploads = _parse_turn_body_and_files()
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
# [STEP 1] multipart 附件必须在返回 SSE 前读完;生成器延迟执行时 request.files 可能已关闭。
|
||||
if uploads:
|
||||
_inject_multipart_upload_payload(body, uploads)
|
||||
|
||||
def relay_stream():
|
||||
if uploads:
|
||||
_inject_multipart_upload_payload(body, uploads)
|
||||
yield from ChatTurnRuntime.stream(
|
||||
user=user,
|
||||
agent=agent,
|
||||
|
||||
@@ -19,6 +19,11 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
@@ -128,6 +133,7 @@ def run_internal_job(name: str):
|
||||
raise NotFoundError(f"Unknown platform job: {name}")
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
@@ -152,6 +158,31 @@ def run_internal_job(name: str):
|
||||
},
|
||||
)
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:schedule/blueprint.py、config、tasks、runs。
|
||||
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
|
||||
"""
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
@@ -11,5 +11,6 @@ import app.api.schedule.common # noqa: F401
|
||||
import app.api.schedule.config # noqa: F401
|
||||
import app.api.schedule.tasks # noqa: F401
|
||||
import app.api.schedule.runs # noqa: F401
|
||||
import app.api.schedule.platform_tasks # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -67,14 +67,17 @@ def update_schedule_task_config(task_id: int):
|
||||
|
||||
config_data = data.get('config', data)
|
||||
if isinstance(config_data, dict) and config_data:
|
||||
# platform_job 仅白名单任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||
raise ValidationError(
|
||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||
)
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
db.session.commit()
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({
|
||||
'data_source_type': task.data_source_type,
|
||||
'config': serialize_task_config(cfg_model) if cfg_model else None,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/api/schedule/platform_tasks.py
|
||||
|
||||
用途:平台任务契约 API(任务定义 + 动态选项),供前端 DynamicTaskParamsForm 通用渲染。
|
||||
依赖:schedule.blueprint、job_registry(任务契约中心)、job_options(options_source 分发)。
|
||||
逻辑:/platform-tasks/definitions 下发 params_schema(仅 enabled);/platform-tasks/options 按 source 返回统一选项;
|
||||
前端不再按任务硬编码 UI,红框参数区完全由 schema 决定。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_definitions():
|
||||
"""
|
||||
返回全部启用平台任务的完整契约(展示信息 + params_schema + defaults)。
|
||||
核心逻辑:直接序列化 job_registry 注册项;前端选择任务后按 params_schema 渲染参数表单。
|
||||
"""
|
||||
return ok([
|
||||
{
|
||||
'task_type': job.key,
|
||||
'label': job.label,
|
||||
'label_key': job.label_key or None,
|
||||
'description': job.description,
|
||||
'description_key': job.description_key or None,
|
||||
'category': job.category,
|
||||
'enabled': job.enabled,
|
||||
'params_schema': list(job.params_schema),
|
||||
'defaults': job.defaults,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/options', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_options():
|
||||
"""
|
||||
按 options_source 返回动态选项(统一 {label, value, description?})。
|
||||
核心逻辑:source 参数分发到 job_options 登记的 provider;前端不感知数据来源。
|
||||
"""
|
||||
source = str(request.args.get('source') or '').strip()
|
||||
if not source:
|
||||
raise ValidationError('source is required')
|
||||
try:
|
||||
options = list_job_options(source)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
return ok(options)
|
||||
@@ -21,6 +21,7 @@ from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@@ -33,6 +34,7 @@ def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
user = get_current_user()
|
||||
existing = (
|
||||
db.session.query(ScheduleRun)
|
||||
|
||||
@@ -3,7 +3,9 @@ backend/app/api/schedule/tasks.py
|
||||
|
||||
用途:排程任务 CRUD、导入导出、启用/禁用 API。
|
||||
依赖:schedule.blueprint、schedule.common、services/schedule/*。
|
||||
逻辑:/schedules* 路由(不含 run 触发与运行记录)。
|
||||
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
|
||||
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
|
||||
ValueError→ValidationError 映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -39,7 +41,10 @@ def get_schedules():
|
||||
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_jobs():
|
||||
"""返回 Job Registry 已注册平台任务列表,供前端下拉动态加载。"""
|
||||
"""
|
||||
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
|
||||
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
|
||||
"""
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
return jsonify([
|
||||
@@ -48,8 +53,10 @@ def get_platform_jobs():
|
||||
'label_key': job.label_key or None,
|
||||
'label': job.label,
|
||||
'description': job.description,
|
||||
'enabled': job.enabled,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@@ -103,6 +110,7 @@ def post_schedule():
|
||||
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
|
||||
data_source_type = 'database'
|
||||
try:
|
||||
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': schedule_type,
|
||||
'data_source_type': data_source_type,
|
||||
@@ -123,6 +131,7 @@ def post_schedule():
|
||||
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
|
||||
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
|
||||
data_source_type=str(data_source_type) if data_source_type is not None else None,
|
||||
job_params=data.get('job_params'),
|
||||
notify_user_ids_json=data.get('notify_user_ids_json')
|
||||
if isinstance(data.get('notify_user_ids_json'), list)
|
||||
else [],
|
||||
@@ -139,7 +148,10 @@ def post_schedule():
|
||||
try:
|
||||
upsert_schedule_task_config(task.id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
@@ -173,7 +185,7 @@ def patch_schedule(task_id: int):
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
try:
|
||||
# [STEP 1] 先校验契约与 config 写入权限,避免 update_task 已提交后 config 被拒产生半更新
|
||||
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': data.get('schedule_type', task.schedule_type),
|
||||
'data_source_type': data.get('data_source_type', task.data_source_type),
|
||||
@@ -193,7 +205,10 @@ def patch_schedule(task_id: int):
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
if config_data:
|
||||
@@ -237,19 +252,20 @@ def delete_schedule(task_id: int):
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
"""启用排程并重新计算 next_run_at。"""
|
||||
"""
|
||||
启用排程并重新计算 next_run_at。
|
||||
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
|
||||
from app.services.schedule.scheduler_service import enable_task
|
||||
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
db.session.commit()
|
||||
try:
|
||||
task = enable_task(task)
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc)) from exc
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ class Config:
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
|
||||
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.json'
|
||||
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||
|
||||
@@ -25,10 +25,29 @@ def _get_current_user() -> User:
|
||||
return user
|
||||
|
||||
|
||||
def _resolve_request_agent_id() -> str | None:
|
||||
"""
|
||||
从 JSON body、query 或 multipart form 解析 agent_id。
|
||||
|
||||
核心逻辑:Chat Turn 附件上传走 multipart/form-data,agent_id 在 form 字段而非 JSON body。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
return (
|
||||
data.get("agent_id")
|
||||
or data.get("agentId")
|
||||
or request.args.get("agent_id")
|
||||
or request.args.get("agentId")
|
||||
or request.form.get("agent_id")
|
||||
or request.form.get("agentId")
|
||||
)
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -37,8 +56,7 @@ def require_agent_permission(f):
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
agent_id = _resolve_request_agent_id()
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
|
||||
@@ -33,6 +33,8 @@ class ScheduleTask(Base):
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
data_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# platform_job 结构化参数(按 job_registry.params_schema 校验后写入)
|
||||
job_params: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
|
||||
@@ -340,6 +340,9 @@ def _register_headers_from_config() -> None:
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
|
||||
|
||||
register_inventory_rpa_excel_headers()
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
|
||||
@@ -3,7 +3,8 @@ backend/app/services/schedule/faq_hot_aggregate_job.py
|
||||
|
||||
用途:排程管理触发的 FAQ 热点离线聚合执行器。
|
||||
依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
|
||||
逻辑:platform_api_path=faq-aggregate-hot 时由 job_registry 调用。
|
||||
逻辑:platform_api_path=faq-aggregate-hot 时由 job_registry 调用;
|
||||
参数取 task.job_params.app_id(schema 契约),历史任务回退 task.dify_agent_id。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,15 +16,28 @@ from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def _resolve_agent_filter(task: ScheduleTask) -> int | None:
|
||||
"""
|
||||
解析限定应用参数。
|
||||
核心逻辑:优先读结构化 job_params.app_id(params_schema 契约);
|
||||
历史任务回退 task.dify_agent_id(旧参数通道)。
|
||||
"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
raw = params.get("app_id")
|
||||
if raw not in (None, ""):
|
||||
return int(raw)
|
||||
return int(task.dify_agent_id) if task.dify_agent_id else None
|
||||
|
||||
|
||||
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行 FAQ 热点离线聚合(非 dry-run)。
|
||||
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
|
||||
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
|
||||
核心逻辑:委托 HotFaqAggregator;job_params.app_id(回退 dify_agent_id)可限定 Agent。
|
||||
@param task - 排程任务;参数经 job_registry.run_platform_job 按 params_schema 预校验
|
||||
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
|
||||
@returns ScheduleExecuteResult 元组
|
||||
"""
|
||||
agent_id = int(task.dify_agent_id) if task.dify_agent_id else None
|
||||
agent_id = _resolve_agent_filter(task)
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=False)
|
||||
|
||||
step_logs: list[dict[str, Any]] = [
|
||||
|
||||
@@ -60,6 +60,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=cfg,
|
||||
)
|
||||
# job_params 由 create_task/update_task 唯一归一化(导入跨环境不校选项范围)
|
||||
existing = None
|
||||
schedule_no = str(migrated.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
@@ -74,6 +75,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
|
||||
'dify_agent_id': migrated.get('dify_agent_id'),
|
||||
'platform_api_path': contract['platform_api_path'],
|
||||
'data_source_type': contract['data_source_type'],
|
||||
'job_params': migrated.get('job_params'),
|
||||
'notify_user_ids_json': migrated.get('notify_user_ids_json')
|
||||
if isinstance(migrated.get('notify_user_ids_json'), list)
|
||||
else [],
|
||||
@@ -83,7 +85,13 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
|
||||
'kb_group_id': migrated.get('kb_group_id'),
|
||||
}
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=actor_id, commit=False)
|
||||
update_task(
|
||||
existing,
|
||||
payload=task_payload,
|
||||
actor_id=actor_id,
|
||||
commit=False,
|
||||
check_options=False,
|
||||
)
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg, commit=False)
|
||||
else:
|
||||
@@ -97,6 +105,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
|
||||
dify_agent_id=task_payload['dify_agent_id'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
data_source_type=contract['data_source_type'],
|
||||
job_params=task_payload['job_params'],
|
||||
notify_user_ids_json=task_payload['notify_user_ids_json'],
|
||||
notify_enabled=task_payload['notify_enabled'],
|
||||
enabled=task_payload['enabled'],
|
||||
@@ -107,6 +116,7 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
|
||||
else None
|
||||
),
|
||||
actor_id=actor_id,
|
||||
check_options=False,
|
||||
commit=False,
|
||||
)
|
||||
if cfg:
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
backend/app/services/schedule/job_options.py
|
||||
|
||||
用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。
|
||||
依赖:models.Agent、shipping_notice.inventory_sources。
|
||||
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
||||
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def _agent_apps_options() -> list[dict[str, Any]]:
|
||||
"""启用中的 Agent 应用列表(value=agents.id)。"""
|
||||
from app.models import Agent
|
||||
|
||||
agents = (
|
||||
Agent.query.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{
|
||||
"label": agent.name,
|
||||
"value": agent.id,
|
||||
"description": (agent.description or "")[:120] or None,
|
||||
}
|
||||
for agent in agents
|
||||
]
|
||||
|
||||
|
||||
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
|
||||
"""启用中的货代库存源(value=source_code,来自 backend/config/shipping_inventory_sources.yaml)。"""
|
||||
from app.services.shipping_notice.inventory_sources import list_inventory_sources
|
||||
|
||||
return [
|
||||
{
|
||||
"label": source.get("display_name") or source.get("source_code"),
|
||||
"value": source.get("source_code"),
|
||||
"description": f"{source.get('site')} · {source.get('warehouse_id')}",
|
||||
}
|
||||
for source in list_inventory_sources()
|
||||
]
|
||||
|
||||
|
||||
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
|
||||
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"agent_apps": _agent_apps_options,
|
||||
"shipping_inventory_sources": _shipping_inventory_sources_options,
|
||||
}
|
||||
|
||||
|
||||
def is_known_options_source(source: str) -> bool:
|
||||
"""判断 options_source 是否已登记。"""
|
||||
return str(source or "").strip() in _OPTIONS_PROVIDERS
|
||||
|
||||
|
||||
def list_job_options(source: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
返回指定 options_source 的选项列表(统一 {label, value, description?} 结构)。
|
||||
Args:
|
||||
source: params_schema 中声明的 options_source 标识。
|
||||
Returns:
|
||||
选项列表;value 为 str/int,前端直接写入 job_params。
|
||||
Raises:
|
||||
ValueError: 未登记的 options_source。
|
||||
"""
|
||||
key = str(source or "").strip()
|
||||
provider = _OPTIONS_PROVIDERS.get(key)
|
||||
if not provider:
|
||||
raise ValueError(f"Unknown options source: {source}")
|
||||
return provider()
|
||||
@@ -0,0 +1,246 @@
|
||||
"""
|
||||
backend/app/services/schedule/job_params.py
|
||||
|
||||
用途:平台任务 job_params 统一校验与契约归一化(保存排程、切换任务、导入、执行前共用)。
|
||||
依赖:job_registry(读取 params_schema/defaults)、job_options(select 选项范围校验)、croniter(cron 校验)。
|
||||
逻辑:scheduler_service.create_task/update_task 为唯一写入前归一化入口(API/import 只传原始值);
|
||||
job_registry.run_platform_job 执行前调用 validate_task_params(check_options=False)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
# 高级参数逃生舱:折叠 JSON 区域的键,不做 schema 声明校验(兼容历史/特殊任务)
|
||||
ADVANCED_PARAMS_KEY = "_advanced"
|
||||
|
||||
_SUPPORTED_TYPES = frozenset({
|
||||
"text", "textarea", "number", "boolean", "select", "multi_select",
|
||||
"date", "datetime", "cron", "json", "info",
|
||||
})
|
||||
|
||||
|
||||
class JobParamsValidationError(ValueError):
|
||||
"""job_params 不满足注册表 params_schema。"""
|
||||
|
||||
|
||||
def _validate_scalar(field: dict[str, Any], value: Any) -> Any:
|
||||
"""
|
||||
按字段 type 校验并归一化单个值。
|
||||
核心逻辑:类型不符直接抛错,不做隐式转换(str "1" 不会转 number),
|
||||
仅 number 允许 int/float 互通。
|
||||
Raises:
|
||||
JobParamsValidationError: 类型或格式非法
|
||||
"""
|
||||
key = field.get("key")
|
||||
ftype = str(field.get("type") or "text")
|
||||
|
||||
if ftype in ("text", "textarea"):
|
||||
if not isinstance(value, str):
|
||||
raise JobParamsValidationError(f"param '{key}' must be a string")
|
||||
return value
|
||||
if ftype == "number":
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise JobParamsValidationError(f"param '{key}' must be a number")
|
||||
return value
|
||||
if ftype == "boolean":
|
||||
if not isinstance(value, bool):
|
||||
raise JobParamsValidationError(f"param '{key}' must be a boolean")
|
||||
return value
|
||||
if ftype == "select":
|
||||
if not isinstance(value, (str, int)):
|
||||
raise JobParamsValidationError(f"param '{key}' must be a string or integer option value")
|
||||
return value
|
||||
if ftype == "multi_select":
|
||||
if not isinstance(value, list) or any(not isinstance(item, (str, int)) for item in value):
|
||||
raise JobParamsValidationError(f"param '{key}' must be a list of option values")
|
||||
return value
|
||||
if ftype == "date":
|
||||
if not isinstance(value, str):
|
||||
raise JobParamsValidationError(f"param '{key}' must be a YYYY-MM-DD date string")
|
||||
try:
|
||||
datetime.strptime(value, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
raise JobParamsValidationError(f"param '{key}' is not a valid date (YYYY-MM-DD)")
|
||||
return value
|
||||
if ftype == "datetime":
|
||||
if not isinstance(value, str):
|
||||
raise JobParamsValidationError(f"param '{key}' must be an ISO datetime string")
|
||||
try:
|
||||
datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
raise JobParamsValidationError(f"param '{key}' is not a valid ISO datetime")
|
||||
return value
|
||||
if ftype == "cron":
|
||||
if not isinstance(value, str) or len(value.split()) != 5:
|
||||
raise JobParamsValidationError(f"param '{key}' must be a 5-field cron expression")
|
||||
try:
|
||||
from croniter import croniter
|
||||
|
||||
if not croniter.is_valid(value):
|
||||
raise JobParamsValidationError(f"param '{key}' is not a valid cron expression")
|
||||
except ImportError:
|
||||
pass
|
||||
return value
|
||||
if ftype == "json":
|
||||
if isinstance(value, (dict, list)):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
raise JobParamsValidationError(f"param '{key}' is not valid JSON")
|
||||
raise JobParamsValidationError(f"param '{key}' must be a JSON object/array")
|
||||
raise JobParamsValidationError(f"param '{key}' has unsupported type '{ftype}'")
|
||||
|
||||
|
||||
def _check_option_range(field: dict[str, Any], value: Any) -> None:
|
||||
"""
|
||||
校验 select/multi_select 值是否在 options_source 当前选项范围内。
|
||||
Raises:
|
||||
JobParamsValidationError: 值不在选项范围
|
||||
"""
|
||||
source = str(field.get("options_source") or "").strip()
|
||||
if not source:
|
||||
return
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
allowed = {str(option["value"]) for option in list_job_options(source)}
|
||||
values = value if isinstance(value, list) else [value]
|
||||
invalid = [str(item) for item in values if str(item) not in allowed]
|
||||
if invalid:
|
||||
raise JobParamsValidationError(
|
||||
f"param '{field.get('key')}' has values not in options of '{source}': {invalid}"
|
||||
)
|
||||
|
||||
|
||||
def validate_task_params(
|
||||
task_type: str,
|
||||
job_params: dict[str, Any] | None,
|
||||
*,
|
||||
check_options: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按注册表 params_schema 校验平台任务参数并返回归一化结果。
|
||||
【AI 触发时机】:保存排程(POST/PATCH /schedules)与执行平台任务前均须调用本函数。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] 查注册表拿 params_schema;未注册 key 抛错。
|
||||
[STEP 2] 未声明字段默认拒绝(_advanced 例外:原样透传,供折叠 JSON 高级配置兜底)。
|
||||
[STEP 3] 逐字段校验必填 + 类型 + 格式;缺省回填 field.default / defaults。
|
||||
[STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。
|
||||
|
||||
Args:
|
||||
task_type: platform job key(如 shipping-inventory-rpa)。
|
||||
job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。
|
||||
check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。
|
||||
|
||||
Returns:
|
||||
归一化后的参数 dict(含默认值回填与 _advanced 透传)。
|
||||
|
||||
Raises:
|
||||
JobParamsValidationError: 未注册任务、未声明字段、必填缺失或类型/格式/范围非法。
|
||||
"""
|
||||
from app.services.schedule.job_registry import get_platform_job
|
||||
|
||||
definition = get_platform_job(task_type)
|
||||
if not definition:
|
||||
raise JobParamsValidationError(f"Unknown platform job: {task_type}")
|
||||
|
||||
raw = dict(job_params or {})
|
||||
if not isinstance(raw, dict):
|
||||
raise JobParamsValidationError("job_params must be a JSON object")
|
||||
|
||||
schema_fields = [f for f in definition.params_schema if f.get("type") != "info"]
|
||||
declared_keys = {f.get("key") for f in schema_fields}
|
||||
|
||||
# [STEP 2] 未声明字段默认拒绝;_advanced 例外
|
||||
advanced = raw.pop(ADVANCED_PARAMS_KEY, None)
|
||||
if advanced is not None and not isinstance(advanced, dict):
|
||||
raise JobParamsValidationError(f"'{ADVANCED_PARAMS_KEY}' must be a JSON object")
|
||||
unknown = sorted(set(raw) - declared_keys)
|
||||
if unknown:
|
||||
raise JobParamsValidationError(f"unknown params for '{definition.key}': {unknown}")
|
||||
|
||||
# [STEP 3] 逐字段校验与默认值回填
|
||||
result: dict[str, Any] = {}
|
||||
for field in schema_fields:
|
||||
key = field.get("key")
|
||||
provided = key in raw
|
||||
value = raw.get(key)
|
||||
if value is None or (not provided):
|
||||
default = field.get("default", definition.defaults.get(key))
|
||||
result[key] = default
|
||||
if field.get("required") and result[key] in (None, "", []):
|
||||
raise JobParamsValidationError(f"param '{key}' is required")
|
||||
continue
|
||||
value = _validate_scalar(field, value)
|
||||
if field.get("required") and value in ("", []):
|
||||
raise JobParamsValidationError(f"param '{key}' is required")
|
||||
# [STEP 4] 选项范围校验(仅保存期)
|
||||
if check_options and field.get("type") in ("select", "multi_select") and value not in (None, []):
|
||||
_check_option_range(field, value)
|
||||
result[key] = value
|
||||
|
||||
if advanced:
|
||||
result[ADVANCED_PARAMS_KEY] = advanced
|
||||
return result
|
||||
|
||||
|
||||
def normalize_job_params_for_contract(
|
||||
schedule_type: str,
|
||||
platform_api_path: str | None,
|
||||
raw_job_params: Any = None,
|
||||
*,
|
||||
check_options: bool = True,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
按排程契约归一化 job_params(保存 / 切换任务 / 导入共用)。
|
||||
|
||||
核心逻辑:
|
||||
- 非 platform_job:禁止携带 job_params,返回 None。
|
||||
- platform_job 有 params_schema:raw 为 None 时按 {} 校验并回填默认值。
|
||||
- platform_job 无 params_schema:None → None;dict → 原样(空 dict 视为 None)。
|
||||
|
||||
Args:
|
||||
schedule_type: data_pipeline | platform_job
|
||||
platform_api_path: 平台任务 key
|
||||
raw_job_params: 请求体或既有参数;切换任务且未传时可传 None 触发默认值重置
|
||||
check_options: 是否校验 options_source 取值范围
|
||||
|
||||
Returns:
|
||||
归一化后的 job_params,或 None(无 schema / 非平台任务)
|
||||
|
||||
Raises:
|
||||
JobParamsValidationError: 类型非法、未知字段、schema/选项校验失败
|
||||
"""
|
||||
from app.services.schedule.schedule_contract import SCHEDULE_TYPE_PLATFORM_JOB
|
||||
|
||||
if schedule_type != SCHEDULE_TYPE_PLATFORM_JOB:
|
||||
if raw_job_params is not None:
|
||||
raise JobParamsValidationError("job_params is only supported for platform_job schedules")
|
||||
return None
|
||||
|
||||
from app.services.schedule.job_registry import get_platform_job
|
||||
|
||||
definition = get_platform_job(platform_api_path)
|
||||
has_schema = bool(definition and definition.params_schema)
|
||||
|
||||
if raw_job_params is None:
|
||||
if not has_schema:
|
||||
return None
|
||||
raw_job_params = {}
|
||||
|
||||
if not isinstance(raw_job_params, dict):
|
||||
raise JobParamsValidationError("job_params must be a JSON object")
|
||||
|
||||
if not has_schema:
|
||||
return raw_job_params or None
|
||||
|
||||
return validate_task_params(
|
||||
str(platform_api_path or ""),
|
||||
raw_job_params,
|
||||
check_options=check_options,
|
||||
)
|
||||
@@ -1,14 +1,15 @@
|
||||
"""
|
||||
backend/app/services/schedule/job_registry.py
|
||||
|
||||
用途:平台内置排程 Job Registry(key → handler)。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job。
|
||||
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key。
|
||||
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_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
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
@@ -22,7 +23,22 @@ _REGISTRY: dict[str, "PlatformJobDefinition"] = {}
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlatformJobDefinition:
|
||||
"""平台内置 Job 元数据与执行 handler。"""
|
||||
"""
|
||||
平台内置 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
|
||||
@@ -31,6 +47,13 @@ class PlatformJobDefinition:
|
||||
# 前端 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:
|
||||
@@ -44,6 +67,11 @@ def register_platform_job(definition: PlatformJobDefinition) -> None:
|
||||
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 {}),
|
||||
)
|
||||
|
||||
|
||||
@@ -70,25 +98,36 @@ def run_platform_job(
|
||||
) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行已注册平台 Job。
|
||||
核心逻辑:执行前按注册表 params_schema 再校验一次 task.job_params
|
||||
(check_options=False:选项集合可能随时间漂移,运行期只校验类型与必填),
|
||||
校验失败直接抛错终止本次 run。
|
||||
Args:
|
||||
key: platform_api_path job key
|
||||
task: 排程任务
|
||||
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}")
|
||||
_ = payload # 预留扩展;FAQ 等从 task 读取 dify_agent_id
|
||||
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。"""
|
||||
"""模块加载时注册内置平台 Job(含参数契约)。"""
|
||||
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
@@ -98,14 +137,51 @@ def _register_builtin_platform_jobs() -> None:
|
||||
label="货代库存 RPA",
|
||||
label_key="admin.schedule.form.platformJobShippingInventory",
|
||||
handler=run_shipping_inventory_rpa_schedule,
|
||||
description="批量写入库存 RPA export trigger,由 freight_rpa_worker 异步导出。",
|
||||
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="faq-aggregate-hot",
|
||||
label="FAQ 热点聚合",
|
||||
label_key="admin.schedule.form.platformJobFaqHotAggregate",
|
||||
handler=run_faq_hot_aggregate_schedule,
|
||||
description="ChatLog 热点发现,结果写入 faq_hot_candidates。",
|
||||
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",
|
||||
@@ -113,6 +189,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
label_key="admin.schedule.form.platformJobFixedAssetsSnapshot",
|
||||
handler=run_fixed_assets_snapshot_schedule,
|
||||
description="同步 PLM 固资快照至本地 manifest。",
|
||||
category="assets",
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
|
||||
'dify_agent_id': task.dify_agent_id,
|
||||
'platform_api_path': task.platform_api_path,
|
||||
'data_source_type': task.data_source_type,
|
||||
'job_params': task.job_params,
|
||||
'kb_sync_enabled': bool(getattr(task, 'kb_sync_enabled', False)),
|
||||
'kb_group_id': getattr(task, 'kb_group_id', None),
|
||||
'notify_user_ids_json': task.notify_user_ids_json or [],
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/services/schedule/schedule_contract.py
|
||||
|
||||
用途:排程三层语义校验与旧数据迁移(schedule_type / data_source_type / platform_api_path)。
|
||||
依赖:job_registry.get_platform_job。
|
||||
逻辑:scheduler_service、api/schedule/tasks、import_service 创建/更新/导入前调用。
|
||||
依赖:job_registry.get_platform_job(含 enabled 停用判定,含 config 白名单)。
|
||||
逻辑:scheduler_service、api/schedule/tasks、import_service 创建/更新/导入前调用;
|
||||
enabled=False 的平台任务在契约校验阶段即拒绝新建/改指向;
|
||||
platform_job_allows_config 同步要求 registry enabled,禁止给停用任务写 ScheduleTaskConfig。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,8 +33,19 @@ PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
|
||||
|
||||
|
||||
def platform_job_allows_config(key: str | None) -> bool:
|
||||
"""判断该 platform_job 是否允许写 ScheduleTaskConfig。"""
|
||||
return normalize_job_key(key) in PLATFORM_JOBS_ALLOWING_CONFIG
|
||||
"""
|
||||
判断该 platform_job 是否允许写 ScheduleTaskConfig。
|
||||
|
||||
核心逻辑:须在白名单内,且 registry 中存在且 enabled=True。
|
||||
停用任务与创建/更新/执行一致,禁止继续改其 ScheduleTaskConfig。
|
||||
"""
|
||||
normalized = normalize_job_key(key)
|
||||
if normalized not in PLATFORM_JOBS_ALLOWING_CONFIG:
|
||||
return False
|
||||
from app.services.schedule.job_registry import get_platform_job
|
||||
|
||||
definition = get_platform_job(normalized)
|
||||
return bool(definition and definition.enabled)
|
||||
|
||||
|
||||
def assert_schedule_config_writable(
|
||||
@@ -44,7 +57,7 @@ def assert_schedule_config_writable(
|
||||
"""
|
||||
携带 config 时校验是否允许写入 ScheduleTaskConfig。
|
||||
Raises:
|
||||
ValueError: 非白名单 platform_job 携带 config
|
||||
ValueError: 非白名单 / 已停用 platform_job 携带 config
|
||||
"""
|
||||
if not config or not isinstance(config, dict):
|
||||
return
|
||||
@@ -156,11 +169,11 @@ def validate_schedule_fields(
|
||||
Args:
|
||||
schedule_type: data_pipeline | platform_job
|
||||
data_source_type: 仅 data_pipeline 必填
|
||||
platform_api_path: 仅 platform_job 必填且须已注册
|
||||
platform_api_path: 仅 platform_job 必填且须已注册且 enabled
|
||||
Returns:
|
||||
(schedule_type, data_source_type, platform_api_path)
|
||||
Raises:
|
||||
ValueError: schedule_type 未知、字段组合非法或未注册 job key
|
||||
ValueError: schedule_type 未知、字段组合非法、未注册或已停用 job key
|
||||
"""
|
||||
st = str(schedule_type or "").strip().lower()
|
||||
if st not in VALID_SCHEDULE_TYPES:
|
||||
@@ -180,8 +193,12 @@ def validate_schedule_fields(
|
||||
raise ValueError("platform_api_path is required for platform_job")
|
||||
from app.services.schedule.job_registry import get_platform_job
|
||||
|
||||
if not get_platform_job(path):
|
||||
definition = get_platform_job(path)
|
||||
if not definition:
|
||||
raise ValueError(f"Unknown platform job key: {path}")
|
||||
# enabled=False 表示任务停用:不可新建/改指向该 key(列表接口也不展示)
|
||||
if not definition.enabled:
|
||||
raise ValueError(f"Platform job is disabled: {path}")
|
||||
return st, None, path
|
||||
|
||||
raise ValueError(f"Unsupported schedule_type: {schedule_type}")
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
"""
|
||||
backend/app/services/schedule/scheduler_service.py
|
||||
|
||||
用途:排程任务生命周期(创建/更新/立即执行)与后台调度 worker。
|
||||
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
|
||||
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
|
||||
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
|
||||
未传参时重置默认值);run_task_now 经 resolve_schedule_executor 分发 handler。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
@@ -14,6 +23,14 @@ from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
is_awaiting_rpa_schedule_run,
|
||||
recover_all_stale_awaiting_rpa_schedule_runs,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
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
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
|
||||
|
||||
@@ -94,6 +111,9 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
f'状态: {status_label}\n'
|
||||
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
|
||||
)
|
||||
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 生成失败'
|
||||
|
||||
media_id = None
|
||||
if run.excel_file_data and run.excel_file_name:
|
||||
@@ -166,6 +186,7 @@ def create_task(
|
||||
dify_agent_id: int | None,
|
||||
platform_api_path: str | None,
|
||||
data_source_type: str | None,
|
||||
job_params: dict[str, Any] | None = None,
|
||||
notify_user_ids_json: list[int] | None,
|
||||
notify_enabled: bool,
|
||||
enabled: bool,
|
||||
@@ -173,7 +194,15 @@ def create_task(
|
||||
kb_group_id: int | None = None,
|
||||
actor_id: int | None,
|
||||
commit: bool = True,
|
||||
check_options: bool = True,
|
||||
) -> ScheduleTask:
|
||||
"""
|
||||
创建排程任务。
|
||||
|
||||
核心逻辑:契约校验后,job_params 经 normalize_job_params_for_contract 唯一归一化再写入。
|
||||
Args:
|
||||
check_options: 是否校验 select/multi_select 选项范围;导入跨环境时传 False。
|
||||
"""
|
||||
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
|
||||
|
||||
cron_expr = normalize_cron_expr(cron_expr)
|
||||
@@ -182,6 +211,12 @@ def create_task(
|
||||
'data_source_type': data_source_type,
|
||||
'platform_api_path': platform_api_path,
|
||||
})
|
||||
normalized_job_params = normalize_job_params_for_contract(
|
||||
contract['schedule_type'],
|
||||
contract['platform_api_path'],
|
||||
job_params,
|
||||
check_options=check_options,
|
||||
)
|
||||
task = ScheduleTask(
|
||||
schedule_no=_generate_schedule_no(),
|
||||
name=name,
|
||||
@@ -193,6 +228,7 @@ def create_task(
|
||||
dify_agent_id=dify_agent_id,
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
data_source_type=contract['data_source_type'],
|
||||
job_params=normalized_job_params,
|
||||
kb_sync_enabled=bool(kb_sync_enabled),
|
||||
kb_group_id=kb_group_id,
|
||||
notify_user_ids_json=notify_user_ids_json or [],
|
||||
@@ -219,8 +255,20 @@ def update_task(
|
||||
payload: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
commit: bool = True,
|
||||
check_options: bool = True,
|
||||
) -> ScheduleTask:
|
||||
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
|
||||
"""
|
||||
更新排程任务字段。
|
||||
|
||||
核心逻辑:契约字段与 job_params 在本层统一归一化——显式传 job_params 时按新契约校验;
|
||||
切换 platform_api_path 且未传 job_params 时重置为新 schema 默认值(或清空)。
|
||||
Args:
|
||||
check_options: 是否校验 select/multi_select 选项范围;导入跨环境时传 False。
|
||||
"""
|
||||
from app.services.schedule.schedule_contract import (
|
||||
apply_schedule_contract_to_payload,
|
||||
normalize_job_key,
|
||||
)
|
||||
|
||||
for key in [
|
||||
"name",
|
||||
@@ -248,7 +296,10 @@ def update_task(
|
||||
raw_group_id = payload.get("kb_group_id")
|
||||
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
|
||||
|
||||
if any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path")):
|
||||
# [STEP 1] 契约字段:有变更则校验并写回;否则沿用当前任务三层语义
|
||||
previous_path = task.platform_api_path
|
||||
contract_touched = any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path"))
|
||||
if contract_touched:
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
"schedule_type": payload.get("schedule_type", task.schedule_type),
|
||||
"data_source_type": payload.get("data_source_type", task.data_source_type),
|
||||
@@ -257,6 +308,32 @@ def update_task(
|
||||
task.schedule_type = contract["schedule_type"]
|
||||
task.data_source_type = contract["data_source_type"]
|
||||
task.platform_api_path = contract["platform_api_path"]
|
||||
else:
|
||||
contract = {
|
||||
"schedule_type": task.schedule_type,
|
||||
"data_source_type": task.data_source_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
}
|
||||
|
||||
# [STEP 2] job_params 唯一归一化入口:显式传参 / 切换 job key 重置 / 非平台任务清空
|
||||
path_changed = normalize_job_key(previous_path) != normalize_job_key(contract["platform_api_path"])
|
||||
if "job_params" in payload:
|
||||
task.job_params = normalize_job_params_for_contract(
|
||||
contract["schedule_type"],
|
||||
contract["platform_api_path"],
|
||||
payload.get("job_params"),
|
||||
check_options=check_options,
|
||||
)
|
||||
elif contract_touched and (
|
||||
contract["schedule_type"] != "platform_job"
|
||||
or path_changed
|
||||
):
|
||||
task.job_params = normalize_job_params_for_contract(
|
||||
contract["schedule_type"],
|
||||
contract["platform_api_path"],
|
||||
None,
|
||||
check_options=check_options,
|
||||
)
|
||||
|
||||
if task.enabled and task.cron_expr:
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
|
||||
@@ -270,7 +347,51 @@ def update_task(
|
||||
return task
|
||||
|
||||
|
||||
def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool = True) -> ScheduleTask:
|
||||
"""
|
||||
启用排程并重新计算 next_run_at。
|
||||
|
||||
核心逻辑:启用前重新校验三层契约(含 registry enabled);platform_job 顺带归一化 job_params,
|
||||
避免停用任务或失效参数被重新放入调度队列。
|
||||
Args:
|
||||
check_options: 是否校验 select/multi_select 选项范围。
|
||||
Raises:
|
||||
ValueError: 契约非法、平台任务已停用或 job_params 校验失败。
|
||||
"""
|
||||
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
|
||||
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': task.schedule_type,
|
||||
'data_source_type': task.data_source_type,
|
||||
'platform_api_path': task.platform_api_path,
|
||||
})
|
||||
task.schedule_type = contract['schedule_type']
|
||||
task.data_source_type = contract['data_source_type']
|
||||
task.platform_api_path = contract['platform_api_path']
|
||||
if contract['schedule_type'] == 'platform_job':
|
||||
task.job_params = normalize_job_params_for_contract(
|
||||
contract['schedule_type'],
|
||||
contract['platform_api_path'],
|
||||
task.job_params,
|
||||
check_options=check_options,
|
||||
)
|
||||
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
|
||||
if run is None:
|
||||
existing = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
@@ -319,6 +440,19 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
clear_cancelled_run(run.id)
|
||||
return run
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
return apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
@@ -449,13 +583,27 @@ def start_scheduler(app):
|
||||
stuck = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.status == "running",
|
||||
).all()
|
||||
cleaned = 0
|
||||
for r in stuck:
|
||||
if is_awaiting_rpa_schedule_run(r):
|
||||
continue
|
||||
r.status = "failed"
|
||||
r.error_message = "服务重启,执行中断"
|
||||
r.finished_at = datetime.utcnow()
|
||||
if stuck:
|
||||
cleaned += 1
|
||||
if cleaned:
|
||||
db.session.commit()
|
||||
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
|
||||
current_app.logger.info(
|
||||
"[schedule-worker] cleaned %d stuck running runs on startup (skipped awaiting RPA)",
|
||||
cleaned,
|
||||
)
|
||||
|
||||
recovered_awaiting = recover_all_stale_awaiting_rpa_schedule_runs()
|
||||
if recovered_awaiting:
|
||||
current_app.logger.info(
|
||||
"[schedule-worker] recovered %d stale awaiting RPA runs on startup",
|
||||
recovered_awaiting,
|
||||
)
|
||||
|
||||
while True:
|
||||
try:
|
||||
@@ -466,6 +614,7 @@ def start_scheduler(app):
|
||||
ScheduleTask.next_run_at <= now,
|
||||
).limit(5).with_for_update(skip_locked=True).all()
|
||||
for task in due_tasks:
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
has_running = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_finalize.py
|
||||
|
||||
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
|
||||
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
|
||||
逻辑:shipping_inventory_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
|
||||
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule import register_schedule_header, resolve_schedule_header
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule import normalize_platform_api_path
|
||||
from app.services.shipping_notice.tool_common import rpa_inventory_timeout_seconds
|
||||
|
||||
SHIPPING_INVENTORY_RPA_JOB_KEY = "shipping-inventory-rpa"
|
||||
AWAITING_RPA_CALLBACK_STATUS = "awaiting_rpa_callback"
|
||||
|
||||
FinalizeScheduleRunResult = dict[str, Any]
|
||||
|
||||
_INVENTORY_RPA_HEADER_ORDER = [
|
||||
"source_code",
|
||||
"warehouse_id",
|
||||
"display_name",
|
||||
"inventory_file_no",
|
||||
"export_status",
|
||||
"error_message",
|
||||
]
|
||||
_INVENTORY_RPA_HEADER_LABELS = {
|
||||
"source_code": "库存源",
|
||||
"warehouse_id": "仓库",
|
||||
"display_name": "名称",
|
||||
"inventory_file_no": "库存快照号",
|
||||
"export_status": "导出状态",
|
||||
"error_message": "错误原因",
|
||||
}
|
||||
|
||||
|
||||
def register_inventory_rpa_excel_headers() -> None:
|
||||
"""
|
||||
注册货代库存 RPA 排程 Excel 列头(幂等)。
|
||||
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
|
||||
"""
|
||||
register_schedule_header(
|
||||
SHIPPING_INVENTORY_RPA_JOB_KEY,
|
||||
_INVENTORY_RPA_HEADER_ORDER,
|
||||
_INVENTORY_RPA_HEADER_LABELS,
|
||||
)
|
||||
|
||||
|
||||
def is_awaiting_rpa_schedule_run(run: ScheduleRun | None) -> bool:
|
||||
"""判断 run 是否处于等待 RPA 回调的 running 态。"""
|
||||
if not run or run.status != "running":
|
||||
return False
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
return bool(summary.get("awaiting_rpa"))
|
||||
|
||||
|
||||
def _source_identity_key(source_code: Any, warehouse_id: Any) -> tuple[str, str]:
|
||||
"""库存源匹配键:(source_code, warehouse_id) 均 uppercase。"""
|
||||
return (
|
||||
str(source_code or "").strip().upper(),
|
||||
str(warehouse_id or "").strip().upper(),
|
||||
)
|
||||
|
||||
|
||||
def is_shipping_inventory_rpa_task(task: ScheduleTask | None) -> bool:
|
||||
"""判断是否为货代库存 RPA 平台排程任务。"""
|
||||
if not task or task.schedule_type != "platform_job":
|
||||
return False
|
||||
return normalize_platform_api_path(task.platform_api_path) == SHIPPING_INVENTORY_RPA_JOB_KEY
|
||||
|
||||
|
||||
def is_awaiting_rpa_callback(step_logs: list | None) -> bool:
|
||||
"""step_logs 是否包含 awaiting_rpa_callback 标记。"""
|
||||
if not step_logs:
|
||||
return False
|
||||
return any(
|
||||
isinstance(item, dict) and item.get("status") == AWAITING_RPA_CALLBACK_STATUS
|
||||
for item in step_logs
|
||||
)
|
||||
|
||||
|
||||
def should_defer_schedule_run_finalization(task: ScheduleTask, step_logs: list | None) -> bool:
|
||||
"""货代库存 RPA 写 trigger 成功后应 defer 终态。"""
|
||||
return is_shipping_inventory_rpa_task(task) and is_awaiting_rpa_callback(step_logs)
|
||||
|
||||
|
||||
def _compute_run_status(*, total_count: int, success_count: int, failed_count: int) -> str:
|
||||
"""
|
||||
根据成功/失败数计算排程终态。
|
||||
核心逻辑:须 success_count == total_count 且无失败才算 success;全失败 failed;否则 partial_failed。
|
||||
"""
|
||||
if total_count <= 0:
|
||||
return "failed"
|
||||
if success_count >= total_count and failed_count == 0:
|
||||
return "success"
|
||||
if success_count == 0:
|
||||
return "failed"
|
||||
return "partial_failed"
|
||||
|
||||
|
||||
def _build_finalize_details(
|
||||
pending_details: list[dict[str, Any]],
|
||||
*,
|
||||
created: list[dict[str, Any]],
|
||||
failed: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
合并 trigger 阶段 pending 明细与 RPA 回调结果,供 Excel 导出。
|
||||
核心逻辑:按 (source_code, warehouse_id) 对齐;未回调的 pending 源补为 failed。
|
||||
"""
|
||||
pending_by_key: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for item in pending_details:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get("source_code") or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
pending_by_key[_source_identity_key(code, item.get("warehouse_id"))] = item
|
||||
|
||||
handled_keys: set[tuple[str, str]] = set()
|
||||
details: list[dict[str, Any]] = []
|
||||
for item in created:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get("source_code") or "").strip()
|
||||
wh = str(item.get("warehouse_id") or "").strip()
|
||||
key = _source_identity_key(code, wh)
|
||||
handled_keys.add(key)
|
||||
base = pending_by_key.get(key, {})
|
||||
details.append({
|
||||
"source_code": code or item.get("source_code"),
|
||||
"warehouse_id": wh or base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": item.get("inventory_file_no"),
|
||||
"export_status": "success",
|
||||
"error_message": "",
|
||||
})
|
||||
for item in failed:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get("source_code") or "").strip()
|
||||
wh = str(item.get("warehouse_id") or "").strip()
|
||||
key = _source_identity_key(code, wh)
|
||||
handled_keys.add(key)
|
||||
base = pending_by_key.get(key, {})
|
||||
details.append({
|
||||
"source_code": code or item.get("source_code"),
|
||||
"warehouse_id": wh or base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": "",
|
||||
"export_status": "failed",
|
||||
"error_message": str(item.get("error") or item.get("error_message") or "export failed")[:500],
|
||||
})
|
||||
for key, base in pending_by_key.items():
|
||||
if key in handled_keys:
|
||||
continue
|
||||
details.append({
|
||||
"source_code": base.get("source_code"),
|
||||
"warehouse_id": base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": "",
|
||||
"export_status": "failed",
|
||||
"error_message": "RPA callback missing",
|
||||
})
|
||||
return details
|
||||
|
||||
|
||||
def apply_deferred_schedule_run_state(
|
||||
run: ScheduleRun,
|
||||
task: ScheduleTask,
|
||||
*,
|
||||
total_count: int,
|
||||
success_count: int,
|
||||
failed_count: int,
|
||||
skipped_count: int,
|
||||
details: list[dict[str, Any]],
|
||||
errors: list[str],
|
||||
step_logs: list[dict[str, Any]] | None,
|
||||
) -> ScheduleRun:
|
||||
"""
|
||||
trigger 已写入、等待 RPA 回调:保持 running,记录 awaiting 元数据,跳过终态收尾。
|
||||
核心逻辑:复用 run 时若 started_at 为空则补写,避免 recover 立即判超时。
|
||||
"""
|
||||
run.status = "running"
|
||||
if not run.started_at:
|
||||
run.started_at = datetime.utcnow()
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.finished_at = None
|
||||
run.duration_ms = 0
|
||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
||||
run.response_summary_json = {
|
||||
"awaiting_rpa": True,
|
||||
"pending_details": details,
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
"schedule_finalize_status": None,
|
||||
"schedule_finalize_error": None,
|
||||
}
|
||||
run.excel_file_data = None
|
||||
run.excel_file_name = None
|
||||
run.excel_file_size = 0
|
||||
db.session.commit()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[schedule-run] run_no=%s deferred awaiting_rpa_callback total=%d",
|
||||
run.run_no,
|
||||
total_count,
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def _try_recover_stale_awaiting_run(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
cutoff: datetime,
|
||||
timeout_seconds: int,
|
||||
require_inventory_rpa_task: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
尝试回收单条超时 awaiting RPA run。
|
||||
核心逻辑:可选校验 task 为货代库存 RPA,避免其他流程复用 awaiting_rpa 字段被误杀。
|
||||
Returns:
|
||||
bool: 是否已标记回收(未 commit,由调用方统一提交)。
|
||||
"""
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if not summary.get("awaiting_rpa"):
|
||||
return False
|
||||
if require_inventory_rpa_task:
|
||||
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
|
||||
if not is_shipping_inventory_rpa_task(task):
|
||||
return False
|
||||
if run.started_at is None:
|
||||
return False
|
||||
if run.started_at > cutoff:
|
||||
return False
|
||||
|
||||
finished_at = datetime.utcnow()
|
||||
step_logs = list(run.step_logs or [])
|
||||
step_logs.append({
|
||||
"step": "shipping_inventory_rpa",
|
||||
"status": "failed",
|
||||
"detail": {"message": "RPA 库存导出等待超时", "timeout_seconds": timeout_seconds},
|
||||
})
|
||||
run.status = "failed"
|
||||
run.finished_at = finished_at
|
||||
run.duration_ms = int((finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.error_message = "RPA 库存导出等待超时"
|
||||
run.step_logs = step_logs
|
||||
summary = dict(summary)
|
||||
summary["awaiting_rpa"] = False
|
||||
summary["recovered_reason"] = "rpa_callback_timeout"
|
||||
run.response_summary_json = summary
|
||||
return True
|
||||
|
||||
|
||||
def recover_stale_awaiting_rpa_schedule_runs(task: ScheduleTask) -> int:
|
||||
"""
|
||||
回收超时的 awaiting RPA 排程 run,避免后续执行被 running 卡住。
|
||||
核心逻辑:仅处理 response_summary_json.awaiting_rpa=true 的 running run。
|
||||
Returns:
|
||||
int: 回收条数
|
||||
"""
|
||||
if not is_shipping_inventory_rpa_task(task):
|
||||
return 0
|
||||
|
||||
timeout_seconds = max(60, rpa_inventory_timeout_seconds())
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
|
||||
stale_runs = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
)
|
||||
.all()
|
||||
)
|
||||
recovered = 0
|
||||
for run in stale_runs:
|
||||
if _try_recover_stale_awaiting_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds):
|
||||
recovered += 1
|
||||
|
||||
if recovered:
|
||||
db.session.commit()
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[schedule-run] recovered %d stale awaiting_rpa runs task_id=%s",
|
||||
recovered,
|
||||
task.id,
|
||||
)
|
||||
return recovered
|
||||
|
||||
|
||||
def recover_all_stale_awaiting_rpa_schedule_runs() -> int:
|
||||
"""
|
||||
全局扫描并回收已超时的 awaiting RPA run(服务启动时调用)。
|
||||
核心逻辑:不依赖 task 是否 due,启动后立即清理陈旧 running。
|
||||
Returns:
|
||||
int: 回收条数
|
||||
"""
|
||||
timeout_seconds = max(60, rpa_inventory_timeout_seconds())
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
|
||||
runs = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
|
||||
recovered = 0
|
||||
for run in runs:
|
||||
if _try_recover_stale_awaiting_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds):
|
||||
recovered += 1
|
||||
if recovered:
|
||||
db.session.commit()
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[schedule-run] recovered %d stale awaiting_rpa runs on startup sweep",
|
||||
recovered,
|
||||
)
|
||||
return recovered
|
||||
|
||||
|
||||
def _record_finalize_failure(run: ScheduleRun, exc: Exception) -> None:
|
||||
"""finalize 失败时保留 awaiting 态并写入错误摘要,便于回调安全重试。"""
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary["awaiting_rpa"] = True
|
||||
summary["schedule_finalize_status"] = "failed"
|
||||
summary["schedule_finalize_error"] = str(exc)[:500]
|
||||
run.response_summary_json = summary
|
||||
run.error_message = f"排程终态化失败: {exc}"[:500]
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def finalize_shipping_inventory_schedule_run(
|
||||
schedule_run_id: int,
|
||||
*,
|
||||
created: list[dict[str, Any]],
|
||||
failed: list[dict[str, Any]],
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> FinalizeScheduleRunResult:
|
||||
"""
|
||||
RPA 批量回调后终态化排程 run:计数、Excel、KB 同步、企微通知。
|
||||
核心逻辑:awaiting_rpa=true 且 running 时可执行;已终态则幂等返回;失败保留 awaiting 供重试。
|
||||
Returns:
|
||||
FinalizeScheduleRunResult: ok / already_finalized / schedule_finalize_status / error
|
||||
"""
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if not run:
|
||||
return {"ok": False, "error": "schedule run not found", "schedule_finalize_status": "skipped"}
|
||||
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if run.status != "running":
|
||||
if run.status in {"success", "failed", "partial_failed"} and not summary.get("awaiting_rpa"):
|
||||
return {
|
||||
"ok": True,
|
||||
"already_finalized": True,
|
||||
"schedule_finalize_status": "ok",
|
||||
"run_status": run.status,
|
||||
}
|
||||
return {
|
||||
"ok": False,
|
||||
"error": f"schedule run status is {run.status}",
|
||||
"schedule_finalize_status": "skipped",
|
||||
}
|
||||
|
||||
if not summary.get("awaiting_rpa"):
|
||||
return {"ok": False, "error": "schedule run is not awaiting RPA callback", "schedule_finalize_status": "skipped"}
|
||||
|
||||
try:
|
||||
return _finalize_shipping_inventory_schedule_run_impl(run, created=created, failed=failed, payload=payload)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
_record_finalize_failure(run, exc)
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[schedule-run] finalize failed run_id=%s run_no=%s: %s",
|
||||
run.id,
|
||||
run.run_no,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
return {
|
||||
"ok": False,
|
||||
"error": str(exc),
|
||||
"schedule_finalize_status": "failed",
|
||||
"manual_retryable": True,
|
||||
}
|
||||
|
||||
|
||||
def _finalize_shipping_inventory_schedule_run_impl(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
created: list[dict[str, Any]],
|
||||
failed: list[dict[str, Any]],
|
||||
payload: dict[str, Any] | None,
|
||||
) -> FinalizeScheduleRunResult:
|
||||
"""finalize 主流程(内部使用,异常由外层捕获并记录)。"""
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
|
||||
if not task:
|
||||
raise RuntimeError("schedule task not found")
|
||||
|
||||
pending_details = summary.get("pending_details") if isinstance(summary.get("pending_details"), list) else []
|
||||
details = _build_finalize_details(pending_details, created=created, failed=failed)
|
||||
success_count = sum(1 for item in details if item.get("export_status") == "success")
|
||||
failed_count = sum(1 for item in details if item.get("export_status") == "failed")
|
||||
total_count = max(int(run.total_count or 0), len(pending_details), len(details))
|
||||
status = _compute_run_status(
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
)
|
||||
|
||||
finished_at = datetime.utcnow()
|
||||
duration_ms = 0
|
||||
if run.started_at:
|
||||
duration_ms = int((finished_at - run.started_at).total_seconds() * 1000)
|
||||
|
||||
errors: list[str] = []
|
||||
if failed_count:
|
||||
errors.extend(
|
||||
f"{item.get('source_code')}/{item.get('warehouse_id')}: {item.get('error_message')}"
|
||||
for item in details
|
||||
if item.get("export_status") == "failed" and item.get("error_message")
|
||||
)
|
||||
|
||||
register_inventory_rpa_excel_headers()
|
||||
header_order, header_labels = resolve_schedule_header(SHIPPING_INVENTORY_RPA_JOB_KEY)
|
||||
excel_export_ok = True
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(
|
||||
run_no=run.run_no,
|
||||
summary={
|
||||
"status": status,
|
||||
"total_count": total_count,
|
||||
"success_count": success_count,
|
||||
"failed_count": failed_count,
|
||||
"duration_ms": duration_ms,
|
||||
},
|
||||
details=details,
|
||||
header_order=header_order,
|
||||
header_labels=header_labels,
|
||||
)
|
||||
except Exception as excel_exc:
|
||||
excel_export_ok = False
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] inventory RPA excel export failed: %s", excel_exc)
|
||||
file_data, file_name, file_size = None, None, 0
|
||||
errors.append(f"Excel导出失败: {excel_exc}")
|
||||
if status == "success":
|
||||
status = "partial_failed"
|
||||
|
||||
step_logs = list(run.step_logs or [])
|
||||
step_logs.append({
|
||||
"step": "shipping_inventory_rpa",
|
||||
"status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed",
|
||||
"detail": {
|
||||
"created_count": success_count,
|
||||
"failed_count": failed_count,
|
||||
"rpa_mode": (payload or {}).get("rpa_mode"),
|
||||
"run_no": (payload or {}).get("run_no"),
|
||||
"excel_export_ok": excel_export_ok,
|
||||
},
|
||||
})
|
||||
|
||||
run.finished_at = finished_at
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.step_logs = step_logs
|
||||
run.api_response_json = {
|
||||
"run_no": (payload or {}).get("run_no"),
|
||||
"rpa_mode": (payload or {}).get("rpa_mode"),
|
||||
"created": created,
|
||||
"failed": failed,
|
||||
}
|
||||
run.response_summary_json = {
|
||||
"awaiting_rpa": False,
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
"schedule_finalize_status": "ok",
|
||||
"schedule_finalize_error": None,
|
||||
"excel_export_status": "ok" if excel_export_ok else "failed",
|
||||
"excel_failed": not excel_export_ok,
|
||||
"rpa_finalize": {
|
||||
"created_count": success_count,
|
||||
"failed_count": failed_count,
|
||||
"excel_failed": not excel_export_ok,
|
||||
},
|
||||
}
|
||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
task.last_run_at = finished_at
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] inventory RPA kb sync failed: %s", kb_exc, exc_info=True)
|
||||
run.kb_sync_status = "failed"
|
||||
run.kb_group_id = getattr(task, "kb_group_id", None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
if 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:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] inventory RPA wecom notify failed: %s", wecom_exc)
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[schedule-run] run_no=%s finalized after RPA callback status=%s success=%d failed=%d",
|
||||
run.run_no,
|
||||
status,
|
||||
success_count,
|
||||
failed_count,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"schedule_finalize_status": "ok",
|
||||
"run_status": status,
|
||||
"success_count": success_count,
|
||||
"failed_count": failed_count,
|
||||
}
|
||||
@@ -3,7 +3,8 @@ backend/app/services/schedule/shipping_inventory_rpa_job.py
|
||||
|
||||
用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。
|
||||
依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
|
||||
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用。
|
||||
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用;
|
||||
写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,6 +15,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
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
|
||||
|
||||
@@ -35,24 +37,90 @@ def _parse_api_body_template(task: ScheduleTask) -> dict[str, Any] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_filter_tokens(raw: Any) -> set[str]:
|
||||
"""
|
||||
将 JSON 中的筛选值归一为 uppercase token 集合。
|
||||
核心逻辑:支持 str / list;忽略空值。
|
||||
"""
|
||||
if isinstance(raw, str):
|
||||
values = [raw]
|
||||
elif isinstance(raw, list):
|
||||
values = raw
|
||||
else:
|
||||
return set()
|
||||
return {str(item).strip().upper() for item in values if str(item).strip()}
|
||||
|
||||
|
||||
def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
|
||||
"""收集库存源可用于匹配的标识集合(source_code / warehouse_id / match_aliases)。"""
|
||||
tokens: set[str] = set()
|
||||
for key in ("source_code", "warehouse_id", "warehouse_code"):
|
||||
value = str(source.get(key) or "").strip().upper()
|
||||
if value:
|
||||
tokens.add(value)
|
||||
for alias in source.get("match_aliases") or []:
|
||||
value = str(alias or "").strip().upper()
|
||||
if value:
|
||||
tokens.add(value)
|
||||
return tokens
|
||||
|
||||
|
||||
def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]:
|
||||
"""
|
||||
从 api_body_template 提取筛选 token。
|
||||
推荐键:source_codes;兼容:source_code / warehouse_ids / warehouse_id / match_aliases。
|
||||
"""
|
||||
wanted: set[str] = set()
|
||||
for key in (
|
||||
"source_codes",
|
||||
"source_code",
|
||||
"warehouse_ids",
|
||||
"warehouse_id",
|
||||
"match_aliases",
|
||||
):
|
||||
if key in body_template:
|
||||
wanted |= _normalize_filter_tokens(body_template.get(key))
|
||||
return wanted
|
||||
|
||||
|
||||
def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None:
|
||||
"""
|
||||
解析筛选参数来源。
|
||||
核心逻辑:优先结构化 job_params(含 _advanced 展平合并,params_schema 契约通道);
|
||||
历史任务回退 ScheduleTaskConfig.api_body_template JSON。
|
||||
"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else None
|
||||
if params:
|
||||
merged = {k: v for k, v in params.items() if k != "_advanced"}
|
||||
advanced = params.get("_advanced")
|
||||
if isinstance(advanced, dict):
|
||||
merged.update(advanced)
|
||||
if any(v not in (None, "", []) for v in merged.values()):
|
||||
return merged
|
||||
return _parse_api_body_template(task)
|
||||
|
||||
|
||||
def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
|
||||
"""读取 enabled 库存源;api_body_template 可限定 source_code 子集。"""
|
||||
"""
|
||||
读取 enabled 库存源;job_params / api_body_template 可限定子集。
|
||||
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / warehouse_id / match_aliases 命中。
|
||||
"""
|
||||
enabled = list_inventory_sources()
|
||||
body_template = _parse_api_body_template(task)
|
||||
body_template = _resolve_filter_payload(task)
|
||||
if body_template:
|
||||
codes = body_template.get("source_codes") or body_template.get("source_code")
|
||||
if isinstance(codes, str):
|
||||
codes = [codes]
|
||||
if isinstance(codes, list):
|
||||
wanted = {str(code).strip().upper() for code in codes if str(code).strip()}
|
||||
enabled = [item for item in enabled if str(item.get("source_code") or "").upper() in wanted]
|
||||
wanted = _extract_wanted_tokens(body_template)
|
||||
if wanted:
|
||||
enabled = [
|
||||
item for item in enabled
|
||||
if _source_identity_tokens(item) & wanted
|
||||
]
|
||||
return [source for source in enabled if build_rpa_inventory_source(source.get("source_code"))]
|
||||
|
||||
|
||||
def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。
|
||||
核心逻辑:不在排程内同步等待 RPA;ScheduleRun 记录 trigger 写入结果。
|
||||
核心逻辑:写 trigger 后返回 awaiting_rpa_callback;终态由 finalize 在回调时写入。
|
||||
"""
|
||||
sources = _filter_sources(task)
|
||||
step_logs: list[dict[str, Any]] = [{
|
||||
@@ -90,7 +158,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
|
||||
|
||||
step_logs.append({
|
||||
"step": "shipping_inventory_rpa",
|
||||
"status": "triggered",
|
||||
"status": AWAITING_RPA_CALLBACK_STATUS,
|
||||
"detail": {"trigger_path": trigger_path, "run_no": run_no},
|
||||
})
|
||||
details = [
|
||||
@@ -101,4 +169,4 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
|
||||
}
|
||||
for item in sources
|
||||
]
|
||||
return len(sources), len(sources), 0, 0, details, [], step_logs
|
||||
return len(sources), 0, 0, 0, details, [], step_logs
|
||||
@@ -1,3 +1,10 @@
|
||||
"""
|
||||
backend/app/services/schedule/sql_config.py
|
||||
|
||||
用途:排程 SQL/数据源配置 dataclass 与 ScheduleTaskConfig ORM 读写。
|
||||
依赖:models.ScheduleTask、ScheduleTaskConfig。
|
||||
逻辑:由 api/schedule/*、import_service、scheduler_service 调用 upsert/get。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
@@ -212,6 +219,63 @@ def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
|
||||
return results
|
||||
|
||||
|
||||
def _sync_postgres_serial_sequence(table_name: str) -> None:
|
||||
"""
|
||||
将 PostgreSQL serial 序列校准为 MAX(id),避免手工导入或迁移后主键冲突。
|
||||
核心逻辑:仅对白名单表执行 setval;非 PostgreSQL 方言下无操作。
|
||||
|
||||
Args:
|
||||
table_name: 仅允许 schedule_task_configs。
|
||||
"""
|
||||
from app import db
|
||||
|
||||
if table_name != 'schedule_task_configs':
|
||||
raise ValueError(f'unsupported table for sequence sync: {table_name}')
|
||||
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
db.session.execute(
|
||||
db.text(
|
||||
"SELECT setval("
|
||||
"pg_get_serial_sequence('public.schedule_task_configs', 'id'), "
|
||||
"COALESCE((SELECT MAX(id) FROM public.schedule_task_configs), 1), "
|
||||
"true)"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _get_or_create_schedule_task_config_model(task_id: int):
|
||||
"""
|
||||
获取或创建 ScheduleTaskConfig ORM,优先走 task.config 关系避免重复 pending INSERT。
|
||||
核心逻辑:no_autoflush 下二次查库;新建前同步 PostgreSQL 序列。
|
||||
Args:
|
||||
task_id: schedule_tasks 主键。
|
||||
Returns:
|
||||
(ScheduleTask, ScheduleTaskConfig) 元组。
|
||||
Raises:
|
||||
ValueError: 排程任务不存在。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if task is None:
|
||||
raise ValueError(f'Schedule task {task_id} not found')
|
||||
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model is None:
|
||||
_sync_postgres_serial_sequence('schedule_task_configs')
|
||||
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
|
||||
task.config = cfg_model
|
||||
db.session.add(cfg_model)
|
||||
return task, cfg_model
|
||||
|
||||
|
||||
def upsert_schedule_task_config(
|
||||
task_id: int,
|
||||
data: dict[str, Any],
|
||||
@@ -219,12 +283,8 @@ def upsert_schedule_task_config(
|
||||
commit: bool = True,
|
||||
) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
|
||||
db.session.add(cfg_model)
|
||||
_task, cfg_model = _get_or_create_schedule_task_config_model(task_id)
|
||||
|
||||
for k, v in data.items():
|
||||
if k == "data_source" and isinstance(v, dict):
|
||||
|
||||
@@ -41,7 +41,7 @@ def create_shipping_batch_from_notice_items(
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError(
|
||||
"all uploaded files failed extraction or contained no parseable text",
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary or {}},
|
||||
)
|
||||
|
||||
|
||||
@@ -660,7 +660,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
|
||||
【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。
|
||||
|
||||
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务。
|
||||
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务;
|
||||
含 schedule_run_id 时委托 finalize 终态化排程 run。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
|
||||
@@ -748,13 +749,32 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
})
|
||||
|
||||
db.session.commit()
|
||||
|
||||
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
|
||||
if schedule_run_id is not None:
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import finalize_shipping_inventory_schedule_run
|
||||
|
||||
finalize_result = finalize_shipping_inventory_schedule_run(
|
||||
schedule_run_id,
|
||||
created=created,
|
||||
failed=failed,
|
||||
payload=payload,
|
||||
)
|
||||
|
||||
response_data = {
|
||||
"run_no": run_no,
|
||||
"created": created,
|
||||
"failed": failed,
|
||||
"rpa_mode": payload.get("rpa_mode"),
|
||||
"schedule_finalize_status": finalize_result.get("schedule_finalize_status"),
|
||||
}
|
||||
if finalize_result.get("error"):
|
||||
response_data["schedule_finalize_error"] = finalize_result.get("error")
|
||||
if finalize_result.get("manual_retryable"):
|
||||
response_data["schedule_finalize_manual_retryable"] = True
|
||||
|
||||
return tool_response(
|
||||
status="ok" if created else "failed",
|
||||
message=f"批量库存回调完成:成功 {len(created)},失败 {len(failed)}",
|
||||
data={
|
||||
"run_no": run_no,
|
||||
"created": created,
|
||||
"failed": failed,
|
||||
"rpa_mode": payload.get("rpa_mode"),
|
||||
},
|
||||
data=response_data,
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_sources.py
|
||||
|
||||
用途:从 JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
|
||||
依赖:Flask current_app、pathlib/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
|
||||
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.json,不改 Python。
|
||||
用途:从 YAML/JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
|
||||
依赖:Flask current_app、pathlib、PyYAML/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
|
||||
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.yaml,不改 Python。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +13,7 @@ from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from flask import current_app
|
||||
|
||||
_SITE_TO_SOURCE_TYPE = {
|
||||
@@ -24,7 +25,7 @@ _CONFIG_CACHE: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class InventorySourceConfigError(ValueError):
|
||||
"""库存源 JSON 配置校验失败。"""
|
||||
"""库存源配置校验失败。"""
|
||||
|
||||
|
||||
def _config_path() -> Path:
|
||||
@@ -39,10 +40,34 @@ def _config_path() -> Path:
|
||||
return path
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.json"
|
||||
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.yaml"
|
||||
return Path(resolve_backend_relative_path(None, default))
|
||||
|
||||
|
||||
def _parse_config_payload(path: Path) -> dict[str, Any]:
|
||||
"""
|
||||
按文件后缀解析库存源配置(默认 YAML;测试夹具仍可用 .json)。
|
||||
Raises:
|
||||
InventorySourceConfigError: 后缀不支持或解析失败
|
||||
"""
|
||||
text = path.read_text(encoding="utf-8")
|
||||
suffix = path.suffix.lower()
|
||||
try:
|
||||
if suffix in {".yaml", ".yml"}:
|
||||
payload = yaml.safe_load(text)
|
||||
elif suffix == ".json":
|
||||
payload = json.loads(text)
|
||||
else:
|
||||
raise InventorySourceConfigError(
|
||||
f"unsupported inventory sources config format: {path.suffix} (use .yaml, .yml, or .json)"
|
||||
)
|
||||
except (yaml.YAMLError, json.JSONDecodeError) as exc:
|
||||
raise InventorySourceConfigError(f"failed to parse inventory sources config: {path}: {exc}") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise InventorySourceConfigError("inventory sources config root must be a mapping")
|
||||
return payload
|
||||
|
||||
|
||||
def _join_parameter_values(parameter: dict[str, Any]) -> str | None:
|
||||
"""将 multi_text 参数值按 joiner 拼接为单字符串。"""
|
||||
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
|
||||
@@ -160,7 +185,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
|
||||
|
||||
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
|
||||
"""加载并缓存 JSON 配置;force_reload 用于测试。"""
|
||||
"""加载并缓存 YAML/JSON 配置;force_reload 用于测试。"""
|
||||
global _CONFIG_CACHE
|
||||
if _CONFIG_CACHE is not None and not force_reload:
|
||||
return _CONFIG_CACHE
|
||||
@@ -169,7 +194,7 @@ def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
|
||||
if not path.is_file():
|
||||
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
|
||||
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
payload = _parse_config_payload(path)
|
||||
sources_raw = payload.get("sources")
|
||||
if not isinstance(sources_raw, list):
|
||||
raise InventorySourceConfigError("sources must be a list")
|
||||
|
||||
Reference in new issue
Block a user