新增后台管理系统

功能模块:
- 仪表盘: 用户统计、对话统计、方言使用分布
- 用户管理: 查看、搜索、删除用户
- 对话管理: 查看、删除对话、消息内容预览
- 数据导出: 导出用户数据

技术栈:
- Flask + Tailwind CSS
- RESTful API
- 数据可视化
This commit is contained in:
2026-04-08 12:16:21 +08:00
parent 376cdacf5e
commit 3aab712ff0
5 changed files with 822 additions and 0 deletions

View File

@@ -94,6 +94,13 @@ API地址: http://192.168.2.5:1234/v1
## 版本历史
### v0.2.0 (2026-04-08)
- 新增后台管理系统
- 用户管理(查看、删除)
- 对话管理(查看、删除)
- 统计仪表盘
- 方言使用分布
### v0.1.0 (2026-04-08)
- 初始版本
- 支持8种方言

250
admin/app.py Normal file
View File

@@ -0,0 +1,250 @@
"""
方言版AI对话助手 - 后台管理系统
"""
from flask import Flask, render_template, jsonify, request, send_file
from flask_cors import CORS
import json
from pathlib import Path
from datetime import datetime
app = Flask(__name__)
CORS(app)
# 数据目录
DATA_DIR = Path(__file__).parent.parent / 'data'
USERS_FILE = DATA_DIR / 'users.json'
CHATS_FILE = DATA_DIR / 'chats.json'
def load_users():
if USERS_FILE.exists():
return json.loads(USERS_FILE.read_text(encoding='utf-8'))
return {}
def load_chats():
if CHATS_FILE.exists():
return json.loads(CHATS_FILE.read_text(encoding='utf-8'))
return {}
# ============ 页面路由 ============
@app.route('/')
def index():
return render_template('index.html')
@app.route('/users')
def users_page():
return render_template('users.html')
@app.route('/chats')
def chats_page():
return render_template('chats.html')
# ============ API路由 ============
@app.route('/api/stats')
def api_stats():
users = load_users()
chats = load_chats()
# 统计消息数
total_messages = 0
for chat in chats.values():
total_messages += len(chat.get('messages', []))
# 今日新增用户
today = datetime.now().strftime('%Y-%m-%d')
today_users = sum(1 for u in users.values() if u.get('created_at', '').startswith(today))
# 今日活跃对话
today_chats = sum(1 for c in chats.values() if c.get('updated_at', '').startswith(today))
return jsonify({
'users_count': len(users),
'chats_count': len(chats),
'messages_count': total_messages,
'today_users': today_users,
'today_chats': today_chats,
})
@app.route('/api/users')
def api_users():
users = load_users()
user_list = []
for uid, user in users.items():
user_list.append({
'id': uid,
'username': user.get('username', ''),
'phone': user.get('phone', ''),
'email': user.get('email', ''),
'chats_count': len(user.get('chats', [])),
'created_at': user.get('created_at', ''),
})
# 按创建时间倒序
user_list.sort(key=lambda x: x['created_at'], reverse=True)
return jsonify(user_list)
@app.route('/api/users/<user_id>')
def api_user_detail(user_id):
users = load_users()
chats = load_chats()
user = users.get(user_id)
if not user:
return jsonify({'error': '用户不存在'}), 404
# 获取用户的对话列表
user_chats = []
for chat_id in user.get('chats', []):
if chat_id in chats:
chat = chats[chat_id]
user_chats.append({
'id': chat_id,
'title': chat.get('title', ''),
'dialect': chat.get('dialect', ''),
'messages_count': len(chat.get('messages', [])),
'created_at': chat.get('created_at', ''),
})
return jsonify({
'user': {
'id': user_id,
'username': user.get('username', ''),
'phone': user.get('phone', ''),
'email': user.get('email', ''),
'created_at': user.get('created_at', ''),
},
'chats': user_chats
})
@app.route('/api/users/<user_id>', methods=['DELETE'])
def api_delete_user(user_id):
users = load_users()
chats = load_chats()
if user_id not in users:
return jsonify({'error': '用户不存在'}), 404
# 删除用户的所有对话
for chat_id in users[user_id].get('chats', []):
if chat_id in chats:
del chats[chat_id]
# 删除用户
del users[user_id]
USERS_FILE.write_text(json.dumps(users, ensure_ascii=False, indent=2), encoding='utf-8')
CHATS_FILE.write_text(json.dumps(chats, ensure_ascii=False, indent=2), encoding='utf-8')
return jsonify({'success': True})
@app.route('/api/chats')
def api_chats():
chats = load_chats()
users = load_users()
chat_list = []
for cid, chat in chats.items():
user = users.get(chat.get('user_id', ''), {})
chat_list.append({
'id': cid,
'title': chat.get('title', ''),
'dialect': chat.get('dialect', ''),
'user_name': user.get('username', '未知'),
'messages_count': len(chat.get('messages', [])),
'created_at': chat.get('created_at', ''),
'updated_at': chat.get('updated_at', ''),
})
# 按更新时间倒序
chat_list.sort(key=lambda x: x['updated_at'], reverse=True)
return jsonify(chat_list)
@app.route('/api/chats/<chat_id>')
def api_chat_detail(chat_id):
chats = load_chats()
users = load_users()
chat = chats.get(chat_id)
if not chat:
return jsonify({'error': '对话不存在'}), 404
user = users.get(chat.get('user_id', ''), {})
return jsonify({
'id': chat_id,
'title': chat.get('title', ''),
'dialect': chat.get('dialect', ''),
'user': {
'id': chat.get('user_id', ''),
'username': user.get('username', '未知'),
},
'messages': chat.get('messages', []),
'created_at': chat.get('created_at', ''),
'updated_at': chat.get('updated_at', ''),
})
@app.route('/api/chats/<chat_id>', methods=['DELETE'])
def api_delete_chat(chat_id):
chats = load_chats()
users = load_users()
if chat_id not in chats:
return jsonify({'error': '对话不存在'}), 404
user_id = chats[chat_id].get('user_id')
# 删除对话
del chats[chat_id]
# 从用户列表中移除
if user_id and user_id in users:
if chat_id in users[user_id].get('chats', []):
users[user_id]['chats'].remove(chat_id)
CHATS_FILE.write_text(json.dumps(chats, ensure_ascii=False, indent=2), encoding='utf-8')
USERS_FILE.write_text(json.dumps(users, ensure_ascii=False, indent=2), encoding='utf-8')
return jsonify({'success': True})
@app.route('/api/dialect-stats')
def api_dialect_stats():
"""方言使用统计"""
chats = load_chats()
dialect_counts = {}
for chat in chats.values():
dialect = chat.get('dialect', 'mandarin')
dialect_counts[dialect] = dialect_counts.get(dialect, 0) + 1
return jsonify(dialect_counts)
@app.route('/api/export/users')
def api_export_users():
"""导出用户数据"""
users = load_users()
# 隐藏密码
export_data = []
for uid, user in users.items():
export_data.append({
'id': uid,
'username': user.get('username', ''),
'phone': user.get('phone', ''),
'email': user.get('email', ''),
'created_at': user.get('created_at', ''),
'chats_count': len(user.get('chats', [])),
})
return jsonify(export_data)
if __name__ == '__main__':
print("=" * 50)
print("方言AI助手 - 后台管理系统")
print("=" * 50)
print(f"访问地址: http://localhost:19003")
print("=" * 50)
app.run(host='0.0.0.0', port=19003, debug=True)

