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
+1779
-87
No files matched your search
@@ -30,7 +30,11 @@
|
||||
- 密码找回:管理员绑定邮箱(自助绑定需 SMTP 邮箱验证码,无需密码),忘记密码时可在登录页通过邮箱获取一次性重置链接(限时、仅可使用一次)
|
||||
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
||||
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
||||
- 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法)
|
||||
- 排行榜:支持总分排行与月度分排行(可选月份查看当月加分/减分/月度分),支持百分比筛选显示前N%的学生(抹零法)与一键导出CSV
|
||||
- 数据报表:考勤统计与作业统计(按日期范围),含汇总与每人明细,可导出CSV
|
||||
- 操作日志:管理端可查询操作日志(操作类型/操作人/日期筛选,分页展示)
|
||||
- 系统设置:密码策略可配置(长度范围与最少字符种类数),全站即时生效
|
||||
- 学期归档对比:查看归档数据时展示与上一归档学期的分数变化与名次升降
|
||||
- 数据导出:按学期导出历史记录、导出德育分记录(默认当前学期,可选历史学期/全部学期)
|
||||
|
||||
**管理员/班干部权限(v4.0 起由权限组动态控制):**
|
||||
@@ -91,9 +95,11 @@ classmanager/
|
||||
│ │ ├── homework.py # 作业模型
|
||||
│ │ ├── log.py # 日志模型
|
||||
│ │ ├── permission_group.py # 权限组模型(功能权限+加减分上限)
|
||||
│ │ ├── report.py # 统计报表模型
|
||||
│ │ ├── semester.py # 学期模型
|
||||
│ │ ├── student.py # 学生模型
|
||||
│ │ ├── subject.py # 科目模型
|
||||
│ │ ├── system_setting.py # 系统设置模型(密码策略等)
|
||||
│ │ └── user.py # 用户模型
|
||||
│ │
|
||||
│ ├── routes/ # API 路由
|
||||
@@ -102,6 +108,7 @@ classmanager/
|
||||
│ │ ├── auth.py # 认证接口
|
||||
│ │ ├── debug.py # 调试入口
|
||||
│ │ ├── parent.py # 家长端接口
|
||||
│ │ ├── report.py # 统计报表接口
|
||||
│ │ ├── semester.py # 学期管理接口
|
||||
│ │ ├── student.py # 学生端接口
|
||||
│ │ └── subject.py # 科目管理接口
|
||||
@@ -126,7 +133,9 @@ classmanager/
|
||||
│ │ ├── homework_service.py
|
||||
│ │ ├── log_service.py
|
||||
│ │ ├── parent_service.py
|
||||
│ │ ├── semester_service.py # 学期服务
|
||||
│ │ ├── report_service.py # 统计报表服务
|
||||
│ │ ├── semester_service.py # 学期服务
|
||||
│ │ ├── setting_service.py # 系统设置服务
|
||||
│ │ ├── student_service.py
|
||||
│ │ └── subject_service.py
|
||||
│ │
|
||||
@@ -156,9 +165,12 @@ classmanager/
|
||||
│ │ ├── dashboard.php # 管理端首页
|
||||
│ │ ├── history.php # 历史记录
|
||||
│ │ ├── homework.php # 作业管理
|
||||
│ │ ├── logs.php # 操作日志
|
||||
│ │ ├── password.php # 修改密码
|
||||
│ │ ├── record_query.php # 个人记录查询(基础分/月度分/理由汇总)
|
||||
│ │ ├── reports.php # 数据报表(考勤/作业)
|
||||
│ │ ├── semesters.php # 学期管理
|
||||
│ │ ├── settings.php # 系统设置(密码策略)
|
||||
│ │ ├── students.php # 学生管理
|
||||
│ │ └── subjects.php # 科目管理
|
||||
│ │
|
||||
@@ -171,8 +183,11 @@ classmanager/
|
||||
│ │ │ └── style.css # 全局样式
|
||||
│ │ ├── js/
|
||||
│ │ │ ├── common.js # 公共 JS
|
||||
│ │ │ ├── logs.js # 操作日志 JS
|
||||
│ │ │ ├── parent.js # 家长端 JS
|
||||
│ │ │ ├── record-query.js # 个人记录查询 JS
|
||||
│ │ │ ├── reports.js # 数据报表 JS
|
||||
│ │ │ ├── settings.js # 系统设置 JS
|
||||
│ │ │ └── student.js # 学生端 JS
|
||||
│ │ └── uploads/
|
||||
│ │ └── sample_import.json # 学生导入示例
|
||||
@@ -291,6 +306,8 @@ classmanager/
|
||||
| v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 |
|
||||
| v4.1 | 2026.9.18 | 管理员可绑定邮箱;自助绑定采用 SMTP 验证码(10分钟有效、限流+尝试次数限制,无需密码),忘记密码使用一次性重置链接(30分钟有效);权限组全部可自定义(可编辑/删除/分配,无锁定预置);个人查询月度分独立计算(与基础分无关,总分=基础分+加减分);登录链路不依赖新表新列,旧库可登录后弹窗升级 |
|
||||
| v4.2 | 2026.9.18 | 科目管理优化:科目代码长度放宽至50(数据库+校验)、编辑可清空代码、重命名查重、支持 ↑↓ 快捷排序(批量重排接口);新增邮件测试入口;密码加密改用 bcrypt 库直连(修复 passlib 兼容问题);前端统一展示422校验错误 |
|
||||
| v4.3 | 2026.9.20 | 新增月度分排行:管理端首页可在"总分排行/月度分排行"间切换,月度排行可按月份查看加分、减分、月度分并支持百分比筛选;SMTP 配置读取加固(显式 backend/.env、兼容 BOM 与布尔拼写)、邮件日志降噪、/api/config 公开路径修复 |
|
||||
| v4.4 | 2026.9.20 | 新增数据报表(考勤/作业统计,可按日期范围查询与导出)、操作日志查看页、系统设置(密码策略可配置并全站生效);排行榜支持导出CSV;学期归档展示与上一学期的分数/名次环比;历史记录导出支持"按学生分表";移动端适配优化(导航横向滚动、表格触控滚动、弹窗与字号调整) |
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
+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]:
|
||||
"""批量查询学期内所有学生的考勤统计"""
|
||||
|
||||
@@ -170,6 +170,32 @@ class StudentModel:
|
||||
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
|
||||
+85
-1
@@ -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:
|
||||
@@ -798,3 +804,81 @@ async def unlock_user(request: Request, req: UnlockUserRequest):
|
||||
ip=request.client.host
|
||||
)
|
||||
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):
|
||||
@@ -94,3 +94,10 @@ class UnlockUserRequest(BaseModel):
|
||||
class EmailTestRequest(BaseModel):
|
||||
"""邮件测试请求"""
|
||||
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, ""
|
||||
|
||||
|
||||
@@ -27,7 +27,10 @@
|
||||
| 学生管理 | 新增/编辑/删除/批量导入学生 |
|
||||
| 科目管理 | 增删改科目信息 |
|
||||
| 管理员管理 | 添加/编辑姓名和权限组/禁用启用/重置密码/管理自定义权限组与加减分上限 |
|
||||
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数 |
|
||||
| 操作日志 | 查询关键操作记录(类型/操作人/日期筛选) |
|
||||
| 数据报表 | 考勤/作业统计(按日期范围,支持导出) |
|
||||
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数、归档环比 |
|
||||
| 系统设置 | 配置密码策略(长度与字符种类) |
|
||||
| 修改密码 | 修改登录密码 |
|
||||
|
||||
## 常用操作
|
||||
@@ -44,7 +47,11 @@
|
||||
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
||||
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
||||
- **学期管理**:学期管理页 → 创建学期(可快捷填充日期)→ 关联历史数据 → 归档(可选重置分数)
|
||||
- **排行榜筛选**:首页 → 输入百分比 → 点击筛选(抹零法,如15%显示前15%的学生)
|
||||
- **排行榜筛选/导出**:首页 → 选择"总分排行/月度分排行"(月度可选月份)→ 输入百分比筛选,或点「导出」下载CSV
|
||||
- **数据报表**:数据报表页 → 选择日期范围 → 查询考勤/作业统计 → 各表右上角导出CSV
|
||||
- **操作日志**:操作日志页 → 选择类型/操作人/日期 → 查询
|
||||
- **密码策略**:系统设置页 → 修改长度与字符种类 → 保存(全站即时生效)
|
||||
- **归档对比**:学期管理 → 已归档学期「查看归档」→ 查看与上一学期的分数/名次环比
|
||||
|
||||
## 常见问题
|
||||
|
||||
|
||||
+39
-4
@@ -26,7 +26,10 @@
|
||||
- 操行分管理
|
||||
- 导入学生
|
||||
- 导出德育分记录
|
||||
- **操行分排行榜**:展示前100名学生的排名、学号、姓名和操行分。排行榜上方提供百分比筛选框,可输入1-100的数字筛选显示前N%的学生(抹零法:如49人×15%=7.35,显示前7人)。
|
||||
- **操行分排行榜**:支持两种排行方式:
|
||||
- **总分排行**:按当前操行分排名(展示前100名)
|
||||
- **月度分排行**:选择月份后按当月净得分排名(月度分 = 当月加分 - 当月减分,与基础分无关),同时展示当月加分/减分
|
||||
- 排行榜上方提供百分比筛选框(抹零法),并支持「导出」按钮将当前排行导出为CSV
|
||||
|
||||
---
|
||||
|
||||
@@ -71,9 +74,11 @@
|
||||
|
||||
#### 导出历史记录
|
||||
1. 设置筛选条件(可选)
|
||||
2. 点击"导出历史记录"按钮
|
||||
2. 点击"导出"按钮,在弹窗中选择导出方式:
|
||||
- **明细记录**:每行一条记录(默认)
|
||||
- **按学生分表**:每个学生一段,包含加分/减分合计与明细,便于发给家长
|
||||
3. 系统自动生成CSV文件并下载(导出全部匹配记录,不受分页限制)
|
||||
4. 文件格式:`时间,学号,姓名,学期,类型,分数变动,原因,操作人`
|
||||
4. 明细导出格式:`时间,学号,姓名,学期,类型,分数变动,原因,操作人`
|
||||
|
||||
#### 撤销记录
|
||||
1. 在历史记录列表中找到目标记录
|
||||
@@ -293,6 +298,7 @@
|
||||
#### 查看归档数据
|
||||
- 已归档学期显示"查看归档"按钮
|
||||
- 展示归档时的学生排名、操行分、考勤统计、作业统计
|
||||
- **环比上次**:同时展示与上一个已归档学期的「分数变化」(+/-)与「排名变化」(↑进步 / ↓退步)
|
||||
|
||||
---
|
||||
|
||||
@@ -323,7 +329,7 @@
|
||||
### 11. 修改密码 (password.php)
|
||||
|
||||
- 输入原密码和新密码
|
||||
- 新密码需符合密码强度要求
|
||||
- 新密码需符合密码强度要求(密码策略可在「系统设置」中调整)
|
||||
- 修改成功后需重新登录
|
||||
- 页面下方可**绑定邮箱**(找回密码用):
|
||||
1. 输入新邮箱,点击"发送验证码"(无需密码)
|
||||
@@ -334,6 +340,35 @@
|
||||
|
||||
---
|
||||
|
||||
### 12. 数据报表 (reports.php)
|
||||
|
||||
用于按日期范围统计全班考勤与作业情况。
|
||||
|
||||
- 选择**开始日期 / 结束日期**(默认当前学期至今),点击"查询"
|
||||
- **考勤统计**:每人出勤/缺勤/迟到/请假次数、记录数、出勤率,按缺勤与迟到降序排列
|
||||
- **作业统计**:每人已交/未交/迟交次数、记录数、未交率,按未交与迟交降序排列
|
||||
- 各表右上角「导出」按钮可导出对应CSV
|
||||
|
||||
> 作业统计按作业截止日期归属;考勤按考勤记录日期归属。
|
||||
|
||||
---
|
||||
|
||||
### 13. 操作日志 (logs.php)
|
||||
|
||||
用于审计管理端所有关键操作。
|
||||
|
||||
- 支持按**操作类型**、**操作人/角色关键词**、**日期范围**筛选
|
||||
- 分页展示:时间、操作人、角色、操作类型、对象、详情、IP
|
||||
|
||||
---
|
||||
|
||||
### 14. 系统设置 (settings.php)
|
||||
|
||||
- **密码策略**:配置密码最小长度、最大长度、最少字符种类数(大写/小写/数字/特殊符号)
|
||||
- 保存后立即生效:修改密码、重置密码、邮箱重置等所有入口统一按该策略校验,前端提示同步更新
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 忘记密码怎么办?
|
||||
|
||||
@@ -211,8 +211,8 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="text" id="newPassword" required minlength="6" placeholder="请输入新密码(至少6位)">
|
||||
<small>密码长度至少6位</small>
|
||||
<input type="text" id="newPassword" required placeholder="请输入新密码">
|
||||
<small class="pwd-policy">密码长度至少6位</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">确认重置</button>
|
||||
|
||||
@@ -35,16 +35,22 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="card">
|
||||
<div class="card-title">操行分排行榜</div>
|
||||
<div class="table-wrapper">
|
||||
<div style="display: flex; align-items: center; margin-bottom: 12px; gap: 8px;">
|
||||
<span style="font-size: 14px; color: #666;">显示前</span>
|
||||
<input type="number" id="percentileFilter" style="width: 70px; padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px;" min="1" max="100" value="100" placeholder="1-100">
|
||||
<span style="font-size: 14px; color: #666;">% 的学生</span>
|
||||
<div class="ranking-toolbar">
|
||||
<select id="rankingType" onchange="onRankingTypeChange()">
|
||||
<option value="total">总分排行</option>
|
||||
<option value="monthly">月度分排行</option>
|
||||
</select>
|
||||
<input type="month" id="rankingMonth" style="display:none;" onchange="loadRanking()">
|
||||
<span class="ranking-tip">显示前</span>
|
||||
<input type="number" id="percentileFilter" style="width: 70px;" min="1" max="100" value="100" placeholder="1-100">
|
||||
<span class="ranking-tip">% 的学生</span>
|
||||
<button class="btn btn-sm btn-primary" onclick="applyPercentileFilter()">筛选</button>
|
||||
<button class="btn btn-sm btn-ghost" onclick="resetPercentileFilter()">显示全部</button>
|
||||
<button class="btn btn-sm btn-secondary" onclick="exportRanking()">导出</button>
|
||||
</div>
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>排名</th><th>学号</th><th>姓名</th><th>操行分</th></tr>
|
||||
<tr id="rankingHead"><th>排名</th><th>学号</th><th>姓名</th><th>操行分</th></tr>
|
||||
</thead>
|
||||
<tbody id="rankingList"></tbody>
|
||||
</table>
|
||||
|
||||
@@ -39,7 +39,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
</select>
|
||||
</label>
|
||||
<?php if (has_perm('export_data')): ?>
|
||||
<button class="btn btn-secondary" onclick="exportHistoryRecords()">导出</button>
|
||||
<button class="btn btn-secondary" onclick="showExportHistoryModal()">导出</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<!-- 高级筛选面板(默认折叠) -->
|
||||
@@ -122,4 +122,30 @@ include __DIR__ . '/../includes/header.php';
|
||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
||||
<script src="/assets/js/history.js"></script>
|
||||
|
||||
<!-- 导出历史记录模态框 -->
|
||||
<div id="exportHistoryModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3>导出历史记录</h3>
|
||||
<button class="modal-close" onclick="closeModal('exportHistoryModal')">×</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>导出方式</label>
|
||||
<div class="check-grid" style="grid-template-columns: 1fr;">
|
||||
<label class="check-item">
|
||||
<input type="radio" name="historyExportMode" value="detail" checked> 明细记录(每行一条记录)
|
||||
</label>
|
||||
<label class="check-item">
|
||||
<input type="radio" name="historyExportMode" value="per_student"> 按学生分表(每人一段,便于发给家长)
|
||||
</label>
|
||||
</div>
|
||||
<small>导出内容跟随当前筛选条件;已撤销记录不导出</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" onclick="exportHistoryRecords()">开始导出</button>
|
||||
<button type="button" class="btn" onclick="closeModal('exportHistoryModal')">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 管理端操作日志
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
|
||||
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
header('Location: /index.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$page_title = '操作日志';
|
||||
$role = current_group_name();
|
||||
require_perm('manage_admins');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<div class="filter-group">
|
||||
<label>操作类型</label>
|
||||
<select id="logTypeFilter">
|
||||
<option value="">全部</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>操作人 / 角色</label>
|
||||
<input type="text" id="logOperatorFilter" placeholder="关键词">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>开始日期</label>
|
||||
<input type="date" id="logStartDate">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>结束日期</label>
|
||||
<input type="date" id="logEndDate">
|
||||
</div>
|
||||
<div class="filter-group" style="flex: 0 0 auto;">
|
||||
<button class="btn btn-primary" onclick="loadLogs(1)">查询</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="white-space: nowrap;">时间</th>
|
||||
<th>操作人</th>
|
||||
<th>角色</th>
|
||||
<th>操作</th>
|
||||
<th>对象</th>
|
||||
<th>详情</th>
|
||||
<th>IP</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="logList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pagination" id="logPagination"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/js/logs.js"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -36,7 +36,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>新密码 <span style="color:red;">*</span></label>
|
||||
<input type="password" id="newPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码 <span style="color:red;">*</span></label>
|
||||
@@ -94,8 +94,9 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword.length < 6 || newPassword.length > 20) {
|
||||
showToast('密码长度需为6-20位', 'error');
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 管理端数据报表
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
|
||||
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
header('Location: /index.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$page_title = '数据报表';
|
||||
$role = current_group_name();
|
||||
require_perm('view_all_records');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<div class="filter-group">
|
||||
<label>开始日期</label>
|
||||
<input type="date" id="reportStartDate">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>结束日期</label>
|
||||
<input type="date" id="reportEndDate">
|
||||
</div>
|
||||
<div class="filter-group" style="flex: 0 0 auto;">
|
||||
<button class="btn btn-primary" onclick="loadReports()">查询</button>
|
||||
</div>
|
||||
</div>
|
||||
<p style="font-size: 12px; color: var(--color-text-secondary);" id="reportRangeHint">
|
||||
默认统计当前学期范围;考勤按记录日期统计,作业按作业截止日期统计
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title" style="display:flex; justify-content:space-between; align-items:center;">
|
||||
<span>考勤统计</span>
|
||||
<button class="btn btn-sm btn-secondary" onclick="exportReport('attendance')">导出</button>
|
||||
</div>
|
||||
<div id="attendanceSummary" class="report-summary"></div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>序号</th>
|
||||
<th>学号</th>
|
||||
<th>姓名</th>
|
||||
<th>出勤</th>
|
||||
<th>缺勤</th>
|
||||
<th>迟到</th>
|
||||
<th>请假</th>
|
||||
<th>记录数</th>
|
||||
<th>出勤率</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="attendanceReportList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title" style="display:flex; justify-content:space-between; align-items:center;">
|
||||
<span>作业统计</span>
|
||||
<button class="btn btn-sm btn-secondary" onclick="exportReport('homework')">导出</button>
|
||||
</div>
|
||||
<div id="homeworkSummary" class="report-summary"></div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>序号</th>
|
||||
<th>学号</th>
|
||||
<th>姓名</th>
|
||||
<th>已交</th>
|
||||
<th>未交</th>
|
||||
<th>迟交</th>
|
||||
<th>记录数</th>
|
||||
<th>未交率</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="homeworkReportList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="/assets/js/reports.js"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -170,12 +170,15 @@ include __DIR__ . '/../includes/header.php';
|
||||
<th colspan="2" style="text-align:center; border-bottom: none;">基本信息</th>
|
||||
<th rowspan="2" style="vertical-align: middle;">姓名</th>
|
||||
<th rowspan="2" style="vertical-align: middle;">操行分</th>
|
||||
<th colspan="2" style="text-align:center; border-bottom: none;">环比上次</th>
|
||||
<th colspan="4" style="text-align:center; border-bottom: none;">考勤统计</th>
|
||||
<th colspan="3" style="text-align:center; border-bottom: none;">作业统计</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>排名</th>
|
||||
<th>学号</th>
|
||||
<th>分数变化</th>
|
||||
<th>排名变化</th>
|
||||
<th>出勤</th>
|
||||
<th>缺勤</th>
|
||||
<th>迟到</th>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 管理端系统设置
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
|
||||
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
header('Location: /index.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$page_title = '系统设置';
|
||||
$role = current_group_name();
|
||||
require_perm('manage_admins');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<div class="card" style="max-width: 640px;">
|
||||
<div class="card-title">密码策略</div>
|
||||
<form id="passwordPolicyForm">
|
||||
<div class="form-group">
|
||||
<label>密码最小长度</label>
|
||||
<input type="number" id="pwdMinLength" min="4" max="64" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码最大长度</label>
|
||||
<input type="number" id="pwdMaxLength" min="8" max="100" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>最少字符种类数</label>
|
||||
<input type="number" id="pwdMinTypes" min="1" max="4" required>
|
||||
<small>可选种类:大写字母 / 小写字母 / 数字 / 特殊符号</small>
|
||||
</div>
|
||||
<small class="pwd-policy"></small>
|
||||
<div style="margin-top: 14px;">
|
||||
<button type="submit" class="btn btn-primary">保存</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/js/settings.js"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -163,7 +163,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<p id="resetStudentInfo" style="margin: 10px 0;"></p>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" id="newStudentPassword" required minlength="6" maxlength="20">
|
||||
<input type="password" id="newStudentPassword" required>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-warning">确认重置</button>
|
||||
|
||||
@@ -338,3 +338,33 @@
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
}
|
||||
/* 排行榜工具栏 */
|
||||
.ranking-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.ranking-toolbar select,
|
||||
.ranking-toolbar input[type="number"],
|
||||
.ranking-toolbar input[type="month"] {
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.ranking-tip {
|
||||
font-size: 14px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
/* 报表汇总说明 */
|
||||
.report-summary {
|
||||
font-size: 13px;
|
||||
color: var(--color-text-secondary);
|
||||
background: var(--color-hover);
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
@@ -289,6 +289,7 @@ body {
|
||||
.table-wrapper {
|
||||
overflow-x: auto;
|
||||
overflow-y: visible;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
table {
|
||||
@@ -798,12 +799,40 @@ tr:hover {
|
||||
}
|
||||
|
||||
.nav {
|
||||
padding: 0 16px;
|
||||
padding: 0 12px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.nav::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.user-role {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
padding: 18px;
|
||||
max-width: 94%;
|
||||
}
|
||||
|
||||
.action-bar {
|
||||
|
||||
@@ -231,8 +231,9 @@ async function submitResetPassword() {
|
||||
if (!currentResetUserId) return;
|
||||
|
||||
const newPassword = document.getElementById('newPassword').value;
|
||||
if (!newPassword || newPassword.length < 6) {
|
||||
showToast('密码长度至少6位', 'warning');
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -275,6 +275,45 @@ function validateScoreChange(value) {
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前密码策略(由后端配置下发)
|
||||
*/
|
||||
function getPasswordPolicy() {
|
||||
return {
|
||||
minLength: window.PASSWORD_MIN_LENGTH || 6,
|
||||
maxLength: window.PASSWORD_MAX_LENGTH || 20,
|
||||
minTypes: window.PASSWORD_MIN_TYPES || 3
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码策略提示文本
|
||||
*/
|
||||
function describePasswordPolicy() {
|
||||
const p = getPasswordPolicy();
|
||||
return '密码长度' + p.minLength + '-' + p.maxLength + '位,需包含大写字母、小写字母、数字、特殊符号中的至少' + p.minTypes + '种';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按密码策略校验,返回错误信息(空字符串表示通过)
|
||||
*/
|
||||
function validatePasswordByPolicy(password) {
|
||||
const p = getPasswordPolicy();
|
||||
if (!password || password.length < p.minLength) {
|
||||
return '密码长度至少' + p.minLength + '位';
|
||||
}
|
||||
if (password.length > p.maxLength) {
|
||||
return '密码长度不能超过' + p.maxLength + '位';
|
||||
}
|
||||
const types = [/[A-Z]/, /[a-z]/, /[0-9]/, /[^A-Za-z0-9]/].filter(function(re) {
|
||||
return re.test(password);
|
||||
}).length;
|
||||
if (types < p.minTypes) {
|
||||
return '密码需包含大写字母、小写字母、数字、特殊符号中的至少' + p.minTypes + '种';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function showToast(message, type = 'success') {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast-${type}`;
|
||||
@@ -490,6 +529,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
if (logoutBtn) {
|
||||
logoutBtn.addEventListener('click', logout);
|
||||
}
|
||||
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||
el.textContent = describePasswordPolicy();
|
||||
});
|
||||
});
|
||||
|
||||
function toggleActionDropdown(el) {
|
||||
|
||||
@@ -71,24 +71,109 @@ async function loadDashboard() {
|
||||
}
|
||||
document.getElementById('quickActions').innerHTML = quickActions || '<p>暂无快捷操作</p>';
|
||||
|
||||
const rankingRes = await apiGet('/api/student/ranking', { limit: 100 });
|
||||
if (rankingRes && rankingRes.success) {
|
||||
totalStudents = rankingRes.data.total_students || 0;
|
||||
let html = '';
|
||||
rankingRes.data.ranking.forEach((student, index) => {
|
||||
const rank = index + 1;
|
||||
await loadRanking();
|
||||
}
|
||||
|
||||
async function loadRanking() {
|
||||
const type = document.getElementById('rankingType').value;
|
||||
const params = { limit: 100 };
|
||||
if (type === 'monthly') {
|
||||
const monthInput = document.getElementById('rankingMonth');
|
||||
if (monthInput.value) params.month = monthInput.value;
|
||||
}
|
||||
|
||||
const rankingRes = await apiGet('/api/student/ranking', params);
|
||||
const head = document.getElementById('rankingHead');
|
||||
if (type === 'monthly') {
|
||||
head.innerHTML = '<th>排名</th><th>学号</th><th>姓名</th><th>加分</th><th>减分</th><th>月度分</th>';
|
||||
} else {
|
||||
head.innerHTML = '<th>排名</th><th>学号</th><th>姓名</th><th>操行分</th>';
|
||||
}
|
||||
if (!rankingRes || !rankingRes.success) return;
|
||||
|
||||
totalStudents = rankingRes.data.total_students || 0;
|
||||
let html = '';
|
||||
rankingRes.data.ranking.forEach((student, index) => {
|
||||
const rank = index + 1;
|
||||
if (type === 'monthly') {
|
||||
const score = student.month_score || 0;
|
||||
const cls = score > 0 ? 'plus' : (score < 0 ? 'minus' : '');
|
||||
html += `<tr>
|
||||
<td>${rank}</td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td>${escapeHtml(student.name)}</td>
|
||||
<td class="plus">+${student.bonus || 0}</td>
|
||||
<td class="minus">${student.deduction || 0}</td>
|
||||
<td class="${cls}">${score > 0 ? '+' : ''}${score}</td>
|
||||
</tr>`;
|
||||
} else {
|
||||
html += `<tr>
|
||||
<td>${rank}</td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td>${escapeHtml(student.name)}</td>
|
||||
<td>${student.total_points}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (rankingRes.data.ranking.length === 0) {
|
||||
html = '<tr><td colspan="4" style="text-align:center;">暂无数据</td></tr>';
|
||||
}
|
||||
document.getElementById('rankingList').innerHTML = html;
|
||||
});
|
||||
if (rankingRes.data.ranking.length === 0) {
|
||||
const cols = type === 'monthly' ? 6 : 4;
|
||||
html = `<tr><td colspan="${cols}" style="text-align:center;">暂无数据</td></tr>`;
|
||||
}
|
||||
document.getElementById('rankingList').innerHTML = html;
|
||||
}
|
||||
|
||||
function onRankingTypeChange() {
|
||||
const isMonthly = document.getElementById('rankingType').value === 'monthly';
|
||||
const monthInput = document.getElementById('rankingMonth');
|
||||
monthInput.style.display = isMonthly ? '' : 'none';
|
||||
if (isMonthly && !monthInput.value) {
|
||||
const now = new Date();
|
||||
monthInput.value = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
|
||||
}
|
||||
resetPercentileFilter();
|
||||
loadRanking();
|
||||
}
|
||||
|
||||
async function exportRanking() {
|
||||
const type = document.getElementById('rankingType').value;
|
||||
const params = { limit: 1000 };
|
||||
let label = '总分排行';
|
||||
if (type === 'monthly') {
|
||||
const month = document.getElementById('rankingMonth').value;
|
||||
if (!month) {
|
||||
showToast('请先选择月份', 'warning');
|
||||
return;
|
||||
}
|
||||
params.month = month;
|
||||
label = '月度排行_' + month;
|
||||
}
|
||||
|
||||
const res = await apiGet('/api/student/ranking', params);
|
||||
if (!res || !res.success) {
|
||||
showToast('导出失败', 'error');
|
||||
return;
|
||||
}
|
||||
const ranking = res.data.ranking || [];
|
||||
if (ranking.length === 0) {
|
||||
showToast('没有可导出的数据', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
let csv = type === 'monthly'
|
||||
? '排名,学号,姓名,加分,减分,月度分\n'
|
||||
: '排名,学号,姓名,操行分\n';
|
||||
ranking.forEach(function(s, index) {
|
||||
if (type === 'monthly') {
|
||||
csv += [index + 1, s.student_no, s.name, s.bonus || 0, s.deduction || 0, s.month_score || 0]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
} else {
|
||||
csv += [index + 1, s.student_no, s.name, s.total_points]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
}
|
||||
});
|
||||
|
||||
downloadCsv('排行榜_' + label + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
showToast('导出成功,共' + ranking.length + '人');
|
||||
}
|
||||
|
||||
function applyPercentileFilter() {
|
||||
@@ -121,6 +206,9 @@ document.getElementById('percentileFilter').addEventListener('keypress', functio
|
||||
loadDashboard();
|
||||
|
||||
window.loadDashboard = loadDashboard;
|
||||
window.loadRanking = loadRanking;
|
||||
window.onRankingTypeChange = onRankingTypeChange;
|
||||
window.exportRanking = exportRanking;
|
||||
window.applyPercentileFilter = applyPercentileFilter;
|
||||
window.resetPercentileFilter = resetPercentileFilter;
|
||||
|
||||
|
||||
@@ -246,12 +246,81 @@ async function exportHistoryRecords() {
|
||||
return;
|
||||
}
|
||||
|
||||
var csv = '时间,学号,姓名,学期,类型,分数变动,原因,操作人\n';
|
||||
records.forEach(function(r) {
|
||||
var mode = getHistoryExportMode();
|
||||
var csv;
|
||||
if (mode === 'per_student') {
|
||||
csv = buildPerStudentCsv(records);
|
||||
} else {
|
||||
csv = '时间,学号,姓名,学期,类型,分数变动,原因,操作人\n';
|
||||
records.forEach(function(r) {
|
||||
csv += [
|
||||
r.created_at || '',
|
||||
r.student_no || '',
|
||||
r.student_name || '',
|
||||
r.semester_name || '',
|
||||
typeMap(r.related_type),
|
||||
(r.points_change > 0 ? '+' : '') + r.points_change,
|
||||
r.reason || '',
|
||||
r.recorder_name || ''
|
||||
].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
}
|
||||
|
||||
var semesterLabel = '全部学期';
|
||||
if (semesterSelect && semesterId && semesterSelect.selectedIndex >= 0) {
|
||||
semesterLabel = semesterSelect.options[semesterSelect.selectedIndex].textContent.replace(/((当前|已归档))$/, '');
|
||||
}
|
||||
var safeLabel = semesterLabel.replace(/[\\/:*?"<>|]/g, '_');
|
||||
var modeLabel = mode === 'per_student' ? '_按学生分表' : '';
|
||||
downloadCsv('历史记录_' + safeLabel + modeLabel + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
|
||||
closeModal('exportHistoryModal');
|
||||
showToast('导出成功,共' + records.length + '条记录');
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function showExportHistoryModal() {
|
||||
document.getElementById('exportHistoryModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function getHistoryExportMode() {
|
||||
var el = document.querySelector('input[name="historyExportMode"]:checked');
|
||||
return el ? el.value : 'detail';
|
||||
}
|
||||
|
||||
// 按学生分表:每个学生一段(汇总 + 明细),便于发给家长
|
||||
function buildPerStudentCsv(records) {
|
||||
var groups = {};
|
||||
var order = [];
|
||||
records.forEach(function(r) {
|
||||
var key = r.student_id;
|
||||
if (!groups[key]) {
|
||||
groups[key] = { no: r.student_no || '', name: r.student_name || '', records: [] };
|
||||
order.push(key);
|
||||
}
|
||||
groups[key].records.push(r);
|
||||
});
|
||||
order.sort(function(a, b) {
|
||||
return String(groups[a].no).localeCompare(String(groups[b].no));
|
||||
});
|
||||
|
||||
var csv = '';
|
||||
order.forEach(function(key) {
|
||||
var group = groups[key];
|
||||
var bonus = 0;
|
||||
var deduction = 0;
|
||||
group.records.forEach(function(r) {
|
||||
if (r.points_change > 0) bonus += r.points_change;
|
||||
else deduction += r.points_change;
|
||||
});
|
||||
csv += ['学生', group.no + ' ' + group.name, '加分合计', '+' + bonus, '减分合计', deduction]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
csv += '时间,学期,类型,分值,原因,操作人\n';
|
||||
group.records.forEach(function(r) {
|
||||
csv += [
|
||||
r.created_at || '',
|
||||
r.student_no || '',
|
||||
r.student_name || '',
|
||||
r.semester_name || '',
|
||||
typeMap(r.related_type),
|
||||
(r.points_change > 0 ? '+' : '') + r.points_change,
|
||||
@@ -259,18 +328,9 @@ async function exportHistoryRecords() {
|
||||
r.recorder_name || ''
|
||||
].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
|
||||
var semesterLabel = '全部学期';
|
||||
if (semesterSelect && semesterId && semesterSelect.selectedIndex >= 0) {
|
||||
semesterLabel = semesterSelect.options[semesterSelect.selectedIndex].textContent.replace(/((当前|已归档))$/, '');
|
||||
}
|
||||
var safeLabel = semesterLabel.replace(/[\\/:*?"<>|]/g, '_');
|
||||
downloadCsv('历史记录_' + safeLabel + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
|
||||
showToast('导出成功,共' + records.length + '条记录');
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
}
|
||||
csv += '\n';
|
||||
});
|
||||
return csv;
|
||||
}
|
||||
|
||||
// 批量撤销合并记录(按条件查找并撤销)
|
||||
@@ -333,6 +393,7 @@ Promise.all([loadStudentsForSelect(), loadSubjectsForFilter(), loadSemestersForF
|
||||
|
||||
window.loadHistory = loadHistory;
|
||||
window.loadStudentsForSelect = loadStudentsForSelect;
|
||||
window.showExportHistoryModal = showExportHistoryModal;
|
||||
window.exportHistoryRecords = exportHistoryRecords;
|
||||
window.batchRevokeGrouped = batchRevokeGrouped;
|
||||
window.onStudentFilterChange = onStudentFilterChange;
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 操作日志页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const OPERATION_TYPES = {
|
||||
add_student: '新增学生',
|
||||
update_student: '编辑学生',
|
||||
delete_student: '删除学生',
|
||||
import_students: '导入学生',
|
||||
reset_student_password: '重置学生密码',
|
||||
add_points: '加减分',
|
||||
revoke_record: '撤销记录',
|
||||
restore_record: '反撤销记录',
|
||||
add_attendance: '添加考勤',
|
||||
add_admin: '添加管理员',
|
||||
reactivate_admin: '重新激活管理员',
|
||||
update_admin: '编辑管理员',
|
||||
toggle_admin_status: '启用/禁用管理员',
|
||||
reset_password: '重置管理员密码',
|
||||
unlock_user: '解除登录锁定',
|
||||
create_semester: '创建学期',
|
||||
update_semester: '编辑学期',
|
||||
delete_semester: '删除学期',
|
||||
activate_semester: '激活学期',
|
||||
associate_records: '关联学期数据',
|
||||
archive_semester: '归档学期',
|
||||
create_permission_group: '新建权限组',
|
||||
update_permission_group: '编辑权限组',
|
||||
delete_permission_group: '删除权限组',
|
||||
update_password_policy: '修改密码策略'
|
||||
};
|
||||
|
||||
const TARGET_TYPES = {
|
||||
student: '学生',
|
||||
admin: '管理员',
|
||||
conduct: '操行分',
|
||||
attendance: '考勤',
|
||||
semester: '学期',
|
||||
subject: '科目',
|
||||
permission_group: '权限组',
|
||||
user: '用户',
|
||||
setting: '系统设置'
|
||||
};
|
||||
|
||||
let currentPage = 1;
|
||||
|
||||
function operationLabel(type) {
|
||||
return OPERATION_TYPES[type] || type;
|
||||
}
|
||||
|
||||
function targetLabel(type) {
|
||||
return type ? (TARGET_TYPES[type] || type) : '-';
|
||||
}
|
||||
|
||||
async function loadLogTypes() {
|
||||
const res = await apiGet('/api/admin/operation-logs/types');
|
||||
if (res && res.success && res.data && res.data.types) {
|
||||
const select = document.getElementById('logTypeFilter');
|
||||
let html = '<option value="">全部</option>';
|
||||
res.data.types.forEach(function(type) {
|
||||
html += '<option value="' + escapeHtml(type) + '">' + escapeHtml(operationLabel(type)) + '</option>';
|
||||
});
|
||||
select.innerHTML = html;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLogs(page) {
|
||||
currentPage = page || 1;
|
||||
const params = {
|
||||
page: currentPage,
|
||||
page_size: 20,
|
||||
operation_type: document.getElementById('logTypeFilter').value,
|
||||
operator: document.getElementById('logOperatorFilter').value.trim(),
|
||||
start_date: document.getElementById('logStartDate').value,
|
||||
end_date: document.getElementById('logEndDate').value
|
||||
};
|
||||
|
||||
const res = await apiGet('/api/admin/operation-logs', params);
|
||||
if (!res || !res.success) {
|
||||
showToast((res && res.message) || '加载操作日志失败', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
(res.data.logs || []).forEach(function(log) {
|
||||
const targetText = targetLabel(log.target_type) + (log.target_id ? '#' + log.target_id : '');
|
||||
html += `<tr>
|
||||
<td style="white-space: nowrap;">${formatDateTime(log.created_at)}</td>
|
||||
<td>${escapeHtml(log.operator_name || '-')}</td>
|
||||
<td>${escapeHtml(log.operator_role || '-')}</td>
|
||||
<td>${escapeHtml(operationLabel(log.operation_type))}</td>
|
||||
<td style="white-space: nowrap;">${escapeHtml(targetText)}</td>
|
||||
<td class="cell-wrap">${escapeHtml(log.details || '-')}</td>
|
||||
<td>${escapeHtml(log.ip_address || '-')}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if ((res.data.logs || []).length === 0) {
|
||||
html = '<tr><td colspan="7" style="text-align:center;">暂无日志</td></tr>';
|
||||
}
|
||||
document.getElementById('logList').innerHTML = html;
|
||||
|
||||
renderSmartPagination('logPagination', currentPage, res.data.total_pages || 1, function(page) {
|
||||
loadLogs(page);
|
||||
});
|
||||
}
|
||||
|
||||
loadLogTypes();
|
||||
loadLogs(1);
|
||||
|
||||
window.loadLogs = loadLogs;
|
||||
|
||||
})();
|
||||
@@ -94,8 +94,9 @@
|
||||
const studentId = document.getElementById('resetStudentId').value;
|
||||
const newPassword = document.getElementById('newStudentPassword').value;
|
||||
|
||||
if (!newPassword || newPassword.length < 6) {
|
||||
showToast('密码至少6位', 'warning');
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 数据报表页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
let attendanceCache = null;
|
||||
let homeworkCache = null;
|
||||
|
||||
function formatDateValue(date) {
|
||||
return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
|
||||
}
|
||||
|
||||
async function initReportDates() {
|
||||
const startInput = document.getElementById('reportStartDate');
|
||||
const endInput = document.getElementById('reportEndDate');
|
||||
const today = new Date();
|
||||
let start = new Date(today.getFullYear(), today.getMonth(), 1);
|
||||
|
||||
try {
|
||||
const res = await apiGet('/api/semester/active');
|
||||
if (res && res.success && res.data && res.data.start_date) {
|
||||
start = new Date(res.data.start_date);
|
||||
}
|
||||
} catch (e) { /* 使用默认月初 */ }
|
||||
|
||||
startInput.value = formatDateValue(start);
|
||||
endInput.value = formatDateValue(today);
|
||||
}
|
||||
|
||||
async function loadReports() {
|
||||
const startDate = document.getElementById('reportStartDate').value;
|
||||
const endDate = document.getElementById('reportEndDate').value;
|
||||
if (!startDate || !endDate) {
|
||||
showToast('请选择开始和结束日期', 'warning');
|
||||
return;
|
||||
}
|
||||
if (startDate > endDate) {
|
||||
showToast('开始日期不能晚于结束日期', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('reportRangeHint').textContent = `统计范围:${startDate} ~ ${endDate}`;
|
||||
|
||||
const [attendanceRes, homeworkRes] = await Promise.all([
|
||||
apiGet('/api/report/attendance', { start_date: startDate, end_date: endDate }),
|
||||
apiGet('/api/report/homework', { start_date: startDate, end_date: endDate })
|
||||
]);
|
||||
|
||||
if (attendanceRes && attendanceRes.success) {
|
||||
attendanceCache = attendanceRes.data;
|
||||
renderAttendance(attendanceRes.data);
|
||||
} else {
|
||||
showToast((attendanceRes && attendanceRes.message) || '考勤报表加载失败', 'error');
|
||||
}
|
||||
if (homeworkRes && homeworkRes.success) {
|
||||
homeworkCache = homeworkRes.data;
|
||||
renderHomework(homeworkRes.data);
|
||||
} else {
|
||||
showToast((homeworkRes && homeworkRes.message) || '作业报表加载失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function rateText(rate) {
|
||||
return (rate === null || rate === undefined) ? '-' : rate + '%';
|
||||
}
|
||||
|
||||
function renderAttendance(data) {
|
||||
const rows = data.rows || [];
|
||||
const summary = data.summary || {};
|
||||
document.getElementById('attendanceSummary').textContent =
|
||||
`共 ${rows.length} 人,${summary.total || 0} 条记录:出勤 ${summary.present || 0}、缺勤 ${summary.absent || 0}、迟到 ${summary.late || 0}、请假 ${summary.leave || 0},出勤率 ${rateText(summary.rate)}`;
|
||||
|
||||
let html = '';
|
||||
rows.forEach((row, index) => {
|
||||
html += `<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td>${escapeHtml(row.student_no)}</td>
|
||||
<td>${escapeHtml(row.name)}</td>
|
||||
<td class="plus">${row.present}</td>
|
||||
<td class="minus">${row.absent}</td>
|
||||
<td>${row.late}</td>
|
||||
<td>${row.leave}</td>
|
||||
<td>${row.total}</td>
|
||||
<td>${rateText(row.rate)}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (rows.length === 0) {
|
||||
html = '<tr><td colspan="9" style="text-align:center;">暂无数据</td></tr>';
|
||||
}
|
||||
document.getElementById('attendanceReportList').innerHTML = html;
|
||||
}
|
||||
|
||||
function renderHomework(data) {
|
||||
const rows = data.rows || [];
|
||||
const summary = data.summary || {};
|
||||
document.getElementById('homeworkSummary').textContent =
|
||||
`共 ${rows.length} 人,${summary.total || 0} 条记录:已交 ${summary.submitted || 0}、未交 ${summary.not_submitted || 0}、迟交 ${summary.late || 0},未交率 ${rateText(summary.miss_rate)}`;
|
||||
|
||||
let html = '';
|
||||
rows.forEach((row, index) => {
|
||||
html += `<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td>${escapeHtml(row.student_no)}</td>
|
||||
<td>${escapeHtml(row.name)}</td>
|
||||
<td class="plus">${row.submitted}</td>
|
||||
<td class="minus">${row.not_submitted}</td>
|
||||
<td>${row.late}</td>
|
||||
<td>${row.total}</td>
|
||||
<td>${rateText(row.miss_rate)}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (rows.length === 0) {
|
||||
html = '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
|
||||
}
|
||||
document.getElementById('homeworkReportList').innerHTML = html;
|
||||
}
|
||||
|
||||
function exportReport(type) {
|
||||
const data = type === 'attendance' ? attendanceCache : homeworkCache;
|
||||
if (!data || !data.rows || data.rows.length === 0) {
|
||||
showToast('请先查询报表数据', 'warning');
|
||||
return;
|
||||
}
|
||||
let csv = '';
|
||||
if (type === 'attendance') {
|
||||
csv += '序号,学号,姓名,出勤,缺勤,迟到,请假,记录数,出勤率(%)\n';
|
||||
data.rows.forEach((row, index) => {
|
||||
csv += [index + 1, row.student_no, row.name, row.present, row.absent, row.late, row.leave, row.total,
|
||||
(row.rate === null || row.rate === undefined) ? '' : row.rate].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
} else {
|
||||
csv += '序号,学号,姓名,已交,未交,迟交,记录数,未交率(%)\n';
|
||||
data.rows.forEach((row, index) => {
|
||||
csv += [index + 1, row.student_no, row.name, row.submitted, row.not_submitted, row.late, row.total,
|
||||
(row.miss_rate === null || row.miss_rate === undefined) ? '' : row.miss_rate].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
}
|
||||
const label = type === 'attendance' ? '考勤统计' : '作业统计';
|
||||
downloadCsv(`${label}_${data.start_date}_${data.end_date}.csv`, csv);
|
||||
showToast('导出成功,共' + data.rows.length + '人');
|
||||
}
|
||||
|
||||
initReportDates().then(loadReports);
|
||||
|
||||
window.loadReports = loadReports;
|
||||
window.exportReport = exportReport;
|
||||
|
||||
})();
|
||||
@@ -253,13 +253,33 @@ async function viewArchiveData(semesterId, semesterName, page) {
|
||||
if (res && res.success) {
|
||||
const data = res.data || {};
|
||||
const archives = data.archives || [];
|
||||
const prevName = data.previous_semester ? data.previous_semester.semester_name : null;
|
||||
document.getElementById('archiveDataTitle').textContent =
|
||||
`归档数据 - ${semesterName}` + (prevName ? `(对比:${prevName})` : '(无对比学期)');
|
||||
let html = '';
|
||||
archives.forEach(a => {
|
||||
const points = a.points_change;
|
||||
const hasPoints = (points !== null && points !== undefined);
|
||||
const pointsText = hasPoints ? (points > 0 ? '+' + points : String(points)) : '-';
|
||||
const pointsClass = hasPoints ? (points > 0 ? 'plus' : (points < 0 ? 'minus' : '')) : '';
|
||||
|
||||
const rankChange = a.rank_change;
|
||||
const hasRank = (rankChange !== null && rankChange !== undefined);
|
||||
let rankText = '-';
|
||||
let rankClass = '';
|
||||
if (hasRank) {
|
||||
if (rankChange > 0) { rankText = '↑' + rankChange; rankClass = 'plus'; }
|
||||
else if (rankChange < 0) { rankText = '↓' + Math.abs(rankChange); rankClass = 'minus'; }
|
||||
else { rankText = '-'; }
|
||||
}
|
||||
|
||||
html += `<tr>
|
||||
<td>${a.rank_position || '-'}</td>
|
||||
<td>${escapeHtml(a.student_no)}</td>
|
||||
<td>${escapeHtml(a.student_name)}</td>
|
||||
<td>${a.final_points}</td>
|
||||
<td class="${pointsClass}">${pointsText}</td>
|
||||
<td class="${rankClass}">${rankText}</td>
|
||||
<td>${a.attendance_present || 0}</td>
|
||||
<td>${a.attendance_absent || 0}</td>
|
||||
<td>${a.attendance_late || 0}</td>
|
||||
@@ -270,7 +290,7 @@ async function viewArchiveData(semesterId, semesterName, page) {
|
||||
</tr>`;
|
||||
});
|
||||
if (archives.length === 0) {
|
||||
html = '<tr><td colspan="11" style="text-align:center;">暂无归档数据</td></tr>';
|
||||
html = '<tr><td colspan="13" style="text-align:center;">暂无归档数据</td></tr>';
|
||||
}
|
||||
document.getElementById('archiveDataList').innerHTML = html;
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 系统设置页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
async function loadPasswordPolicy() {
|
||||
const res = await apiGet('/api/admin/settings/password-policy');
|
||||
if (!res || !res.success) {
|
||||
showToast((res && res.message) || '获取密码策略失败', 'error');
|
||||
return;
|
||||
}
|
||||
document.getElementById('pwdMinLength').value = res.data.min_length;
|
||||
document.getElementById('pwdMaxLength').value = res.data.max_length;
|
||||
document.getElementById('pwdMinTypes').value = res.data.min_types;
|
||||
applyPolicyGlobals(res.data);
|
||||
}
|
||||
|
||||
function applyPolicyGlobals(policy) {
|
||||
window.PASSWORD_MIN_LENGTH = policy.min_length;
|
||||
window.PASSWORD_MAX_LENGTH = policy.max_length;
|
||||
window.PASSWORD_MIN_TYPES = policy.min_types;
|
||||
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||
el.textContent = describePasswordPolicy();
|
||||
});
|
||||
}
|
||||
|
||||
async function savePasswordPolicy() {
|
||||
const minLength = parseInt(document.getElementById('pwdMinLength').value);
|
||||
const maxLength = parseInt(document.getElementById('pwdMaxLength').value);
|
||||
const minTypes = parseInt(document.getElementById('pwdMinTypes').value);
|
||||
|
||||
if (isNaN(minLength) || isNaN(maxLength) || isNaN(minTypes)) {
|
||||
showToast('请填写完整的密码策略', 'warning');
|
||||
return;
|
||||
}
|
||||
if (minLength < 4 || minLength > 64) {
|
||||
showToast('最小长度需在4-64之间', 'warning');
|
||||
return;
|
||||
}
|
||||
if (maxLength < 8 || maxLength > 100) {
|
||||
showToast('最大长度需在8-100之间', 'warning');
|
||||
return;
|
||||
}
|
||||
if (minLength > maxLength) {
|
||||
showToast('最小长度不能大于最大长度', 'warning');
|
||||
return;
|
||||
}
|
||||
if (minTypes < 1 || minTypes > 4) {
|
||||
showToast('字符种类数需在1-4之间', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await apiPut('/api/admin/settings/password-policy', {
|
||||
min_length: minLength,
|
||||
max_length: maxLength,
|
||||
min_types: minTypes
|
||||
});
|
||||
if (res && res.success) {
|
||||
applyPolicyGlobals({ min_length: minLength, max_length: maxLength, min_types: minTypes });
|
||||
showToast(res.message || '密码策略已保存');
|
||||
} else {
|
||||
showToast((res && res.message) || '保存失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('passwordPolicyForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
savePasswordPolicy();
|
||||
});
|
||||
|
||||
loadPasswordPolicy();
|
||||
|
||||
window.savePasswordPolicy = savePasswordPolicy;
|
||||
|
||||
})();
|
||||
@@ -62,6 +62,9 @@ $page_title = $page_title ?? '首页';
|
||||
window.DEDUCTION_ATTENDANCE_LATE = resp.data.DEDUCTION_ATTENDANCE_LATE;
|
||||
window.DEDUCTION_ATTENDANCE_LEAVE = resp.data.DEDUCTION_ATTENDANCE_LEAVE;
|
||||
window.STUDENT_INITIAL_POINTS = resp.data.STUDENT_INITIAL_POINTS;
|
||||
window.PASSWORD_MIN_LENGTH = resp.data.PASSWORD_MIN_LENGTH;
|
||||
window.PASSWORD_MAX_LENGTH = resp.data.PASSWORD_MAX_LENGTH;
|
||||
window.PASSWORD_MIN_TYPES = resp.data.PASSWORD_MIN_TYPES;
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
@@ -72,6 +75,9 @@ $page_title = $page_title ?? '首页';
|
||||
window.DEDUCTION_ATTENDANCE_LATE = 1;
|
||||
window.DEDUCTION_ATTENDANCE_LEAVE = 0;
|
||||
window.STUDENT_INITIAL_POINTS = 60;
|
||||
window.PASSWORD_MIN_LENGTH = 6;
|
||||
window.PASSWORD_MAX_LENGTH = 20;
|
||||
window.PASSWORD_MIN_TYPES = 3;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -8,12 +8,19 @@
|
||||
<?php if (has_perm('manage_attendance')): ?>
|
||||
<a href="/admin/attendance.php" class="nav-item<?php echo $current_page === 'attendance' ? ' active' : ''; ?>">考勤管理</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('view_all_records')): ?>
|
||||
<a href="/admin/reports.php" class="nav-item<?php echo $current_page === 'reports' ? ' active' : ''; ?>">数据报表</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_admins')): ?>
|
||||
<a href="/admin/admins.php" class="nav-item<?php echo $current_page === 'admins' ? ' active' : ''; ?>">管理员管理</a>
|
||||
<a href="/admin/logs.php" class="nav-item<?php echo $current_page === 'logs' ? ' active' : ''; ?>">操作日志</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_semesters')): ?>
|
||||
<a href="/admin/semesters.php" class="nav-item<?php echo $current_page === 'semesters' ? ' active' : ''; ?>">学期管理</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_admins')): ?>
|
||||
<a href="/admin/settings.php" class="nav-item<?php echo $current_page === 'settings' ? ' active' : ''; ?>">系统设置</a>
|
||||
<?php endif; ?>
|
||||
<a href="/admin/history.php" class="nav-item<?php echo $current_page === 'history' ? ' active' : ''; ?>">历史记录</a>
|
||||
<?php if (has_perm('view_all_records')): ?>
|
||||
<a href="/admin/record_query.php" class="nav-item<?php echo $current_page === 'record_query' ? ' active' : ''; ?>">个人查询</a>
|
||||
|
||||
@@ -39,7 +39,7 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
||||
<div class="form-group">
|
||||
<label>新密码 <span style="color:red;">*</span></label>
|
||||
<input type="password" id="newPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码 <span style="color:red;">*</span></label>
|
||||
@@ -62,10 +62,26 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/js/common.js"></script>
|
||||
<script>
|
||||
window.API_BASE_URL = '<?php echo API_BASE_URL; ?>';
|
||||
const RESET_TOKEN = '<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>';
|
||||
|
||||
// 加载密码策略(公开配置)
|
||||
fetch(window.API_BASE_URL + '/api/config/deduction-rules')
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(resp) {
|
||||
if (resp && resp.success && resp.data) {
|
||||
window.PASSWORD_MIN_LENGTH = resp.data.PASSWORD_MIN_LENGTH;
|
||||
window.PASSWORD_MAX_LENGTH = resp.data.PASSWORD_MAX_LENGTH;
|
||||
window.PASSWORD_MIN_TYPES = resp.data.PASSWORD_MIN_TYPES;
|
||||
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||
el.textContent = describePasswordPolicy();
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(function() {});
|
||||
|
||||
function showTip(msg, isError) {
|
||||
const tip = document.getElementById('tipMsg');
|
||||
tip.textContent = msg;
|
||||
@@ -106,8 +122,9 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
||||
showTip('两次输入的密码不一致', true);
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 6 || newPassword.length > 20) {
|
||||
showTip('密码长度需为6-20位', true);
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showTip(policyError, true);
|
||||
return;
|
||||
}
|
||||
const btn = document.getElementById('submitBtn');
|
||||
|
||||
@@ -202,7 +202,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" id="newPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码</label>
|
||||
@@ -224,7 +224,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" id="forceNewPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码</label>
|
||||
|
||||
@@ -40,7 +40,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" id="newPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码</label>
|
||||
@@ -63,6 +63,12 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
||||
return;
|
||||
}
|
||||
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await apiPost('/api/auth/change-password', {
|
||||
old_password: oldPassword,
|
||||
new_password: newPassword
|
||||
|
||||
+2
-2
@@ -277,7 +277,7 @@ VALUES
|
||||
|
||||
-- 初始化系统版本号
|
||||
INSERT INTO `system_settings` (`setting_key`, `setting_value`)
|
||||
VALUES ('db_version', '4.2')
|
||||
ON DUPLICATE KEY UPDATE `setting_value` = '4.2';
|
||||
VALUES ('db_version', '4.4')
|
||||
ON DUPLICATE KEY UPDATE `setting_value` = '4.4';
|
||||
-- 控制台输出初始化结果(含版本号)
|
||||
SELECT CONCAT('数据库初始化完成!版本: v', (SELECT setting_value FROM system_settings WHERE setting_key = 'db_version')) AS message;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- ===========================================
|
||||
-- 班级操行分管理系统 - v4.2 → v4.3 升级脚本
|
||||
-- 字符集: utf8mb4
|
||||
--
|
||||
-- 说明: v4.3 月度分排行(无数据库结构变更)
|
||||
-- 管理端首页新增"月度分排行",可按月份查看当月加分/减分/月度分排名;
|
||||
-- 月度分 = 当月加分 - 当月减分,与基础分无关。
|
||||
--
|
||||
-- 兼容性: 幂等,可重复执行
|
||||
-- ===========================================
|
||||
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- ===========================================
|
||||
-- 班级操行分管理系统 - v4.3 → v4.4 升级脚本
|
||||
-- 字符集: utf8mb4
|
||||
--
|
||||
-- 说明: v4.4 报表与审计(无数据库结构变更)
|
||||
-- 1. 数据报表:考勤统计、作业统计(支持日期范围与CSV导出)
|
||||
-- 2. 操作日志查看页(筛选 + 分页)
|
||||
-- 3. 系统设置:密码策略可配置(存于 system_settings 表)
|
||||
-- 4. 排行榜导出;学期归档环比对比;历史记录按学生分表导出
|
||||
--
|
||||
-- 兼容性: 幂等,可重复执行
|
||||
-- ===========================================
|
||||
|
||||
SELECT 1;
|
||||
@@ -37,6 +37,8 @@ $UPGRADE_VERSIONS = [
|
||||
'4.0' => __DIR__ . '/sql/upgrades/v4.0.sql',
|
||||
'4.1' => __DIR__ . '/sql/upgrades/v4.1.sql',
|
||||
'4.2' => __DIR__ . '/sql/upgrades/v4.2.sql',
|
||||
'4.3' => __DIR__ . '/sql/upgrades/v4.3.sql',
|
||||
'4.4' => __DIR__ . '/sql/upgrades/v4.4.sql',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user