feat:项目完成

This commit is contained in:
2025-06-17 19:55:10 +08:00
commit e166ec615b
21 changed files with 1548 additions and 0 deletions

170
templates/login.html Normal file
View File

@@ -0,0 +1,170 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>登录 - 订单管理后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Poppins', sans-serif;
height: 100vh;
height: 100vh;
background: linear-gradient(-45deg, #1e3c72, #2a5298, #1e3c72, #2a5298);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
@keyframes gradientBG {
0% { background-position: 0% 50%; }
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
.login-container {
background-color: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(10px);
padding: 40px 30px;
border-radius: 16px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
width: 100%;
max-width: 400px;
transition: transform 0.3s ease;
}
.login-container:hover {
transform: translateY(-5px);
}
.login-container h2 {
text-align: center;
margin-bottom: 24px;
font-weight: 600;
letter-spacing: 1px;
}
form {
display: flex;
flex-direction: column;
}
label {
position: relative;
margin-bottom: 20px;
font-size: 14px;
}
input {
width: 100%;
padding: 12px 40px 12px 12px;
border: none;
border-radius: 8px;
background-color: rgba(255, 255, 255, 0.2);
color: rgb(12, 12, 12);
font-size: 1rem;
transition: all 0.3s ease;
}
input:focus {
outline: none;
background-color: rgba(255, 255, 255, 0.3);
}
label::before {
content: attr(data-icon);
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
font-size: 18px;
opacity: 0.7;
}
button {
margin-top: 10px;
padding: 12px;
background-color: #ffffff;
color: #1e3c72;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
}
button:hover {
background-color: #f0f0f0;
transform: scale(1.03);
}
button:active {
transform: scale(0.98);
}
#msg {
margin-top: 16px;
color: #ffdddd;
font-size: 0.9rem;
text-align: center;
}
@media (max-width: 500px) {
.login-container {
padding: 30px 20px;
}
}
</style>
</head>
<body>
<div class="login-container">
<h2>订单管理系统</h2>
<form id="loginForm">
<label data-icon="👤">
<input type="text" name="username" required placeholder="用户名" class="w-full px-4 py-2 rounded-lg bg-white/10 backdrop-blur-sm text-white placeholder:text-white/70 focus:outline-none focus:ring-2 focus:ring-white/50">
</label>
<label data-icon="🔒">
<input type="password" name="password" required placeholder="密码" class="w-full px-4 py-2 rounded-lg bg-white/10 backdrop-blur-sm text-white placeholder:text-white/70 focus:outline-none focus:ring-2 focus:ring-white/50">
</label>
<button type="submit" class="w-full mt-2 py-2 bg-white text-blue-900 font-bold rounded-lg hover:bg-gray-100/90 hover:shadow-lg transition-all duration-300">登 录</button>
</form>
<div id="msg"></div>
</div>
<script>
document.getElementById('loginForm').onsubmit = async function(e) {
e.preventDefault();
const username = this.username.value;
const password = this.password.value;
try {
const res = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await res.json();
if (data.token) {
localStorage.setItem('jwt', data.token);
window.location.href = '/orders/panel';
} else {
document.getElementById('msg').innerText = data.msg || '登录失败,请重试';
}
} catch (error) {
document.getElementById('msg').innerText = '网络错误,请检查连接';
}
};
</script>
</body>
</html>

187
templates/order_detail.html Normal file
View File

@@ -0,0 +1,187 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>订单详情 - 订单管理后台</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
<style>
body { background: #f4f6fb; font-family: 'Poppins', 'Microsoft YaHei', Arial, sans-serif; margin: 0; min-height: 100vh; }
.container { max-width: 500px; margin: 40px auto; background: #fff; border-radius: 16px; box-shadow: 0 6px 32px rgba(30,60,114,0.10); padding: 36px 28px 28px 28px; }
h2 { color: #2563eb; font-size: 2rem; font-weight: 700; margin-bottom: 18px; letter-spacing: 1px; }
.field { margin-bottom: 18px; }
.label { color: #1e293b; font-weight: 600; margin-bottom: 4px; }
.value { color: #222; font-size: 1.1rem; }
.back-btn { margin-bottom: 18px; background: #e0e7ef; color: #222; }
.back-btn:hover { background: #2563eb; color: #fff; }
#msg { margin: 10px 0 0 0; color: #e11d48; font-size: 1rem; text-align: center; min-height: 1.2em; }
</style>
</head>
<body>
<div class="container">
<h2>订单详情</h2>
<button class="back-btn" onclick="window.location.href='/orders/panel'">返回订单管理</button>
<div id="msg"></div>
<div id="detail"></div>
</div>
<script>
window.ORDER_ID = {{ order_id|tojson }};
</script>
<script>
const jwt = localStorage.getItem('jwt');
if (!jwt) location.href = '/login_page';
const msgBox = document.getElementById('msg');
const orderId = window.ORDER_ID;
async function fetchDetail() {
msgBox.innerText = '加载中...';
const res = await fetch(`/orders/${orderId}`, {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401) {
msgBox.innerText = '未登录或无权限';
setTimeout(()=>{window.location.href='/login_page';}, 1200);
return;
}
if (res.status === 404) {
msgBox.innerText = '订单不存在';
return;
}
const order = await res.json();
const detailElement = document.getElementById('detail');
detailElement.innerHTML = '';
// 订单ID
const idDiv = document.createElement('div');
idDiv.className = 'field';
idDiv.innerHTML = '<span class="label">订单ID</span><span class="value">' + order.id + '</span>';
// 标题
const titleDiv = document.createElement('div');
titleDiv.className = 'field';
titleDiv.innerHTML = '<span class="label">标题:</span><span class="value">' + order.title + '</span>';
// 描述
const descDiv = document.createElement('div');
descDiv.className = 'field';
descDiv.innerHTML = '<span class="label">描述:</span><span class="value">' + (order.description || '') + '</span>';
// 状态
const statusDiv = document.createElement('div');
statusDiv.className = 'field';
const statusLabel = document.createElement('span');
statusLabel.className = 'label';
statusLabel.textContent = '状态:';
const statusTag = document.createElement('span');
statusTag.className = 'value status-tag ' +
(order.status === "pending" ? "status-pending" : "status-completed");
statusTag.textContent = order.status === "pending" ? "待处理" : "已完成";
const statusSelect = document.createElement('select');
statusSelect.id = 'status-select';
statusSelect.className = 'status-select';
const pendingOption = document.createElement('option');
pendingOption.value = 'pending';
pendingOption.textContent = '待处理';
const completedOption = document.createElement('option');
completedOption.value = 'completed';
completedOption.textContent = '已完成';
statusSelect.appendChild(pendingOption);
statusSelect.appendChild(completedOption);
const updateBtn = document.createElement('button');
updateBtn.className = 'update-btn';
updateBtn.textContent = '更新状态';
updateBtn.onclick = updateStatus;
statusDiv.appendChild(statusLabel);
statusDiv.appendChild(statusTag);
statusDiv.appendChild(statusSelect);
statusDiv.appendChild(updateBtn);
// 创建时间
const timeDiv = document.createElement('div');
timeDiv.className = 'field';
timeDiv.innerHTML = '<span class="label">创建时间:</span><span class="value">' +
(order.created_at ? order.created_at.replace("T", " ").slice(0, 19) : "") + '</span>';
// 添加所有元素
detailElement.appendChild(idDiv);
detailElement.appendChild(titleDiv);
detailElement.appendChild(descDiv);
detailElement.appendChild(statusDiv);
detailElement.appendChild(timeDiv);
msgBox.innerText = '';
}
function updateStatus() {
const newStatus = document.getElementById('status-select').value;
fetch(`/orders/${orderId}`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + jwt,
'Content-Type': 'application/json'
},
body: JSON.stringify({ status: newStatus })
})
.then(res => {
if (res.status === 401) {
msgBox.innerText = '未登录或无权限';
setTimeout(() => window.location.href = '/login_page', 1200);
return;
}
if (res.status === 404) {
msgBox.innerText = '订单不存在';
return;
}
return res.json();
})
.then(data => {
if (data) {
msgBox.innerText = '状态更新成功';
fetchDetail();
}
})
.catch(error => {
msgBox.innerText = '网络错误,请重试';
});
}
fetchDetail();
</script>
<style>
.status-tag {
padding: 4px 8px;
border-radius: 4px;
font-size: 0.9rem;
margin-left: 8px;
}
.status-pending { background: #fee2e2; color: #be123c; }
.status-completed { background: #dcfce7; color: #15803d; }
.status-select {
margin-left: 8px;
padding: 4px 8px;
border-radius: 6px;
border: 1px solid #cbd5e1;
}
.update-btn {
margin-left: 12px;
padding: 4px 8px;
background: #2563eb;
color: #fff;
border: none;
border-radius: 6px;
cursor: pointer;
}
.update-btn:hover {
background: #1d4ed8;
}
</style>
</body>
</html>

526
templates/orders.html Normal file
View File

@@ -0,0 +1,526 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>订单管理后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;700&display=swap" rel="stylesheet">
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
body {
background: linear-gradient(-45deg, #1e3c72, #2a5298, #1e3c72, #2a5298);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
min-height: 100vh;
padding: 20px;
color: #fff;
}
@keyframes gradientBG {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.card {
background-color: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 20px;
margin: 20px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
transition: transform 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
}
</style>
</head>
<body>
<div class="container">
<h2 class="text-2xl font-bold mb-6 text-white">订单管理</h2>
<div class="absolute top-4 right-4 flex gap-2">
<button onclick="logout()" class="py-2 px-4 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">退出登录</button>
<button id="adminBtn" onclick="location.href='/users/panel'" class="py-2 px-4 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors hidden">账号管理</button>
</div>
<!-- 订单统计图表 -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="card p-6 bg-white/10 backdrop-blur-sm rounded-xl">
<h3 class="text-xl font-semibold mb-4 text-white">订单状态统计</h3>
<div id="orderChart" style="width: 100%; height: 400px;"></div>
<div class="mt-4 flex items-center">
<span class="text-white/80 mr-2">刷新频率(秒):</span>
<input type="number" id="refreshInterval" value="3" min="1" max="60"
class="w-16 px-2 py-1 bg-white/20 text-white rounded">
<button onclick="updateAllCharts()" class="ml-2 px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors">手动刷新</button>
</div>
</div>
<div class="card p-6 bg-white/10 backdrop-blur-sm rounded-xl">
<h3 class="text-xl font-semibold mb-4 text-white">热门商品Top5</h3>
<div id="topProductsChart" style="width: 100%; height: 400px;"></div>
</div>
<div class="card p-6 bg-white/10 backdrop-blur-sm rounded-xl">
<h3 class="text-xl font-semibold mb-4 text-white">订单评分统计</h3>
<div id="ratingChart" style="width: 100%; height: 400px;"></div>
</div>
</div>
<div class="card p-6 bg-white/10 backdrop-blur-sm rounded-xl">
<h3 class="text-xl font-semibold mb-4 text-white">订单类型统计</h3>
<div id="typeChart" style="width: 100%; height: 400px;"></div>
</div>
</div>
<div class="card mb-8 p-6 bg-white/10 backdrop-blur-sm rounded-xl">
<h3 class="text-xl font-semibold mb-4 text-white">新建订单</h3>
<form id="createForm">
<div class="mb-4">
<input type="text" name="title" placeholder="标题" required class="w-full px-4 py-2 rounded-lg bg-white/20 text-white placeholder:text-white/70 focus:outline-none focus:ring-2 focus:ring-white/50">
</div>
<div class="mb-4">
<input type="text" name="description" placeholder="描述" class="w-full px-4 py-2 rounded-lg bg-white/20 text-white placeholder:text-white/70 focus:outline-none focus:ring-2 focus:ring-white/50">
</div>
<button type="submit" class="w-full py-2 bg-green-500 text-white font-bold rounded-lg hover:bg-green-600 transition-colors">创建订单</button>
</form>
</div>
<h3 class="text-xl font-semibold mb-4 text-white">订单列表</h3>
<div class="overflow-x-auto">
<table id="ordersTable" class="w-full text-sm text-left text-white/80">
<thead class="text-xs uppercase bg-white/10">
<tr>
<th class="px-6 py-3">ID</th>
<th class="px-6 py-3">标题</th>
<th class="px-6 py-3">描述</th>
<th class="px-6 py-3">状态</th>
<th class="px-6 py-3">操作</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<script>
const jwt = localStorage.getItem('jwt');
if (!jwt) location.href = '/login_page';
async function fetchOrders() {
const res = await fetch('/orders/', {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401) {
localStorage.removeItem('jwt');
location.href = '/login_page';
return;
}
const orders = await res.json();
const tbody = document.querySelector('#ordersTable tbody');
tbody.innerHTML = '';
orders.forEach(order => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${order.id}</td>
<td><input value="${order.title}" onchange="updateOrder(${order.id}, 'title', this.value)" class="w-full px-3 py-1 bg-transparent text-white/90 focus:outline-none focus:ring-2 focus:ring-blue-500/50 rounded"></td>
<td><input value="${order.description||''}" onchange="updateOrder(${order.id}, 'description', this.value)" class="w-full px-3 py-1 bg-transparent text-white/90 focus:outline-none focus:ring-2 focus:ring-blue-500/50 rounded"></td>
<td>
<select onchange="updateOrder(${order.id}, 'status', this.value)" style="background-color: transparent;">
<option value="pending" class="bg-blue-900 text-white" ${order.status === 'pending' ? 'selected' : ''}>待处理</option>
<option value="in_progress" class="bg-blue-900 text-white" ${order.status === 'in_progress' ? 'selected' : ''}>处理中</option>
<option value="completed" class="bg-blue-900 text-white" ${order.status === 'completed' ? 'selected' : ''}>已完成</option>
</select>
</td>
<td><button onclick="deleteOrder(${order.id})" class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors">删除</button></td>
`;
tbody.appendChild(tr);
});
}
async function updateOrder(id, field, value) {
const body = {};
body[field] = value;
await fetch('/orders/' + id, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + jwt
},
body: JSON.stringify(body)
});
fetchOrders();
}
async function deleteOrder(id) {
await fetch('/orders/' + id, {
method: 'DELETE',
headers: {Authorization: 'Bearer ' + jwt}
});
fetchOrders();
}
document.getElementById('createForm').onsubmit = async function(e) {
e.preventDefault();
const title = this.title.value;
const description = this.description.value;
await fetch('/orders/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + jwt
},
body: JSON.stringify({title, description})
});
this.reset();
fetchOrders();
};
function logout() {
localStorage.removeItem('jwt');
location.href = '/login_page';
}
// 初始化图表
const chartDom = document.getElementById('orderChart');
const myChart = echarts.init(chartDom);
// 获取订单统计数据
async function fetchOrderSummary() {
const res = await fetch('/orders/summary', {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401) {
localStorage.removeItem('jwt');
location.href = '/login_page';
return;
}
return await res.json();
}
// 获取类型统计数据
async function fetchTypeSummary() {
const res = await fetch('/orders/type_summary', {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401) {
localStorage.removeItem('jwt');
location.href = '/login_page';
return;
}
return await res.json();
}
// 获取评分统计数据
async function fetchRatingSummary() {
const res = await fetch('/orders/rating_summary', {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401) {
localStorage.removeItem('jwt');
location.href = '/login_page';
return;
}
return await res.json();
}
// 初始化类型图表
const typeChartDom = document.getElementById('typeChart');
const typeChart = echarts.init(typeChartDom);
// 初始化评分图表
const ratingChartDom = document.getElementById('ratingChart');
const ratingChart = echarts.init(ratingChartDom);
// 更新类型图表
async function updateTypeChart() {
const data = await fetchTypeSummary();
if (!data) return;
const option = {
backgroundColor: 'transparent',
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
right: 10,
top: 'center',
textStyle: { color: '#fff' }
},
series: [{
name: '订单类型',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: 'rgba(255, 255, 255, 0.2)',
borderWidth: 2
},
label: {
show: true,
color: '#fff',
formatter: '{b}: {c} ({d}%)'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
data: data.map(item => ({
value: item.count,
name: item.order_type
}))
}]
};
typeChart.setOption(option);
}
// 获取热门商品数据
async function fetchTopProducts() {
const res = await fetch('/orders/top_products', {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401) {
localStorage.removeItem('jwt');
location.href = '/login_page';
return;
}
return await res.json();
}
// 初始化热门商品图表
const topProductsChartDom = document.getElementById('topProductsChart');
const topProductsChart = echarts.init(topProductsChartDom);
// 更新热门商品图表
async function updateTopProductsChart() {
const data = await fetchTopProducts();
if (!data) return;
console.log('Top products data:', data); // 调试日志
// 确保数据按销量降序排列
data.sort((a, b) => b.sales_count - a.sales_count);
const option = {
backgroundColor: 'transparent',
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value',
axisLine: { lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
yAxis: {
type: 'category',
data: data.map(item => item.product_name),
axisLine: { lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff' }
},
series: [{
name: '销量',
type: 'bar',
data: data.map(item => item.sales_count),
label: {
show: true,
position: 'right',
formatter: '{c}',
color: '#fff'
},
itemStyle: {
color: function(params) {
// 渐变色
const colorList = ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae'];
return colorList[params.dataIndex];
},
borderRadius: [0, 4, 4, 0]
},
label: {
show: true,
position: 'right',
color: '#fff'
}
}]
};
topProductsChart.setOption(option);
}
// 更新所有图表
async function updateAllCharts() {
await updateOrderChart();
await updateTopProductsChart();
await updateRatingChart();
await updateTypeChart();
}
// 更新订单图表
async function updateOrderChart() {
const data = await fetchOrderSummary();
if (!data) return;
const option = {
backgroundColor: 'transparent',
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
right: 10,
top: 'center',
textStyle: { color: '#fff' }
},
series: [{
name: '订单状态',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: 'rgba(255, 255, 255, 0.2)',
borderWidth: 2
},
label: {
show: true,
color: '#fff',
formatter: '{b}: {c} ({d}%)'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
data: data.map(item => ({
value: item.count,
name: item.status // 直接用后端返回的 status 字段
}))
}]
};
myChart.setOption(option);
}
// 更新评分图表
async function updateRatingChart() {
const data = await fetchRatingSummary();
if (!data) return;
// 确保数据格式正确
const option = {
backgroundColor: 'transparent',
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' }
},
legend: {
data: data.series.map(item => item.name),
textStyle: { color: '#fff' }
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
data: data.categories,
axisLine: { lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff' }
},
yAxis: {
type: 'value',
axisLine: { lineStyle: { color: '#fff' } },
axisLabel: { color: '#fff' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
series: data.series.map(item => ({
name: item.name,
type: 'bar',
stack: 'total',
emphasis: { focus: 'series' },
data: item.data,
itemStyle: {
borderRadius: [4, 4, 0, 0],
color: function(params) {
const colors = {
'差评': '#ff4d4f',
'中评': '#faad14',
'好评': '#52c41a'
};
// 确保颜色与图例顺序一致
const colorMap = {
'差评': '#ff4d4f',
'中评': '#faad14',
'好评': '#52c41a'
};
return colorMap[params.seriesName] || '#1890ff';
}
}
}))
};
ratingChart.setOption(option);
}
// 自动刷新图表
let refreshTimer;
function startAutoRefresh() {
const interval = parseInt(document.getElementById('refreshInterval').value) * 1000;
if (refreshTimer) clearInterval(refreshTimer);
refreshTimer = setInterval(updateAllCharts, interval);
}
// 检查用户角色
async function checkAdmin() {
try {
const token = jwt.split('.')[1];
const payload = JSON.parse(atob(token));
if (payload.role === 'admin') {
document.getElementById('adminBtn').classList.remove('hidden');
}
} catch (e) {
console.error('Error checking admin role:', e);
}
}
// 初始化
checkAdmin();
fetchOrders();
updateAllCharts();
startAutoRefresh();
// 监听刷新频率变化
document.getElementById('refreshInterval').addEventListener('change', startAutoRefresh);
// 响应式调整图表大小
window.addEventListener('resize', function() {
myChart.resize();
topProductsChart.resize();
ratingChart.resize();
typeChart.resize();
});
</script>
</body>
</html>

205
templates/users.html Normal file
View File

@@ -0,0 +1,205 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>用户管理 - 订单管理后台</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;700&display=swap" rel="stylesheet">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Poppins', sans-serif; }
body {
background: linear-gradient(-45deg, #1e3c72, #2a5298, #1e3c72, #2a5298);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
min-height: 100vh;
padding: 20px;
color: #fff;
}
@keyframes gradientBG {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
.container {
max-width: 900px;
margin: 0 auto;
padding: 20px;
}
.card {
background-color: rgba(255, 255, 255, 0.08);
backdrop-filter: blur(10px);
border-radius: 16px;
padding: 20px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
transition: transform 0.3s ease;
}
.card:hover { transform: translateY(-5px); }
</style>
</head>
<body>
<div class="container">
<h2 class="text-2xl font-bold mb-6 text-white">用户管理</h2>
<button class="py-2 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors mb-4" onclick="window.location.href='/orders/panel'">返回订单管理</button>
<button class="py-2 px-4 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors mb-4 ml-2" onclick="window.location.href='/users/panel'">刷新用户列表</button>
<div id="msg" class="my-2 text-red-300 text-center min-h-[1.2em]"></div>
<div class="card mb-6">
<h3 class="text-lg font-semibold mb-4 text-white">新增用户</h3>
<form id="createUserForm" class="flex flex-col md:flex-row gap-4 items-center">
<input type="text" name="username" required placeholder="用户名" class="px-4 py-2 rounded-lg bg-white/20 text-blue-900 placeholder:text-blue-900/70 focus:outline-none focus:ring-2 focus:ring-blue-400/50">
<input type="password" name="password" required placeholder="密码" class="px-4 py-2 rounded-lg bg-white/20 text-blue-900 placeholder:text-blue-900/70 focus:outline-none focus:ring-2 focus:ring-blue-400/50">
<select name="role" class="px-4 py-2 rounded-lg bg-white/20 text-blue-900">
<option value="user">普通用户</option>
<option value="admin">管理员</option>
</select>
<button type="submit" class="py-2 px-4 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors">新增</button>
</form>
</div>
<div class="card">
<div class="overflow-x-auto">
<table id="usersTable" class="w-full text-sm text-left text-white/80">
<thead class="text-xs uppercase bg-white/10">
<tr><th class="px-6 py-3">ID</th><th class="px-6 py-3">用户名</th><th class="px-6 py-3">角色</th><th class="px-6 py-3 text-center">操作</th></tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
<script>
const jwt = localStorage.getItem('jwt');
if (!jwt) location.href = '/login_page';
const msgBox = document.getElementById('msg');
async function fetchUsers() {
msgBox.innerText = '加载中...';
const res = await fetch('/users/', {
headers: {Authorization: 'Bearer ' + jwt}
});
if (res.status === 401 || res.status === 403) {
msgBox.innerText = '无权限访问';
setTimeout(()=>{window.location.href='/orders/panel';}, 1200);
return;
}
const users = await res.json();
const tbody = document.querySelector('#usersTable tbody');
tbody.innerHTML = '';
users.forEach(user => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td class="px-6 py-2">${user.id}</td>
<td class="px-6 py-2">${user.username}</td>
<td class="px-6 py-2">${user.role}</td>
<td class="px-6 py-2 text-center">
<button class="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 transition-colors mr-2" onclick="editUser(${user.id})">编辑</button>
<button class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors" onclick="deleteUser(${user.id})">删除</button>
</td>
`;
tbody.appendChild(tr);
});
msgBox.innerText = '';
}
fetchUsers();
function editUser(userId) {
// 获取当前用户信息
const user = Array.from(document.querySelectorAll('#usersTable tbody tr'))
.map(tr => ({
id: parseInt(tr.children[0].textContent),
username: tr.children[1].textContent,
role: tr.children[2].textContent
}))
.find(u => u.id === userId);
const editModal = document.createElement('div');
editModal.style.position = 'fixed';
editModal.style.top = '0';
editModal.style.left = '0';
editModal.style.width = '100%';
editModal.style.height = '100%';
editModal.style.backgroundColor = 'rgba(0,0,0,0.5)';
editModal.style.display = 'flex';
editModal.style.justifyContent = 'center';
editModal.style.alignItems = 'center';
editModal.style.zIndex = '1000';
editModal.innerHTML = `
<div class="bg-white/90 p-8 rounded-xl shadow-lg w-[320px]">
<h3 class="text-lg font-bold mb-4 text-blue-900">编辑用户</h3>
<div class="mb-4">
<label class="block text-blue-900 mb-1">用户名:
<input type="text" id="editUsername" value="${user ? user.username : ''}" class="w-full px-3 py-2 rounded bg-gray-100 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-400" />
</label>
</div>
<div class="mb-4">
<label class="block text-blue-900 mb-1">角色:
<select id="editRole" class="w-full px-3 py-2 rounded bg-gray-100 border border-gray-300">
<option value="admin" ${user && user.role === 'admin' ? 'selected' : ''}>管理员</option>
<option value="user" ${user && user.role === 'user' ? 'selected' : ''}>普通用户</option>
</select>
</label>
</div>
<div class="flex justify-between">
<button class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600" onclick="updateUser(${userId})">保存</button>
<button class="px-4 py-2 bg-gray-400 text-white rounded hover:bg-gray-500" onclick="this.parentNode.parentNode.parentNode.remove()">取消</button>
</div>
</div>
`;
document.body.appendChild(editModal);
}
async function updateUser(userId) {
const username = document.getElementById('editUsername').value;
const role = document.getElementById('editRole').value;
const jwt = localStorage.getItem('jwt');
const res = await fetch(`/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + jwt
},
body: JSON.stringify({username, role})
});
if (res.ok) {
alert('用户信息更新成功');
document.querySelector('div[style*="position: fixed"]').remove();
fetchUsers();
} else {
alert('更新失败: ' + (await res.text()));
}
}
document.getElementById('createUserForm').onsubmit = async function(e) {
e.preventDefault();
const username = this.username.value;
const password = this.password.value;
const role = this.role.value;
const jwt = localStorage.getItem('jwt');
const res = await fetch('/users/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + jwt
},
body: JSON.stringify({ username, password, role })
});
if (res.ok) {
this.reset();
fetchUsers();
} else {
alert('新增失败: ' + (await res.text()));
}
}
async function deleteUser(userId) {
if (!confirm('确定要删除该用户吗?')) return;
const jwt = localStorage.getItem('jwt');
const res = await fetch(`/users/${userId}`, {
method: 'DELETE',
headers: { 'Authorization': 'Bearer ' + jwt }
});
if (res.ok) {
fetchUsers();
} else {
alert('删除失败: ' + (await res.text()));
}
}
</script>
</body>
</html>