Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c71f27072a | |||
| 22a109d6c0 | |||
| 0244715a8a | |||
| 1c3f7604c9 | |||
| 0086eaa1d6 | |||
| 8e17ef5e15 | |||
| 773fb89b01 | |||
| 8199773ef6 | |||
| d153986f3d | |||
| e9357577cb | |||
| 24ba04b3e3 | |||
| d1ddd340c0 | |||
| 6ab58cb363 | |||
| ba8d0ae679 | |||
| 52d98e88c6 | |||
| 25dff98583 | |||
| 6452e4c976 | |||
| f85991064f |
749
backend/app.py
749
backend/app.py
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AI Chat App - 后台管理服务
|
||||
端口: 19020 (与前端同一端口)
|
||||
端口: 19021 (与前端同一端口)
|
||||
"""
|
||||
|
||||
from flask import Flask, jsonify, request, send_from_directory
|
||||
@@ -11,6 +11,7 @@ import json
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import base64
|
||||
|
||||
app = Flask(__name__, static_folder='../www')
|
||||
CORS(app)
|
||||
@@ -18,6 +19,11 @@ CORS(app)
|
||||
# 数据库路径
|
||||
DB_PATH = os.path.join(os.path.dirname(__file__), 'data.db')
|
||||
|
||||
# 头像存储目录
|
||||
AVATAR_DIR = os.path.join(os.path.dirname(__file__), 'avatars')
|
||||
if not os.path.exists(AVATAR_DIR):
|
||||
os.makedirs(AVATAR_DIR)
|
||||
|
||||
# 管理员账户(默认)
|
||||
ADMIN_USERNAME = 'admin'
|
||||
ADMIN_PASSWORD_HASH = hashlib.sha256('admin123'.encode()).hexdigest()
|
||||
@@ -66,9 +72,10 @@ def init_db():
|
||||
llm_config_id INTEGER,
|
||||
temperature REAL DEFAULT 0.7,
|
||||
max_tokens INTEGER DEFAULT 2048,
|
||||
enable_search INTEGER DEFAULT 0,
|
||||
enable_tools TEXT,
|
||||
tags TEXT,
|
||||
heat INTEGER DEFAULT 0,
|
||||
is_online INTEGER DEFAULT 1,
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -146,6 +153,54 @@ def init_db():
|
||||
)
|
||||
''')
|
||||
|
||||
# 用户表(前端注册用户)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
phone TEXT NOT NULL UNIQUE,
|
||||
email TEXT,
|
||||
avatar TEXT DEFAULT '👤',
|
||||
signature TEXT,
|
||||
gender TEXT,
|
||||
age INTEGER,
|
||||
region TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
last_login_at TIMESTAMP
|
||||
)
|
||||
''')
|
||||
|
||||
# 用户智能体配置表(我的智能体)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS user_agents (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
agent_id TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
is_pinned INTEGER DEFAULT 0,
|
||||
is_favorite INTEGER DEFAULT 0,
|
||||
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
UNIQUE(user_id, agent_id)
|
||||
)
|
||||
''')
|
||||
|
||||
# 对话表(用户对话数据)
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS conversations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
agent_id TEXT,
|
||||
messages TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
)
|
||||
''')
|
||||
|
||||
# 初始化默认大模型配置
|
||||
cursor.execute('SELECT COUNT(*) FROM llm_configs')
|
||||
if cursor.fetchone()[0] == 0:
|
||||
@@ -176,24 +231,28 @@ def init_db():
|
||||
cursor.execute('SELECT COUNT(*) FROM agents')
|
||||
if cursor.fetchone()[0] == 0:
|
||||
default_agents = [
|
||||
('assistant', '通用助手', '🤖', 'hot', '能回答各类问题,帮助写作、分析、解答疑惑', '你是一个智能助手,能够回答各类问题,帮助用户解决问题。', 9500),
|
||||
('writer', '写作助手', '✍️', 'hot', '专注于文章写作、文案创作、内容润色', '你是一个专业的写作助手,擅长各类文章写作、文案创作和内容润色。', 8800),
|
||||
('coder', '编程助手', '👨💻', 'hot', '精通编程语言,解答技术问题,生成代码', '你是一个专业的编程助手,精通各类编程语言,能够解答技术问题并生成高质量代码。', 8500),
|
||||
('translator', '翻译助手', '🌐', 'hot', '多语言翻译,精准表达,文化适配', '你是一个专业的翻译助手,精通多语言翻译,能够精准表达并适配文化差异。', 7200),
|
||||
('work', '工作助手', '💼', 'work', '职场问题解答,工作效率提升', '你是一个工作助手,帮助解决职场问题,提升工作效率。', 5000),
|
||||
('ppt', 'PPT助手', '📊', 'work', 'PPT内容生成,结构优化,设计建议', '你是一个PPT助手,擅长PPT内容生成、结构优化和设计建议。', 4500),
|
||||
('excel', 'Excel助手', '📈', 'work', 'Excel公式、数据分析、表格优化', '你是一个Excel助手,精通Excel公式、数据分析和表格优化。', 4000),
|
||||
('teacher', '学习助手', '📚', 'study', '知识讲解,学习方法,考试辅导', '你是一个学习助手,擅长知识讲解、学习方法指导和考试辅导。', 5500),
|
||||
('english', '英语助手', '🔤', 'study', '英语学习,语法纠正,口语练习', '你是一个英语助手,帮助英语学习、语法纠正和口语练习。', 5000),
|
||||
('math', '数学助手', '🔢', 'study', '数学解题,公式推导,概念讲解', '你是一个数学助手,擅长数学解题、公式推导和概念讲解。', 4500),
|
||||
('health', '健康助手', '🏥', 'life', '健康咨询,养生建议,运动指导', '你是一个健康助手,提供健康咨询、养生建议和运动指导。', 3500),
|
||||
('travel', '旅行助手', '✈️', 'life', '旅行规划,景点推荐,美食指南', '你是一个旅行助手,擅长旅行规划、景点推荐和美食指南。', 3200),
|
||||
('food', '美食助手', '🍳', 'life', '菜谱推荐,烹饪技巧,营养搭配', '你是一个美食助手,提供菜谱推荐、烹饪技巧和营养搭配建议。', 3000),
|
||||
# 基础类别
|
||||
('assistant', '通用助手', '🤖', 'basic', '能回答各类问题,帮助写作、分析、解答疑惑', '你是一个智能助手,能够回答各类问题,帮助用户解决问题。', 'hot', 9500),
|
||||
('writer', '写作助手', '✍️', 'basic', '专注于文章写作、文案创作、内容润色', '你是一个专业的写作助手,擅长各类文章写作、文案创作和内容润色。', 'hot', 8800),
|
||||
('coder', '编程助手', '👨💻', 'basic', '精通编程语言,解答技术问题,生成代码', '你是一个专业的编程助手,精通各类编程语言,能够解答技术问题并生成高质量代码。', 'hot', 8500),
|
||||
('translator', '翻译助手', '🌐', 'basic', '多语言翻译,精准表达,文化适配', '你是一个专业的翻译助手,精通多语言翻译,能够精准表达并适配文化差异。', 'hot', 7200),
|
||||
# 工作类别
|
||||
('work', '工作助手', '💼', 'work', '职场问题解答,工作效率提升', '你是一个工作助手,帮助解决职场问题,提升工作效率。', 'popular', 5000),
|
||||
('ppt', 'PPT助手', '📊', 'work', 'PPT内容生成,结构优化,设计建议', '你是一个PPT助手,擅长PPT内容生成、结构优化和设计建议。', 'popular', 4500),
|
||||
('excel', 'Excel助手', '📈', 'work', 'Excel公式、数据分析、表格优化', '你是一个Excel助手,精通Excel公式、数据分析和表格优化。', '', 4000),
|
||||
# 学习类别
|
||||
('teacher', '学习助手', '📚', 'study', '知识讲解,学习方法,考试辅导', '你是一个学习助手,擅长知识讲解、学习方法指导和考试辅导。', 'popular', 5500),
|
||||
('english', '英语助手', '🔤', 'study', '英语学习,语法纠正,口语练习', '你是一个英语助手,帮助英语学习、语法纠正和口语练习。', '', 5000),
|
||||
('math', '数学助手', '🔢', 'study', '数学解题,公式推导,概念讲解', '你是一个数学助手,擅长数学解题、公式推导和概念讲解。', '', 4500),
|
||||
# 生活类别
|
||||
('health', '健康助手', '🏥', 'life', '健康咨询,养生建议,运动指导', '你是一个健康助手,提供健康咨询、养生建议和运动指导。', '', 3500),
|
||||
('travel', '旅行助手', '✈️', 'life', '旅行规划,景点推荐,美食指南', '你是一个旅行助手,擅长旅行规划、景点推荐和美食指南。', 'popular', 3200),
|
||||
('food', '美食助手', '🍳', 'life', '菜谱推荐,烹饪技巧,营养搭配', '你是一个美食助手,提供菜谱推荐、烹饪技巧和营养搭配建议。', '', 3000),
|
||||
]
|
||||
for agent in default_agents:
|
||||
cursor.execute('''
|
||||
INSERT INTO agents (agent_id, name, avatar, category, description, system_prompt, heat)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO agents (agent_id, name, avatar, category, description, system_prompt, tags, heat, is_online)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
|
||||
''', agent)
|
||||
|
||||
# 初始化系统配置
|
||||
@@ -201,13 +260,19 @@ def init_db():
|
||||
if cursor.fetchone()[0] == 0:
|
||||
default_configs = [
|
||||
('app_name', 'AI助手', '应用名称'),
|
||||
('app_version', '3.5.1', '应用版本'),
|
||||
('app_version', '3.10.0', '应用版本'),
|
||||
('llm_provider', 'zhipu', '默认大模型提供商'),
|
||||
('enable_search', 'true', '是否启用联网搜索'),
|
||||
('guest_chat_sessions', '1', '游客每日对话会话限制'),
|
||||
('guest_chat_messages', '20', '游客每日对话消息限制'),
|
||||
('guest_agent_messages', '20', '游客每日智能体消息限制'),
|
||||
('admin_password', 'admin123', '管理员密码'),
|
||||
('app_developer', 'OpenClaw Team', '开发者'),
|
||||
('app_update_date', '2026-04-27', '更新日期'),
|
||||
('app_technology', '智谱 GLM-4.5-Air 大模型', '技术基础'),
|
||||
('app_description', '提供智能对话、多种智能体服务', '应用简介'),
|
||||
('privacy_policy_url', '', '隐私政策链接'),
|
||||
('user_agreement_url', '', '用户协议链接'),
|
||||
]
|
||||
for key, value, desc in default_configs:
|
||||
cursor.execute('INSERT INTO system_configs (key, value, description) VALUES (?, ?, ?)', (key, value, desc))
|
||||
@@ -290,6 +355,615 @@ def admin_login():
|
||||
return jsonify({'error': '用户名或密码错误'}), 401
|
||||
|
||||
|
||||
# ==================== 用户管理 ====================
|
||||
|
||||
@app.route('/api/register', methods=['POST'])
|
||||
def user_register():
|
||||
"""用户注册"""
|
||||
data = request.json
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
phone = data.get('phone')
|
||||
email = data.get('email')
|
||||
code = data.get('code') # 验证码(暂时只校验格式)
|
||||
|
||||
# 参数验证
|
||||
if not username or not password or not phone:
|
||||
return jsonify({'error': '请填写完整信息'}), 400
|
||||
|
||||
# 用户名长度检查
|
||||
if len(username) < 2 or len(username) > 20:
|
||||
return jsonify({'error': '用户名长度应为2-20字符'}), 400
|
||||
|
||||
# 手机号格式检查
|
||||
import re
|
||||
if not re.match(r'^1[3-9]\d{9}$', phone):
|
||||
return jsonify({'error': '手机号格式不正确'}), 400
|
||||
|
||||
# 验证码检查(模拟,6位数字)
|
||||
if not code or not re.match(r'^\d{6}$', code):
|
||||
return jsonify({'error': '验证码格式不正确'}), 400
|
||||
|
||||
# 邮箱格式检查(可选)
|
||||
if email and not re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', email):
|
||||
return jsonify({'error': '邮箱格式不正确'}), 400
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查用户名是否已存在
|
||||
cursor.execute('SELECT id FROM users WHERE username = ?', (username,))
|
||||
if cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '用户名已存在'}), 400
|
||||
|
||||
# 检查手机号是否已存在
|
||||
cursor.execute('SELECT id FROM users WHERE phone = ?', (phone,))
|
||||
if cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '手机号已注册'}), 400
|
||||
|
||||
# 创建用户
|
||||
password_hash = hashlib.sha256(password.encode()).hexdigest()
|
||||
cursor.execute('''
|
||||
INSERT INTO users (username, password_hash, phone, email)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (username, password_hash, phone, email))
|
||||
|
||||
# 记录注册统计
|
||||
cursor.execute('INSERT INTO stats_logs (log_type, log_key) VALUES (?, ?)', ('user_register', 'new'))
|
||||
|
||||
conn.commit()
|
||||
user_id = cursor.lastrowid
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True, 'user_id': user_id})
|
||||
|
||||
|
||||
@app.route('/api/login', methods=['POST'])
|
||||
def user_login():
|
||||
"""用户登录"""
|
||||
data = request.json
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
if not username or not password:
|
||||
return jsonify({'error': '请输入用户名和密码'}), 400
|
||||
|
||||
password_hash = hashlib.sha256(password.encode()).hexdigest()
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('SELECT * FROM users WHERE username = ? AND password_hash = ?', (username, password_hash))
|
||||
user = cursor.fetchone()
|
||||
|
||||
if user:
|
||||
# 更新最后登录时间
|
||||
cursor.execute('UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ?', (user['id'],))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'user': {
|
||||
'id': user['id'],
|
||||
'username': user['username'],
|
||||
'phone': user['phone'],
|
||||
'email': user['email'],
|
||||
'avatar': user['avatar'],
|
||||
'signature': user['signature'],
|
||||
'gender': user['gender'],
|
||||
'age': user['age'],
|
||||
'region': user['region']
|
||||
}
|
||||
})
|
||||
else:
|
||||
conn.close()
|
||||
return jsonify({'error': '用户名或密码错误'}), 401
|
||||
|
||||
|
||||
@app.route('/api/admin/users', methods=['GET'])
|
||||
def get_users():
|
||||
"""获取用户列表"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 支持搜索
|
||||
search = request.args.get('search', '')
|
||||
if search:
|
||||
cursor.execute('''
|
||||
SELECT id, username, phone, email, avatar, signature, gender, age, region,
|
||||
created_at, last_login_at FROM users
|
||||
WHERE username LIKE ? OR phone LIKE ? OR email LIKE ?
|
||||
ORDER BY created_at DESC
|
||||
''', (f'%{search}%', f'%{search}%', f'%{search}%'))
|
||||
else:
|
||||
cursor.execute('''
|
||||
SELECT id, username, phone, email, avatar, signature, gender, age, region,
|
||||
created_at, last_login_at FROM users ORDER BY created_at DESC
|
||||
''')
|
||||
|
||||
users = [dict(row) for row in cursor.fetchall()]
|
||||
conn.close()
|
||||
return jsonify(users)
|
||||
|
||||
|
||||
@app.route('/api/admin/users/<int:id>', methods=['GET'])
|
||||
def get_user(id):
|
||||
"""获取单个用户"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('SELECT * FROM users WHERE id = ?', (id,))
|
||||
user = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
if user:
|
||||
return jsonify(dict(user))
|
||||
else:
|
||||
return jsonify({'error': '用户不存在'}), 404
|
||||
|
||||
|
||||
@app.route('/api/admin/users/<int:id>', methods=['PUT'])
|
||||
def update_user(id):
|
||||
"""更新用户信息"""
|
||||
data = request.json
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查用户是否存在
|
||||
cursor.execute('SELECT id FROM users WHERE id = ?', (id,))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '用户不存在'}), 404
|
||||
|
||||
# 检查用户名是否重复(如果要修改用户名)
|
||||
if data.get('username'):
|
||||
cursor.execute('SELECT id FROM users WHERE username = ? AND id != ?', (data['username'], id))
|
||||
if cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '用户名已存在'}), 400
|
||||
|
||||
# 更新用户信息
|
||||
cursor.execute('''
|
||||
UPDATE users SET username=?, email=?, avatar=?, signature=?, gender=?, age=?, region=?,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE id=?
|
||||
''', (data.get('username'), data.get('email'), data.get('avatar', '👤'),
|
||||
data.get('signature'), data.get('gender'), data.get('age'),
|
||||
data.get('region'), id))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/admin/users/<int:id>', methods=['DELETE'])
|
||||
def delete_user(id):
|
||||
"""删除用户"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('DELETE FROM users WHERE id = ?', (id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/admin/users/<int:id>/password', methods=['PUT'])
|
||||
def reset_user_password(id):
|
||||
"""重置用户密码"""
|
||||
data = request.json
|
||||
new_password = data.get('password')
|
||||
|
||||
if not new_password or len(new_password) < 6:
|
||||
return jsonify({'error': '密码长度至少6位'}), 400
|
||||
|
||||
password_hash = hashlib.sha256(new_password.encode()).hexdigest()
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?',
|
||||
(password_hash, id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:id>', methods=['PUT'])
|
||||
def update_user_profile(id):
|
||||
"""用户更新自己的资料"""
|
||||
data = request.json
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查用户是否存在
|
||||
cursor.execute('SELECT id FROM users WHERE id = ?', (id,))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '用户不存在'}), 404
|
||||
|
||||
# 更新用户资料
|
||||
cursor.execute('''
|
||||
UPDATE users SET avatar=?, signature=?, gender=?, age=?, region=?, email=?,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE id=?
|
||||
''', (data.get('avatar', '👤'), data.get('signature'), data.get('gender'),
|
||||
data.get('age'), data.get('region'), data.get('email'), id))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:id>/password', methods=['PUT'])
|
||||
def change_user_password(id):
|
||||
"""用户修改自己的密码"""
|
||||
data = request.json
|
||||
old_password = data.get('old_password')
|
||||
new_password = data.get('new_password')
|
||||
|
||||
if not old_password or not new_password:
|
||||
return jsonify({'error': '请输入旧密码和新密码'}), 400
|
||||
|
||||
if len(new_password) < 6:
|
||||
return jsonify({'error': '新密码长度至少6位'}), 400
|
||||
|
||||
old_hash = hashlib.sha256(old_password.encode()).hexdigest()
|
||||
new_hash = hashlib.sha256(new_password.encode()).hexdigest()
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 验证旧密码
|
||||
cursor.execute('SELECT id FROM users WHERE id = ? AND password_hash = ?', (id, old_hash))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '旧密码不正确'}), 400
|
||||
|
||||
# 更新密码
|
||||
cursor.execute('UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?',
|
||||
(new_hash, id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 用户头像上传 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/avatar', methods=['POST'])
|
||||
def upload_user_avatar(user_id):
|
||||
"""上传用户头像"""
|
||||
data = request.json
|
||||
avatar_data = data.get('avatar') # base64 格式图片
|
||||
|
||||
if not avatar_data:
|
||||
return jsonify({'error': '头像数据不能为空'}), 400
|
||||
|
||||
# 解析 base64 数据
|
||||
try:
|
||||
# 支持两种格式:
|
||||
# 1. data:image/png;base64,xxxxx
|
||||
# 2. 纯 base64 字符串
|
||||
|
||||
if avatar_data.startswith('data:'):
|
||||
# 提取格式和内容
|
||||
header, content = avatar_data.split(',', 1)
|
||||
# 提取图片格式
|
||||
mime_type = header.split(':')[1].split(';')[0]
|
||||
ext = mime_type.split('/')[1] if '/' in mime_type else 'png'
|
||||
else:
|
||||
content = avatar_data
|
||||
ext = 'png'
|
||||
|
||||
# 解码 base64
|
||||
image_bytes = base64.b64decode(content)
|
||||
|
||||
# 验证图片大小(最大 2MB)
|
||||
if len(image_bytes) > 2 * 1024 * 1024:
|
||||
return jsonify({'error': '头像大小不能超过2MB'}), 400
|
||||
|
||||
# 生成文件名
|
||||
filename = f'user_{user_id}_{int(datetime.now().timestamp())}.{ext}'
|
||||
filepath = os.path.join(AVATAR_DIR, filename)
|
||||
|
||||
# 保存文件
|
||||
with open(filepath, 'wb') as f:
|
||||
f.write(image_bytes)
|
||||
|
||||
# 更新数据库(存储文件名)
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('UPDATE users SET avatar=?, updated_at=CURRENT_TIMESTAMP WHERE id=?',
|
||||
(filename, user_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True, 'avatar': filename, 'avatar_url': f'/api/avatars/{filename}'})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'error': f'头像上传失败: {str(e)}'}), 500
|
||||
|
||||
|
||||
@app.route('/api/avatars/<filename>', methods=['GET'])
|
||||
def get_avatar(filename):
|
||||
"""获取头像图片"""
|
||||
return send_from_directory(AVATAR_DIR, filename)
|
||||
|
||||
|
||||
@app.route('/api/admin/users/<int:user_id>/avatar', methods=['POST'])
|
||||
def admin_upload_user_avatar(user_id):
|
||||
"""管理员上传用户头像"""
|
||||
return upload_user_avatar(user_id)
|
||||
|
||||
|
||||
# ==================== 用户对话数据同步 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations', methods=['GET'])
|
||||
def get_user_conversations(user_id):
|
||||
"""获取用户所有对话"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, title, agent_id, messages, created_at, updated_at
|
||||
FROM conversations WHERE user_id = ? ORDER BY updated_at DESC
|
||||
''', (user_id,))
|
||||
|
||||
conversations = []
|
||||
for row in cursor.fetchall():
|
||||
conv = dict(row)
|
||||
# 解析消息JSON
|
||||
try:
|
||||
conv['messages'] = json.loads(conv['messages']) if conv['messages'] else []
|
||||
except:
|
||||
conv['messages'] = []
|
||||
# 转换为前端格式(使用字符串ID)
|
||||
conv['id'] = str(conv['id'])
|
||||
conv['createdAt'] = int(datetime.strptime(conv['created_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['created_at'] else 0
|
||||
conv['updatedAt'] = int(datetime.strptime(conv['updated_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['updated_at'] else 0
|
||||
conv['agentId'] = conv['agent_id']
|
||||
conversations.append(conv)
|
||||
|
||||
conn.close()
|
||||
return jsonify(conversations)
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations/<int:conv_id>', methods=['GET'])
|
||||
def get_user_conversation_detail(user_id, conv_id):
|
||||
"""获取单个对话详情"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, title, agent_id, messages, created_at, updated_at
|
||||
FROM conversations WHERE id = ? AND user_id = ?
|
||||
''', (conv_id, user_id))
|
||||
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
if not row:
|
||||
return jsonify({'error': '对话不存在'}), 404
|
||||
|
||||
conv = dict(row)
|
||||
try:
|
||||
conv['messages'] = json.loads(conv['messages']) if conv['messages'] else []
|
||||
except:
|
||||
conv['messages'] = []
|
||||
|
||||
conv['id'] = str(conv['id'])
|
||||
conv['createdAt'] = int(datetime.strptime(conv['created_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['created_at'] else 0
|
||||
conv['updatedAt'] = int(datetime.strptime(conv['updated_at'], '%Y-%m-%d %H:%M:%S').timestamp() * 1000) if conv['updated_at'] else 0
|
||||
conv['agentId'] = conv['agent_id']
|
||||
|
||||
return jsonify(conv)
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations', methods=['POST'])
|
||||
def create_user_conversation(user_id):
|
||||
"""创建新对话"""
|
||||
data = request.json
|
||||
title = data.get('title', '新对话')
|
||||
agent_id = data.get('agentId') or data.get('agent_id')
|
||||
messages = data.get('messages', [])
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO conversations (user_id, title, agent_id, messages)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (user_id, title, agent_id, json.dumps(messages)))
|
||||
conn.commit()
|
||||
|
||||
conv_id = cursor.lastrowid
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True, 'id': str(conv_id)})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations/<int:conv_id>', methods=['PUT'])
|
||||
def update_user_conversation(user_id, conv_id):
|
||||
"""更新对话(添加消息、修改标题等)"""
|
||||
data = request.json
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 验证对话属于该用户
|
||||
cursor.execute('SELECT id FROM conversations WHERE id = ? AND user_id = ?', (conv_id, user_id))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '对话不存在'}), 404
|
||||
|
||||
# 更新字段
|
||||
updates = []
|
||||
values = []
|
||||
|
||||
if 'title' in data:
|
||||
updates.append('title = ?')
|
||||
values.append(data['title'])
|
||||
|
||||
if 'messages' in data:
|
||||
updates.append('messages = ?')
|
||||
values.append(json.dumps(data['messages']))
|
||||
|
||||
if 'agentId' in data or 'agent_id' in data:
|
||||
updates.append('agent_id = ?')
|
||||
values.append(data.get('agentId') or data.get('agent_id'))
|
||||
|
||||
if updates:
|
||||
updates.append('updated_at = CURRENT_TIMESTAMP')
|
||||
sql = f'UPDATE conversations SET {", ".join(updates)} WHERE id = ?'
|
||||
values.append(conv_id)
|
||||
cursor.execute(sql, values)
|
||||
conn.commit()
|
||||
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/conversations/<int:conv_id>', methods=['DELETE'])
|
||||
def delete_user_conversation(user_id, conv_id):
|
||||
"""删除对话"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 验证对话属于该用户
|
||||
cursor.execute('SELECT id FROM conversations WHERE id = ? AND user_id = ?', (conv_id, user_id))
|
||||
if not cursor.fetchone():
|
||||
conn.close()
|
||||
return jsonify({'error': '对话不存在'}), 404
|
||||
|
||||
cursor.execute('DELETE FROM conversations WHERE id = ?', (conv_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 用户智能体数据同步 ====================
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents', methods=['GET'])
|
||||
def get_user_agents(user_id):
|
||||
"""获取用户智能体配置"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT agent_id, category, is_pinned, is_favorite, added_at
|
||||
FROM user_agents WHERE user_id = ?
|
||||
''', (user_id,))
|
||||
|
||||
agents_data = {
|
||||
'myAgents': {}, # {category: [agent_ids]}
|
||||
'favoriteAgents': [], # [agent_ids]
|
||||
'pinnedAgents': {} # {category: [agent_ids]}
|
||||
}
|
||||
|
||||
for row in cursor.fetchall():
|
||||
agent_id = row['agent_id']
|
||||
category = row['category']
|
||||
is_pinned = row['is_pinned']
|
||||
is_favorite = row['is_favorite']
|
||||
|
||||
# 添加到 myAgents
|
||||
if category not in agents_data['myAgents']:
|
||||
agents_data['myAgents'][category] = []
|
||||
agents_data['myAgents'][category].append(agent_id)
|
||||
|
||||
# 添加到 pinnedAgents
|
||||
if is_pinned:
|
||||
if category not in agents_data['pinnedAgents']:
|
||||
agents_data['pinnedAgents'][category] = []
|
||||
agents_data['pinnedAgents'][category].append(agent_id)
|
||||
|
||||
# 添加到 favoriteAgents
|
||||
if is_favorite:
|
||||
agents_data['favoriteAgents'].append(agent_id)
|
||||
|
||||
conn.close()
|
||||
return jsonify(agents_data)
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>', methods=['POST'])
|
||||
def add_user_agent(user_id, agent_id):
|
||||
"""添加智能体到用户列表"""
|
||||
data = request.json
|
||||
category = data.get('category', 'basic')
|
||||
is_pinned = data.get('is_pinned', 0)
|
||||
is_favorite = data.get('is_favorite', 0)
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO user_agents (user_id, agent_id, category, is_pinned, is_favorite)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
''', (user_id, agent_id, category, is_pinned, is_favorite))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
except:
|
||||
# 已存在,更新
|
||||
cursor.execute('''
|
||||
UPDATE user_agents SET category=?, is_pinned=?, is_favorite=?
|
||||
WHERE user_id=? AND agent_id=?
|
||||
''', (category, is_pinned, is_favorite, user_id, agent_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>', methods=['DELETE'])
|
||||
def remove_user_agent(user_id, agent_id):
|
||||
"""从用户列表移除智能体"""
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('DELETE FROM user_agents WHERE user_id=? AND agent_id=?', (user_id, agent_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>/pin', methods=['POST'])
|
||||
def toggle_user_agent_pin(user_id, agent_id):
|
||||
"""切换智能体置顶状态"""
|
||||
data = request.json
|
||||
is_pinned = data.get('is_pinned', 1)
|
||||
category = data.get('category', 'basic')
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查是否存在
|
||||
cursor.execute('SELECT id FROM user_agents WHERE user_id=? AND agent_id=?', (user_id, agent_id))
|
||||
if cursor.fetchone():
|
||||
cursor.execute('UPDATE user_agents SET is_pinned=? WHERE user_id=? AND agent_id=?',
|
||||
(is_pinned, user_id, agent_id))
|
||||
else:
|
||||
cursor.execute('INSERT INTO user_agents (user_id, agent_id, category, is_pinned) VALUES (?, ?, ?, ?)',
|
||||
(user_id, agent_id, category, is_pinned))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/user/<int:user_id>/agents/<agent_id>/favorite', methods=['POST'])
|
||||
def toggle_user_agent_favorite(user_id, agent_id):
|
||||
"""切换智能体收藏状态"""
|
||||
data = request.json
|
||||
is_favorite = data.get('is_favorite', 1)
|
||||
category = data.get('category', 'basic')
|
||||
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 检查是否存在
|
||||
cursor.execute('SELECT id FROM user_agents WHERE user_id=? AND agent_id=?', (user_id, agent_id))
|
||||
if cursor.fetchone():
|
||||
cursor.execute('UPDATE user_agents SET is_favorite=? WHERE user_id=? AND agent_id=?',
|
||||
(is_favorite, user_id, agent_id))
|
||||
else:
|
||||
cursor.execute('INSERT INTO user_agents (user_id, agent_id, category, is_favorite) VALUES (?, ?, ?, ?)',
|
||||
(user_id, agent_id, category, is_favorite))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 大模型接口管理 ====================
|
||||
|
||||
@app.route('/api/admin/llm', methods=['GET'])
|
||||
@@ -380,12 +1054,13 @@ def add_agent():
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO agents (agent_id, name, avatar, category, description, system_prompt,
|
||||
llm_config_id, temperature, max_tokens, enable_search, tags, heat)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
llm_config_id, temperature, max_tokens, enable_tools, tags, heat, is_online)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (data['agent_id'], data['name'], data.get('avatar', '🤖'), data['category'],
|
||||
data.get('description', ''), data['system_prompt'], data.get('llm_config_id'),
|
||||
data.get('temperature', 0.7), data.get('max_tokens', 2048),
|
||||
data.get('enable_search', 0), data.get('tags', ''), data.get('heat', 0)))
|
||||
data.get('enable_tools', ''), data.get('tags', ''), data.get('heat', 0),
|
||||
data.get('is_online', 1)))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
@@ -399,12 +1074,13 @@ def update_agent(agent_id):
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE agents SET name=?, avatar=?, category=?, description=?, system_prompt=?,
|
||||
llm_config_id=?, temperature=?, max_tokens=?, enable_search=?, tags=?, heat=?,
|
||||
llm_config_id=?, temperature=?, max_tokens=?, enable_tools=?, tags=?, heat=?, is_online=?,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE agent_id=?
|
||||
''', (data['name'], data.get('avatar', '🤖'), data['category'],
|
||||
data.get('description', ''), data['system_prompt'], data.get('llm_config_id'),
|
||||
data.get('temperature', 0.7), data.get('max_tokens', 2048),
|
||||
data.get('enable_search', 0), data.get('tags', ''), data.get('heat', 0), agent_id))
|
||||
data.get('enable_tools', ''), data.get('tags', ''), data.get('heat', 0),
|
||||
data.get('is_online', 1), agent_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
@@ -421,6 +1097,19 @@ def delete_agent(agent_id):
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@app.route('/api/admin/agents/<agent_id>/online', methods=['POST'])
|
||||
def toggle_agent_online(agent_id):
|
||||
"""切换智能体上线状态"""
|
||||
data = request.json
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('UPDATE agents SET is_online=?, updated_at=CURRENT_TIMESTAMP WHERE agent_id=?',
|
||||
(data.get('is_online', 1), agent_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ==================== 对话配置管理 ====================
|
||||
|
||||
@app.route('/api/admin/chat', methods=['GET'])
|
||||
@@ -643,8 +1332,8 @@ def get_frontend_config():
|
||||
cursor.execute('SELECT * FROM tool_configs WHERE is_default=1 AND is_active=1')
|
||||
tools = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
# 获取所有智能体
|
||||
cursor.execute('SELECT agent_id, name, avatar, category, description, system_prompt, heat, enable_search FROM agents WHERE is_active=1')
|
||||
# 获取所有智能体(上线且活跃)
|
||||
cursor.execute('SELECT agent_id, name, avatar, category, description, system_prompt, heat, tags, enable_tools FROM agents WHERE is_online=1 AND is_active=1')
|
||||
agents = [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
# 获取默认对话配置
|
||||
@@ -664,13 +1353,19 @@ def get_frontend_config():
|
||||
'chat_config': dict(chat_config) if chat_config else None,
|
||||
'system': {
|
||||
'appName': system.get('app_name', 'AI助手'),
|
||||
'version': system.get('app_version', '3.6.0'),
|
||||
'version': system.get('app_version', '3.10.0'),
|
||||
'enableSearch': system.get('enable_search', 'true') == 'true',
|
||||
'guestLimits': {
|
||||
'chatSessions': int(system.get('guest_chat_sessions', '1')),
|
||||
'chatMessages': int(system.get('guest_chat_messages', '20')),
|
||||
'agentMessages': int(system.get('guest_agent_messages', '20')),
|
||||
}
|
||||
},
|
||||
'developer': system.get('app_developer', 'OpenClaw Team'),
|
||||
'updateDate': system.get('app_update_date', '2026-04-27'),
|
||||
'technology': system.get('app_technology', '智谱 GLM-4.5-Air 大模型'),
|
||||
'description': system.get('app_description', '提供智能对话、多种智能体服务'),
|
||||
'privacyPolicyUrl': system.get('privacy_policy_url', ''),
|
||||
'userAgreementUrl': system.get('user_agreement_url', ''),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AI助手 - 后台管理</title>
|
||||
<link rel="stylesheet" href="admin.css?v=3.6.6">
|
||||
<style>
|
||||
:root {
|
||||
--primary: #667eea;
|
||||
@@ -318,6 +319,8 @@
|
||||
border-radius: 16px;
|
||||
max-width: 500px;
|
||||
width: 90%;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
@@ -432,6 +435,10 @@
|
||||
<span class="sidebar-icon">📊</span>
|
||||
<span>统计信息</span>
|
||||
</div>
|
||||
<div class="sidebar-item" data-page="users">
|
||||
<span class="sidebar-icon">👥</span>
|
||||
<span>用户管理</span>
|
||||
</div>
|
||||
<div class="sidebar-item" data-page="llm">
|
||||
<span class="sidebar-icon">🧠</span>
|
||||
<span>大模型配置</span>
|
||||
@@ -470,6 +477,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="admin.js?v=1.0.0"></script>
|
||||
<script src="admin.js?v=3.6.6"></script>
|
||||
</body>
|
||||
</html>
|
||||
503
www/admin.js
503
www/admin.js
@@ -81,6 +81,9 @@ async function loadPage(page) {
|
||||
case 'stats':
|
||||
await loadStatsPage(content);
|
||||
break;
|
||||
case 'users':
|
||||
await loadUsersPage(content);
|
||||
break;
|
||||
case 'llm':
|
||||
await loadLLMPage(content);
|
||||
break;
|
||||
@@ -177,6 +180,367 @@ async function loadStatsPage(content) {
|
||||
`;
|
||||
}
|
||||
|
||||
// ==================== 用户管理页面 ====================
|
||||
|
||||
let users = [];
|
||||
|
||||
async function loadUsersPage(content) {
|
||||
users = await fetchAPI('/api/admin/users');
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="content-header">
|
||||
<h1 class="content-title">用户管理</h1>
|
||||
<div style="display: flex; gap: 12px;">
|
||||
<input type="text" class="form-input" id="userSearch" placeholder="搜索用户名/手机/邮箱" style="width: 200px;" onkeyup="searchUsers(event)">
|
||||
<button class="add-btn" onclick="searchUsersBtn()">搜索</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stats-grid" style="grid-template-columns: repeat(4, 1fr);">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">👥</div>
|
||||
<div class="stat-value">${users.length}</div>
|
||||
<div class="stat-label">总用户数</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">🆕</div>
|
||||
<div class="stat-value">${users.filter(u => {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
return u.created_at && u.created_at.startsWith(today);
|
||||
}).length}</div>
|
||||
<div class="stat-label">今日新增</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">📧</div>
|
||||
<div class="stat-value">${users.filter(u => u.email).length}</div>
|
||||
<div class="stat-label">已绑定邮箱</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">📱</div>
|
||||
<div class="stat-value">${users.length}</div>
|
||||
<div class="stat-label">已绑定手机</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>头像</th>
|
||||
<th>用户名</th>
|
||||
<th>手机号</th>
|
||||
<th>邮箱</th>
|
||||
<th>注册时间</th>
|
||||
<th>最后登录</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${users.length === 0 ? '<tr><td colspan="8" style="text-align: center; color: #999;">暂无用户</td></tr>' :
|
||||
users.map(u => `
|
||||
<tr>
|
||||
<td>${u.id}</td>
|
||||
<td style="font-size: 24px;">${u.avatar || '👤'}</td>
|
||||
<td>${u.username}</td>
|
||||
<td>${u.phone}</td>
|
||||
<td>${u.email || '-'}</td>
|
||||
<td>${formatDate(u.created_at)}</td>
|
||||
<td>${u.last_login_at ? formatDate(u.last_login_at) : '从未登录'}</td>
|
||||
<td>
|
||||
<div class="action-btns">
|
||||
<button class="action-btn edit" onclick="showEditUserModal(${u.id})">编辑</button>
|
||||
<button class="action-btn" style="background: #8b5cf6; color: white;" onclick="showUserConversations(${u.id}, '${u.username}')">查看对话</button>
|
||||
<button class="action-btn" style="background: #f59e0b; color: white;" onclick="showResetPasswordModal(${u.id})">重置密码</button>
|
||||
<button class="action-btn delete" onclick="deleteUser(${u.id})">删除</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
const d = new Date(dateStr);
|
||||
return d.toLocaleDateString() + ' ' + d.toLocaleTimeString().slice(0, 5);
|
||||
}
|
||||
|
||||
async function searchUsers(event) {
|
||||
if (event && event.key !== 'Enter') return;
|
||||
const search = document.getElementById('userSearch').value.trim();
|
||||
users = await fetchAPI(`/api/admin/users?search=${encodeURIComponent(search)}`);
|
||||
loadUsersPage(document.getElementById('mainContent'));
|
||||
}
|
||||
|
||||
async function searchUsersBtn() {
|
||||
const search = document.getElementById('userSearch').value.trim();
|
||||
users = await fetchAPI(`/api/admin/users?search=${encodeURIComponent(search)}`);
|
||||
loadUsersPage(document.getElementById('mainContent'));
|
||||
}
|
||||
|
||||
function showEditUserModal(id) {
|
||||
const user = users.find(u => u.id === id);
|
||||
if (!user) return;
|
||||
|
||||
const avatars = ['👤', '😊', '😎', '🤓', '🦸', '🧙', '🥷', '👨', '👩', '🧑', '👴', '👵', '👦', '👧', '🤖', '👽', '🧛', '🧜', '🧚', '🦊'];
|
||||
|
||||
showModal('编辑用户', `
|
||||
<div class="form-group">
|
||||
<label class="form-label">用户名</label>
|
||||
<input type="text" class="form-input" id="editUserName" value="${user.username}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">手机号(不可修改)</label>
|
||||
<input type="text" class="form-input" id="editUserPhone" value="${user.phone}" readonly style="background: #f5f7fa;">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">邮箱</label>
|
||||
<input type="email" class="form-input" id="editUserEmail" value="${user.email || ''}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">头像</label>
|
||||
<select class="form-select" id="editUserAvatar">
|
||||
${avatars.map(a => `<option value="${a}" ${a === (user.avatar || '👤') ? 'selected' : ''}>${a}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">个性签名</label>
|
||||
<input type="text" class="form-input" id="editUserSignature" value="${user.signature || ''}" maxlength="50">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">性别</label>
|
||||
<select class="form-select" id="editUserGender">
|
||||
<option value="" ${!user.gender ? 'selected' : ''}>未设置</option>
|
||||
<option value="male" ${user.gender === 'male' ? 'selected' : ''}>男</option>
|
||||
<option value="female" ${user.gender === 'female' ? 'selected' : ''}>女</option>
|
||||
<option value="other" ${user.gender === 'other' ? 'selected' : ''}>其他</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">年龄</label>
|
||||
<input type="number" class="form-input" id="editUserAge" value="${user.age || ''}" min="1" max="150">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">地区</label>
|
||||
<input type="text" class="form-input" id="editUserRegion" value="${user.region || ''}">
|
||||
</div>
|
||||
<button class="form-submit" onclick="updateUser(${id})">保存</button>
|
||||
`);
|
||||
}
|
||||
|
||||
async function updateUser(id) {
|
||||
const data = {
|
||||
username: document.getElementById('editUserName').value,
|
||||
email: document.getElementById('editUserEmail').value,
|
||||
avatar: document.getElementById('editUserAvatar').value,
|
||||
signature: document.getElementById('editUserSignature').value,
|
||||
gender: document.getElementById('editUserGender').value,
|
||||
age: document.getElementById('editUserAge').value ? parseInt(document.getElementById('editUserAge').value) : null,
|
||||
region: document.getElementById('editUserRegion').value
|
||||
};
|
||||
|
||||
if (!data.username) {
|
||||
showToast('用户名不能为空');
|
||||
return;
|
||||
}
|
||||
|
||||
await fetchAPI(`/api/admin/users/${id}`, 'PUT', data);
|
||||
closeModal();
|
||||
showToast('更新成功');
|
||||
loadPage('users');
|
||||
}
|
||||
|
||||
function showResetPasswordModal(id) {
|
||||
const user = users.find(u => u.id === id);
|
||||
if (!user) return;
|
||||
|
||||
showModal('重置密码', `
|
||||
<div style="padding: 16px; background: #f5f7fa; border-radius: 8px; margin-bottom: 16px;">
|
||||
<p><strong>用户:</strong> ${user.username}</p>
|
||||
<p><strong>手机:</strong> ${user.phone}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">新密码</label>
|
||||
<input type="text" class="form-input" id="resetPassword" placeholder="输入新密码(至少6位)">
|
||||
</div>
|
||||
<p style="color: #999; font-size: 12px;">⚠️ 重置后用户需使用新密码登录</p>
|
||||
<button class="form-submit" onclick="resetPassword(${id})">确认重置</button>
|
||||
`);
|
||||
}
|
||||
|
||||
async function resetPassword(id) {
|
||||
const password = document.getElementById('resetPassword').value;
|
||||
|
||||
if (!password || password.length < 6) {
|
||||
showToast('密码长度至少6位');
|
||||
return;
|
||||
}
|
||||
|
||||
await fetchAPI(`/api/admin/users/${id}/password`, 'PUT', { password });
|
||||
closeModal();
|
||||
showToast('密码已重置');
|
||||
}
|
||||
|
||||
async function deleteUser(id) {
|
||||
const user = users.find(u => u.id === id);
|
||||
if (!user) return;
|
||||
|
||||
if (!confirm(`确定删除用户 "${user.username}"?\n此操作不可恢复!`)) return;
|
||||
|
||||
await fetchAPI(`/api/admin/users/${id}`, 'DELETE');
|
||||
showToast('删除成功');
|
||||
loadPage('users');
|
||||
}
|
||||
|
||||
// ==================== 查看用户对话记录 ====================
|
||||
|
||||
async function showUserConversations(userId, username) {
|
||||
// 加载用户对话列表
|
||||
const conversations = await fetchAPI(`/api/user/${userId}/conversations`);
|
||||
|
||||
const content = document.getElementById('mainContent');
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="content-header">
|
||||
<h1 class="content-title">用户对话记录 - ${username}</h1>
|
||||
<button class="add-btn" style="background: #718096;" onclick="loadPage('users')">返回用户列表</button>
|
||||
</div>
|
||||
|
||||
<div class="stats-grid" style="grid-template-columns: repeat(3, 1fr);">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">💬</div>
|
||||
<div class="stat-value">${conversations.length}</div>
|
||||
<div class="stat-label">对话总数</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">🤖</div>
|
||||
<div class="stat-value">${conversations.filter(c => c.agentId).length}</div>
|
||||
<div class="stat-label">智能体对话</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">📝</div>
|
||||
<div class="stat-value">${conversations.reduce((sum, c) => sum + (c.messages?.length || 0), 0)}</div>
|
||||
<div class="stat-label">消息总数</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>标题</th>
|
||||
<th>智能体</th>
|
||||
<th>消息数</th>
|
||||
<th>创建时间</th>
|
||||
<th>更新时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${conversations.length === 0 ? '<tr><td colspan="7" style="text-align: center; color: #999;">暂无对话记录</td></tr>' :
|
||||
conversations.map(conv => `
|
||||
<tr>
|
||||
<td>${conv.id}</td>
|
||||
<td>${conv.title || '新对话'}</td>
|
||||
<td>${conv.agentId ? getAgentName(conv.agentId) : '普通对话'}</td>
|
||||
<td>${conv.messages?.length || 0}</td>
|
||||
<td>${formatDate(conv.createdAt || conv.created_at)}</td>
|
||||
<td>${formatDate(conv.updatedAt || conv.updated_at)}</td>
|
||||
<td>
|
||||
<div class="action-btns">
|
||||
<button class="action-btn edit" onclick="showConversationMessages(${userId}, ${conv.id}, '${conv.title || '新对话'}')">查看详情</button>
|
||||
<button class="action-btn delete" onclick="deleteUserConversation(${userId}, ${conv.id})">删除</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function getAgentName(agentId) {
|
||||
const agent = agents.find(a => a.agent_id === agentId);
|
||||
return agent ? `${agent.avatar} ${agent.name}` : agentId;
|
||||
}
|
||||
|
||||
async function showConversationMessages(userId, convId, title) {
|
||||
// 获取对话详情
|
||||
const conv = await fetchAPI(`/api/user/${userId}/conversations/${convId}`);
|
||||
|
||||
const content = document.getElementById('mainContent');
|
||||
|
||||
const messages = conv.messages || [];
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="content-header">
|
||||
<h1 class="content-title">对话详情 - ${title}</h1>
|
||||
<button class="add-btn" style="background: #718096;" onclick="showUserConversations(${userId}, '用户')">返回对话列表</button>
|
||||
</div>
|
||||
|
||||
<div style="background: white; padding: 16px; border-radius: 12px; margin-bottom: 16px;">
|
||||
<div style="display: flex; gap: 16px; color: #718096;">
|
||||
<span>💬 消息数: ${messages.length}</span>
|
||||
<span>🤖 智能体: ${conv.agentId ? getAgentName(conv.agentId) : '普通对话'}</span>
|
||||
<span>📅 创建: ${formatDate(conv.createdAt || conv.created_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 60px;">序号</th>
|
||||
<th style="width: 80px;">角色</th>
|
||||
<th>内容</th>
|
||||
<th style="width: 150px;">时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${messages.length === 0 ? '<tr><td colspan="4" style="text-align: center; color: #999;">暂无消息</td></tr>' :
|
||||
messages.map((msg, idx) => `
|
||||
<tr>
|
||||
<td>${idx + 1}</td>
|
||||
<td style="color: ${msg.role === 'user' ? '#3b82f6' : '#10b981'};">
|
||||
${msg.role === 'user' ? '👤 用户' : '🤖 AI'}
|
||||
</td>
|
||||
<td style="max-width: 500px; white-space: pre-wrap; word-break: break-all;">
|
||||
${escapeHtml(msg.content?.slice(0, 500) || '')}${msg.content?.length > 500 ? '...' : ''}
|
||||
${msg.thinking ? `<div style="color: #f59e0b; margin-top: 8px; font-size: 12px;">💭 思考: ${escapeHtml(msg.thinking?.slice(0, 200) || '')}...</div>` : ''}
|
||||
</td>
|
||||
<td>${formatDate(msg.timestamp || msg.createdAt)}</td>
|
||||
</tr>
|
||||
`).join('')
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function deleteUserConversation(userId, convId) {
|
||||
if (!confirm('确定删除此对话?此操作不可恢复!')) return;
|
||||
|
||||
await fetchAPI(`/api/user/${userId}/conversations/${convId}`, 'DELETE');
|
||||
showToast('删除成功');
|
||||
showUserConversations(userId, '用户');
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// ==================== 大模型配置页面 ====================
|
||||
|
||||
async function loadLLMPage(content) {
|
||||
@@ -361,14 +725,22 @@ async function deleteLLM(id) {
|
||||
async function loadAgentsPage(content) {
|
||||
agents = await fetchAPI('/api/admin/agents');
|
||||
llmConfigs = await fetchAPI('/api/admin/llm');
|
||||
toolConfigs = await fetchAPI('/api/admin/tools');
|
||||
|
||||
const categories = {
|
||||
hot: '热门',
|
||||
basic: '基础',
|
||||
work: '工作',
|
||||
study: '学习',
|
||||
life: '生活'
|
||||
};
|
||||
|
||||
const tagLabels = {
|
||||
'hot': '🔥 热门',
|
||||
'popular': '👍 推荐',
|
||||
'new': '🆕 新品',
|
||||
'': ''
|
||||
};
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="content-header">
|
||||
<h1 class="content-title">智能体管理</h1>
|
||||
@@ -382,9 +754,9 @@ async function loadAgentsPage(content) {
|
||||
<th>头像</th>
|
||||
<th>名称</th>
|
||||
<th>类别</th>
|
||||
<th>描述</th>
|
||||
<th>标签</th>
|
||||
<th>热度</th>
|
||||
<th>状态</th>
|
||||
<th>上线状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -394,9 +766,13 @@ async function loadAgentsPage(content) {
|
||||
<td style="font-size: 24px;">${a.avatar}</td>
|
||||
<td>${a.name}</td>
|
||||
<td>${categories[a.category] || a.category}</td>
|
||||
<td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">${a.description || '-'}</td>
|
||||
<td>${a.tags ? a.tags.split(',').map(t => tagLabels[t] || t).filter(t => t).join(' ') : '-'}</td>
|
||||
<td>${a.heat || 0}</td>
|
||||
<td>${a.is_active ? '✅ 启用' : '❌ 禁用'}</td>
|
||||
<td>
|
||||
<span style="cursor: pointer; color: ${a.is_online ? '#22c55e' : '#e53e3e'};" onclick="toggleAgentOnline('${a.agent_id}', ${a.is_online})">
|
||||
${a.is_online ? '✅ 已上线' : '❌ 未上线'}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="action-btns">
|
||||
<button class="action-btn edit" onclick="showEditAgentModal('${a.agent_id}')">编辑</button>
|
||||
@@ -408,9 +784,34 @@ async function loadAgentsPage(content) {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 24px; padding: 16px; background: white; border-radius: 12px;">
|
||||
<h3 style="margin-bottom: 16px;">说明</h3>
|
||||
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
|
||||
<div style="padding: 12px; background: #f5f7fa; border-radius: 8px;">
|
||||
<strong>上线状态</strong>
|
||||
<p style="color: #718096; font-size: 12px; margin-top: 4px;">点击可快速切换,未上线则APP不可见</p>
|
||||
</div>
|
||||
<div style="padding: 12px; background: #f5f7fa; border-radius: 8px;">
|
||||
<strong>标签</strong>
|
||||
<p style="color: #718096; font-size: 12px; margin-top: 4px;">hot=热门, popular=推荐, new=新品</p>
|
||||
</div>
|
||||
<div style="padding: 12px; background: #f5f7fa; border-radius: 8px;">
|
||||
<strong>类别</strong>
|
||||
<p style="color: #718096; font-size: 12px; margin-top: 4px;">basic/work/study/life</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function toggleAgentOnline(agentId, currentStatus) {
|
||||
const newStatus = currentStatus ? 0 : 1;
|
||||
await fetchAPI(`/api/admin/agents/${agentId}/online`, 'POST', { is_online: newStatus });
|
||||
showToast(newStatus ? '已上线' : '已下线');
|
||||
loadPage('agents');
|
||||
}
|
||||
|
||||
function showAddAgentModal() {
|
||||
showModal('添加智能体', `
|
||||
<div class="form-group">
|
||||
@@ -432,12 +833,17 @@ function showAddAgentModal() {
|
||||
<div class="form-group">
|
||||
<label class="form-label">类别</label>
|
||||
<select class="form-select" id="agentCategory">
|
||||
<option value="hot">热门</option>
|
||||
<option value="basic">基础</option>
|
||||
<option value="work">工作</option>
|
||||
<option value="study">学习</option>
|
||||
<option value="life">生活</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">标签(逗号分隔)</label>
|
||||
<input type="text" class="form-input" id="agentTags" placeholder="如:hot,popular">
|
||||
<span style="color: #999; font-size: 12px;">可选: hot(热门), popular(推荐), new(新品)</span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">描述</label>
|
||||
<input type="text" class="form-input" id="agentDescription" placeholder="智能体描述">
|
||||
@@ -447,23 +853,24 @@ function showAddAgentModal() {
|
||||
<textarea class="form-textarea" id="agentPrompt" placeholder="系统提示词"></textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">LLM配置</label>
|
||||
<label class="form-label">LLM配置(可选)</label>
|
||||
<select class="form-select" id="agentLLM">
|
||||
<option value="">使用默认</option>
|
||||
${llmConfigs.map(c => `<option value="${c.id}">${c.name}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">可使用工具(逗号分隔)</label>
|
||||
<input type="text" class="form-input" id="agentEnableTools" placeholder="如:search,calculator">
|
||||
<span style="color: #999; font-size: 12px;">已配置工具: ${toolConfigs.map(t => t.tool_id).join(', ')}</span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">热度</label>
|
||||
<input type="number" class="form-input" id="agentHeat" value="0">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">标签</label>
|
||||
<input type="text" class="form-input" id="agentTags" placeholder="多个标签用逗号分隔">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 8px;">
|
||||
<input type="checkbox" id="agentEnableSearch"> 启用联网搜索
|
||||
<input type="checkbox" id="agentIsOnline" checked> 立即上线
|
||||
</label>
|
||||
</div>
|
||||
<button class="form-submit" onclick="saveAgent()">保存</button>
|
||||
@@ -494,12 +901,17 @@ function showEditAgentModal(agentId) {
|
||||
<div class="form-group">
|
||||
<label class="form-label">类别</label>
|
||||
<select class="form-select" id="agentCategory">
|
||||
<option value="hot" ${agent.category === 'hot' ? 'selected' : ''}>热门</option>
|
||||
<option value="basic" ${agent.category === 'basic' ? 'selected' : ''}>基础</option>
|
||||
<option value="work" ${agent.category === 'work' ? 'selected' : ''}>工作</option>
|
||||
<option value="study" ${agent.category === 'study' ? 'selected' : ''}>学习</option>
|
||||
<option value="life" ${agent.category === 'life' ? 'selected' : ''}>生活</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">标签(逗号分隔)</label>
|
||||
<input type="text" class="form-input" id="agentTags" value="${agent.tags || ''}">
|
||||
<span style="color: #999; font-size: 12px;">可选: hot(热门), popular(推荐), new(新品)</span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">描述</label>
|
||||
<input type="text" class="form-input" id="agentDescription" value="${agent.description || ''}">
|
||||
@@ -509,23 +921,24 @@ function showEditAgentModal(agentId) {
|
||||
<textarea class="form-textarea" id="agentPrompt">${agent.system_prompt || ''}</textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">LLM配置</label>
|
||||
<label class="form-label">LLM配置(可选)</label>
|
||||
<select class="form-select" id="agentLLM">
|
||||
<option value="">使用默认</option>
|
||||
<option value="" ${!agent.llm_config_id ? 'selected' : ''}>使用默认</option>
|
||||
${llmConfigs.map(c => `<option value="${c.id}" ${c.id === agent.llm_config_id ? 'selected' : ''}>${c.name}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">可使用工具(逗号分隔)</label>
|
||||
<input type="text" class="form-input" id="agentEnableTools" value="${agent.enable_tools || ''}">
|
||||
<span style="color: #999; font-size: 12px;">已配置工具: ${toolConfigs.map(t => t.tool_id).join(', ')}</span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">热度</label>
|
||||
<input type="number" class="form-input" id="agentHeat" value="${agent.heat || 0}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">标签</label>
|
||||
<input type="text" class="form-input" id="agentTags" value="${agent.tags || ''}">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 8px;">
|
||||
<input type="checkbox" id="agentEnableSearch" ${agent.enable_search ? 'checked' : ''}> 启用联网搜索
|
||||
<input type="checkbox" id="agentIsOnline" ${agent.is_online ? 'checked' : ''}> 已上线
|
||||
</label>
|
||||
</div>
|
||||
<button class="form-submit" onclick="updateAgent('${agentId}')">保存</button>
|
||||
@@ -538,12 +951,13 @@ async function saveAgent() {
|
||||
name: document.getElementById('agentName').value,
|
||||
avatar: document.getElementById('agentAvatar').value,
|
||||
category: document.getElementById('agentCategory').value,
|
||||
tags: document.getElementById('agentTags').value,
|
||||
description: document.getElementById('agentDescription').value,
|
||||
system_prompt: document.getElementById('agentPrompt').value,
|
||||
llm_config_id: document.getElementById('agentLLM').value || null,
|
||||
enable_tools: document.getElementById('agentEnableTools').value,
|
||||
heat: parseInt(document.getElementById('agentHeat').value),
|
||||
tags: document.getElementById('agentTags').value,
|
||||
enable_search: document.getElementById('agentEnableSearch').checked ? 1 : 0
|
||||
is_online: document.getElementById('agentIsOnline').checked ? 1 : 0
|
||||
};
|
||||
|
||||
if (!data.agent_id || !data.name || !data.system_prompt) {
|
||||
@@ -562,12 +976,13 @@ async function updateAgent(agentId) {
|
||||
name: document.getElementById('agentName').value,
|
||||
avatar: document.getElementById('agentAvatar').value,
|
||||
category: document.getElementById('agentCategory').value,
|
||||
tags: document.getElementById('agentTags').value,
|
||||
description: document.getElementById('agentDescription').value,
|
||||
system_prompt: document.getElementById('agentPrompt').value,
|
||||
llm_config_id: document.getElementById('agentLLM').value || null,
|
||||
enable_tools: document.getElementById('agentEnableTools').value,
|
||||
heat: parseInt(document.getElementById('agentHeat').value),
|
||||
tags: document.getElementById('agentTags').value,
|
||||
enable_search: document.getElementById('agentEnableSearch').checked ? 1 : 0
|
||||
is_online: document.getElementById('agentIsOnline').checked ? 1 : 0
|
||||
};
|
||||
|
||||
await fetchAPI(`/api/admin/agents/${agentId}`, 'PUT', data);
|
||||
@@ -940,6 +1355,26 @@ async function loadSystemPage(content) {
|
||||
<input type="text" class="form-input" id="appVersion" value="${systemConfigs.app_version?.value || ''}">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">应用简介</label>
|
||||
<input type="text" class="form-input" id="appDescription" value="${systemConfigs.app_description?.value || ''}" placeholder="如:提供智能对话、多种智能体服务">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">技术基础</label>
|
||||
<input type="text" class="form-input" id="appTechnology" value="${systemConfigs.app_technology?.value || ''}" placeholder="如:智谱 GLM-4.5-Air 大模型">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">开发者</label>
|
||||
<input type="text" class="form-input" id="appDeveloper" value="${systemConfigs.app_developer?.value || ''}" placeholder="如:OpenClaw Team">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">更新日期</label>
|
||||
<input type="text" class="form-input" id="appUpdateDate" value="${systemConfigs.app_update_date?.value || ''}" placeholder="如:2026-04-27">
|
||||
</div>
|
||||
|
||||
<h3 style="margin: 24px 0 16px; padding-top: 16px; border-top: 1px solid #e2e8f0;">游客使用限制</h3>
|
||||
|
||||
<div class="form-group">
|
||||
@@ -964,6 +1399,18 @@ async function loadSystemPage(content) {
|
||||
<input type="text" class="form-input" id="adminPassword" value="${systemConfigs.admin_password?.value || ''}" placeholder="修改管理员密码">
|
||||
</div>
|
||||
|
||||
<h3 style="margin: 24px 0 16px; padding-top: 16px; border-top: 1px solid #e2e8f0;">链接配置</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">隐私政策链接</label>
|
||||
<input type="text" class="form-input" id="privacyPolicyUrl" value="${systemConfigs.privacy_policy_url?.value || ''}" placeholder="隐私政策页面URL">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">用户协议链接</label>
|
||||
<input type="text" class="form-input" id="userAgreementUrl" value="${systemConfigs.user_agreement_url?.value || ''}" placeholder="用户协议页面URL">
|
||||
</div>
|
||||
|
||||
<button class="form-submit" onclick="saveSystemConfig()">保存设置</button>
|
||||
</div>
|
||||
|
||||
@@ -979,10 +1426,16 @@ async function saveSystemConfig() {
|
||||
const data = {
|
||||
app_name: document.getElementById('appName').value,
|
||||
app_version: document.getElementById('appVersion').value,
|
||||
app_description: document.getElementById('appDescription').value,
|
||||
app_technology: document.getElementById('appTechnology').value,
|
||||
app_developer: document.getElementById('appDeveloper').value,
|
||||
app_update_date: document.getElementById('appUpdateDate').value,
|
||||
guest_chat_sessions: document.getElementById('guestChatSessions').value,
|
||||
guest_chat_messages: document.getElementById('guestChatMessages').value,
|
||||
guest_agent_messages: document.getElementById('guestAgentMessages').value,
|
||||
admin_password: document.getElementById('adminPassword').value
|
||||
admin_password: document.getElementById('adminPassword').value,
|
||||
privacy_policy_url: document.getElementById('privacyPolicyUrl').value,
|
||||
user_agreement_url: document.getElementById('userAgreementUrl').value,
|
||||
};
|
||||
|
||||
await fetchAPI('/api/admin/system', 'POST', data);
|
||||
|
||||
800
www/app.js
800
www/app.js
File diff suppressed because it is too large
Load Diff
@@ -1049,6 +1049,31 @@ body {
|
||||
box-shadow: 0 0 8px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.avatar-upload-section {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.avatar-upload-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 24px;
|
||||
background: linear-gradient(135deg, var(--primary) 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.avatar-upload-btn:hover {
|
||||
transform: scale(1.02);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.edit-input-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user