diff --git a/.env.test b/.env.test index 490c2181..b7f38199 100644 --- a/.env.test +++ b/.env.test @@ -35,3 +35,6 @@ CASDOOR_WECOM_PROVIDER_HINT=wecom # Gunicorn配置 GUNICORN_WORKERS=6 + +# 企业微信通知配置(如果不使用企业微信通知,留空即可) +WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/ \ No newline at end of file diff --git a/backend/app/api/agents.py b/backend/app/api/agents.py index 3805244e..650e1a96 100644 --- a/backend/app/api/agents.py +++ b/backend/app/api/agents.py @@ -20,6 +20,7 @@ def _serialize_agent_row(row) -> dict: 'name': row.name, 'description': row.description, 'icon_url': row.icon_url, + 'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None, } @@ -35,7 +36,7 @@ def list_user_agents(): # 管理员:返回所有激活的 Agent if user.role == 'admin': agent_rows = ( - db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url) + db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config) .filter(Agent.is_active.is_(True)) .order_by(Agent.id.asc()) .all() @@ -48,6 +49,7 @@ def list_user_agents(): 'name': a.name, 'description': a.description, 'icon_url': a.icon_url, + 'extra_config': a.extra_config, })() for a in user.agents if a.is_active @@ -64,7 +66,7 @@ def list_public_agents(): """ # 返回所有激活的 Agent,包含基本信息 agent_rows = ( - db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url) + db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config) .filter(Agent.is_active.is_(True)) .order_by(Agent.id.asc()) .all() diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py index 4394e4f9..618f221a 100644 --- a/backend/app/api/schedule_admin.py +++ b/backend/app/api/schedule_admin.py @@ -4,6 +4,9 @@ import threading from datetime import datetime from flask import Blueprint, current_app, jsonify, request, send_file +from flask import Response +from io import BytesIO +import json from app.decorators import require_admin from app import db @@ -24,6 +27,12 @@ from app.services.schedule.srm_service import _fetch_records schedule_admin_bp = Blueprint('schedule_admin', __name__) +def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict: + payload = serialize_task(task) + payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None + return payload + + def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict: return { "row_id_key": cfg_model.row_id_key or "id", @@ -372,6 +381,108 @@ def get_schedules(): return jsonify(list_tasks()) +@schedule_admin_bp.route('/schedules//export', methods=['GET']) +@require_admin +def export_schedule(task_id: int): + task = db.session.get(ScheduleTask, task_id) + if not task: + return jsonify({'error': 'Not found'}), 404 + cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() + payload = { + "schema_version": 1, + "exported_at": datetime.utcnow().isoformat(), + "schedules": [_serialize_task_for_export(task, cfg_model)], + } + body = json.dumps(payload, ensure_ascii=False, indent=2) + filename = f"{(task.schedule_no or f'schedule_{task.id}')}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json" + return Response( + body, + mimetype='application/json; charset=utf-8', + headers={'Content-Disposition': f'attachment; filename="{filename}"'}, + ) + + +@schedule_admin_bp.route('/schedules/import', methods=['POST']) +@require_admin +def import_schedules(): + data = request.get_json(silent=True) or {} + schedules = data.get('schedules') + if not isinstance(schedules, list): + return jsonify({'error': 'Invalid import file: schedules missing'}), 400 + + user = get_current_user() + imported = 0 + skipped = 0 + errors: list[str] = [] + + for item in schedules: + if not isinstance(item, dict): + skipped += 1 + continue + try: + name = str(item.get('name') or '').strip() + cron_expr = str(item.get('cron_expr') or '').strip() + owner_user_id = int(item.get('owner_user_id')) + if not name or not cron_expr: + raise ValueError('name or cron_expr missing') + + existing = None + schedule_no = str(item.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': str(item.get('schedule_type') or 'platform_app'), + 'owner_user_id': owner_user_id, + 'cron_expr': cron_expr, + 'wait_seconds': int(item.get('wait_seconds') or 0), + 'dify_agent_id': item.get('dify_agent_id'), + 'platform_api_path': item.get('platform_api_path'), + 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], + 'notify_enabled': bool(item.get('notify_enabled', True)), + 'enabled': bool(item.get('enabled', True)), + 'data_source_type': str(item.get('data_source_type') or 'database'), + } + cfg = item.get('config') if isinstance(item.get('config'), dict) else None + + if existing: + update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None)) + existing.data_source_type = task_payload['data_source_type'] + if cfg: + upsert_schedule_task_config(existing.id, cfg) + else: + task = create_task( + name=name, + schedule_type=task_payload['schedule_type'], + owner_user_id=owner_user_id, + cron_expr=cron_expr, + wait_seconds=task_payload['wait_seconds'], + dify_agent_id=task_payload['dify_agent_id'], + platform_api_path=task_payload['platform_api_path'], + notify_user_ids_json=task_payload['notify_user_ids_json'], + notify_enabled=task_payload['notify_enabled'], + enabled=task_payload['enabled'], + actor_id=getattr(user, 'id', None), + ) + task.data_source_type = task_payload['data_source_type'] + db.session.commit() + if cfg: + upsert_schedule_task_config(task.id, cfg) + imported += 1 + except Exception as exc: + errors.append(str(exc)) + skipped += 1 + + db.session.commit() + return jsonify({ + 'ok': True, + 'imported': imported, + 'skipped': skipped, + 'errors': errors[:20], + }) + + @schedule_admin_bp.route('/schedules', methods=['POST']) @require_admin def post_schedule(): diff --git a/backend/app/api/user.py b/backend/app/api/user.py index 99d2f0a6..46b171cd 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -1887,7 +1887,7 @@ def home(): # Get all agents available to user (including public ones) if user.role == 'admin': agent_rows = ( - db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url) + db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config) .filter(Agent.is_active.is_(True)) .all() ) @@ -1898,6 +1898,7 @@ def home(): 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, + 'extra_config': agent.extra_config, } for agent in user.agents] favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all() @@ -1934,7 +1935,12 @@ def home(): 'id': a.id if hasattr(a, 'id') else a['id'], 'name': a.name if hasattr(a, 'name') else a['name'], 'description': a.description if hasattr(a, 'description') else a['description'], - 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'] + 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'], + 'dify_app_type': ( + (a.extra_config or {}).get('dify_app_type') + if hasattr(a, 'extra_config') + else (a.get('extra_config') or {}).get('dify_app_type') + ) or 'chatflow' } for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{ diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index cbc3324e..58806f75 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -22,6 +22,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic 'wait_seconds': task.wait_seconds, 'dify_agent_id': task.dify_agent_id, 'platform_api_path': task.platform_api_path, + 'data_source_type': task.data_source_type, 'notify_user_ids_json': task.notify_user_ids_json or [], 'notify_enabled': bool(task.notify_enabled), 'enabled': bool(task.enabled), diff --git a/frontend/src/api/schedule.ts b/frontend/src/api/schedule.ts index a3c10c29..28295ea6 100644 --- a/frontend/src/api/schedule.ts +++ b/frontend/src/api/schedule.ts @@ -68,6 +68,21 @@ async function getJson(url: string): Promise { export const listAdminSchedules = () => getJson('/api/admin/schedules'); +export const exportAdminScheduleUrl = (taskId: number) => `/api/admin/schedules/${taskId}/export`; + +export const importAdminSchedules = async (payload: any) => { + const res = await fetch('/api/admin/schedules/import', { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || 'Import failed'); + } + return res.json(); +}; + export const getAdminScheduleTaskConfig = (taskId: number) => getJson<{ data_source_type: string; config: Record | null }>(`/api/admin/schedule-config/${taskId}`); diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index d2bd68f8..b002647e 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -22,6 +22,7 @@ import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog'; import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom'; import { getAuthHeaders } from '../utils/auth'; import { listAdminSchedules, createAdminSchedule, updateAdminSchedule, deleteAdminSchedule, toggleAdminSchedule, runAdminSchedule, listAdminScheduleRuns, getAdminScheduleTaskConfig, testAdminScheduleSql, testAdminScheduleRun, type ScheduleTask, type ScheduleRun, type TestScheduleRunResult } from '../api/schedule'; +import { exportAdminScheduleUrl, importAdminSchedules } from '../api/schedule'; import { ArrowLeft, // Save, @@ -38,6 +39,7 @@ import { MessageSquare, Globe, Download, + ArrowUpFromLine, UserCog, Building, MessageCircleQuestion, @@ -708,6 +710,8 @@ const openScheduleCreateModal = async () => { const openScheduleEditModal = async (task: ScheduleTask) => { await Promise.all([loadAgents(), loadUsers()]); scheduleConfigCollapsed.value = true; + scheduleNotifyFilterText.value = ''; + scheduleNotifyDropdownOpen.value = false; scheduleEditingId.value = task.id; scheduleCreateForm.value = { name: task.name || '', @@ -720,6 +724,31 @@ const openScheduleEditModal = async (task: ScheduleTask) => { enabled: !!task.enabled, data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api', }; + scheduleSqlEditForm.value = { + base_fetch_sql: '', + fetch_where_conditions: '', + fetch_order_by: '', + detail_sql: '', + writeback_sql: '', + row_id_key: 'id', + log_prefix: '', + alias_order_str: '', + detail_alias_order_str: '', + header_labels_str: '{}', + ds_db_type: 'sqlserver', + ds_host: '', + ds_port: '', + ds_database: '', + ds_username: '', + ds_password: '', + ds_driver: '', + ds_encrypt: '', + ds_trust_cert: '', + api_url: '', + api_method: 'POST', + api_headers_str: '{}', + api_body_template: '', + }; try { const result = await getAdminScheduleTaskConfig(task.id); @@ -906,6 +935,7 @@ const selectedScheduleLatestRunAt = computed( const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length); const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length); const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length); +const scheduleImportInputRef = ref(null); const loadSchedules = async () => { scheduleLoading.value = true; @@ -930,6 +960,38 @@ const loadSchedules = async () => { } }; +const exportSchedule = async (taskId: number) => { + const res = await fetch(exportAdminScheduleUrl(taskId), { headers: getAuthHeaders() }); + if (!res.ok) { + showMessageDialog('error', '导出失败'); + return; + } + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `schedule_${taskId}_${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.json`; + a.click(); + URL.revokeObjectURL(url); +}; + +const importSchedulesFromFile = async (event: Event) => { + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + if (!file) return; + try { + const text = await file.text(); + const payload = JSON.parse(text); + const result = await importAdminSchedules(payload); + showMessageDialog('success', `导入完成:${result.imported} 条,跳过 ${result.skipped} 条`); + await loadSchedules(); + } catch (e: any) { + showMessageDialog('error', e?.message || '导入失败'); + } finally { + input.value = ''; + } +}; + const scheduleSqlEditForm = ref({ base_fetch_sql: '', fetch_where_conditions: '', @@ -980,6 +1042,24 @@ const handleTestScheduleSql = async () => { }; const scheduleNotifyDropdownOpen = ref(false); +const scheduleNotifyFilterText = ref(''); + +const filteredScheduleNotifyUsers = computed(() => { + const keyword = scheduleNotifyFilterText.value.trim().toLowerCase(); + if (!keyword) return users.value; + return users.value.filter((u) => { + const fields = [ + u.real_name, + u.username, + u.employee_id, + u.email, + u.phone_number, + ] + .filter(Boolean) + .map(v => String(v).toLowerCase()); + return fields.some(v => v.includes(keyword)); + }); +}); const getUserName = (uid: number) => { const u = users.value.find(x => x.id === uid); @@ -4241,7 +4321,7 @@ const handlePermissionImport = async (event: Event) => {