184
admin/templates/chats.html Normal file
View File

@@ -0,0 +1,184 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>对话管理 - 方言AI后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
</head>
<body class="bg-gray-50 min-h-screen">
<div class="flex">
<aside class="w-64 bg-slate-800 min-h-screen fixed left-0 top-0">
<div class="p-6">
<h1 class="text-white text-xl font-bold flex items-center gap-2">
<i class="ri-translate-2 text-2xl text-purple-400"></i>
方言AI后台
</h1>
</div>
<nav class="mt-6">
<a href="/" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-dashboard-line"></i><span>仪表盘</span>
</a>
<a href="/users" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-user-line"></i><span>用户管理</span>
</a>
<a href="/chats" class="flex items-center gap-3 px-6 py-3 bg-slate-700 text-white">
<i class="ri-chat-3-line"></i><span>对话管理</span>
</a>
</nav>
</aside>
<main class="ml-64 flex-1 p-8">
<h1 class="text-2xl font-bold text-gray-800 mb-6">对话管理</h1>
<!-- 对话列表 -->
<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
<table class="w-full">
<thead class="bg-gray-50 border-b border-gray-100">
<tr>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">标题</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">用户</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">方言</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">消息数</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">最后更新</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">操作</th>
</tr>
</thead>
<tbody id="chatTable">
<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">加载中...</td></tr>
</tbody>
</table>
</div>
<!-- 详情弹窗 -->
<div id="detailModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
<div class="bg-white rounded-xl w-3/4 max-w-3xl max-h-[80vh] overflow-hidden flex flex-col">
<div class="p-6 border-b border-gray-100 flex justify-between items-center">
<h2 class="text-xl font-bold text-gray-800" id="modalTitle">对话详情</h2>
<button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
<i class="ri-close-line text-2xl"></i>
</button>
</div>
<div class="p-6 overflow-auto flex-1" id="modalContent"></div>
</div>
</div>
</main>
</div>
<script>
const DIALECT_NAMES = {
'mandarin': '普通话',
'sichuan': '四川话',
'cantonese': '粤语',
'shanghai': '上海话',
'hakka': '客家话',
'minnan': '闽南话',
'northeast': '东北话',
'henan': '河南话'
};
async function loadChats() {
const response = await fetch('/api/chats');
const chats = await response.json();
const tbody = document.getElementById('chatTable');
if (chats.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">暂无对话</td></tr>';
return;
}
tbody.innerHTML = chats.map(c => `
<tr class="border-b border-gray-50 hover:bg-gray-50">
<td class="px-6 py-4 font-medium text-gray-800">${c.title}</td>
<td class="px-6 py-4 text-gray-600">${c.user_name}</td>
<td class="px-6 py-4">
<span class="px-2 py-1 bg-purple-100 text-purple-700 rounded text-xs">
${DIALECT_NAMES[c.dialect] || c.dialect}
</span>
</td>
<td class="px-6 py-4 text-gray-600">${c.messages_count}</td>
<td class="px-6 py-4 text-sm text-gray-500">
${c.updated_at ? new Date(c.updated_at).toLocaleString() : '-'}
</td>
<td class="px-6 py-4">
<button onclick="viewDetail('${c.id}')" class="text-blue-500 hover:text-blue-700 mr-3">
<i class="ri-eye-line"></i> 查看
</button>
<button onclick="deleteChat('${c.id}')" class="text-red-500 hover:text-red-700">
<i class="ri-delete-bin-line"></i>
</button>
</td>
</tr>
`).join('');
}
async function viewDetail(chatId) {
const response = await fetch(`/api/chats/${chatId}`);
const data = await response.json();
document.getElementById('modalTitle').textContent = data.title;
const content = document.getElementById('modalContent');
content.innerHTML = `
<div class="space-y-4">
<div class="grid grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg">
<div>
<p class="text-sm text-gray-500">用户</p>
<p class="font-medium">${data.user.username}</p>
</div>
<div>
<p class="text-sm text-gray-500">方言</p>
<p class="font-medium">${DIALECT_NAMES[data.dialect] || data.dialect}</p>
</div>
<div>
<p class="text-sm text-gray-500">消息数</p>
<p class="font-medium">${data.messages.length}</p>
</div>
</div>
<div class="border-t pt-4">
<h3 class="font-medium text-gray-800 mb-3">对话内容</h3>
<div class="space-y-3 max-h-96 overflow-auto">
${data.messages.map(m => `
<div class="flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}">
<div class="max-w-[80%] p-3 rounded-lg ${m.role === 'user' ? 'bg-purple-500 text-white' : 'bg-gray-100 text-gray-800'}">
<p class="text-sm whitespace-pre-wrap">${m.content}</p>
<p class="text-xs ${m.role === 'user' ? 'text-purple-200' : 'text-gray-400'} mt-1">
${m.time ? new Date(m.time).toLocaleString() : ''}
</p>
</div>
</div>
`).join('') || '<p class="text-gray-500">暂无消息</p>'}
</div>
</div>
</div>
`;
document.getElementById('detailModal').classList.remove('hidden');
document.getElementById('detailModal').classList.add('flex');
}
function closeModal() {
document.getElementById('detailModal').classList.add('hidden');
document.getElementById('detailModal').classList.remove('flex');
}
async function deleteChat(chatId) {
if (!confirm('确定要删除这个对话吗?')) return;
const response = await fetch(`/api/chats/${chatId}`, { method: 'DELETE' });
const data = await response.json();
if (data.success) {
loadChats();
} else {
alert('删除失败');
}
}
loadChats();
</script>
</body>
</html>

