v4.4 数据报表/操作日志/系统设置与月度分排行
1. 月度分排行:管理端首页支持总分/月度分切换与月份选择,新增排行榜导出CSV 2. 数据报表:新增考勤/作业统计页(日期范围、汇总与每人明细、CSV导出) 3. 操作日志:新增查看页(操作类型/操作人/日期筛选,分页) 4. 系统设置:密码策略可配置(长度/字符种类),全站改密与重置统一校验、前端提示同步;策略通过公开配置下发 5. 学期归档对比:查看归档时展示与上一学期的分数变化与名次升降 6. 历史记录导出支持按学生分表(每人一段,便于发家长) 7. 移动端适配:导航横向滚动、表格触控滚动、字号与弹窗优化 8. 版本升级至4.4(无数据库结构变更)
This commit is contained in:
1 parent
9a19add6c1
commit
768ea281e0
54 files changed
+1782
-90
No files matched your search
+2
-1
@@ -23,7 +23,7 @@ from utils.database import init_db_pool, close_db_pool
|
||||
from utils.redis_client import init_redis_pool, close_redis_pool
|
||||
from utils.email_sender import EmailSender
|
||||
from middleware.auth_middleware import AuthMiddleware
|
||||
from routes import auth, student, parent, admin, subject, semester, debug, upgrade
|
||||
from routes import auth, student, parent, admin, subject, semester, debug, upgrade, report
|
||||
from routes.config import router as config_router
|
||||
|
||||
|
||||
@@ -140,6 +140,7 @@ app.include_router(parent.router, prefix="/api/parent", tags=["家长端"])
|
||||
app.include_router(admin.router, prefix="/api/admin", tags=["管理端"])
|
||||
app.include_router(subject.router, prefix="/api/subject", tags=["科目管理"])
|
||||
app.include_router(semester.router, prefix="/api/semester", tags=["学期管理"])
|
||||
app.include_router(report.router, prefix="/api/report", tags=["统计报表"])
|
||||
app.include_router(config_router, prefix="/api/config", tags=["配置"])
|
||||
app.include_router(upgrade.router, prefix="/api/upgrade", tags=["升级管理"])
|
||||
app.include_router(debug.router, tags=["调试"])
|
||||
|
||||
+74
-1
@@ -9,7 +9,8 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from utils.database import execute_insert
|
||||
from typing import Dict, Any, List
|
||||
from utils.database import execute_insert, execute_one, execute_query
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -62,3 +63,75 @@ class OperationLogModel:
|
||||
"""
|
||||
return await execute_insert(sql, (operator_id, operator_name, operator_role,
|
||||
operation_type, target_type, target_id, details, ip_address))
|
||||
|
||||
@staticmethod
|
||||
def _build_filters(
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None
|
||||
):
|
||||
conditions = ["1=1"]
|
||||
params = []
|
||||
if operation_type:
|
||||
conditions.append("operation_type = %s")
|
||||
params.append(operation_type)
|
||||
if operator:
|
||||
conditions.append("(operator_name LIKE %s OR operator_role LIKE %s)")
|
||||
params.extend([f"%{operator}%", f"%{operator}%"])
|
||||
if start_date:
|
||||
conditions.append("DATE(created_at) >= %s")
|
||||
params.append(start_date)
|
||||
if end_date:
|
||||
conditions.append("DATE(created_at) <= %s")
|
||||
params.append(end_date)
|
||||
return " AND ".join(conditions), params
|
||||
|
||||
@staticmethod
|
||||
async def get_logs(
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
limit: int = 20,
|
||||
offset: int = 0
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""查询操作日志(分页)"""
|
||||
where, params = OperationLogModel._build_filters(
|
||||
operation_type, operator, start_date, end_date
|
||||
)
|
||||
sql = f"""
|
||||
SELECT log_id, operator_id, operator_name, operator_role,
|
||||
operation_type, target_type, target_id, details, ip_address, created_at
|
||||
FROM operation_logs
|
||||
WHERE {where}
|
||||
ORDER BY log_id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
"""
|
||||
params.extend([limit, offset])
|
||||
return await execute_query(sql, tuple(params))
|
||||
|
||||
@staticmethod
|
||||
async def count_logs(
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None
|
||||
) -> int:
|
||||
"""统计操作日志数量"""
|
||||
where, params = OperationLogModel._build_filters(
|
||||
operation_type, operator, start_date, end_date
|
||||
)
|
||||
result = await execute_one(
|
||||
f"SELECT COUNT(*) AS total FROM operation_logs WHERE {where}",
|
||||
tuple(params)
|
||||
)
|
||||
return result["total"] if result else 0
|
||||
|
||||
@staticmethod
|
||||
async def get_types() -> List[str]:
|
||||
"""获取所有操作类型(用于筛选项)"""
|
||||
rows = await execute_query(
|
||||
"SELECT DISTINCT operation_type FROM operation_logs ORDER BY operation_type"
|
||||
)
|
||||
return [row["operation_type"] for row in rows]
|
||||
@@ -0,0 +1,52 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 统计报表数据模型
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, List
|
||||
from utils.database import execute_query
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ReportModel:
|
||||
"""统计报表数据模型"""
|
||||
|
||||
@staticmethod
|
||||
async def get_active_students() -> List[Dict[str, Any]]:
|
||||
"""获取所有在读学生(报表左表,保证无记录学生也展示)"""
|
||||
return await execute_query(
|
||||
"SELECT student_id, student_no, name FROM students WHERE status = 1 ORDER BY student_no"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def get_attendance_stats(start_date: str, end_date: str) -> List[Dict[str, Any]]:
|
||||
"""按学生+状态统计日期范围内的考勤次数"""
|
||||
sql = """
|
||||
SELECT ar.student_id, ar.status, COUNT(*) AS cnt
|
||||
FROM attendance_records ar
|
||||
JOIN students s ON ar.student_id = s.student_id
|
||||
WHERE ar.date BETWEEN %s AND %s AND s.status = 1
|
||||
GROUP BY ar.student_id, ar.status
|
||||
"""
|
||||
return await execute_query(sql, (start_date, end_date))
|
||||
|
||||
@staticmethod
|
||||
async def get_homework_stats(start_date: str, end_date: str) -> List[Dict[str, Any]]:
|
||||
"""按学生+状态统计日期范围内(按作业截止日期)的作业提交情况"""
|
||||
sql = """
|
||||
SELECT hs.student_id, hs.status, COUNT(*) AS cnt
|
||||
FROM homework_submissions hs
|
||||
JOIN students s ON hs.student_id = s.student_id
|
||||
JOIN assignments a ON hs.assignment_id = a.assignment_id
|
||||
WHERE a.deadline BETWEEN %s AND %s AND s.status = 1
|
||||
GROUP BY hs.student_id, hs.status
|
||||
"""
|
||||
return await execute_query(sql, (start_date, end_date))
|
||||
@@ -115,6 +115,23 @@ class SemesterModel:
|
||||
result = await execute_one(sql, (record_id,))
|
||||
return result['semester_id'] if result else None
|
||||
|
||||
@staticmethod
|
||||
async def get_previous_archived_semester(semester_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""获取上一个已归档学期(按开始日期/创建日期比较,用于归档对比)"""
|
||||
sql = """
|
||||
SELECT semester_id, semester_name, start_date, end_date, archived_at
|
||||
FROM semesters
|
||||
WHERE is_archived = 1
|
||||
AND semester_id <> %s
|
||||
AND COALESCE(start_date, DATE(created_at)) < COALESCE(
|
||||
(SELECT start_date FROM semesters x WHERE x.semester_id = %s),
|
||||
(SELECT DATE(x.created_at) FROM semesters x WHERE x.semester_id = %s)
|
||||
)
|
||||
ORDER BY COALESCE(start_date, DATE(created_at)) DESC, semester_id DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
return await execute_one(sql, (semester_id, semester_id, semester_id))
|
||||
|
||||
@staticmethod
|
||||
async def get_attendance_stats_by_semester(semester_id: int, start_date: str, end_date: str) -> List[Dict]:
|
||||
"""批量查询学期内所有学生的考勤统计"""
|
||||
|
||||
@@ -169,6 +169,32 @@ class StudentModel:
|
||||
for i, row in enumerate(results):
|
||||
row['rank'] = i + 1
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_monthly_ranking(month: str, limit: int = 100) -> List[Dict[str, Any]]:
|
||||
"""获取月度操行分排行(月度分 = 当月加分 - 当月减分,与基础分无关)"""
|
||||
sql = """
|
||||
SELECT s.student_id, s.student_no, s.name,
|
||||
COALESCE(SUM(CASE WHEN cr.points_change > 0 THEN cr.points_change ELSE 0 END), 0) AS bonus,
|
||||
COALESCE(SUM(CASE WHEN cr.points_change < 0 THEN cr.points_change ELSE 0 END), 0) AS deduction,
|
||||
COALESCE(SUM(cr.points_change), 0) AS month_score
|
||||
FROM students s
|
||||
LEFT JOIN conduct_records cr
|
||||
ON cr.student_id = s.student_id
|
||||
AND cr.is_revoked = 0
|
||||
AND DATE_FORMAT(cr.created_at, '%%Y-%%m') = %s
|
||||
WHERE s.status = 1
|
||||
GROUP BY s.student_id, s.student_no, s.name
|
||||
ORDER BY month_score DESC, s.student_id ASC
|
||||
LIMIT %s
|
||||
"""
|
||||
results = await execute_query(sql, (month, limit))
|
||||
for i, row in enumerate(results):
|
||||
row['rank'] = i + 1
|
||||
row['bonus'] = int(row.get('bonus') or 0)
|
||||
row['deduction'] = int(row.get('deduction') or 0)
|
||||
row['month_score'] = int(row.get('month_score') or 0)
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_total_count() -> int:
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 系统设置数据模型
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, Dict, List
|
||||
from utils.database import execute_one, execute_query, execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class SystemSettingModel:
|
||||
"""system_settings 键值表数据模型"""
|
||||
|
||||
@staticmethod
|
||||
async def get(key: str) -> Optional[str]:
|
||||
result = await execute_one(
|
||||
"SELECT setting_value FROM system_settings WHERE setting_key = %s", (key,)
|
||||
)
|
||||
return result["setting_value"] if result else None
|
||||
|
||||
@staticmethod
|
||||
async def get_many(keys: List[str]) -> Dict[str, str]:
|
||||
if not keys:
|
||||
return {}
|
||||
placeholders = ", ".join(["%s"] * len(keys))
|
||||
rows = await execute_query(
|
||||
f"SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ({placeholders})",
|
||||
tuple(keys)
|
||||
)
|
||||
return {row["setting_key"]: row["setting_value"] for row in rows}
|
||||
|
||||
@staticmethod
|
||||
async def upsert(key: str, value: str) -> bool:
|
||||
sql = """
|
||||
INSERT INTO system_settings (setting_key, setting_value)
|
||||
VALUES (%s, %s)
|
||||
ON DUPLICATE KEY UPDATE setting_value = %s
|
||||
"""
|
||||
result = await execute_update(sql, (key, value, value))
|
||||
return result >= 0
|
||||
+86
-2
@@ -21,13 +21,15 @@ from services.admin_service import AdminService
|
||||
from services.conduct_service import ConductService
|
||||
from services.attendance_service import AttendanceService
|
||||
from services.log_service import LogService
|
||||
from services.setting_service import SettingService
|
||||
from utils.redis_client import RedisClient
|
||||
from schemas.admin import (
|
||||
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
||||
AddStudentRequest, UpdateStudentRequest,
|
||||
AddAttendanceRequest,
|
||||
UpdateAdminRequest, ResetPasswordRequest,
|
||||
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest
|
||||
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
||||
PasswordPolicyRequest
|
||||
)
|
||||
from utils.response import success_response, error_response
|
||||
from utils.validators import is_valid_email
|
||||
@@ -758,6 +760,10 @@ async def reset_admin_password(request: Request, user_id: int, req: ResetPasswor
|
||||
if target_user["user_type"] != "admin":
|
||||
return error_response(message="只能重置管理员密码", code=400)
|
||||
|
||||
policy_check = await AdminService.validate_new_password(req.new_password)
|
||||
if not policy_check["success"]:
|
||||
return error_response(message=policy_check["message"])
|
||||
|
||||
# 使用传入的新密码(UserModel.update_password 内部会进行哈希)
|
||||
updated = await UserModel.update_password(user_id, req.new_password)
|
||||
if updated:
|
||||
@@ -797,4 +803,82 @@ async def unlock_user(request: Request, req: UnlockUserRequest):
|
||||
details=f"解除用户登录锁定: {req.username}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message=f"已解除用户 {req.username} 的登录锁定")
|
||||
return success_response(message=f"已解除用户 {req.username} 的登录锁定")
|
||||
|
||||
|
||||
# ========== 系统设置 ==========
|
||||
|
||||
@router.get("/settings/password-policy")
|
||||
async def get_password_policy(request: Request):
|
||||
"""获取密码策略"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
policy = await SettingService.get_password_policy()
|
||||
return success_response(data=policy)
|
||||
|
||||
|
||||
@router.put("/settings/password-policy")
|
||||
async def update_password_policy(request: Request, req: PasswordPolicyRequest):
|
||||
"""更新密码策略"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
result = await SettingService.update_password_policy(
|
||||
min_length=req.min_length,
|
||||
max_length=req.max_length,
|
||||
min_types=req.min_types,
|
||||
operator_id=user["user_id"]
|
||||
)
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="update_password_policy",
|
||||
target_type="setting",
|
||||
details=f"密码策略: {req.min_length}-{req.max_length}位, 至少{req.min_types}种字符",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message=result["message"])
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
# ========== 操作日志查看 ==========
|
||||
|
||||
@router.get("/operation-logs")
|
||||
async def get_operation_logs(
|
||||
request: Request,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=200),
|
||||
operation_type: Optional[str] = None,
|
||||
operator: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None
|
||||
):
|
||||
"""查询操作日志(班主任)"""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
result = await LogService.get_operation_logs(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
operation_type=operation_type,
|
||||
operator=operator,
|
||||
start_date=start_date,
|
||||
end_date=end_date
|
||||
)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"查询操作日志失败: {e}", exc_info=True)
|
||||
return error_response(message=f"查询操作日志失败: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/operation-logs/types")
|
||||
async def get_operation_log_types(request: Request):
|
||||
"""获取操作日志类型列表(用于筛选项)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
result = await LogService.get_operation_log_types()
|
||||
return success_response(data=result)
|
||||
@@ -11,13 +11,21 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
from config import settings
|
||||
from services.setting_service import SettingService
|
||||
from utils.response import success_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@router.get("/deduction-rules")
|
||||
async def get_deduction_rules():
|
||||
"""获取扣分规则配置(公开接口)"""
|
||||
"""获取扣分规则与密码策略配置(公开接口)"""
|
||||
policy = {"min_length": 6, "max_length": 20, "min_types": 3}
|
||||
try:
|
||||
policy = await SettingService.get_password_policy()
|
||||
except Exception as e:
|
||||
logger.warning(f"读取密码策略失败,使用默认值: {e}")
|
||||
data = {
|
||||
"DEDUCTION_HOMEWORK_NOT_SUBMIT": settings.DEDUCTION_HOMEWORK_NOT_SUBMIT,
|
||||
"DEDUCTION_HOMEWORK_LATE": settings.DEDUCTION_HOMEWORK_LATE,
|
||||
@@ -25,5 +33,8 @@ async def get_deduction_rules():
|
||||
"DEDUCTION_ATTENDANCE_LATE": settings.DEDUCTION_ATTENDANCE_LATE,
|
||||
"DEDUCTION_ATTENDANCE_LEAVE": settings.DEDUCTION_ATTENDANCE_LEAVE,
|
||||
"STUDENT_INITIAL_POINTS": settings.STUDENT_INITIAL_POINTS,
|
||||
"PASSWORD_MIN_LENGTH": policy["min_length"],
|
||||
"PASSWORD_MAX_LENGTH": policy["max_length"],
|
||||
"PASSWORD_MIN_TYPES": policy["min_types"],
|
||||
}
|
||||
return success_response(data=data)
|
||||
@@ -0,0 +1,62 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 统计报表路由
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from middleware.permission import get_current_user, PermissionChecker
|
||||
from services.report_service import ReportService
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def _check_report_permission(request: Request):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "view_all_records"):
|
||||
return user, error_response(message="无查看报表权限", code=403)
|
||||
return user, None
|
||||
|
||||
|
||||
@router.get("/attendance")
|
||||
async def attendance_report(
|
||||
request: Request,
|
||||
start_date: str = Query(..., description="开始日期 YYYY-MM-DD"),
|
||||
end_date: str = Query(..., description="结束日期 YYYY-MM-DD")
|
||||
):
|
||||
"""考勤统计报表"""
|
||||
try:
|
||||
_, denied = await _check_report_permission(request)
|
||||
if denied:
|
||||
return denied
|
||||
result = await ReportService.attendance_report(start_date, end_date)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"考勤报表生成失败: {e}", exc_info=True)
|
||||
return error_response(message=f"考勤报表生成失败: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/homework")
|
||||
async def homework_report(
|
||||
request: Request,
|
||||
start_date: str = Query(..., description="开始日期 YYYY-MM-DD"),
|
||||
end_date: str = Query(..., description="结束日期 YYYY-MM-DD")
|
||||
):
|
||||
"""作业统计报表"""
|
||||
try:
|
||||
_, denied = await _check_report_permission(request)
|
||||
if denied:
|
||||
return denied
|
||||
result = await ReportService.homework_report(start_date, end_date)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"作业报表生成失败: {e}", exc_info=True)
|
||||
return error_response(message=f"作业报表生成失败: {str(e)}")
|
||||
@@ -92,16 +92,18 @@ async def get_attendance_records(
|
||||
@router.get("/ranking")
|
||||
async def get_ranking(
|
||||
request: Request,
|
||||
limit: int = Query(50, ge=1, le=100)
|
||||
limit: int = Query(50, ge=1, le=1000),
|
||||
month: Optional[str] = Query(None, pattern=r'^\d{4}-\d{2}$')
|
||||
):
|
||||
"""
|
||||
获取操行分排行榜
|
||||
获取操行分排行榜(传 month=YYYY-MM 时为月度分排行)
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
|
||||
result = await StudentService.get_ranking(
|
||||
user_id=user["user_id"],
|
||||
limit=limit
|
||||
limit=limit,
|
||||
month=month
|
||||
)
|
||||
|
||||
return success_response(data=result)
|
||||
|
||||
@@ -46,6 +46,8 @@ ALL_VERSIONS = {
|
||||
'4.0': 'v4.0.sql',
|
||||
'4.1': 'v4.1.sql',
|
||||
'4.2': 'v4.2.sql',
|
||||
'4.3': 'v4.3.sql',
|
||||
'4.4': 'v4.4.sql',
|
||||
}
|
||||
# 版本特征标记(按优先级从高到低)
|
||||
VERSION_MARKERS = [
|
||||
|
||||
@@ -76,7 +76,7 @@ class AddAttendanceRequest(BaseModel):
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
"""重置密码请求"""
|
||||
new_password: str = Field(..., min_length=6, max_length=50, description="新密码")
|
||||
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
|
||||
|
||||
class UpdateStudentRequest(BaseModel):
|
||||
@@ -93,4 +93,11 @@ class UnlockUserRequest(BaseModel):
|
||||
|
||||
class EmailTestRequest(BaseModel):
|
||||
"""邮件测试请求"""
|
||||
email: str = Field(..., min_length=3, max_length=100, description="接收测试邮件的邮箱")
|
||||
email: str = Field(..., min_length=3, max_length=100, description="接收测试邮件的邮箱")
|
||||
|
||||
|
||||
class PasswordPolicyRequest(BaseModel):
|
||||
"""密码策略请求"""
|
||||
min_length: int = Field(..., ge=4, le=64, description="密码最小长度")
|
||||
max_length: int = Field(..., ge=8, le=100, description="密码最大长度")
|
||||
min_types: int = Field(..., ge=1, le=4, description="最少字符种类数")
|
||||
@@ -21,7 +21,7 @@ class LoginRequest(BaseModel):
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
"""修改密码请求"""
|
||||
old_password: str = Field(default="", max_length=50, description="原密码")
|
||||
new_password: str = Field(..., min_length=6, max_length=20, description="新密码")
|
||||
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
force: bool = Field(default=False, description="是否强制修改(首次登录)")
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ class ForgotPasswordRequest(BaseModel):
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
"""通过邮件令牌重置密码请求"""
|
||||
token: str = Field(..., min_length=10, max_length=200, description="重置令牌")
|
||||
new_password: str = Field(..., min_length=6, max_length=20, description="新密码")
|
||||
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
|
||||
|
||||
class SendEmailCodeRequest(BaseModel):
|
||||
|
||||
@@ -15,6 +15,7 @@ from models.user import UserModel
|
||||
from models.student import StudentModel
|
||||
from models.admin_role import AdminRoleModel
|
||||
from models.permission_group import PermissionGroupModel, PERMISSION_KEYS
|
||||
from services.setting_service import SettingService
|
||||
from utils.security import security
|
||||
from utils.validators import is_valid_email
|
||||
from utils.logger import get_logger
|
||||
@@ -616,9 +617,23 @@ class AdminService:
|
||||
logger.error(f"删除学生失败: {e}")
|
||||
return {"success": False, "message": f"删除失败: {str(e)}"}
|
||||
|
||||
@staticmethod
|
||||
async def validate_new_password(new_password: str) -> Dict[str, Any]:
|
||||
"""按系统密码策略校验新密码"""
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, msg = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": msg}
|
||||
return {"success": True}
|
||||
|
||||
@staticmethod
|
||||
async def reset_student_password(student_id: int, new_password: str) -> Dict[str, Any]:
|
||||
"""重置学生密码"""
|
||||
policy_check = await AdminService.validate_new_password(new_password)
|
||||
if not policy_check["success"]:
|
||||
return policy_check
|
||||
try:
|
||||
user = await execute_one(
|
||||
"SELECT user_id FROM users WHERE student_id = %s AND user_type = 'student'",
|
||||
|
||||
@@ -18,6 +18,7 @@ from models.user import UserModel
|
||||
from models.student import StudentModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from services.log_service import LogService
|
||||
from services.setting_service import SettingService
|
||||
from utils.security import security
|
||||
from utils.validators import is_valid_email
|
||||
from utils.email_sender import EmailSender
|
||||
@@ -160,8 +161,11 @@ class AuthService:
|
||||
if not is_valid:
|
||||
return {"success": False, "message": "原密码错误"}
|
||||
|
||||
# 验证新密码强度
|
||||
is_valid, msg = security.validate_password_strength(new_password)
|
||||
# 验证新密码强度(策略可配置)
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, msg = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": msg}
|
||||
|
||||
@@ -315,7 +319,10 @@ class AuthService:
|
||||
if not user or user.get("user_type") != "admin" or user.get("status") != 1:
|
||||
return {"success": False, "message": "账号不存在或不可重置密码"}
|
||||
|
||||
is_valid, message = security.validate_password_strength(new_password)
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, message = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": message}
|
||||
|
||||
|
||||
@@ -54,3 +54,41 @@ class LogService:
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"写入操作日志失败: {e}")
|
||||
|
||||
@staticmethod
|
||||
async def get_operation_logs(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None
|
||||
) -> dict:
|
||||
"""查询操作日志(分页 + 筛选)"""
|
||||
if operation_type == "":
|
||||
operation_type = None
|
||||
if operator == "":
|
||||
operator = None
|
||||
if start_date == "":
|
||||
start_date = None
|
||||
if end_date == "":
|
||||
end_date = None
|
||||
offset = (page - 1) * page_size
|
||||
total = await OperationLogModel.count_logs(
|
||||
operation_type, operator, start_date, end_date
|
||||
)
|
||||
logs = await OperationLogModel.get_logs(
|
||||
operation_type, operator, start_date, end_date, page_size, offset
|
||||
)
|
||||
return {
|
||||
"logs": logs,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def get_operation_log_types() -> dict:
|
||||
"""获取操作日志类型列表(用于筛选下拉)"""
|
||||
return {"types": await OperationLogModel.get_types()}
|
||||
@@ -0,0 +1,115 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 统计报表服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any
|
||||
from models.report import ReportModel
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
ATTENDANCE_STATUSES = ["present", "absent", "late", "leave"]
|
||||
HOMEWORK_STATUSES = ["submitted", "not_submitted", "late"]
|
||||
|
||||
|
||||
class ReportService:
|
||||
"""统计报表服务"""
|
||||
|
||||
@staticmethod
|
||||
async def attendance_report(start_date: str, end_date: str) -> Dict[str, Any]:
|
||||
"""考勤统计报表:出勤/缺勤/迟到/请假与出勤率"""
|
||||
students = await ReportModel.get_active_students()
|
||||
stats = await ReportModel.get_attendance_stats(start_date, end_date)
|
||||
|
||||
counts_map: Dict[int, Dict[str, int]] = {}
|
||||
for stat in stats:
|
||||
sid = stat["student_id"]
|
||||
entry = counts_map.setdefault(sid, {key: 0 for key in ATTENDANCE_STATUSES})
|
||||
if stat["status"] in entry:
|
||||
entry[stat["status"]] = int(stat["cnt"] or 0)
|
||||
|
||||
rows = []
|
||||
summary = {key: 0 for key in ATTENDANCE_STATUSES}
|
||||
for student in students:
|
||||
counts = counts_map.get(student["student_id"], {key: 0 for key in ATTENDANCE_STATUSES})
|
||||
total = sum(counts.values())
|
||||
present = counts["present"]
|
||||
rate = round(present / total * 100, 1) if total else None
|
||||
rows.append({
|
||||
"student_id": student["student_id"],
|
||||
"student_no": student["student_no"],
|
||||
"name": student["name"],
|
||||
"present": present,
|
||||
"absent": counts["absent"],
|
||||
"late": counts["late"],
|
||||
"leave": counts["leave"],
|
||||
"total": total,
|
||||
"rate": rate
|
||||
})
|
||||
for key in ATTENDANCE_STATUSES:
|
||||
summary[key] += counts[key]
|
||||
|
||||
rows.sort(key=lambda r: (-r["absent"], -r["late"], r["student_no"]))
|
||||
summary["total"] = sum(summary.values())
|
||||
summary["rate"] = (
|
||||
round(summary["present"] / summary["total"] * 100, 1)
|
||||
if summary["total"] else None
|
||||
)
|
||||
return {
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"rows": rows,
|
||||
"summary": summary
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def homework_report(start_date: str, end_date: str) -> Dict[str, Any]:
|
||||
"""作业统计报表:已交/未交/迟交与未交率"""
|
||||
students = await ReportModel.get_active_students()
|
||||
stats = await ReportModel.get_homework_stats(start_date, end_date)
|
||||
|
||||
counts_map: Dict[int, Dict[str, int]] = {}
|
||||
for stat in stats:
|
||||
sid = stat["student_id"]
|
||||
entry = counts_map.setdefault(sid, {key: 0 for key in HOMEWORK_STATUSES})
|
||||
if stat["status"] in entry:
|
||||
entry[stat["status"]] = int(stat["cnt"] or 0)
|
||||
|
||||
rows = []
|
||||
summary = {key: 0 for key in HOMEWORK_STATUSES}
|
||||
for student in students:
|
||||
counts = counts_map.get(student["student_id"], {key: 0 for key in HOMEWORK_STATUSES})
|
||||
total = sum(counts.values())
|
||||
miss_rate = round(counts["not_submitted"] / total * 100, 1) if total else None
|
||||
rows.append({
|
||||
"student_id": student["student_id"],
|
||||
"student_no": student["student_no"],
|
||||
"name": student["name"],
|
||||
"submitted": counts["submitted"],
|
||||
"not_submitted": counts["not_submitted"],
|
||||
"late": counts["late"],
|
||||
"total": total,
|
||||
"miss_rate": miss_rate
|
||||
})
|
||||
for key in HOMEWORK_STATUSES:
|
||||
summary[key] += counts[key]
|
||||
|
||||
rows.sort(key=lambda r: (-r["not_submitted"], -r["late"], r["student_no"]))
|
||||
summary["total"] = sum(summary.values())
|
||||
summary["miss_rate"] = (
|
||||
round(summary["not_submitted"] / summary["total"] * 100, 1)
|
||||
if summary["total"] else None
|
||||
)
|
||||
return {
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"rows": rows,
|
||||
"summary": summary
|
||||
}
|
||||
@@ -387,6 +387,25 @@ class SemesterService:
|
||||
|
||||
archives = await SemesterArchiveModel.get_by_semester(semester_id)
|
||||
|
||||
# 归档对比:与上一个已归档学期比较分数与名次
|
||||
previous_semester = await SemesterModel.get_previous_archived_semester(semester_id)
|
||||
if previous_semester:
|
||||
prev_archives = await SemesterArchiveModel.get_by_semester(previous_semester["semester_id"])
|
||||
prev_map = {a["student_id"]: a for a in prev_archives}
|
||||
for archive in archives:
|
||||
prev = prev_map.get(archive["student_id"])
|
||||
if prev:
|
||||
archive["prev_final_points"] = prev["final_points"]
|
||||
archive["points_change"] = (archive["final_points"] or 0) - (prev["final_points"] or 0)
|
||||
archive["prev_rank_position"] = prev["rank_position"]
|
||||
# 正数表示名次进步
|
||||
archive["rank_change"] = (prev["rank_position"] or 0) - (archive["rank_position"] or 0)
|
||||
else:
|
||||
archive["prev_final_points"] = None
|
||||
archive["points_change"] = None
|
||||
archive["prev_rank_position"] = None
|
||||
archive["rank_change"] = None
|
||||
|
||||
total = len(archives)
|
||||
offset = (page - 1) * page_size
|
||||
paged_archives = archives[offset:offset + page_size]
|
||||
@@ -401,6 +420,10 @@ class SemesterService:
|
||||
"end_date": semester.get('end_date'),
|
||||
"is_archived": bool(semester['is_archived'])
|
||||
},
|
||||
"previous_semester": {
|
||||
"semester_id": previous_semester["semester_id"],
|
||||
"semester_name": previous_semester["semester_name"]
|
||||
} if previous_semester else None,
|
||||
"archives": paged_archives,
|
||||
"total": total,
|
||||
"page": page,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 系统设置服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any
|
||||
from models.system_setting import SystemSettingModel
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 密码策略默认值(未配置时使用)
|
||||
DEFAULT_PASSWORD_POLICY = {
|
||||
"min_length": 6,
|
||||
"max_length": 20,
|
||||
"min_types": 3
|
||||
}
|
||||
|
||||
|
||||
class SettingService:
|
||||
"""系统设置服务"""
|
||||
|
||||
@staticmethod
|
||||
async def get_password_policy() -> Dict[str, int]:
|
||||
"""获取密码策略(长度范围与最少字符种类数)"""
|
||||
values = await SystemSettingModel.get_many([
|
||||
"password_min_length", "password_max_length", "password_min_types"
|
||||
])
|
||||
policy = dict(DEFAULT_PASSWORD_POLICY)
|
||||
|
||||
def parse_int(key: str, default: int, low: int, high: int) -> int:
|
||||
try:
|
||||
value = int(values.get(key, ""))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(low, min(high, value))
|
||||
|
||||
policy["min_length"] = parse_int("password_min_length", policy["min_length"], 4, 64)
|
||||
policy["max_length"] = parse_int("password_max_length", policy["max_length"], 8, 100)
|
||||
policy["min_types"] = parse_int("password_min_types", policy["min_types"], 1, 4)
|
||||
if policy["min_length"] > policy["max_length"]:
|
||||
policy["min_length"] = policy["max_length"]
|
||||
return policy
|
||||
|
||||
@staticmethod
|
||||
async def update_password_policy(
|
||||
min_length: int,
|
||||
max_length: int,
|
||||
min_types: int,
|
||||
operator_id: int = None
|
||||
) -> Dict[str, Any]:
|
||||
"""更新密码策略"""
|
||||
if not (4 <= min_length <= 64):
|
||||
return {"success": False, "message": "最小长度需在4-64之间"}
|
||||
if not (8 <= max_length <= 100):
|
||||
return {"success": False, "message": "最大长度需在8-100之间"}
|
||||
if min_length > max_length:
|
||||
return {"success": False, "message": "最小长度不能大于最大长度"}
|
||||
if not (1 <= min_types <= 4):
|
||||
return {"success": False, "message": "字符种类数需在1-4之间"}
|
||||
|
||||
await SystemSettingModel.upsert("password_min_length", str(min_length))
|
||||
await SystemSettingModel.upsert("password_max_length", str(max_length))
|
||||
await SystemSettingModel.upsert("password_min_types", str(min_types))
|
||||
logger.info(
|
||||
f"用户[{operator_id}] 更新密码策略: {min_length}-{max_length}位, 至少{min_types}种字符"
|
||||
)
|
||||
return {"success": True, "message": "密码策略已保存"}
|
||||
@@ -121,15 +121,20 @@ class StudentService:
|
||||
@staticmethod
|
||||
async def get_ranking(
|
||||
user_id: int,
|
||||
limit: int = 50
|
||||
limit: int = 50,
|
||||
month: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""获取排行榜(单班级系统)"""
|
||||
ranking = await StudentModel.get_ranking(limit=limit)
|
||||
"""获取排行榜(单班级系统);传 month 时返回月度分排行"""
|
||||
if month:
|
||||
ranking = await StudentModel.get_monthly_ranking(month=month, limit=limit)
|
||||
else:
|
||||
ranking = await StudentModel.get_ranking(limit=limit)
|
||||
total_students = await StudentModel.get_total_count()
|
||||
|
||||
return {
|
||||
"ranking": ranking,
|
||||
"total_students": total_students
|
||||
"total_students": total_students,
|
||||
"month": month
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -86,16 +86,21 @@ class SecurityUtils:
|
||||
return ''.join(secrets.choice(alphabet) for _ in range(length))
|
||||
|
||||
@staticmethod
|
||||
def validate_password_strength(password: str) -> tuple:
|
||||
def validate_password_strength(
|
||||
password: str,
|
||||
min_length: int = 6,
|
||||
max_length: int = 20,
|
||||
min_types: int = 3
|
||||
) -> tuple:
|
||||
"""
|
||||
验证密码强度
|
||||
要求:大小写字母、数字、特殊符号 至少包含其中3种
|
||||
验证密码强度(策略可配置)
|
||||
要求:由 大写字母/小写字母/数字/特殊符号 中至少 min_types 种组成
|
||||
返回: (是否有效, 错误信息)
|
||||
"""
|
||||
if len(password) < 6:
|
||||
return False, "密码长度至少6位"
|
||||
if len(password) > 20:
|
||||
return False, "密码长度不能超过20位"
|
||||
if len(password) < min_length:
|
||||
return False, f"密码长度至少{min_length}位"
|
||||
if len(password) > max_length:
|
||||
return False, f"密码长度不能超过{max_length}位"
|
||||
|
||||
# 检查四种字符类型
|
||||
has_upper = any(c.isupper() for c in password) # 大写字母
|
||||
@@ -106,8 +111,8 @@ class SecurityUtils:
|
||||
# 统计满足的字符类型数量
|
||||
char_types = sum([has_upper, has_lower, has_digit, has_special])
|
||||
|
||||
if char_types < 3:
|
||||
return False, "密码必须包含大写字母、小写字母、数字、特殊符号中的至少3种"
|
||||
if char_types < min_types:
|
||||
return False, f"密码必须包含大写字母、小写字母、数字、特殊符号中的至少{min_types}种"
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
Reference in new issue
Block a user