Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8199773ef6 | |||
| d153986f3d | |||
| e9357577cb | |||
| 24ba04b3e3 | |||
| d1ddd340c0 | |||
| 6ab58cb363 | |||
| ba8d0ae679 | |||
| 52d98e88c6 | |||
| 25dff98583 | |||
| 6452e4c976 | |||
| f85991064f |
478
backend/app.py
478
backend/app.py
@@ -66,9 +66,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 +147,39 @@ 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 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 +210,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)
|
||||
|
||||
# 初始化系统配置
|
||||
@@ -290,6 +328,385 @@ 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>/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', 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/admin/llm', methods=['GET'])
|
||||
@@ -380,12 +797,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 +817,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 +840,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 +1075,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()]
|
||||
|
||||
# 获取默认对话配置
|
||||
|
||||
@@ -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>
|
||||
318
www/admin.js
318
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,222 @@ 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: #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 loadLLMPage(content) {
|
||||
@@ -361,14 +580,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 +609,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 +621,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 +639,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 +688,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 +708,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 +756,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 +776,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 +806,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 +831,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);
|
||||
|
||||
469
www/app.js
469
www/app.js
@@ -19,39 +19,18 @@ let isLoading = false;
|
||||
// 当前页面状态
|
||||
let currentPage = 'chats'; // chats | agents | profile
|
||||
|
||||
// 系统智能体数据(完整列表)
|
||||
let systemAgents = [
|
||||
// 热门智能体
|
||||
{ id: 'assistant', name: '通用助手', avatar: '🤖', category: 'hot', desc: '能回答各类问题,帮助写作、分析、解答疑惑', systemPrompt: '你是一个智能助手,能够回答各类问题,帮助用户解决问题。', heat: 9500 },
|
||||
{ id: 'writer', name: '写作助手', avatar: '✍️', category: 'hot', desc: '专注于文章写作、文案创作、内容润色', systemPrompt: '你是一个专业的写作助手,擅长各类文章写作、文案创作和内容润色。', heat: 8800 },
|
||||
{ id: 'coder', name: '编程助手', avatar: '👨💻', category: 'hot', desc: '精通编程语言,解答技术问题,生成代码', systemPrompt: '你是一个专业的编程助手,精通各类编程语言,能够解答技术问题并生成高质量代码。', heat: 8500 },
|
||||
{ id: 'translator', name: '翻译助手', avatar: '🌐', category: 'hot', desc: '多语言翻译,精准表达,文化适配', systemPrompt: '你是一个专业的翻译助手,精通多语言翻译,能够精准表达并适配文化差异。', heat: 7200 },
|
||||
|
||||
// 工作助手
|
||||
{ id: 'assistant-work', name: '工作助手', avatar: '💼', category: 'work', desc: '职场问题解答,工作效率提升', systemPrompt: '你是一个工作助手,帮助解决职场问题,提升工作效率。', heat: 5000 },
|
||||
{ id: 'ppt', name: 'PPT助手', avatar: '📊', category: 'work', desc: 'PPT内容生成,结构优化,设计建议', systemPrompt: '你是一个PPT助手,擅长PPT内容生成、结构优化和设计建议。', heat: 4500 },
|
||||
{ id: 'excel', name: 'Excel助手', avatar: '📈', category: 'work', desc: 'Excel公式、数据分析、表格优化', systemPrompt: '你是一个Excel助手,精通Excel公式、数据分析和表格优化。', heat: 4000 },
|
||||
|
||||
// 学习助手
|
||||
{ id: 'teacher', name: '学习助手', avatar: '📚', category: 'study', desc: '知识讲解,学习方法,考试辅导', systemPrompt: '你是一个学习助手,擅长知识讲解、学习方法指导和考试辅导。', heat: 5500 },
|
||||
{ id: 'english', name: '英语助手', avatar: '🔤', category: 'study', desc: '英语学习,语法纠正,口语练习', systemPrompt: '你是一个英语助手,帮助英语学习、语法纠正和口语练习。', heat: 5000 },
|
||||
{ id: 'math', name: '数学助手', avatar: '🔢', category: 'study', desc: '数学解题,公式推导,概念讲解', systemPrompt: '你是一个数学助手,擅长数学解题、公式推导和概念讲解。', heat: 4500 },
|
||||
|
||||
// 生活助手
|
||||
{ id: 'health', name: '健康助手', avatar: '🏥', category: 'life', desc: '健康咨询,养生建议,运动指导', systemPrompt: '你是一个健康助手,提供健康咨询、养生建议和运动指导。', heat: 3500 },
|
||||
{ id: 'travel', name: '旅行助手', avatar: '✈️', category: 'life', desc: '旅行规划,景点推荐,美食指南', systemPrompt: '你是一个旅行助手,擅长旅行规划、景点推荐和美食指南。', heat: 3200 },
|
||||
{ id: 'food', name: '美食助手', avatar: '🍳', category: 'life', desc: '菜谱推荐,烹饪技巧,营养搭配', systemPrompt: '你是一个美食助手,提供菜谱推荐、烹饪技巧和营养搭配建议。', heat: 3000 },
|
||||
];
|
||||
// 系统智能体数据(从后台API加载)
|
||||
let systemAgents = [];
|
||||
|
||||
// 用户智能体界面显示的智能体(默认显示热门智能体)
|
||||
// 用户智能体界面显示的智能体
|
||||
let agents = [];
|
||||
|
||||
// 用户添加的智能体(按类别分组)
|
||||
let myAgents = {
|
||||
hot: ['assistant', 'writer', 'coder', 'translator'],
|
||||
work: ['assistant-work', 'ppt', 'excel'],
|
||||
study: ['teacher', 'english', 'math'],
|
||||
life: ['health', 'travel', 'food']
|
||||
basic: [],
|
||||
work: [],
|
||||
study: [],
|
||||
life: []
|
||||
};
|
||||
|
||||
// 收藏的智能体列表
|
||||
@@ -59,7 +38,7 @@ let favoriteAgents = [];
|
||||
|
||||
// 置顶的智能体列表(按类别)
|
||||
let pinnedAgents = {
|
||||
hot: [],
|
||||
basic: [],
|
||||
work: [],
|
||||
study: [],
|
||||
life: []
|
||||
@@ -67,6 +46,9 @@ let pinnedAgents = {
|
||||
|
||||
let currentAgent = null; // 当前选中的智能体
|
||||
|
||||
// 后台配置
|
||||
let backendConfig = null; // 从API获取的配置
|
||||
|
||||
// 用户状态
|
||||
let currentUser = null; // 当前登录用户 { username, password, registeredAt }
|
||||
|
||||
@@ -79,12 +61,12 @@ let dailyUsage = {
|
||||
agentMessages: 0 // 智能体消息数
|
||||
};
|
||||
|
||||
// 未登录用户限制
|
||||
const GUEST_LIMITS = {
|
||||
maxChatSessionsPerDay: 1, // 每天最多1个对话会话
|
||||
maxChatMessagesPerDay: 20, // 每天最多20条对话消息
|
||||
maxAgentPerDay: 1, // 每天只能用1个智能体(通用助手)
|
||||
maxAgentMessagesPerDay: 20 // 每天最多20条智能体消息
|
||||
// 未登录用户限制(从后台配置加载)
|
||||
let GUEST_LIMITS = {
|
||||
maxChatSessionsPerDay: 1,
|
||||
maxChatMessagesPerDay: 20,
|
||||
maxAgentPerDay: 1,
|
||||
maxAgentMessagesPerDay: 20
|
||||
};
|
||||
|
||||
// 获取今日日期字符串
|
||||
@@ -93,6 +75,59 @@ function getTodayDate() {
|
||||
return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// 从后台API加载配置
|
||||
async function loadBackendConfig() {
|
||||
try {
|
||||
// 使用相对路径,自动适应当前域名
|
||||
const API_BASE = window.location.origin;
|
||||
const res = await fetch(`${API_BASE}/api/config`);
|
||||
backendConfig = await res.json();
|
||||
|
||||
// 加载智能体列表
|
||||
if (backendConfig.agents) {
|
||||
systemAgents = backendConfig.agents.map(a => ({
|
||||
id: a.agent_id,
|
||||
name: a.name,
|
||||
avatar: a.avatar,
|
||||
category: a.category,
|
||||
desc: a.description,
|
||||
systemPrompt: a.system_prompt,
|
||||
heat: a.heat || 0,
|
||||
tags: a.tags || '',
|
||||
enable_tools: a.enable_tools || ''
|
||||
}));
|
||||
|
||||
// 初始化用户智能体列表(按类别)
|
||||
systemAgents.forEach(agent => {
|
||||
if (!myAgents[agent.category]) {
|
||||
myAgents[agent.category] = [];
|
||||
}
|
||||
myAgents[agent.category].push(agent.id);
|
||||
});
|
||||
}
|
||||
|
||||
// 加载游客限制配置
|
||||
if (backendConfig.system?.guestLimits) {
|
||||
GUEST_LIMITS = {
|
||||
maxChatSessionsPerDay: backendConfig.system.guestLimits.chatSessions || 1,
|
||||
maxChatMessagesPerDay: backendConfig.system.guestLimits.chatMessages || 20,
|
||||
maxAgentPerDay: 1, // 游客只能用通用助手
|
||||
maxAgentMessagesPerDay: backendConfig.system.guestLimits.agentMessages || 20
|
||||
};
|
||||
}
|
||||
|
||||
updateAgentsDisplay();
|
||||
console.log('后台配置已加载', backendConfig);
|
||||
} catch (e) {
|
||||
console.error('加载后台配置失败', e);
|
||||
// 使用默认配置
|
||||
systemAgents = [
|
||||
{ id: 'assistant', name: '通用助手', avatar: '🤖', category: 'basic', desc: '能回答各类问题,帮助写作、分析、解答疑惑', systemPrompt: '你是一个智能助手,能够回答各类问题,帮助用户解决问题。', heat: 9500, tags: 'hot' },
|
||||
];
|
||||
updateAgentsDisplay();
|
||||
}
|
||||
}
|
||||
|
||||
// 检查并重置每日使用统计
|
||||
function checkDailyUsage() {
|
||||
const today = getTodayDate();
|
||||
@@ -228,9 +263,10 @@ function getRemainingQuota() {
|
||||
}
|
||||
|
||||
// 获取使用智能体的对话列表(按时间倒序)
|
||||
// 只返回真正有对话消息的记录(messages.length > 0)
|
||||
function getAgentConversationHistory(limit = 5) {
|
||||
return conversations
|
||||
.filter(conv => conv.agentId) // 筛选有智能体的对话
|
||||
.filter(conv => conv.agentId && conv.messages && conv.messages.length > 0) // 筛选有智能体且有消息的对话
|
||||
.sort((a, b) => b.updatedAt - a.updatedAt) // 按更新时间倒序
|
||||
.slice(0, limit)
|
||||
.map(conv => {
|
||||
@@ -321,7 +357,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
checkDailyUsage();
|
||||
|
||||
// 根据用户配置更新显示的智能体
|
||||
updateAgentsDisplay();
|
||||
// updateAgentsDisplay(); // 先不调用,等后台配置加载后再更新
|
||||
|
||||
// 加载当前页面状态
|
||||
const savedPage = localStorage.getItem('currentPage');
|
||||
@@ -329,8 +365,13 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
currentPage = savedPage;
|
||||
}
|
||||
|
||||
// 显示主页
|
||||
showMainPage();
|
||||
// 加载后台配置并显示主页
|
||||
loadBackendConfig().then(() => {
|
||||
showMainPage();
|
||||
}).catch(() => {
|
||||
// 即使加载失败也显示主页
|
||||
showMainPage();
|
||||
});
|
||||
});
|
||||
|
||||
// 根据用户配置更新显示的智能体
|
||||
@@ -644,8 +685,11 @@ function bindChatsPageEvents() {
|
||||
// ==================== 智能体页面 ====================
|
||||
|
||||
function renderAgentsPage() {
|
||||
// 根据用户配置筛选智能体
|
||||
const hotAgents = agents.filter(a => a.category === 'hot');
|
||||
// 根据后台配置筛选智能体
|
||||
// 热门智能体 = 标签中包含 "hot"
|
||||
const hotAgents = agents.filter(a => a.tags && a.tags.split(',').includes('hot'));
|
||||
// 其他类别 = 根据 category 字段分类
|
||||
const basicAgents = agents.filter(a => a.category === 'basic');
|
||||
const workAgents = agents.filter(a => a.category === 'work');
|
||||
const studyAgents = agents.filter(a => a.category === 'study');
|
||||
const lifeAgents = agents.filter(a => a.category === 'life');
|
||||
@@ -698,7 +742,7 @@ function renderAgentsPage() {
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<!-- 热门智能体 -->
|
||||
<!-- 热门智能体(标签为hot) -->
|
||||
${hotAgents.length > 0 ? `
|
||||
<div class="agents-section">
|
||||
<div class="section-title">🔥 热门智能体</div>
|
||||
@@ -1032,7 +1076,10 @@ function showAgentDiscoverPage() {
|
||||
const sortedAgents = [...systemAgents].sort((a, b) => b.heat - a.heat);
|
||||
|
||||
// 分类显示
|
||||
const hotAgents = systemAgents.filter(a => a.category === 'hot');
|
||||
// 热门智能体 = 标签中包含 "hot"
|
||||
const hotAgents = systemAgents.filter(a => a.tags && a.tags.split(',').includes('hot'));
|
||||
// 其他类别
|
||||
const basicAgents = systemAgents.filter(a => a.category === 'basic');
|
||||
const workAgents = systemAgents.filter(a => a.category === 'work');
|
||||
const studyAgents = systemAgents.filter(a => a.category === 'study');
|
||||
const lifeAgents = systemAgents.filter(a => a.category === 'life');
|
||||
@@ -1053,37 +1100,55 @@ function showAgentDiscoverPage() {
|
||||
<input type="text" id="discoverSearchInput" placeholder="搜索智能体名称或描述...">
|
||||
</div>
|
||||
|
||||
<!-- 热门智能体 -->
|
||||
<!-- 热门智能体(标签为hot) -->
|
||||
${hotAgents.length > 0 ? `
|
||||
<div class="discover-section">
|
||||
<div class="discover-section-title">🔥 热门智能体</div>
|
||||
<div class="discover-grid" id="discoverHotGrid">
|
||||
${hotAgents.map(agent => renderDiscoverCard(agent)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<!-- 基础智能体 -->
|
||||
${basicAgents.length > 0 ? `
|
||||
<div class="discover-section">
|
||||
<div class="discover-section-title">⭐ 基础智能体</div>
|
||||
<div class="discover-grid" id="discoverBasicGrid">
|
||||
${basicAgents.map(agent => renderDiscoverCard(agent)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<!-- 工作助手 -->
|
||||
${workAgents.length > 0 ? `
|
||||
<div class="discover-section">
|
||||
<div class="discover-section-title">💼 工作助手</div>
|
||||
<div class="discover-grid" id="discoverWorkGrid">
|
||||
${workAgents.map(agent => renderDiscoverCard(agent)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<!-- 学习助手 -->
|
||||
${studyAgents.length > 0 ? `
|
||||
<div class="discover-section">
|
||||
<div class="discover-section-title">📚 学习助手</div>
|
||||
<div class="discover-grid" id="discoverStudyGrid">
|
||||
${studyAgents.map(agent => renderDiscoverCard(agent)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<!-- 生活助手 -->
|
||||
${lifeAgents.length > 0 ? `
|
||||
<div class="discover-section">
|
||||
<div class="discover-section-title">🏠 生活助手</div>
|
||||
<div class="discover-grid" id="discoverLifeGrid">
|
||||
${lifeAgents.map(agent => renderDiscoverCard(agent)).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -1555,14 +1620,43 @@ function showEditProfilePage() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取完整用户信息
|
||||
const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
|
||||
const fullUser = users.find(u => u.username === currentUser.username);
|
||||
|
||||
// 如果用户已登录且有ID,从 backend 获取完整用户信息
|
||||
if (currentUser.id) {
|
||||
fetch(`/api/admin/users/${currentUser.id}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data && data.id) {
|
||||
// 更新 currentUser 的完整信息
|
||||
currentUser.avatar = data.avatar || '👤';
|
||||
currentUser.signature = data.signature || '';
|
||||
currentUser.email = data.email || '';
|
||||
currentUser.gender = data.gender || '';
|
||||
currentUser.age = data.age || '';
|
||||
currentUser.region = data.region || '';
|
||||
currentUser.phone = data.phone || '';
|
||||
|
||||
// 渲染编辑页面
|
||||
renderEditProfilePage();
|
||||
} else {
|
||||
// 使用本地数据
|
||||
renderEditProfilePage();
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
// 使用本地数据
|
||||
renderEditProfilePage();
|
||||
});
|
||||
} else {
|
||||
// 游客用户,使用本地数据
|
||||
renderEditProfilePage();
|
||||
}
|
||||
}
|
||||
|
||||
function renderEditProfilePage() {
|
||||
const avatar = currentUser.avatar || '👤';
|
||||
const signature = currentUser.signature || '';
|
||||
const phone = fullUser?.phone || '';
|
||||
const email = fullUser?.email || '';
|
||||
const phone = currentUser.phone || '';
|
||||
const email = currentUser.email || '';
|
||||
const gender = currentUser.gender || '';
|
||||
const age = currentUser.age || '';
|
||||
const region = currentUser.region || '';
|
||||
@@ -1708,26 +1802,6 @@ function handleSaveProfile() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查用户名是否被其他人占用
|
||||
const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
|
||||
if (newUsername !== currentUser.username) {
|
||||
if (users.find(u => u.username === newUsername)) {
|
||||
showToast('用户名已被占用');
|
||||
return;
|
||||
}
|
||||
// 更新用户名
|
||||
const userIndex = users.findIndex(u => u.username === currentUser.username);
|
||||
if (userIndex >= 0) {
|
||||
users[userIndex].username = newUsername;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新邮箱
|
||||
const userIndex = users.findIndex(u => u.username === currentUser.username);
|
||||
if (userIndex >= 0) {
|
||||
users[userIndex].email = newEmail;
|
||||
}
|
||||
|
||||
// 更新 currentUser
|
||||
currentUser.avatar = newAvatar;
|
||||
currentUser.username = newUsername;
|
||||
@@ -1735,12 +1809,42 @@ function handleSaveProfile() {
|
||||
currentUser.gender = newGender;
|
||||
currentUser.age = newAge ? parseInt(newAge) : '';
|
||||
currentUser.region = newRegion;
|
||||
currentUser.email = newEmail;
|
||||
|
||||
saveCurrentUser();
|
||||
localStorage.setItem('registeredUsers', JSON.stringify(users));
|
||||
|
||||
showToast('保存成功');
|
||||
switchPage('profile');
|
||||
// 如果用户已登录,调用 backend API 更新
|
||||
if (currentUser.id) {
|
||||
fetch(`/api/user/${currentUser.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: newUsername,
|
||||
email: newEmail,
|
||||
avatar: newAvatar,
|
||||
signature: newSignature,
|
||||
gender: newGender,
|
||||
age: newAge ? parseInt(newAge) : null,
|
||||
region: newRegion
|
||||
})
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
saveCurrentUser();
|
||||
showToast('保存成功');
|
||||
switchPage('profile');
|
||||
} else {
|
||||
showToast(data.error || '保存失败');
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
showToast('网络错误,请重试');
|
||||
});
|
||||
} else {
|
||||
// 未登录用户,保存到本地
|
||||
saveCurrentUser();
|
||||
showToast('保存成功');
|
||||
switchPage('profile');
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 消息通知页面 ====================
|
||||
@@ -2382,18 +2486,38 @@ function handleLogin() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查本地存储的用户
|
||||
const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
|
||||
const user = users.find(u => u.username === username && u.password === password);
|
||||
|
||||
if (user) {
|
||||
currentUser = { username: user.username, registeredAt: user.registeredAt };
|
||||
saveCurrentUser();
|
||||
showToast('登录成功');
|
||||
showMainPage();
|
||||
} else {
|
||||
showToast('用户名或密码错误');
|
||||
}
|
||||
// 调用后台登录API
|
||||
fetch('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
currentUser = {
|
||||
id: data.user.id,
|
||||
username: data.user.username,
|
||||
phone: data.user.phone,
|
||||
email: data.user.email || '',
|
||||
avatar: data.user.avatar || '👤',
|
||||
signature: data.user.signature || '',
|
||||
registeredAt: Date.now()
|
||||
};
|
||||
saveCurrentUser();
|
||||
|
||||
// 从 backend 加载用户对话数据
|
||||
loadUserConversations().then(() => {
|
||||
showToast('登录成功');
|
||||
showMainPage();
|
||||
});
|
||||
} else {
|
||||
showToast(data.error || '用户名或密码错误');
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
showToast('网络错误,请重试');
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 注册页面 ====================
|
||||
@@ -2412,7 +2536,7 @@ function showRegisterPage() {
|
||||
<div class="auth-form">
|
||||
<div class="auth-input-group">
|
||||
<label>用户名</label>
|
||||
<input type="text" id="registerUsername" placeholder="请输入用户名(3-20字符)" autocomplete="username">
|
||||
<input type="text" id="registerUsername" placeholder="请输入用户名(2-20字符)" autocomplete="username">
|
||||
</div>
|
||||
<div class="auth-input-group">
|
||||
<label>手机号 <span class="required">*</span></label>
|
||||
@@ -2498,8 +2622,8 @@ function handleRegister() {
|
||||
const passwordConfirm = document.getElementById('registerPasswordConfirm')?.value;
|
||||
|
||||
// 验证用户名
|
||||
if (!username || username.length < 3 || username.length > 20) {
|
||||
showToast('用户名需要3-20个字符');
|
||||
if (!username || username.length < 2 || username.length > 20) {
|
||||
showToast('用户名需要2-20个字符');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2510,7 +2634,7 @@ function handleRegister() {
|
||||
}
|
||||
|
||||
// 验证邮箱(可选)
|
||||
if (!validateEmail(email)) {
|
||||
if (email && !validateEmail(email)) {
|
||||
showToast('请输入正确的邮箱格式');
|
||||
return;
|
||||
}
|
||||
@@ -2526,37 +2650,45 @@ function handleRegister() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查用户名是否已存在
|
||||
const users = JSON.parse(localStorage.getItem('registeredUsers') || '[]');
|
||||
if (users.find(u => u.username === username)) {
|
||||
showToast('用户名已存在');
|
||||
return;
|
||||
}
|
||||
// 调用后台注册API(验证码暂时跳过,传随机值)
|
||||
const code = Math.floor(100000 + Math.random() * 900000).toString();
|
||||
|
||||
// 检查手机号是否已注册
|
||||
if (users.find(u => u.phone === phone)) {
|
||||
showToast('该手机号已注册');
|
||||
return;
|
||||
}
|
||||
|
||||
// 注册新用户
|
||||
const newUser = {
|
||||
username,
|
||||
phone,
|
||||
email: email || '',
|
||||
password,
|
||||
registeredAt: Date.now()
|
||||
};
|
||||
|
||||
users.push(newUser);
|
||||
localStorage.setItem('registeredUsers', JSON.stringify(users));
|
||||
|
||||
// 自动登录
|
||||
currentUser = { username: newUser.username, phone: newUser.phone, registeredAt: newUser.registeredAt };
|
||||
saveCurrentUser();
|
||||
|
||||
showToast('注册成功');
|
||||
showMainPage();
|
||||
fetch('/api/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
phone,
|
||||
email: email || '',
|
||||
password,
|
||||
code
|
||||
})
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
// 注册成功,自动登录
|
||||
currentUser = {
|
||||
id: data.user_id,
|
||||
username: username,
|
||||
phone: phone,
|
||||
email: email || '',
|
||||
registeredAt: Date.now()
|
||||
};
|
||||
saveCurrentUser();
|
||||
|
||||
// 加载对话数据(新用户为空)
|
||||
loadUserConversations().then(() => {
|
||||
showToast('注册成功');
|
||||
showMainPage();
|
||||
});
|
||||
} else {
|
||||
showToast(data.error || '注册失败');
|
||||
}
|
||||
})
|
||||
.catch(e => {
|
||||
showToast('网络错误,请重试');
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 限制提示 ====================
|
||||
@@ -3411,6 +3543,17 @@ function deleteConversation(id) {
|
||||
|
||||
conversations = conversations.filter(c => c.id !== id);
|
||||
saveConversations();
|
||||
|
||||
// 如果用户已登录,从 backend 删除
|
||||
if (currentUser && currentUser.id) {
|
||||
const convId = parseInt(id);
|
||||
if (convId > 0) {
|
||||
fetch(`/api/user/${currentUser.id}/conversations/${convId}`, {
|
||||
method: 'DELETE'
|
||||
}).catch(e => console.error('删除对话失败:', e));
|
||||
}
|
||||
}
|
||||
|
||||
showConversationList();
|
||||
}
|
||||
|
||||
@@ -4081,7 +4224,91 @@ function setupScrollListener() {
|
||||
|
||||
// 保存对话列表
|
||||
function saveConversations() {
|
||||
// 保存到本地存储(离线可用)
|
||||
localStorage.setItem('conversations', JSON.stringify(conversations));
|
||||
|
||||
// 如果用户已登录,同步到 backend
|
||||
if (currentUser && currentUser.id) {
|
||||
syncConversationsToBackend();
|
||||
}
|
||||
}
|
||||
|
||||
// 同步对话数据到 backend
|
||||
async function syncConversationsToBackend() {
|
||||
if (!currentUser || !currentUser.id) return;
|
||||
|
||||
try {
|
||||
// 批量同步所有对话
|
||||
for (const conv of conversations) {
|
||||
const convId = parseInt(conv.id);
|
||||
if (convId > 0) {
|
||||
// 更新现有对话
|
||||
await fetch(`/api/user/${currentUser.id}/conversations/${convId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: conv.title,
|
||||
messages: conv.messages,
|
||||
agentId: conv.agentId
|
||||
})
|
||||
});
|
||||
} else {
|
||||
// 新对话,需要创建
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: conv.title,
|
||||
messages: conv.messages,
|
||||
agentId: conv.agentId
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.success && data.id) {
|
||||
// 更新本地ID为backend ID
|
||||
conv.id = data.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 同步失败,静默处理(下次登录时会重新加载)
|
||||
console.error('同步对话失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 从 backend 加载用户对话数据
|
||||
async function loadUserConversations() {
|
||||
if (!currentUser || !currentUser.id) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/user/${currentUser.id}/conversations`);
|
||||
const data = await res.json();
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
// 合并本地和云端数据(云端优先)
|
||||
const localConvIds = conversations.map(c => c.id);
|
||||
|
||||
for (const cloudConv of data) {
|
||||
const localIdx = localConvIds.indexOf(cloudConv.id);
|
||||
if (localIdx >= 0) {
|
||||
// 更新本地对话(云端数据优先)
|
||||
conversations[localIdx] = cloudConv;
|
||||
} else {
|
||||
// 添加云端对话
|
||||
conversations.push(cloudConv);
|
||||
}
|
||||
}
|
||||
|
||||
// 按更新时间排序
|
||||
conversations.sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
|
||||
// 保存到本地
|
||||
localStorage.setItem('conversations', JSON.stringify(conversations));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('加载对话失败:', e);
|
||||
// 使用本地数据
|
||||
}
|
||||
}
|
||||
|
||||
// 显示提示
|
||||
|
||||
Reference in New Issue
Block a user