Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
sophie committed 2026-05-21 15:15:25 +08:00
commit c0cb55dce6
9 files changed
+268 -17

No files matched your search

+3
View File
@@ -35,3 +35,6 @@ CASDOOR_WECOM_PROVIDER_HINT=wecom
# Gunicorn配置
GUNICORN_WORKERS=6
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
+4 -2
View File
@@ -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()
+111
View File
@@ -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/<int:task_id>/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():
+8 -2
View File
@@ -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': [{
@@ -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),
+15
View File
@@ -68,6 +68,21 @@ async function getJson<T>(url: string): Promise<T> {
export const listAdminSchedules = () =>
getJson<ScheduleTask[]>('/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<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
+118 -9
View File
@@ -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<HTMLInputElement | null>(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) => {
<template v-if="scheduleViewMode === 'overview'">
<div class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
<div class="mb-5 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
<div class="mb-5 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
<div class="rounded-2xl bg-slate-50 px-4 py-3">
<div class="text-xl font-bold text-slate-900">{{ schedules.length }}</div>
<div class="text-sm text-slate-500">排程总数</div>
@@ -4272,6 +4352,13 @@ const handlePermissionImport = async (event: Event) => {
<Settings2 class="h-4 w-4" />
</div>
<div class="font-semibold text-slate-900">新增排程</div>
<button
class="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-violet-200 text-violet-700 transition hover:bg-violet-50"
title="汇入"
@click="scheduleImportInputRef?.click()"
>
<ArrowUpFromLine class="h-4 w-4" />
</button>
</div>
<div class="text-sm text-slate-500">
点击按钮后弹窗录入排程字段。
@@ -4284,6 +4371,13 @@ const handlePermissionImport = async (event: Event) => {
<Plus class="h-4 w-4" />
新增排程
</button>
<input
ref="scheduleImportInputRef"
type="file"
accept=".json,application/json"
class="hidden"
@change="importSchedulesFromFile"
/>
</div>
</div>
@@ -4295,7 +4389,16 @@ const handlePermissionImport = async (event: Event) => {
<button class="w-full text-left" @click="openScheduleRunSubmenu(s.id)">
<div class="min-h-[96px]">
<div class="flex items-center justify-between gap-3">
<div class="truncate text-base font-semibold text-slate-900">{{ s.name }}</div>
<div class="flex min-w-0 items-center gap-2">
<div class="truncate text-base font-semibold text-slate-900">{{ s.name }}</div>
<button
class="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-emerald-200 text-emerald-700 transition hover:bg-emerald-50"
title="汇出"
@click.stop="exportSchedule(s.id)"
>
<Download class="h-4 w-4" />
</button>
</div>
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold"
:class="s.enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-200 text-slate-600'">
{{ s.enabled ? '启用' : '停用' }}
@@ -4303,12 +4406,6 @@ const handlePermissionImport = async (event: Event) => {
</div>
<div class="mt-2 text-sm text-slate-500">编号:{{ s.schedule_no }}</div>
<div class="mt-1 text-sm text-slate-500">Cron:{{ s.cron_expr }}</div>
<div
v-if="s.schedule_type === 'platform_app' && s.platform_api_path"
class="mt-1 text-sm text-slate-500"
>
配置:{{ s.platform_api_path }}
</div>
<div class="mt-1 text-sm text-slate-500">所有者:{{ s.owner_username || s.owner_user_id }}</div>
</div>
</button>
@@ -6046,8 +6143,17 @@ const handlePermissionImport = async (event: Event) => {
v-if="scheduleNotifyDropdownOpen"
class="absolute z-50 mt-1 max-h-52 w-full overflow-auto rounded-xl border border-slate-200 bg-white shadow-lg"
>
<div class="sticky top-0 z-10 border-b border-slate-100 bg-white p-2">
<input
v-model.trim="scheduleNotifyFilterText"
type="text"
class="input-field !h-8 !rounded-lg !px-2.5 !py-1 !text-xs"
placeholder="输入姓名 / 工号 / 用户名筛选"
@click.stop
/>
</div>
<div
v-for="u in users"
v-for="u in filteredScheduleNotifyUsers"
:key="u.id"
class="flex cursor-pointer items-center gap-2 px-3 py-2 text-sm transition hover:bg-slate-50"
:class="scheduleCreateForm.notify_user_ids_json.includes(u.id) ? 'bg-blue-50/50' : ''"
@@ -6063,6 +6169,9 @@ const handlePermissionImport = async (event: Event) => {
/>
<span class="text-slate-700">{{ u.real_name || u.username }}{{ u.employee_id ? '(' + u.employee_id + ')' : '' }}</span>
</div>
<div v-if="filteredScheduleNotifyUsers.length === 0" class="px-3 py-3 text-xs text-slate-400">
未找到匹配人员
</div>
</div>
</div>
</div>
+4 -2
View File
@@ -589,7 +589,7 @@ const copiedIndex = ref<number | null>(null);
const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string }>>([]);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
const showGeneralFeedbackDialog = ref(false);
const showAgentPanel = ref(true);
@@ -1689,7 +1689,9 @@ const loadUserAgents = async () => {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (res.ok) {
const agents = await res.json();
userAgents.value = Array.isArray(agents) ? agents.filter((a: any) => a.id !== agentId) : [];
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
+4 -2
View File
@@ -89,6 +89,7 @@ interface Agent {
name: string;
description: string;
icon_url?: string;
dify_app_type?: 'chatflow' | 'workflow';
}
interface QuickQuestion {
@@ -244,9 +245,10 @@ const favoriteAgents = computed(() => {
});
const otherAgents = computed(() => {
if (!searchQuery.value.trim()) return agents.value;
const chatflowAgents = agents.value.filter((a) => (a.dify_app_type || 'chatflow') === 'chatflow');
if (!searchQuery.value.trim()) return chatflowAgents;
const q = searchQuery.value.toLowerCase();
return agents.value.filter(
return chatflowAgents.filter(
(a) => a.name.toLowerCase().includes(q) || a.description.toLowerCase().includes(q)
);
});