From a6f35b375c5766faba5e30ec0d5eb9fdf6e10822 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Thu, 21 May 2026 09:54:39 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E5=BF=BD=E7=95=A5index=E7=9B=AE=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/dist/index.html | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 frontend/dist/index.html diff --git a/frontend/dist/index.html b/frontend/dist/index.html deleted file mode 100644 index 37024f90..00000000 --- a/frontend/dist/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - AI工作台 - - - - -
- - From b1613824ce7c0094510b69e6e20cb587e9ce5a58 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Thu, 21 May 2026 11:38:54 +0800 Subject: [PATCH 2/7] git hook --- .githooks/_common.sh | 45 ++++++++++++++++++++++++++++ .githooks/pre-commit | 16 ++++++++++ .githooks/pre-push | 54 ++++++++++++++++++++++++++++++++++ Jenkinsfile | 16 ++++++++++ docs/新人环境搭建与配置文档.md | 33 +++++++++++++++++++-- hxops_menu.sh | 6 ++-- scripts/ci_frontend_build.sh | 19 ++++++++++++ scripts/install_git_hooks.sh | 23 ++++++++++----- 8 files changed, 200 insertions(+), 12 deletions(-) create mode 100644 .githooks/_common.sh create mode 100644 .githooks/pre-push create mode 100644 scripts/ci_frontend_build.sh diff --git a/.githooks/_common.sh b/.githooks/_common.sh new file mode 100644 index 00000000..731a4a16 --- /dev/null +++ b/.githooks/_common.sh @@ -0,0 +1,45 @@ +# shellcheck shell=bash +# 供 pre-commit / pre-push 引用;勿直接执行。 + +hook_should_skip() { + [[ "${SKIP_GIT_HOOKS:-}" == "1" ]] || [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]] +} + +frontend_paths_in() { + local file_list="${1:-}" + echo "${file_list}" | grep -qE '^frontend/' +} + +ensure_frontend_deps() { + local frontend_dir="${1}/frontend" + if [[ ! -d "${frontend_dir}/node_modules" ]]; then + echo "[git-hook] frontend/node_modules 不存在,请先执行:" + echo " cd frontend && npm install" + return 1 + fi + return 0 +} + +run_frontend_typecheck() { + local root_dir="${1}" + echo "[pre-commit] 检测到 frontend/ 变更,运行 vue-tsc 类型检查..." + if ! ensure_frontend_deps "${root_dir}"; then + return 1 + fi + ( + cd "${root_dir}/frontend" + npx vue-tsc -b --pretty false + ) +} + +run_frontend_build() { + local root_dir="${1}" + echo "[pre-push] 检测到将要推送的提交包含 frontend/ 变更,运行 npm run build..." + if ! ensure_frontend_deps "${root_dir}"; then + return 1 + fi + ( + cd "${root_dir}/frontend" + npm run build + ) +} diff --git a/.githooks/pre-commit b/.githooks/pre-commit index f5040541..c5f14568 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -3,6 +3,8 @@ set -euo pipefail ROOT_DIR="$(git rev-parse --show-toplevel)" cd "${ROOT_DIR}" +# shellcheck source=_common.sh +source "${ROOT_DIR}/.githooks/_common.sh" STAGED_FILES="$(git diff --cached --name-only --diff-filter=ACMR || true)" if [[ -z "${STAGED_FILES}" ]]; then @@ -30,4 +32,18 @@ if [[ "${MODELS_CHANGED}" -eq 1 && "${MIGRATION_CHANGED}" -eq 0 ]]; then exit 1 fi +if hook_should_skip; then + exit 0 +fi + +if frontend_paths_in "${STAGED_FILES}"; then + if ! run_frontend_typecheck "${ROOT_DIR}"; then + echo "[pre-commit] vue-tsc 失败,已阻止提交。" + echo "[pre-commit] 跳过前端检查: SKIP_FRONTEND_HOOKS=1 git commit" + echo "[pre-commit] 或跳过全部 hook: git commit --no-verify" + exit 1 + fi + echo "[pre-commit] frontend 类型检查通过。" +fi + exit 0 diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100644 index 00000000..e7fd208d --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(git rev-parse --show-toplevel)" +# shellcheck source=_common.sh +source "${ROOT_DIR}/.githooks/_common.sh" + +if hook_should_skip; then + exit 0 +fi + +zero="0000000000000000000000000000000000000000" +need_frontend_build=0 + +while read -r local_ref local_sha remote_ref remote_sha; do + [[ "${local_sha}" == "${zero}" ]] && continue + + changed_files="" + if [[ "${remote_sha}" == "${zero}" ]]; then + upstream_ref="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)" + if [[ -n "${upstream_ref}" ]]; then + remote_branch="${upstream_ref#*/}" + remote_name="${upstream_ref%%/*}" + merge_base="$(git merge-base "${local_sha}" "${remote_name}/${remote_branch}" 2>/dev/null || true)" + if [[ -n "${merge_base}" ]]; then + changed_files="$(git diff --name-only --diff-filter=ACMR "${merge_base}" "${local_sha}" || true)" + fi + fi + if [[ -z "${changed_files}" ]]; then + changed_files="$(git diff-tree --no-commit-id --name-only --diff-filter=ACMR -r "${local_sha}" || true)" + fi + else + changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)" + fi + + if frontend_paths_in "${changed_files}"; then + need_frontend_build=1 + break + fi +done + +if [[ "${need_frontend_build}" -eq 0 ]]; then + exit 0 +fi + +if ! run_frontend_build "${ROOT_DIR}"; then + echo "[pre-push] 前端 build 失败,已阻止 push。" + echo "[pre-push] 跳过检查可设置: SKIP_FRONTEND_HOOKS=1 git push" + echo "[pre-push] 或跳过全部 hook: git push --no-verify" + exit 1 +fi + +echo "[pre-push] 前端 build 通过。" +exit 0 diff --git a/Jenkinsfile b/Jenkinsfile index 88ff599b..ef465e07 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -329,6 +329,22 @@ pipeline { } } + stage('Frontend Build (CI)') { + when { + expression { env.FRONTEND_CHANGED == 'true' } + } + steps { + echo '[Frontend Build] FRONTEND_CHANGED=true,容器内执行 npm ci && npm run build(与部署构建一致)' + sh ''' + set -e + docker run --rm \ + -v "${WORKSPACE}:/repo" \ + -w /repo \ + node:22-alpine sh -c "chmod +x scripts/ci_frontend_build.sh && ./scripts/ci_frontend_build.sh" + ''' + } + } + stage('Deploy Dev') { when { expression { diff --git a/docs/新人环境搭建与配置文档.md b/docs/新人环境搭建与配置文档.md index 18f565eb..504666ba 100644 --- a/docs/新人环境搭建与配置文档.md +++ b/docs/新人环境搭建与配置文档.md @@ -48,6 +48,7 @@ 4. 提交信息建议规范化:`feat:`、`fix:`、`refactor:`、`docs:`、`chore:` 5. 合并前必须完成最少检查: - 能启动前后端 + - 改动了 `frontend/` 时本地 `cd frontend && npm run build` 通过(或已安装 Git Hooks,由 pre-push 自动检查) - 关键页面可访问 - 登录流程可用 6. 任何涉及数据库结构变更的提交,必须包含迁移脚本或升级说明 @@ -62,7 +63,35 @@ git clone https://gitee.com/justop/hxops.git cd hxops ``` -### 4.2 常用 Git 操作示例 +### 4.2 安装 Git Hooks(推荐,每人 clone 后执行一次) + +仓库根目录的 `.githooks/` 会随代码拉取;**不会自动生效**,需在本机启用: + +| Hook | 时机 | 检查内容 | +|------|------|----------| +| `pre-commit` | `git commit` | 改 `models.py` 须同时提交 migration;暂存 `frontend/` 时跑 `vue-tsc` | +| `pre-push` | `git push` | 本次推送含 `frontend/` 变更时跑 `npm run build`(与 Jenkins 部署一致) | + +**Git Bash / WSL:** + +```bash +chmod +x scripts/install_git_hooks.sh .githooks/pre-commit .githooks/pre-push +./scripts/install_git_hooks.sh +``` + +**PowerShell(仅启用钩子目录):** + +```powershell +git config core.hooksPath .githooks +``` + +验证:`git config --get core.hooksPath` 应输出 `.githooks`。 + +前置:已执行 `cd frontend && npm install`。应急跳过前端检查:`$env:SKIP_FRONTEND_HOOKS="1"`(bash 为 `SKIP_FRONTEND_HOOKS=1`)。 + +Jenkins 在检测到 `frontend/` 变更时会再跑一遍同款构建(`scripts/ci_frontend_build.sh`),作为 Hook 被跳过时的兜底。 + +### 4.3 常用 Git 操作示例 ```bash # 拉取远程分支 @@ -81,7 +110,7 @@ git commit -m "feat: your change summary" git push origin feature/your-feature-name ``` -### 4.3 关键目录 +### 4.4 关键目录 - `frontend/`:Vue 3 + TypeScript + Vite - `backend/`:Flask + SQLAlchemy + Flask-Migrate diff --git a/hxops_menu.sh b/hxops_menu.sh index 280104d5..9390a745 100644 --- a/hxops_menu.sh +++ b/hxops_menu.sh @@ -666,7 +666,7 @@ run_ci_migration_check() { } install_precommit_hook() { - echo "=== 安装 Git pre-commit Hook ===" + echo "=== 安装 Git Hooks(pre-commit + pre-push)===" local install_script="${ROOT_DIR}/scripts/install_git_hooks.sh" if [[ ! -x "${install_script}" ]]; then echo "未找到可执行脚本: ${install_script}" @@ -695,7 +695,7 @@ show_help() { branches或 34 -> 查看本地所有分支及默认分支、远端所有分支及默认分支 dbdrift或 41 -> 检查当前数据库结构与 SQLAlchemy 模型是否一致 migci 或 42 -> 运行 CI 同款迁移一致性检查(空库升级+漂移检测) - hook 或 43 -> 安装 pre-commit Hook(改 models 必须带 migration) + hook 或 43 -> 安装 Git Hooks(models+migration / frontend vue-tsc / push 前 build) help 或 9 -> 再次显示本帮助 help -> 再次显示本帮助 exit 或 0 -> 退出脚本 @@ -759,7 +759,7 @@ main_loop() { confirm_and_run "CI同款迁移一致性检查" run_ci_migration_check ;; 43|hook) - confirm_and_run "安装 pre-commit Hook" install_precommit_hook + confirm_and_run "安装 Git Hooks" install_precommit_hook ;; 9|help) show_help diff --git a/scripts/ci_frontend_build.sh b/scripts/ci_frontend_build.sh new file mode 100644 index 00000000..f3cd2c8f --- /dev/null +++ b/scripts/ci_frontend_build.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Jenkins / 本地 CI 同款前端生产构建(与 deploy.sh、frontend/Dockerfile 一致) +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +FRONTEND_DIR="${ROOT_DIR}/frontend" + +if [[ ! -f "${FRONTEND_DIR}/package.json" ]]; then + echo "[ci-frontend-build] missing ${FRONTEND_DIR}/package.json" + exit 1 +fi + +cd "${FRONTEND_DIR}" +echo "[ci-frontend-build] npm ci" +npm ci +echo "[ci-frontend-build] npm run build" +npm run build +echo "[ci-frontend-build] OK" diff --git a/scripts/install_git_hooks.sh b/scripts/install_git_hooks.sh index fa1efc91..198f391f 100755 --- a/scripts/install_git_hooks.sh +++ b/scripts/install_git_hooks.sh @@ -9,13 +9,18 @@ if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then exit 1 fi -HOOK_PATH="${ROOT_DIR}/.githooks/pre-commit" -if [[ ! -f "${HOOK_PATH}" ]]; then - echo "[hook-install] missing hook file: ${HOOK_PATH}" - exit 1 -fi +HOOKS_DIR="${ROOT_DIR}/.githooks" +REQUIRED_HOOKS=(pre-commit pre-push _common.sh) + +for hook_name in "${REQUIRED_HOOKS[@]}"; do + hook_path="${HOOKS_DIR}/${hook_name}" + if [[ ! -f "${hook_path}" ]]; then + echo "[hook-install] missing hook file: ${hook_path}" + exit 1 + fi + chmod +x "${hook_path}" +done -chmod +x "${HOOK_PATH}" if ! git -C "${ROOT_DIR}" config core.hooksPath .githooks; then echo "[hook-install] failed to set git config core.hooksPath." echo "[hook-install] please run manually in your local shell:" @@ -23,5 +28,9 @@ if ! git -C "${ROOT_DIR}" config core.hooksPath .githooks; then exit 1 fi -echo "[hook-install] Installed pre-commit hook successfully." +echo "[hook-install] Installed Git hooks successfully." +echo "[hook-install] pre-commit: models 变更需带 migration;frontend 暂存时跑 vue-tsc" +echo "[hook-install] pre-push: 推送含 frontend 变更时跑 npm run build" echo "[hook-install] core.hooksPath=$(git -C "${ROOT_DIR}" config --get core.hooksPath)" +echo "[hook-install] 跳过前端检查: SKIP_FRONTEND_HOOKS=1" +echo "[hook-install] 跳过全部 hook: SKIP_GIT_HOOKS=1 或 git commit/push --no-verify" From dc8ad4de523545b4aa72a64b7b67431afe36f0ed Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 21 May 2026 13:58:34 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E5=8F=AF=E7=94=A8=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E5=8F=AA=E6=98=BE=E7=A4=BADify=E5=BA=94=E7=94=A8=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E4=B8=BAChatflow=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/views/ChatView.vue | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index cfaee995..494c8cda 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -589,7 +589,7 @@ const copiedIndex = ref(null); const { messages, isThinking, conversationId, sendMessage } = useChat(); const input = ref(''); const currentAgent = ref(null); -const userAgents = ref>([]); +const userAgents = ref>([]); 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; } From 05913f742fdf8935efaf36278fd355559eb5f1f1 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 21 May 2026 14:01:12 +0800 Subject: [PATCH 4/7] =?UTF-8?q?1.=E6=8E=92=E7=A8=8B=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E4=BC=81=E4=B8=9A=E5=BE=AE=E4=BF=A1=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=8A=9F=E8=83=BD=202.=E5=8F=AF=E7=94=A8=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E4=BB=A5=E5=8F=8A=E6=99=BA=E8=83=BD=E4=BD=93=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E5=8F=AA=E6=98=BE=E7=A4=BAChatflow=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=BA=94=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.test | 3 + backend/app/api/agents.py | 6 +- backend/app/api/schedule_admin.py | 111 +++++++++++++++ backend/app/api/user.py | 10 +- .../app/services/schedule/query_service.py | 1 + frontend/src/api/schedule.ts | 15 +++ frontend/src/views/AdminView.vue | 127 ++++++++++++++++-- frontend/src/views/WorkspaceView.vue | 6 +- 8 files changed, 264 insertions(+), 15 deletions(-) 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 eb2e18d0..381dbaa3 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -21,6 +21,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, @@ -37,6 +38,7 @@ import { MessageSquare, Globe, Download, + ArrowUpFromLine, UserCog, Building, MessageCircleQuestion, @@ -705,6 +707,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 || '', @@ -717,6 +721,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); @@ -903,6 +932,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; @@ -927,6 +957,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: '', @@ -977,6 +1039,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); @@ -4231,7 +4311,7 @@ const handlePermissionImport = async (event: Event) => {