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

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.venv

20
Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
# 使用官方 Python 运行时作为父镜像
FROM python:3.11-slim
# 设置工作目录
WORKDIR /app
# 复制依赖文件
COPY requirements.txt .
# 安装依赖
RUN pip install --no-cache-dir -r requirements.txt
# 复制项目文件
COPY . .
# 暴露端口假设你的应用运行在8000端口
EXPOSE 8000
# 启动命令假设用uvicorn启动FastAPI如果是Flask请替换为flask run
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

26
app/__init__.py Normal file
View File

@@ -0,0 +1,26 @@
from flask import Flask, request, g
from flask_cors import CORS
from .routes import auth_bp, order_bp
import time
from datetime import datetime
def create_app():
app = Flask(__name__, static_folder="../static", template_folder="../templates")
app.config['SECRET_KEY'] = 'your-secret-key'
CORS(app)
# 添加性能监控中间件
@app.before_request
def before_request():
g.start_time = time.time()
@app.after_request
def after_request(response):
if hasattr(g, 'start_time'):
duration = round((time.time() - g.start_time) * 1000, 2)
app.logger.info(f"[{datetime.now()}] {request.method} {request.path} - {duration}ms")
return response
app.register_blueprint(auth_bp)
app.register_blueprint(order_bp, url_prefix='/orders')
return app

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

35
app/db.py Normal file
View File

@@ -0,0 +1,35 @@
from sqlmodel import create_engine, SQLModel
from sqlalchemy.pool import QueuePool
from sqlalchemy import text
from app.models import UserRole, OrderStatus
import time
def wait_for_db(max_retries=5, delay=5):
"""等待数据库连接可用"""
for i in range(max_retries):
try:
test_engine = create_engine(
"mysql+pymysql://root:123456@niit-node3/orders_db",
poolclass=QueuePool,
pool_size=10,
max_overflow=20,
pool_timeout=30,
pool_recycle=3600,
echo=False
)
with test_engine.connect() as conn:
conn.execute(text("SELECT 1"))
print(f"数据库连接测试成功 (尝试 {i+1}/{max_retries})")
return test_engine
except Exception as e:
if i == max_retries - 1:
raise
time.sleep(delay)
return None
# 使用连接池的数据库引擎
engine = wait_for_db()
# 创建数据库表
def init_db():
SQLModel.metadata.create_all(engine)

31
app/models.py Normal file
View File

