""" backend/app/services/schedule/import_service.py 用途:排程任务 JSON 批量导入(upsert by schedule_no)。 依赖:models、scheduler_service、schedule_contract、sql_config。 逻辑:由 api/schedule/tasks.py import 路由调用;导入时自动迁移旧语义。 """ from __future__ import annotations from typing import Any from app import db from app.core.errors import ValidationError from app.models import ScheduleTask from app.services.schedule.schedule_contract import ( apply_schedule_contract_to_payload, assert_schedule_config_writable, migrate_legacy_schedule_payload, ) from app.services.schedule.scheduler_service import create_task, update_task from app.services.schedule.sql_config import upsert_schedule_task_config def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None) -> dict[str, Any]: """ 批量导入排程 JSON。 Args: schedules: 导出文件中的 schedules 数组。 actor_id: 当前管理员 user id。 Returns: ok、imported、skipped、errors(最多 20 条)。 Raises: ValidationError: schedules 非 list。 """ if not isinstance(schedules, list): raise ValidationError('Invalid import file: schedules missing') imported = 0 skipped = 0 errors: list[str] = [] for item in schedules: if not isinstance(item, dict): skipped += 1 continue try: migrated = migrate_legacy_schedule_payload(item) name = str(migrated.get('name') or '').strip() cron_expr = str(migrated.get('cron_expr') or '').strip() owner_user_id = int(migrated.get('owner_user_id')) if not name or not cron_expr: raise ValueError('name or cron_expr missing') contract = apply_schedule_contract_to_payload({ 'schedule_type': migrated.get('schedule_type'), 'data_source_type': migrated.get('data_source_type'), 'platform_api_path': migrated.get('platform_api_path'), }) cfg = migrated.get('config') if isinstance(migrated.get('config'), dict) else None assert_schedule_config_writable( schedule_type=contract['schedule_type'], 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: existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first() task_payload = { 'name': name, 'schedule_type': contract['schedule_type'], 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': migrated.get('schedule_timezone'), 'wait_seconds': int(migrated.get('wait_seconds') or 0), '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 [], 'notify_enabled': bool(migrated.get('notify_enabled', True)), 'enabled': bool(migrated.get('enabled', True)), 'kb_sync_enabled': bool(migrated.get('kb_sync_enabled', False)), 'kb_group_id': migrated.get('kb_group_id'), } if existing: 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: task = create_task( name=name, schedule_type=contract['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], 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'], kb_sync_enabled=task_payload['kb_sync_enabled'], kb_group_id=( int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None ), actor_id=actor_id, check_options=False, commit=False, ) if cfg: upsert_schedule_task_config(task.id, cfg, commit=False) db.session.commit() imported += 1 except Exception as exc: db.session.rollback() errors.append(str(exc)) skipped += 1 return {'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]}