202
admin/templates/index.html Normal file
View File

@@ -0,0 +1,202 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>方言AI助手 - 后台管理</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
<style>
.sidebar { transition: all 0.3s; }
.card:hover { transform: translateY(-2px); box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1); }
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<div class="flex">
<!-- 侧边栏 -->
<aside class="sidebar w-64 bg-slate-800 min-h-screen fixed left-0 top-0">
<div class="p-6">
<h1 class="text-white text-xl font-bold flex items-center gap-2">
<i class="ri-translate-2 text-2xl text-purple-400"></i>
方言AI后台
</h1>
</div>
<nav class="mt-6">
<a href="/" class="flex items-center gap-3 px-6 py-3 bg-slate-700 text-white">
<i class="ri-dashboard-line"></i><span>仪表盘</span>
</a>
<a href="/users" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-user-line"></i><span>用户管理</span>
</a>
<a href="/chats" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话管理</span>
</a>
</nav>
</aside>
<!-- 主内容区 -->
<main class="ml-64 flex-1 p-8">
<!-- 统计卡片 -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="card bg-white rounded-xl p-6 shadow-sm border border-gray-100">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-sm">用户总数</p>
<p class="text-3xl font-bold text-gray-800 mt-2" id="stat-users">-</p>
</div>
<div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
<i class="ri-user-line text-2xl text-blue-600"></i>
</div>
</div>
<p class="text-xs text-gray-400 mt-2">今日新增: <span id="stat-today-users">0</span></p>
</div>
<div class="card bg-white rounded-xl p-6 shadow-sm border border-gray-100">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-sm">对话总数</p>
<p class="text-3xl font-bold text-gray-800 mt-2" id="stat-chats">-</p>
</div>
<div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
<i class="ri-chat-3-line text-2xl text-green-600"></i>
</div>
</div>
<p class="text-xs text-gray-400 mt-2">今日活跃: <span id="stat-today-chats">0</span></p>
</div>
<div class="card bg-white rounded-xl p-6 shadow-sm border border-gray-100">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-sm">消息总数</p>
<p class="text-3xl font-bold text-gray-800 mt-2" id="stat-messages">-</p>
</div>
<div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
<i class="ri-message-3-line text-2xl text-purple-600"></i>
</div>
</div>
</div>
<div class="card bg-white rounded-xl p-6 shadow-sm border border-gray-100">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-sm">最热方言</p>
<p class="text-xl font-bold text-gray-800 mt-2" id="stat-hot-dialect">-</p>
</div>
<div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
<i class="ri-fire-line text-2xl text-orange-600"></i>
</div>
</div>
</div>
</div>
<!-- 方言使用统计 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
<h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
<i class="ri-pie-chart-line text-purple-500"></i>
方言使用分布
</h2>
<div id="dialectChart" class="space-y-3">
<p class="text-gray-500">加载中...</p>
</div>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
<h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
<i class="ri-history-line text-blue-500"></i>
最近活跃用户
</h2>
<div id="recentUsers" class="space-y-3">
<p class="text-gray-500">加载中...</p>
</div>
</div>
</div>
</main>
</div>
<script>
const DIALECT_NAMES = {
'mandarin': '普通话',
'sichuan': '四川话',
'cantonese': '粤语',
'shanghai': '上海话',
'hakka': '客家话',
'minnan': '闽南话',
'northeast': '东北话',
'henan': '河南话'
};
async function loadStats() {
const response = await fetch('/api/stats');
const data = await response.json();
document.getElementById('stat-users').textContent = data.users_count;
document.getElementById('stat-chats').textContent = data.chats_count;
document.getElementById('stat-messages').textContent = data.messages_count;
document.getElementById('stat-today-users').textContent = data.today_users;
document.getElementById('stat-today-chats').textContent = data.today_chats;
}
async function loadDialectStats() {
const response = await fetch('/api/dialect-stats');
const data = await response.json();
const container = document.getElementById('dialectChart');
if (Object.keys(data).length === 0) {
container.innerHTML = '<p class="text-gray-500">暂无数据</p>';
return;
}
const total = Object.values(data).reduce((a, b) => a + b, 0);
const sorted = Object.entries(data).sort((a, b) => b[1] - a[1]);
// 设置最热方言
document.getElementById('stat-hot-dialect').textContent = DIALECT_NAMES[sorted[0][0]] || sorted[0][0];
container.innerHTML = sorted.map(([dialect, count]) => {
const percent = ((count / total) * 100).toFixed(1);
return `
<div class="flex items-center gap-3">
<span class="w-20 text-sm text-gray-600">${DIALECT_NAMES[dialect] || dialect}</span>
<div class="flex-1 bg-gray-100 rounded-full h-4">
<div class="bg-purple-500 h-4 rounded-full" style="width: ${percent}%"></div>
</div>
<span class="text-sm text-gray-500">${count} (${percent}%)</span>
</div>
`;
}).join('');
}
async function loadRecentUsers() {
const response = await fetch('/api/users');
const users = await response.json();
const container = document.getElementById('recentUsers');
if (users.length === 0) {
container.innerHTML = '<p class="text-gray-500">暂无用户</p>';
return;
}
container.innerHTML = users.slice(0, 5).map(u => `
<div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
<div>
<p class="font-medium text-gray-800">${u.username}</p>
<p class="text-xs text-gray-500">${u.phone}</p>
</div>
<div class="text-right">
<p class="text-sm text-purple-600">${u.chats_count} 个对话</p>
<p class="text-xs text-gray-400">${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</p>
</div>
</div>
`).join('');
}
// 初始化
loadStats();
loadDialectStats();
loadRecentUsers();
</script>
</body>
</html>

