!3 Merge branch 'sophie' into dev
Merge pull request !3 from sophie/dev
This commit is contained in:
79 files changed
+8775
-659
No files matched your search
@@ -0,0 +1,16 @@
|
||||
.git
|
||||
.gitignore
|
||||
.venv
|
||||
venv
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/*.pyo
|
||||
**/*.log
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
backend/venv
|
||||
backend/local_test.db
|
||||
deploy
|
||||
docs
|
||||
tmp_restore
|
||||
tests
|
||||
@@ -0,0 +1,4 @@
|
||||
# Development environment
|
||||
DATABASE_URL=postgresql://postgres:123456@8.152.207.171/hxops_db
|
||||
FLASK_APP=run.py
|
||||
FLASK_ENV=development
|
||||
@@ -0,0 +1,4 @@
|
||||
# Production environment
|
||||
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
FLASK_APP=run.py
|
||||
FLASK_ENV=production
|
||||
@@ -0,0 +1,4 @@
|
||||
# Test environment
|
||||
DATABASE_URL=postgresql://postgres:change_me@127.0.0.1:5432/hxops_db
|
||||
FLASK_APP=run.py
|
||||
FLASK_ENV=test
|
||||
+14
-15
@@ -1,11 +1,12 @@
|
||||
# Environments
|
||||
deploy.sh
|
||||
deploy_docker_rsync.sh
|
||||
docs/
|
||||
#docs/
|
||||
venv/
|
||||
backend/venv/
|
||||
backend/instance/
|
||||
tmpwork/
|
||||
env/
|
||||
.env
|
||||
|
||||
# .env
|
||||
.venv
|
||||
build/
|
||||
develop-eggs/
|
||||
@@ -36,6 +37,9 @@ frontend/node_modules/
|
||||
frontend/.DS_Store
|
||||
frontend/.env.local
|
||||
frontend/.env.*.local
|
||||
frontend/.npm-cache
|
||||
frontend/public/WW_verify_46MjWA55y3PBRLid.txt
|
||||
frontend/package-lock.json
|
||||
|
||||
# IDEs
|
||||
.vscode/
|
||||
@@ -52,16 +56,11 @@ Thumbs.db
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
# tmp
|
||||
.tmp/
|
||||
.tmp2/
|
||||
|
||||
docker-compose.yml
|
||||
nginx.conf
|
||||
deploy_docker_rsync.sh
|
||||
.npm-cache
|
||||
.npm-cache2
|
||||
.pip-cache
|
||||
|
||||
|
||||
gunicorn_config.py
|
||||
hxops_menu.sh
|
||||
|
||||
nginx.conf
|
||||
docker-compose.yml
|
||||
gunicorn_config.py
|
||||
hxops_menu.sh
|
||||
@@ -1,63 +0,0 @@
|
||||
* Serving Flask app 'app'
|
||||
* Debug mode: on
|
||||
[31m[1mWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.[0m
|
||||
* Running on all addresses (0.0.0.0)
|
||||
* Running on http://127.0.0.1:5002
|
||||
* Running on http://192.168.31.48:5002
|
||||
[33mPress CTRL+C to quit[0m
|
||||
* Restarting with stat
|
||||
* Debugger is active!
|
||||
* Debugger PIN: 679-745-431
|
||||
127.0.0.1 - - [28/Mar/2026 23:45:02] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:45:08] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:45:37] "[35m[1mPOST /api/admin/agents HTTP/1.1[0m" 201 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:47:50] "[31m[1mGET /api/admin/agents HTTP/1.1[0m" 403 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:47:55] "[31m[1mGET /api/admin/agents HTTP/1.1[0m" 403 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:48:02] "GET /api/admin/agents HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:00] "GET /api/agents/public HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:10] "[31m[1mPOST /api/user/login HTTP/1.1[0m" 401 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:17] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:18] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:20] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:20] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:30] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:30] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:50:02] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:50:45] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:50:51] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:34] "GET /api/agents/public HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:43] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:43] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:46] "GET /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:57] "POST /api/user/change-password HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:59] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:59] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:02] "GET /api/agents/public HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:07] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:07] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/agents HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/permission-requests HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/reports/usage HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/departments HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/users HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/reports/feedback HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:16] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:17] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:17] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:27] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:28] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
@@ -1 +0,0 @@
|
||||
4903
|
||||
@@ -1,10 +0,0 @@
|
||||
|
||||
> frontend@0.0.0 dev
|
||||
> vite
|
||||
|
||||
|
||||
VITE v8.0.0-beta.15 ready in 118 ms
|
||||
|
||||
➜ Local: http://localhost:8881/
|
||||
➜ Network: use --host to expose
|
||||
11:51:45 PM [vite] (client) page reload src/main.ts
|
||||
@@ -1 +0,0 @@
|
||||
4917
|
||||
@@ -1,12 +0,0 @@
|
||||
2026-03-28 23:44:52.265 CST [4865] LOG: starting PostgreSQL 18.1 (Homebrew) on aarch64-apple-darwin25.2.0, compiled by Apple clang version 17.0.0 (clang-1700.6.3.2), 64-bit
|
||||
2026-03-28 23:44:52.267 CST [4865] LOG: listening on IPv6 address "::1", port 5432
|
||||
2026-03-28 23:44:52.267 CST [4865] LOG: listening on IPv4 address "127.0.0.1", port 5432
|
||||
2026-03-28 23:44:52.267 CST [4865] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"
|
||||
2026-03-28 23:44:52.275 CST [4872] LOG: database system was shut down at 2026-03-28 23:37:09 CST
|
||||
2026-03-28 23:44:52.277 CST [4865] LOG: database system is ready to accept connections
|
||||
2026-03-28 23:49:52.269 CST [4870] LOG: checkpoint starting: time
|
||||
2026-03-28 23:49:53.685 CST [4870] LOG: checkpoint complete: wrote 14 buffers (0.1%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=1.414 s, sync=0.002 s, total=1.416 s; sync files=16, longest=0.001 s, average=0.001 s; distance=40 kB, estimate=40 kB; lsn=0/3994578, redo lsn=0/39944E8
|
||||
2026-03-28 23:54:52.680 CST [4870] LOG: checkpoint starting: time
|
||||
2026-03-28 23:54:53.185 CST [4870] LOG: checkpoint complete: wrote 5 buffers (0.0%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.505 s, sync=0.001 s, total=0.506 s; sync files=6, longest=0.001 s, average=0.001 s; distance=11 kB, estimate=37 kB; lsn=0/3997280, redo lsn=0/3997228
|
||||
2026-03-28 23:59:52.181 CST [4870] LOG: checkpoint starting: time
|
||||
2026-03-28 23:59:52.687 CST [4870] LOG: checkpoint complete: wrote 5 buffers (0.0%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.505 s, sync=0.001 s, total=0.507 s; sync files=6, longest=0.001 s, average=0.001 s; distance=12 kB, estimate=34 kB; lsn=0/399A400, redo lsn=0/399A3A8
|
||||
@@ -1 +0,0 @@
|
||||
4865
|
||||
Vendored
+194
@@ -0,0 +1,194 @@
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
options {
|
||||
// 打印时间戳,便于在 Jenkins 日志里定位耗时步骤 / Add timestamps to locate slow steps in Jenkins logs
|
||||
timestamps()
|
||||
// 禁止同一任务并发执行,避免部署相互覆盖 / Prevent concurrent runs to avoid deployment conflicts
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
|
||||
environment {
|
||||
DEPLOY_CONFIG_CHANGED = 'false'
|
||||
|
||||
// 环境服务器地址 / Environment hosts
|
||||
DEV_DEPLOY_HOST = '8.152.207.171'
|
||||
TEST_DEPLOY_HOST = 'YOUR_TEST_SERVER_IP'
|
||||
PROD_DEPLOY_HOST = '192.168.100.230'
|
||||
|
||||
// SSH 连接参数 / SSH connection settings
|
||||
DEV_SSH_USER = 'root'
|
||||
TEST_SSH_USER = 'root'
|
||||
PROD_SSH_USER = 'inspur'
|
||||
SSH_PORT = '22'
|
||||
|
||||
// 各环境统一部署目录 / Unified deploy root
|
||||
DEV_DEPLOY_ROOT = '/opt/hxops'
|
||||
TEST_DEPLOY_ROOT = '/opt/hxops'
|
||||
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
// 多分支流水线检出当前分支代码 / Checkout source from current branch in Multibranch Pipeline
|
||||
checkout scm
|
||||
echo "[Checkout] BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}, COMMIT=${env.GIT_COMMIT}"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Detect Changes') {
|
||||
steps {
|
||||
script {
|
||||
// BRANCH_NAME 必须由 Multibranch Pipeline 提供 / BRANCH_NAME must be provided by Multibranch Pipeline
|
||||
def branchName = env.BRANCH_NAME?.trim()
|
||||
if (!branchName) {
|
||||
error('BRANCH_NAME is empty. Please run this as a Multibranch Pipeline job.')
|
||||
}
|
||||
|
||||
// 以上次成功构建为差异基线 / Use previous successful commit as diff base
|
||||
def baseCommit = env.GIT_PREVIOUS_SUCCESSFUL_COMMIT?.trim()
|
||||
if (!baseCommit) {
|
||||
baseCommit = sh(returnStdout: true, script: 'git rev-parse HEAD^ 2>/dev/null || true').trim()
|
||||
}
|
||||
|
||||
List<String> changedFiles = []
|
||||
if (baseCommit) {
|
||||
changedFiles = sh(
|
||||
returnStdout: true,
|
||||
script: "git diff --name-only ${baseCommit} ${env.GIT_COMMIT}"
|
||||
).trim().split('\\n').findAll { it?.trim() }
|
||||
} else {
|
||||
// 首次构建默认按前后端都变更处理 / First build defaults to full-scope deployment
|
||||
changedFiles = ['frontend/', 'backend/']
|
||||
}
|
||||
|
||||
// 目录级变更识别:用于前后端增量构建 / Directory-level change detection for incremental builds
|
||||
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
|
||||
def backendChanged = changedFiles.any { it.startsWith('backend/') }
|
||||
def deployConfigChanged = changedFiles.any {
|
||||
it == 'docker-compose.yml' ||
|
||||
it == 'Jenkinsfile' ||
|
||||
it == 'scripts/deploy_compose.sh' ||
|
||||
it == 'scripts/healthcheck.sh' ||
|
||||
it == '.env.dev' ||
|
||||
it == '.env.test' ||
|
||||
it == '.env.prod'
|
||||
}
|
||||
|
||||
env.FRONTEND_CHANGED = frontendChanged ? 'true' : 'false'
|
||||
env.BACKEND_CHANGED = backendChanged ? 'true' : 'false'
|
||||
env.DEPLOY_CONFIG_CHANGED = deployConfigChanged ? 'true' : 'false'
|
||||
|
||||
echo "[Detect Changes] branch=${branchName}"
|
||||
echo "[Detect Changes] baseCommit=${baseCommit ?: 'none'}"
|
||||
echo "[Detect Changes] files=${changedFiles.join(', ')}"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Dev') {
|
||||
when {
|
||||
expression {
|
||||
// dev 分支都部署到 dev 环境 / dev branches deploy to dev environment
|
||||
(env.BRANCH_NAME == 'dev') &&
|
||||
// 无变更不部署 / Skip deploy when no effective changes
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Dev] start branch=${env.BRANCH_NAME} host=${env.DEV_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_DEV_DEPLOY私钥部署到开发服务器
|
||||
// Use SSH_DEV_DEPLOY credential to deploy to dev server
|
||||
sshagent(credentials: ['SSH_DEV_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
# 远端更新代码并执行部署脚本 / Update repo on target host and run deploy script
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${DEV_SSH_USER}@${DEV_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${DEV_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh dev "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Dev] done"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Test') {
|
||||
when {
|
||||
expression {
|
||||
// test 分支部署到 test 环境 / test branch deploys to test environment
|
||||
env.BRANCH_NAME == 'test' &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Test] start host=${env.TEST_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_TEST_DEPLOY私钥部署到测试服务器
|
||||
// Use SSH_TEST_DEPLOY credential to deploy to test server
|
||||
sshagent(credentials: ['SSH_TEST_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${TEST_SSH_USER}@${TEST_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${TEST_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git checkout -B test origin/test
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh test "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Test] done"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Prod') {
|
||||
when {
|
||||
expression {
|
||||
// prod 分支部署到生产环境 / prod branch deploys to production environment
|
||||
(env.BRANCH_NAME == 'prod' || env.BRANCH_NAME == 'sophie') &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
// 生产环境增加人工确认 / Manual approval before production deploy
|
||||
input message: 'Confirm deployment to production?'
|
||||
|
||||
echo "[Deploy Prod] start host=${env.PROD_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_PROD_DEPLOY私钥部署到生产服务器
|
||||
// Use SSH_PROD_DEPLOY credential to deploy to prod server
|
||||
sshagent(credentials: ['SSH_PROD_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh prod "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Prod] done"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
// 统一输出最终状态,便于回溯 / Print final flags for traceability
|
||||
echo "[Post] BRANCH_NAME=${env.BRANCH_NAME}, FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,12 +4,18 @@
|
||||
|
||||
Set these on the backend runtime:
|
||||
|
||||
- Recommended start point: copy `backend/.env.production.example` to `backend/.env` and update values.
|
||||
|
||||
- `WECOM_ENABLED=true`
|
||||
- `WECOM_CORP_ID=<your_corp_id>`
|
||||
- `WECOM_AGENT_ID=<your_agent_id>`
|
||||
- `WECOM_SECRET=<your_app_secret>`
|
||||
- `WECOM_REDIRECT_URI=https://<your-domain>/workspace`
|
||||
- `WECOM_AUTO_CREATE_USER=true` (or `false` if you require manual admin binding)
|
||||
- `WECOM_MATCH_RULES=employee_id,mobile` (supported: `employee_id,mobile,email`)
|
||||
- `WECOM_MATCH_OPERATOR=AND` (`AND` / `OR`)
|
||||
- `WECOM_EMPLOYEE_ID_SOURCE=userid` (or `extattr:<name>`)
|
||||
- `WECOM_MOBILE_NORMALIZE=true`
|
||||
|
||||
## 2) Database Migration
|
||||
|
||||
@@ -56,4 +62,3 @@ Available admin APIs:
|
||||
2. WeCom login success creates an audit record.
|
||||
3. Invalid/expired state is rejected.
|
||||
4. Disabled user cannot login via WeCom.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
local_test.db
|
||||
.git
|
||||
.vscode
|
||||
tests
|
||||
@@ -0,0 +1,2 @@
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
@@ -0,0 +1,72 @@
|
||||
# hxops backend production environment template
|
||||
# Usage:
|
||||
# 1) Copy this file to backend/.env
|
||||
# 2) Replace placeholder values
|
||||
# 3) Restart backend service
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Core
|
||||
# -----------------------------------------------------------------------------
|
||||
SECRET_KEY=replace-with-strong-random-secret
|
||||
DATABASE_URL=postgresql://<db_user>:<db_password>@<db_host>:5432/<db_name>
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Dify
|
||||
# -----------------------------------------------------------------------------
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
DIFY_API_KEY=replace-with-default-dify-api-key
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Redis
|
||||
# -----------------------------------------------------------------------------
|
||||
REDIS_URL=redis://:<redis_password>@<redis_host>:6379/0
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Feature switches
|
||||
# -----------------------------------------------------------------------------
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Optional integrations
|
||||
# -----------------------------------------------------------------------------
|
||||
HR_WORKFLOW_IFRAME_URL=https://<your-hr-workflow-url>
|
||||
HR_WORKFLOW_API_BASE=https://<your-hr-workflow-api-base>
|
||||
HR_WORKFLOW_API_KEY=
|
||||
|
||||
INTEGRATION_API_BASE=https://<your-integration-api-base>
|
||||
INTEGRATION_API_KEY=
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# WeCom OAuth
|
||||
# -----------------------------------------------------------------------------
|
||||
WECOM_ENABLED=true
|
||||
WECOM_CORP_ID=wwxxxxxxxxxxxxxxxx
|
||||
WECOM_AGENT_ID=1000001
|
||||
WECOM_SECRET=replace-with-wecom-app-secret
|
||||
WECOM_REDIRECT_URI=https://<your-domain>/workspace
|
||||
# Optional: public HTTPS origin for WeCom console URLs (admin copy helper). Overrides notify base and request host when set.
|
||||
WECOM_PUBLIC_BASE_URL=https://<your-domain>
|
||||
|
||||
# Login strategy:
|
||||
# - Match existing local account first.
|
||||
# - If no match, block login and require admin provision/binding.
|
||||
WECOM_AUTO_CREATE_USER=false
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
|
||||
# Employee id source options:
|
||||
# - userid (default)
|
||||
# - extattr:<name> (from WeCom custom attributes)
|
||||
# - any direct field name returned by user/get
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_ENCODING_AES_KEY=
|
||||
WECOM_CALLBACK_URL=https://<your-domain>/api/user/wecom/callback
|
||||
WECOM_HOMEPAGE_URL=https://<your-domain>/workspace
|
||||
WECOM_TRUSTED_DOMAIN=<your-domain>
|
||||
|
||||
# WeCom notify/deeplink
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=https://<your-domain>
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed
|
||||
@@ -2,13 +2,6 @@ FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
# libpq-dev is required for psycopg2
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
libpq-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
+62
-1
@@ -3,15 +3,39 @@
|
||||
backend/app/__init__.py
|
||||
应用工厂
|
||||
"""
|
||||
from flask import Flask
|
||||
import logging
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from app.config import config
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
|
||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||
return
|
||||
for key, value in applied.items():
|
||||
app.config[key] = value
|
||||
|
||||
|
||||
def create_app(config_name='default'):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
@@ -35,4 +59,41 @@ def create_app(config_name='default'):
|
||||
# 当前用户相关接口(首页、常用问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
# serve the defaults baked into config.py / the image).
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
_apply_persisted_settings(app)
|
||||
|
||||
def _should_return_json_error() -> bool:
|
||||
if request.path.startswith('/api/'):
|
||||
return True
|
||||
accepted = request.headers.get('Accept', '')
|
||||
return 'application/json' in accepted.lower()
|
||||
|
||||
@app.errorhandler(HTTPException)
|
||||
def _handle_http_exception(exc: HTTPException):
|
||||
if not _should_return_json_error():
|
||||
return exc
|
||||
message = exc.description or exc.name or 'HTTP error'
|
||||
return jsonify({'error': str(message)}), int(exc.code or 500)
|
||||
|
||||
@app.errorhandler(Exception)
|
||||
def _handle_unexpected_exception(exc: Exception):
|
||||
app.logger.exception(
|
||||
'Unhandled exception on %s %s',
|
||||
request.method,
|
||||
request.path,
|
||||
exc_info=exc,
|
||||
)
|
||||
if not _should_return_json_error():
|
||||
return '<h1><p>Internal Server Error</p></h1>', 500
|
||||
message = str(exc).strip() or 'Internal server error'
|
||||
return jsonify({'error': message}), 500
|
||||
|
||||
return app
|
||||
+541
-5
@@ -4,19 +4,206 @@ backend/app/api/admin.py
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from datetime import datetime
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import requests
|
||||
import uuid
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
|
||||
def _serialize_wecom_notify_settings():
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
||||
'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '',
|
||||
'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x],
|
||||
}
|
||||
|
||||
|
||||
def _serialize_wecom_system_settings():
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_ENABLED', False)),
|
||||
'corp_id': current_app.config.get('WECOM_CORP_ID') or '',
|
||||
'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''),
|
||||
'secret': current_app.config.get('WECOM_SECRET') or '',
|
||||
'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '',
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile',
|
||||
'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(),
|
||||
'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(),
|
||||
'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email',
|
||||
'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid',
|
||||
'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)),
|
||||
'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '',
|
||||
'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '',
|
||||
'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '',
|
||||
'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '',
|
||||
'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '',
|
||||
'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '',
|
||||
}
|
||||
|
||||
|
||||
def _default_public_base():
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
configured = current_app.config.get(key) or ''
|
||||
if configured:
|
||||
return configured.rstrip('/')
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
|
||||
def _serialize_wecom_integration_manifest():
|
||||
settings = _serialize_wecom_system_settings()
|
||||
public_base = _default_public_base()
|
||||
callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback'
|
||||
homepage_url = settings.get('homepage_url') or f'{public_base}/workspace'
|
||||
trusted_domain = settings.get('trusted_domain') or request.host.split(':')[0]
|
||||
|
||||
return {
|
||||
'public_base_url': public_base,
|
||||
'callback_url': callback_url,
|
||||
'callback_token': settings.get('callback_token') or '',
|
||||
'encoding_aes_key': settings.get('encoding_aes_key') or '',
|
||||
'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url,
|
||||
'homepage_url': homepage_url,
|
||||
'trusted_domain': trusted_domain,
|
||||
'authorize_api': f'{public_base}/api/user/wecom/authorize-url',
|
||||
'login_api': f'{public_base}/api/user/wecom/login',
|
||||
}
|
||||
|
||||
|
||||
def _serialize_debug_match_user(user: User) -> dict:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
'wecom_userid': user.wecom_userid,
|
||||
'wecom_unionid': user.wecom_unionid,
|
||||
}
|
||||
|
||||
|
||||
def _build_wecom_match_preview(identity: dict, rules: list[str], operator: str) -> dict:
|
||||
from app.api import user as user_api
|
||||
|
||||
bind_mode = user_api._get_wecom_first_login_bind_mode()
|
||||
preview = {
|
||||
'bind_mode': bind_mode,
|
||||
'rules': {
|
||||
'fields': rules,
|
||||
'operator': operator,
|
||||
},
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
}
|
||||
|
||||
bound_user = None
|
||||
if identity.get('wecom_userid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||||
if not bound_user and identity.get('wecom_unionid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first()
|
||||
|
||||
if bound_user:
|
||||
preview['decision'] = 'already_bound'
|
||||
preview['bound_user'] = _serialize_debug_match_user(bound_user)
|
||||
return preview
|
||||
|
||||
if bind_mode == 'input_verify':
|
||||
preview['decision'] = 'input_verification_required'
|
||||
preview['allowed_fields'] = user_api._get_wecom_first_login_input_fields()
|
||||
return preview
|
||||
|
||||
matched_users, missing_fields = user_api._find_users_by_match_rules(identity, rules, operator)
|
||||
preview['missing_fields'] = missing_fields
|
||||
preview['matched_users'] = [_serialize_debug_match_user(user) for user in matched_users]
|
||||
|
||||
if missing_fields:
|
||||
preview['decision'] = 'missing_match_fields'
|
||||
elif len(matched_users) == 1:
|
||||
preview['decision'] = 'matched_existing_user'
|
||||
elif len(matched_users) > 1:
|
||||
preview['decision'] = 'ambiguous_match'
|
||||
elif preview['auto_create_user']:
|
||||
preview['decision'] = 'would_auto_create_user'
|
||||
else:
|
||||
preview['decision'] = 'bind_required'
|
||||
return preview
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||||
@require_admin
|
||||
def debug_wecom_user_by_code():
|
||||
from app.api import user as user_api
|
||||
|
||||
if not user_api._is_wecom_configured():
|
||||
return jsonify({'error': 'WeCom login is not configured'}), 400
|
||||
|
||||
data = request.get_json() or {}
|
||||
code = str(data.get('code') or '').strip()
|
||||
if not code:
|
||||
return jsonify({'error': 'code is required'}), 400
|
||||
|
||||
access_token = user_api._get_wecom_access_token()
|
||||
info_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo',
|
||||
params={'access_token': access_token, 'code': code},
|
||||
timeout=8,
|
||||
)
|
||||
auth_info = info_resp.json()
|
||||
userid = auth_info.get('userid') or auth_info.get('UserId')
|
||||
openid = auth_info.get('openid') or auth_info.get('OpenId')
|
||||
|
||||
payload = {
|
||||
'auth_info': auth_info,
|
||||
}
|
||||
|
||||
if auth_info.get('errcode') != 0:
|
||||
payload.update({
|
||||
'error': f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}",
|
||||
'error_code': 'WECOM_AUTH_FAILED',
|
||||
})
|
||||
return jsonify(payload), 401
|
||||
|
||||
if not userid:
|
||||
payload.update({
|
||||
'error': '当前 code 对应的账号不在应用可见范围内,或不是本企业成员。',
|
||||
'error_code': 'WECOM_NOT_IN_AGENT_SCOPE',
|
||||
'openid': openid,
|
||||
})
|
||||
return jsonify(payload), 401
|
||||
|
||||
user_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
|
||||
params={'access_token': access_token, 'userid': userid},
|
||||
timeout=8,
|
||||
)
|
||||
wecom_user = user_resp.json()
|
||||
payload['wecom_user'] = wecom_user
|
||||
|
||||
if wecom_user.get('errcode') != 0:
|
||||
payload.update({
|
||||
'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}",
|
||||
'error_code': 'WECOM_USER_FETCH_FAILED',
|
||||
})
|
||||
return jsonify(payload), 401
|
||||
|
||||
identity = user_api._extract_wecom_identity(wecom_user)
|
||||
rules, operator = user_api._get_wecom_match_config()
|
||||
payload['normalized_identity'] = identity
|
||||
payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator)
|
||||
return jsonify(payload)
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
@@ -452,7 +639,17 @@ def batch_update_permissions():
|
||||
for agent in agents:
|
||||
if agent in user.agents:
|
||||
user.agents.remove(agent)
|
||||
|
||||
if user.wecom_userid:
|
||||
action_label = {'add': '新增', 'remove': '移除', 'set': '重置为'}[action]
|
||||
agent_names = '、'.join([a.name for a in agents]) if agents else '无'
|
||||
send_wecom_event_message(
|
||||
event_type='permission_batch_updated',
|
||||
user=user,
|
||||
title='应用权限已更新',
|
||||
content=f'管理员已{action_label}你的应用权限:{agent_names}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'updated_count': len(users)})
|
||||
|
||||
@@ -510,7 +707,15 @@ def approve_request(id):
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and agent and agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
|
||||
if user and user.wecom_userid:
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_approved',
|
||||
user=user,
|
||||
title='权限申请已通过',
|
||||
content=f'你申请的应用权限已通过:{agent.name if agent else req.agent_id}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -521,6 +726,16 @@ def reject_request(id):
|
||||
if not req: return jsonify({'error': 'Not found'}), 404
|
||||
req.status = 'rejected'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
user = db.session.get(User, req.user_id)
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and user.wecom_userid:
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_rejected',
|
||||
user=user,
|
||||
title='权限申请未通过',
|
||||
content=f'你申请的应用权限未通过:{agent.name if agent else req.agent_id}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -614,6 +829,85 @@ def feedback_report():
|
||||
'distribution': [{'score': s, 'count': c} for s, c in dist]
|
||||
})
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||||
@require_admin
|
||||
def list_general_feedbacks_report():
|
||||
"""
|
||||
List rows from general_feedbacks for report page display.
|
||||
Supports simple fuzzy filters by column name and optional limit.
|
||||
"""
|
||||
query = (
|
||||
db.session.query(
|
||||
GeneralFeedback,
|
||||
User.real_name.label('real_name'),
|
||||
User.department.label('department'),
|
||||
)
|
||||
.outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||
)
|
||||
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved:
|
||||
continue
|
||||
if not value:
|
||||
continue
|
||||
if hasattr(GeneralFeedback, key):
|
||||
col = getattr(GeneralFeedback, key)
|
||||
elif key == 'real_name':
|
||||
col = User.real_name
|
||||
elif key == 'department':
|
||||
col = User.department
|
||||
else:
|
||||
continue
|
||||
query = query.filter(col.cast(db.String).ilike(f"%{value}%"))
|
||||
|
||||
query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id))
|
||||
|
||||
try:
|
||||
limit = int(request.args.get('limit', 200))
|
||||
except (TypeError, ValueError):
|
||||
limit = 200
|
||||
limit = max(1, min(limit, 1000))
|
||||
|
||||
items = query.limit(limit).all()
|
||||
rows = []
|
||||
for item, real_name, department in items:
|
||||
row = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
row[col.name] = val
|
||||
row['real_name'] = real_name
|
||||
row['department'] = department
|
||||
rows.append(row)
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||||
@require_admin
|
||||
def count_general_feedbacks_report():
|
||||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved:
|
||||
continue
|
||||
if not value:
|
||||
continue
|
||||
if hasattr(GeneralFeedback, key):
|
||||
col = getattr(GeneralFeedback, key)
|
||||
elif key == 'real_name':
|
||||
col = User.real_name
|
||||
elif key == 'department':
|
||||
col = User.department
|
||||
else:
|
||||
continue
|
||||
query = query.filter(col.cast(db.String).ilike(f"%{value}%"))
|
||||
|
||||
total = query.count()
|
||||
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
|
||||
|
||||
|
||||
# --- Database ---
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@@ -805,6 +1099,119 @@ def unbind_wecom_user():
|
||||
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||||
@require_admin
|
||||
def provision_wecom_user():
|
||||
"""
|
||||
Atomic admin helper to create user (optional), bind WeCom identity and assign agent permissions.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
create_user = bool(data.get('create_user', True))
|
||||
user_data = data.get('user') or {}
|
||||
bind_data = data.get('bind') or {}
|
||||
user_id = data.get('user_id')
|
||||
permission_updated = False
|
||||
|
||||
wecom_userid = (bind_data.get('wecom_userid') or '').strip()
|
||||
wecom_unionid = (bind_data.get('wecom_unionid') or '').strip()
|
||||
if not wecom_userid:
|
||||
return jsonify({'error': 'bind.wecom_userid is required'}), 400
|
||||
|
||||
if create_user:
|
||||
username = (user_data.get('username') or '').strip()
|
||||
if not username:
|
||||
return jsonify({'error': 'user.username is required when create_user=true'}), 400
|
||||
if db.session.query(User).filter_by(username=username).first():
|
||||
return jsonify({'error': 'Username exists'}), 400
|
||||
|
||||
email = (user_data.get('email') or '').strip() or None
|
||||
employee_id = (user_data.get('employee_id') or '').strip() or None
|
||||
phone_number = (user_data.get('phone_number') or '').strip() or None
|
||||
if email and db.session.query(User).filter_by(email=email).first():
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first():
|
||||
return jsonify({'error': 'Phone number already exists'}), 400
|
||||
|
||||
user = User(
|
||||
username=username,
|
||||
email=email,
|
||||
department=user_data.get('department'),
|
||||
role=user_data.get('role', 'user'),
|
||||
status=user_data.get('status', 'active'),
|
||||
real_name=user_data.get('real_name'),
|
||||
employee_id=employee_id,
|
||||
phone_number=phone_number,
|
||||
)
|
||||
password = user_data.get('password')
|
||||
user.set_password(password or uuid.uuid4().hex)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
binding_status = 'created'
|
||||
else:
|
||||
if user_id is None:
|
||||
user_id = user_data.get('id')
|
||||
if user_id is None:
|
||||
return jsonify({'error': 'user_id is required when create_user=false'}), 400
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'user_id must be integer'}), 400
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
return jsonify({'error': 'User not found'}), 404
|
||||
binding_status = 'updated'
|
||||
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': f'wecom_userid already bound to user {dup.username}'}), 400
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': f'wecom_unionid already bound to user {dup_union.username}'}), 400
|
||||
|
||||
user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
user.wecom_unionid = wecom_unionid
|
||||
|
||||
has_agent_ids = 'agent_ids' in data
|
||||
if has_agent_ids:
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
if not isinstance(agent_ids, list):
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'agent_ids must be array'}), 400
|
||||
if agent_ids:
|
||||
try:
|
||||
unique_ids = sorted({int(i) for i in agent_ids})
|
||||
except (TypeError, ValueError):
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'agent_ids must be integer array'}), 400
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all()
|
||||
if len(agents) != len(unique_ids):
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'Some agent_ids are invalid'}), 400
|
||||
user.agents = agents
|
||||
else:
|
||||
user.agents = []
|
||||
permission_updated = True
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': 'Provision failed due to data uniqueness conflict'}), 400
|
||||
|
||||
return jsonify({
|
||||
'status': 'ok',
|
||||
'user_id': user.id,
|
||||
'binding': binding_status,
|
||||
'permission_updated': permission_updated,
|
||||
}), 201 if create_user else 200
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def get_wecom_login_audits():
|
||||
@@ -834,9 +1241,138 @@ def get_wecom_login_audits():
|
||||
'source': r.source,
|
||||
'status': r.status,
|
||||
'reason': r.reason,
|
||||
'error_code': r.error_code,
|
||||
'match_rules': r.match_rules,
|
||||
'match_operator': r.match_operator,
|
||||
'match_result': r.match_result,
|
||||
'wecom_userid': r.wecom_userid,
|
||||
'ip': r.ip,
|
||||
'user_agent': r.user_agent,
|
||||
'created_at': r.created_at.isoformat() if r.created_at else None,
|
||||
} for r in rows
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_notify_settings():
|
||||
if request.method == 'GET':
|
||||
return jsonify(_serialize_wecom_notify_settings())
|
||||
|
||||
data = request.get_json() or {}
|
||||
updates = {}
|
||||
if 'enabled' in data:
|
||||
updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled'))
|
||||
if 'base_url' in data:
|
||||
updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip()
|
||||
if 'events' in data:
|
||||
events = data.get('events') or []
|
||||
if isinstance(events, list):
|
||||
updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()])
|
||||
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
persist_env_settings(updates)
|
||||
|
||||
return jsonify({'status': 'ok', 'settings': _serialize_wecom_notify_settings()})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_system_settings():
|
||||
if request.method == 'GET':
|
||||
return jsonify(_serialize_wecom_system_settings())
|
||||
|
||||
data = request.get_json() or {}
|
||||
bool_keys = {
|
||||
'enabled': 'WECOM_ENABLED',
|
||||
'auto_create_user': 'WECOM_AUTO_CREATE_USER',
|
||||
'mobile_normalize': 'WECOM_MOBILE_NORMALIZE',
|
||||
}
|
||||
str_keys = {
|
||||
'corp_id': 'WECOM_CORP_ID',
|
||||
'agent_id': 'WECOM_AGENT_ID',
|
||||
'secret': 'WECOM_SECRET',
|
||||
'redirect_uri': 'WECOM_REDIRECT_URI',
|
||||
'match_rules': 'WECOM_MATCH_RULES',
|
||||
'match_operator': 'WECOM_MATCH_OPERATOR',
|
||||
'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE',
|
||||
'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS',
|
||||
'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE',
|
||||
'callback_token': 'WECOM_CALLBACK_TOKEN',
|
||||
'encoding_aes_key': 'WECOM_ENCODING_AES_KEY',
|
||||
'callback_url': 'WECOM_CALLBACK_URL',
|
||||
'homepage_url': 'WECOM_HOMEPAGE_URL',
|
||||
'trusted_domain': 'WECOM_TRUSTED_DOMAIN',
|
||||
'public_base_url': 'WECOM_PUBLIC_BASE_URL',
|
||||
}
|
||||
|
||||
updates = {}
|
||||
for req_key, cfg_key in bool_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = bool(data.get(req_key))
|
||||
for req_key, cfg_key in str_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = str(data.get(req_key) or '').strip()
|
||||
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
|
||||
if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}:
|
||||
current_app.config['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
updates['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
|
||||
if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}:
|
||||
current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
|
||||
persist_env_settings(updates)
|
||||
|
||||
return jsonify({'status': 'ok', 'settings': _serialize_wecom_system_settings()})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_integration_manifest():
|
||||
return jsonify(_serialize_wecom_integration_manifest())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_notify_metrics():
|
||||
now = datetime.utcnow()
|
||||
from_time = now - timedelta(days=30)
|
||||
total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0
|
||||
sent = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.status == 'sent'
|
||||
).scalar() or 0
|
||||
opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.opened_at.isnot(None),
|
||||
).scalar() or 0
|
||||
|
||||
by_event_rows = db.session.query(
|
||||
WecomNotifyAudit.event_type,
|
||||
WecomNotifyAudit.status,
|
||||
func.count(WecomNotifyAudit.id)
|
||||
).filter(WecomNotifyAudit.created_at >= from_time).group_by(
|
||||
WecomNotifyAudit.event_type,
|
||||
WecomNotifyAudit.status
|
||||
).all()
|
||||
by_event = {}
|
||||
for event_type, status, cnt in by_event_rows:
|
||||
if event_type not in by_event:
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
|
||||
return jsonify({
|
||||
'window_days': 30,
|
||||
'total': int(total),
|
||||
'sent': int(sent),
|
||||
'failed': int(total - sent),
|
||||
'send_success_rate': round((sent / total) * 100, 2) if total else 0,
|
||||
'opened_24h': int(opened_24h),
|
||||
'opened_24h_rate': round((opened_24h / sent) * 100, 2) if sent else 0,
|
||||
'by_event': by_event,
|
||||
})
|
||||
+92
-11
@@ -62,11 +62,69 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
def _fetch_preview_source_bytes(file_url: str):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
返回: (content_bytes, content_type, error_tuple)
|
||||
其中 error_tuple = (message, status_code);成功时为 None。
|
||||
"""
|
||||
headers = {}
|
||||
base_url = current_app.config.get('INTEGRATION_API_BASE', '')
|
||||
api_key = current_app.config.get('INTEGRATION_API_KEY', '')
|
||||
|
||||
# 尝试解析 token 并续期
|
||||
if base_url and file_url.startswith(base_url) and 'token=' in file_url:
|
||||
try:
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
parsed = urlparse(file_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
if 'token' in qs:
|
||||
token = qs['token'][0]
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_str = base64.urlsafe_b64decode(payload_b64).decode('utf-8')
|
||||
payload_data = json.loads(payload_str)
|
||||
|
||||
# 检查是否过期,或者直接重新获取
|
||||
import time
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300: # 如果已经过期或者即将在 5 分钟内过期
|
||||
dataset_id = payload_data.get('dataset_id')
|
||||
remote_document_id = payload_data.get('remote_document_id')
|
||||
|
||||
# 如果旧版本的 token 里没有这俩 ID,尝试从聊天记录反查
|
||||
if not dataset_id or not remote_document_id:
|
||||
from app.models import ChatLog
|
||||
from app import db
|
||||
import sqlalchemy as sa
|
||||
try:
|
||||
stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url")
|
||||
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{file_url}%').order_by(ChatLog.created_at.desc()).first()
|
||||
if log and log.retriever_resources:
|
||||
for r in log.retriever_resources:
|
||||
if r.get('source_download_url') == file_url:
|
||||
dataset_id = dataset_id or r.get('dataset_id') or r.get('metadata', {}).get('dataset_id')
|
||||
remote_document_id = remote_document_id or r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id')
|
||||
if dataset_id and remote_document_id:
|
||||
break
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e)
|
||||
|
||||
if dataset_id and remote_document_id:
|
||||
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if new_info and new_info.get('source_download_url'):
|
||||
file_url = new_info['source_download_url']
|
||||
current_app.logger.info("[file-preview] refreshed expired integration url for dataset=%s doc=%s", dataset_id, remote_document_id)
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[file-preview] failed to refresh expired integration token: %s", e)
|
||||
|
||||
if base_url and file_url.startswith(base_url) and api_key:
|
||||
headers['X-Integration-Key'] = api_key
|
||||
|
||||
try:
|
||||
upstream = requests.get(file_url, timeout=(5, 20))
|
||||
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning("[file-preview] upstream request failed: %s", e)
|
||||
return None, None, ('failed to fetch source file', 502)
|
||||
@@ -155,6 +213,7 @@ def get_chat_messages():
|
||||
messages.append({
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or []
|
||||
})
|
||||
@@ -253,12 +312,12 @@ def submit_feedback():
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
|
||||
# 构造查询:限定在当前用户和 Agent 范围内
|
||||
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
|
||||
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
|
||||
if conversation_id:
|
||||
query = query.filter_by(conversation_id=conversation_id)
|
||||
chat_logs_query = chat_logs_query.filter_by(conversation_id=conversation_id)
|
||||
|
||||
# 取最新一条对话日志
|
||||
chat_log = query.order_by(ChatLog.created_at.desc()).first()
|
||||
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
|
||||
if not chat_log:
|
||||
return jsonify({'error': 'ChatLog not found'}), 404
|
||||
|
||||
@@ -327,10 +386,11 @@ def preview_excel():
|
||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||
|
||||
parsed = urlparse(file_url)
|
||||
ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
if ext == 'xls':
|
||||
return jsonify({'error': 'xls is not supported in online preview'}), 415
|
||||
if ext and ext not in ('xlsx',):
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
ext = url_path_ext or name_ext
|
||||
if ext and ext not in ('xlsx', 'xls'):
|
||||
return jsonify({'error': f'unsupported file extension: {ext}'}), 415
|
||||
|
||||
try:
|
||||
@@ -402,7 +462,10 @@ def preview_text():
|
||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||
|
||||
parsed = urlparse(file_url)
|
||||
ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
ext = url_path_ext or name_ext
|
||||
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
|
||||
if ext and ext not in allowed:
|
||||
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
||||
@@ -446,7 +509,10 @@ def preview_file_raw():
|
||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||
|
||||
parsed = urlparse(file_url)
|
||||
ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
ext = url_path_ext or name_ext
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url)
|
||||
if err:
|
||||
msg, code = err
|
||||
@@ -456,14 +522,29 @@ def preview_file_raw():
|
||||
'pdf': 'application/pdf',
|
||||
'doc': 'application/msword',
|
||||
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'xls': 'application/vnd.ms-excel',
|
||||
'csv': 'text/csv',
|
||||
'txt': 'text/plain',
|
||||
'md': 'text/markdown',
|
||||
'markdown': 'text/markdown',
|
||||
'html': 'text/html',
|
||||
'htm': 'text/html',
|
||||
}
|
||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||
return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422
|
||||
|
||||
mime = fallback_types.get(ext) or content_type or 'application/octet-stream'
|
||||
|
||||
from urllib.parse import quote
|
||||
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
|
||||
encoded_filename = quote(filename)
|
||||
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f'preview.{ext or "bin"}'
|
||||
|
||||
is_download = request.args.get('download') == '1'
|
||||
disposition_type = 'attachment' if is_download else 'inline'
|
||||
|
||||
resp = Response(content, status=200, mimetype=mime)
|
||||
resp.headers['Content-Disposition'] = f'inline; filename="{filename}"'
|
||||
resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
|
||||
resp.headers['Cache-Control'] = 'no-store'
|
||||
return resp
|
||||
+931
-61
File diff suppressed because it is too large.
Load diff
+22
-1
@@ -47,13 +47,34 @@ class Config:
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR', 'AND').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE', 'match_rules')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE', 'userid')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN', '')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY', '')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL', '')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL', '')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN', '')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL', '')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL', '')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv(
|
||||
'WECOM_NOTIFY_EVENTS',
|
||||
'permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed',
|
||||
)
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
||||
#'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
||||
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
||||
'postgresql://postgres:123456@localhost:5432/hxops_db',
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``backend/.env`` - best-effort secondary write so local/dev workflows that
|
||||
read the env file directly (or restart without DB access) still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge .env (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
BACKEND_ENV_PATH = Path(__file__).resolve().parents[1] / '.env'
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
BACKEND_ENV_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not BACKEND_ENV_PATH.exists():
|
||||
BACKEND_ENV_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', BACKEND_ENV_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(BACKEND_ENV_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, BACKEND_ENV_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
if not BACKEND_ENV_PATH.exists():
|
||||
return {}
|
||||
try:
|
||||
loaded = dotenv_values(BACKEND_ENV_PATH)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', BACKEND_ENV_PATH, exc)
|
||||
return {}
|
||||
return {
|
||||
key: (value if value is not None else '')
|
||||
for key, value in loaded.items()
|
||||
if key and _matches_prefixes(key, prefixes)
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. Best-effort write to ``backend/.env`` so dev workflows that grep the
|
||||
file or restart without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env file. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over ``backend/.env`` values; both are merged so
|
||||
keys that only live in the env file (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
+82
-1
@@ -1,4 +1,3 @@
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
|
||||
@@ -217,6 +216,23 @@ class Feedback(Base):
|
||||
|
||||
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
@@ -274,7 +290,72 @@ class LoginAudit(Base):
|
||||
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
|
||||
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
|
||||
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
|
||||
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class WecomNotifyAudit(Base):
|
||||
"""
|
||||
企业微信触达审计表
|
||||
用途:记录企微消息发送结果与回流点击数据
|
||||
"""
|
||||
__tablename__ = 'wecom_notify_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed
|
||||
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""
|
||||
应用运行时配置表(Key/Value)
|
||||
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
|
||||
避免容器/部署重建后写入 backend/.env 的修改丢失。
|
||||
"""
|
||||
__tablename__ = 'app_settings'
|
||||
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
|
||||
)
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
用途:记录消息与事件回调(安全模式解密后的内容摘要)
|
||||
"""
|
||||
__tablename__ = 'wecom_callback_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
@@ -24,7 +24,7 @@ chat.py (/api/chat/completions)
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from typing import Any, List
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
@@ -129,7 +129,9 @@ class DifyService:
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
||||
if data.get('answer'):
|
||||
# Keep metadata from non-message events, but avoid appending
|
||||
# intermediate workflow/agent outputs into final user answer.
|
||||
if event == 'message_end' and data.get('answer'):
|
||||
full_answer.append(data.get('answer', ''))
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
@@ -151,7 +153,7 @@ class DifyService:
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
|
||||
with current_app.app_context():
|
||||
DifyService._log_chat(
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or conversation_id,
|
||||
@@ -162,6 +164,8 @@ class DifyService:
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if chat_log_id:
|
||||
data['chat_log_id'] = chat_log_id
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
|
||||
@@ -193,7 +197,7 @@ class DifyService:
|
||||
latency,
|
||||
retriever_resources=None,
|
||||
attribution_parts=None,
|
||||
):
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
把最终问答和元数据写入 ChatLog
|
||||
Persist one chat record into ChatLog table.
|
||||
@@ -221,10 +225,14 @@ class DifyService:
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
return chat_log.id
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.error(f'Failed to log chat: {e}')
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_resources(resources):
|
||||
|
||||
@@ -19,13 +19,36 @@ class IntegrationApiService:
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp = payload.get("download_url_expires_at")
|
||||
if not exp:
|
||||
return True
|
||||
try:
|
||||
return datetime.fromisoformat(exp) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
return True
|
||||
exp_str = payload.get("download_url_expires_at")
|
||||
if exp_str:
|
||||
try:
|
||||
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
|
||||
source_url = payload.get("source_download_url") or ""
|
||||
if "token=" in source_url:
|
||||
try:
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import time
|
||||
qs = parse_qs(urlparse(source_url).query)
|
||||
if 'token' in qs:
|
||||
token = qs['token'][0]
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300:
|
||||
return False # 已过期或即将过期
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
WeCom (企业微信) callback crypto helpers — compatible with WXBizMsgCrypt layout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import random
|
||||
import struct
|
||||
from typing import Optional
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def sha1_hex(parts: list[str]) -> str:
|
||||
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
|
||||
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
|
||||
pad_len = block_size - (len(data) % block_size)
|
||||
return data + bytes([pad_len] * pad_len)
|
||||
|
||||
|
||||
def _pkcs7_unpad(data: bytes) -> bytes:
|
||||
if not data:
|
||||
return data
|
||||
pad_len = data[-1]
|
||||
if pad_len < 1 or pad_len > 32:
|
||||
raise ValueError('invalid pkcs7 padding')
|
||||
if data[-pad_len:] != bytes([pad_len] * pad_len):
|
||||
raise ValueError('invalid pkcs7 padding tail')
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
|
||||
raw = (encoding_aes_key_b64 or '').strip()
|
||||
key = base64.b64decode(raw + '=')
|
||||
if len(key) != 32:
|
||||
raise ValueError('EncodingAESKey must decode to 32 bytes')
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
"""
|
||||
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
|
||||
"""
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
|
||||
msg_bytes = plain_text.encode('utf-8')
|
||||
pack = (
|
||||
random_bytes
|
||||
+ struct.pack('>I', len(msg_bytes))
|
||||
+ msg_bytes
|
||||
+ corp_id.encode('utf-8')
|
||||
)
|
||||
padded = _pkcs7_pad(pack, 32)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
encrypted = cipher.encrypt(padded)
|
||||
return base64.b64encode(encrypted).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
cipher_bytes = base64.b64decode(cipher_b64)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
plain_padded = cipher.decrypt(cipher_bytes)
|
||||
plain = _pkcs7_unpad(plain_padded)
|
||||
content = plain[16:]
|
||||
if len(content) < 4:
|
||||
raise ValueError('decrypted payload too short')
|
||||
xml_len = struct.unpack('>I', content[:4])[0]
|
||||
xml_bytes = content[4:4 + xml_len]
|
||||
tail = content[4 + xml_len:]
|
||||
if tail.decode('utf-8', errors='strict') != corp_id:
|
||||
raise ValueError('corp_id mismatch after decrypt')
|
||||
return xml_bytes.decode('utf-8')
|
||||
|
||||
|
||||
def extract_encrypt_field(xml_body: str) -> Optional[str]:
|
||||
if not xml_body:
|
||||
return None
|
||||
import re
|
||||
|
||||
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
@@ -0,0 +1,146 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlencode
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User, WecomNotifyAudit
|
||||
|
||||
|
||||
_TOKEN_CACHE = {
|
||||
'token': None,
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
if isinstance(raw, str):
|
||||
return {x.strip() for x in raw.split(',') if x.strip()}
|
||||
if isinstance(raw, (list, tuple, set)):
|
||||
return {str(x).strip() for x in raw if str(x).strip()}
|
||||
return set()
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or ''
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
if not path.startswith('/'):
|
||||
path = f'/{path}'
|
||||
merged = {'wecom_trace': trace_id}
|
||||
if params:
|
||||
merged.update({k: v for k, v in params.items() if v is not None})
|
||||
return f'{base}{path}?{urlencode(merged)}'
|
||||
|
||||
|
||||
def _get_access_token() -> str:
|
||||
now = datetime.utcnow()
|
||||
token = _TOKEN_CACHE.get('token')
|
||||
expires_at = _TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and now < expires_at:
|
||||
return token
|
||||
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||||
params={'corpid': corp_id, 'corpsecret': secret},
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
||||
|
||||
_TOKEN_CACHE['token'] = data['access_token']
|
||||
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
) -> dict:
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = WecomNotifyAudit(
|
||||
event_type=event_type,
|
||||
status='failed',
|
||||
trace_id=trace_id,
|
||||
user_id=user.id if user else None,
|
||||
username=user.username if user else None,
|
||||
wecom_userid=user.wecom_userid if user else None,
|
||||
title=title,
|
||||
content=content,
|
||||
)
|
||||
db.session.add(audit)
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
audit.error_code = 'NOTIFY_DISABLED'
|
||||
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
|
||||
|
||||
if event_type not in _get_enabled_events():
|
||||
audit.error_code = 'EVENT_DISABLED'
|
||||
audit.error_message = f'event {event_type} disabled'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
|
||||
|
||||
if not user or not user.wecom_userid:
|
||||
audit.error_code = 'WECOM_USER_UNBOUND'
|
||||
audit.error_message = 'user has no wecom_userid'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
token = _get_access_token()
|
||||
jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = jump_url
|
||||
payload = {
|
||||
'touser': user.wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (content or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
|
||||
except Exception as exc:
|
||||
audit.error_code = 'EXCEPTION'
|
||||
audit.error_message = str(exc)[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
|
||||
|
||||
|
||||
def mark_wecom_message_opened(trace_id: str) -> bool:
|
||||
if not trace_id:
|
||||
return False
|
||||
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
|
||||
if not row:
|
||||
return False
|
||||
if not row.opened_at:
|
||||
row.opened_at = datetime.utcnow()
|
||||
return True
|
||||
@@ -10,7 +10,7 @@ with app.app_context():
|
||||
print(f'id={u.id}, username={u.username}, role={u.role}')
|
||||
|
||||
print()
|
||||
print('=== 各用户对 Agent 3 的会话统计 ===')
|
||||
print('=== 各用户对 Agent 3 的会话统计 ===')
|
||||
for uid in [1, 2, 3, 4, 5]:
|
||||
count = db.session.query(func.count(ChatLog.id)).filter(
|
||||
ChatLog.user_id == uid,
|
||||
|
||||
@@ -7,7 +7,7 @@ import multiprocessing
|
||||
import os
|
||||
|
||||
# 绑定地址
|
||||
bind = "127.0.0.1:5000"
|
||||
bind = "0.0.0.0:5000"
|
||||
|
||||
# 工作模式
|
||||
# 使用 gevent 处理高并发和长连接 (SSE)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""add chat_log_id to general_feedbacks
|
||||
|
||||
Revision ID: 1c2d3e4f5a6b
|
||||
Revises: f2b3c4d5e6f7
|
||||
Create Date: 2026-04-23 16:25:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1c2d3e4f5a6b'
|
||||
down_revision = 'f2b3c4d5e6f7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _normalize_chat_logs_id_postgresql(bind):
|
||||
"""
|
||||
Ensure chat_logs.id is unique before adding PK.
|
||||
Strategy:
|
||||
- Keep the first row for each duplicated id unchanged.
|
||||
- Reassign subsequent duplicated rows to fresh ids > current max(id).
|
||||
"""
|
||||
# fast path: already unique
|
||||
dup_cnt = bind.execute(sa.text(
|
||||
"SELECT COUNT(*) FROM (SELECT id FROM chat_logs GROUP BY id HAVING COUNT(*) > 1) t"
|
||||
)).scalar() or 0
|
||||
if int(dup_cnt) == 0:
|
||||
return
|
||||
|
||||
# Reassign duplicated rows (rn > 1) with new ids.
|
||||
bind.execute(sa.text("""
|
||||
WITH ordered AS (
|
||||
SELECT
|
||||
ctid,
|
||||
id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY id
|
||||
ORDER BY created_at NULLS LAST, ctid
|
||||
) AS rn
|
||||
FROM chat_logs
|
||||
),
|
||||
dups AS (
|
||||
SELECT
|
||||
ctid,
|
||||
id,
|
||||
ROW_NUMBER() OVER (ORDER BY id, ctid) AS dup_seq
|
||||
FROM ordered
|
||||
WHERE rn > 1
|
||||
),
|
||||
max_id AS (
|
||||
SELECT COALESCE(MAX(id), 0) AS m FROM chat_logs
|
||||
)
|
||||
UPDATE chat_logs t
|
||||
SET id = (SELECT m FROM max_id) + dups.dup_seq
|
||||
FROM dups
|
||||
WHERE t.ctid = dups.ctid
|
||||
"""))
|
||||
|
||||
|
||||
def _ensure_chat_logs_id_unique(bind):
|
||||
inspector = sa.inspect(bind)
|
||||
tables = inspector.get_table_names()
|
||||
if 'chat_logs' not in tables:
|
||||
return
|
||||
|
||||
# 1) If id is already the PK, we're good.
|
||||
pk = inspector.get_pk_constraint('chat_logs') or {}
|
||||
constrained = pk.get('constrained_columns') or []
|
||||
if 'id' in constrained:
|
||||
return
|
||||
|
||||
# 2) If id has a UNIQUE constraint, that's also enough for FK target.
|
||||
for uq in inspector.get_unique_constraints('chat_logs') or []:
|
||||
cols = uq.get('column_names') or []
|
||||
if cols == ['id'] or 'id' in cols:
|
||||
return
|
||||
|
||||
# 3) Fallback: add primary key on id.
|
||||
if bind.dialect.name == 'sqlite':
|
||||
# SQLite cannot easily add PK via ALTER TABLE.
|
||||
return
|
||||
|
||||
if bind.dialect.name == 'postgresql':
|
||||
_normalize_chat_logs_id_postgresql(bind)
|
||||
op.execute('ALTER TABLE chat_logs ADD PRIMARY KEY (id)')
|
||||
|
||||
# If chat_logs.id uses a sequence default, align sequence to MAX(id).
|
||||
op.execute("""
|
||||
DO $$
|
||||
DECLARE
|
||||
seq_name text;
|
||||
BEGIN
|
||||
SELECT pg_get_serial_sequence('chat_logs', 'id') INTO seq_name;
|
||||
IF seq_name IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'SELECT setval(%L, COALESCE((SELECT MAX(id) FROM chat_logs), 0), true)',
|
||||
seq_name
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
""")
|
||||
return
|
||||
|
||||
op.create_primary_key('pk_chat_logs', 'chat_logs', ['id'])
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
_ensure_chat_logs_id_unique(bind)
|
||||
|
||||
op.add_column('general_feedbacks', sa.Column('chat_log_id', sa.Integer(), nullable=True))
|
||||
op.create_index('ix_general_feedbacks_chat_log_id', 'general_feedbacks', ['chat_log_id'])
|
||||
op.create_foreign_key(
|
||||
'fk_general_feedbacks_chat_log_id_chat_logs',
|
||||
'general_feedbacks',
|
||||
'chat_logs',
|
||||
['chat_log_id'],
|
||||
['id'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint('fk_general_feedbacks_chat_log_id_chat_logs', 'general_feedbacks', type_='foreignkey')
|
||||
op.drop_index('ix_general_feedbacks_chat_log_id', table_name='general_feedbacks')
|
||||
op.drop_column('general_feedbacks', 'chat_log_id')
|
||||
@@ -0,0 +1,95 @@
|
||||
"""repair missing postgres id sequences
|
||||
|
||||
Revision ID: 9a2d6b4e8c1f
|
||||
Revises: c7d2a4b9e1f0
|
||||
Create Date: 2026-04-19 22:40:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '9a2d6b4e8c1f'
|
||||
down_revision = 'c7d2a4b9e1f0'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _column_info(bind, table_name: str):
|
||||
return bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
select data_type, is_identity, column_default
|
||||
from information_schema.columns
|
||||
where table_schema = 'public'
|
||||
and table_name = :table_name
|
||||
and column_name = 'id'
|
||||
"""
|
||||
),
|
||||
{'table_name': table_name},
|
||||
).mappings().first()
|
||||
|
||||
|
||||
def _needs_sequence(bind, inspector, table_name: str) -> bool:
|
||||
columns = {column['name'] for column in inspector.get_columns(table_name)}
|
||||
if 'id' not in columns:
|
||||
return False
|
||||
|
||||
pk = inspector.get_pk_constraint(table_name) or {}
|
||||
constrained = pk.get('constrained_columns') or []
|
||||
if 'id' not in constrained:
|
||||
return False
|
||||
|
||||
info = _column_info(bind, table_name)
|
||||
if not info:
|
||||
return False
|
||||
if info['data_type'] not in {'integer', 'bigint'}:
|
||||
return False
|
||||
if info['is_identity'] == 'YES':
|
||||
return False
|
||||
|
||||
sequence_name = bind.execute(
|
||||
sa.text("select pg_get_serial_sequence(:table_name, 'id')"),
|
||||
{'table_name': f'public.{table_name}'},
|
||||
).scalar()
|
||||
return sequence_name is None
|
||||
|
||||
|
||||
def _repair_sequence(table_name: str) -> None:
|
||||
seq_name = f'{table_name}_id_seq'
|
||||
op.execute(f'CREATE SEQUENCE IF NOT EXISTS public.{seq_name}')
|
||||
op.execute(f'ALTER SEQUENCE public.{seq_name} OWNED BY public.{table_name}.id')
|
||||
op.execute(
|
||||
"ALTER TABLE public.{table} "
|
||||
"ALTER COLUMN id SET DEFAULT nextval('public.{seq}'::regclass)".format(
|
||||
table=table_name,
|
||||
seq=seq_name,
|
||||
)
|
||||
)
|
||||
op.execute(
|
||||
"""
|
||||
SELECT setval(
|
||||
'public.{seq}',
|
||||
COALESCE((SELECT MAX(id) FROM public.{table}), 1),
|
||||
COALESCE((SELECT MAX(id) FROM public.{table}), 0) > 0
|
||||
)
|
||||
""".format(table=table_name, seq=seq_name)
|
||||
)
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name != 'postgresql':
|
||||
return
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
for table_name in inspector.get_table_names():
|
||||
if _needs_sequence(bind, inspector, table_name):
|
||||
_repair_sequence(table_name)
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Legacy databases may already rely on these repaired defaults/sequences.
|
||||
# Rolling them back would risk breaking inserts again, so keep downgrade noop.
|
||||
pass
|
||||
@@ -0,0 +1,66 @@
|
||||
"""add general feedbacks table
|
||||
|
||||
Revision ID: ab12cd34ef56
|
||||
Revises: 9a2d6b4e8c1f
|
||||
Create Date: 2026-04-22 15:30:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ab12cd34ef56'
|
||||
down_revision = '9a2d6b4e8c1f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _ensure_users_primary_key(bind):
|
||||
inspector = sa.inspect(bind)
|
||||
tables = inspector.get_table_names()
|
||||
if 'users' not in tables:
|
||||
return
|
||||
|
||||
pk = inspector.get_pk_constraint('users') or {}
|
||||
constrained = pk.get('constrained_columns') or []
|
||||
if 'id' in constrained:
|
||||
return
|
||||
|
||||
if bind.dialect.name == 'sqlite':
|
||||
# SQLite alter table limitations: assume existing schema already has users.id PK.
|
||||
return
|
||||
|
||||
if bind.dialect.name == 'postgresql':
|
||||
op.execute('ALTER TABLE users ADD PRIMARY KEY (id)')
|
||||
return
|
||||
|
||||
# Generic fallback for other dialects.
|
||||
op.create_primary_key('pk_users', 'users', ['id'])
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
_ensure_users_primary_key(bind)
|
||||
|
||||
op.create_table(
|
||||
'general_feedbacks',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=50), nullable=False),
|
||||
sa.Column('feedback_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('feedback_module', sa.String(length=32), nullable=False),
|
||||
sa.Column('content', sa.Text(), nullable=False),
|
||||
sa.Column('source_page', sa.String(length=32), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index('ix_general_feedbacks_user_id', 'general_feedbacks', ['user_id'])
|
||||
op.create_index('ix_general_feedbacks_created_at', 'general_feedbacks', ['created_at'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('ix_general_feedbacks_created_at', table_name='general_feedbacks')
|
||||
op.drop_index('ix_general_feedbacks_user_id', table_name='general_feedbacks')
|
||||
op.drop_table('general_feedbacks')
|
||||
@@ -0,0 +1,40 @@
|
||||
"""add app_settings table
|
||||
|
||||
Revision ID: c7d2a4b9e1f0
|
||||
Revises: e6b0b1c2d3f4
|
||||
Create Date: 2026-04-19 20:10:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c7d2a4b9e1f0'
|
||||
down_revision = 'e6b0b1c2d3f4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _has_table(table_name: str) -> bool:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
return table_name in inspector.get_table_names()
|
||||
|
||||
|
||||
def upgrade():
|
||||
if _has_table('app_settings'):
|
||||
return
|
||||
op.create_table(
|
||||
'app_settings',
|
||||
sa.Column('key', sa.String(length=128), nullable=False),
|
||||
sa.Column('value', sa.Text(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('key'),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
if not _has_table('app_settings'):
|
||||
return
|
||||
op.drop_table('app_settings')
|
||||
@@ -0,0 +1,23 @@
|
||||
"""legacy revision bridge
|
||||
|
||||
Revision ID: d4e5f6a7b8c9
|
||||
Revises: c7d2a4b9e1f0
|
||||
Create Date: 2026-04-22 23:30:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd4e5f6a7b8c9'
|
||||
down_revision = 'c7d2a4b9e1f0'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Compatibility bridge for environments whose alembic_version
|
||||
# was stamped to a historical, now-missing revision id.
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,48 @@
|
||||
"""expand login audit columns
|
||||
|
||||
Revision ID: e6b0b1c2d3f4
|
||||
Revises: f1a0b9c8d7e6
|
||||
Create Date: 2026-04-18 17:40:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e6b0b1c2d3f4'
|
||||
down_revision = 'f1a0b9c8d7e6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _get_columns(table_name: str) -> set[str]:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
return {column['name'] for column in inspector.get_columns(table_name)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
existing = _get_columns('login_audits')
|
||||
|
||||
if 'error_code' not in existing:
|
||||
op.add_column('login_audits', sa.Column('error_code', sa.String(length=64), nullable=True))
|
||||
if 'match_rules' not in existing:
|
||||
op.add_column('login_audits', sa.Column('match_rules', sa.String(length=128), nullable=True))
|
||||
if 'match_operator' not in existing:
|
||||
op.add_column('login_audits', sa.Column('match_operator', sa.String(length=8), nullable=True))
|
||||
if 'match_result' not in existing:
|
||||
op.add_column('login_audits', sa.Column('match_result', sa.String(length=64), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
existing = _get_columns('login_audits')
|
||||
|
||||
if 'match_result' in existing:
|
||||
op.drop_column('login_audits', 'match_result')
|
||||
if 'match_operator' in existing:
|
||||
op.drop_column('login_audits', 'match_operator')
|
||||
if 'match_rules' in existing:
|
||||
op.drop_column('login_audits', 'match_rules')
|
||||
if 'error_code' in existing:
|
||||
op.drop_column('login_audits', 'error_code')
|
||||
@@ -0,0 +1,50 @@
|
||||
"""add wecom callback audits
|
||||
|
||||
Revision ID: f1a0b9c8d7e6
|
||||
Revises: d1e8a7f4c2b9
|
||||
Create Date: 2026-04-18 12:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f1a0b9c8d7e6'
|
||||
down_revision = 'd1e8a7f4c2b9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'wecom_callback_audits',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('msg_signature', sa.String(length=128), nullable=True),
|
||||
sa.Column('timestamp', sa.String(length=32), nullable=True),
|
||||
sa.Column('nonce', sa.String(length=64), nullable=True),
|
||||
sa.Column('encrypt_raw', sa.Text(), nullable=True),
|
||||
sa.Column('decrypted_xml', sa.Text(), nullable=True),
|
||||
sa.Column('msg_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('event', sa.String(length=64), nullable=True),
|
||||
sa.Column('from_user', sa.String(length=128), nullable=True),
|
||||
sa.Column('agent_id', sa.String(length=32), nullable=True),
|
||||
sa.Column('msg_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('error_message', sa.String(length=255), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index(op.f('ix_wecom_callback_audits_created_at'), 'wecom_callback_audits', ['created_at'], unique=False)
|
||||
op.create_index(op.f('ix_wecom_callback_audits_msg_type'), 'wecom_callback_audits', ['msg_type'], unique=False)
|
||||
op.create_index(op.f('ix_wecom_callback_audits_event'), 'wecom_callback_audits', ['event'], unique=False)
|
||||
op.create_index(op.f('ix_wecom_callback_audits_from_user'), 'wecom_callback_audits', ['from_user'], unique=False)
|
||||
op.create_index(op.f('ix_wecom_callback_audits_msg_id'), 'wecom_callback_audits', ['msg_id'], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_wecom_callback_audits_msg_id'), table_name='wecom_callback_audits')
|
||||
op.drop_index(op.f('ix_wecom_callback_audits_from_user'), table_name='wecom_callback_audits')
|
||||
op.drop_index(op.f('ix_wecom_callback_audits_event'), table_name='wecom_callback_audits')
|
||||
op.drop_index(op.f('ix_wecom_callback_audits_msg_type'), table_name='wecom_callback_audits')
|
||||
op.drop_index(op.f('ix_wecom_callback_audits_created_at'), table_name='wecom_callback_audits')
|
||||
op.drop_table('wecom_callback_audits')
|
||||
@@ -0,0 +1,22 @@
|
||||
"""merge heads after legacy bridge
|
||||
|
||||
Revision ID: f2b3c4d5e6f7
|
||||
Revises: ab12cd34ef56, d4e5f6a7b8c9
|
||||
Create Date: 2026-04-22 23:50:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f2b3c4d5e6f7'
|
||||
down_revision = ('ab12cd34ef56', 'd4e5f6a7b8c9')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Merge-only revision to unify multiple heads.
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -11,3 +11,4 @@ gevent
|
||||
pydantic
|
||||
python-dotenv
|
||||
openpyxl
|
||||
pycryptodome
|
||||
@@ -1,9 +1,26 @@
|
||||
import pytest
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_persisted_settings(monkeypatch, tmp_path):
|
||||
"""Prevent tests from inheriting the developer's local ``backend/.env``.
|
||||
|
||||
``apply_env_settings`` is called eagerly in ``create_app`` and on every
|
||||
request via the ``before_request`` hook. If the dev's real ``backend/.env``
|
||||
contains ``WECOM_AUTO_CREATE_USER=true`` (or any other WECOM_* override),
|
||||
those values would silently overwrite the explicit ``app.config.update(...)``
|
||||
calls inside test fixtures. Routing reads to a tmp path makes every test
|
||||
start from a clean slate.
|
||||
"""
|
||||
from app import env_persistence
|
||||
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', tmp_path / 'isolated.env')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
from app import create_app, db
|
||||
|
||||
app = create_app('testing')
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
@@ -11,10 +28,12 @@ def app():
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
return app.test_client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers():
|
||||
return {
|
||||
@@ -23,6 +42,7 @@ def admin_headers():
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_headers():
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
def test_login_succeeds_when_login_audit_insert_fails(app, client, monkeypatch):
|
||||
with app.app_context():
|
||||
admin = User(
|
||||
username='admin',
|
||||
email='admin@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
employee_id='EMP-ADMIN',
|
||||
)
|
||||
admin.set_password('admin123')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
|
||||
def _raise_audit_error(payload):
|
||||
raise RuntimeError('simulated audit insert failure')
|
||||
|
||||
monkeypatch.setattr(user_api, '_execute_login_audit_insert', _raise_audit_error)
|
||||
|
||||
response = client.post('/api/user/login', json={
|
||||
'username': 'admin',
|
||||
'password': 'admin123',
|
||||
})
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()
|
||||
assert data['username'] == 'admin'
|
||||
assert data['role'] == 'admin'
|
||||
@@ -0,0 +1,21 @@
|
||||
import base64
|
||||
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
|
||||
|
||||
|
||||
def test_wecom_aes_roundtrip():
|
||||
corp_id = 'ww1234567890abcdef'
|
||||
aes_key_b64 = base64.b64encode(b'0' * 32).decode('ascii').rstrip('=')
|
||||
xml = '<xml><MsgType><![CDATA[event]]></MsgType></xml>'
|
||||
cipher = encrypt_wecom_aes(xml, aes_key_b64, corp_id)
|
||||
plain = decrypt_wecom_aes(cipher, aes_key_b64, corp_id)
|
||||
assert plain == xml
|
||||
|
||||
|
||||
def test_wecom_msg_signature():
|
||||
token = 'hxops-token'
|
||||
ts = '123'
|
||||
nonce = 'abc'
|
||||
encrypt = 'cipher-text'
|
||||
sig = sha1_hex([token, ts, nonce, encrypt])
|
||||
assert sha1_hex([token, ts, nonce, encrypt]) == sig
|
||||
@@ -0,0 +1,96 @@
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.api import admin as admin_api
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
class DummyResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
def test_wecom_debug_user_by_code_returns_raw_user_and_match_preview(client, app, admin_headers, monkeypatch):
|
||||
app.config.update(
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
WECOM_AUTO_CREATE_USER=False,
|
||||
WECOM_MATCH_RULES='employee_id',
|
||||
WECOM_MATCH_OPERATOR='AND',
|
||||
WECOM_EMPLOYEE_ID_SOURCE='userid',
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1')
|
||||
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': 'EMP001'})
|
||||
if 'cgi-bin/user/get' in url:
|
||||
return DummyResponse({
|
||||
'errcode': 0,
|
||||
'userid': 'EMP001',
|
||||
'name': '王超',
|
||||
'mobile': '13800138000',
|
||||
'email': 'emp001@example.com',
|
||||
})
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(admin_api.requests, 'get', fake_get)
|
||||
|
||||
res = client.post(
|
||||
'/api/admin/wecom/debug-user-by-code',
|
||||
json={'code': 'real-code-from-wecom'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['auth_info']['userid'] == 'EMP001'
|
||||
assert data['wecom_user']['name'] == '王超'
|
||||
assert data['normalized_identity']['employee_id'] == 'EMP001'
|
||||
assert data['match_preview']['decision'] == 'matched_existing_user'
|
||||
assert data['match_preview']['matched_users'][0]['username'] == 'emp001'
|
||||
|
||||
|
||||
def test_wecom_debug_user_by_code_returns_scope_error_when_only_openid(client, app, admin_headers, monkeypatch):
|
||||
app.config.update(
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1')
|
||||
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'})
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(admin_api.requests, 'get', fake_get)
|
||||
|
||||
res = client.post(
|
||||
'/api/admin/wecom/debug-user-by-code',
|
||||
json={'code': 'code-out-of-scope'},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 401
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert data['openid'] == 'oExternal_xx'
|
||||
@@ -0,0 +1,247 @@
|
||||
import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
class DummyResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wecom_input_verify_client():
|
||||
app = create_app('testing')
|
||||
app.config.update(
|
||||
TESTING=True,
|
||||
SQLALCHEMY_DATABASE_URI='sqlite:///:memory:',
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
WECOM_REDIRECT_URI='https://example.com/workspace',
|
||||
WECOM_AUTO_CREATE_USER=False,
|
||||
WECOM_MATCH_RULES='employee_id,mobile',
|
||||
WECOM_MATCH_OPERATOR='AND',
|
||||
WECOM_FIRST_LOGIN_BIND_MODE='input_verify',
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS='employee_id,mobile,email',
|
||||
WECOM_EMPLOYEE_ID_SOURCE='userid',
|
||||
WECOM_MOBILE_NORMALIZE=True,
|
||||
)
|
||||
with app.test_client() as client:
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_BIND_SESSION_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
yield client, app
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_BIND_SESSION_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
|
||||
|
||||
def _issue_state(client):
|
||||
res = client.get('/api/user/wecom/authorize-url', query_string={'redirect_uri': 'https://example.com/workspace'})
|
||||
assert res.status_code == 200
|
||||
return res.get_json()['state']
|
||||
|
||||
|
||||
def _mock_wecom_requests(monkeypatch, userid, *, name='Test User', mobile=None, email=None):
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/gettoken' in url:
|
||||
return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200})
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': userid})
|
||||
if 'cgi-bin/user/get' in url:
|
||||
payload = {'errcode': 0, 'userid': userid, 'name': name}
|
||||
if mobile is not None:
|
||||
payload['mobile'] = mobile
|
||||
if email is not None:
|
||||
payload['email'] = email
|
||||
return DummyResponse(payload)
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(user_api.requests, 'get', fake_get)
|
||||
|
||||
|
||||
def _start_input_verify_login(client, monkeypatch, *, userid, name='Test User', mobile=None, email=None):
|
||||
_mock_wecom_requests(monkeypatch, userid=userid, name=name, mobile=mobile, email=email)
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-input-verify', 'state': state})
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_BIND_INPUT_REQUIRED'
|
||||
assert data['binding_token']
|
||||
return data
|
||||
|
||||
|
||||
def test_wecom_login_returns_input_verify_prompt_on_first_login(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP001',
|
||||
name='王超',
|
||||
mobile='13800138000',
|
||||
email='emp001@example.com',
|
||||
)
|
||||
|
||||
assert data['allowed_fields'] == ['employee_id', 'mobile', 'email']
|
||||
assert data['wecom_name'] == '王超'
|
||||
assert data['wecom_userid'] == 'EMP001'
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='emp001').first()
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
def test_wecom_complete_bind_binds_user_by_selected_field(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
login_data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP001',
|
||||
name='王超',
|
||||
mobile='13800138000',
|
||||
email='emp001@example.com',
|
||||
)
|
||||
|
||||
bind_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'employee_id',
|
||||
'value': 'EMP001',
|
||||
})
|
||||
assert bind_res.status_code == 200
|
||||
bind_data = bind_res.get_json()
|
||||
assert bind_data['username'] == 'emp001'
|
||||
assert bind_data['source'] == 'wecom'
|
||||
assert bind_data['bind_status'] == 'input_verified_and_bound'
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='emp001').first()
|
||||
assert user.wecom_userid == 'EMP001'
|
||||
assert user.real_name == '王超'
|
||||
|
||||
expired_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'employee_id',
|
||||
'value': 'EMP001',
|
||||
})
|
||||
assert expired_res.status_code == 400
|
||||
assert expired_res.get_json()['error_code'] == 'WECOM_BIND_SESSION_EXPIRED'
|
||||
|
||||
|
||||
def test_wecom_complete_bind_returns_not_found_when_value_does_not_match(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
login_data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP001',
|
||||
name='王超',
|
||||
mobile='13800138000',
|
||||
email='emp001@example.com',
|
||||
)
|
||||
|
||||
bind_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'email',
|
||||
'value': 'missing@example.com',
|
||||
})
|
||||
assert bind_res.status_code == 404
|
||||
bind_data = bind_res.get_json()
|
||||
assert bind_data['error_code'] == 'WECOM_BIND_INPUT_NOT_FOUND'
|
||||
|
||||
|
||||
def test_wecom_complete_bind_returns_ambiguous_for_mobile_raw_and_normalized_duplicates(wecom_input_verify_client, monkeypatch):
|
||||
client, app = wecom_input_verify_client
|
||||
|
||||
with app.app_context():
|
||||
user1 = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user1.set_password('pwd')
|
||||
user2 = User(
|
||||
username='emp002',
|
||||
email='emp002@example.com',
|
||||
employee_id='EMP002',
|
||||
phone_number='+86 13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user2.set_password('pwd')
|
||||
db.session.add_all([user1, user2])
|
||||
db.session.commit()
|
||||
|
||||
login_data = _start_input_verify_login(
|
||||
client,
|
||||
monkeypatch,
|
||||
userid='EMP009',
|
||||
name='李雷',
|
||||
mobile='13800990000',
|
||||
email='emp009@example.com',
|
||||
)
|
||||
|
||||
bind_res = client.post('/api/user/wecom/complete-bind', json={
|
||||
'binding_token': login_data['binding_token'],
|
||||
'field': 'mobile',
|
||||
'value': '+86 13800138000',
|
||||
})
|
||||
assert bind_res.status_code == 409
|
||||
bind_data = bind_res.get_json()
|
||||
assert bind_data['error_code'] == 'WECOM_BIND_INPUT_AMBIGUOUS'
|
||||
assert bind_data['candidate_count'] == 2
|
||||
@@ -0,0 +1,195 @@
|
||||
import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
|
||||
|
||||
class DummyResponse:
|
||||
def __init__(self, payload):
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wecom_client():
|
||||
app = create_app('testing')
|
||||
app.config.update(
|
||||
TESTING=True,
|
||||
SQLALCHEMY_DATABASE_URI='sqlite:///:memory:',
|
||||
WECOM_ENABLED=True,
|
||||
WECOM_CORP_ID='ww-test',
|
||||
WECOM_AGENT_ID='100001',
|
||||
WECOM_SECRET='secret-test',
|
||||
WECOM_REDIRECT_URI='https://example.com/workspace',
|
||||
WECOM_AUTO_CREATE_USER=False,
|
||||
WECOM_MATCH_RULES='employee_id,mobile',
|
||||
WECOM_MATCH_OPERATOR='AND',
|
||||
WECOM_EMPLOYEE_ID_SOURCE='userid',
|
||||
WECOM_MOBILE_NORMALIZE=True,
|
||||
)
|
||||
with app.test_client() as client:
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
yield client, app
|
||||
db.session.remove()
|
||||
db.drop_all()
|
||||
user_api._WECOM_STATE_CACHE.clear()
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['token'] = None
|
||||
user_api._WECOM_ACCESS_TOKEN_CACHE['expires_at'] = None
|
||||
|
||||
|
||||
def _issue_state(client):
|
||||
res = client.get('/api/user/wecom/authorize-url', query_string={'redirect_uri': 'https://example.com/workspace'})
|
||||
assert res.status_code == 200
|
||||
return res.get_json()['state']
|
||||
|
||||
|
||||
def _mock_wecom_requests(monkeypatch, userid, mobile=None, email=None):
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/gettoken' in url:
|
||||
return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200})
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
# 真实 WeCom /cgi-bin/auth/getuserinfo 返回的是小写 userid (企业成员),
|
||||
# 外部联系人/不在可见范围则返回 openid 而无 userid。
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'userid': userid})
|
||||
if 'cgi-bin/user/get' in url:
|
||||
payload = {'errcode': 0, 'userid': userid, 'name': 'Test User'}
|
||||
if mobile is not None:
|
||||
payload['mobile'] = mobile
|
||||
if email is not None:
|
||||
payload['email'] = email
|
||||
return DummyResponse(payload)
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(user_api.requests, 'get', fake_get)
|
||||
|
||||
|
||||
def test_wecom_login_match_existing_user_by_employee_and_mobile(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='emp001',
|
||||
email='emp001@example.com',
|
||||
employee_id='EMP001',
|
||||
phone_number='13800138000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP001', mobile='13800138000', email='emp001@example.com')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-1', 'state': state})
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['bind_status'] == 'matched_and_bound'
|
||||
assert data['username'] == 'emp001'
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='emp001').first()
|
||||
assert user.wecom_userid == 'EMP001'
|
||||
|
||||
|
||||
def test_wecom_login_bind_required_when_no_match(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP404', mobile='13800999999', email='emp404@example.com')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-2', 'state': state})
|
||||
assert res.status_code == 403
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_BIND_REQUIRED'
|
||||
assert data['reason'] == 'bind_required'
|
||||
|
||||
with app.app_context():
|
||||
assert db.session.query(User).count() == 0
|
||||
|
||||
|
||||
def test_wecom_login_ambiguous_match_returns_409(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
with app.app_context():
|
||||
app.config['WECOM_MATCH_OPERATOR'] = 'OR'
|
||||
user1 = User(
|
||||
username='u1',
|
||||
email='u1@example.com',
|
||||
employee_id='EMP777',
|
||||
phone_number='13900000001',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user1.set_password('pwd')
|
||||
user2 = User(
|
||||
username='u2',
|
||||
email='u2@example.com',
|
||||
employee_id='EMP888',
|
||||
phone_number='13888888888',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user2.set_password('pwd')
|
||||
db.session.add_all([user1, user2])
|
||||
db.session.commit()
|
||||
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP777', mobile='13888888888')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-3', 'state': state})
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_MATCH_AMBIGUOUS'
|
||||
assert data['reason'] == 'ambiguous_match'
|
||||
assert data['candidate_count'] == 2
|
||||
|
||||
|
||||
def test_wecom_login_missing_match_attr_returns_422(wecom_client, monkeypatch):
|
||||
client, app = wecom_client
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='u3',
|
||||
email='u3@example.com',
|
||||
employee_id='EMP003',
|
||||
phone_number='13800380000',
|
||||
status='active',
|
||||
role='user',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
_mock_wecom_requests(monkeypatch, userid='EMP003', mobile=None, email='u3@example.com')
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-4', 'state': state})
|
||||
assert res.status_code == 422
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_MATCH_ATTR_MISSING'
|
||||
assert data['missing_field'] == 'mobile'
|
||||
|
||||
|
||||
def test_wecom_login_returns_clear_error_when_user_not_in_agent_scope(wecom_client, monkeypatch):
|
||||
"""当 /auth/getuserinfo 返回 errcode=0 但只有 openid(登录者不在自建应用的可见范围)时,
|
||||
必须给出明确的中文提示而不是 'WeCom auth failed: ok'。
|
||||
"""
|
||||
client, app = wecom_client
|
||||
|
||||
def fake_get(url, params=None, timeout=8):
|
||||
if 'cgi-bin/gettoken' in url:
|
||||
return DummyResponse({'errcode': 0, 'access_token': 'token-1', 'expires_in': 7200})
|
||||
if 'cgi-bin/auth/getuserinfo' in url:
|
||||
return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'})
|
||||
raise AssertionError(f'unexpected url: {url}')
|
||||
|
||||
monkeypatch.setattr(user_api.requests, 'get', fake_get)
|
||||
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-out-of-scope', 'state': state})
|
||||
assert res.status_code == 401
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert '可见范围' in data['error']
|
||||
assert 'WeCom auth failed: ok' not in data['error']
|
||||
@@ -0,0 +1,107 @@
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def test_wecom_provision_create_bind_and_set_permissions(client, app, admin_headers):
|
||||
with app.app_context():
|
||||
a1 = Agent(name='A1', type='api', dify_app_id='app-a1', dify_api_key='k-a1', is_active=True)
|
||||
a2 = Agent(name='A2', type='api', dify_app_id='app-a2', dify_api_key='k-a2', is_active=True)
|
||||
db.session.add_all([a1, a2])
|
||||
db.session.commit()
|
||||
a1_id, a2_id = a1.id, a2.id
|
||||
|
||||
payload = {
|
||||
'create_user': True,
|
||||
'user': {
|
||||
'username': 'emp2001',
|
||||
'real_name': 'Emp 2001',
|
||||
'employee_id': 'EMP2001',
|
||||
'phone_number': '13800111222',
|
||||
'email': 'emp2001@example.com',
|
||||
'department': 'IT',
|
||||
'role': 'user',
|
||||
'status': 'active',
|
||||
},
|
||||
'bind': {
|
||||
'wecom_userid': 'EMP2001',
|
||||
'wecom_unionid': 'UNION-2001',
|
||||
},
|
||||
'agent_ids': [a1_id, a2_id],
|
||||
}
|
||||
res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 201
|
||||
body = res.get_json()
|
||||
assert body['status'] == 'ok'
|
||||
assert body['permission_updated'] is True
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, body['user_id'])
|
||||
assert user is not None
|
||||
assert user.wecom_userid == 'EMP2001'
|
||||
assert user.wecom_unionid == 'UNION-2001'
|
||||
assert sorted([a.id for a in user.agents]) == sorted([a1_id, a2_id])
|
||||
|
||||
|
||||
def test_wecom_provision_conflict_should_not_create_new_user(client, app, admin_headers):
|
||||
with app.app_context():
|
||||
existing = User(username='bound_user', email='bound@example.com', role='user', status='active', wecom_userid='WX-DUP')
|
||||
existing.set_password('pwd')
|
||||
db.session.add(existing)
|
||||
db.session.commit()
|
||||
|
||||
payload = {
|
||||
'create_user': True,
|
||||
'user': {
|
||||
'username': 'new_to_rollback',
|
||||
'email': 'new_to_rollback@example.com',
|
||||
},
|
||||
'bind': {
|
||||
'wecom_userid': 'WX-DUP',
|
||||
},
|
||||
'agent_ids': [],
|
||||
}
|
||||
res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 400
|
||||
assert 'already bound to user' in res.get_json()['error']
|
||||
|
||||
with app.app_context():
|
||||
should_not_exist = db.session.query(User).filter_by(username='new_to_rollback').first()
|
||||
assert should_not_exist is None
|
||||
|
||||
|
||||
def test_wecom_provision_bind_existing_user(client, app, admin_headers):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='existing_user',
|
||||
email='existing@example.com',
|
||||
employee_id='EMP3001',
|
||||
phone_number='13800990011',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('pwd')
|
||||
agent = Agent(name='A3', type='api', dify_app_id='app-a3', dify_api_key='k-a3', is_active=True)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
user_id = user.id
|
||||
agent_id = agent.id
|
||||
|
||||
payload = {
|
||||
'create_user': False,
|
||||
'user_id': user_id,
|
||||
'bind': {
|
||||
'wecom_userid': 'EMP3001',
|
||||
},
|
||||
'agent_ids': [agent_id],
|
||||
}
|
||||
res = client.post('/api/admin/wecom/provision', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()
|
||||
assert body['binding'] == 'updated'
|
||||
assert body['permission_updated'] is True
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, user_id)
|
||||
assert user.wecom_userid == 'EMP3001'
|
||||
assert [a.id for a in user.agents] == [agent_id]
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
from dotenv import dotenv_values
|
||||
|
||||
from app import db, env_persistence
|
||||
from app.models import AppSetting
|
||||
|
||||
|
||||
def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path):
|
||||
env_file = tmp_path / '.env'
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
|
||||
|
||||
payload = {
|
||||
'enabled': True,
|
||||
'corp_id': 'ww-persisted',
|
||||
'agent_id': '1000999',
|
||||
'secret': 'persist-secret',
|
||||
'redirect_uri': 'https://example.com/workspace',
|
||||
'auto_create_user': False,
|
||||
'match_rules': 'employee_id,email',
|
||||
'match_operator': 'OR',
|
||||
'employee_id_source': 'extattr:job_no',
|
||||
'mobile_normalize': False,
|
||||
'callback_token': 'cb-token',
|
||||
'encoding_aes_key': 'enc-key',
|
||||
'callback_url': 'https://example.com/api/user/wecom/callback',
|
||||
'homepage_url': 'https://example.com/workspace',
|
||||
'trusted_domain': 'example.com',
|
||||
'public_base_url': 'https://example.com',
|
||||
}
|
||||
|
||||
res = client.put('/api/admin/wecom/system-settings', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
|
||||
saved = dotenv_values(env_file)
|
||||
assert saved['WECOM_ENABLED'] == 'true'
|
||||
assert saved['WECOM_CORP_ID'] == 'ww-persisted'
|
||||
assert saved['WECOM_MATCH_OPERATOR'] == 'OR'
|
||||
assert saved['WECOM_PUBLIC_BASE_URL'] == 'https://example.com'
|
||||
|
||||
with app.app_context():
|
||||
rows = {row.key: row.value for row in db.session.query(AppSetting).all()}
|
||||
assert rows['WECOM_ENABLED'] == 'true'
|
||||
assert rows['WECOM_CORP_ID'] == 'ww-persisted'
|
||||
assert rows['WECOM_MATCH_OPERATOR'] == 'OR'
|
||||
assert rows['WECOM_PUBLIC_BASE_URL'] == 'https://example.com'
|
||||
|
||||
with app.app_context():
|
||||
app.config['WECOM_ENABLED'] = False
|
||||
app.config['WECOM_CORP_ID'] = ''
|
||||
app.config['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
app.config['WECOM_PUBLIC_BASE_URL'] = ''
|
||||
|
||||
res = client.get('/api/admin/wecom/system-settings', headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['enabled'] is True
|
||||
assert data['corp_id'] == 'ww-persisted'
|
||||
assert data['match_operator'] == 'OR'
|
||||
assert data['public_base_url'] == 'https://example.com'
|
||||
|
||||
|
||||
def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path):
|
||||
env_file = tmp_path / '.env'
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
|
||||
|
||||
payload = {
|
||||
'enabled': False,
|
||||
'base_url': 'https://notify.example.com',
|
||||
'events': ['task_completed', 'permission_batch_updated'],
|
||||
}
|
||||
|
||||
res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
|
||||
saved = dotenv_values(env_file)
|
||||
assert saved['WECOM_NOTIFY_ENABLED'] == 'false'
|
||||
assert saved['WECOM_NOTIFY_BASE_URL'] == 'https://notify.example.com'
|
||||
assert saved['WECOM_NOTIFY_EVENTS'] == 'task_completed,permission_batch_updated'
|
||||
|
||||
with app.app_context():
|
||||
rows = {row.key: row.value for row in db.session.query(AppSetting).all()}
|
||||
assert rows['WECOM_NOTIFY_ENABLED'] == 'false'
|
||||
assert rows['WECOM_NOTIFY_BASE_URL'] == 'https://notify.example.com'
|
||||
assert rows['WECOM_NOTIFY_EVENTS'] == 'task_completed,permission_batch_updated'
|
||||
|
||||
with app.app_context():
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
app.config['WECOM_NOTIFY_BASE_URL'] = ''
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = ''
|
||||
|
||||
res = client.get('/api/admin/wecom/notify-settings', headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['enabled'] is False
|
||||
assert data['base_url'] == 'https://notify.example.com'
|
||||
assert data['events'] == ['task_completed', 'permission_batch_updated']
|
||||
|
||||
|
||||
def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin_headers, monkeypatch, tmp_path):
|
||||
"""Simulate a container rebuild that wipes backend/.env. The DB row must
|
||||
still drive the runtime configuration."""
|
||||
env_file = tmp_path / '.env'
|
||||
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
|
||||
|
||||
res = client.put(
|
||||
'/api/admin/wecom/system-settings',
|
||||
json={'corp_id': 'ww-from-db-only', 'enabled': True},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
# Wipe the env file the way a fresh container build would.
|
||||
if env_file.exists():
|
||||
env_file.unlink()
|
||||
|
||||
# Reset in-memory config to defaults to prove the next request reloads
|
||||
# values from the database rather than the (now empty) env file.
|
||||
with app.app_context():
|
||||
app.config['WECOM_CORP_ID'] = ''
|
||||
app.config['WECOM_ENABLED'] = False
|
||||
|
||||
res = client.get('/api/admin/wecom/system-settings', headers=admin_headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['corp_id'] == 'ww-from-db-only'
|
||||
assert data['enabled'] is True
|
||||
+12
-5
@@ -3,23 +3,29 @@ services:
|
||||
# hxops-backend: Flask 后端服务 (端口: 5000)
|
||||
# ==============================================================================
|
||||
hxops-backend:
|
||||
image: ${BACKEND_IMAGE:-hxops-backend:local}
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: hxops-backend
|
||||
restart: always
|
||||
environment:
|
||||
# 数据库连接 (指向宿主机或其他容器,请根据实际环境修改)
|
||||
- DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
# Flask 配置
|
||||
- FLASK_APP=run.py
|
||||
- FLASK_ENV=production
|
||||
# 数据库连接 (在环境变量中配置)
|
||||
- DATABASE_URL=${DATABASE_URL}
|
||||
- FLASK_APP=${FLASK_APP:-run.py}
|
||||
- FLASK_ENV=${FLASK_ENV:-production}
|
||||
# 允许容器访问宿主机服务 (如数据库)
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
# 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露
|
||||
ports:
|
||||
- "5002:5002"
|
||||
# 持久化运行时可写文件:
|
||||
# - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写,
|
||||
# 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动
|
||||
# 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。
|
||||
volumes:
|
||||
- ./backend/.env:/app/.env
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
@@ -27,6 +33,7 @@ services:
|
||||
# hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80)
|
||||
# ==============================================================================
|
||||
hxops-frontend:
|
||||
image: ${FRONTEND_IMAGE:-hxops-frontend:local}
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Agent 使用公告
|
||||
|
||||
发布日期:2026-04-10
|
||||
|
||||
为便于统一使用企业知识能力,现对当前可用 Agent 及使用方式公告如下。
|
||||
|
||||
## 一、当前可用 Agent
|
||||
|
||||
1. 人事规章 Agent
|
||||
- 适用范围:人事制度查询、请假/考勤/入离职等规则说明。
|
||||
- 常见问题:假期天数、审批流程、制度条款解释。
|
||||
|
||||
2. 体系文件 Agent
|
||||
- 适用范围:质量体系、流程规范、制度文件检索与解读。
|
||||
- 常见问题:流程步骤、责任分工、文件版本与执行标准。
|
||||
|
||||
3. 有害物质检测报告 Agent
|
||||
- 适用范围:有害物质检测报告查询、指标解读、报告版本核对。
|
||||
- 常见问题:检测项目说明、结果判定、报告有效性。
|
||||
|
||||
4. MSDS Agent
|
||||
- 适用范围:化学品安全技术说明书检索与安全要求查询。
|
||||
- 常见问题:危害特性、防护措施、储存运输要求。
|
||||
|
||||
5. 材质证明 Agent
|
||||
- 适用范围:材质证明文件检索、材质参数与批次信息核对。
|
||||
- 常见问题:材质等级、证明文件匹配、供应批次追溯。
|
||||
|
||||
6. 研发专利 Agent
|
||||
- 适用范围:研发专利资料查询、专利信息归档与检索。
|
||||
- 常见问题:专利状态、专利主题检索、资料定位。
|
||||
|
||||
7. 项目合由 Agent
|
||||
- 适用范围:项目合由相关资料查询与条款信息检索。
|
||||
- 常见问题:项目信息定位、条款核对、执行依据查询。
|
||||
|
||||
8. 生产 SOP Agent
|
||||
- 适用范围:生产标准作业程序查询、步骤与规范解释。
|
||||
- 常见问题:工序顺序、操作要点、异常处理流程。
|
||||
|
||||
9. 固资管理 Agent
|
||||
- 适用范围:固定资产管理制度、台账与流程说明查询。
|
||||
- 常见问题:资产登记、盘点流程、报废与调拨规则。
|
||||
|
||||
10. 资讯 Agent
|
||||
- 适用范围:资讯信息汇总、分类检索与快速查询。
|
||||
- 常见问题:信息定位、主题分类、最新资讯查阅。
|
||||
|
||||
## 二、使用办法
|
||||
|
||||
1. 登录系统后进入 Agent 工作台。
|
||||
2. 选择对应 Agent(如“人事规章”或“体系文件”)。
|
||||
3. 用完整问题描述需求,建议包含场景、时间范围和关键对象。
|
||||
4. 获取回复后,可继续追问以补充细节。
|
||||
5. 对关键结论请结合原制度文件进行复核后执行。
|
||||
|
||||
## 三、提问建议
|
||||
|
||||
1. 尽量一次说清楚背景,例如“适用于哪个部门、哪个时间段”。
|
||||
2. 优先使用“我想确认……是否符合规定”这类明确问法。
|
||||
3. 涉及审批或执行动作时,先确认流程节点和责任人。
|
||||
|
||||
## 四、注意事项
|
||||
|
||||
1. Agent 回复用于辅助决策,不替代正式制度原文。
|
||||
2. 如遇制度冲突或版本疑问,请以最新发布文件和管理部门口径为准。
|
||||
3. 涉及敏感信息时,请遵循公司数据与权限管理要求。
|
||||
|
||||
请各部门按本公告执行,如需新增 Agent 能力,请提交需求至平台管理员。
|
||||
@@ -0,0 +1,257 @@
|
||||
# HXOPS 新人环境搭建与配置文档(已补齐)
|
||||
|
||||
> 更新时间:2026-04-25
|
||||
> 适用对象:开发、测试、运维、实施同学
|
||||
|
||||
## 1. 项目基础信息
|
||||
|
||||
- 项目名称:`HXOPS / Enterprise AI Gateway`
|
||||
- 代码仓库:`https://gitee.com/justop/hxops.git`
|
||||
- 项目任务看板:`https://www.kdocs.cn/l/ct8FI9gCM5eU`
|
||||
- 服务器部署默认分支:`dev`
|
||||
- 当前本地分支(示例):`sophie`
|
||||
- 项目根目录:`hxops/`
|
||||
|
||||
## 2. 新人需要安装的软件
|
||||
|
||||
1. Git(建议 `>= 2.40`)
|
||||
2. Node.js + npm(建议 `Node.js 20 LTS`)
|
||||
3. Python(建议 `3.12`)
|
||||
4. PostgreSQL(建议 `>= 14`)
|
||||
5. Redis(建议 `>= 6`)
|
||||
6. Docker Desktop(推荐)
|
||||
7. VS Code 或 Cursor(推荐插件:Python、Pylance、Vue - Official、ESLint、Prettier、Docker)
|
||||
8. 可选:Postman/Apifox、DBeaver/DataGrip、企业微信客户端
|
||||
|
||||
## 3. Git 分支说明与操作原则
|
||||
|
||||
### 3.1 分支用途
|
||||
|
||||
- `dev`:日常开发主分支,功能开发和缺陷修复先进入 `dev`
|
||||
- `test`:测试验收分支,用于联调、回归和UAT验证
|
||||
- `prod`:生产发布分支,仅保留可发布代码
|
||||
|
||||
### 3.2 标准流转方向
|
||||
|
||||
1. 功能分支从 `dev` 切出(例如 `feature/xxx`、`fix/xxx`)
|
||||
2. 开发完成后合并回 `dev`
|
||||
3. 提测时由 `dev` 合并到 `test`
|
||||
4. 验收通过后由 `test` 合并到 `prod`
|
||||
5. 生产紧急修复后,需要反向同步回 `dev`(必要时也同步到 `test`)
|
||||
|
||||
### 3.3 操作原则
|
||||
|
||||
1. `prod` 禁止直接开发和直接推送,必须通过合并请求(PR/MR)
|
||||
2. `test` 只接收来自 `dev` 的提测合并,不做长期开发
|
||||
3. 所有功能开发在独立功能分支完成,禁止在公共分支上直接提交
|
||||
4. 提交信息建议规范化:`feat:`、`fix:`、`refactor:`、`docs:`、`chore:`
|
||||
5. 合并前必须完成最少检查:
|
||||
- 能启动前后端
|
||||
- 关键页面可访问
|
||||
- 登录流程可用
|
||||
6. 任何涉及数据库结构变更的提交,必须包含迁移脚本或升级说明
|
||||
7. 禁止将密钥、密码、生产地址等敏感信息提交到仓库
|
||||
|
||||
## 4. 代码拉取与目录说明
|
||||
|
||||
### 4.1 拉取代码
|
||||
|
||||
```bash
|
||||
git clone https://gitee.com/justop/hxops.git
|
||||
cd hxops
|
||||
```
|
||||
|
||||
### 4.2 常用 Git 操作示例
|
||||
|
||||
```bash
|
||||
# 拉取远程分支
|
||||
git fetch origin
|
||||
|
||||
# 切到开发主分支
|
||||
git checkout dev
|
||||
git pull origin dev
|
||||
|
||||
# 从 dev 新建功能分支
|
||||
git checkout -b feature/your-feature-name
|
||||
|
||||
# 开发完成后推送
|
||||
git add .
|
||||
git commit -m "feat: your change summary"
|
||||
git push origin feature/your-feature-name
|
||||
```
|
||||
|
||||
### 4.3 关键目录
|
||||
|
||||
- `frontend/`:Vue 3 + TypeScript + Vite
|
||||
- `backend/`:Flask + SQLAlchemy + Flask-Migrate
|
||||
- `docs/`:项目文档
|
||||
- `scripts/`:部署和运维脚本
|
||||
- `docker-compose.yml`:容器编排
|
||||
|
||||
## 5. 本地开发环境搭建
|
||||
|
||||
### 5.1 后端(本地)
|
||||
|
||||
1. 创建虚拟环境并激活
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv .venv
|
||||
# Windows
|
||||
.venv\Scripts\activate
|
||||
# macOS/Linux
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 初始化数据库(2选1)
|
||||
```bash
|
||||
# 方案A:PostgreSQL(推荐)
|
||||
python init_db.py
|
||||
|
||||
# 方案B:导入现有环境数据库(按团队流程执行)
|
||||
# 数据库主机:192.168.100.230
|
||||
# 用户名:postgres
|
||||
# 密码:difyai123456
|
||||
# 目标库:hxops_db
|
||||
```
|
||||
|
||||
4. 启动后端
|
||||
```bash
|
||||
python run.py
|
||||
```
|
||||
|
||||
后端本地开发端口:`5002`(`backend/run.py`)。
|
||||
|
||||
### 5.2 前端(本地)
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端本地开发端口:`8881`(`frontend/vite.config.ts`)。
|
||||
本地开发时前端 `/api` 已代理到 `http://127.0.0.1:5002`。
|
||||
|
||||
### 5.3 Docker 启动(推荐)
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
当前对外端口映射(`docker-compose.yml`):
|
||||
- 前端:`8890:80`
|
||||
- 后端:`5002:5002`
|
||||
|
||||
注意:当前项目中后端端口存在 `5000` 与 `5002` 并存配置,若容器联调异常,优先统一端口配置。
|
||||
|
||||
## 6. 项目登录环境与账号配置
|
||||
|
||||
### 6.1 登录方式
|
||||
|
||||
1. 账号密码登录
|
||||
2. 企业微信 OAuth 登录(WECOM)
|
||||
|
||||
### 6.2 环境入口(已补齐可确定项)
|
||||
|
||||
| 环境 | 前端地址 | 后端地址 | 登录方式 | 备注 |
|
||||
|---|---|---|---|---|
|
||||
| 本地 | `http://localhost:8881` | `http://localhost:5002` | 密码/企业微信(按配置) | |
|
||||
| 测试 | `待定` | `待定` | 密码/企业微信(按配置) | |
|
||||
| 生产 | `http://192.168.100.230:8881/` | | 密码/企业微信(按配置) | |
|
||||
| 服务器部署(脚本) | `<待补:域名>` | `<待补:网关地址>` | 密码/企业微信 | |
|
||||
| Prod | `<待补>` | `<待补>` | `<待补>` | |
|
||||
|
||||
### 6.3 默认测试账号(仅本地初始化脚本场景)
|
||||
|
||||
| 用户名 | 默认密码 | 角色 | 来源 |
|
||||
|---|---|---|---|
|
||||
| `admin` | `Hxit@54321` | `admin` | `backend/init_local_db.py` / `backend/fix_admin.py` |
|
||||
|
||||
说明:生产环境禁止使用默认密码,首次上线后必须立即重置。
|
||||
|
||||
### 6.4 企业微信登录(WECOM)配置
|
||||
|
||||
后端 `.env` 至少配置:
|
||||
|
||||
- `WECOM_ENABLED=true`
|
||||
- `WECOM_CORP_ID=`
|
||||
- `WECOM_AGENT_ID=`
|
||||
- `WECOM_SECRET=`
|
||||
- `WECOM_REDIRECT_URI=https://<your-domain>/workspace`
|
||||
- `WECOM_CALLBACK_URL=https://<your-domain>/api/user/wecom/callback`
|
||||
- `WECOM_HOMEPAGE_URL=https://<your-domain>/workspace`
|
||||
- `WECOM_TRUSTED_DOMAIN=<your-domain>`
|
||||
|
||||
推荐策略:
|
||||
|
||||
- `WECOM_AUTO_CREATE_USER=false`
|
||||
- `WECOM_MATCH_RULES=employee_id,mobile`
|
||||
- `WECOM_MATCH_OPERATOR=AND`
|
||||
- `WECOM_EMPLOYEE_ID_SOURCE=userid`
|
||||
|
||||
联调清单参考:`WECOM_SETUP_CHECKLIST.md`。
|
||||
|
||||
## 7. 环境变量清单(交接必填)
|
||||
|
||||
| 变量名 | 用途 | 示例 |
|
||||
|---|---|---|
|
||||
| `SECRET_KEY` | Flask 密钥 | 随机长字符串 |
|
||||
| `DATABASE_URL` | 数据库连接 | `postgresql://user:pwd@host:5432/db` |
|
||||
| `REDIS_URL` | Redis 连接 | `redis://:pwd@host:6379/0` |
|
||||
| `DIFY_API_BASE` | Dify 地址 | `https://api.dify.ai/v1` |
|
||||
| `DIFY_API_KEY` | Dify 密钥 | `sk-...` |
|
||||
| `HR_WORKFLOW_IFRAME_URL` | HR 页面链接 | `https://...` |
|
||||
| `HR_WORKFLOW_API_BASE` | HR API 地址 | `https://...` |
|
||||
| `HR_WORKFLOW_API_KEY` | HR API 密钥 | `<待补>` |
|
||||
| `INTEGRATION_API_BASE` | 集成 API 地址 | `https://...` |
|
||||
| `INTEGRATION_API_KEY` | 集成 API 密钥 | `<待补>` |
|
||||
| `WECOM_*` | 企业微信配置 | 见第 6.4 节 |
|
||||
|
||||
## 8. Codex 配置方案
|
||||
|
||||
### 8.1 使用目标
|
||||
|
||||
1. 新人快速上手仓库(读代码、跑命令、生成文档)
|
||||
2. 减少重复劳动(脚本执行、排障检查、变更说明)
|
||||
3. 统一输出格式(PR 说明、测试记录、交接文档)
|
||||
|
||||
### 8.2 推荐使用方式
|
||||
|
||||
1. Codex Desktop(推荐)
|
||||
- 直接打开 `hxops` 根目录
|
||||
- 在同一工作区执行命令、改代码、更新文档
|
||||
2. Codex CLI(可选)
|
||||
- 适合远程 SSH 或纯终端场景
|
||||
|
||||
### 8.3 项目级约定(建议)
|
||||
|
||||
1. 工作目录固定:`hxops/`
|
||||
2. 常用命令:
|
||||
- 前端:`cd frontend && npm install && npm run dev`
|
||||
- 后端:`cd backend && pip install -r requirements.txt && python run.py`
|
||||
- 容器:`docker compose up -d --build`
|
||||
3. 文档统一输出到 `docs/`
|
||||
4. 生产敏感信息(密钥/密码)禁止写入仓库
|
||||
5. 未知信息统一写 `<待补>`
|
||||
|
||||
## 9. 新人首日验收清单
|
||||
|
||||
1. 成功拉取并安装依赖
|
||||
2. 本地能启动前后端
|
||||
3. 能完成管理员登录
|
||||
4. 能打通至少 1 条业务链路
|
||||
5. 能使用 Codex 生成一份巡检或排查文档
|
||||
|
||||
## 10. 待补充信息区
|
||||
|
||||
- 服务器正式访问域名:`ai.well-trust.com:8881`
|
||||
- Dev/UAT/Prod 实际入口地址:`<待补>`
|
||||
- 数据库与 Redis 实际地址:`postgresql://postgres:difyai123456@localhost:5432/hxops_db`
|
||||
- 企业微信应用 `CorpID/AgentID`:
|
||||
- 新人账号申请与审批流程:`OA账号联系李振申`
|
||||
- 值班群与故障升级联系人:
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
.npm-cache
|
||||
.git
|
||||
.vscode
|
||||
+10
-7
@@ -1,12 +1,15 @@
|
||||
FROM node:22-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
|
||||
# 复制自定义 Nginx 配置
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
# 复制构建好的静态资源
|
||||
# 注意:在本地先执行 npm run build,然后将 dist 目录提交或在部署脚本中生成
|
||||
COPY dist /usr/share/nginx/html
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -0,0 +1 @@
|
||||
46MjWA55y3PBRLid
|
||||
Vendored
+5
-4
@@ -7,13 +7,14 @@
|
||||
<meta name="theme-color" content="#0284c7" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="hxai" />
|
||||
<meta name="apple-mobile-web-app-title" content="AI工作台" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>hxai</title>
|
||||
<script type="module" crossorigin src="/assets/index-CevSaenJ.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CqpZrvvZ.css">
|
||||
<title>AI工作台</title>
|
||||
<script type="module" crossorigin src="/assets/index-DNiQ9nKy.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DDtKBb2t.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+2
-2
@@ -7,9 +7,9 @@
|
||||
<meta name="theme-color" content="#0284c7" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="hxai" />
|
||||
<meta name="apple-mobile-web-app-title" content="AI工作台" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>hxai</title>
|
||||
<title>AI工作台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Generated
+20
-20
@@ -481,23 +481,6 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.0.0-rc.5",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.5.tgz",
|
||||
"integrity": "sha512-VQ8F9ld5gw29epjnVGdrx8ugiLTe8BMqmhDYy7nGbdeDo4HAt4bgdZvLbViEhg7DZyHLpiEUlO5/jPSUrIuxRQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/pluginutils": {
|
||||
"version": "1.0.0-rc.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz",
|
||||
@@ -611,7 +594,7 @@
|
||||
},
|
||||
"node_modules/@vue-office/docx": {
|
||||
"version": "1.6.3",
|
||||
"resolved": "https://registry.npmjs.org/@vue-office/docx/-/docx-1.6.3.tgz",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@vue-office/docx/-/docx-1.6.3.tgz",
|
||||
"integrity": "sha512-Cs+3CAaRBOWOiW4XAhTwwxJ0dy8cPIf6DqfNvYcD3YACiLwO4kuawLF2IAXxyijhbuOeoFsfvoVbOc16A/4bZA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
@@ -628,7 +611,7 @@
|
||||
},
|
||||
"node_modules/@vue-office/excel": {
|
||||
"version": "1.7.14",
|
||||
"resolved": "https://registry.npmjs.org/@vue-office/excel/-/excel-1.7.14.tgz",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@vue-office/excel/-/excel-1.7.14.tgz",
|
||||
"integrity": "sha512-pVUgt+emDQUnW7q22CfnQ+jl43mM/7IFwYzOg7lwOwPEbiVB4K4qEQf+y/bc4xGXz75w1/e3Kz3G6wAafmFBFg==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
@@ -645,7 +628,7 @@
|
||||
},
|
||||
"node_modules/@vue-office/pdf": {
|
||||
"version": "1.6.5",
|
||||
"resolved": "https://registry.npmjs.org/@vue-office/pdf/-/pdf-1.6.5.tgz",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@vue-office/pdf/-/pdf-1.6.5.tgz",
|
||||
"integrity": "sha512-3BePzeA5wji2JoZGJhdlc3XEXs6gMcSnBXrBXlGGfhZHjNijxcHa9V5Ibm8dDKoEwPPsfg+kf4TGP9/2GBR8jQ==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
@@ -2350,6 +2333,23 @@
|
||||
"@rolldown/binding-win32-x64-msvc": "1.0.0-rc.5"
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown/node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.0.0-rc.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.5.tgz",
|
||||
"integrity": "sha512-VQ8F9ld5gw29epjnVGdrx8ugiLTe8BMqmhDYy7nGbdeDo4HAt4bgdZvLbViEhg7DZyHLpiEUlO5/jPSUrIuxRQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown/node_modules/@rolldown/pluginutils": {
|
||||
"version": "1.0.0-rc.5",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.5.tgz",
|
||||
|
||||
@@ -3,9 +3,18 @@
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { watch, onMounted } from 'vue';
|
||||
import { useTheme } from './composables/useTheme';
|
||||
import LevelMessageDialog from './components/LevelMessageDialog.vue';
|
||||
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
|
||||
|
||||
const { locale } = useI18n();
|
||||
const { themePreference, initTheme, setThemePreference } = useTheme();
|
||||
const {
|
||||
messageDialogVisible,
|
||||
messageDialogLevel,
|
||||
messageDialogTitle,
|
||||
messageDialogContent,
|
||||
closeMessageDialog,
|
||||
} = useGlobalMessageDialog();
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const candidates = [
|
||||
@@ -96,4 +105,11 @@ onMounted(async () => {
|
||||
|
||||
<template>
|
||||
<router-view />
|
||||
<LevelMessageDialog
|
||||
v-model="messageDialogVisible"
|
||||
:level="messageDialogLevel"
|
||||
:title="messageDialogTitle"
|
||||
:message="messageDialogContent"
|
||||
@close="closeMessageDialog"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,192 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
interface Props {
|
||||
// 由父组件控制显隐,使用 v-model 统一管理弹框状态。
|
||||
modelValue: boolean;
|
||||
// title/message 支持外部按场景透传,不传时走 i18n 默认值。
|
||||
title?: string;
|
||||
message?: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
confirmLoading?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
title: '',
|
||||
message: '',
|
||||
confirmText: '',
|
||||
cancelText: '',
|
||||
confirmLoading: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'confirm'): void;
|
||||
(e: 'cancel'): void;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const resolvedTitle = computed(() => props.title || t('common.deleteDialog.defaultTitle'));
|
||||
const resolvedMessage = computed(() => props.message || t('common.deleteDialog.defaultMessage'));
|
||||
const resolvedCancelText = computed(() => props.cancelText || t('common.deleteDialog.cancel'));
|
||||
const resolvedConfirmText = computed(() => props.confirmText || t('common.deleteDialog.confirm'));
|
||||
|
||||
const closeDialog = () => {
|
||||
emit('update:modelValue', false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
// 先抛出 cancel 事件,方便父组件做状态回滚,再关闭弹框。
|
||||
emit('cancel');
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
emit('confirm');
|
||||
};
|
||||
|
||||
const handleEscKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && props.modelValue) {
|
||||
handleCancel();
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(visible) => {
|
||||
// 关键点:弹框打开时监听 ESC,关闭后及时解绑,避免全局事件泄漏。
|
||||
if (visible) {
|
||||
document.addEventListener('keydown', handleEscKey);
|
||||
return;
|
||||
}
|
||||
document.removeEventListener('keydown', handleEscKey);
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', handleEscKey);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition name="delete-dialog-fade">
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="fixed inset-0 z-[100] bg-black/45 flex items-center justify-center p-4"
|
||||
@click.self="handleCancel"
|
||||
>
|
||||
<div class="delete-dialog-container w-full max-w-[416px] rounded-lg bg-white shadow-[0_6px_16px_0_rgba(0,0,0,0.08),0_3px_6px_-4px_rgba(0,0,0,0.12),0_9px_28px_8px_rgba(0,0,0,0.05)] px-6 pt-7 pb-5">
|
||||
<div class="flex items-start gap-3">
|
||||
<span class="delete-dialog-icon" aria-hidden="true">!</span>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-[16px] leading-6 font-semibold text-[rgba(0,0,0,0.88)]">
|
||||
{{ resolvedTitle }}
|
||||
</h3>
|
||||
<p class="mt-3 text-[14px] leading-[22px] text-[rgba(0,0,0,0.65)] whitespace-pre-line">
|
||||
{{ resolvedMessage }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex justify-end gap-2">
|
||||
<button type="button" class="delete-dialog-btn cancel" @click="handleCancel">
|
||||
{{ resolvedCancelText }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="delete-dialog-btn confirm"
|
||||
:disabled="confirmLoading"
|
||||
@click="handleConfirm"
|
||||
>
|
||||
{{ resolvedConfirmText }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.delete-dialog-icon {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 9999px;
|
||||
background: #faad14;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
font-weight: 600;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.delete-dialog-btn {
|
||||
min-width: 66px;
|
||||
height: 32px;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
font-weight: 400;
|
||||
padding: 4px 15px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.delete-dialog-btn.cancel {
|
||||
color: rgba(0, 0, 0, 0.88);
|
||||
background: #fff;
|
||||
border: 1px solid #d9d9d9;
|
||||
}
|
||||
|
||||
.delete-dialog-btn.cancel:hover {
|
||||
border-color: #4096ff;
|
||||
color: #4096ff;
|
||||
}
|
||||
|
||||
.delete-dialog-btn.confirm {
|
||||
color: #fff;
|
||||
background: #1677ff;
|
||||
border: 1px solid #1677ff;
|
||||
}
|
||||
|
||||
.delete-dialog-btn.confirm:hover {
|
||||
background: #4096ff;
|
||||
border-color: #4096ff;
|
||||
}
|
||||
|
||||
.delete-dialog-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.delete-dialog-fade-enter-active,
|
||||
.delete-dialog-fade-leave-active {
|
||||
transition: opacity 0.18s ease;
|
||||
}
|
||||
|
||||
.delete-dialog-fade-enter-from,
|
||||
.delete-dialog-fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.delete-dialog-container {
|
||||
max-width: 94vw;
|
||||
padding: 20px 16px 16px;
|
||||
}
|
||||
|
||||
.delete-dialog-icon {
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.delete-dialog-btn {
|
||||
min-width: 62px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -57,8 +57,10 @@ const officeObjectUrl = ref<string>('');
|
||||
*/
|
||||
const getExt = (raw: string) => {
|
||||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||||
const i = clean.lastIndexOf('.');
|
||||
return i >= 0 ? clean.slice(i + 1) : '';
|
||||
const parts = clean.split('/');
|
||||
const lastPart = parts[parts.length - 1];
|
||||
const i = lastPart.lastIndexOf('.');
|
||||
return i >= 0 ? lastPart.slice(i + 1) : '';
|
||||
};
|
||||
|
||||
const ext = computed(() => {
|
||||
@@ -71,8 +73,8 @@ const ext = computed(() => {
|
||||
const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => {
|
||||
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
|
||||
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
||||
if (['xlsx'].includes(ext.value)) return 'office';
|
||||
if (['docx'].includes(ext.value)) return 'office';
|
||||
if (['xlsx', 'xls'].includes(ext.value)) return 'office';
|
||||
if (['docx', 'doc', 'pdf'].includes(ext.value)) return 'iframe';
|
||||
return 'iframe';
|
||||
});
|
||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
|
||||
@@ -148,6 +150,46 @@ const iframeSrc = computed(() => {
|
||||
|
||||
const close = () => emit('update:modelValue', false);
|
||||
|
||||
const isDownloading = ref(false);
|
||||
|
||||
const downloadFile = async () => {
|
||||
if (!props.file?.url || !props.agentId) return;
|
||||
isDownloading.value = true;
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
download: '1'
|
||||
});
|
||||
|
||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = props.file.name || 'download';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (err: any) {
|
||||
console.error('Download failed:', err);
|
||||
alert('下载失败: ' + (err.message || '未知错误'));
|
||||
} finally {
|
||||
isDownloading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const clearOfficeObjectUrl = () => {
|
||||
if (officeObjectUrl.value) {
|
||||
URL.revokeObjectURL(officeObjectUrl.value);
|
||||
@@ -179,8 +221,8 @@ const loadOfficeContent = async () => {
|
||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||
officeSrc.value = officeObjectUrl.value;
|
||||
|
||||
if (ext.value === 'docx') officeKind.value = 'docx';
|
||||
else if (ext.value === 'xlsx') officeKind.value = 'excel';
|
||||
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
|
||||
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
|
||||
else officeKind.value = null;
|
||||
};
|
||||
|
||||
@@ -270,6 +312,7 @@ const loadContent = async () => {
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
limit: '100',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
|
||||
@@ -300,6 +343,7 @@ const loadContent = async () => {
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
@@ -345,13 +389,22 @@ watch(
|
||||
<template>
|
||||
<div v-if="modelValue && file" class="fixed inset-0 z-[80] flex items-center justify-center bg-black/50 dark:bg-slate-950/70 backdrop-blur-sm p-4">
|
||||
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-xl w-full max-w-5xl h-[85vh] flex flex-col overflow-hidden border border-slate-200 dark:border-slate-700">
|
||||
<div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between gap-4">
|
||||
<div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm text-slate-500 dark:text-slate-400 uppercase tracking-wide">文件预览</div>
|
||||
<div class="font-semibold text-slate-900 dark:text-slate-100 truncate">{{ file.name }}</div>
|
||||
<a :href="file.url" target="_blank" class="text-xs text-brand-600 hover:text-brand-700 break-all">{{ file.url }}</a>
|
||||
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">文件预览</div>
|
||||
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
||||
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
{{ isDownloading ? '下载中...' : '下载文件' }}
|
||||
</button>
|
||||
</div>
|
||||
<button @click="close" class="px-3 py-1.5 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
|
||||
<button type="button" @click="close" class="shrink-0 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 bg-white/80 dark:bg-slate-900/80 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-auto p-4 bg-slate-50 dark:bg-slate-950">
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { MessageSquareText, X } from 'lucide-vue-next';
|
||||
|
||||
interface Props {
|
||||
modelValue: boolean;
|
||||
authHeaders?: Record<string, string>;
|
||||
sourcePage?: string;
|
||||
chatLogId?: number | null;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
authHeaders: () => ({}),
|
||||
sourcePage: 'unknown',
|
||||
chatLogId: null,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'submitted'): void;
|
||||
}>();
|
||||
|
||||
const typeOptions = ['功能建议', '问题反馈', '体验优化'];
|
||||
const moduleOptions = ['知识库', '通用', '工作流', '账号权限'];
|
||||
|
||||
const selectedType = ref<string>('功能建议');
|
||||
const selectedModule = ref<string>('知识库');
|
||||
const content = ref('');
|
||||
const submitting = ref(false);
|
||||
const error = ref('');
|
||||
|
||||
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value);
|
||||
|
||||
const closeDialog = () => {
|
||||
emit('update:modelValue', false);
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
selectedType.value = '功能建议';
|
||||
selectedModule.value = '知识库';
|
||||
content.value = '';
|
||||
error.value = '';
|
||||
submitting.value = false;
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(visible) => {
|
||||
if (visible) {
|
||||
resetForm();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const submitFeedback = async () => {
|
||||
if (!canSubmit.value) {
|
||||
error.value = '请填写反馈内容';
|
||||
return;
|
||||
}
|
||||
|
||||
submitting.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const payload: Record<string, unknown> = {
|
||||
feedback_type: selectedType.value,
|
||||
feedback_module: selectedModule.value,
|
||||
content: content.value.trim(),
|
||||
source_page: props.sourcePage,
|
||||
};
|
||||
if (props.chatLogId !== null && props.chatLogId !== undefined) {
|
||||
payload.chat_log_id = props.chatLogId;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/user/feedback', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...props.authHeaders,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
error.value = data?.error || '提交失败,请稍后重试';
|
||||
return;
|
||||
}
|
||||
|
||||
emit('submitted');
|
||||
closeDialog();
|
||||
} catch {
|
||||
error.value = '提交失败,请稍后重试';
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="fixed inset-0 z-[80] flex items-start justify-center overflow-y-auto bg-black/40 p-3 backdrop-blur-sm sm:items-center sm:p-4"
|
||||
>
|
||||
<div class="flex max-h-[92vh] w-full max-w-2xl flex-col rounded-2xl bg-white shadow-2xl">
|
||||
<div class="flex items-center justify-between border-b border-gray-100 px-5 pb-4 pt-5 sm:px-8 sm:pb-4 sm:pt-7">
|
||||
<h3 class="text-2xl font-bold text-gray-900">意见反馈</h3>
|
||||
<button
|
||||
@click="closeDialog"
|
||||
class="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-5 overflow-y-auto px-5 py-5 sm:px-8">
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-sm font-semibold text-gray-600">反馈类型</label>
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<button
|
||||
v-for="item in typeOptions"
|
||||
:key="item"
|
||||
@click="selectedType = item"
|
||||
class="rounded-xl border px-4 py-2.5 text-base font-medium transition-colors"
|
||||
:class="
|
||||
selectedType === item
|
||||
? 'border-blue-500 bg-blue-50 text-blue-700'
|
||||
: 'border-gray-200 bg-gray-50 text-gray-700 hover:bg-gray-100'
|
||||
"
|
||||
>
|
||||
{{ item }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-sm font-semibold text-gray-600">反馈模块</label>
|
||||
<select
|
||||
v-model="selectedModule"
|
||||
class="w-full rounded-xl border-gray-200 bg-gray-50 px-4 py-3 text-base shadow-sm outline-none transition-all focus:border-blue-500 focus:bg-white focus:ring-2 focus:ring-blue-500/20"
|
||||
>
|
||||
<option v-for="item in moduleOptions" :key="item" :value="item">{{ item }}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<label class="block text-sm font-semibold text-gray-600">反馈内容<span class="ml-0.5 text-red-500">*</span></label>
|
||||
<textarea
|
||||
v-model="content"
|
||||
rows="5"
|
||||
maxlength="2000"
|
||||
class="w-full resize-none rounded-xl border-gray-200 bg-gray-50 px-4 py-3 text-base shadow-sm outline-none transition-all focus:border-blue-500 focus:bg-white focus:ring-2 focus:ring-blue-500/20"
|
||||
placeholder="请描述你的问题或建议,帮助我们持续优化。"
|
||||
/>
|
||||
<div class="mt-2 flex items-center justify-between">
|
||||
<div v-if="error" class="text-base text-red-600">{{ error }}</div>
|
||||
<div v-else class="text-base text-gray-400"> </div>
|
||||
<div class="text-base text-gray-400">{{ content.length }}/2000</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-3 rounded-b-2xl border-t border-gray-100 bg-white px-5 py-4 sm:px-8">
|
||||
<button
|
||||
@click="closeDialog"
|
||||
class="rounded-xl px-5 py-2.5 text-base font-medium text-gray-600 transition-colors hover:bg-gray-100"
|
||||
:disabled="submitting"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
@click="submitFeedback"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl bg-blue-600 px-5 py-2.5 text-base font-medium text-white shadow-md shadow-blue-200 transition-all hover:bg-blue-700 active:scale-95 disabled:cursor-not-allowed disabled:opacity-70"
|
||||
:disabled="!canSubmit"
|
||||
>
|
||||
<MessageSquareText class="h-5 w-5" />
|
||||
{{ submitting ? '提交中' : '提交' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -18,7 +18,7 @@ const count = ref(0)
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Check out
|
||||
Check out
|
||||
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
|
||||
>create-vue</a
|
||||
>, the official Vue + Vite starter
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, watch } from 'vue';
|
||||
import { Check, Info, AlertTriangle, XCircle, X } from 'lucide-vue-next';
|
||||
|
||||
type MessageLevel = 'success' | 'info' | 'warning' | 'error';
|
||||
|
||||
interface Props {
|
||||
// 父组件通过 v-model 控制弹框显隐。
|
||||
modelValue: boolean;
|
||||
// 消息级别决定配色和图标。
|
||||
level?: MessageLevel;
|
||||
title?: string;
|
||||
message?: string;
|
||||
closeOnMask?: boolean;
|
||||
closeOnEsc?: boolean;
|
||||
// 自动关闭时长(毫秒):<= 0 表示不自动关闭。
|
||||
autoCloseMs?: number;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
level: 'info',
|
||||
title: '',
|
||||
message: '',
|
||||
closeOnMask: true,
|
||||
closeOnEsc: true,
|
||||
autoCloseMs: 3000,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'close'): void;
|
||||
}>();
|
||||
|
||||
const STYLE_MAP: Record<MessageLevel, { panel: string; iconWrap: string; icon: string }> = {
|
||||
success: {
|
||||
panel: 'bg-[#eef8e8] border-[#b7e2a7]',
|
||||
iconWrap: 'border-[#52c41a]',
|
||||
icon: 'text-[#52c41a]',
|
||||
},
|
||||
info: {
|
||||
panel: 'bg-[#eaf4ff] border-[#9fcbff]',
|
||||
iconWrap: 'border-[#1677ff]',
|
||||
icon: 'text-[#1677ff]',
|
||||
},
|
||||
warning: {
|
||||
panel: 'bg-[#fff8e8] border-[#ffd88a]',
|
||||
iconWrap: 'border-[#faad14]',
|
||||
icon: 'text-[#faad14]',
|
||||
},
|
||||
error: {
|
||||
panel: 'bg-[#fff1f0] border-[#ffb3b0]',
|
||||
iconWrap: 'border-[#ff4d4f]',
|
||||
icon: 'text-[#ff4d4f]',
|
||||
},
|
||||
};
|
||||
|
||||
const ICON_MAP: Record<MessageLevel, any> = {
|
||||
success: Check,
|
||||
info: Info,
|
||||
warning: AlertTriangle,
|
||||
error: XCircle,
|
||||
};
|
||||
|
||||
const DEFAULT_TITLE_MAP: Record<MessageLevel, string> = {
|
||||
success: 'Success',
|
||||
info: 'Info',
|
||||
warning: 'Warning',
|
||||
error: 'Error',
|
||||
};
|
||||
|
||||
const resolvedStyle = computed(() => STYLE_MAP[props.level]);
|
||||
const resolvedIcon = computed(() => ICON_MAP[props.level]);
|
||||
const resolvedTitle = computed(() => props.title || DEFAULT_TITLE_MAP[props.level]);
|
||||
const resolvedMessage = computed(() => props.message || '');
|
||||
let autoCloseTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const clearAutoCloseTimer = () => {
|
||||
if (!autoCloseTimer) return;
|
||||
clearTimeout(autoCloseTimer);
|
||||
autoCloseTimer = null;
|
||||
};
|
||||
|
||||
const closeDialog = () => {
|
||||
clearAutoCloseTimer();
|
||||
emit('update:modelValue', false);
|
||||
emit('close');
|
||||
};
|
||||
|
||||
const handleMaskClose = () => {
|
||||
if (!props.closeOnMask) return;
|
||||
closeDialog();
|
||||
};
|
||||
|
||||
const handleEscKey = (event: KeyboardEvent) => {
|
||||
if (!props.closeOnEsc) return;
|
||||
if (event.key === 'Escape' && props.modelValue) {
|
||||
closeDialog();
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.modelValue, props.level, props.title, props.message, props.autoCloseMs],
|
||||
([visible]) => {
|
||||
clearAutoCloseTimer();
|
||||
|
||||
if (!visible) {
|
||||
document.removeEventListener('keydown', handleEscKey);
|
||||
return;
|
||||
}
|
||||
document.addEventListener('keydown', handleEscKey);
|
||||
|
||||
// 关键点:弹框可见时只要内容变化,也会重新计时自动关闭。
|
||||
if (props.autoCloseMs > 0) {
|
||||
autoCloseTimer = setTimeout(() => {
|
||||
closeDialog();
|
||||
}, props.autoCloseMs);
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearAutoCloseTimer();
|
||||
document.removeEventListener('keydown', handleEscKey);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition name="level-dialog-fade">
|
||||
<div
|
||||
v-if="modelValue"
|
||||
class="fixed inset-0 z-[110] bg-black/40 flex items-center justify-center p-4"
|
||||
@click.self="handleMaskClose"
|
||||
>
|
||||
<div
|
||||
class="level-dialog-panel w-full max-w-[430px] rounded-2xl border shadow-[0_14px_28px_rgba(0,0,0,0.14)] px-9 py-8 relative"
|
||||
:class="resolvedStyle.panel"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute top-4 right-4 w-8 h-8 inline-flex items-center justify-center rounded-full text-slate-500 hover:text-slate-700 hover:bg-black/5 transition-colors"
|
||||
@click="closeDialog"
|
||||
aria-label="close dialog"
|
||||
>
|
||||
<X class="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div class="flex items-start gap-4 pr-8 min-h-0">
|
||||
<span
|
||||
class="w-8 h-8 rounded-full border-2 inline-flex items-center justify-center shrink-0 mt-0.5"
|
||||
:class="resolvedStyle.iconWrap"
|
||||
>
|
||||
<component :is="resolvedIcon" class="w-4 h-4" :class="resolvedStyle.icon" />
|
||||
</span>
|
||||
|
||||
<div class="min-w-0 w-full">
|
||||
<h3 class="text-[16px] leading-6 font-semibold text-slate-800">
|
||||
{{ resolvedTitle }}
|
||||
</h3>
|
||||
<p class="level-dialog-message mt-3 text-[14px] leading-8 text-slate-700 whitespace-pre-line break-words">
|
||||
{{ resolvedMessage }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.level-dialog-fade-enter-active,
|
||||
.level-dialog-fade-leave-active {
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.level-dialog-fade-enter-from,
|
||||
.level-dialog-fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.level-dialog-panel {
|
||||
max-height: min(80vh, 640px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.level-dialog-message {
|
||||
max-height: min(48vh, 320px);
|
||||
overflow: auto;
|
||||
padding-right: 0.25rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.level-dialog-panel {
|
||||
max-width: 94vw;
|
||||
max-height: 82vh;
|
||||
padding: 20px 18px;
|
||||
}
|
||||
|
||||
.level-dialog-panel p {
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.level-dialog-message {
|
||||
max-height: 52vh;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -15,7 +15,7 @@ const isDarkTheme = computed(() => appliedTheme.value === 'dark');
|
||||
const buttonClass = computed(() =>
|
||||
props.floating
|
||||
? 'fixed bottom-5 right-5 z-[70] h-11 w-11 rounded-full bg-white/90 dark:bg-slate-900/90 backdrop-blur-md shadow-lg border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:shadow-xl flex items-center justify-center transition-all'
|
||||
: 'h-9 w-9 rounded-full bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shadow-sm border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:shadow-md flex items-center justify-center transition-all'
|
||||
: 'h-8 w-8 md:h-9 md:w-9 rounded-full bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shadow-sm border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:shadow-md flex items-center justify-center transition-all'
|
||||
);
|
||||
</script>
|
||||
|
||||
@@ -26,7 +26,7 @@ const buttonClass = computed(() =>
|
||||
:title="isDarkTheme ? (t('theme.switchToLight') || 'Switch to light mode') : (t('theme.switchToDark') || 'Switch to dark mode')"
|
||||
:aria-label="isDarkTheme ? (t('theme.switchToLight') || 'Switch to light mode') : (t('theme.switchToDark') || 'Switch to dark mode')"
|
||||
>
|
||||
<Sun v-if="isDarkTheme" class="w-5 h-5" />
|
||||
<Moon v-else class="w-5 h-5" />
|
||||
<Sun v-if="isDarkTheme" class="w-4 h-4 md:w-5 md:h-5" />
|
||||
<Moon v-else class="w-4 h-4 md:w-5 md:h-5" />
|
||||
</button>
|
||||
</template>
|
||||
@@ -8,6 +8,7 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
interface RetrieverResource {
|
||||
// 知识库/检索来源的基础字段,具体键可能因后端返回而扩展
|
||||
dataset_name?: string;
|
||||
document_name?: string;
|
||||
segment_id?: string;
|
||||
@@ -17,12 +18,15 @@ interface RetrieverResource {
|
||||
}
|
||||
|
||||
interface ChatMessage {
|
||||
// 对话消息结构:用户/助手文本 + 可选的来源与归因信息
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
}
|
||||
|
||||
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
|
||||
const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||
if (!resources) return [];
|
||||
if (Array.isArray(resources)) return resources;
|
||||
@@ -30,11 +34,13 @@ const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||
return [];
|
||||
};
|
||||
|
||||
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重
|
||||
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
const list = normalizeResources(resources);
|
||||
if (list.length === 0) return;
|
||||
if (!msg.retriever_resources) msg.retriever_resources = [];
|
||||
for (const item of list) {
|
||||
// 使用稳定键进行去重,避免同一条来源在多事件中重复展示
|
||||
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
|
||||
const exists = msg.retriever_resources.some(
|
||||
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
|
||||
@@ -45,10 +51,12 @@ const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 归一化并合并归因内容(支持 string/array/object),按文本去重
|
||||
const addAttributionParts = (msg: ChatMessage, value: any) => {
|
||||
if (!value) return;
|
||||
if (!msg.attribution_parts) msg.attribution_parts = [];
|
||||
|
||||
// 只收集非空文本,且保证唯一
|
||||
const pushUnique = (text: string) => {
|
||||
const v = text.trim();
|
||||
if (!v) return;
|
||||
@@ -78,6 +86,7 @@ const addAttributionParts = (msg: ChatMessage, value: any) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 从事件顶层与 metadata 中提取来源/归因信息并写回当前消息
|
||||
const applyEventMetadata = (msg: ChatMessage, data: any) => {
|
||||
const metadata = data?.metadata || {};
|
||||
addRetrieverResources(msg, data?.retriever_resources);
|
||||
@@ -141,7 +150,7 @@ export function useChat() {
|
||||
* 用途:发送消息并处理 SSE 流式响应
|
||||
* 核心逻辑:
|
||||
* 1. 乐观更新 UI (立即显示用户消息)
|
||||
* 2. 创建空的 AI 消息占位
|
||||
* 2. Create assistant message lazily only after receiving real answer chunks.
|
||||
* 3. 发起 Fetch POST 请求
|
||||
* 4. 获取 Reader 流式读取
|
||||
* 5. 逐块解码并追加到当前 AI 消息中
|
||||
@@ -157,13 +166,19 @@ export function useChat() {
|
||||
});
|
||||
// 1. 乐观 UI 更新:立即将用户消息推入列表
|
||||
messages.value.push({ role: 'user', content: query });
|
||||
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
|
||||
const botMsgIndex = messages.value.push({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
retriever_resources: [],
|
||||
attribution_parts: []
|
||||
}) - 1;
|
||||
// Lazily create assistant message only when answer/error arrives.
|
||||
let botMsgIndex: number | null = null;
|
||||
const ensureBotMessage = () => {
|
||||
if (botMsgIndex === null) {
|
||||
botMsgIndex = messages.value.push({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
retriever_resources: [],
|
||||
attribution_parts: []
|
||||
}) - 1;
|
||||
}
|
||||
return messages.value[botMsgIndex] || null;
|
||||
};
|
||||
|
||||
isThinking.value = true;
|
||||
|
||||
@@ -224,8 +239,6 @@ export function useChat() {
|
||||
|
||||
try {
|
||||
const data = JSON.parse(payload);
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (!botMsg) continue;
|
||||
console.debug('[chat][sse] event', {
|
||||
event: data?.event,
|
||||
answerLength: typeof data?.answer === 'string' ? data.answer.length : 0,
|
||||
@@ -233,8 +246,10 @@ export function useChat() {
|
||||
conversationId: data?.conversation_id || conversationId.value,
|
||||
});
|
||||
|
||||
if (data.event === 'message' || data.event === 'agent_message') {
|
||||
if (data.event === 'message') {
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += data.answer;
|
||||
console.debug('[chat][sse] append answer chunk', {
|
||||
event: data.event,
|
||||
@@ -242,13 +257,25 @@ export function useChat() {
|
||||
total: botMsg.content.length,
|
||||
});
|
||||
}
|
||||
applyEventMetadata(botMsg, data);
|
||||
} else if (data.event === 'message_end' || data.event === 'workflow_finished') {
|
||||
if (botMsgIndex !== null) {
|
||||
const currentBotMsg = messages.value[botMsgIndex];
|
||||
if (currentBotMsg) {
|
||||
applyEventMetadata(currentBotMsg, data);
|
||||
}
|
||||
}
|
||||
} else if (data.event === 'message_end') {
|
||||
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
|
||||
const currentBotMsg = messages.value[botMsgIndex];
|
||||
if (currentBotMsg) {
|
||||
currentBotMsg.chat_log_id = Number(data.chat_log_id);
|
||||
}
|
||||
}
|
||||
if (data.conversation_id) {
|
||||
conversationId.value = data.conversation_id;
|
||||
}
|
||||
// Some providers may put final answer on message_end/workflow events.
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += data.answer;
|
||||
console.debug('[chat][sse] append final answer', {
|
||||
event: data.event,
|
||||
@@ -256,8 +283,15 @@ export function useChat() {
|
||||
total: botMsg.content.length,
|
||||
});
|
||||
}
|
||||
applyEventMetadata(botMsg, data);
|
||||
if (botMsgIndex !== null) {
|
||||
const currentBotMsg = messages.value[botMsgIndex];
|
||||
if (currentBotMsg) {
|
||||
applyEventMetadata(currentBotMsg, data);
|
||||
}
|
||||
}
|
||||
} else if (data.event === 'error') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += `\n[Error: ${data.message}]`;
|
||||
console.error('[chat][sse] backend error event', data);
|
||||
}
|
||||
@@ -269,7 +303,7 @@ export function useChat() {
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error('[chat][send] failed', e);
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
const botMsg = ensureBotMessage();
|
||||
if (botMsg) {
|
||||
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { readonly, ref } from 'vue';
|
||||
|
||||
export type MessageLevel = 'success' | 'info' | 'warning' | 'error';
|
||||
|
||||
// 全局单例状态:整个应用共享一套消息弹框。
|
||||
const visible = ref(false);
|
||||
const level = ref<MessageLevel>('info');
|
||||
const title = ref('');
|
||||
const message = ref('');
|
||||
|
||||
const MAX_DIALOG_MESSAGE_LENGTH = 240;
|
||||
|
||||
const normalizeMessage = (raw: string) => {
|
||||
if (!raw) return '';
|
||||
return raw
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/<[^>]*>/g, '')
|
||||
.trim();
|
||||
};
|
||||
|
||||
const formatMessageForDialog = (level: MessageLevel, raw: string) => {
|
||||
const normalized = normalizeMessage(raw);
|
||||
if (!normalized) return '';
|
||||
|
||||
// Error messages often include long backend stack/driver details.
|
||||
if (level === 'error' && normalized.length > MAX_DIALOG_MESSAGE_LENGTH) {
|
||||
return `${normalized.slice(0, MAX_DIALOG_MESSAGE_LENGTH)}...`;
|
||||
}
|
||||
return normalized;
|
||||
};
|
||||
|
||||
export const useGlobalMessageDialog = () => {
|
||||
const showMessageDialog = (
|
||||
nextLevel: MessageLevel,
|
||||
nextMessage: string,
|
||||
nextTitle = ''
|
||||
) => {
|
||||
level.value = nextLevel;
|
||||
title.value = nextTitle;
|
||||
message.value = formatMessageForDialog(nextLevel, nextMessage);
|
||||
visible.value = true;
|
||||
};
|
||||
|
||||
const closeMessageDialog = () => {
|
||||
visible.value = false;
|
||||
title.value = '';
|
||||
message.value = '';
|
||||
};
|
||||
|
||||
return {
|
||||
messageDialogVisible: visible,
|
||||
messageDialogLevel: readonly(level),
|
||||
messageDialogTitle: readonly(title),
|
||||
messageDialogContent: readonly(message),
|
||||
showMessageDialog,
|
||||
closeMessageDialog,
|
||||
};
|
||||
};
|
||||
+17
-4
@@ -1,15 +1,28 @@
|
||||
export const config = {
|
||||
appTitle: 'hxai',
|
||||
export const config = {
|
||||
appTitle: 'AI工作台',
|
||||
auth: {
|
||||
wecom: {
|
||||
enabled: true,
|
||||
authorizeApi: '/api/user/wecom/authorize-url',
|
||||
loginApi: '/api/user/wecom/login',
|
||||
callbackPath: '/workspace'
|
||||
completeBindApi: '/api/user/wecom/complete-bind',
|
||||
callbackPath: '/workspace',
|
||||
deeplinkTraceApi: '/api/user/wecom/deeplink-opened',
|
||||
taskCompleteApi: '/api/user/wecom/task-complete'
|
||||
}
|
||||
},
|
||||
workspace: {
|
||||
enableFeedback: true,
|
||||
// true 显示评分区;false 隐藏评分区
|
||||
showChatRating: true,
|
||||
// 聊天窗口“源文件展示”开关配置
|
||||
sourceFiles: {
|
||||
// 是否显示源文件区域(包含上方文件按钮 + 下方“源文档”详情)
|
||||
showSourceFiles: true,
|
||||
// 是否显示 MD 源文件(文件名后缀为 .md/.markdown)
|
||||
showMdFiles: false,
|
||||
// 当 showMdFiles=true 时,MD 源文件是否默认展开“源文档”详情
|
||||
expandMdByDefault: false,
|
||||
},
|
||||
modules: {
|
||||
announcements: true,
|
||||
favorites: true,
|
||||
|
||||
+866
-27
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,7 @@ import i18n from './i18n'
|
||||
import { config } from './config'
|
||||
|
||||
// Set document title from config
|
||||
document.title = config.appTitle || 'hxai';
|
||||
document.title = config.appTitle || 'AI工作台';
|
||||
|
||||
createApp(App)
|
||||
.use(router)
|
||||
|
||||
@@ -48,7 +48,7 @@ const router = createRouter({
|
||||
});
|
||||
|
||||
router.afterEach((to) => {
|
||||
const baseTitle = config.appTitle || 'hxai';
|
||||
const baseTitle = config.appTitle || 'AI工作台';
|
||||
if (to.meta.title) {
|
||||
document.title = `${to.meta.title} - ${baseTitle}`;
|
||||
} else {
|
||||
|
||||
+32
-4
@@ -1,6 +1,4 @@
|
||||
|
||||
@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Space+Grotesk:wght@500;600;700&display=swap');
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -22,7 +20,7 @@
|
||||
}
|
||||
|
||||
html {
|
||||
font-family: 'Manrope', 'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif;
|
||||
font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI', 'Helvetica Neue', Arial, system-ui, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
background-color: var(--bg-page);
|
||||
@@ -48,7 +46,7 @@
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
font-family: 'Space Grotesk', 'Manrope', sans-serif;
|
||||
font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI Semibold', 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
|
||||
@apply tracking-tight font-semibold text-slate-900;
|
||||
}
|
||||
|
||||
@@ -103,6 +101,27 @@
|
||||
@apply bg-white rounded-2xl border border-slate-100 shadow-soft hover:shadow-lg transition-all duration-300;
|
||||
}
|
||||
|
||||
/* Mobile-first layout tokens for consistent spacing and density. */
|
||||
.page-shell-mobile {
|
||||
@apply px-3 md:px-8;
|
||||
}
|
||||
|
||||
.section-gap-mobile {
|
||||
@apply mb-3 md:mb-8;
|
||||
}
|
||||
|
||||
.card-mobile-compact {
|
||||
@apply p-3 sm:p-5;
|
||||
}
|
||||
|
||||
.icon-box-mobile {
|
||||
@apply w-8 h-8 sm:w-10 sm:h-10;
|
||||
}
|
||||
|
||||
.icon-glyph-mobile {
|
||||
@apply w-4 h-4 sm:w-6 sm:h-6;
|
||||
}
|
||||
|
||||
.badge {
|
||||
@apply px-2.5 py-0.5 rounded-full text-xs font-medium border;
|
||||
}
|
||||
@@ -133,6 +152,15 @@
|
||||
caret-color: #0891b2;
|
||||
}
|
||||
|
||||
.chat-composer-textarea:focus,
|
||||
.chat-composer-textarea:focus-visible {
|
||||
outline: none !important;
|
||||
box-shadow: none !important;
|
||||
border: 0 !important;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
|
||||
.chat-composer-textarea::selection {
|
||||
background-color: rgba(14, 165, 233, 0.2);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
export type WecomMatchField = 'employee_id' | 'mobile' | 'email';
|
||||
|
||||
export interface WecomNormalizedMatchRules {
|
||||
operator: 'AND' | 'OR';
|
||||
fields: WecomMatchField[];
|
||||
}
|
||||
|
||||
export interface WecomLoginErrorPayload {
|
||||
error?: string | null;
|
||||
error_code?: string | null;
|
||||
reason?: string | null;
|
||||
missing_field?: string | null;
|
||||
candidate_count?: number | null;
|
||||
match_rules?: unknown;
|
||||
}
|
||||
|
||||
export interface WecomLoginDialogContent {
|
||||
title: string;
|
||||
summary: string;
|
||||
details: string[];
|
||||
technical?: string;
|
||||
}
|
||||
|
||||
export interface WecomAuditRowLike {
|
||||
status?: string | null;
|
||||
reason?: string | null;
|
||||
error_code?: string | null;
|
||||
match_rules?: string | null;
|
||||
match_operator?: string | null;
|
||||
match_result?: string | null;
|
||||
}
|
||||
|
||||
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
const KNOWN_MATCH_FIELDS: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
|
||||
|
||||
function cleanText(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
|
||||
}
|
||||
|
||||
function normalizeMatchField(value: unknown): WecomMatchField | null {
|
||||
const normalized = cleanText(value).toLowerCase();
|
||||
return KNOWN_MATCH_FIELDS.includes(normalized as WecomMatchField)
|
||||
? (normalized as WecomMatchField)
|
||||
: null;
|
||||
}
|
||||
|
||||
function getFieldGuide(field: WecomMatchField | null, t: TranslateFn): string {
|
||||
if (field === 'mobile') return t('login.wecomFieldGuides.mobile');
|
||||
if (field === 'email') return t('login.wecomFieldGuides.email');
|
||||
if (field === 'employee_id') return t('login.wecomFieldGuides.employee_id');
|
||||
return t('login.wecomFieldGuides.default');
|
||||
}
|
||||
|
||||
function extractMissingField(reason: string): WecomMatchField | null {
|
||||
if (!reason.startsWith('missing_attr:')) return null;
|
||||
return normalizeMatchField(reason.split(':', 2)[1]);
|
||||
}
|
||||
|
||||
function formatRuleList(fields: WecomMatchField[], operator: 'AND' | 'OR', t: TranslateFn): string {
|
||||
if (fields.length === 0) return t('login.wecomFieldLabels.match_rules');
|
||||
const labels = fields.map((field) => formatWecomFieldLabel(field, t));
|
||||
if (labels.length === 1) return labels[0] || t('login.wecomFieldLabels.match_rules');
|
||||
const joiner = operator === 'OR' ? ` ${t('login.wecomRuleJoin.or')} ` : ` ${t('login.wecomRuleJoin.and')} `;
|
||||
return labels.join(joiner);
|
||||
}
|
||||
|
||||
function buildTechnicalInfo(errorCode: string, rawError: string): string | undefined {
|
||||
const parts: string[] = [];
|
||||
if (errorCode) parts.push(`code=${errorCode}`);
|
||||
if (rawError) parts.push(rawError);
|
||||
return parts.length ? parts.join(' | ') : undefined;
|
||||
}
|
||||
|
||||
export function normalizeWecomMatchRules(
|
||||
input: unknown,
|
||||
fallbackOperator: unknown = 'AND',
|
||||
): WecomNormalizedMatchRules {
|
||||
let fieldsSource: unknown[] = [];
|
||||
let operator: 'AND' | 'OR' = cleanText(fallbackOperator).toUpperCase() === 'OR' ? 'OR' : 'AND';
|
||||
|
||||
if (Array.isArray(input)) {
|
||||
fieldsSource = input;
|
||||
} else if (typeof input === 'string') {
|
||||
fieldsSource = input.split(',');
|
||||
} else if (input && typeof input === 'object') {
|
||||
const maybeRules = input as Record<string, unknown>;
|
||||
fieldsSource = Array.isArray(maybeRules.fields) ? maybeRules.fields : [];
|
||||
operator = cleanText(maybeRules.operator).toUpperCase() === 'OR' ? 'OR' : operator;
|
||||
}
|
||||
|
||||
const fields = fieldsSource
|
||||
.map((value) => normalizeMatchField(value))
|
||||
.filter((value): value is WecomMatchField => Boolean(value));
|
||||
|
||||
return { operator, fields };
|
||||
}
|
||||
|
||||
export function formatWecomFieldLabel(field: unknown, t: TranslateFn): string {
|
||||
const normalized = normalizeMatchField(field);
|
||||
if (normalized === 'employee_id') return t('login.wecomFieldLabels.employee_id');
|
||||
if (normalized === 'mobile') return t('login.wecomFieldLabels.mobile');
|
||||
if (normalized === 'email') return t('login.wecomFieldLabels.email');
|
||||
return t('login.wecomFieldLabels.match_rules');
|
||||
}
|
||||
|
||||
export function formatWecomRuleText(
|
||||
input: unknown,
|
||||
t: TranslateFn,
|
||||
fallbackOperator: unknown = 'AND',
|
||||
): string {
|
||||
const rules = normalizeWecomMatchRules(input, fallbackOperator);
|
||||
return formatRuleList(rules.fields, rules.operator, t);
|
||||
}
|
||||
|
||||
export function buildWecomLoginDialogContent(
|
||||
payload: WecomLoginErrorPayload,
|
||||
t: TranslateFn,
|
||||
): WecomLoginDialogContent {
|
||||
const rawError = cleanText(payload.error);
|
||||
const errorCode = cleanText(payload.error_code);
|
||||
const reason = cleanText(payload.reason);
|
||||
const rulesText = formatWecomRuleText(payload.match_rules, t);
|
||||
const technical = buildTechnicalInfo(errorCode, rawError);
|
||||
|
||||
if (errorCode === 'WECOM_MATCH_ATTR_MISSING') {
|
||||
const missingField = normalizeMatchField(payload.missing_field) || extractMissingField(reason);
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.matchAttrMissing'),
|
||||
summary: t('login.wecomDialogSummaries.matchAttrMissing', {
|
||||
field: formatWecomFieldLabel(missingField, t),
|
||||
}),
|
||||
details: [
|
||||
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
|
||||
getFieldGuide(missingField, t),
|
||||
t('login.wecomDialogDetails.bindFallback'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_MATCH_AMBIGUOUS') {
|
||||
const candidateCount = Number(payload.candidate_count || 0);
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.matchAmbiguous'),
|
||||
summary: candidateCount > 1
|
||||
? t('login.wecomDialogSummaries.matchAmbiguousWithCount', { count: candidateCount })
|
||||
: t('login.wecomDialogSummaries.matchAmbiguous'),
|
||||
details: [
|
||||
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
|
||||
t('login.wecomDialogDetails.ambiguousAction'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_REQUIRED') {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.bindRequired'),
|
||||
summary: t('login.wecomDialogSummaries.bindRequired'),
|
||||
details: [
|
||||
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
|
||||
t('login.wecomDialogDetails.bindRequiredAction'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.bindInputRequired'),
|
||||
summary: t('login.wecomDialogSummaries.bindInputRequired'),
|
||||
details: [
|
||||
t('login.wecomDialogDetails.bindInputRequiredAction'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_CONFLICT') {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.bindConflict'),
|
||||
summary: t('login.wecomDialogSummaries.bindConflict'),
|
||||
details: [
|
||||
rawError || t('login.wecomDialogDetails.bindConflictAction'),
|
||||
t('login.wecomDialogDetails.bindConflictAction'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.notInScope'),
|
||||
summary: t('login.wecomDialogSummaries.notInScope'),
|
||||
details: [
|
||||
rawError || t('login.wecomDialogDetails.notInScopeAction'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (rawError.includes('Invalid or expired WeCom state')) {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.stateExpired'),
|
||||
summary: t('login.wecomStateExpired'),
|
||||
details: [t('login.wecomDialogDetails.retryLogin')],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (rawError.includes('Account is disabled')) {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.accountDisabled'),
|
||||
summary: t('login.wecomAccountDisabled'),
|
||||
details: [t('login.wecomDialogDetails.contactAdmin')],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.bindRequired'),
|
||||
summary: t('login.wecomDialogSummaries.bindRequired'),
|
||||
details: [
|
||||
t('login.wecomDialogDetails.currentRules', { rules: rulesText }),
|
||||
t('login.wecomDialogDetails.bindRequiredAction'),
|
||||
],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: t('login.wecomDialogTitles.loginFailed'),
|
||||
summary: rawError || t('login.wecomLoginFailed'),
|
||||
details: [t('login.wecomDialogDetails.retryLogin')],
|
||||
technical,
|
||||
};
|
||||
}
|
||||
|
||||
function formatWecomMatchResult(result: string, t: TranslateFn): string {
|
||||
if (result === 'already_bound') return t('admin.wecom.auditResults.already_bound');
|
||||
if (result === 'matched_and_bound') return t('admin.wecom.auditResults.matched_and_bound');
|
||||
if (result === 'auto_created') return t('admin.wecom.auditResults.auto_created');
|
||||
if (result === 'input_verified_and_bound') return t('admin.wecom.auditResults.input_verified_and_bound');
|
||||
return result || '-';
|
||||
}
|
||||
|
||||
export function formatWecomAuditReason(row: WecomAuditRowLike, t: TranslateFn): string {
|
||||
const reason = cleanText(row.reason);
|
||||
const errorCode = cleanText(row.error_code);
|
||||
|
||||
if (cleanText(row.status) === 'success') {
|
||||
const result = cleanText(row.match_result);
|
||||
return result ? formatWecomMatchResult(result, t) : t('admin.wecom.auditMessages.loginSuccess');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_MATCH_ATTR_MISSING') {
|
||||
const field = extractMissingField(reason);
|
||||
return t('admin.wecom.auditMessages.matchAttrMissing', {
|
||||
field: formatWecomFieldLabel(field, t),
|
||||
});
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_MATCH_AMBIGUOUS') {
|
||||
return t('admin.wecom.auditMessages.matchAmbiguous');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_REQUIRED') {
|
||||
return t('admin.wecom.auditMessages.bindRequired');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_CONFLICT') {
|
||||
return t('admin.wecom.auditMessages.bindConflict');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
|
||||
return t('admin.wecom.auditMessages.bindInputRequired');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') {
|
||||
return t('admin.wecom.auditMessages.bindInputNotFound');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') {
|
||||
return t('admin.wecom.auditMessages.bindInputAmbiguous');
|
||||
}
|
||||
|
||||
if (errorCode === 'WECOM_NOT_IN_AGENT_SCOPE') {
|
||||
return t('admin.wecom.auditMessages.notInScope');
|
||||
}
|
||||
|
||||
if (reason === 'invalid_state') return t('admin.wecom.auditMessages.invalidState');
|
||||
if (reason === 'missing_code') return t('admin.wecom.auditMessages.missingCode');
|
||||
if (reason === 'account_disabled') return t('admin.wecom.auditMessages.accountDisabled');
|
||||
if (reason.startsWith('auth_failed:')) {
|
||||
return t('admin.wecom.auditMessages.authFailed', {
|
||||
detail: reason.split(':', 2)[1] || '-',
|
||||
});
|
||||
}
|
||||
if (reason.startsWith('user_fetch_failed:')) {
|
||||
return t('admin.wecom.auditMessages.userFetchFailed', {
|
||||
detail: reason.split(':', 2)[1] || '-',
|
||||
});
|
||||
}
|
||||
if (reason.startsWith('not_in_agent_scope:')) return t('admin.wecom.auditMessages.notInScope');
|
||||
if (reason.startsWith('exception:')) {
|
||||
return t('admin.wecom.auditMessages.exception', {
|
||||
detail: reason.split(':', 2)[1] || '-',
|
||||
});
|
||||
}
|
||||
|
||||
return reason || '-';
|
||||
}
|
||||
|
||||
export function buildWecomAuditMeta(row: WecomAuditRowLike, t: TranslateFn): string[] {
|
||||
const items: string[] = [];
|
||||
const rulesText = formatWecomRuleText(row.match_rules, t, row.match_operator);
|
||||
if (cleanText(row.match_rules)) {
|
||||
items.push(t('admin.wecom.auditMeta.rules', { rules: rulesText }));
|
||||
}
|
||||
if (cleanText(row.match_result)) {
|
||||
items.push(t('admin.wecom.auditMeta.result', {
|
||||
result: formatWecomMatchResult(cleanText(row.match_result), t),
|
||||
}));
|
||||
}
|
||||
if (cleanText(row.error_code)) {
|
||||
items.push(t('admin.wecom.auditMeta.errorCode', { code: cleanText(row.error_code) }));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
+992
-195
File diff suppressed because it is too large.
Load diff
+198
-74
@@ -13,21 +13,52 @@
|
||||
import { ref, onMounted, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useChat } from '../composables/useChat';
|
||||
import { Send, User, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, RotateCw, Check } from 'lucide-vue-next';
|
||||
import { Send, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, RotateCw, Check } from 'lucide-vue-next';
|
||||
import { marked } from 'marked';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { config } from '../config';
|
||||
import FilePreviewModal from '../components/FilePreviewModal.vue';
|
||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
|
||||
const stripReasoningPrelude = (text: string) => {
|
||||
if (!text) return '';
|
||||
let cleaned = text
|
||||
.replace(/<think[\s\S]*?<\/think>/gi, '')
|
||||
.replace(/<analysis[\s\S]*?<\/analysis>/gi, '')
|
||||
.trim();
|
||||
|
||||
const reasoningMarkers = [
|
||||
'让我分析',
|
||||
'根据应答生成规则',
|
||||
'分析知识库返回的内容',
|
||||
'我需要直接给出答案',
|
||||
'思考过程',
|
||||
'推理过程',
|
||||
];
|
||||
const hasReasoningMarker = reasoningMarkers.some((marker) => cleaned.includes(marker));
|
||||
if (!hasReasoningMarker) return cleaned;
|
||||
|
||||
const headingMatch = cleaned.match(/(^|\n)\s{0,3}#{1,6}\s+/);
|
||||
if (headingMatch && typeof headingMatch.index === 'number') {
|
||||
const start = headingMatch.index + (headingMatch[1] ? headingMatch[1].length : 0);
|
||||
cleaned = cleaned.slice(start).trim();
|
||||
}
|
||||
return cleaned;
|
||||
};
|
||||
|
||||
const renderMarkdown = (text: string) => {
|
||||
if (!text) return '';
|
||||
const displayText = stripReasoningPrelude(text);
|
||||
try {
|
||||
return marked.parse(text);
|
||||
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
|
||||
return marked.parse(displayText);
|
||||
} catch (e) {
|
||||
return text;
|
||||
return displayText;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -63,6 +94,16 @@ interface SourceFileLink {
|
||||
url: string;
|
||||
}
|
||||
|
||||
// 源文件展示配置(来自 config.ts)
|
||||
// const sourceFileConfig = {
|
||||
// // 是否显示整个“源文件”区域
|
||||
// showSourceFiles: config.workspace?.sourceFiles?.showSourceFiles !== false,
|
||||
// // 是否显示 MD 源文件(.md/.markdown)
|
||||
// showMdFiles: config.workspace?.sourceFiles?.showMdFiles !== false,
|
||||
// // MD 源文件是否默认展开“源文档”详情
|
||||
// expandMdByDefault: config.workspace?.sourceFiles?.expandMdByDefault === true,
|
||||
// };
|
||||
|
||||
const PREFERRED_SOURCE_EXTS = new Set([
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
|
||||
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
|
||||
@@ -106,7 +147,7 @@ const getUrlExt = (url: string) => {
|
||||
};
|
||||
|
||||
const isChunkLikeLink = (url: string) => {
|
||||
// Keep original Markdown files; only filter explicit chunk/segment-style links.
|
||||
// 保留原始 Markdown 文件链接;仅过滤明显的分片/切片类链接。
|
||||
return /segment|chunk|fragments?|split/i.test(url);
|
||||
};
|
||||
|
||||
@@ -116,12 +157,12 @@ const isPreferredSourceLink = (url: string) => {
|
||||
};
|
||||
|
||||
const isNoisySourceUrl = (url: string) => {
|
||||
// Raw signed download links are noisy in UI (e.g. download?version_id=...&token=...).
|
||||
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
|
||||
return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||||
};
|
||||
|
||||
const isNoisySourceName = (name: string) => {
|
||||
// Guard against names that are actually query strings instead of human-readable filenames.
|
||||
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
|
||||
const n = (name || '').trim().toLowerCase();
|
||||
return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||||
};
|
||||
@@ -129,12 +170,14 @@ const isNoisySourceName = (name: string) => {
|
||||
const looksLikeFileName = (name: string) => {
|
||||
const n = (name || '').trim();
|
||||
if (!n) return false;
|
||||
// Keep Chinese/English file labels such as 员工手册.doc
|
||||
// 保留中英文文件名,如 员工手册.doc
|
||||
return /\.[A-Za-z0-9]{2,8}$/.test(n);
|
||||
};
|
||||
|
||||
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
|
||||
|
||||
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
|
||||
|
||||
const extractUrlsFromText = (text: string) => {
|
||||
if (!text) return [];
|
||||
const urls: string[] = [];
|
||||
@@ -202,7 +245,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
...extractUrlsFromText(serialized),
|
||||
];
|
||||
|
||||
// Parse explicit file URL array if Dify provides it.
|
||||
// 若 Dify 返回了 files 数组,额外补充其显式文件链接。
|
||||
const files = Array.isArray(item?.files) ? item.files : [];
|
||||
for (const f of files) {
|
||||
const fu = normalizeUrl(f?.url || f?.download_url || f?.file_url || '');
|
||||
@@ -213,11 +256,13 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
|
||||
for (const url of discovered) {
|
||||
if (isChunkLikeLink(url)) continue;
|
||||
// If URL is noisy and we don't have an explicit filename from metadata, skip it.
|
||||
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
|
||||
if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||||
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
|
||||
// Skip links whose display name itself is noisy.
|
||||
if (isNoisySourceName(name)) continue;
|
||||
// 根据配置决定是否显示 MD 文件
|
||||
if ( (isMarkdownFileName(name) || isMarkdownByUrl(url))) continue;
|
||||
const key = `${name}|${url}`;
|
||||
if (!map.has(key)) {
|
||||
map.set(key, { name, url });
|
||||
@@ -230,13 +275,18 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
};
|
||||
|
||||
const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
// if (!sourceFileConfig.showSourceFiles) {
|
||||
// console.info('showSourceFiles is false');
|
||||
// return [];
|
||||
// }
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
|
||||
const merge = (links: SourceFileLink[]) => {
|
||||
for (const link of links) {
|
||||
if (isChunkLikeLink(link.url)) continue;
|
||||
// Keep file buttons if name is valid, even when URL is signed/temporary.
|
||||
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
|
||||
if (isNoisySourceName(link.name)) continue;
|
||||
if ( (isMarkdownFileName(link.name) || isMarkdownByUrl(link.url))) continue;
|
||||
if (isMarkdownFileName(link.name)) {
|
||||
const key = `${link.name}|${link.url}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
@@ -249,8 +299,8 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
};
|
||||
|
||||
if (msg?.retriever_resources) {
|
||||
// Only use structured retriever resources for source buttons,
|
||||
// so we don't accidentally show random URLs from answer text.
|
||||
// 仅使用结构化 retriever_resources 生成源文件按钮,
|
||||
// 避免把回答正文里的普通 URL 误显示为“源文件”。
|
||||
merge(getSourceLinks(msg.retriever_resources));
|
||||
}
|
||||
|
||||
@@ -259,6 +309,54 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
};
|
||||
|
||||
const getDisplayRetrieverResources = (msg: any): any[] => {
|
||||
// if (!sourceFileConfig.showSourceFiles) return [];
|
||||
const list = Array.isArray(msg?.retriever_resources) ? msg.retriever_resources : [];
|
||||
// if (sourceFileConfig.showMdFiles) return list;
|
||||
return list.filter((doc: any) => {
|
||||
const name = doc?.source_filename || doc?.document_name || doc?.title || '';
|
||||
const url = doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '';
|
||||
return !(isMarkdownFileName(String(name)) || isMarkdownByUrl(String(url)));
|
||||
});
|
||||
};
|
||||
|
||||
const shouldExpandSourceDetails = (msg: any): boolean => {
|
||||
// if (!sourceFileConfig.showSourceFiles) {
|
||||
// console.info('showSourceFiles is false');
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
|
||||
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url));
|
||||
};
|
||||
|
||||
const shouldRenderMessage = (msg: any): boolean => {
|
||||
if (msg?.role === 'user') return true;
|
||||
const content = (msg?.content || '').trim();
|
||||
if (content) return true;
|
||||
if (getMessageLinks(msg).length > 0) return true;
|
||||
if (getDisplayRetrieverResources(msg).length > 0) return true;
|
||||
return Array.isArray(msg?.attribution_parts) && msg.attribution_parts.length > 0;
|
||||
};
|
||||
|
||||
// “正在生成回答...” 仅在当前轮次还没有任何可显示的 assistant 内容时显示。
|
||||
// 一旦最后一条用户消息之后出现了可渲染的 assistant 内容(思考或答案文本等),
|
||||
// 该 loading 气泡就会隐藏,避免与正文同时出现。
|
||||
const shouldShowThinkingBubble = computed(() => {
|
||||
if (!isThinking.value) return false;
|
||||
let lastUserIndex = -1;
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
if (messages.value[i]?.role === 'user') {
|
||||
lastUserIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastUserIndex < 0) return true;
|
||||
return !messages.value
|
||||
.slice(lastUserIndex + 1)
|
||||
.some((msg) => msg?.role === 'assistant' && shouldRenderMessage(msg));
|
||||
});
|
||||
|
||||
const filePreviewVisible = ref(false);
|
||||
const previewFile = ref<SourceFileLink | null>(null);
|
||||
|
||||
@@ -278,6 +376,17 @@ const copiedIndex = ref<number | null>(null);
|
||||
const { messages, isThinking, conversationId, sendMessage } = useChat();
|
||||
const input = ref('');
|
||||
const currentAgent = ref<any>(null);
|
||||
const showGeneralFeedbackDialog = ref(false);
|
||||
const currentGeneralFeedbackChatLogId = computed(() => {
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
const msg: any = messages.value[i];
|
||||
if (msg?.role === 'assistant') {
|
||||
const id = Number(msg?.chat_log_id);
|
||||
if (Number.isInteger(id) && id > 0) return id;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
interface ChatHistoryItem {
|
||||
id: number;
|
||||
@@ -409,7 +518,7 @@ const loadAgent = async () => {
|
||||
currentAgent.value = await res.json();
|
||||
} else {
|
||||
if (res.status === 403) {
|
||||
alert(t('workspace.permission.denied') || 'Access denied');
|
||||
showMessageDialog('error', t('workspace.permission.denied') || 'Access denied');
|
||||
router.push('/');
|
||||
return;
|
||||
}
|
||||
@@ -431,17 +540,17 @@ onMounted(async () => {
|
||||
handleSend();
|
||||
}
|
||||
// Use config from config.ts instead of API
|
||||
enableFeedback.value = config.workspace.enableFeedback;
|
||||
showChatRating.value = config.workspace.showChatRating;
|
||||
});
|
||||
|
||||
/**
|
||||
* 反馈相关状态
|
||||
* enableFeedback:是否启用评分功能(后续可接入配置)
|
||||
* showChatRating:是否启用评分功能(后续可接入配置)
|
||||
* rating:用户选择的评分(1-5)
|
||||
* feedbackComment:用户输入的文字意见
|
||||
* feedbackSubmitted:是否已经提交反馈
|
||||
*/
|
||||
const enableFeedback = ref(true);
|
||||
const showChatRating = ref(false);
|
||||
const rating = ref<number | null>(null);
|
||||
const feedbackComment = ref('');
|
||||
const feedbackSubmitted = ref(false);
|
||||
@@ -451,9 +560,9 @@ const feedbackSubmitted = ref(false);
|
||||
* 用途:将评分与评论提交到后端 /api/chat/feedback
|
||||
*/
|
||||
const submitFeedback = async () => {
|
||||
if (!enableFeedback.value || feedbackSubmitted.value) return;
|
||||
if (!showChatRating.value || feedbackSubmitted.value) return;
|
||||
if (!rating.value) {
|
||||
alert(t('chat.feedback.selectRating'));
|
||||
showMessageDialog('warning', t('chat.feedback.selectRating'));
|
||||
return;
|
||||
}
|
||||
const res = await fetch('/api/chat/feedback', {
|
||||
@@ -487,10 +596,10 @@ const submitFeedback = async () => {
|
||||
></div>
|
||||
|
||||
<aside
|
||||
class="glass-panel fixed inset-y-0 left-0 z-50 flex w-80 flex-col border-r transition-transform duration-300 ease-in-out md:relative md:translate-x-0"
|
||||
class="glass-panel fixed inset-y-0 left-0 z-50 flex w-[86vw] max-w-[300px] flex-col border-r transition-transform duration-300 ease-in-out md:relative md:w-80 md:max-w-none md:translate-x-0"
|
||||
:class="isSidebarOpen ? 'translate-x-0' : '-translate-x-full'"
|
||||
>
|
||||
<div class="border-b border-slate-200/70 p-4 dark:border-slate-700/70">
|
||||
<div class="border-b border-slate-200/70 p-3 dark:border-slate-700/70 md:p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<button @click="router.push('/workspace')" class="rounded-xl p-2 text-slate-500 transition-all hover:bg-white/80 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800/80 dark:hover:text-slate-100" title="Back to Workspace">
|
||||
<ArrowLeft class="h-5 w-5" />
|
||||
@@ -498,62 +607,71 @@ const submitFeedback = async () => {
|
||||
<span class="text-sm font-semibold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-300">{{ $t('chat.history') }}</span>
|
||||
<ThemeToggleButton />
|
||||
</div>
|
||||
<button @click="startNewChat(); isSidebarOpen = false;" class="mt-4 flex w-full items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-cyan-600 to-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-lg shadow-cyan-500/30 transition-all hover:from-cyan-500 hover:to-blue-500">
|
||||
<button @click="startNewChat(); isSidebarOpen = false;" class="mt-3 inline-flex w-[92%] max-w-[320px] self-center items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-500 px-5 py-2.5 text-sm font-semibold text-white shadow-sm shadow-cyan-500/20 transition-all hover:from-cyan-400 hover:to-blue-400 hover:shadow-md hover:shadow-cyan-500/25 md:mt-4 md:w-[88%] md:max-w-none md:py-3">
|
||||
<Plus class="h-4 w-4" /> {{ $t('chat.newChat') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 space-y-1 overflow-y-auto px-3 py-3 scrollbar-thin">
|
||||
<div v-if="history.length === 0" class="py-10 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</div>
|
||||
<div class="flex-1 overflow-y-auto px-2.5 py-2.5 scrollbar-thin md:px-3 md:py-3">
|
||||
<div v-if="history.length === 0" class="py-8 text-center text-sm italic text-slate-400 md:py-10">{{ $t('chat.noHistory') }}</div>
|
||||
<div v-else class="divide-y divide-slate-200/70 dark:divide-slate-700/70">
|
||||
<button
|
||||
v-for="item in history"
|
||||
:key="item.conversation_id"
|
||||
class="w-full truncate rounded-xl border px-4 py-3 text-left text-sm transition-all"
|
||||
class="w-full truncate px-2 py-3 text-left text-sm transition-colors md:px-3"
|
||||
:class="conversationId === item.conversation_id
|
||||
? 'border-cyan-300/70 bg-cyan-50/80 font-semibold text-cyan-700 shadow-sm dark:border-cyan-500/30 dark:bg-cyan-500/10 dark:text-cyan-200'
|
||||
: 'border-transparent bg-white/50 text-slate-600 hover:border-slate-200 hover:bg-white/90 hover:text-slate-900 dark:bg-slate-900/30 dark:text-slate-300 dark:hover:border-slate-700 dark:hover:bg-slate-800/70 dark:hover:text-slate-100'"
|
||||
? 'font-semibold text-cyan-700 dark:text-cyan-200'
|
||||
: 'text-slate-600 hover:bg-slate-100/70 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800/60 dark:hover:text-slate-100'"
|
||||
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
|
||||
>
|
||||
{{ item.title || $t('chat.newChat') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3 border-t border-slate-200/70 bg-white/35 p-4 dark:border-slate-700/70 dark:bg-slate-900/35">
|
||||
<div class="space-y-2.5 border-t border-slate-200/70 bg-white/35 p-3 dark:border-slate-700/70 dark:bg-slate-900/35 md:space-y-3 md:p-4">
|
||||
<select
|
||||
v-model="locale"
|
||||
class="w-full rounded-xl border border-slate-200 bg-white/90 px-3 py-2 text-sm shadow-sm outline-none transition-all focus:border-cyan-500 focus:ring-2 focus:ring-cyan-500/20 dark:border-slate-700 dark:bg-slate-900/80"
|
||||
class="w-full rounded-xl border border-slate-200 bg-white/90 px-3 py-1.5 text-sm shadow-sm outline-none transition-all focus:border-cyan-500 focus:ring-2 focus:ring-cyan-500/20 dark:border-slate-700 dark:bg-slate-900/80 md:py-2"
|
||||
>
|
||||
<option value="en">English</option>
|
||||
<option value="zh-CN">简体中文</option>
|
||||
<option value="zh-TW">繁體中文</option>
|
||||
<option value="th">ไทย</option>
|
||||
</select>
|
||||
<div class="flex items-center justify-center gap-2 rounded-lg bg-slate-100/90 py-1.5 font-mono text-xs text-slate-500 dark:bg-slate-800/85 dark:text-slate-300">
|
||||
<span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
|
||||
{{ $t('chat.agentId') }} {{ agentId }}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden">
|
||||
<header class="sticky top-0 z-30 flex shrink-0 items-center justify-between border-b border-slate-200/70 bg-white/70 px-4 py-3 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:px-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<button @click="isSidebarOpen = !isSidebarOpen" class="rounded-lg p-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:hidden">
|
||||
<Menu class="h-5 w-5 text-slate-600 dark:text-slate-300" />
|
||||
</button>
|
||||
<header class="sticky top-0 z-30 flex shrink-0 items-center justify-between border-b border-slate-200/70 bg-white/70 pl-1 pr-2 py-3 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:px-6">
|
||||
<div class="flex min-w-0 items-center gap-1">
|
||||
<div class="mr-1 flex items-center gap-0 md:mr-0">
|
||||
<button @click="router.push('/workspace')" class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:hidden">
|
||||
<ArrowLeft class="h-5 w-5 text-slate-600 dark:text-slate-300" />
|
||||
</button>
|
||||
<button @click="isSidebarOpen = !isSidebarOpen" class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:hidden">
|
||||
<Menu class="h-5 w-5 text-slate-600 dark:text-slate-300" />
|
||||
</button>
|
||||
</div>
|
||||
<button @click="router.push('/workspace')" class="hidden rounded-lg p-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:inline-flex">
|
||||
<ArrowLeft class="h-5 w-5 text-slate-600 dark:text-slate-300" />
|
||||
</button>
|
||||
<div>
|
||||
<div class="min-w-0">
|
||||
<p class="font-semibold tracking-tight text-slate-900 dark:text-slate-100">{{ currentAgent?.name || $t('chat.defaultTitle') }}</p>
|
||||
<p class="text-xs text-slate-500 dark:text-slate-400">{{ $t('chat.assistantLabel') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button @click="startNewChat" class="hidden items-center gap-1 rounded-xl border border-slate-200 bg-white/80 px-3 py-2 text-xs font-semibold text-slate-600 transition-colors hover:border-cyan-300 hover:text-cyan-700 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:border-cyan-500/40 dark:hover:text-cyan-200 md:flex">
|
||||
<div class="ml-3 flex shrink-0 items-center gap-2">
|
||||
<button @click="startNewChat" class="inline-flex items-center gap-1 rounded-xl border border-slate-200 bg-white/80 px-2 py-1.5 text-[11px] font-semibold text-slate-600 transition-colors hover:border-cyan-300 hover:text-cyan-700 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:border-cyan-500/40 dark:hover:text-cyan-200 md:px-3 md:py-2 md:text-xs">
|
||||
<Plus class="h-4 w-4" />
|
||||
{{ $t('chat.newChat') }}
|
||||
</button>
|
||||
<button
|
||||
@click="showGeneralFeedbackDialog = true"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-[#8cbce8] bg-[#eef6ff] px-2 py-1.5 text-[11px] font-semibold text-[#2f73b2] transition-colors hover:bg-[#e3f1ff] md:px-3 md:py-2 md:text-xs"
|
||||
>
|
||||
{{ '\u610f\u89c1\u53cd\u9988' }}
|
||||
</button>
|
||||
<ThemeToggleButton />
|
||||
</div>
|
||||
</header>
|
||||
@@ -572,15 +690,15 @@ const submitFeedback = async () => {
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<main class="flex-1 space-y-8 overflow-y-auto p-4 scrollbar-thin md:p-8">
|
||||
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center pb-20 text-slate-400">
|
||||
<div class="mb-8 flex h-24 w-24 items-center justify-center rounded-3xl bg-gradient-to-br from-cyan-500 via-blue-600 to-indigo-600 shadow-2xl shadow-cyan-500/30">
|
||||
<Bot class="h-10 w-10 text-white" />
|
||||
</div>
|
||||
<h2 class="mb-3 text-center text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">{{ $t('chat.welcome.title') }}</h2>
|
||||
<p class="max-w-xl text-center text-base leading-relaxed text-slate-500 dark:text-slate-300">{{ $t('chat.welcome.subtitle') }}</p>
|
||||
<main
|
||||
class="flex-1 p-3 md:p-8"
|
||||
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'space-y-2 overflow-y-auto scrollbar-thin md:space-y-6'"
|
||||
>
|
||||
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 text-slate-400 md:pb-16">
|
||||
<h2 class="mb-2 text-center text-lg font-semibold tracking-tight text-slate-700 dark:text-slate-200 md:text-3xl md:font-bold md:text-slate-900 md:dark:text-slate-100">{{ $t('chat.welcome.title') }}</h2>
|
||||
<p class="max-w-xl text-center text-sm leading-relaxed text-slate-500 dark:text-slate-300 md:text-base">{{ $t('chat.welcome.subtitle') }}</p>
|
||||
|
||||
<div class="mt-12 grid w-full max-w-3xl grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div class="mt-5 hidden w-full max-w-md grid-cols-1 justify-items-center gap-3 md:mt-10 md:grid md:max-w-3xl md:gap-4 md:grid-cols-2 md:justify-items-stretch">
|
||||
<button v-for="suggestion in (currentAgent.suggested_questions && currentAgent.suggested_questions.length > 0 ? currentAgent.suggested_questions : [
|
||||
$t('chat.suggestions.whatCanYouDo'),
|
||||
$t('chat.suggestions.helpWriteReport'),
|
||||
@@ -589,29 +707,28 @@ const submitFeedback = async () => {
|
||||
])"
|
||||
:key="suggestion"
|
||||
@click="input = suggestion; handleSend()"
|
||||
class="rounded-2xl border border-slate-200 bg-white/90 p-4 text-left text-sm font-semibold text-slate-600 shadow-sm transition-all hover:-translate-y-0.5 hover:border-cyan-300 hover:text-cyan-700 hover:shadow-lg dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:border-cyan-500/40 dark:hover:text-cyan-200"
|
||||
class="w-full max-w-[320px] rounded-xl border border-slate-200 bg-white/90 px-4 py-3 text-left text-sm font-semibold text-slate-600 shadow-sm transition-all hover:-translate-y-0.5 hover:border-cyan-300 hover:text-cyan-700 hover:shadow-lg dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:border-cyan-500/40 dark:hover:text-cyan-200 md:max-w-none"
|
||||
>
|
||||
{{ suggestion }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-for="(msg, index) in messages" :key="index">
|
||||
<div
|
||||
v-for="(msg, index) in messages"
|
||||
:key="index"
|
||||
class="group mx-auto flex max-w-5xl gap-4 animate-slide-up"
|
||||
v-if="shouldRenderMessage(msg)"
|
||||
class="group mx-auto flex max-w-5xl gap-0 animate-slide-up"
|
||||
:class="msg.role === 'user' ? 'justify-end' : ''"
|
||||
>
|
||||
<div v-if="msg.role === 'assistant'" class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 shadow-md shadow-cyan-500/30">
|
||||
<Bot class="h-5 w-5 text-white" />
|
||||
</div>
|
||||
|
||||
<div class="flex max-w-[88%] flex-col md:max-w-[74%]">
|
||||
<div
|
||||
class="rounded-2xl px-6 py-4 text-[15px] leading-relaxed shadow-md"
|
||||
<div
|
||||
class="flex flex-col"
|
||||
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%]' : 'w-full'"
|
||||
>
|
||||
<div
|
||||
class="text-[15px] leading-relaxed shadow-md"
|
||||
:class="msg.role === 'user'
|
||||
? 'rounded-tr-md border border-cyan-400/20 bg-gradient-to-br from-cyan-600 via-blue-600 to-indigo-600 text-white shadow-cyan-500/35'
|
||||
: 'rounded-tl-md border border-slate-200 bg-white/95 text-slate-800 shadow-slate-300/30 dark:border-slate-700 dark:bg-slate-900/85 dark:text-slate-100'"
|
||||
? 'rounded-xl rounded-tr-md bg-gradient-to-r from-cyan-500 to-blue-500 px-5 py-2.5 text-white shadow-sm shadow-cyan-500/20'
|
||||
: 'rounded-2xl rounded-tl-md border border-slate-200 bg-white/95 px-6 py-4 text-slate-800 shadow-slate-300/30 dark:border-slate-700 dark:bg-slate-900/85 dark:text-slate-100'"
|
||||
>
|
||||
<div
|
||||
v-if="msg.role === 'user'"
|
||||
@@ -619,15 +736,16 @@ const submitFeedback = async () => {
|
||||
>{{ msg.content }}</div>
|
||||
<div
|
||||
v-else
|
||||
class="prose prose-sm max-w-none text-slate-800 dark:text-slate-100 prose-a:text-cyan-600 dark:prose-a:text-cyan-300 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-cyan-700 dark:prose-code:bg-slate-800 dark:prose-code:text-cyan-300 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
|
||||
class="prose prose-sm max-w-none leading-7 text-slate-800 dark:text-slate-100 prose-a:text-cyan-600 dark:prose-a:text-cyan-300 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-cyan-700 dark:prose-code:bg-slate-800 dark:prose-code:text-cyan-300 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
|
||||
v-html="renderMarkdown(msg.content)"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="msg.role === 'assistant' && ((msg.retriever_resources && msg.retriever_resources.length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
|
||||
v-if=" msg.role === 'assistant' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
|
||||
class="mt-2 space-y-2"
|
||||
>
|
||||
<!-- 带有URL链接的源文件名称,支持预览 -->
|
||||
<div v-if="getMessageLinks(msg).length > 0" class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(file, linkIndex) in getMessageLinks(msg)"
|
||||
@@ -640,15 +758,16 @@ const submitFeedback = async () => {
|
||||
</div>
|
||||
|
||||
<details
|
||||
v-if="msg.retriever_resources && msg.retriever_resources.length > 0"
|
||||
v-if="getDisplayRetrieverResources(msg).length > 0"
|
||||
class="rounded-xl border border-slate-200 bg-slate-50/90 px-4 py-3 dark:border-slate-700 dark:bg-slate-800/65"
|
||||
:open="shouldExpandSourceDetails(msg)"
|
||||
>
|
||||
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300">
|
||||
源文档 ({{ msg.retriever_resources.length }})
|
||||
源文档 ({{ getDisplayRetrieverResources(msg).length }})
|
||||
</summary>
|
||||
<div class="mt-3 space-y-2">
|
||||
<div
|
||||
v-for="(doc, docIndex) in msg.retriever_resources"
|
||||
v-for="(doc, docIndex) in getDisplayRetrieverResources(msg)"
|
||||
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
|
||||
class="rounded-lg border border-slate-200 bg-white p-3 dark:border-slate-700 dark:bg-slate-900"
|
||||
>
|
||||
@@ -722,12 +841,10 @@ const submitFeedback = async () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="msg.role === 'user'" class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<User class="h-5 w-5 text-slate-500 dark:text-slate-300" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="isThinking" class="mx-auto flex max-w-5xl gap-4">
|
||||
<div v-if="shouldShowThinkingBubble" class="mx-auto flex max-w-5xl gap-4">
|
||||
<div class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 shadow-md shadow-cyan-500/30">
|
||||
<Bot class="h-5 w-5 text-white" />
|
||||
</div>
|
||||
@@ -742,7 +859,7 @@ const submitFeedback = async () => {
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="enableFeedback && messages.length > 0 && !isThinking"
|
||||
v-if="showChatRating && messages.length > 0 && !isThinking"
|
||||
class="mx-auto mt-8 max-w-5xl border-t border-slate-200/80 pt-8 dark:border-slate-700/70"
|
||||
>
|
||||
<div class="glass-panel flex flex-col items-center gap-4 rounded-2xl p-6">
|
||||
@@ -778,12 +895,12 @@ const submitFeedback = async () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="h-6 md:h-8"></div>
|
||||
<div v-if="messages.length > 0" class="h-6 md:h-8"></div>
|
||||
</main>
|
||||
|
||||
<footer class="safe-bottom-lg sticky bottom-0 z-20 border-t border-slate-200/80 bg-white/70 p-4 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:p-6">
|
||||
<footer class="safe-bottom sticky bottom-0 z-20 border-t border-slate-200/80 bg-white/70 p-3 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:p-6">
|
||||
<div class="relative mx-auto max-w-5xl">
|
||||
<div class="chat-composer-shell relative overflow-hidden rounded-2xl border border-slate-200 bg-white/95 shadow-xl shadow-slate-300/25 transition-all duration-300 focus-within:border-cyan-500 focus-within:ring-2 focus-within:ring-cyan-500/25 dark:border-slate-700 dark:bg-slate-900/88 dark:shadow-none">
|
||||
<div class="chat-composer-shell relative overflow-hidden rounded-2xl border border-slate-200 bg-white/95 shadow-xl shadow-slate-300/25 transition-all duration-300 focus-within:border-cyan-500 dark:border-slate-700 dark:bg-slate-900/88 dark:shadow-none">
|
||||
<textarea
|
||||
v-model="input"
|
||||
@keydown.enter.prevent="handleSend"
|
||||
@@ -819,4 +936,11 @@ const submitFeedback = async () => {
|
||||
:agent-id="agentId"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
/>
|
||||
<GeneralFeedbackDialog
|
||||
v-model="showGeneralFeedbackDialog"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
source-page="chat"
|
||||
:chat-log-id="currentGeneralFeedbackChatLogId"
|
||||
@submitted="showMessageDialog('success', '\u53cd\u9988\u63d0\u4ea4\u6210\u529f')"
|
||||
/>
|
||||
</template>
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from 'vue-router';
|
||||
import { useTheme } from '../composables/useTheme';
|
||||
import type { ThemePreference } from '../composables/useTheme';
|
||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||
import {
|
||||
User,
|
||||
Mail,
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
} from 'lucide-vue-next';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
const router = useRouter();
|
||||
const { setThemePreference } = useTheme();
|
||||
|
||||
@@ -199,16 +201,16 @@ const handleSaveProfile = async () => {
|
||||
|
||||
if (!res.ok) {
|
||||
const message = await parseErrorMessage(res);
|
||||
alert(message || 'Failed to save profile');
|
||||
showMessageDialog('error', message || 'Failed to save profile');
|
||||
return;
|
||||
}
|
||||
|
||||
alert(t('profile.saveSuccess') || 'Profile saved successfully');
|
||||
showMessageDialog('success', t('profile.saveSuccess') || 'Profile saved successfully');
|
||||
captureOriginalProfile();
|
||||
isEditing.value = false;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert('Failed to save profile');
|
||||
showMessageDialog('error', 'Failed to save profile');
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
@@ -216,7 +218,7 @@ const handleSaveProfile = async () => {
|
||||
|
||||
const handleChangePassword = async () => {
|
||||
if (passwordForm.value.new !== passwordForm.value.confirm) {
|
||||
alert(t('profile.passwordMismatch') || 'Passwords do not match');
|
||||
showMessageDialog('warning', t('profile.passwordMismatch') || 'Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -232,15 +234,15 @@ const handleChangePassword = async () => {
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
alert(t('profile.passwordChanged') || 'Password changed successfully');
|
||||
showMessageDialog('success', t('profile.passwordChanged') || 'Password changed successfully');
|
||||
passwordForm.value = { current: '', new: '', confirm: '' };
|
||||
showPasswordModal.value = false;
|
||||
} else {
|
||||
alert(data.error || 'Failed to change password');
|
||||
showMessageDialog('error', data.error || 'Failed to change password');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert('Error changing password');
|
||||
showMessageDialog('error', 'Error changing password');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* WorkspaceView.vue
|
||||
* 鏂囦欢鐢ㄩ€旓細鐢ㄦ埛宸ヤ綔鍙帮紝鏀寔鑷畾涔夊竷灞€銆佹敹钘忋€佸祵鍏?Agent
|
||||
* 寮曠敤鏂囦欢锛歷ue, vue-router, lucide-vue-next, 鍚庣 /api/user 鎺ュ彛
|
||||
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
|
||||
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
|
||||
*/
|
||||
import { ref, onMounted, computed, watch } from 'vue';
|
||||
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { config } from '../config';
|
||||
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
|
||||
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
|
||||
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
||||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||||
|
||||
import {
|
||||
buildWecomLoginDialogContent,
|
||||
formatWecomFieldLabel,
|
||||
normalizeWecomMatchRules,
|
||||
type WecomLoginDialogContent,
|
||||
type WecomMatchField,
|
||||
} from '../utils/wecom';
|
||||
import {
|
||||
Settings,
|
||||
LayoutGrid,
|
||||
@@ -29,6 +40,7 @@ import {
|
||||
} from 'lucide-vue-next';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
const router = useRouter();
|
||||
|
||||
const loadLanguagePreference = () => {
|
||||
@@ -81,6 +93,16 @@ interface Announcement {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface WecomBindPromptState {
|
||||
binding_token: string;
|
||||
allowed_fields: WecomMatchField[];
|
||||
wecom_name?: string;
|
||||
field: WecomMatchField;
|
||||
value: string;
|
||||
submitting: boolean;
|
||||
error: string;
|
||||
}
|
||||
|
||||
// State
|
||||
const isLoading = ref(true);
|
||||
const currentUser = ref<{ id: number; username: string; role: string; default_agent_id?: number | null } | null>(null);
|
||||
@@ -118,10 +140,21 @@ const registerForm = ref({ username: '', password: '', email: '', real_name: '',
|
||||
const forgotPasswordForm = ref({ email: '' });
|
||||
const pendingAgentId = ref<number | null>(null);
|
||||
const isWecomLoggingIn = ref(false);
|
||||
const showDeleteQuickQuestionDialog = ref(false);
|
||||
const pendingDeleteQuickQuestionId = ref<number | null>(null);
|
||||
const showGeneralFeedbackDialog = ref(false);
|
||||
const wecomEntryHint = ref('');
|
||||
const wecomLoginDialog = ref<WecomLoginDialogContent | null>(null);
|
||||
const wecomBindPrompt = ref<WecomBindPromptState | null>(null);
|
||||
|
||||
const clearWecomCallbackQuery = () => {
|
||||
const nextUrl = `${window.location.pathname}${window.location.hash || ''}`;
|
||||
window.history.replaceState({}, '', nextUrl);
|
||||
};
|
||||
|
||||
const handleForgotPassword = async () => {
|
||||
if (!forgotPasswordForm.value.email) {
|
||||
alert(t('register.emailRequired'));
|
||||
showMessageDialog('warning', t('register.emailRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -134,21 +167,21 @@ const handleForgotPassword = async () => {
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
alert(t('login.passwordResetEmailSent'));
|
||||
showMessageDialog('success', t('login.passwordResetEmailSent'));
|
||||
showForgotPasswordModal.value = false;
|
||||
forgotPasswordForm.value = { email: '' };
|
||||
} else {
|
||||
alert(data.error || t('login.passwordResetRequestFailed'));
|
||||
showMessageDialog('error', data.error || t('login.passwordResetRequestFailed'));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Password reset error', e);
|
||||
alert(t('common.errorOccurred'));
|
||||
showMessageDialog('error', t('common.errorOccurred'));
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
const showLoginTip = () => {
|
||||
alert(t('login.pleaseLoginFirst'));
|
||||
showMessageDialog('warning', t('login.pleaseLoginFirst'));
|
||||
};
|
||||
*/
|
||||
const userReport = ref<any>(null);
|
||||
@@ -382,7 +415,7 @@ const persistLoginUser = (user: any) => {
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!loginUsername.value.trim()) {
|
||||
alert(t('login.usernameRequired'));
|
||||
showMessageDialog('warning', t('login.usernameRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -406,7 +439,7 @@ const handleLogin = async () => {
|
||||
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
|
||||
if (err.error === 'Internal server error') msg = t('login.internalError');
|
||||
|
||||
alert(msg);
|
||||
showMessageDialog('error', msg);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -422,12 +455,12 @@ const handleLogin = async () => {
|
||||
if (agents.value.some(a => a.id === targetId)) {
|
||||
navigateToChat(targetId);
|
||||
} else {
|
||||
alert(t('workspace.permission.denied'));
|
||||
showMessageDialog('error', t('workspace.permission.denied'));
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(t('login.requestFailed'));
|
||||
showMessageDialog('error', t('login.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -439,7 +472,7 @@ const handleWecomLogin = async () => {
|
||||
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data.url) {
|
||||
alert(data.error || t('login.wecomStartFailed'));
|
||||
showMessageDialog('error', data.error || t('login.wecomStartFailed'));
|
||||
return;
|
||||
}
|
||||
if (data.state) {
|
||||
@@ -448,7 +481,86 @@ const handleWecomLogin = async () => {
|
||||
window.location.href = data.url;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(t('login.wecomStartFailed'));
|
||||
showMessageDialog('error', t('login.wecomStartFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const openWecomLoginDialog = (payload: Record<string, unknown>) => {
|
||||
wecomLoginDialog.value = buildWecomLoginDialogContent(payload, t);
|
||||
};
|
||||
|
||||
const openWecomBindPrompt = (payload: Record<string, unknown>) => {
|
||||
const allowedFields = normalizeWecomMatchRules(payload.allowed_fields).fields;
|
||||
const fallbackFields: WecomMatchField[] = ['employee_id', 'mobile', 'email'];
|
||||
const fields: WecomMatchField[] = allowedFields.length ? allowedFields : fallbackFields;
|
||||
wecomBindPrompt.value = {
|
||||
binding_token: String(payload.binding_token || ''),
|
||||
allowed_fields: fields,
|
||||
wecom_name: String(payload.wecom_name || ''),
|
||||
field: fields[0] || 'employee_id',
|
||||
value: '',
|
||||
submitting: false,
|
||||
error: '',
|
||||
};
|
||||
};
|
||||
|
||||
const formatWecomBindPromptError = (payload: Record<string, unknown>) => {
|
||||
const errorCode = String(payload.error_code || '');
|
||||
if (errorCode === 'WECOM_BIND_INPUT_NOT_FOUND') return t('login.wecomBindInputNotFound');
|
||||
if (errorCode === 'WECOM_BIND_INPUT_AMBIGUOUS') return t('login.wecomBindInputAmbiguous');
|
||||
if (errorCode === 'WECOM_BIND_SESSION_EXPIRED') return t('login.wecomBindSessionExpired');
|
||||
if (errorCode === 'WECOM_BIND_CONFLICT') return t('login.wecomBindConflict');
|
||||
if (errorCode === 'WECOM_BIND_FIELD_NOT_ALLOWED') return t('login.wecomBindFieldNotAllowed');
|
||||
if (errorCode === 'WECOM_BIND_INPUT_VALUE_REQUIRED') return t('login.wecomBindValueRequired');
|
||||
if (String(payload.error || '').includes('Account is disabled')) return t('login.wecomAccountDisabled');
|
||||
return String(payload.error || t('login.wecomLoginFailed'));
|
||||
};
|
||||
|
||||
const submitWecomCompleteBind = async () => {
|
||||
if (!wecomBindPrompt.value) return;
|
||||
if (!wecomBindPrompt.value.value.trim()) {
|
||||
wecomBindPrompt.value.error = t('login.wecomBindValueRequired');
|
||||
return;
|
||||
}
|
||||
|
||||
wecomBindPrompt.value.submitting = true;
|
||||
wecomBindPrompt.value.error = '';
|
||||
try {
|
||||
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
|
||||
const res = await fetch(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
binding_token: wecomBindPrompt.value.binding_token,
|
||||
field: wecomBindPrompt.value.field,
|
||||
value: wecomBindPrompt.value.value.trim(),
|
||||
}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
wecomBindPrompt.value.error = formatWecomBindPromptError(data);
|
||||
if (String(data.error_code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
|
||||
openWecomLoginDialog(data);
|
||||
wecomBindPrompt.value = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
wecomLoginDialog.value = null;
|
||||
persistLoginUser(data);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
wecomBindPrompt.value = null;
|
||||
window.history.replaceState({}, '', '/workspace');
|
||||
await fetchHome();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
if (wecomBindPrompt.value) {
|
||||
wecomBindPrompt.value.error = t('login.wecomLoginFailed');
|
||||
}
|
||||
} finally {
|
||||
if (wecomBindPrompt.value) {
|
||||
wecomBindPrompt.value.submitting = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -462,7 +574,9 @@ const tryWecomCallbackLogin = async () => {
|
||||
|
||||
const expectedState = sessionStorage.getItem('hxops_wecom_state');
|
||||
if (expectedState && state && state !== expectedState) {
|
||||
alert(t('login.wecomInvalidState'));
|
||||
showMessageDialog('error', t('login.wecomInvalidState'));
|
||||
openWecomLoginDialog({ error: 'Invalid or expired WeCom state' });
|
||||
clearWecomCallbackQuery();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -485,10 +599,19 @@ const tryWecomCallbackLogin = async () => {
|
||||
} else if (rawError.includes('Account is disabled')) {
|
||||
friendly = t('login.wecomAccountDisabled');
|
||||
}
|
||||
alert(friendly);
|
||||
showMessageDialog('error', friendly);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') {
|
||||
openWecomBindPrompt(data);
|
||||
clearWecomCallbackQuery();
|
||||
return true;
|
||||
}
|
||||
openWecomLoginDialog(data);
|
||||
clearWecomCallbackQuery();
|
||||
return true;
|
||||
}
|
||||
|
||||
wecomLoginDialog.value = null;
|
||||
persistLoginUser(data);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
window.history.replaceState({}, '', '/workspace');
|
||||
@@ -496,7 +619,10 @@ const tryWecomCallbackLogin = async () => {
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(t('login.wecomLoginFailed'));
|
||||
showMessageDialog('error', t('login.wecomLoginFailed'));
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
openWecomLoginDialog({ error: t('login.wecomLoginFailed') });
|
||||
clearWecomCallbackQuery();
|
||||
return true;
|
||||
} finally {
|
||||
isWecomLoggingIn.value = false;
|
||||
@@ -505,7 +631,7 @@ const tryWecomCallbackLogin = async () => {
|
||||
|
||||
const handleRegister = async () => {
|
||||
if (!registerForm.value.username || !registerForm.value.password || !registerForm.value.real_name || !registerForm.value.employee_id || !registerForm.value.phone_number) {
|
||||
alert(t('register.inputError'));
|
||||
showMessageDialog('warning', t('register.inputError'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -517,21 +643,30 @@ const handleRegister = async () => {
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert(t('register.success'));
|
||||
showMessageDialog('success', t('register.success'));
|
||||
showRegisterModal.value = false;
|
||||
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert(err.error || t('register.failed'));
|
||||
showMessageDialog('error', err.error || t('register.failed'));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Register error:', e);
|
||||
alert(t('register.requestFailed'));
|
||||
showMessageDialog('error', t('register.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
// Header Dropdown State
|
||||
const showUserDropdown = ref(false);
|
||||
const userMenuRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
|
||||
if (!showUserDropdown.value) return;
|
||||
const target = event.target as Node | null;
|
||||
if (!target) return;
|
||||
if (userMenuRef.value?.contains(target)) return;
|
||||
showUserDropdown.value = false;
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('hxops_user');
|
||||
@@ -552,7 +687,7 @@ const navigateToProfile = () => {
|
||||
const navigateToChat = (id: number) => {
|
||||
if (!isLoggedIn.value) {
|
||||
pendingAgentId.value = id;
|
||||
alert(t('login.loginRequired'));
|
||||
showMessageDialog('warning', t('login.loginRequired'));
|
||||
return;
|
||||
}
|
||||
const url = router.resolve(`/chat/${id}`).href;
|
||||
@@ -562,7 +697,7 @@ const navigateToChat = (id: number) => {
|
||||
const navigateWithQuickQuestion = (agentId: number, question: string) => {
|
||||
if (!isLoggedIn.value) {
|
||||
pendingAgentId.value = agentId;
|
||||
alert(t('login.loginRequired'));
|
||||
showMessageDialog('warning', t('login.loginRequired'));
|
||||
return;
|
||||
}
|
||||
const url = router.resolve({
|
||||
@@ -572,6 +707,45 @@ const navigateWithQuickQuestion = (agentId: number, question: string) => {
|
||||
window.open(url, '_blank');
|
||||
};
|
||||
|
||||
const handleWecomDeeplinkContext = async () => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const traceId = params.get('wecom_trace');
|
||||
const target = params.get('target');
|
||||
const agentIdRaw = params.get('agent_id');
|
||||
const preset = params.get('preset');
|
||||
|
||||
if (!traceId && !target) return;
|
||||
wecomEntryHint.value = t('workspace.wecomEntryNotice');
|
||||
|
||||
if (traceId && isLoggedIn.value) {
|
||||
try {
|
||||
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
|
||||
await fetch(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ trace_id: traceId }),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('Failed to mark WeCom deeplink opened', e);
|
||||
}
|
||||
}
|
||||
|
||||
if (target === 'chat' && agentIdRaw && isLoggedIn.value) {
|
||||
const agentId = Number(agentIdRaw);
|
||||
if (Number.isInteger(agentId) && agents.value.some((a) => a.id === agentId)) {
|
||||
const url = router.resolve({
|
||||
path: `/chat/${agentId}`,
|
||||
query: preset ? { preset } : {},
|
||||
}).href;
|
||||
window.open(url, '_blank');
|
||||
}
|
||||
}
|
||||
|
||||
if (traceId || target) {
|
||||
window.history.replaceState({}, '', '/workspace');
|
||||
}
|
||||
};
|
||||
|
||||
// Favorites
|
||||
const toggleFavorite = async (agentId: number) => {
|
||||
if (favoriteAgentIds.value.includes(agentId)) {
|
||||
@@ -615,7 +789,7 @@ const cancelAddQuestion = () => {
|
||||
|
||||
const saveQuickQuestion = async () => {
|
||||
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
|
||||
alert(t('workspace.quickQuestions.msg.fillAll'));
|
||||
showMessageDialog('warning', t('workspace.quickQuestions.msg.fillAll'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -636,14 +810,27 @@ const saveQuickQuestion = async () => {
|
||||
isAddingQuestion.value = false;
|
||||
editingQuestionId.value = null;
|
||||
} else {
|
||||
alert(t('workspace.quickQuestions.msg.saveFailed'));
|
||||
showMessageDialog('error', t('workspace.quickQuestions.msg.saveFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const removeQuickQuestion = async (id: number) => {
|
||||
if (!window.confirm(t('workspace.quickQuestions.confirmDelete'))) return;
|
||||
await fetch(`/api/user/quick-questions/${id}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||
// 删除动作分两步:先记录待删除 id 并打开公共弹框,真正删除在 confirm 回调中执行。
|
||||
pendingDeleteQuickQuestionId.value = id;
|
||||
showDeleteQuickQuestionDialog.value = true;
|
||||
};
|
||||
|
||||
const confirmRemoveQuickQuestion = async () => {
|
||||
if (pendingDeleteQuickQuestionId.value === null) return;
|
||||
await fetch(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||
await fetchHome();
|
||||
pendingDeleteQuickQuestionId.value = null;
|
||||
showDeleteQuickQuestionDialog.value = false;
|
||||
};
|
||||
|
||||
const cancelRemoveQuickQuestion = () => {
|
||||
pendingDeleteQuickQuestionId.value = null;
|
||||
showDeleteQuickQuestionDialog.value = false;
|
||||
};
|
||||
|
||||
// Drag & Drop
|
||||
@@ -688,6 +875,8 @@ const openAnnouncement = (ann: Announcement) => {
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
document.addEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||
loadLanguagePreference();
|
||||
fetchAnnouncements();
|
||||
const handledWecom = await tryWecomCallbackLogin();
|
||||
@@ -697,11 +886,17 @@ onMounted(async () => {
|
||||
loadAuthUser();
|
||||
if (currentUser.value && currentUser.value.role !== 'guest') {
|
||||
await fetchHome();
|
||||
await handleWecomDeeplinkContext();
|
||||
} else {
|
||||
await fetchPublicAgents();
|
||||
isLoading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -718,47 +913,45 @@ onMounted(async () => {
|
||||
</div>
|
||||
|
||||
<!-- Header (Logged In) -->
|
||||
<header v-if="isLoggedIn" class="sticky top-0 z-30 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-gray-100 dark:border-slate-700 px-4 md:px-8 py-4 mb-8 transition-all duration-300">
|
||||
<div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="w-10 h-10 bg-gradient-to-br from-brand-500 to-brand-700 rounded-xl flex items-center justify-center text-white shadow-lg shadow-brand-500/30">
|
||||
<Bot class="w-6 h-6" />
|
||||
<header v-if="isLoggedIn" class="sticky top-0 z-30 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-gray-100 dark:border-slate-700 page-shell-mobile py-2.5 md:py-4 section-gap-mobile transition-all duration-300">
|
||||
<div class="max-w-7xl mx-auto flex flex-wrap md:flex-nowrap justify-between items-start md:items-center gap-2 md:gap-4">
|
||||
<div class="flex items-center gap-2 md:gap-3 min-w-0 flex-1">
|
||||
<div class="w-8 h-8 md:w-10 md:h-10 bg-gradient-to-br from-brand-500 to-brand-700 rounded-xl flex items-center justify-center text-white shadow-lg shadow-brand-500/30 shrink-0">
|
||||
<Bot class="w-4 h-4 md:w-6 md:h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-xl font-bold text-slate-900 dark:text-slate-100 tracking-tight">
|
||||
{{ currentUser ? $t('workspace.userTitle', { username: currentUser.username }) : $t('workspace.title') }}
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-lg md:text-xl font-bold text-[#1b2b49] dark:text-slate-100 tracking-tight leading-tight truncate">
|
||||
{{ $t('workspace.brandTitle') }}
|
||||
</h1>
|
||||
<p class="text-slate-500 dark:text-slate-400 text-xs font-medium">{{ $t('workspace.subtitle') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<!-- 已登录页将主题与语言切换放入头部右侧,避免不同分辨率下被遮挡 -->
|
||||
<div class="flex items-center gap-2 md:gap-4 shrink-0">
|
||||
<!-- Keep header actions minimal on mobile; language switch is in the profile dropdown. -->
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
@click="showGeneralFeedbackDialog = true"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-[#8cbce8] bg-[#eef6ff] px-2 py-1.5 text-[11px] font-semibold text-[#2f73b2] transition-colors hover:bg-[#e3f1ff] md:px-3 md:py-2 md:text-xs"
|
||||
>
|
||||
{{ '\u610f\u89c1\u53cd\u9988' }}
|
||||
</button>
|
||||
<ThemeToggleButton />
|
||||
<select v-model="locale" class="bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shadow-sm border border-slate-200 dark:border-slate-700 text-xs font-medium text-slate-600 dark:text-slate-300 hover:text-slate-800 dark:hover:text-slate-100 cursor-pointer outline-none rounded-full px-3 py-1.5 transition-all hover:shadow-md">
|
||||
<option value="en">English</option>
|
||||
<option value="zh-CN">简体中文</option>
|
||||
<option value="zh-TW">繁體中文</option>
|
||||
<option value="th">ไทย</option>
|
||||
</select>
|
||||
</div>
|
||||
<!-- User Profile Dropdown -->
|
||||
<div class="relative">
|
||||
<button @click="showUserDropdown = !showUserDropdown" class="flex items-center gap-3 pl-3 pr-2 py-1.5 rounded-full hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
|
||||
<div ref="userMenuRef" class="relative">
|
||||
<button @click="showUserDropdown = !showUserDropdown" class="flex items-center gap-2 md:gap-3 pl-2 md:pl-3 pr-1.5 md:pr-2 py-1 md:py-1.5 rounded-full hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
|
||||
<div class="text-right hidden sm:block">
|
||||
<div class="text-sm font-bold text-slate-900 dark:text-slate-100 leading-tight">{{ currentUser?.username }}</div>
|
||||
<div class="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{{ currentUser?.role }}</div>
|
||||
</div>
|
||||
<div class="w-9 h-9 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold border-2 border-white shadow-sm">
|
||||
<div class="w-8 h-8 md:w-9 md:h-9 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold border-2 border-white shadow-sm">
|
||||
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<!-- Dropdown Menu -->
|
||||
<div v-if="showUserDropdown"
|
||||
class="absolute right-0 top-full mt-2 w-48 bg-white dark:bg-slate-900 rounded-xl shadow-xl border border-slate-100 dark:border-slate-700 py-1 z-50 animate-fade-in"
|
||||
@click.away="showUserDropdown = false">
|
||||
class="absolute right-0 top-full mt-2 w-56 bg-white dark:bg-slate-900 rounded-xl shadow-xl border border-slate-100 dark:border-slate-700 py-1 z-50 animate-fade-in">
|
||||
<div class="px-4 py-3 border-b border-slate-50 dark:border-slate-700 md:hidden">
|
||||
<div class="text-sm font-bold text-slate-900 dark:text-slate-100">{{ currentUser?.username }}</div>
|
||||
<div class="text-xs text-slate-500 dark:text-slate-400">{{ currentUser?.role }}</div>
|
||||
@@ -773,7 +966,16 @@ onMounted(async () => {
|
||||
<Settings class="w-4 h-4" />
|
||||
{{ $t('admin.title') }}
|
||||
</button>
|
||||
|
||||
<div class="px-4 pt-2 pb-3 border-t border-slate-50 dark:border-slate-700 mt-1">
|
||||
<label class="block text-[11px] font-semibold text-slate-500 dark:text-slate-400 mb-1.5 uppercase tracking-wide">{{ $t('workspace.languageLabel') }}</label>
|
||||
<select v-model="locale" class="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-xs font-medium text-slate-700 dark:text-slate-300 rounded-lg px-2.5 py-2 outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500">
|
||||
<option value="en">English</option>
|
||||
<option value="zh-CN">简体中文</option>
|
||||
<option value="zh-TW">繁體中文</option>
|
||||
<option value="th">ไทย</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-slate-50 dark:border-slate-700 my-1"></div>
|
||||
|
||||
<button @click="handleLogout" class="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2">
|
||||
@@ -786,7 +988,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="max-w-7xl mx-auto px-4 md:px-8 pb-12">
|
||||
<main class="max-w-7xl mx-auto page-shell-mobile pb-12">
|
||||
<div v-if="isLoading" class="animate-pulse space-y-8">
|
||||
<div class="h-48 bg-gray-200 rounded-2xl"></div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
@@ -922,6 +1124,9 @@ onMounted(async () => {
|
||||
|
||||
<!-- Logged In Layout -->
|
||||
<div v-else class="space-y-8 animate-fade-in">
|
||||
<div v-if="wecomEntryHint" class="rounded-xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
|
||||
{{ wecomEntryHint }}
|
||||
</div>
|
||||
<!-- Draggable Sections -->
|
||||
<div
|
||||
v-for="(section, index) in layoutSections"
|
||||
@@ -942,7 +1147,7 @@ onMounted(async () => {
|
||||
<div class="md:pl-6">
|
||||
<!-- Header -->
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h2 class="text-xl font-bold text-slate-800 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)">
|
||||
<h2 class="text-lg md:text-xl font-semibold text-[#1b2b49] dark:text-slate-100 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)">
|
||||
<div class="p-2 rounded-lg" :class="{
|
||||
'bg-emerald-50 text-emerald-600': section.id === 'announcements',
|
||||
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
|
||||
@@ -984,15 +1189,15 @@ onMounted(async () => {
|
||||
<!-- Content: Favorites -->
|
||||
<div v-if="section.id === 'favorites'">
|
||||
<div v-if="favoriteAgents.length === 0" class="text-slate-400 text-sm italic py-4 bg-slate-50 rounded-xl text-center border border-dashed border-slate-200">{{ $t('workspace.noFavorites') }}</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
|
||||
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
|
||||
<div v-for="agent in favoriteAgents" :key="agent.id" @click="navigateToChat(agent.id)"
|
||||
class="card p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
|
||||
<div class="w-12 h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
|
||||
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-7 h-7" />
|
||||
<Bot v-else class="w-7 h-7" />
|
||||
class="card p-4 sm:p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
|
||||
<div class="w-8 h-8 sm:w-12 sm:h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-3 sm:mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
|
||||
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-5 h-5 sm:w-7 sm:h-7" />
|
||||
<Bot v-else class="w-5 h-5 sm:w-7 sm:h-7" />
|
||||
</div>
|
||||
<div class="font-bold text-slate-900 mb-1 group-hover/card:text-brand-700 transition-colors">{{ agent.name }}</div>
|
||||
<div class="text-xs text-slate-500 truncate">{{ agent.description }}</div>
|
||||
<div class="text-[15px] sm:text-base font-semibold text-[#1b2b49] dark:text-slate-100 mb-1 group-hover/card:text-brand-700 dark:group-hover/card:text-brand-300 transition-colors truncate">{{ agent.name }}</div>
|
||||
<div class="text-[13px] sm:text-xs text-[#8fa1b8] dark:text-slate-300 truncate">{{ agent.description }}</div>
|
||||
<button @click.stop="toggleFavorite(agent.id)" class="absolute top-3 right-3 text-yellow-400 hover:text-yellow-500 hover:scale-110 transition-all opacity-0 group-hover/card:opacity-100">
|
||||
<Star class="w-5 h-5 fill-current" />
|
||||
</button>
|
||||
@@ -1076,23 +1281,21 @@ onMounted(async () => {
|
||||
<div class="mb-6">
|
||||
<input v-model="searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" />
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
|
||||
<div v-for="agent in otherAgents" :key="agent.id"
|
||||
class="card p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200">
|
||||
<div class="flex items-start justify-between mb-4">
|
||||
<div class="w-10 h-10 bg-slate-50 rounded-xl flex items-center justify-center text-slate-500 group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors">
|
||||
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-6 h-6" />
|
||||
<Bot v-else class="w-6 h-6" />
|
||||
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
|
||||
<div v-for="agent in otherAgents" :key="agent.id"
|
||||
@click="navigateToChat(agent.id)"
|
||||
class="card card-mobile-compact cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200">
|
||||
<div class="flex items-start justify-between mb-2 sm:mb-4">
|
||||
<div class="w-8 h-8 sm:w-10 sm:h-10 bg-slate-50 rounded-xl flex items-center justify-center text-slate-500 group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors">
|
||||
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-4 h-4 sm:w-6 sm:h-6" />
|
||||
<Bot v-else class="w-4 h-4 sm:w-6 sm:h-6" />
|
||||
</div>
|
||||
<button @click.stop="toggleFavorite(agent.id)" class="text-slate-200 hover:text-yellow-400 transition-colors">
|
||||
<Star class="w-5 h-5" :class="{ 'fill-yellow-400 text-yellow-400': favoriteAgentIds.includes(agent.id) }" />
|
||||
</button>
|
||||
</div>
|
||||
<h3 class="font-bold text-slate-900 mb-1 group-hover/card:text-brand-700 transition-colors">{{ agent.name }}</h3>
|
||||
<p class="text-xs text-slate-500 line-clamp-2 h-8 leading-relaxed">{{ agent.description }}</p>
|
||||
<button @click="navigateToChat(agent.id)" class="mt-5 w-full py-2 bg-slate-50 text-slate-600 text-xs font-bold rounded-xl hover:bg-brand-600 hover:text-white transition-all duration-300">
|
||||
{{ $t('workspace.startChatShort') }}
|
||||
</button>
|
||||
<h3 class="text-[15px] sm:text-base font-semibold text-[#1b2b49] dark:text-slate-100 mb-1 group-hover/card:text-brand-700 dark:group-hover/card:text-brand-300 transition-colors line-clamp-1 sm:line-clamp-2 leading-tight">{{ agent.name }}</h3>
|
||||
<p class="text-[13px] sm:text-xs text-[#8fa1b8] dark:text-slate-300 line-clamp-1 sm:line-clamp-2 h-4 sm:h-8 leading-relaxed">{{ agent.description }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1147,6 +1350,79 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<div v-if="wecomLoginDialog" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
|
||||
<div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-lg p-8 animate-slide-up relative border border-slate-200 dark:border-slate-700">
|
||||
<button @click="wecomLoginDialog = null" class="absolute top-4 right-4 text-slate-400 hover:text-slate-600">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
<div class="mb-5">
|
||||
<div class="w-12 h-12 bg-amber-100 text-amber-700 rounded-xl flex items-center justify-center mb-4">
|
||||
<Lock class="w-6 h-6" />
|
||||
</div>
|
||||
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ wecomLoginDialog.title }}</h3>
|
||||
<p class="text-sm text-slate-600 dark:text-slate-300 mt-3 leading-6">{{ wecomLoginDialog.summary }}</p>
|
||||
</div>
|
||||
<div v-if="wecomLoginDialog.details.length" class="rounded-2xl bg-slate-50 dark:bg-slate-800/80 border border-slate-200 dark:border-slate-700 px-4 py-4 space-y-3">
|
||||
<p v-for="(detail, index) in wecomLoginDialog.details" :key="`${detail}-${index}`" class="text-sm text-slate-600 dark:text-slate-300 leading-6">
|
||||
{{ detail }}
|
||||
</p>
|
||||
</div>
|
||||
<p v-if="wecomLoginDialog.technical" class="mt-4 text-xs text-slate-400 break-all">
|
||||
{{ $t('login.wecomTechnicalInfo', { detail: wecomLoginDialog.technical }) }}
|
||||
</p>
|
||||
<div class="flex justify-end gap-3 mt-8">
|
||||
<button @click="wecomLoginDialog = null" class="btn-secondary">{{ $t('admin.close') }}</button>
|
||||
<button @click="wecomLoginDialog = null; handleWecomLogin()" class="btn-primary" :disabled="isWecomLoggingIn">
|
||||
{{ $t('login.wecomRetry') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="wecomBindPrompt" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
|
||||
<div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-lg p-8 animate-slide-up relative border border-slate-200 dark:border-slate-700">
|
||||
<button @click="wecomBindPrompt = null" class="absolute top-4 right-4 text-slate-400 hover:text-slate-600">
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
<div class="mb-6">
|
||||
<div class="w-12 h-12 bg-blue-100 text-blue-700 rounded-xl flex items-center justify-center mb-4">
|
||||
<User class="w-6 h-6" />
|
||||
</div>
|
||||
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ $t('login.wecomBindPromptTitle') }}</h3>
|
||||
<p class="text-sm text-slate-600 dark:text-slate-300 mt-3 leading-6">
|
||||
{{ $t('login.wecomBindPromptDesc', { name: wecomBindPrompt.wecom_name || '-' }) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="mb-1.5 block text-xs font-semibold text-slate-600 uppercase">{{ $t('login.wecomBindField') }}</label>
|
||||
<select v-model="wecomBindPrompt.field" class="input-field">
|
||||
<option v-for="field in wecomBindPrompt.allowed_fields" :key="field" :value="field">
|
||||
{{ formatWecomFieldLabel(field, t) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1.5 block text-xs font-semibold text-slate-600 uppercase">{{ $t('login.wecomBindValue') }}</label>
|
||||
<input
|
||||
v-model="wecomBindPrompt.value"
|
||||
class="input-field"
|
||||
:placeholder="$t('login.wecomBindValuePlaceholder', { field: formatWecomFieldLabel(wecomBindPrompt.field, t) })"
|
||||
@keyup.enter="submitWecomCompleteBind"
|
||||
/>
|
||||
</div>
|
||||
<p class="text-xs text-slate-500 leading-5">{{ $t('login.wecomBindPromptHint') }}</p>
|
||||
<p v-if="wecomBindPrompt.error" class="text-sm text-red-600 leading-6">{{ wecomBindPrompt.error }}</p>
|
||||
</div>
|
||||
<div class="flex justify-end gap-3 mt-8">
|
||||
<button @click="wecomBindPrompt = null" class="btn-secondary">{{ $t('admin.close') }}</button>
|
||||
<button @click="submitWecomCompleteBind" class="btn-primary" :disabled="wecomBindPrompt.submitting">
|
||||
{{ wecomBindPrompt.submitting ? $t('login.wecomConnecting') : $t('login.wecomBindSubmit') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Register Modal -->
|
||||
<div v-if="showRegisterModal" class="fixed inset-0 bg-slate-900/40 dark:bg-slate-950/70 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
|
||||
@@ -1170,6 +1446,19 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="showDeleteQuickQuestionDialog"
|
||||
:title="$t('workspace.quickQuestions.deleteDialog.title')"
|
||||
:message="$t('workspace.quickQuestions.deleteDialog.message')"
|
||||
@confirm="confirmRemoveQuickQuestion"
|
||||
@cancel="cancelRemoveQuickQuestion"
|
||||
/>
|
||||
<GeneralFeedbackDialog
|
||||
v-model="showGeneralFeedbackDialog"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
source-page="workspace"
|
||||
@submitted="showMessageDialog('success', '\u53cd\u9988\u63d0\u4ea4\u6210\u529f')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便
|
||||
allowedHosts: ['hx.benl.cn'],
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:5002',
|
||||
|
||||
+781
@@ -0,0 +1,781 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
if git -C "${SCRIPT_DIR}" rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||
ROOT_DIR="$(git -C "${SCRIPT_DIR}" rev-parse --show-toplevel)"
|
||||
elif git -C "${SCRIPT_DIR}/.." rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||
ROOT_DIR="$(git -C "${SCRIPT_DIR}/.." rev-parse --show-toplevel)"
|
||||
else
|
||||
ROOT_DIR="${SCRIPT_DIR}"
|
||||
fi
|
||||
|
||||
RUN_DIR="${ROOT_DIR}/.run"
|
||||
BACKEND_DIR="${ROOT_DIR}/backend"
|
||||
FRONTEND_DIR="${ROOT_DIR}/frontend"
|
||||
|
||||
BACKEND_PORT=5002
|
||||
FRONTEND_PORT=8881
|
||||
DB_PORT=5432
|
||||
DB_DATA_DIR="/opt/homebrew/var/postgresql@18"
|
||||
DB_BIN="/opt/homebrew/opt/postgresql@18/bin/postgres"
|
||||
|
||||
mkdir -p "${RUN_DIR}"
|
||||
|
||||
is_listening() {
|
||||
local port="$1"
|
||||
lsof -nP -iTCP:"${port}" -sTCP:LISTEN >/dev/null 2>&1
|
||||
}
|
||||
|
||||
get_lan_ip() {
|
||||
local ip=""
|
||||
for iface in en0 en1; do
|
||||
ip="$(ipconfig getifaddr "${iface}" 2>/dev/null || true)"
|
||||
if [[ -n "${ip}" ]]; then
|
||||
echo "${ip}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
ip="$(ifconfig 2>/dev/null | awk '/inet / && $2 != "127.0.0.1" {print $2; exit}')"
|
||||
if [[ -n "${ip}" ]]; then
|
||||
echo "${ip}"
|
||||
fi
|
||||
}
|
||||
|
||||
print_access_links() {
|
||||
local lan_ip
|
||||
lan_ip="$(get_lan_ip || true)"
|
||||
|
||||
echo "== 访问链接 =="
|
||||
echo "前端(本机): http://127.0.0.1:${FRONTEND_PORT}"
|
||||
echo "后端(本机): http://127.0.0.1:${BACKEND_PORT}"
|
||||
if [[ -n "${lan_ip}" ]]; then
|
||||
echo "前端(局域网): http://${lan_ip}:${FRONTEND_PORT}"
|
||||
echo "后端(局域网): http://${lan_ip}:${BACKEND_PORT}"
|
||||
fi
|
||||
}
|
||||
|
||||
start_project() {
|
||||
echo "=== 启动 HXOPS 项目 ==="
|
||||
|
||||
if is_listening "${DB_PORT}"; then
|
||||
echo "[数据库] 端口 ${DB_PORT} 已在监听,跳过启动。"
|
||||
else
|
||||
echo "[数据库] 正在启动..."
|
||||
nohup env LC_ALL="en_US.UTF-8" "${DB_BIN}" -D "${DB_DATA_DIR}" > "${RUN_DIR}/postgres.log" 2>&1 &
|
||||
echo $! > "${RUN_DIR}/postgres.pid"
|
||||
sleep 2
|
||||
if is_listening "${DB_PORT}"; then
|
||||
echo "[数据库] 启动成功,端口 ${DB_PORT}。"
|
||||
else
|
||||
echo "[数据库] 启动失败,请查看日志: ${RUN_DIR}/postgres.log"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if is_listening "${BACKEND_PORT}"; then
|
||||
echo "[后端] 端口 ${BACKEND_PORT} 已在监听,跳过启动。"
|
||||
else
|
||||
echo "[后端] 正在启动..."
|
||||
(
|
||||
cd "${BACKEND_DIR}"
|
||||
source venv/bin/activate
|
||||
nohup python3 run.py > "${RUN_DIR}/backend.log" 2>&1 &
|
||||
echo $! > "${RUN_DIR}/backend.pid"
|
||||
)
|
||||
sleep 2
|
||||
if is_listening "${BACKEND_PORT}"; then
|
||||
echo "[后端] 启动成功,端口 ${BACKEND_PORT}。"
|
||||
else
|
||||
echo "[后端] 启动失败,请查看日志: ${RUN_DIR}/backend.log"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if is_listening "${FRONTEND_PORT}"; then
|
||||
echo "[前端] 端口 ${FRONTEND_PORT} 已在监听,跳过启动。"
|
||||
else
|
||||
echo "[前端] 正在启动..."
|
||||
(
|
||||
cd "${FRONTEND_DIR}"
|
||||
nohup npm run dev > "${RUN_DIR}/frontend.log" 2>&1 &
|
||||
echo $! > "${RUN_DIR}/frontend.pid"
|
||||
)
|
||||
sleep 3
|
||||
if is_listening "${FRONTEND_PORT}"; then
|
||||
echo "[前端] 启动成功,端口 ${FRONTEND_PORT}。"
|
||||
else
|
||||
echo "[前端] 启动失败,请查看日志: ${RUN_DIR}/frontend.log"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
|
||||
print_access_links
|
||||
echo "日志目录: ${RUN_DIR}"
|
||||
}
|
||||
|
||||
kill_by_pid_file() {
|
||||
local name="$1"
|
||||
local pid_file="$2"
|
||||
|
||||
if [[ ! -f "${pid_file}" ]]; then
|
||||
echo "[${name}] 未找到 PID 文件,跳过。"
|
||||
return
|
||||
fi
|
||||
|
||||
local pid
|
||||
pid="$(cat "${pid_file}")"
|
||||
|
||||
if [[ -z "${pid}" ]] || ! kill -0 "${pid}" >/dev/null 2>&1; then
|
||||
echo "[${name}] PID ${pid:-<empty>} 不存在,清理 PID 文件。"
|
||||
rm -f "${pid_file}"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "[${name}] 正在停止进程 PID=${pid}..."
|
||||
kill "${pid}" >/dev/null 2>&1 || true
|
||||
|
||||
for _ in {1..10}; do
|
||||
if ! kill -0 "${pid}" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
if kill -0 "${pid}" >/dev/null 2>&1; then
|
||||
echo "[${name}] 进程未退出,执行强制停止 PID=${pid}。"
|
||||
kill -9 "${pid}" >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
rm -f "${pid_file}"
|
||||
echo "[${name}] 已停止。"
|
||||
}
|
||||
|
||||
kill_by_port_if_needed() {
|
||||
local name="$1"
|
||||
local port="$2"
|
||||
|
||||
local pids
|
||||
pids="$(lsof -ti tcp:${port} 2>/dev/null || true)"
|
||||
if [[ -z "${pids}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
echo "[${name}] 检测到端口 ${port} 仍有进程: ${pids},尝试终止..."
|
||||
for pid in ${pids}; do
|
||||
kill "${pid}" >/dev/null 2>&1 || true
|
||||
done
|
||||
sleep 1
|
||||
|
||||
pids="$(lsof -ti tcp:${port} 2>/dev/null || true)"
|
||||
if [[ -n "${pids}" ]]; then
|
||||
for pid in ${pids}; do
|
||||
kill -9 "${pid}" >/dev/null 2>&1 || true
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
stop_project() {
|
||||
echo "=== 关闭 HXOPS 项目 ==="
|
||||
kill_by_pid_file "后端" "${RUN_DIR}/backend.pid"
|
||||
kill_by_pid_file "前端" "${RUN_DIR}/frontend.pid"
|
||||
kill_by_port_if_needed "后端" "${BACKEND_PORT}"
|
||||
kill_by_port_if_needed "前端" "${FRONTEND_PORT}"
|
||||
kill_by_pid_file "数据库" "${RUN_DIR}/postgres.pid"
|
||||
kill_by_port_if_needed "数据库" "${DB_PORT}"
|
||||
echo "关闭完成。"
|
||||
}
|
||||
|
||||
push_gitee() {
|
||||
echo "=== 上传代码到 Gitee ==="
|
||||
|
||||
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "当前目录不是 Git 仓库,已退出。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local remote_url
|
||||
remote_url="$(git -C "${ROOT_DIR}" remote get-url origin 2>/dev/null || true)"
|
||||
if [[ -z "${remote_url}" ]]; then
|
||||
echo "未找到 origin 远程仓库,请先配置后再上传。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [[ "${remote_url}" != *"gitee.com"* ]]; then
|
||||
echo "警告: 当前 origin 不是 Gitee: ${remote_url}"
|
||||
read -r -p "仍要继续 push 到 origin 吗? (y/N): " force_push
|
||||
if [[ ! "${force_push}" =~ ^[Yy]$ ]]; then
|
||||
echo "已取消。"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
local branch
|
||||
branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
|
||||
|
||||
local migration_check_script="${BACKEND_DIR}/scripts/ci_check_migrations.sh"
|
||||
if [[ -x "${migration_check_script}" ]]; then
|
||||
echo "== 提交前检查: 数据库结构一致性 =="
|
||||
(
|
||||
cd "${BACKEND_DIR}"
|
||||
"${migration_check_script}"
|
||||
) || {
|
||||
echo "检查未通过,已阻止 commit/push。"
|
||||
echo "请先修复 models/migrations/database 不一致问题后重试。"
|
||||
return 1
|
||||
}
|
||||
else
|
||||
echo "警告: 未找到可执行检查脚本 ${migration_check_script},跳过结构检查。"
|
||||
fi
|
||||
|
||||
if [[ -n "$(git -C "${ROOT_DIR}" status --porcelain)" ]]; then
|
||||
git -C "${ROOT_DIR}" add -A
|
||||
read -r -p "请输入提交说明(留空使用默认): " commit_msg
|
||||
if [[ -z "${commit_msg:-}" ]]; then
|
||||
commit_msg="chore: update $(date '+%Y-%m-%d %H:%M:%S')"
|
||||
fi
|
||||
|
||||
if [[ -n "$(git -C "${ROOT_DIR}" diff --cached --name-only)" ]]; then
|
||||
git -C "${ROOT_DIR}" commit -m "${commit_msg}"
|
||||
fi
|
||||
else
|
||||
echo "工作区无变更,将直接 push 当前分支。"
|
||||
fi
|
||||
|
||||
echo "推送分支: ${branch} -> origin/${branch}"
|
||||
git -C "${ROOT_DIR}" push origin "${branch}"
|
||||
echo "上传完成。"
|
||||
}
|
||||
|
||||
show_status() {
|
||||
echo "== 项目服务状态 =="
|
||||
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
|
||||
local compose_table
|
||||
compose_table="$(docker compose -p hxops ps --format 'table {{.Name}}\t{{.Image}}\t{{.Command}}\t{{.Service}}\t{{.CreatedAt}}\t{{.State}}\t{{.Publishers}}' 2>/dev/null || true)"
|
||||
if [[ -n "${compose_table}" ]]; then
|
||||
echo "${compose_table}"
|
||||
else
|
||||
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
|
||||
"NAME" "IMAGE" "COMMAND" "SERVICE" "CREATED" "STATUS" "PORTS"
|
||||
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
|
||||
"hxops-backend" "hxops-hxops-backend" "\"python3 run.py\"" "hxops-backend" "-" \
|
||||
"$(is_listening "${BACKEND_PORT}" && echo "Up" || echo "Down")" \
|
||||
"0.0.0.0:${BACKEND_PORT}->${BACKEND_PORT}/tcp, [::]:${BACKEND_PORT}->${BACKEND_PORT}/tcp"
|
||||
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
|
||||
"hxops-frontend" "hxops-hxops-frontend" "\"npm run dev\"" "hxops-frontend" "-" \
|
||||
"$(is_listening "${FRONTEND_PORT}" && echo "Up" || echo "Down")" \
|
||||
"0.0.0.0:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp, [::]:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp"
|
||||
fi
|
||||
else
|
||||
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
|
||||
"NAME" "IMAGE" "COMMAND" "SERVICE" "CREATED" "STATUS" "PORTS"
|
||||
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
|
||||
"hxops-backend" "hxops-hxops-backend" "\"python3 run.py\"" "hxops-backend" "-" \
|
||||
"$(is_listening "${BACKEND_PORT}" && echo "Up" || echo "Down")" \
|
||||
"0.0.0.0:${BACKEND_PORT}->${BACKEND_PORT}/tcp, [::]:${BACKEND_PORT}->${BACKEND_PORT}/tcp"
|
||||
printf "%-16s %-22s %-24s %-16s %-12s %-12s %-s\n" \
|
||||
"hxops-frontend" "hxops-hxops-frontend" "\"npm run dev\"" "hxops-frontend" "-" \
|
||||
"$(is_listening "${FRONTEND_PORT}" && echo "Up" || echo "Down")" \
|
||||
"0.0.0.0:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp, [::]:${FRONTEND_PORT}->${FRONTEND_PORT}/tcp"
|
||||
fi
|
||||
|
||||
echo "=== 当前状态 ==="
|
||||
if is_listening "${DB_PORT}"; then
|
||||
echo "数据库: 运行中 (端口 ${DB_PORT})"
|
||||
else
|
||||
echo "数据库: 未运行"
|
||||
fi
|
||||
|
||||
if is_listening "${BACKEND_PORT}"; then
|
||||
echo "后端: 运行中 (端口 ${BACKEND_PORT})"
|
||||
else
|
||||
echo "后端: 未运行"
|
||||
fi
|
||||
|
||||
if is_listening "${FRONTEND_PORT}"; then
|
||||
echo "前端: 运行中 (端口 ${FRONTEND_PORT})"
|
||||
else
|
||||
echo "前端: 未运行"
|
||||
fi
|
||||
print_access_links
|
||||
}
|
||||
|
||||
show_dev_open_ports() {
|
||||
echo "=== 开发服务端口扫描(排除 macOS 常规系统服务) ==="
|
||||
echo "说明: 仅显示当前用户 ${USER} 打开的 TCP 监听端口。"
|
||||
echo ""
|
||||
printf "%-20s %-8s %-24s\n" "进程名" "PID" "监听地址"
|
||||
printf "%-20s %-8s %-24s\n" "--------------------" "--------" "------------------------"
|
||||
|
||||
local output
|
||||
output="$(
|
||||
lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null \
|
||||
| awk -v user="${USER}" '
|
||||
function ignored(cmd) {
|
||||
return (cmd ~ /^(ControlCe|rapportd|cfprefsd|trustd|sharingd|identitys)$/)
|
||||
}
|
||||
NR > 1 && $3 == user {
|
||||
if (ignored($1)) next
|
||||
endpoint = $(NF-1)
|
||||
key = $1 "|" $2 "|" endpoint
|
||||
if (!seen[key]++) {
|
||||
printf "%-20s %-8s %-24s\n", $1, $2, endpoint
|
||||
}
|
||||
}
|
||||
'
|
||||
)"
|
||||
|
||||
if [[ -z "${output}" ]]; then
|
||||
echo "未发现当前用户启动的监听端口。"
|
||||
return
|
||||
fi
|
||||
|
||||
echo "${output}"
|
||||
}
|
||||
|
||||
show_non_system_open_ports() {
|
||||
echo "=== 非系统端口扫描(全量监听端口 - macOS 系统服务) ==="
|
||||
echo "说明: 扫描所有 TCP 监听端口,过滤系统进程后按服务分组展示。"
|
||||
|
||||
local rows
|
||||
rows="$(
|
||||
lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null \
|
||||
| awk '
|
||||
NR > 1 {
|
||||
cmd = $1
|
||||
pid = $2
|
||||
user = $3
|
||||
endpoint = $(NF-1)
|
||||
key = pid "|" endpoint
|
||||
if (!seen[key]++) {
|
||||
print pid "\t" user "\t" cmd "\t" endpoint
|
||||
}
|
||||
}
|
||||
'
|
||||
)"
|
||||
|
||||
if [[ -z "${rows}" ]]; then
|
||||
echo "未发现监听端口。"
|
||||
return
|
||||
fi
|
||||
|
||||
local tmp_dir
|
||||
tmp_dir="$(mktemp -d)"
|
||||
trap 'rm -rf "${tmp_dir}"' RETURN
|
||||
|
||||
local f_openclaw="${tmp_dir}/openclaw.txt"
|
||||
local f_hxops="${tmp_dir}/hxops.txt"
|
||||
local f_central="${tmp_dir}/central.txt"
|
||||
local f_erp="${tmp_dir}/erp.txt"
|
||||
local f_pg="${tmp_dir}/pg.txt"
|
||||
local f_other="${tmp_dir}/other.txt"
|
||||
|
||||
touch "${f_openclaw}" "${f_hxops}" "${f_central}" "${f_erp}" "${f_pg}" "${f_other}"
|
||||
|
||||
local matched=0
|
||||
while IFS=$'\t' read -r pid user cmd endpoint; do
|
||||
[[ -z "${pid}" ]] && continue
|
||||
|
||||
local full_cmd bin_path
|
||||
full_cmd="$(ps -p "${pid}" -o command= 2>/dev/null || true)"
|
||||
bin_path="${full_cmd%% *}"
|
||||
|
||||
# 过滤典型系统账号与系统二进制路径
|
||||
if [[ "${user}" == _* ]]; then
|
||||
continue
|
||||
fi
|
||||
if [[ "${bin_path}" == /System/* || "${bin_path}" == /usr/libexec/* ]]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# 过滤常见 macOS 系统守护进程
|
||||
case "${cmd}" in
|
||||
launchd|syslogd|mDNSResponder|distnoted|notifyd|powerd|configd|kernelmanagerd|airportd|\
|
||||
cfprefsd|sharingd|trustd|identityservicesd|ControlCe|rapportd|runningboardd|\
|
||||
UserEventAgent|logd|securityd|opendirectoryd)
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
local port group target_file
|
||||
port="${endpoint##*:}"
|
||||
|
||||
if [[ "${port}" == "18789" || "${cmd}" == "DingTalk" ]]; then
|
||||
group="openclaw"
|
||||
target_file="${f_openclaw}"
|
||||
elif [[ "${port}" == "8881" ]]; then
|
||||
group="hxops"
|
||||
target_file="${f_hxops}"
|
||||
elif [[ "${port}" == "8891" ]]; then
|
||||
group="Central-Auth-Core"
|
||||
target_file="${f_central}"
|
||||
elif [[ "${port}" == "8892" ]]; then
|
||||
group="ERP-Data-Agent"
|
||||
target_file="${f_erp}"
|
||||
elif [[ "${port}" == "5432" ]]; then
|
||||
group="postgresql"
|
||||
target_file="${f_pg}"
|
||||
else
|
||||
group="其它服务"
|
||||
target_file="${f_other}"
|
||||
fi
|
||||
|
||||
printf "%-20s %-10s %-8s %-24s %-18s\n" "${cmd}" "${user}" "${pid}" "${endpoint}" "${port}" >> "${target_file}"
|
||||
matched=1
|
||||
done <<< "${rows}"
|
||||
|
||||
if [[ "${matched}" -eq 0 ]]; then
|
||||
echo "未发现非系统监听端口。"
|
||||
return
|
||||
fi
|
||||
|
||||
print_group() {
|
||||
local title="$1"
|
||||
local file="$2"
|
||||
[[ ! -s "${file}" ]] && return
|
||||
echo ""
|
||||
echo "[$title]"
|
||||
printf "%-20s %-10s %-8s %-24s %-18s\n" "进程名" "用户" "PID" "监听地址" "端口"
|
||||
printf "%-20s %-10s %-8s %-24s %-18s\n" "--------------------" "----------" "--------" "------------------------" "------------------"
|
||||
cat "${file}"
|
||||
}
|
||||
|
||||
print_group "openclaw" "${f_openclaw}"
|
||||
print_group "hxops" "${f_hxops}"
|
||||
print_group "Central-Auth-Core" "${f_central}"
|
||||
print_group "ERP-Data-Agent" "${f_erp}"
|
||||
print_group "postgresql" "${f_pg}"
|
||||
print_group "其它服务" "${f_other}"
|
||||
}
|
||||
|
||||
show_local_changes_detail() {
|
||||
echo "=== 本地改动详情(相对上游分支 @{u}) ==="
|
||||
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "当前目录不是 Git 仓库。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local branch upstream
|
||||
branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
|
||||
upstream="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
|
||||
|
||||
if [[ -z "${upstream}" ]]; then
|
||||
echo "当前分支 ${branch} 未设置上游分支,无法执行: git diff --stat @{u}.."
|
||||
echo "可先执行: git branch --set-upstream-to origin/${branch} ${branch}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "当前分支: ${branch}"
|
||||
echo "上游分支: ${upstream}"
|
||||
echo ""
|
||||
|
||||
echo "== 统计(git diff --stat @{u}..) =="
|
||||
git -C "${ROOT_DIR}" -c color.ui=always diff --stat --color=always '@{u}..' || true
|
||||
|
||||
local tracked_files
|
||||
tracked_files="$(git -C "${ROOT_DIR}" diff --name-only '@{u}..' || true)"
|
||||
if [[ -z "${tracked_files}" ]]; then
|
||||
echo ""
|
||||
echo "当前相对 ${upstream} 没有改动。"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "== 文件改动内容(彩色) =="
|
||||
while IFS= read -r f; do
|
||||
[[ -z "${f}" ]] && continue
|
||||
echo ""
|
||||
echo "---- ${f} ----"
|
||||
git -C "${ROOT_DIR}" -c color.ui=always diff --color=always '@{u}..' -- "${f}" || true
|
||||
done <<< "${tracked_files}"
|
||||
}
|
||||
|
||||
show_remote_branch_changes_detail() {
|
||||
echo "=== 远端分支改动详情(仅远端新增) ==="
|
||||
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "当前目录不是 Git 仓库。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local current_branch target_branch remote_ref
|
||||
current_branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
|
||||
read -r -p "请输入远端分支名(默认 ${current_branch}): " target_branch
|
||||
target_branch="${target_branch:-${current_branch}}"
|
||||
remote_ref="origin/${target_branch}"
|
||||
|
||||
if ! git -C "${ROOT_DIR}" fetch origin "${target_branch}" --prune >/dev/null 2>&1; then
|
||||
echo "警告: 拉取 origin/${target_branch} 失败,尝试使用本地已缓存的远端引用继续。"
|
||||
fi
|
||||
|
||||
if ! git -C "${ROOT_DIR}" show-ref --verify --quiet "refs/remotes/${remote_ref}"; then
|
||||
echo "未找到本地远端引用 ${remote_ref}。"
|
||||
echo "请先确认分支存在,或手动执行: git fetch origin ${target_branch}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local remote_numstat remote_files
|
||||
remote_numstat="$(git -C "${ROOT_DIR}" diff --numstat HEAD..${remote_ref} || true)"
|
||||
remote_files="$(git -C "${ROOT_DIR}" diff --name-only HEAD..${remote_ref} || true)"
|
||||
|
||||
if [[ -z "${remote_files}" ]]; then
|
||||
echo "远端分支相对本地 HEAD 没有新增改动。"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "== 远端相对本地的文件与行数统计 =="
|
||||
printf "%-10s %-10s %s\n" "ADDED" "DELETED" "FILE"
|
||||
printf "%-10s %-10s %s\n" "----------" "----------" "------------------------------"
|
||||
echo "${remote_numstat}" | awk '{printf "%-10s %-10s %s\n", $1, $2, $3}'
|
||||
echo ""
|
||||
|
||||
echo "== 远端新增提交(HEAD..${remote_ref}) =="
|
||||
git -C "${ROOT_DIR}" log --oneline --decorate HEAD..${remote_ref} | sed -n '1,200p'
|
||||
echo ""
|
||||
|
||||
echo "== 远端每个文件改动内容(HEAD..${remote_ref}) =="
|
||||
while IFS= read -r f; do
|
||||
[[ -z "${f}" ]] && continue
|
||||
echo ""
|
||||
echo "---- ${f} ----"
|
||||
git -C "${ROOT_DIR}" diff --no-color HEAD..${remote_ref} -- "${f}" || true
|
||||
done <<< "${remote_files}"
|
||||
}
|
||||
|
||||
show_local_remote_compare() {
|
||||
echo "=== 本地与远端差异对比(直观) ==="
|
||||
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "当前目录不是 Git 仓库。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local current_branch target_branch remote_ref
|
||||
current_branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD)"
|
||||
read -r -p "请输入远端分支名(默认 ${current_branch}): " target_branch
|
||||
target_branch="${target_branch:-${current_branch}}"
|
||||
remote_ref="origin/${target_branch}"
|
||||
|
||||
if ! git -C "${ROOT_DIR}" fetch origin "${target_branch}" --prune >/dev/null 2>&1; then
|
||||
echo "警告: 拉取 origin/${target_branch} 失败,尝试使用本地已缓存的远端引用继续。"
|
||||
fi
|
||||
|
||||
if ! git -C "${ROOT_DIR}" show-ref --verify --quiet "refs/remotes/${remote_ref}"; then
|
||||
echo "未找到本地远端引用 ${remote_ref}。"
|
||||
echo "请先确认分支存在,或手动执行: git fetch origin ${target_branch}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local ahead behind
|
||||
read -r ahead behind < <(git -C "${ROOT_DIR}" rev-list --left-right --count HEAD...${remote_ref})
|
||||
echo "对比分支: HEAD vs ${remote_ref}"
|
||||
echo "本地领先: ${ahead} 个提交"
|
||||
echo "远端领先: ${behind} 个提交"
|
||||
echo ""
|
||||
|
||||
echo "== 本地独有提交(${remote_ref}..HEAD) =="
|
||||
git -C "${ROOT_DIR}" log --oneline --decorate "${remote_ref}..HEAD" | sed -n '1,120p'
|
||||
echo ""
|
||||
|
||||
echo "== 远端独有提交(HEAD..${remote_ref}) =="
|
||||
git -C "${ROOT_DIR}" log --oneline --decorate "HEAD..${remote_ref}" | sed -n '1,120p'
|
||||
echo ""
|
||||
|
||||
echo "== 双向文件统计(git diff --stat HEAD...${remote_ref}) =="
|
||||
git -C "${ROOT_DIR}" diff --stat HEAD..."${remote_ref}" || true
|
||||
echo ""
|
||||
|
||||
echo "== 本地相对远端的改动(${remote_ref}..HEAD) =="
|
||||
git -C "${ROOT_DIR}" diff --stat "${remote_ref}..HEAD" || true
|
||||
echo ""
|
||||
echo "== 远端相对本地的改动(HEAD..${remote_ref}) =="
|
||||
git -C "${ROOT_DIR}" diff --stat "HEAD..${remote_ref}" || true
|
||||
}
|
||||
|
||||
show_all_branches_info() {
|
||||
echo "=== 分支总览(本地 + 远端) ==="
|
||||
if ! git -C "${ROOT_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
echo "当前目录不是 Git 仓库。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local current_branch local_default remote_default
|
||||
current_branch="$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD 2>/dev/null || echo '-')"
|
||||
local_default="$(git -C "${ROOT_DIR}" symbolic-ref --short refs/heads/main 2>/dev/null || true)"
|
||||
if [[ -z "${local_default}" ]]; then
|
||||
local_default="$(git -C "${ROOT_DIR}" symbolic-ref --short refs/heads/master 2>/dev/null || true)"
|
||||
fi
|
||||
remote_default="$(git -C "${ROOT_DIR}" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)"
|
||||
|
||||
if ! git -C "${ROOT_DIR}" fetch origin --prune >/dev/null 2>&1; then
|
||||
echo "警告: fetch origin 失败,将基于当前本地缓存的远端分支信息展示。"
|
||||
fi
|
||||
|
||||
echo "== 本地分支 =="
|
||||
echo "当前分支: ${current_branch}"
|
||||
if [[ -n "${local_default}" ]]; then
|
||||
echo "本地默认分支(按 main/master 识别): ${local_default}"
|
||||
else
|
||||
echo "本地默认分支: 未识别(可按团队约定确认)"
|
||||
fi
|
||||
git -C "${ROOT_DIR}" branch -vv
|
||||
echo ""
|
||||
|
||||
echo "== 远端分支(origin) =="
|
||||
if [[ -n "${remote_default}" ]]; then
|
||||
echo "远端默认分支: ${remote_default}"
|
||||
else
|
||||
echo "远端默认分支: 未识别(可执行 git remote set-head origin -a 后重试)"
|
||||
fi
|
||||
git -C "${ROOT_DIR}" branch -r
|
||||
}
|
||||
|
||||
run_schema_drift_check() {
|
||||
echo "=== 检查数据库结构与 SQLAlchemy 模型是否一致 ==="
|
||||
local python_bin="${BACKEND_DIR}/venv/bin/python3"
|
||||
local check_script="${BACKEND_DIR}/scripts/check_schema_drift.py"
|
||||
|
||||
if [[ ! -x "${python_bin}" ]]; then
|
||||
echo "未找到 Python: ${python_bin}"
|
||||
return 1
|
||||
fi
|
||||
if [[ ! -f "${check_script}" ]]; then
|
||||
echo "未找到检查脚本: ${check_script}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
(
|
||||
cd "${BACKEND_DIR}"
|
||||
"${python_bin}" "scripts/check_schema_drift.py"
|
||||
)
|
||||
}
|
||||
|
||||
run_ci_migration_check() {
|
||||
echo "=== 运行 CI 同款 migration 漂移检查 ==="
|
||||
local check_script="${BACKEND_DIR}/scripts/ci_check_migrations.sh"
|
||||
if [[ ! -x "${check_script}" ]]; then
|
||||
echo "未找到可执行脚本: ${check_script}"
|
||||
echo "可先执行: chmod +x ${check_script}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
(
|
||||
cd "${BACKEND_DIR}"
|
||||
"${check_script}"
|
||||
)
|
||||
}
|
||||
|
||||
install_precommit_hook() {
|
||||
echo "=== 安装 Git pre-commit Hook ==="
|
||||
local install_script="${ROOT_DIR}/scripts/install_git_hooks.sh"
|
||||
if [[ ! -x "${install_script}" ]]; then
|
||||
echo "未找到可执行脚本: ${install_script}"
|
||||
echo "可先执行: chmod +x ${install_script}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
(
|
||||
cd "${ROOT_DIR}"
|
||||
"${install_script}"
|
||||
)
|
||||
}
|
||||
|
||||
show_help() {
|
||||
cat <<'HELP'
|
||||
可输入的指令与结果:
|
||||
start 或 1 -> 启动项目(数据库+后端+前端)
|
||||
stop 或 2 -> 关闭项目(后端+前端+数据库)
|
||||
push 或 3 -> 提交并上传到 Gitee(origin)
|
||||
status或 4 -> 查看服务运行状态
|
||||
ports 或 5 -> 扫描当前用户开启的开发服务端口
|
||||
allports或 6 -> 扫描所有非系统监听端口(应用/自装服务)
|
||||
localchg或 31 -> 查看本地改了哪些文件/多少行/逐文件改动
|
||||
remotechg或 32 -> 只查看远端分支改了哪些文件/多少行/逐文件改动
|
||||
compare 或 33 -> 直观对比本地与远端差异(领先提交、双向改动)
|
||||
branches或 34 -> 查看本地所有分支及默认分支、远端所有分支及默认分支
|
||||
dbdrift或 41 -> 检查当前数据库结构与 SQLAlchemy 模型是否一致
|
||||
migci 或 42 -> 运行 CI 同款迁移一致性检查(空库升级+漂移检测)
|
||||
hook 或 43 -> 安装 pre-commit Hook(改 models 必须带 migration)
|
||||
help 或 9 -> 再次显示本帮助
|
||||
help -> 再次显示本帮助
|
||||
exit 或 0 -> 退出脚本
|
||||
HELP
|
||||
}
|
||||
|
||||
confirm_and_run() {
|
||||
local label="$1"
|
||||
local fn_name="$2"
|
||||
|
||||
read -r -p "确认执行【${label}】? (y/N): " confirm
|
||||
if [[ "${confirm}" =~ ^[Yy]$ ]]; then
|
||||
"${fn_name}"
|
||||
else
|
||||
echo "已取消【${label}】。"
|
||||
fi
|
||||
}
|
||||
|
||||
main_loop() {
|
||||
echo "===== HXOPS 单脚本控制台 ====="
|
||||
show_help
|
||||
|
||||
while true; do
|
||||
echo ""
|
||||
read -r -p "请输入指令: " cmd
|
||||
case "${cmd}" in
|
||||
1|start)
|
||||
confirm_and_run "启动项目" start_project
|
||||
;;
|
||||
2|stop)
|
||||
confirm_and_run "关闭项目" stop_project
|
||||
;;
|
||||
3|push)
|
||||
confirm_and_run "上传到 Gitee" push_gitee
|
||||
;;
|
||||
4|status)
|
||||
show_status
|
||||
;;
|
||||
5|ports|scan)
|
||||
show_dev_open_ports
|
||||
;;
|
||||
6|allports)
|
||||
show_non_system_open_ports
|
||||
;;
|
||||
31|localchg)
|
||||
show_local_changes_detail
|
||||
;;
|
||||
32|remotechg)
|
||||
show_remote_branch_changes_detail
|
||||
;;
|
||||
33|compare)
|
||||
show_local_remote_compare
|
||||
;;
|
||||
34|branches)
|
||||
show_all_branches_info
|
||||
;;
|
||||
41|dbdrift)
|
||||
run_schema_drift_check
|
||||
;;
|
||||
42|migci)
|
||||
confirm_and_run "CI同款迁移一致性检查" run_ci_migration_check
|
||||
;;
|
||||
43|hook)
|
||||
confirm_and_run "安装 pre-commit Hook" install_precommit_hook
|
||||
;;
|
||||
9|help)
|
||||
show_help
|
||||
;;
|
||||
0|exit|quit)
|
||||
echo "已退出。"
|
||||
exit 0
|
||||
;;
|
||||
"")
|
||||
echo "请输入有效指令,输入 help 可查看可用命令。"
|
||||
;;
|
||||
*)
|
||||
echo "未知指令: ${cmd},输入 help 可查看可用命令。"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
main_loop
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# 参数说明:
|
||||
# 1: 环境名(dev/test/prod)
|
||||
# 2: 前端镜像名(可空;非空表示使用预构建镜像)
|
||||
# 3: 后端镜像名(可空;非空表示使用预构建镜像)
|
||||
# 4: 前端是否有变更(true/false)
|
||||
# 5: 后端是否有变更(true/false)
|
||||
# 6: 部署配置是否有变更(true/false)
|
||||
ENV_NAME="${1:-default}"
|
||||
FRONTEND_IMAGE="${2:-}"
|
||||
BACKEND_IMAGE="${3:-}"
|
||||
FRONTEND_CHANGED="${4:-false}"
|
||||
BACKEND_CHANGED="${5:-false}"
|
||||
DEPLOY_CONFIG_CHANGED="${6:-false}"
|
||||
|
||||
# 统一使用仓库根目录下的 compose 和环境文件
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
COMPOSE_FILE="${ROOT_DIR}/docker-compose.yml"
|
||||
ENV_FILE="${ROOT_DIR}/.env.${ENV_NAME}"
|
||||
|
||||
# 基础文件检查:compose 文件必须存在
|
||||
if [[ ! -f "${COMPOSE_FILE}" ]]; then
|
||||
echo "Missing compose file: ${COMPOSE_FILE}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 环境配置检查:不同环境对应不同 .env 文件
|
||||
if [[ ! -f "${ENV_FILE}" ]]; then
|
||||
echo "Missing env file for environment '${ENV_NAME}': ${ENV_FILE}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 兼容 docker compose(v2) 与 docker-compose(v1)
|
||||
if docker compose version >/dev/null 2>&1; then
|
||||
DC_CMD=(docker compose)
|
||||
elif command -v docker-compose >/dev/null 2>&1; then
|
||||
DC_CMD=(docker-compose)
|
||||
else
|
||||
echo "Missing docker compose command. Install docker compose plugin or docker-compose."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Using compose command: ${DC_CMD[*]}"
|
||||
echo "Using env file: ${ENV_FILE}"
|
||||
|
||||
declare -a compose_args=(-f "${COMPOSE_FILE}" --env-file "${ENV_FILE}")
|
||||
|
||||
# 当传入镜像名时,认为是“预构建镜像模式”
|
||||
# 该模式下只拉起容器,不在目标机重新构建
|
||||
PREBUILT_MODE="false"
|
||||
if [[ -n "${FRONTEND_IMAGE}" || -n "${BACKEND_IMAGE}" ]]; then
|
||||
PREBUILT_MODE="true"
|
||||
fi
|
||||
|
||||
# 将镜像标签导出给 docker-compose.yml 使用(image: ${FRONTEND_IMAGE} / ${BACKEND_IMAGE})
|
||||
if [[ -n "${FRONTEND_IMAGE}" ]]; then
|
||||
export FRONTEND_IMAGE
|
||||
fi
|
||||
if [[ -n "${BACKEND_IMAGE}" ]]; then
|
||||
export BACKEND_IMAGE
|
||||
fi
|
||||
|
||||
cd "${ROOT_DIR}"
|
||||
|
||||
# 根据变更范围决定要更新的服务,实现前后端增量部署
|
||||
services=()
|
||||
if [[ "${FRONTEND_CHANGED}" == "true" ]]; then
|
||||
services+=("hxops-frontend")
|
||||
fi
|
||||
if [[ "${BACKEND_CHANGED}" == "true" ]]; then
|
||||
services+=("hxops-backend")
|
||||
fi
|
||||
|
||||
# 如果只是部署配置变更(如 compose/env/脚本),但前后端代码未改,则两边都更新
|
||||
if [[ ${#services[@]} -eq 0 && "${DEPLOY_CONFIG_CHANGED}" == "true" ]]; then
|
||||
services=("hxops-frontend" "hxops-backend")
|
||||
fi
|
||||
|
||||
# 无变更则直接跳过,避免无意义重启
|
||||
if [[ ${#services[@]} -eq 0 ]]; then
|
||||
echo "No service changes detected, skipping deployment."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Deploying environment: ${ENV_NAME}"
|
||||
echo "Services: ${services[*]}"
|
||||
echo "Prebuilt image mode: ${PREBUILT_MODE}"
|
||||
|
||||
# 预构建镜像模式:只启动,不构建
|
||||
# 非预构建镜像模式:在目标机本地构建并启动
|
||||
if [[ "${PREBUILT_MODE}" == "true" ]]; then
|
||||
"${DC_CMD[@]}" "${compose_args[@]}" up -d --no-build "${services[@]}"
|
||||
else
|
||||
"${DC_CMD[@]}" "${compose_args[@]}" up -d --build "${services[@]}"
|
||||
fi
|
||||
|
||||
# Keep DB schema aligned with backend code after deployment.
|
||||
if printf '%s\n' "${services[@]}" | grep -qx "hxops-backend"; then
|
||||
echo "Running database migrations (flask db upgrade)..."
|
||||
"${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend flask --app manage.py db upgrade
|
||||
fi
|
||||
|
||||
"${ROOT_DIR}/scripts/healthcheck.sh" "${ENV_NAME}" "${COMPOSE_FILE}" "${ENV_FILE}"
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ENV_NAME="${1:-default}"
|
||||
COMPOSE_FILE="${2:?Compose file path required}"
|
||||
ENV_FILE="${3:-}"
|
||||
|
||||
if docker compose version >/dev/null 2>&1; then
|
||||
DC_CMD=(docker compose)
|
||||
elif command -v docker-compose >/dev/null 2>&1; then
|
||||
DC_CMD=(docker-compose)
|
||||
else
|
||||
echo "Missing docker compose command. Install docker compose plugin or docker-compose."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
declare -a compose_args=(-f "${COMPOSE_FILE}")
|
||||
if [[ -n "${ENV_FILE}" && -f "${ENV_FILE}" ]]; then
|
||||
compose_args+=(--env-file "${ENV_FILE}")
|
||||
fi
|
||||
|
||||
max_attempts=20
|
||||
sleep_seconds=3
|
||||
|
||||
for ((i=1; i<=max_attempts; i++)); do
|
||||
status=$("${DC_CMD[@]}" "${compose_args[@]}" ps --status running --services | wc -l)
|
||||
if [[ "${status}" -ge 2 ]]; then
|
||||
echo "Healthcheck passed for ${ENV_NAME} environment."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Healthcheck waiting (${i}/${max_attempts})..."
|
||||
sleep "${sleep_seconds}"
|
||||
done
|
||||
|
||||
echo "Healthcheck failed for ${ENV_NAME} environment."
|
||||
"${DC_CMD[@]}" "${compose_args[@]}" ps
|
||||
exit 1
|
||||
Reference in new issue
Block a user