@@ -0,0 +1,31 @@
from sqlmodel import SQLModel, Field
from typing import Optional
from enum import Enum
import datetime
class UserRole(str, Enum):
admin = "admin"
user = "user"
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
username: str = Field(index=True, unique=True)
password_hash: str
role: UserRole = Field(default=UserRole.user)
class OrderStatus(str, Enum):
pending = "pending"
in_progress = "in_progress"
completed = "completed"
class Order(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
title: str
description: Optional[str] = None
created_at: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
status: OrderStatus = Field(default=OrderStatus.pending)
class TopProductSummary(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
product_name: str = Field(index=True)
sales_count: int = Field(default=0)

250
app/routes.py Normal file
View File

@@ -0,0 +1,250 @@
from flask import Blueprint, request, jsonify, g, render_template, redirect, url_for
from sqlmodel import Session, select
from sqlalchemy import text
from .models import User, Order
from .schemas import UserLogin, OrderCreate, OrderUpdate, UserUpdate
from .utils import hash_password, verify_password, create_jwt_token, decode_jwt_token, admin_required
from .db import engine
from .schemas import OrderStatus
auth_bp = Blueprint('auth', __name__)
order_bp = Blueprint('order', __name__)
def jwt_required(f):
def wrapper(*args, **kwargs):
auth = request.headers.get('Authorization', None)
if not auth or not auth.startswith('Bearer '):
return jsonify({'msg': 'Missing or invalid token'}), 401
token = auth.split(' ')[1]
user_data = decode_jwt_token(token)
if not user_data:
return jsonify({'msg': 'Token invalid or expired'}), 401
g.user_id = user_data['user_id']
g.role = user_data['role']
return f(*args, **kwargs)
wrapper.__name__ = f.__name__
return wrapper
@auth_bp.route('/login', methods=['POST'])
def login():
data = request.get_json()
login_data = UserLogin(**data)
with Session(engine) as session:
user = session.exec(select(User).where(User.username == login_data.username)).first()
if not user or not verify_password(login_data.password, user.password_hash):
return jsonify({'msg': 'Invalid credentials'}), 401
token = create_jwt_token(user)
return jsonify({'token': token})
@auth_bp.route('/')
def index():
return redirect(url_for('auth.login_page'))
@auth_bp.route('/login_page')
def login_page():
return render_template('login.html')
# 订单管理接口
@order_bp.route('/', methods=['GET'])
@jwt_required
def list_orders():
with Session(engine) as session:
orders = session.exec(select(Order)).all()
return jsonify([order.dict() for order in orders])
@order_bp.route('/', methods=['POST'])
@jwt_required
def create_order():
data = request.get_json()
order_data = OrderCreate(**data)
order = Order(title=order_data.title, description=order_data.description)
with Session(engine) as session:
session.add(order)
session.commit()
session.refresh(order)
return jsonify(order.dict()), 201
@order_bp.route('/<int:order_id>', methods=['PUT'])
@jwt_required
def update_order(order_id):
data = request.get_json()
with Session(engine) as session:
order = session.get(Order, order_id)
if not order:
return jsonify({'msg': 'Order not found'}), 404
update_data = OrderUpdate(**data)
for field, value in update_data.dict(exclude_unset=True).items():
if field == "status" and value is not None:
order.status = value
elif field != "status":
setattr(order, field, value)
session.add(order)
session.commit()
return jsonify(order.dict())
@order_bp.route('/<int:order_id>', methods=['DELETE'])
@jwt_required
def delete_order(order_id):
with Session(engine) as session:
order = session.get(Order, order_id)
if not order:
return jsonify({'msg': 'Order not found'}), 404
session.delete(order)
session.commit()
return jsonify({'msg': 'Deleted'})
@auth_bp.route('/users/<int:user_id>', methods=['PUT'])
@jwt_required
def update_user(user_id):
data = request.get_json()
update_data = UserUpdate(**data)
with Session(engine) as session:
user = session.get(User, user_id)
if not user:
return jsonify({'msg': 'User not found'}), 404
for field, value in update_data.dict(exclude_unset=True).items():
setattr(user, field, value)
session.add(user)
session.commit()
return jsonify(user.dict())
@order_bp.route('/panel')
def order_panel():
return render_template('orders.html')
@order_bp.route('/summary')
@jwt_required
def get_order_summary():
with Session(engine) as session:
# 查询all_orders_summary表按status分组统计count总和
result = session.execute(
text("SELECT status, SUM(count) as total_count "
"FROM all_orders_summary "
"GROUP BY status")
).fetchall()
# 转换为字典列表格式
status_mapping = {
"0": "差评",
"50": "中评",
"100": "好评"
}
summary = [{"status": status_mapping.get(str(row[0]), str(row[0])), "count": row[1]} for row in result]
return jsonify(summary)
@order_bp.route('/rating_summary')
@jwt_required
def get_rating_summary():
with Session(engine) as session:
# 查询each_order_summary表按order_id和status分组统计
result = session.execute(
text("SELECT order_id, status, SUM(count) as total_count "
"FROM each_order_summary "
"GROUP BY order_id, status "
"ORDER BY order_id, status")
).fetchall()
# 获取所有种类
categories = sorted({row[0] for row in result})
status_mapping = {
"0": "差评",
"50": "中评",
"100": "好评"
}
# 初始化数据结构,确保每个种类都有三种评分
series_data = {
"差评": [0] * len(categories),
"中评": [0] * len(categories),
"好评": [0] * len(categories)
}
# 填充数据
for row in result:
category_idx = categories.index(row[0])
status = status_mapping[row[1]]
series_data[status][category_idx] = row[2]
return jsonify({
"categories": categories,
"series": [
{"name": "差评", "data": series_data["差评"]},
{"name": "中评", "data": series_data["中评"]},
{"name": "好评", "data": series_data["好评"]}
]
})
@order_bp.route('/type_summary')
@jwt_required
def get_type_summary():
with Session(engine) as session:
# 查询order_type_summary表按order_type分组统计count总和
result = session.execute(
text("SELECT order_type, SUM(count) as total_count "
"FROM order_type_summary "
"GROUP BY order_type")
).fetchall()
# 转换为字典列表格式
summary = [{"order_type": row[0], "count": row[1]} for row in result]
return jsonify(summary)
@order_bp.route('/top_products')
@jwt_required
def get_top_products():
with Session(engine) as session:
# 查询top_products_summary表按sales_count降序获取前5条记录
result = session.execute(
text("SELECT order_type, SUM(count) as total_count "
"FROM order_type_summary "
"GROUP BY order_type"
" ORDER BY total_count DESC "
"LIMIT 5")
).fetchall()
# 转换为字典列表格式
top_products = [{"product_name": row[0], "sales_count": row[1]} for row in result]
return jsonify(top_products)
@auth_bp.route('/users/', methods=['GET'])
@jwt_required
@admin_required
def list_users():
with Session(engine) as session:
users = session.exec(select(User)).all()
return jsonify([user.dict() for user in users])
@auth_bp.route('/users/panel')
def users_panel():
return render_template('users.html')
@auth_bp.route('/users/', methods=['POST'])
@jwt_required
@admin_required
def create_user():
data = request.get_json()
username = data.get('username')
password = data.get('password')
role = data.get('role', 'user')
if not username or not password:
return jsonify({'msg': '用户名和密码必填'}), 400
with Session(engine) as session:
if session.exec(select(User).where(User.username == username)).first():
return jsonify({'msg': '用户名已存在'}), 400
from .utils import hash_password
user = User(username=username, password_hash=hash_password(password), role=role)
session.add(user)
session.commit()
return jsonify(user.dict()), 201
@auth_bp.route('/users/<int:user_id>', methods=['DELETE'])
@jwt_required
@admin_required
def delete_user(user_id):
with Session(engine) as session:
user = session.get(User, user_id)
if not user:
return jsonify({'msg': '用户不存在'}), 404
session.delete(user)
session.commit()
return jsonify({'msg': '已删除'})

28
app/schemas.py Normal file
View File

@@ -0,0 +1,28 @@
from pydantic import BaseModel
from enum import Enum as PydanticEnum
class UserRole(str, PydanticEnum):
admin = "admin"
user = "user"
class UserLogin(BaseModel):
username: str
password: str
class OrderStatus(str, PydanticEnum):
pending = "pending"
in_progress = "in_progress"
completed = "completed"
class OrderCreate(BaseModel):
title: str
description: str = ""
class OrderUpdate(BaseModel):
title: str = None
description: str = None
status: OrderStatus = None
class UserUpdate(BaseModel):
username: str = None
role: UserRole = None

41
app/utils.py Normal file
View File

@@ -0,0 +1,41 @@
import jwt
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, timedelta
from flask import current_app, request, jsonify
def hash_password(password):
return generate_password_hash(password)
def verify_password(password, password_hash):
return check_password_hash(password_hash, password)
def create_jwt_token(user):
payload = {
'user_id': user.id,
'role': user.role,
'exp': datetime.utcnow() + timedelta(days=1)
}
token = jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')
return token
def decode_jwt_token(token):
try:
payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
return {'user_id': payload['user_id'], 'role': payload['role']}
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
def admin_required(f):
def wrapper(*args, **kwargs):
auth = request.headers.get('Authorization', None)
if not auth or not auth.startswith('Bearer '):
return jsonify({'msg': 'Missing or invalid token'}), 401
token = auth.split(' ')[1]
user_data = decode_jwt_token(token)
if not user_data or user_data.get('role') != 'admin':
return jsonify({'msg': 'Admin access required'}), 403
return f(*args, **kwargs)
wrapper.__name__ = f.__name__
return wrapper

20
main.py Normal file
View File

@@ -0,0 +1,20 @@
from app import create_app
from app.models import SQLModel, User
from app.db import engine
from app.utils import hash_password
def init_db():
SQLModel.metadata.create_all(engine)
# 创建初始管理员
from sqlmodel import Session, select
with Session(engine) as session:
admin = session.exec(select(User).where(User.username == "admin")).first()
if not admin:
admin = User(username="admin", password_hash=hash_password("admin123"),role="admin")
session.add(admin)
session.commit()
if __name__ == '__main__':
init_db()
app = create_app()
app.run(debug=True,host='0.0.0.0',port=5000)

BIN
order_ms.db Normal file

Binary file not shown.

8
requirements.txt Normal file
View File

@@ -0,0 +1,8 @@
flask
sqlmodel
pydantic
pyjwt
werkzeug
flask-cors
pymysql
pyecharts

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>