179
admin/templates/users.html Normal file
View File

@@ -0,0 +1,179 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户管理 - 方言AI后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
</head>
<body class="bg-gray-50 min-h-screen">
<div class="flex">
<aside class="w-64 bg-slate-800 min-h-screen fixed left-0 top-0">
<div class="p-6">
<h1 class="text-white text-xl font-bold flex items-center gap-2">
<i class="ri-translate-2 text-2xl text-purple-400"></i>
方言AI后台
</h1>
</div>
<nav class="mt-6">
<a href="/" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-dashboard-line"></i><span>仪表盘</span>
</a>
<a href="/users" class="flex items-center gap-3 px-6 py-3 bg-slate-700 text-white">
<i class="ri-user-line"></i><span>用户管理</span>
</a>
<a href="/chats" class="flex items-center gap-3 px-6 py-3 text-slate-300 hover:bg-slate-700 hover:text-white">
<i class="ri-chat-3-line"></i><span>对话管理</span>
</a>
</nav>
</aside>
<main class="ml-64 flex-1 p-8">
<div class="flex items-center justify-between mb-6">
<h1 class="text-2xl font-bold text-gray-800">用户管理</h1>
<button onclick="exportUsers()" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 flex items-center gap-2">
<i class="ri-download-line"></i> 导出
</button>
</div>
<!-- 用户列表 -->
<div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
<table class="w-full">
<thead class="bg-gray-50 border-b border-gray-100">
<tr>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">用户名</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">手机号</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">邮箱</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">对话数</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">注册时间</th>
<th class="px-6 py-3 text-left text-sm font-medium text-gray-500">操作</th>
</tr>
</thead>
<tbody id="userTable">
<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">加载中...</td></tr>
</tbody>
</table>
</div>
<!-- 详情弹窗 -->
<div id="detailModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
<div class="bg-white rounded-xl w-3/4 max-w-2xl max-h-[80vh] overflow-hidden flex flex-col">
<div class="p-6 border-b border-gray-100 flex justify-between items-center">
<h2 class="text-xl font-bold text-gray-800">用户详情</h2>
<button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
<i class="ri-close-line text-2xl"></i>
</button>
</div>
<div class="p-6 overflow-auto flex-1" id="modalContent"></div>
</div>
</div>
</main>
</div>
<script>
async function loadUsers() {
const response = await fetch('/api/users');
const users = await response.json();
const tbody = document.getElementById('userTable');
if (users.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="px-6 py-8 text-center text-gray-500">暂无用户</td></tr>';
return;
}
tbody.innerHTML = users.map(u => `
<tr class="border-b border-gray-50 hover:bg-gray-50">
<td class="px-6 py-4 font-medium text-gray-800">${u.username}</td>
<td class="px-6 py-4 text-gray-600">${u.phone || '-'}</td>
<td class="px-6 py-4 text-gray-600">${u.email || '-'}</td>
<td class="px-6 py-4">
<span class="px-2 py-1 bg-purple-100 text-purple-700 rounded text-xs">${u.chats_count}</span>
</td>
<td class="px-6 py-4 text-sm text-gray-500">
${u.created_at ? new Date(u.created_at).toLocaleString() : '-'}
</td>
<td class="px-6 py-4">
<button onclick="viewDetail('${u.id}')" class="text-blue-500 hover:text-blue-700 mr-3">
<i class="ri-eye-line"></i> 查看
</button>
<button onclick="deleteUser('${u.id}')" class="text-red-500 hover:text-red-700">
<i class="ri-delete-bin-line"></i>
</button>
</td>
</tr>
`).join('');
}
async function viewDetail(userId) {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
const content = document.getElementById('modalContent');
content.innerHTML = `
<div class="space-y-4">
<div class="grid grid-cols-2 gap-4">
<div>
<p class="text-sm text-gray-500">用户名</p>
<p class="font-medium">${data.user.username}</p>
</div>
<div>
<p class="text-sm text-gray-500">手机号</p>
<p class="font-medium">${data.user.phone || '-'}</p>
</div>
<div>
<p class="text-sm text-gray-500">邮箱</p>
<p class="font-medium">${data.user.email || '-'}</p>
</div>
<div>
<p class="text-sm text-gray-500">注册时间</p>
<p class="font-medium">${data.user.created_at ? new Date(data.user.created_at).toLocaleString() : '-'}</p>
</div>
</div>
<div class="pt-4 border-t">
<h3 class="font-medium text-gray-800 mb-3">对话列表 (${data.chats.length})</h3>
<div class="space-y-2 max-h-60 overflow-auto">
${data.chats.map(c => `
<div class="p-3 bg-gray-50 rounded-lg flex justify-between items-center">
<div>
<p class="font-medium text-gray-800">${c.title}</p>
<p class="text-xs text-gray-500">${c.dialect} · ${c.messages_count} 条消息</p>
</div>
</div>
`).join('') || '<p class="text-gray-500">暂无对话</p>'}
</div>
</div>
</div>
`;
document.getElementById('detailModal').classList.remove('hidden');
document.getElementById('detailModal').classList.add('flex');
}
function closeModal() {
document.getElementById('detailModal').classList.add('hidden');
document.getElementById('detailModal').classList.remove('flex');
}
async function deleteUser(userId) {
if (!confirm('确定要删除这个用户吗?这将同时删除该用户的所有对话!')) return;
const response = await fetch(`/api/users/${userId}`, { method: 'DELETE' });
const data = await response.json();
if (data.success) {
loadUsers();
} else {
alert('删除失败');
}
}
async function exportUsers() {
window.location.href = '/api/export/users';
}
loadUsers();
</script>
</body>
</html>