Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
058dee9dc4 | ||
|
|
3588b4c28c |
No files matched your search
+12
@@ -332,6 +332,18 @@ sudo systemctl restart nginx
|
||||
| `DEDUCTION_ATTENDANCE_ABSENT` | 缺勤扣分 | 5 |
|
||||
| `DEDUCTION_ATTENDANCE_LATE` | 迟到扣分 | 2 |
|
||||
| `DEDUCTION_ATTENDANCE_LEAVE` | 请假扣分 | 1 |
|
||||
| `FRONTEND_URL` | 前端站点地址(生成密码重置链接) | https://class.example.com |
|
||||
| `SMTP_ENABLED` | 是否启用邮件(找回密码) | true / false |
|
||||
| `SMTP_HOST` | SMTP服务器 | smtp.qq.com |
|
||||
| `SMTP_PORT` | SMTP端口(SSL:465 / STARTTLS:587) | 465 |
|
||||
| `SMTP_USER` | SMTP账号 | no-reply@example.com |
|
||||
| `SMTP_PASSWORD` | SMTP密码/授权码 | 授权码 |
|
||||
| `SMTP_FROM` | 发件人邮箱 | no-reply@example.com |
|
||||
| `SMTP_SSL` | 是否使用SSL直连 | true |
|
||||
| `SMTP_STARTTLS` | 是否使用STARTTLS | false |
|
||||
| `PASSWORD_RESET_EXPIRE_MINUTES` | 重置链接有效期(分钟) | 30 |
|
||||
|
||||
> 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -21,35 +21,23 @@
|
||||
### 管理端
|
||||
|
||||
**班主任权限:**
|
||||
- 学生管理:新增/编辑/删除学生、批量导入学生(JSON)
|
||||
- 操行分管理:对学生进行加减分、撤销任何扣分记录、查看全班历史记录、导出德育分记录
|
||||
- 学生管理:新增/编辑/删除学生、批量导入学生(JSON)、按自选字段导出学生名单(CSV)
|
||||
- 操行分管理:对学生进行加减分、撤销任何扣分记录、查看全班历史记录、按学期导出德育分记录(含基础分/加分/减分拆分)
|
||||
- 作业管理:发布作业、查看提交情况
|
||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值
|
||||
- 科目管理:动态增删学科
|
||||
- 管理员管理:添加/编辑/禁用-启用/重置密码班长/科代表/考勤委员/劳动委员/志愿委员
|
||||
- 权限组管理:自定义权限组(勾选功能权限 + 配置加分/扣分上限),管理员账号绑定权限组与邮箱;班主任组为锁定系统组,其余预置组可编辑
|
||||
- 密码找回:管理员绑定邮箱后,可在登录页通过 SMTP 邮件自助重置密码(链接一次性、限时有效)
|
||||
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
||||
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
||||
- 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法)
|
||||
- 数据导出:导出历史记录、导出德育分记录(含加分/减分历史)
|
||||
- 数据导出:按学期导出历史记录、导出德育分记录(默认当前学期,可选历史学期/全部学期)
|
||||
|
||||
**班长权限:**
|
||||
- 操行分管理:对学生进行加减分(±5分以内)、撤销任何人的扣分记录、查看全班历史记录
|
||||
|
||||
**学习委员权限:**
|
||||
- 作业管理:更新作业提交状态、关联扣分(仅扣分,按规则)
|
||||
- 科目管理:动态增删学科
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
**考勤委员权限:**
|
||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤状态、关联扣分(仅扣分,按规则)
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
**劳动委员权限:**
|
||||
- 操行分管理:以卫生值日为理由进行加减分(固定 ±1 分)
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
**志愿委员权限:**
|
||||
- 操行分管理:以服务时长为由进行加分(仅加分)
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
**管理员/班干部权限(v4.0 起由权限组动态控制):**
|
||||
- 管理员账号绑定一个权限组,权限组可自定义以下能力与上限:
|
||||
- 功能权限:学生管理、导出学生名单、操行分加减、撤销他人/撤销自己记录、反撤销、作业扣分、考勤管理、科目管理、管理员管理、学期管理、查看全班/个人查询、数据导出、系统升级
|
||||
- 加减分上限:是否允许加分、单次加分上限、是否允许扣分、单次扣分上限(留空为无限制)
|
||||
- 系统预置六个权限组(班主任/班长/学习委员/考勤委员/劳动委员/志愿委员),默认权限与原角色一致,可随时调整上限或新建自定义组
|
||||
|
||||
## 技术栈
|
||||
## 安全特性
|
||||
@@ -102,6 +90,7 @@ classmanager/
|
||||
│ │ ├── conduct.py # 操行分模型
|
||||
│ │ ├── homework.py # 作业模型
|
||||
│ │ ├── log.py # 日志模型
|
||||
│ │ ├── permission_group.py # 权限组模型(功能权限+加减分上限)
|
||||
│ │ ├── semester.py # 学期模型
|
||||
│ │ ├── student.py # 学生模型
|
||||
│ │ ├── subject.py # 科目模型
|
||||
@@ -144,17 +133,21 @@ classmanager/
|
||||
│ └── utils/ # 工具类
|
||||
│ ├── __init__.py
|
||||
│ ├── database.py # MySQL 连接池
|
||||
│ ├── email_sender.py # SMTP 邮件发送(找回密码)
|
||||
│ ├── jwt_handler.py # JWT 处理
|
||||
│ ├── logger.py # 日志轮转
|
||||
│ ├── redis_client.py # Redis 客户端
|
||||
│ ├── response.py # 统一响应
|
||||
│ └── security.py # 密码加密
|
||||
│ ├── security.py # 密码加密
|
||||
│ └── validators.py # 通用校验(邮箱等)
|
||||
│
|
||||
├── frontend/ # PHP 前端
|
||||
│ ├── .env.example # 前端环境变量示例
|
||||
│ ├── .htaccess # Apache 配置(可选)
|
||||
│ ├── config.php # 前端配置
|
||||
│ ├── forgot_password.php # 忘记密码(申请重置邮件)
|
||||
│ ├── index.php # 登录入口
|
||||
│ ├── reset_password.php # 重置密码(邮件链接落地页)
|
||||
│ │
|
||||
│ ├── admin/ # 管理端
|
||||
│ │ ├── admins.php # 管理员管理
|
||||
@@ -164,6 +157,7 @@ classmanager/
|
||||
│ │ ├── history.php # 历史记录
|
||||
│ │ ├── homework.php # 作业管理
|
||||
│ │ ├── password.php # 修改密码
|
||||
│ │ ├── record_query.php # 个人记录查询(基础分/月度分/理由汇总)
|
||||
│ │ ├── semesters.php # 学期管理
|
||||
│ │ ├── students.php # 学生管理
|
||||
│ │ └── subjects.php # 科目管理
|
||||
@@ -179,6 +173,7 @@ classmanager/
|
||||
│ │ │ ├── admin.js # 管理端 JS
|
||||
│ │ │ ├── common.js # 公共 JS
|
||||
│ │ │ ├── parent.js # 家长端 JS
|
||||
│ │ │ ├── record-query.js # 个人记录查询 JS
|
||||
│ │ │ └── student.js # 学生端 JS
|
||||
│ │ └── uploads/
|
||||
│ │ └── sample_import.json # 学生导入示例
|
||||
@@ -202,7 +197,9 @@ classmanager/
|
||||
│ └── semester_history.php # 学期记录
|
||||
│
|
||||
├── sql/ # 数据库脚本
|
||||
│ └── init.sql # 初始化表结构
|
||||
│ ├── init.sql # 初始化表结构
|
||||
│ └── upgrades/ # 增量升级脚本
|
||||
│ └── v3.0.sql # 最新升级脚本
|
||||
│
|
||||
├── docs/ # 文档
|
||||
│ ├── student.md # 学生端详细文档
|
||||
@@ -222,16 +219,26 @@ classmanager/
|
||||
|
||||
```
|
||||
|
||||
## 角色权限一览表
|
||||
## 权限说明(v4.0 权限组)
|
||||
|
||||
| 角色 | 操行分查看 | 操行分加减 | 撤销扣分 | 历史记录查看 | 其他权限 |
|
||||
| 项目 | 说明 |
|
||||
|------|------|
|
||||
| 权限模型 | 管理员账号绑定一个权限组;权限组由「功能权限 + 加减分上限」组成,可在管理端动态配置 |
|
||||
| 预置权限组 | 班主任(锁定不可编辑)、班长、学习委员、考勤委员、劳动委员、志愿委员,默认权限如下表,上限可随时调整 |
|
||||
| 自定义权限组 | 可新建自定义组(如"纪律委员"),自由勾选 14 项功能权限并设置加分/扣分上限 |
|
||||
| 加减分上限 | 每项操作按权限组的"允许加分/加分上限/允许扣分/扣分上限"校验(前后端一致),留空表示无限制 |
|
||||
| 生效方式 | 权限组调整后,相关管理员刷新页面或最多 60 秒后自动生效 |
|
||||
|
||||
### 预置权限组默认权限
|
||||
|
||||
| 权限组 | 操行分查看 | 操行分加减 | 撤销扣分 | 历史记录查看 | 其他权限 |
|
||||
|------|-----------|-----------|---------|-------------|---------|
|
||||
| 班主任 | 全班 | 无限制 | 可撤销任何记录 | 全班所有记录 | 学生/管理员/科目管理、数据导出 |
|
||||
| 班长 | 全班 | ±5分 | 可撤销任何记录 | 全班所有记录 | - |
|
||||
| 班主任 | 全班 | 无限制 | 可撤销任何记录 | 全班所有记录 | 全部权限(锁定) |
|
||||
| 班长 | 全班 | ±5分 | 可撤销任何记录 | 全班所有记录 | 个人查询 |
|
||||
| 学习委员 | 全班 | ±5分以内(加减分) | 不可撤销 | 仅自己提交的 | 作业管理、科目管理 |
|
||||
| 考勤委员 | 全班 | 仅扣分,最多扣8分 | 不可撤销 | 仅自己提交的 | 考勤管理 |
|
||||
| 考勤委员 | 全班 | 仅扣分,最多扣8分 | 仅撤销自己的记录 | 仅自己提交的 | 考勤管理 |
|
||||
| 劳动委员 | 全班 | ±1分以内 | 不可撤销 | 仅自己提交的 | - |
|
||||
| 志愿委员 | 全班 | 仅加分,最多+5分 | 不可撤销 | 仅自己提交的 | - |
|
||||
| 志愿委员 | 全班 | 仅加分,最多+5分 | 不可撤销 | 仅自己提交的 | 个人查询 |
|
||||
| 学生 | 自己 | 无 | 无 | 自己的历史 | 修改密码 |
|
||||
| 家长 | 子女总分 | 无 | 无 | 不可见详情 | - |
|
||||
|
||||
@@ -281,6 +288,9 @@ classmanager/
|
||||
| v2.7 | 2026.5.29 | 操作菜单定位修复、历史记录显示修复、筛选面板修复、科目删除修复、学期周数列修复、escapeHtml 转义修复 |
|
||||
| v2.8 | 2026.6.2 | 管理员软删除改为禁用/启用切换(保留admin_roles记录)、科目管理面板显示全部科目(禁用/启用均可见)、添加管理员支持重新激活已禁用账号、升级系统补全v2.8版本号 |
|
||||
| v2.9 | 2026.6.8 | 历史记录表头优化:合并/非合并视图统一新增"类型"列(手动/作业/考勤),列顺序统一为"类型、分值、原因、学生、操作人、时间" |
|
||||
| v3.0 | 2026.9.17 | 导出按学期隔离(默认当前学期,可选历史/全部,历史导出不再受1000条限制);新增管理端"个人查询"页面(基础分/加分/减分/月度分/月度理由汇总/明细,可导出,支持学生列表直达);加减分与考勤记录自动关联当前学期,历史记录页新增学期筛选 |
|
||||
| v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 |
|
||||
| v4.1 | 2026.9.17 | 管理员可绑定邮箱;新增找回密码(SMTP邮件重置链接,一次性、30分钟有效);登录页新增忘记密码入口,管理端支持添加/编辑管理员邮箱与自助绑定 |
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
+32
-1
@@ -99,7 +99,10 @@ LABOR_POINTS_ADD=1
|
||||
LABOR_POINTS_SUBTRACT=-1
|
||||
|
||||
# ===========================================
|
||||
# 各角色加减分限制配置
|
||||
# 加减分上限配置(v4.0 起废弃)
|
||||
#
|
||||
# 各权限组的加减分上限改为在系统内「管理员管理 → 权限组」中动态配置,
|
||||
# 以下环境变量不再生效,仅保留以兼容旧配置文件。
|
||||
# ===========================================
|
||||
|
||||
# 班长单次加分上限
|
||||
@@ -119,6 +122,34 @@ LABOR_REP_MAX_POINTS=1
|
||||
# 志愿委员单次加分上限
|
||||
VOLUNTEER_REP_MAX_POINTS=5
|
||||
|
||||
# ===========================================
|
||||
# 站点地址与 SMTP 邮件配置(管理员找回密码)
|
||||
# ===========================================
|
||||
|
||||
# 前端站点地址 - 用于生成密码重置链接(注意结尾不要带斜杠)
|
||||
FRONTEND_URL=https://class.example.com
|
||||
|
||||
# 是否启用邮件功能 - true/false
|
||||
SMTP_ENABLED=false
|
||||
# SMTP 服务器地址(如 smtp.qq.com / smtp.163.com / smtp.exmail.qq.com)
|
||||
SMTP_HOST=smtp.example.com
|
||||
# SMTP 端口:SSL 通常为 465,STARTTLS 通常为 587
|
||||
SMTP_PORT=465
|
||||
# SMTP 登录账号(一般为邮箱地址)
|
||||
SMTP_USER=no-reply@example.com
|
||||
# SMTP 登录密码/授权码
|
||||
SMTP_PASSWORD=your-smtp-password
|
||||
# 发件人邮箱(默认与 SMTP_USER 一致时可不填)
|
||||
SMTP_FROM=no-reply@example.com
|
||||
# 发件人显示名称
|
||||
SMTP_FROM_NAME=班级操行分管理系统
|
||||
# 是否使用 SSL 直连(465端口用 true,587端口用 false)
|
||||
SMTP_SSL=true
|
||||
# 是否使用 STARTTLS(587端口用 true)
|
||||
SMTP_STARTTLS=false
|
||||
# 密码重置链接有效期(分钟)
|
||||
PASSWORD_RESET_EXPIRE_MINUTES=30
|
||||
|
||||
# ===========================================
|
||||
# 日志配置
|
||||
# ===========================================
|
||||
|
||||
@@ -51,6 +51,21 @@ class Settings:
|
||||
DEBUG_ENABLED: bool = os.getenv("DEBUG_ENABLED", "False").lower() == "true"
|
||||
DEBUG_PATH: str = os.getenv("DEBUG_PATH", "/debug_add_admin")
|
||||
|
||||
# ========== 站点地址与邮件(找回密码) ==========
|
||||
# 前端站点地址,用于生成密码重置链接,如 https://class.example.com
|
||||
FRONTEND_URL: str = os.getenv("FRONTEND_URL", "").rstrip("/")
|
||||
SMTP_ENABLED: bool = os.getenv("SMTP_ENABLED", "False").lower() == "true"
|
||||
SMTP_HOST: str = os.getenv("SMTP_HOST", "")
|
||||
SMTP_PORT: int = int(os.getenv("SMTP_PORT", "465"))
|
||||
SMTP_USER: str = os.getenv("SMTP_USER", "")
|
||||
SMTP_PASSWORD: str = os.getenv("SMTP_PASSWORD", "")
|
||||
SMTP_FROM: str = os.getenv("SMTP_FROM", "")
|
||||
SMTP_FROM_NAME: str = os.getenv("SMTP_FROM_NAME", os.getenv("APP_NAME", "班级操行分管理系统"))
|
||||
SMTP_SSL: bool = os.getenv("SMTP_SSL", "True").lower() == "true"
|
||||
SMTP_STARTTLS: bool = os.getenv("SMTP_STARTTLS", "False").lower() == "true"
|
||||
# 密码重置链接有效期(分钟)
|
||||
PASSWORD_RESET_EXPIRE_MINUTES: int = int(os.getenv("PASSWORD_RESET_EXPIRE_MINUTES", "30"))
|
||||
|
||||
DEDUCTION_HOMEWORK_NOT_SUBMIT: int = int(os.getenv("DEDUCTION_HOMEWORK_NOT_SUBMIT", "2"))
|
||||
DEDUCTION_HOMEWORK_LATE: int = int(os.getenv("DEDUCTION_HOMEWORK_LATE", "1"))
|
||||
DEDUCTION_ATTENDANCE_ABSENT: int = int(os.getenv("DEDUCTION_ATTENDANCE_ABSENT", "3"))
|
||||
@@ -60,6 +75,8 @@ class Settings:
|
||||
LABOR_POINTS_ADD: int = int(os.getenv("LABOR_POINTS_ADD", "1"))
|
||||
LABOR_POINTS_SUBTRACT: int = int(os.getenv("LABOR_POINTS_SUBTRACT", "-1"))
|
||||
|
||||
# 以下加减分上限自 v4.0 起废弃:权限组上限存于数据库 permission_groups 表,
|
||||
# 通过「管理员管理 → 权限组」动态配置,保留字段仅为兼容旧 .env 文件。
|
||||
MONITOR_MAX_ADD: int = int(os.getenv("MONITOR_MAX_ADD", "5"))
|
||||
MONITOR_MAX_SUBTRACT: int = int(os.getenv("MONITOR_MAX_SUBTRACT", "-5"))
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ PUBLIC_PATHS = [
|
||||
r'^/$',
|
||||
r'^/health$',
|
||||
r'^/api/auth/login$',
|
||||
r'^/api/auth/forgot-password$',
|
||||
r'^/api/auth/reset-password$',
|
||||
r'^/api/auth/reset-token/check$',
|
||||
]
|
||||
def is_public_path(path: str) -> bool:
|
||||
"""检查是否为公开路径"""
|
||||
|
||||
@@ -10,13 +10,11 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import Request
|
||||
from typing import List, Optional, Callable, Dict, Any
|
||||
from functools import wraps
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from utils.response import forbidden_response
|
||||
from utils.database import execute_one
|
||||
from utils.logger import get_logger
|
||||
from models.admin_role import AdminRoleModel
|
||||
from models.permission_group import PermissionGroupModel
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -33,182 +31,73 @@ async def get_current_user(request: Request) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
async def get_current_user_id(request: Request) -> int:
|
||||
"""获取当前用户ID"""
|
||||
return getattr(request.state, 'user_id', None)
|
||||
|
||||
|
||||
class PermissionChecker:
|
||||
"""权限检查器"""
|
||||
"""权限检查器(基于自定义权限组)"""
|
||||
|
||||
@staticmethod
|
||||
async def get_user_group(user_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""获取用户绑定的权限组(含解析后的权限与上限)"""
|
||||
if not user_id:
|
||||
return None
|
||||
return await PermissionGroupModel.get_by_user_id(user_id)
|
||||
|
||||
@staticmethod
|
||||
async def get_user_role(user_id: int) -> Optional[str]:
|
||||
"""获取用户的管理员角色"""
|
||||
sql = "SELECT role_type FROM admin_roles WHERE user_id = %s LIMIT 1"
|
||||
result = await execute_one(sql, (user_id,))
|
||||
return result["role_type"] if result else None
|
||||
"""获取用户权限组名称(用于展示与操作日志)"""
|
||||
group = await PermissionChecker.get_user_group(user_id)
|
||||
if not group:
|
||||
return None
|
||||
return group.get("group_name") or group.get("role_type")
|
||||
|
||||
@staticmethod
|
||||
async def check_is_teacher(user_id: int) -> bool:
|
||||
"""检查是否为班主任"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role == "班主任"
|
||||
async def get_permissions(user_id: int) -> Dict[str, bool]:
|
||||
"""获取用户权限字典"""
|
||||
group = await PermissionChecker.get_user_group(user_id)
|
||||
if not group:
|
||||
return {}
|
||||
return group.get("permissions_data", {})
|
||||
|
||||
@staticmethod
|
||||
async def check_is_monitor(user_id: int) -> bool:
|
||||
"""检查是否为班长"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role == "班长"
|
||||
async def check_permission(user_id: int, permission: str) -> bool:
|
||||
"""检查用户是否拥有指定权限"""
|
||||
permissions = await PermissionChecker.get_permissions(user_id)
|
||||
return bool(permissions.get(permission))
|
||||
|
||||
@staticmethod
|
||||
async def check_is_study_commissioner(user_id: int) -> bool:
|
||||
"""检查是否为学习委员"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role == "学习委员"
|
||||
|
||||
@staticmethod
|
||||
async def check_is_attendance_rep(user_id: int) -> bool:
|
||||
"""检查是否为考勤委员"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role == "考勤委员"
|
||||
|
||||
@staticmethod
|
||||
async def check_is_labor_rep(user_id: int) -> bool:
|
||||
"""检查是否为劳动委员"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role == "劳动委员"
|
||||
|
||||
@staticmethod
|
||||
async def check_is_volunteer_rep(user_id: int) -> bool:
|
||||
"""检查是否为志愿委员"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role == "志愿委员"
|
||||
|
||||
@staticmethod
|
||||
async def check_can_manage_subjects(user_id: int) -> bool:
|
||||
"""检查是否可以管理科目(班主任或学习委员)"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role in ["班主任", "学习委员"]
|
||||
|
||||
@staticmethod
|
||||
async def get_user_class_id(user_id: int) -> Optional[int]:
|
||||
"""
|
||||
获取用户关联的班级ID
|
||||
单班级系统,固定返回1
|
||||
"""
|
||||
# 本系统为单班级设计,class_id 固定为 1
|
||||
return 1
|
||||
|
||||
@staticmethod
|
||||
async def get_user_subject_ids(user_id: int) -> List[int]:
|
||||
"""获取用户管理的科目ID列表"""
|
||||
admin_role = await AdminRoleModel.get_by_user_id(user_id)
|
||||
if not admin_role:
|
||||
return []
|
||||
# 班主任可以管理所有科目
|
||||
if admin_role["role_type"] == "班主任":
|
||||
from models.subject import SubjectModel
|
||||
subjects = await SubjectModel.get_all(is_active=True)
|
||||
return [s["subject_id"] for s in subjects]
|
||||
# 其他角色返回关联的科目
|
||||
if admin_role.get("subject_id"):
|
||||
return [admin_role["subject_id"]]
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
async def check_can_manage_student(user_id: int, student_id: int) -> bool:
|
||||
"""检查是否可以管理指定学生(管理员默认可管理所有学生)"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
return role is not None
|
||||
async def get_score_limits(user_id: int) -> Dict[str, Any]:
|
||||
"""获取用户加减分权限与动态上限"""
|
||||
group = await PermissionChecker.get_user_group(user_id)
|
||||
if not group:
|
||||
return {
|
||||
"can_manage_conduct": False,
|
||||
"can_add": False, "max_add": None,
|
||||
"can_subtract": False, "max_subtract": None
|
||||
}
|
||||
return {
|
||||
"can_manage_conduct": bool(group.get("permissions_data", {}).get("manage_conduct")),
|
||||
"can_add": bool(group.get("can_add_points")),
|
||||
"max_add": group.get("max_add_points"),
|
||||
"can_subtract": bool(group.get("can_subtract_points")),
|
||||
"max_subtract": group.get("max_subtract_points")
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def check_can_revoke(user_id: int, record_id: int) -> bool:
|
||||
"""
|
||||
检查是否可以撤销扣分记录
|
||||
班主任:可以撤销/反撤销任何记录
|
||||
班长:可以撤销/反撤销任何记录
|
||||
考勤委员:可以撤销自己创建的记录
|
||||
其他角色:无撤销权限
|
||||
"""
|
||||
"""检查是否可以撤销记录:撤销任何人 / 仅撤销自己提交的"""
|
||||
record = await execute_one(
|
||||
"SELECT record_id, recorder_id FROM conduct_records WHERE record_id = %s",
|
||||
(record_id,)
|
||||
)
|
||||
if not record:
|
||||
return False
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
if role in ["班主任", "班长"]:
|
||||
permissions = await PermissionChecker.get_permissions(user_id)
|
||||
if permissions.get("revoke_any"):
|
||||
return True
|
||||
if role == "考勤委员" and record.get("recorder_id") == user_id:
|
||||
if permissions.get("revoke_own") and record.get("recorder_id") == user_id:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def require_auth(func: Callable):
|
||||
"""需要认证的装饰器"""
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
request = kwargs.get('request')
|
||||
if not request or not hasattr(request.state, 'user_id'):
|
||||
return forbidden_response("请先登录")
|
||||
return await func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
def require_role(roles: List[str]):
|
||||
"""需要特定角色的装饰器"""
|
||||
def decorator(func: Callable):
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
request = kwargs.get('request')
|
||||
if not request or not hasattr(request.state, 'user_id'):
|
||||
return forbidden_response("请先登录")
|
||||
user_id = request.state.user_id
|
||||
user_role = await PermissionChecker.get_user_role(user_id)
|
||||
if user_role not in roles:
|
||||
return forbidden_response(f"需要{','.join(roles)}权限")
|
||||
return await func(*args, **kwargs)
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
def require_teacher(func: Callable):
|
||||
"""需要班主任权限的装饰器"""
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
request = kwargs.get('request')
|
||||
if not request or not hasattr(request.state, 'user_id'):
|
||||
return forbidden_response("请先登录")
|
||||
is_teacher = await PermissionChecker.check_is_teacher(request.state.user_id)
|
||||
if not is_teacher:
|
||||
return forbidden_response("需要班主任权限")
|
||||
return await func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
def require_monitor(func: Callable):
|
||||
"""需要班长权限的装饰器"""
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
request = kwargs.get('request')
|
||||
if not request or not hasattr(request.state, 'user_id'):
|
||||
return forbidden_response("请先登录")
|
||||
is_monitor = await PermissionChecker.check_is_monitor(request.state.user_id)
|
||||
if not is_monitor:
|
||||
return forbidden_response("需要班长权限")
|
||||
return await func(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
def require_study_commissioner(func: Callable):
|
||||
"""需要学习委员权限的装饰器"""
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
request = kwargs.get('request')
|
||||
if not request or not hasattr(request.state, 'user_id'):
|
||||
return forbidden_response("请先登录")
|
||||
is_study = await PermissionChecker.check_is_study_commissioner(request.state.user_id)
|
||||
if not is_study:
|
||||
return forbidden_response("需要学习委员权限")
|
||||
return await func(*args, **kwargs)
|
||||
return wrapper
|
||||
@staticmethod
|
||||
async def check_can_restore(user_id: int) -> bool:
|
||||
"""检查是否可以反撤销记录"""
|
||||
return await PermissionChecker.check_permission(user_id, "restore_records")
|
||||
@@ -14,14 +14,19 @@ from utils.database import execute_one, execute_query, execute_insert, execute_u
|
||||
|
||||
|
||||
class AdminRoleModel:
|
||||
"""管理员角色数据模型"""
|
||||
"""管理员角色数据模型(关联权限组)"""
|
||||
|
||||
@staticmethod
|
||||
async def get_by_user_id(user_id: int) -> Optional[Dict[str, Any]]:
|
||||
sql = """
|
||||
SELECT ar.*, s.subject_name
|
||||
SELECT ar.*, s.subject_name,
|
||||
pg.group_name, pg.description AS group_description, pg.permissions,
|
||||
pg.can_add_points, pg.max_add_points,
|
||||
pg.can_subtract_points, pg.max_subtract_points,
|
||||
pg.is_system, pg.is_locked
|
||||
FROM admin_roles ar
|
||||
LEFT JOIN subjects s ON ar.subject_id = s.subject_id
|
||||
LEFT JOIN permission_groups pg ON ar.group_id = pg.group_id
|
||||
WHERE ar.user_id = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
@@ -30,20 +35,30 @@ class AdminRoleModel:
|
||||
@staticmethod
|
||||
async def get_all() -> List[Dict[str, Any]]:
|
||||
sql = """
|
||||
SELECT ar.*, u.real_name, u.username, u.status, s.subject_name
|
||||
SELECT ar.*, u.real_name, u.username, u.email, u.status, s.subject_name,
|
||||
pg.group_name, pg.can_add_points, pg.max_add_points,
|
||||
pg.can_subtract_points, pg.max_subtract_points,
|
||||
pg.is_system, pg.is_locked
|
||||
FROM admin_roles ar
|
||||
JOIN users u ON ar.user_id = u.user_id
|
||||
LEFT JOIN subjects s ON ar.subject_id = s.subject_id
|
||||
ORDER BY ar.role_type
|
||||
LEFT JOIN permission_groups pg ON ar.group_id = pg.group_id
|
||||
ORDER BY COALESCE(pg.is_locked, 0) DESC, COALESCE(pg.is_system, 0) DESC, ar.user_id
|
||||
"""
|
||||
return await execute_query(sql)
|
||||
|
||||
@staticmethod
|
||||
async def create(user_id: int, role_type: str, subject_id: int = None) -> int:
|
||||
async def create(
|
||||
user_id: int,
|
||||
role_type: str,
|
||||
group_id: int = None,
|
||||
subject_id: int = None
|
||||
) -> int:
|
||||
sql = """
|
||||
INSERT INTO admin_roles (user_id, role_type, subject_id)
|
||||
VALUES (%s, %s, %s)
|
||||
INSERT INTO admin_roles (user_id, role_type, group_id, subject_id)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
"""
|
||||
return await execute_insert(sql, (user_id, role_type, subject_id))
|
||||
return await execute_insert(sql, (user_id, role_type, group_id, subject_id))
|
||||
|
||||
@staticmethod
|
||||
async def delete(user_id: int) -> bool:
|
||||
@@ -52,11 +67,16 @@ class AdminRoleModel:
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def update_role(user_id: int, role_type: str, subject_id: int = None) -> bool:
|
||||
async def update_role(
|
||||
user_id: int,
|
||||
role_type: str,
|
||||
group_id: int = None,
|
||||
subject_id: int = None
|
||||
) -> bool:
|
||||
sql = """
|
||||
UPDATE admin_roles
|
||||
SET role_type = %s, subject_id = %s
|
||||
SET role_type = %s, group_id = %s, subject_id = %s
|
||||
WHERE user_id = %s
|
||||
"""
|
||||
result = await execute_update(sql, (role_type, subject_id, user_id))
|
||||
result = await execute_update(sql, (role_type, group_id, subject_id, user_id))
|
||||
return result > 0
|
||||
@@ -71,7 +71,8 @@ class AttendanceModel:
|
||||
status: str,
|
||||
reason: str = None,
|
||||
recorder_id: int = None,
|
||||
slot: str = 'morning'
|
||||
slot: str = 'morning',
|
||||
semester_id: int = None
|
||||
) -> int:
|
||||
# 检查是否已存在当天同时段记录
|
||||
existing = await execute_one(
|
||||
@@ -83,18 +84,18 @@ class AttendanceModel:
|
||||
# 更新已有记录
|
||||
sql = """
|
||||
UPDATE attendance_records
|
||||
SET status = %s, reason = %s, recorder_id = %s
|
||||
SET status = %s, reason = %s, recorder_id = %s, semester_id = %s
|
||||
WHERE student_id = %s AND date = %s AND slot = %s
|
||||
"""
|
||||
await execute_update(sql, (status, reason, recorder_id, student_id, date, slot))
|
||||
await execute_update(sql, (status, reason, recorder_id, semester_id, student_id, date, slot))
|
||||
return existing["attendance_id"]
|
||||
else:
|
||||
# 插入新记录
|
||||
sql = """
|
||||
INSERT INTO attendance_records (student_id, date, slot, status, reason, recorder_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
INSERT INTO attendance_records (student_id, date, slot, status, reason, recorder_id, semester_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
return await execute_insert(sql, (student_id, date, slot, status, reason, recorder_id))
|
||||
return await execute_insert(sql, (student_id, date, slot, status, reason, recorder_id, semester_id))
|
||||
|
||||
@staticmethod
|
||||
async def mark_deduction_applied(attendance_id: int) -> bool:
|
||||
|
||||
+113
-16
@@ -17,6 +17,34 @@ from utils.logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def _append_semester_filter(
|
||||
sql: str,
|
||||
params: list,
|
||||
semester_id: Optional[int],
|
||||
semester_start_date: Optional[str],
|
||||
semester_end_date: Optional[str],
|
||||
column: str = "cr"
|
||||
) -> tuple:
|
||||
"""追加学期过滤条件
|
||||
|
||||
优先使用 semester_id 精确过滤;对未关联学期的历史记录(semester_id 为空),
|
||||
使用学期日期范围兜底,与归档统计口径保持一致。
|
||||
"""
|
||||
if not semester_id:
|
||||
return sql, params
|
||||
col = f"{column}." if column else ""
|
||||
if semester_start_date and semester_end_date:
|
||||
sql += (
|
||||
f" AND ({col}semester_id = %s OR "
|
||||
f"({col}semester_id IS NULL AND DATE({col}created_at) BETWEEN %s AND %s))"
|
||||
)
|
||||
params.extend([semester_id, semester_start_date, semester_end_date])
|
||||
else:
|
||||
sql += f" AND {col}semester_id = %s"
|
||||
params.append(semester_id)
|
||||
return sql, params
|
||||
|
||||
|
||||
class ConductModel:
|
||||
"""操行分数据模型"""
|
||||
|
||||
@@ -28,16 +56,18 @@ class ConductModel:
|
||||
recorder_id: int,
|
||||
recorder_name: str = None,
|
||||
related_type: str = 'manual',
|
||||
related_id: int = None
|
||||
related_id: int = None,
|
||||
semester_id: int = None
|
||||
) -> int:
|
||||
"""创建操行分记录"""
|
||||
sql = """
|
||||
INSERT INTO conduct_records
|
||||
(student_id, points_change, reason, recorder_id, recorder_name, related_type, related_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
(student_id, points_change, reason, recorder_id, recorder_name, related_type, related_id, semester_id)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
return await execute_insert(sql, (
|
||||
student_id, points_change, reason, recorder_id, recorder_name, related_type, related_id
|
||||
student_id, points_change, reason, recorder_id, recorder_name,
|
||||
related_type, related_id, semester_id
|
||||
))
|
||||
|
||||
@staticmethod
|
||||
@@ -46,7 +76,10 @@ class ConductModel:
|
||||
include_revoked: bool = False,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
recorder_id: int = None
|
||||
recorder_id: int = None,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None
|
||||
) -> int:
|
||||
"""统计学生操行分记录总数"""
|
||||
conditions = ["student_id = %s"]
|
||||
@@ -62,7 +95,10 @@ class ConductModel:
|
||||
if recorder_id:
|
||||
conditions.append("recorder_id = %s")
|
||||
params.append(recorder_id)
|
||||
where = " AND ".join(conditions)
|
||||
where, params = _append_semester_filter(
|
||||
" AND ".join(conditions), params,
|
||||
semester_id, semester_start_date, semester_end_date, column=""
|
||||
)
|
||||
sql = f"SELECT COUNT(*) as total FROM conduct_records WHERE {where}"
|
||||
result = await execute_one(sql, tuple(params))
|
||||
return result["total"] if result else 0
|
||||
@@ -71,7 +107,10 @@ class ConductModel:
|
||||
async def count_records_by_recorder(
|
||||
recorder_id: int,
|
||||
start_date: str = None,
|
||||
end_date: str = None
|
||||
end_date: str = None,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None
|
||||
) -> int:
|
||||
"""统计记录人提交的操行分记录总数"""
|
||||
conditions = ["recorder_id = %s"]
|
||||
@@ -82,7 +121,10 @@ class ConductModel:
|
||||
if end_date:
|
||||
conditions.append("DATE(created_at) <= %s")
|
||||
params.append(end_date)
|
||||
where = " AND ".join(conditions)
|
||||
where, params = _append_semester_filter(
|
||||
" AND ".join(conditions), params,
|
||||
semester_id, semester_start_date, semester_end_date, column=""
|
||||
)
|
||||
sql = f"SELECT COUNT(*) as total FROM conduct_records WHERE {where}"
|
||||
result = await execute_one(sql, tuple(params))
|
||||
return result["total"] if result else 0
|
||||
@@ -95,7 +137,10 @@ class ConductModel:
|
||||
include_revoked: bool = False,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
recorder_id: int = None
|
||||
recorder_id: int = None,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""获取学生操行分记录"""
|
||||
conditions = ["cr.student_id = %s"]
|
||||
@@ -111,7 +156,10 @@ class ConductModel:
|
||||
if recorder_id:
|
||||
conditions.append("cr.recorder_id = %s")
|
||||
params.append(recorder_id)
|
||||
where = " AND ".join(conditions)
|
||||
where, params = _append_semester_filter(
|
||||
" AND ".join(conditions), params,
|
||||
semester_id, semester_start_date, semester_end_date
|
||||
)
|
||||
sql = f"""
|
||||
SELECT cr.*, u.real_name as recorder_name
|
||||
FROM conduct_records cr
|
||||
@@ -129,7 +177,10 @@ class ConductModel:
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
start_date: str = None,
|
||||
end_date: str = None
|
||||
end_date: str = None,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""获取操作人提交的记录"""
|
||||
conditions = ["cr.recorder_id = %s", "cr.is_revoked = 0"]
|
||||
@@ -140,7 +191,10 @@ class ConductModel:
|
||||
if end_date:
|
||||
conditions.append("DATE(cr.created_at) <= %s")
|
||||
params.append(end_date)
|
||||
where = " AND ".join(conditions)
|
||||
where, params = _append_semester_filter(
|
||||
" AND ".join(conditions), params,
|
||||
semester_id, semester_start_date, semester_end_date
|
||||
)
|
||||
sql = f"""
|
||||
SELECT cr.*, s.name as student_name
|
||||
FROM conduct_records cr
|
||||
@@ -152,7 +206,6 @@ class ConductModel:
|
||||
params.extend([limit, offset])
|
||||
return await execute_query(sql, tuple(params))
|
||||
|
||||
@staticmethod
|
||||
@staticmethod
|
||||
async def get_all_records(
|
||||
limit: int = 100,
|
||||
@@ -164,7 +217,10 @@ class ConductModel:
|
||||
related_type: str = None,
|
||||
reason_prefix: str = None,
|
||||
is_revoked: int = None,
|
||||
reason_search: str = None
|
||||
reason_search: str = None,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""获取所有记录(班主任/班长专用)"""
|
||||
# 空字符串转为None
|
||||
@@ -180,11 +236,12 @@ class ConductModel:
|
||||
reason_search = None
|
||||
sql = """
|
||||
SELECT cr.*, s.name as student_name, s.student_no, u.real_name as recorder_name,
|
||||
ru.real_name as revoker_name
|
||||
ru.real_name as revoker_name, sem.semester_name
|
||||
FROM conduct_records cr
|
||||
JOIN students s ON cr.student_id = s.student_id
|
||||
JOIN users u ON cr.recorder_id = u.user_id
|
||||
LEFT JOIN users ru ON cr.revoked_by = ru.user_id
|
||||
LEFT JOIN semesters sem ON cr.semester_id = sem.semester_id
|
||||
WHERE 1=1
|
||||
"""
|
||||
if not include_revoked:
|
||||
@@ -219,11 +276,45 @@ class ConductModel:
|
||||
sql += " AND cr.is_revoked = %s"
|
||||
params.append(1 if is_revoked else 0)
|
||||
|
||||
sql, params = _append_semester_filter(
|
||||
sql, params, semester_id, semester_start_date, semester_end_date
|
||||
)
|
||||
|
||||
sql += " ORDER BY cr.created_at DESC LIMIT %s OFFSET %s"
|
||||
params.extend([limit, offset])
|
||||
|
||||
return await execute_query(sql, tuple(params))
|
||||
|
||||
@staticmethod
|
||||
async def get_student_monthly_stats(
|
||||
student_id: int,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None,
|
||||
recorder_id: int = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""按月份+原因统计学生加减分(仅统计未撤销记录)"""
|
||||
conditions = ["cr.student_id = %s", "cr.is_revoked = 0"]
|
||||
params: List[Any] = [student_id]
|
||||
if recorder_id:
|
||||
conditions.append("cr.recorder_id = %s")
|
||||
params.append(recorder_id)
|
||||
where_clause, params = _append_semester_filter(
|
||||
" AND ".join(conditions), params,
|
||||
semester_id, semester_start_date, semester_end_date
|
||||
)
|
||||
sql = f"""
|
||||
SELECT DATE_FORMAT(cr.created_at, '%%Y-%%m') AS month,
|
||||
cr.reason AS reason,
|
||||
cr.points_change AS points_change,
|
||||
COUNT(*) AS cnt
|
||||
FROM conduct_records cr
|
||||
WHERE {where_clause}
|
||||
GROUP BY month, cr.reason, cr.points_change
|
||||
ORDER BY month ASC, cr.points_change DESC, cnt DESC
|
||||
"""
|
||||
return await execute_query(sql, tuple(params))
|
||||
|
||||
@staticmethod
|
||||
async def get_grouped_records(
|
||||
student_id: int = None,
|
||||
@@ -234,7 +325,10 @@ class ConductModel:
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
is_revoked: int = None,
|
||||
reason_search: str = None
|
||||
reason_search: str = None,
|
||||
semester_id: int = None,
|
||||
semester_start_date: str = None,
|
||||
semester_end_date: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""获取分组后的操行分记录(同批次合并)"""
|
||||
if start_date == "":
|
||||
@@ -277,6 +371,9 @@ class ConductModel:
|
||||
params.append(f"%{reason_search}%")
|
||||
|
||||
where_clause = " AND ".join(conditions)
|
||||
where_clause, params = _append_semester_filter(
|
||||
where_clause, params, semester_id, semester_start_date, semester_end_date
|
||||
)
|
||||
|
||||
count_sql = f"""
|
||||
SELECT COUNT(DISTINCT CONCAT(cr.points_change, '|', cr.reason, '|', cr.recorder_id, '|', DATE_FORMAT(cr.created_at, '%%Y-%%m-%%d %%H:%%i:%%s'))) as total
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 权限组数据模型
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
import json
|
||||
from typing import Optional, Dict, Any, List
|
||||
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 全部可配置权限项(新增权限项时在此登记,不存在的项默认 False)
|
||||
PERMISSION_KEYS = [
|
||||
"manage_students", # 学生管理:新增/编辑/删除/导入/重置密码
|
||||
"export_students", # 导出学生名单
|
||||
"manage_conduct", # 操行分加减分
|
||||
"revoke_any", # 撤销任何人的记录
|
||||
"revoke_own", # 仅撤销自己提交的记录
|
||||
"restore_records", # 反撤销记录
|
||||
"manage_homework", # 作业扣分
|
||||
"manage_attendance", # 考勤管理
|
||||
"manage_subjects", # 科目管理
|
||||
"manage_admins", # 管理员与权限组管理
|
||||
"manage_semesters", # 学期管理
|
||||
"view_all_records", # 查看全班记录/个人查询
|
||||
"export_data", # 导出德育分记录/历史记录
|
||||
"manage_upgrade", # 系统升级
|
||||
]
|
||||
|
||||
|
||||
class PermissionGroupModel:
|
||||
"""权限组数据模型"""
|
||||
|
||||
@staticmethod
|
||||
def parse_group(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""解析权限组数据(JSON字符串 -> 布尔字典)"""
|
||||
if not row:
|
||||
return row
|
||||
raw = row.get("permissions")
|
||||
parsed: Dict[str, Any] = {}
|
||||
if isinstance(raw, dict):
|
||||
parsed = raw
|
||||
elif isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except (ValueError, TypeError):
|
||||
logger.warning(f"权限组[{row.get('group_id')}]权限配置解析失败")
|
||||
parsed = {}
|
||||
row["permissions_data"] = {key: bool(parsed.get(key, False)) for key in PERMISSION_KEYS}
|
||||
row["can_add_points"] = bool(row.get("can_add_points"))
|
||||
row["can_subtract_points"] = bool(row.get("can_subtract_points"))
|
||||
return row
|
||||
|
||||
@staticmethod
|
||||
async def get_by_id(group_id: int) -> Optional[Dict[str, Any]]:
|
||||
result = await execute_one("SELECT * FROM permission_groups WHERE group_id = %s", (group_id,))
|
||||
return PermissionGroupModel.parse_group(result)
|
||||
|
||||
@staticmethod
|
||||
async def get_by_name(group_name: str) -> Optional[Dict[str, Any]]:
|
||||
result = await execute_one(
|
||||
"SELECT * FROM permission_groups WHERE group_name = %s LIMIT 1", (group_name,)
|
||||
)
|
||||
return PermissionGroupModel.parse_group(result)
|
||||
|
||||
@staticmethod
|
||||
async def get_all() -> List[Dict[str, Any]]:
|
||||
rows = await execute_query(
|
||||
"""
|
||||
SELECT pg.*, (SELECT COUNT(*) FROM admin_roles ar WHERE ar.group_id = pg.group_id) AS member_count
|
||||
FROM permission_groups pg
|
||||
ORDER BY pg.is_locked DESC, pg.is_system DESC, pg.group_id ASC
|
||||
"""
|
||||
)
|
||||
return [PermissionGroupModel.parse_group(row) for row in rows]
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
group_name: str,
|
||||
description: str,
|
||||
permissions: Dict[str, bool],
|
||||
can_add_points: bool,
|
||||
max_add_points: Optional[int],
|
||||
can_subtract_points: bool,
|
||||
max_subtract_points: Optional[int]
|
||||
) -> int:
|
||||
sql = """
|
||||
INSERT INTO permission_groups
|
||||
(group_name, description, permissions, can_add_points, max_add_points,
|
||||
can_subtract_points, max_subtract_points, is_system, is_locked)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 0, 0)
|
||||
"""
|
||||
return await execute_insert(sql, (
|
||||
group_name, description or None, json.dumps(permissions, ensure_ascii=False),
|
||||
1 if can_add_points else 0, max_add_points,
|
||||
1 if can_subtract_points else 0, max_subtract_points
|
||||
))
|
||||
|
||||
@staticmethod
|
||||
async def update(
|
||||
group_id: int,
|
||||
group_name: str,
|
||||
description: str,
|
||||
permissions: Dict[str, bool],
|
||||
can_add_points: bool,
|
||||
max_add_points: Optional[int],
|
||||
can_subtract_points: bool,
|
||||
max_subtract_points: Optional[int]
|
||||
) -> bool:
|
||||
sql = """
|
||||
UPDATE permission_groups
|
||||
SET group_name = %s, description = %s, permissions = %s,
|
||||
can_add_points = %s, max_add_points = %s,
|
||||
can_subtract_points = %s, max_subtract_points = %s
|
||||
WHERE group_id = %s AND is_locked = 0
|
||||
"""
|
||||
result = await execute_update(sql, (
|
||||
group_name, description or None, json.dumps(permissions, ensure_ascii=False),
|
||||
1 if can_add_points else 0, max_add_points,
|
||||
1 if can_subtract_points else 0, max_subtract_points,
|
||||
group_id
|
||||
))
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def delete(group_id: int) -> bool:
|
||||
result = await execute_update(
|
||||
"DELETE FROM permission_groups WHERE group_id = %s AND is_system = 0 AND is_locked = 0",
|
||||
(group_id,)
|
||||
)
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def count_members(group_id: int) -> int:
|
||||
result = await execute_one(
|
||||
"SELECT COUNT(*) AS cnt FROM admin_roles WHERE group_id = %s", (group_id,)
|
||||
)
|
||||
return result["cnt"] if result else 0
|
||||
|
||||
@staticmethod
|
||||
async def get_by_user_id(user_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""获取用户绑定权限组(兼容仅有 role_type 的旧数据)"""
|
||||
sql = """
|
||||
SELECT ar.role_type,
|
||||
pg.group_id, pg.group_name, pg.description, pg.permissions,
|
||||
pg.can_add_points, pg.max_add_points,
|
||||
pg.can_subtract_points, pg.max_subtract_points,
|
||||
pg.is_system, pg.is_locked
|
||||
FROM admin_roles ar
|
||||
LEFT JOIN permission_groups pg ON ar.group_id = pg.group_id
|
||||
WHERE ar.user_id = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
row = await execute_one(sql, (user_id,))
|
||||
if not row:
|
||||
return None
|
||||
if not row.get("group_id") and row.get("role_type"):
|
||||
legacy = await PermissionGroupModel.get_by_name(row["role_type"])
|
||||
if legacy:
|
||||
legacy["role_type"] = legacy.get("group_name")
|
||||
return legacy
|
||||
return PermissionGroupModel.parse_group(row)
|
||||
+15
-8
@@ -1,4 +1,4 @@
|
||||
# ===========================================
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
@@ -23,7 +23,7 @@ class UserModel:
|
||||
async def get_by_username(username: str) -> dict:
|
||||
"""根据用户名获取用户"""
|
||||
sql = """
|
||||
SELECT user_id, username, password_hash, real_name, user_type,
|
||||
SELECT user_id, username, password_hash, real_name, email, user_type,
|
||||
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||
FROM users
|
||||
WHERE username = %s AND status = 1
|
||||
@@ -34,7 +34,7 @@ class UserModel:
|
||||
async def get_by_user_id(user_id: int) -> dict:
|
||||
"""根据用户ID获取用户"""
|
||||
sql = """
|
||||
SELECT user_id, username, password_hash, real_name, user_type, student_id,
|
||||
SELECT user_id, username, password_hash, real_name, email, user_type, student_id,
|
||||
need_change_password, status
|
||||
FROM users
|
||||
WHERE user_id = %s
|
||||
@@ -62,14 +62,14 @@ class UserModel:
|
||||
return await execute_insert(sql, (username, password_hash, real_name, student_id))
|
||||
|
||||
@staticmethod
|
||||
async def create_admin(username: str, password: str, real_name: str) -> int:
|
||||
async def create_admin(username: str, password: str, real_name: str, email: str = None) -> int:
|
||||
"""创建管理员账号"""
|
||||
password_hash = security.bcrypt_password(password)
|
||||
sql = """
|
||||
INSERT INTO users (username, password_hash, real_name, user_type, need_change_password)
|
||||
VALUES (%s, %s, %s, 'admin', 1)
|
||||
INSERT INTO users (username, password_hash, real_name, email, user_type, need_change_password)
|
||||
VALUES (%s, %s, %s, %s, 'admin', 1)
|
||||
"""
|
||||
return await execute_insert(sql, (username, password_hash, real_name))
|
||||
return await execute_insert(sql, (username, password_hash, real_name, email))
|
||||
|
||||
@staticmethod
|
||||
async def update_password(user_id: int, new_password: str) -> bool:
|
||||
@@ -97,7 +97,7 @@ class UserModel:
|
||||
async def get_by_username_any(username: str) -> dict:
|
||||
"""根据用户名获取用户(含已禁用)"""
|
||||
sql = """
|
||||
SELECT user_id, username, password_hash, real_name, user_type,
|
||||
SELECT user_id, username, password_hash, real_name, email, user_type,
|
||||
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||
FROM users
|
||||
WHERE username = %s
|
||||
@@ -124,3 +124,10 @@ class UserModel:
|
||||
sql = "UPDATE users SET real_name = %s WHERE user_id = %s"
|
||||
result = await execute_update(sql, (real_name, user_id))
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def update_email(user_id: int, email: str) -> bool:
|
||||
"""更新用户绑定邮箱(传空字符串解除绑定)"""
|
||||
sql = "UPDATE users SET email = %s WHERE user_id = %s"
|
||||
result = await execute_update(sql, (email or None, user_id))
|
||||
return result > 0
|
||||
+203
-90
@@ -15,7 +15,6 @@ import json
|
||||
|
||||
from middleware.permission import (
|
||||
get_current_user,
|
||||
require_teacher,
|
||||
PermissionChecker
|
||||
)
|
||||
from services.admin_service import AdminService
|
||||
@@ -28,7 +27,7 @@ from schemas.admin import (
|
||||
AddStudentRequest, UpdateStudentRequest,
|
||||
AddAttendanceRequest,
|
||||
UpdateAdminRequest, DeleteAdminRequest, ResetPasswordRequest,
|
||||
UnlockUserRequest
|
||||
UnlockUserRequest, PermissionGroupRequest
|
||||
)
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
@@ -70,11 +69,10 @@ async def get_students(
|
||||
|
||||
@router.post("/students/import")
|
||||
async def import_students(request: Request, file: UploadFile = File(...)):
|
||||
"""批量导入学生(JSON格式),初始操行分默认为60分"""
|
||||
"""批量导入学生(JSON格式),初始操行分取系统配置 STUDENT_INITIAL_POINTS"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可导入学生", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_students"):
|
||||
return error_response(message="无学生管理权限", code=403)
|
||||
|
||||
content = await file.read()
|
||||
file_size = len(content)
|
||||
@@ -100,11 +98,11 @@ async def import_students(request: Request, file: UploadFile = File(...)):
|
||||
result = await AdminService.import_students(
|
||||
students=students,
|
||||
operator_id=user["user_id"],
|
||||
initial_points=60
|
||||
initial_points=settings.STUDENT_INITIAL_POINTS
|
||||
)
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="import_students",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="import_students",
|
||||
target_type="student",
|
||||
details=f"批量导入: 成功{result['success_count']}人, 失败{result['failed_count']}人",
|
||||
ip=request.client.host
|
||||
@@ -116,22 +114,21 @@ async def import_students(request: Request, file: UploadFile = File(...)):
|
||||
async def add_student(request: Request, req: AddStudentRequest):
|
||||
"""新增学生"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可新增学生", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_students"):
|
||||
return error_response(message="无学生管理权限", code=403)
|
||||
|
||||
result = await AdminService.add_student(
|
||||
student_no=req.student_no,
|
||||
name=req.name,
|
||||
parent_phone=req.parent_phone,
|
||||
operator_id=user["user_id"],
|
||||
initial_points=60,
|
||||
initial_points=settings.STUDENT_INITIAL_POINTS,
|
||||
dormitory_number=req.dormitory_number
|
||||
)
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="add_student",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="add_student",
|
||||
target_type="student", target_id=result.get("student_id"),
|
||||
details=f"新增学生: {req.name}({req.student_no})",
|
||||
ip=request.client.host
|
||||
@@ -143,11 +140,10 @@ async def add_student(request: Request, req: AddStudentRequest):
|
||||
|
||||
@router.put("/students/{student_id}")
|
||||
async def update_student(request: Request, student_id: int, req: UpdateStudentRequest):
|
||||
"""编辑学生信息(班主任)"""
|
||||
"""编辑学生信息"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可编辑学生信息", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_students"):
|
||||
return error_response(message="无学生管理权限", code=403)
|
||||
|
||||
result = await AdminService.update_student(
|
||||
student_id=student_id,
|
||||
@@ -158,7 +154,7 @@ async def update_student(request: Request, student_id: int, req: UpdateStudentRe
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="update_student",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="update_student",
|
||||
target_type="student", target_id=student_id,
|
||||
details=f"编辑学生ID: {student_id}",
|
||||
ip=request.client.host
|
||||
@@ -170,17 +166,16 @@ async def update_student(request: Request, student_id: int, req: UpdateStudentRe
|
||||
|
||||
@router.delete("/students/{student_id}")
|
||||
async def delete_student(request: Request, student_id: int):
|
||||
"""删除学生(班主任)"""
|
||||
"""删除学生"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可删除学生", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_students"):
|
||||
return error_response(message="无学生管理权限", code=403)
|
||||
|
||||
result = await AdminService.delete_student(student_id=student_id)
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="delete_student",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="delete_student",
|
||||
target_type="student", target_id=student_id,
|
||||
details=f"删除学生ID: {student_id}",
|
||||
ip=request.client.host
|
||||
@@ -192,11 +187,10 @@ async def delete_student(request: Request, student_id: int):
|
||||
|
||||
@router.post("/students/reset-password/{student_id}")
|
||||
async def reset_student_password(request: Request, student_id: int, req: ResetPasswordRequest):
|
||||
"""重置学生密码(班主任)"""
|
||||
"""重置学生密码"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可重置学生密码", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_students"):
|
||||
return error_response(message="无学生管理权限", code=403)
|
||||
|
||||
result = await AdminService.reset_student_password(
|
||||
student_id=student_id,
|
||||
@@ -205,7 +199,7 @@ async def reset_student_password(request: Request, student_id: int, req: ResetPa
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="reset_student_password",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="reset_student_password",
|
||||
target_type="student", target_id=student_id,
|
||||
details=f"重置学生密码, 学生ID: {student_id}",
|
||||
ip=request.client.host
|
||||
@@ -295,7 +289,7 @@ async def restore_conduct_record(request: Request, req: RevokeRequest):
|
||||
record = result.get("record", {})
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="restore_record",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="restore_record",
|
||||
target_type="conduct", target_id=req.record_id,
|
||||
details=(
|
||||
f"反撤销记录ID: {req.record_id}, "
|
||||
@@ -322,7 +316,8 @@ async def get_conduct_history(
|
||||
related_type: Optional[str] = None,
|
||||
reason_prefix: Optional[str] = None,
|
||||
is_revoked: Optional[int] = None,
|
||||
reason_search: Optional[str] = None
|
||||
reason_search: Optional[str] = None,
|
||||
semester_id: Optional[int] = None
|
||||
):
|
||||
"""获取操行分历史记录"""
|
||||
try:
|
||||
@@ -340,7 +335,8 @@ async def get_conduct_history(
|
||||
related_type=related_type,
|
||||
reason_prefix=reason_prefix,
|
||||
is_revoked=is_revoked,
|
||||
reason_search=reason_search
|
||||
reason_search=reason_search,
|
||||
semester_id=semester_id
|
||||
)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
@@ -348,6 +344,30 @@ async def get_conduct_history(
|
||||
return error_response(message=f"获取历史记录失败: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/conduct/student-summary")
|
||||
async def get_student_conduct_summary(
|
||||
request: Request,
|
||||
student_id: int = Query(..., ge=1),
|
||||
semester_id: Optional[int] = None
|
||||
):
|
||||
"""获取学生个人操行分汇总(基础分/加分/减分/月度分/月度理由汇总)"""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可查看学生操行分汇总", code=403)
|
||||
result = await ConductService.get_student_summary(
|
||||
user_id=user["user_id"],
|
||||
student_id=student_id,
|
||||
semester_id=semester_id
|
||||
)
|
||||
if not result.get("success"):
|
||||
return error_response(message=result.get("message", "获取汇总失败"), code=403)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"获取学生操行分汇总失败: {e}", exc_info=True)
|
||||
return error_response(message=f"获取学生操行分汇总失败: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/conduct/batch-revoke")
|
||||
async def batch_revoke_conduct_records(request: Request):
|
||||
"""批量撤销操行分记录"""
|
||||
@@ -433,11 +453,11 @@ async def batch_restore_conduct_records(request: Request):
|
||||
|
||||
@router.post("/attendance")
|
||||
async def add_attendance(request: Request, req: AddAttendanceRequest):
|
||||
"""添加考勤记录(考勤委员)"""
|
||||
"""添加考勤记录"""
|
||||
user = await get_current_user(request)
|
||||
role = await PermissionChecker.get_user_role(user["user_id"])
|
||||
if role not in ["班主任", "考勤委员"]:
|
||||
return error_response(message="无权进行此操作", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_attendance"):
|
||||
return error_response(message="无考勤管理权限", code=403)
|
||||
role = await PermissionChecker.get_user_role(user["user_id"]) or "管理员"
|
||||
result = await AttendanceService.add_attendance(
|
||||
student_id=req.student_id,
|
||||
date=str(req.date),
|
||||
@@ -470,9 +490,8 @@ async def get_attendance_records(
|
||||
):
|
||||
"""获取考勤记录"""
|
||||
user = await get_current_user(request)
|
||||
role = await PermissionChecker.get_user_role(user["user_id"])
|
||||
if role not in ["班主任", "考勤委员"]:
|
||||
return error_response(message="无权查看考勤记录", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_attendance"):
|
||||
return error_response(message="无考勤管理权限", code=403)
|
||||
result = await AttendanceService.get_records(
|
||||
user_id=user["user_id"],
|
||||
date=date,
|
||||
@@ -486,28 +505,26 @@ async def get_attendance_records(
|
||||
|
||||
@router.post("/add")
|
||||
async def add_admin(request: Request, req: AddAdminRequest):
|
||||
"""添加管理员(班主任)"""
|
||||
"""添加管理员"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可添加管理员", code=403)
|
||||
if req.role_type not in ["班长", "学习委员", "考勤委员", "劳动委员", "志愿委员"]:
|
||||
return error_response(message="无效的角色类型", code=400)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
result = await AdminService.add_admin(
|
||||
username=req.username,
|
||||
real_name=req.real_name,
|
||||
password=req.password,
|
||||
role_type=req.role_type,
|
||||
operator_id=user["user_id"]
|
||||
group_id=req.group_id,
|
||||
operator_id=user["user_id"],
|
||||
email=req.email
|
||||
)
|
||||
if result["success"]:
|
||||
is_reactivation = result.get("password") is None
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任",
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="reactivate_admin" if is_reactivation else "add_admin",
|
||||
target_type="admin",
|
||||
details=f"{'重新激活' if is_reactivation else '新增'}管理员: {req.real_name}({req.username}), 角色: {req.role_type}",
|
||||
details=f"{'重新激活' if is_reactivation else '新增'}管理员: {req.real_name}({req.username}), 权限组: {result.get('role_type')}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(data=result, message="管理员添加成功")
|
||||
@@ -517,12 +534,11 @@ async def add_admin(request: Request, req: AddAdminRequest):
|
||||
|
||||
@router.get("/list")
|
||||
async def get_admins(request: Request):
|
||||
"""获取管理员列表(班主任)"""
|
||||
"""获取管理员列表"""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可查看管理员列表", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
result = await AdminService.get_admins()
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
@@ -530,49 +546,141 @@ async def get_admins(request: Request):
|
||||
return error_response(message=f"获取管理员列表失败: {str(e)}")
|
||||
|
||||
|
||||
@router.put("/update/{user_id}")
|
||||
async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
||||
"""更新管理员信息(班主任)"""
|
||||
@router.get("/permission-groups")
|
||||
async def get_permission_groups(request: Request):
|
||||
"""获取权限组列表"""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可更新管理员", code=403)
|
||||
if req.role_type not in ["班长", "学习委员", "考勤委员", "劳动委员", "志愿委员"]:
|
||||
return error_response(message="无效的角色类型", code=400)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
result = await AdminService.get_permission_groups()
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"获取权限组列表失败: {e}", exc_info=True)
|
||||
return error_response(message=f"获取权限组列表失败: {str(e)}")
|
||||
|
||||
from models.admin_role import AdminRoleModel
|
||||
from models.user import UserModel
|
||||
|
||||
# 更新角色
|
||||
result = await AdminRoleModel.update_role(
|
||||
user_id=user_id,
|
||||
role_type=req.role_type
|
||||
@router.post("/permission-groups")
|
||||
async def create_permission_group(request: Request, req: PermissionGroupRequest):
|
||||
"""新建权限组"""
|
||||
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 AdminService.create_permission_group(
|
||||
group_name=req.group_name,
|
||||
description=req.description,
|
||||
permissions={key: True for key in req.permissions},
|
||||
can_add_points=req.can_add_points,
|
||||
max_add_points=req.max_add_points,
|
||||
can_subtract_points=req.can_subtract_points,
|
||||
max_subtract_points=req.max_subtract_points,
|
||||
operator_id=user["user_id"]
|
||||
)
|
||||
|
||||
# 更新姓名
|
||||
if req.real_name:
|
||||
await UserModel.update_real_name(user_id, req.real_name)
|
||||
|
||||
if result:
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="update_admin",
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="create_permission_group",
|
||||
target_type="permission_group", target_id=result.get("group_id"),
|
||||
details=f"新建权限组: {req.group_name}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(data=result, message="权限组创建成功")
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.put("/permission-groups/{group_id}")
|
||||
async def update_permission_group(request: Request, group_id: int, req: PermissionGroupRequest):
|
||||
"""编辑权限组"""
|
||||
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 AdminService.update_permission_group(
|
||||
group_id=group_id,
|
||||
group_name=req.group_name,
|
||||
description=req.description,
|
||||
permissions={key: True for key in req.permissions},
|
||||
can_add_points=req.can_add_points,
|
||||
max_add_points=req.max_add_points,
|
||||
can_subtract_points=req.can_subtract_points,
|
||||
max_subtract_points=req.max_subtract_points,
|
||||
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_permission_group",
|
||||
target_type="permission_group", target_id=group_id,
|
||||
details=f"编辑权限组: {req.group_name}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message="权限组更新成功")
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.delete("/permission-groups/{group_id}")
|
||||
async def delete_permission_group(request: Request, group_id: int):
|
||||
"""删除权限组"""
|
||||
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 AdminService.delete_permission_group(
|
||||
group_id=group_id,
|
||||
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="delete_permission_group",
|
||||
target_type="permission_group", target_id=group_id,
|
||||
details=f"删除权限组 ID: {group_id}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message="权限组已删除")
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.put("/update/{user_id}")
|
||||
async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
||||
"""更新管理员信息"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
if user_id == user["user_id"]:
|
||||
return error_response(message="不能修改当前登录管理员的权限组", code=400)
|
||||
|
||||
result = await AdminService.update_admin(
|
||||
user_id=user_id,
|
||||
real_name=req.real_name,
|
||||
group_id=req.group_id,
|
||||
operator_id=user["user_id"],
|
||||
email=req.email
|
||||
)
|
||||
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_admin",
|
||||
target_type="admin", target_id=user_id,
|
||||
details=f"更新管理员角色为: {req.role_type}, 姓名: {req.real_name}",
|
||||
details=f"更新管理员姓名: {req.real_name}, 权限组ID: {req.group_id}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message="管理员更新成功")
|
||||
else:
|
||||
return error_response(message="更新失败或管理员不存在")
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.put("/toggle-status/{user_id}")
|
||||
async def toggle_admin_status(request: Request, user_id: int):
|
||||
"""启用/禁用管理员(班主任),保留角色记录"""
|
||||
"""启用/禁用管理员,保留角色记录"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可操作", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
|
||||
# 防止禁用自己
|
||||
if user_id == user["user_id"]:
|
||||
@@ -597,7 +705,8 @@ async def toggle_admin_status(request: Request, user_id: int):
|
||||
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="toggle_admin_status",
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="toggle_admin_status",
|
||||
target_type="admin", target_id=user_id,
|
||||
details=f"{action_text}管理员: {target_user['real_name']}({target_user['username']})",
|
||||
ip=request.client.host
|
||||
@@ -607,11 +716,10 @@ async def toggle_admin_status(request: Request, user_id: int):
|
||||
|
||||
@router.post("/reset-password/{user_id}")
|
||||
async def reset_admin_password(request: Request, user_id: int, req: ResetPasswordRequest):
|
||||
"""重置管理员密码(班主任)"""
|
||||
"""重置管理员密码"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可重置密码", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
|
||||
from models.user import UserModel
|
||||
|
||||
@@ -628,7 +736,8 @@ async def reset_admin_password(request: Request, user_id: int, req: ResetPasswor
|
||||
if updated:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="reset_password",
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="reset_password",
|
||||
target_type="admin", target_id=user_id,
|
||||
details=f"重置管理员密码: {target_user['real_name']}({target_user['username']})",
|
||||
ip=request.client.host
|
||||
@@ -642,17 +751,21 @@ async def reset_admin_password(request: Request, user_id: int, req: ResetPasswor
|
||||
|
||||
@router.post("/unlock-user")
|
||||
async def unlock_user(request: Request, req: UnlockUserRequest):
|
||||
"""解除用户登录锁定(班主任)"""
|
||||
"""解除用户登录锁定(管理员管理或学生管理权限)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可解除用户锁定", code=403)
|
||||
can_manage = (
|
||||
await PermissionChecker.check_permission(user["user_id"], "manage_admins")
|
||||
or await PermissionChecker.check_permission(user["user_id"], "manage_students")
|
||||
)
|
||||
if not can_manage:
|
||||
return error_response(message="无操作权限", code=403)
|
||||
|
||||
await RedisClient.clear_login_attempts(req.username)
|
||||
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="unlock_user",
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="unlock_user",
|
||||
target_type="user",
|
||||
details=f"解除用户登录锁定: {req.username}",
|
||||
ip=request.client.host
|
||||
|
||||
+60
-1
@@ -12,7 +12,10 @@
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from typing import Dict, Any
|
||||
|
||||
from schemas.auth import LoginRequest, ChangePasswordRequest
|
||||
from schemas.auth import (
|
||||
LoginRequest, ChangePasswordRequest,
|
||||
ForgotPasswordRequest, ResetPasswordRequest, BindEmailRequest
|
||||
)
|
||||
from services.auth_service import AuthService
|
||||
from middleware.permission import get_current_user
|
||||
from utils.response import success_response, error_response, unauthorized_response
|
||||
@@ -48,6 +51,9 @@ async def login(request: LoginRequest, http_request: Request):
|
||||
"user_type": result["user_type"],
|
||||
"student_id": result.get("student_id"),
|
||||
"role": result.get("role"),
|
||||
"permissions": result.get("permissions", {}),
|
||||
"group": result.get("group"),
|
||||
"email": result.get("email"),
|
||||
"need_change_password": result["need_change_password"],
|
||||
"redirect": result["redirect"]
|
||||
},
|
||||
@@ -105,3 +111,56 @@ async def get_current_user_info(request: Request):
|
||||
user_info = await AuthService.get_user_info(user["user_id"])
|
||||
|
||||
return success_response(data=user_info)
|
||||
|
||||
|
||||
@router.post("/forgot-password")
|
||||
async def forgot_password(request: Request, req: ForgotPasswordRequest):
|
||||
"""
|
||||
管理员找回密码:向绑定邮箱发送重置链接(公开接口)
|
||||
"""
|
||||
client_ip = request.client.host if request.client else None
|
||||
result = await AuthService.request_password_reset(username=req.username, ip=client_ip)
|
||||
if result["success"]:
|
||||
return success_response(message=result["message"])
|
||||
return error_response(message=result["message"], code=400)
|
||||
|
||||
|
||||
@router.get("/reset-token/check")
|
||||
async def check_reset_token(request: Request, token: str = ""):
|
||||
"""
|
||||
校验密码重置令牌(公开接口)
|
||||
"""
|
||||
result = await AuthService.check_reset_token(token)
|
||||
return success_response(data=result)
|
||||
|
||||
|
||||
@router.post("/reset-password")
|
||||
async def reset_password_by_token(request: Request, req: ResetPasswordRequest):
|
||||
"""
|
||||
使用邮件令牌重置密码(公开接口)
|
||||
"""
|
||||
result = await AuthService.reset_password_by_token(
|
||||
token=req.token,
|
||||
new_password=req.new_password
|
||||
)
|
||||
if result["success"]:
|
||||
return success_response(message=result["message"])
|
||||
return error_response(message=result["message"], code=400)
|
||||
|
||||
|
||||
@router.post("/bind-email")
|
||||
async def bind_email(request: Request, req: BindEmailRequest):
|
||||
"""
|
||||
管理员绑定/修改绑定邮箱(需验证当前密码)
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可绑定邮箱", code=403)
|
||||
result = await AuthService.bind_email(
|
||||
user_id=user["user_id"],
|
||||
password=req.password,
|
||||
email=req.email
|
||||
)
|
||||
if result["success"]:
|
||||
return success_response(data={"email": result.get("email")}, message=result["message"])
|
||||
return error_response(message=result["message"])
|
||||
+11
-5
@@ -42,10 +42,14 @@ async def debug_add_admin(request: Request, req: AddAdminDebugRequest):
|
||||
logger.warning(f"调试入口在生产环境中被调用!路径: {settings.DEBUG_PATH}, 来源IP: {request.client.host}")
|
||||
|
||||
from models.user import UserModel
|
||||
from models.permission_group import PermissionGroupModel
|
||||
|
||||
valid_roles = ["班主任", "班长", "学习委员", "考勤委员", "劳动委员", "志愿委员"]
|
||||
if req.role_type not in valid_roles:
|
||||
return error_response(message=f"无效的角色类型,可选: {', '.join(valid_roles)}")
|
||||
group = await PermissionGroupModel.get_by_name(req.role_type)
|
||||
if not group and req.role_type not in valid_roles:
|
||||
return error_response(message=f"无效的权限组,可选: {', '.join(valid_roles)} 或已有自定义权限组")
|
||||
if not group:
|
||||
return error_response(message=f"权限组不存在: {req.role_type}")
|
||||
|
||||
existing = await UserModel.get_by_username(req.username)
|
||||
if existing:
|
||||
@@ -55,8 +59,9 @@ async def debug_add_admin(request: Request, req: AddAdminDebugRequest):
|
||||
username=req.username,
|
||||
real_name=req.real_name,
|
||||
password=req.password,
|
||||
role_type=req.role_type,
|
||||
operator_id=0
|
||||
group_id=group["group_id"],
|
||||
operator_id=0,
|
||||
allow_locked=True
|
||||
)
|
||||
|
||||
if result["success"]:
|
||||
@@ -65,7 +70,8 @@ async def debug_add_admin(request: Request, req: AddAdminDebugRequest):
|
||||
data={
|
||||
"username": req.username,
|
||||
"password": req.password,
|
||||
"role_type": req.role_type
|
||||
"role_type": req.role_type,
|
||||
"group_id": group["group_id"]
|
||||
},
|
||||
message=f"管理员 {req.username} 创建成功"
|
||||
)
|
||||
|
||||
+33
-30
@@ -30,9 +30,8 @@ logger = get_logger(__name__)
|
||||
async def list_semesters(request: Request):
|
||||
"""获取学期列表(仅班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可查看学期列表", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
result = await SemesterService.list_semesters()
|
||||
if result["success"]:
|
||||
return success_response(data=result["semesters"])
|
||||
@@ -68,13 +67,23 @@ async def get_active_semester(request: Request):
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.get("/options")
|
||||
async def get_semester_options(request: Request):
|
||||
"""获取学期下拉选项(所有管理员,只读)"""
|
||||
user = await get_current_user(request)
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可查看学期列表", code=403)
|
||||
from models.semester import SemesterModel
|
||||
semesters = await SemesterModel.get_all()
|
||||
return success_response(data=semesters)
|
||||
|
||||
|
||||
@router.post("/create")
|
||||
async def create_semester(request: Request, req: CreateSemesterRequest):
|
||||
"""创建学期(班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可创建学期", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
|
||||
result = await SemesterService.create_semester(
|
||||
semester_name=req.semester_name,
|
||||
@@ -85,7 +94,7 @@ async def create_semester(request: Request, req: CreateSemesterRequest):
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="create_semester",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="create_semester",
|
||||
target_type="semester", target_id=result.get("semester_id"),
|
||||
details=f"创建学期: {req.semester_name}",
|
||||
ip=request.client.host
|
||||
@@ -99,9 +108,8 @@ async def create_semester(request: Request, req: CreateSemesterRequest):
|
||||
async def activate_semester(request: Request, semester_id: int):
|
||||
"""设为当前学期(班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可设置当前学期", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
|
||||
result = await SemesterService.activate_semester(
|
||||
semester_id=semester_id,
|
||||
@@ -110,7 +118,7 @@ async def activate_semester(request: Request, semester_id: int):
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="activate_semester",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="activate_semester",
|
||||
target_type="semester", target_id=semester_id,
|
||||
details=f"激活学期ID: {semester_id}",
|
||||
ip=request.client.host
|
||||
@@ -124,9 +132,8 @@ async def activate_semester(request: Request, semester_id: int):
|
||||
async def update_semester(request: Request, semester_id: int, req: UpdateSemesterRequest):
|
||||
"""编辑学期(班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可编辑学期", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
|
||||
result = await SemesterService.update_semester(
|
||||
semester_id=semester_id,
|
||||
@@ -138,7 +145,7 @@ async def update_semester(request: Request, semester_id: int, req: UpdateSemeste
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="update_semester",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="update_semester",
|
||||
target_type="semester", target_id=semester_id,
|
||||
details=f"编辑学期ID: {semester_id}",
|
||||
ip=request.client.host
|
||||
@@ -152,9 +159,8 @@ async def update_semester(request: Request, semester_id: int, req: UpdateSemeste
|
||||
async def delete_semester(request: Request, semester_id: int):
|
||||
"""删除学期(班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可删除学期", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
|
||||
result = await SemesterService.delete_semester(
|
||||
semester_id=semester_id,
|
||||
@@ -163,7 +169,7 @@ async def delete_semester(request: Request, semester_id: int):
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="delete_semester",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="delete_semester",
|
||||
target_type="semester", target_id=semester_id,
|
||||
details=f"删除学期ID: {semester_id}",
|
||||
ip=request.client.host
|
||||
@@ -177,9 +183,8 @@ async def delete_semester(request: Request, semester_id: int):
|
||||
async def associate_records(request: Request, semester_id: int):
|
||||
"""关联记录到学期(班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可关联数据", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
|
||||
result = await SemesterService.associate_records(
|
||||
semester_id=semester_id,
|
||||
@@ -188,7 +193,7 @@ async def associate_records(request: Request, semester_id: int):
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="associate_records",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="associate_records",
|
||||
target_type="semester", target_id=semester_id,
|
||||
details=f"关联数据到学期ID: {semester_id}, 结果: {result.get('data', {})}",
|
||||
ip=request.client.host
|
||||
@@ -206,9 +211,8 @@ async def archive_semester(
|
||||
):
|
||||
"""归档学期(班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可归档学期", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
|
||||
result = await SemesterService.archive_semester(
|
||||
semester_id=semester_id,
|
||||
@@ -221,7 +225,7 @@ async def archive_semester(
|
||||
log_detail += " 并重置学生操行分"
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role="班主任", operation_type="archive_semester",
|
||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), operation_type="archive_semester",
|
||||
target_type="semester", target_id=semester_id,
|
||||
details=log_detail,
|
||||
ip=request.client.host
|
||||
@@ -240,9 +244,8 @@ async def get_archive_records(
|
||||
):
|
||||
"""查看归档数据(仅班主任)"""
|
||||
user = await get_current_user(request)
|
||||
is_teacher = await PermissionChecker.check_is_teacher(user["user_id"])
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可查看归档数据", code=403)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_semesters"):
|
||||
return error_response(message="无学期管理权限", code=403)
|
||||
result = await SemesterService.get_archive_records(
|
||||
semester_id=semester_id,
|
||||
page=page,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# ===========================================
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
@@ -33,7 +33,7 @@ async def get_subjects(request: Request, is_active: Optional[bool] = None):
|
||||
@router.post("/create")
|
||||
async def create_subject(request: Request, req: CreateSubjectRequest):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_can_manage_subjects(user["user_id"]):
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_subjects"):
|
||||
return error_response(message="无权限", code=403)
|
||||
result = await SubjectService.create_subject(req.subject_name, req.subject_code, req.sort_order)
|
||||
return success_response(data=result, message="科目创建成功") if result["success"] else error_response(message=result["message"])
|
||||
@@ -41,7 +41,7 @@ async def create_subject(request: Request, req: CreateSubjectRequest):
|
||||
@router.put("/update/{subject_id}")
|
||||
async def update_subject(request: Request, subject_id: int, req: UpdateSubjectRequest):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_can_manage_subjects(user["user_id"]):
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_subjects"):
|
||||
return error_response(message="无权限", code=403)
|
||||
result = await SubjectService.update_subject(subject_id, **req.dict(exclude_none=True))
|
||||
return success_response(message="科目更新成功") if result["success"] else error_response(message=result["message"])
|
||||
@@ -49,7 +49,7 @@ async def update_subject(request: Request, subject_id: int, req: UpdateSubjectRe
|
||||
@router.delete("/delete/{subject_id}")
|
||||
async def delete_subject(request: Request, subject_id: int):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_can_manage_subjects(user["user_id"]):
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_subjects"):
|
||||
return error_response(message="无权限", code=403)
|
||||
result = await SubjectService.delete_subject(subject_id)
|
||||
return success_response(message="科目已删除") if result["success"] else error_response(message=result["message"])
|
||||
+15
-12
@@ -42,9 +42,14 @@ ALL_VERSIONS = {
|
||||
'2.7': 'v2.7.sql',
|
||||
'2.8': 'v2.8.sql',
|
||||
'2.9': 'v2.9.sql',
|
||||
'3.0': 'v3.0.sql',
|
||||
'4.0': 'v4.0.sql',
|
||||
'4.1': 'v4.1.sql',
|
||||
}
|
||||
# 版本特征标记(按优先级从高到低)
|
||||
VERSION_MARKERS = [
|
||||
('4.1', 'users', 'email'),
|
||||
('4.0', 'admin_roles', 'group_id'),
|
||||
('2.0', 'students', 'dormitory_number'),
|
||||
('1.8', 'conduct_records', 'related_type'),
|
||||
('1.7', 'subjects', 'sort_order'),
|
||||
@@ -104,16 +109,15 @@ async def _detect_current_version() -> str:
|
||||
@router.get("/check")
|
||||
async def check_upgrade(request: Request):
|
||||
"""检查数据库版本是否需要升级"""
|
||||
# 权限检查:仅班主任可执行升级操作
|
||||
# 权限检查:仅拥有系统升级权限的管理员可操作
|
||||
user_type = getattr(request.state, 'user_type', None)
|
||||
if user_type != 'admin':
|
||||
return error_response(message="仅管理员可执行升级操作", code=403)
|
||||
|
||||
is_teacher = await PermissionChecker.check_is_teacher(
|
||||
getattr(request.state, 'user_id', 0)
|
||||
)
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可执行升级操作", code=403)
|
||||
if not await PermissionChecker.check_permission(
|
||||
getattr(request.state, 'user_id', 0), "manage_upgrade"
|
||||
):
|
||||
return error_response(message="无系统升级权限", code=403)
|
||||
|
||||
# 检测当前数据库版本(支持自动推断)
|
||||
current_version = await _detect_current_version()
|
||||
@@ -171,16 +175,15 @@ MAX_RETRIES = 2
|
||||
@router.post("/step")
|
||||
async def execute_upgrade_step(request: Request):
|
||||
"""执行单个升级步骤(含验证与重试)"""
|
||||
# 权限检查:仅班主任可执行升级操作
|
||||
# 权限检查:仅拥有系统升级权限的管理员可操作
|
||||
user_type = getattr(request.state, 'user_type', None)
|
||||
if user_type != 'admin':
|
||||
return error_response(message="仅管理员可执行升级操作", code=403)
|
||||
|
||||
is_teacher = await PermissionChecker.check_is_teacher(
|
||||
getattr(request.state, 'user_id', 0)
|
||||
)
|
||||
if not is_teacher:
|
||||
return error_response(message="仅班主任可执行升级操作", code=403)
|
||||
if not await PermissionChecker.check_permission(
|
||||
getattr(request.state, 'user_id', 0), "manage_upgrade"
|
||||
):
|
||||
return error_response(message="无系统升级权限", code=403)
|
||||
|
||||
body = await request.json()
|
||||
version = body.get('version', '')
|
||||
|
||||
@@ -52,7 +52,8 @@ class AddAdminRequest(BaseModel):
|
||||
username: str = Field(..., min_length=2, max_length=50, pattern=r'^[a-zA-Z0-9_\u4e00-\u9fa5]+$', description="登录账号")
|
||||
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
||||
password: Optional[str] = Field(None, min_length=6, max_length=50, description="密码(不填则自动生成)")
|
||||
role_type: str = Field(..., pattern=r'^(班长|学习委员|考勤委员|劳动委员|志愿委员)$', description="角色类型")
|
||||
group_id: int = Field(..., gt=0, description="权限组ID")
|
||||
email: Optional[str] = Field(None, max_length=100, description="绑定邮箱(用于找回密码)")
|
||||
subject_id: Optional[int] = Field(None, gt=0, description="科目ID(科代表需要)")
|
||||
|
||||
|
||||
@@ -86,7 +87,19 @@ class AddAttendanceRequest(BaseModel):
|
||||
class UpdateAdminRequest(BaseModel):
|
||||
"""更新管理员请求"""
|
||||
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
||||
role_type: str = Field(..., pattern=r'^(班长|学习委员|考勤委员|劳动委员|志愿委员)$', description="角色类型")
|
||||
group_id: int = Field(..., gt=0, description="权限组ID")
|
||||
email: Optional[str] = Field(None, max_length=100, description="绑定邮箱(留空解除绑定)")
|
||||
|
||||
|
||||
class PermissionGroupRequest(BaseModel):
|
||||
"""权限组创建/编辑请求"""
|
||||
group_name: str = Field(..., min_length=1, max_length=50, description="权限组名称")
|
||||
description: Optional[str] = Field(None, max_length=255, description="说明")
|
||||
permissions: List[str] = Field(default_factory=list, description="权限项列表")
|
||||
can_add_points: bool = Field(True, description="是否允许加分")
|
||||
max_add_points: Optional[int] = Field(None, ge=1, le=100, description="单次加分上限,不填为无限制")
|
||||
can_subtract_points: bool = Field(True, description="是否允许扣分")
|
||||
max_subtract_points: Optional[int] = Field(None, ge=1, le=100, description="单次扣分上限,不填为无限制")
|
||||
|
||||
|
||||
class DeleteAdminRequest(BaseModel):
|
||||
|
||||
@@ -52,4 +52,22 @@ class UserInfo(BaseModel):
|
||||
user_type: str
|
||||
student_id: Optional[int] = None
|
||||
role: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
need_change_password: bool
|
||||
|
||||
|
||||
class ForgotPasswordRequest(BaseModel):
|
||||
"""忘记密码请求"""
|
||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
"""通过邮件令牌重置密码请求"""
|
||||
token: str = Field(..., min_length=10, max_length=200, description="重置令牌")
|
||||
new_password: str = Field(..., min_length=6, max_length=20, description="新密码")
|
||||
|
||||
|
||||
class BindEmailRequest(BaseModel):
|
||||
"""绑定/修改邮箱请求"""
|
||||
password: str = Field(..., min_length=1, max_length=50, description="当前密码")
|
||||
email: str = Field(default="", max_length=100, description="新邮箱(留空解除绑定)")
|
||||
@@ -14,11 +14,74 @@ from utils.database import execute_query, execute_one, execute_update
|
||||
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 utils.security import security
|
||||
from utils.validators import is_valid_email
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
MAX_POINT_LIMIT = 100
|
||||
|
||||
|
||||
def _normalize_group_payload(
|
||||
group_name: str,
|
||||
description: Optional[str],
|
||||
permissions: Optional[Dict[str, Any]],
|
||||
can_add_points: bool,
|
||||
max_add_points: Optional[int],
|
||||
can_subtract_points: bool,
|
||||
max_subtract_points: Optional[int]
|
||||
) -> Dict[str, Any]:
|
||||
"""校验并规范化权限组配置"""
|
||||
name = (group_name or "").strip()
|
||||
if not name or len(name) > 50:
|
||||
return {"success": False, "message": "权限组名称不能为空且不超过50字符"}
|
||||
if description is not None and len(description) > 255:
|
||||
return {"success": False, "message": "说明不能超过255字符"}
|
||||
|
||||
normalized_permissions = {
|
||||
key: bool((permissions or {}).get(key, False)) for key in PERMISSION_KEYS
|
||||
}
|
||||
|
||||
def normalize_limit(value):
|
||||
if value is None or value == "":
|
||||
return None, None
|
||||
try:
|
||||
limit = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None, "上限必须是整数"
|
||||
if limit < 1 or limit > MAX_POINT_LIMIT:
|
||||
return None, f"上限必须在1-{MAX_POINT_LIMIT}之间"
|
||||
return limit, None
|
||||
|
||||
if can_add_points:
|
||||
max_add, error = normalize_limit(max_add_points)
|
||||
if error:
|
||||
return {"success": False, "message": f"加分{error}"}
|
||||
else:
|
||||
max_add = None
|
||||
|
||||
if can_subtract_points:
|
||||
max_sub, error = normalize_limit(max_subtract_points)
|
||||
if error:
|
||||
return {"success": False, "message": f"扣分{error}"}
|
||||
else:
|
||||
max_sub = None
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"data": {
|
||||
"group_name": name,
|
||||
"description": (description or "").strip() or None,
|
||||
"permissions": normalized_permissions,
|
||||
"can_add_points": bool(can_add_points),
|
||||
"max_add_points": max_add,
|
||||
"can_subtract_points": bool(can_subtract_points),
|
||||
"max_subtract_points": max_sub
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class AdminService:
|
||||
"""管理员服务"""
|
||||
@@ -242,10 +305,26 @@ class AdminService:
|
||||
username: str,
|
||||
real_name: str,
|
||||
password: Optional[str],
|
||||
role_type: str,
|
||||
operator_id: int
|
||||
group_id: int,
|
||||
operator_id: int,
|
||||
email: Optional[str] = None,
|
||||
allow_locked: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
"""添加管理员(支持重新激活已删除的管理员)"""
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
if not group:
|
||||
return {"success": False, "message": "权限组不存在"}
|
||||
if group.get("is_locked") and not allow_locked:
|
||||
return {"success": False, "message": "该权限组不可分配"}
|
||||
role_type = group["group_name"]
|
||||
|
||||
# 邮箱校验(留空表示不绑定)
|
||||
normalized_email = None
|
||||
if email is not None and str(email).strip():
|
||||
normalized_email = str(email).strip()
|
||||
if not is_valid_email(normalized_email):
|
||||
return {"success": False, "message": "邮箱格式不正确"}
|
||||
|
||||
# 检查用户名是否存在(含已禁用用户,因 username 有 UNIQUE 约束)
|
||||
existing = await UserModel.get_by_username_any(username)
|
||||
if existing:
|
||||
@@ -254,20 +333,24 @@ class AdminService:
|
||||
# 用户已被软删除(status=0),重新激活
|
||||
await UserModel.update_status(existing['user_id'], 1)
|
||||
await UserModel.update_real_name(existing['user_id'], real_name)
|
||||
if email is not None:
|
||||
await UserModel.update_email(existing['user_id'], normalized_email)
|
||||
user_id = existing['user_id']
|
||||
# 检查是否已有管理员角色
|
||||
existing_role = await AdminRoleModel.get_by_user_id(user_id)
|
||||
if existing_role:
|
||||
await AdminRoleModel.update_role(user_id, role_type)
|
||||
await AdminRoleModel.update_role(user_id, role_type, group_id=group_id)
|
||||
else:
|
||||
await AdminRoleModel.create(user_id=user_id, role_type=role_type, subject_id=None)
|
||||
await AdminRoleModel.create(user_id=user_id, role_type=role_type, group_id=group_id)
|
||||
logger.info(f"用户[{operator_id}] 重新激活管理员: {username} ({role_type})")
|
||||
return {
|
||||
"success": True,
|
||||
"user_id": user_id,
|
||||
"username": username,
|
||||
"password": None, # 重新激活不返回密码
|
||||
"role_type": role_type
|
||||
"role_type": role_type,
|
||||
"group_id": group_id,
|
||||
"email": normalized_email
|
||||
}
|
||||
|
||||
if not password:
|
||||
@@ -276,13 +359,14 @@ class AdminService:
|
||||
user_id = await UserModel.create_admin(
|
||||
username=username,
|
||||
password=password,
|
||||
real_name=real_name
|
||||
real_name=real_name,
|
||||
email=normalized_email
|
||||
)
|
||||
|
||||
await AdminRoleModel.create(
|
||||
user_id=user_id,
|
||||
role_type=role_type,
|
||||
subject_id=None
|
||||
group_id=group_id
|
||||
)
|
||||
|
||||
logger.info(f"用户[{operator_id}] 添加管理员: {username} ({role_type})")
|
||||
@@ -292,8 +376,162 @@ class AdminService:
|
||||
"user_id": user_id,
|
||||
"username": username,
|
||||
"password": password,
|
||||
"role_type": role_type
|
||||
"role_type": role_type,
|
||||
"group_id": group_id,
|
||||
"email": normalized_email
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def update_admin(
|
||||
user_id: int,
|
||||
real_name: str,
|
||||
group_id: int,
|
||||
operator_id: int,
|
||||
email: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""更新管理员姓名、权限组与绑定邮箱"""
|
||||
target_user = await UserModel.get_by_user_id(user_id)
|
||||
if not target_user or target_user.get("user_type") != "admin":
|
||||
return {"success": False, "message": "管理员不存在"}
|
||||
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
if not group:
|
||||
return {"success": False, "message": "权限组不存在"}
|
||||
if group.get("is_locked"):
|
||||
return {"success": False, "message": "该权限组不可分配"}
|
||||
|
||||
# 邮箱校验(留空表示解除绑定)
|
||||
normalized_email = None
|
||||
if email is not None:
|
||||
normalized_email = str(email).strip() or None
|
||||
if normalized_email and not is_valid_email(normalized_email):
|
||||
return {"success": False, "message": "邮箱格式不正确"}
|
||||
|
||||
await AdminRoleModel.update_role(user_id, group["group_name"], group_id=group_id)
|
||||
if real_name:
|
||||
await UserModel.update_real_name(user_id, real_name)
|
||||
if email is not None:
|
||||
await UserModel.update_email(user_id, normalized_email)
|
||||
|
||||
logger.info(f"用户[{operator_id}] 更新管理员[{user_id}]权限组: {group['group_name']}")
|
||||
return {"success": True, "message": "管理员更新成功"}
|
||||
|
||||
# ========== 权限组管理 ==========
|
||||
|
||||
@staticmethod
|
||||
async def get_permission_groups() -> Dict[str, Any]:
|
||||
"""获取权限组列表"""
|
||||
groups = await PermissionGroupModel.get_all()
|
||||
return {"groups": groups}
|
||||
|
||||
@staticmethod
|
||||
async def create_permission_group(
|
||||
group_name: str,
|
||||
description: Optional[str],
|
||||
permissions: Optional[Dict[str, Any]],
|
||||
can_add_points: bool,
|
||||
max_add_points: Optional[int],
|
||||
can_subtract_points: bool,
|
||||
max_subtract_points: Optional[int],
|
||||
operator_id: int = None
|
||||
) -> Dict[str, Any]:
|
||||
"""新建自定义权限组"""
|
||||
normalized = _normalize_group_payload(
|
||||
group_name, description, permissions,
|
||||
can_add_points, max_add_points,
|
||||
can_subtract_points, max_subtract_points
|
||||
)
|
||||
if not normalized["success"]:
|
||||
return normalized
|
||||
|
||||
data = normalized["data"]
|
||||
if await PermissionGroupModel.get_by_name(data["group_name"]):
|
||||
return {"success": False, "message": "权限组名称已存在"}
|
||||
|
||||
group_id = await PermissionGroupModel.create(
|
||||
group_name=data["group_name"],
|
||||
description=data["description"],
|
||||
permissions=data["permissions"],
|
||||
can_add_points=data["can_add_points"],
|
||||
max_add_points=data["max_add_points"],
|
||||
can_subtract_points=data["can_subtract_points"],
|
||||
max_subtract_points=data["max_subtract_points"]
|
||||
)
|
||||
logger.info(f"用户[{operator_id}] 新建权限组: {data['group_name']} (ID={group_id})")
|
||||
return {"success": True, "message": "权限组创建成功", "group_id": group_id}
|
||||
|
||||
@staticmethod
|
||||
async def update_permission_group(
|
||||
group_id: int,
|
||||
group_name: str,
|
||||
description: Optional[str],
|
||||
permissions: Optional[Dict[str, Any]],
|
||||
can_add_points: bool,
|
||||
max_add_points: Optional[int],
|
||||
can_subtract_points: bool,
|
||||
max_subtract_points: Optional[int],
|
||||
operator_id: int = None
|
||||
) -> Dict[str, Any]:
|
||||
"""编辑权限组(锁定组不可编辑)"""
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
if not group:
|
||||
return {"success": False, "message": "权限组不存在"}
|
||||
if group.get("is_locked"):
|
||||
return {"success": False, "message": "该权限组已锁定,不可编辑"}
|
||||
|
||||
normalized = _normalize_group_payload(
|
||||
group_name, description, permissions,
|
||||
can_add_points, max_add_points,
|
||||
can_subtract_points, max_subtract_points
|
||||
)
|
||||
if not normalized["success"]:
|
||||
return normalized
|
||||
|
||||
data = normalized["data"]
|
||||
same_name = await PermissionGroupModel.get_by_name(data["group_name"])
|
||||
if same_name and same_name["group_id"] != group_id:
|
||||
return {"success": False, "message": "权限组名称已存在"}
|
||||
|
||||
updated = await PermissionGroupModel.update(
|
||||
group_id=group_id,
|
||||
group_name=data["group_name"],
|
||||
description=data["description"],
|
||||
permissions=data["permissions"],
|
||||
can_add_points=data["can_add_points"],
|
||||
max_add_points=data["max_add_points"],
|
||||
can_subtract_points=data["can_subtract_points"],
|
||||
max_subtract_points=data["max_subtract_points"]
|
||||
)
|
||||
if not updated:
|
||||
return {"success": False, "message": "权限组更新失败"}
|
||||
|
||||
# 同步冗余的 role_type 显示名
|
||||
await execute_update(
|
||||
"UPDATE admin_roles SET role_type = %s WHERE group_id = %s",
|
||||
(data["group_name"], group_id)
|
||||
)
|
||||
logger.info(f"用户[{operator_id}] 更新权限组: {data['group_name']} (ID={group_id})")
|
||||
return {"success": True, "message": "权限组更新成功"}
|
||||
|
||||
@staticmethod
|
||||
async def delete_permission_group(group_id: int, operator_id: int = None) -> Dict[str, Any]:
|
||||
"""删除权限组(系统预置组不可删除,有成员时不可删除)"""
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
if not group:
|
||||
return {"success": False, "message": "权限组不存在"}
|
||||
if group.get("is_system") or group.get("is_locked"):
|
||||
return {"success": False, "message": "系统预置权限组不可删除"}
|
||||
|
||||
member_count = await PermissionGroupModel.count_members(group_id)
|
||||
if member_count > 0:
|
||||
return {"success": False, "message": f"该权限组下还有 {member_count} 个管理员,请先调整后再删除"}
|
||||
|
||||
deleted = await PermissionGroupModel.delete(group_id)
|
||||
if not deleted:
|
||||
return {"success": False, "message": "权限组删除失败"}
|
||||
logger.info(f"用户[{operator_id}] 删除权限组 ID={group_id}")
|
||||
return {"success": True, "message": "权限组已删除"}
|
||||
|
||||
@staticmethod
|
||||
async def get_admins() -> Dict[str, Any]:
|
||||
"""获取管理员列表"""
|
||||
|
||||
@@ -56,14 +56,30 @@ class AttendanceService:
|
||||
return {"success": False, "message": "自定义扣分必须在1-20之间"}
|
||||
|
||||
# 检查权限
|
||||
role = await PermissionChecker.get_user_role(recorder_id)
|
||||
if role not in ["班主任", "考勤委员"]:
|
||||
return {"success": False, "message": "无权进行此操作"}
|
||||
if not await PermissionChecker.check_permission(recorder_id, "manage_attendance"):
|
||||
return {"success": False, "message": "无考勤管理权限"}
|
||||
|
||||
# 考勤委员扣分上限
|
||||
if role == "考勤委员" and apply_deduction and status in ["absent", "late"]:
|
||||
if custom_deduction is not None and custom_deduction > settings.ATTENDANCE_REP_MAX_POINTS:
|
||||
return {"success": False, "message": f"考勤委员单次扣分上限为{settings.ATTENDANCE_REP_MAX_POINTS}分"}
|
||||
limits = await PermissionChecker.get_score_limits(recorder_id)
|
||||
|
||||
# 扣分权限与动态上限校验
|
||||
if apply_deduction and status in ["absent", "late", "leave"]:
|
||||
if not limits["can_subtract"]:
|
||||
return {"success": False, "message": "当前权限组不允许扣分"}
|
||||
if limits["max_subtract"] is not None:
|
||||
if custom_deduction is not None and custom_deduction > limits["max_subtract"]:
|
||||
return {"success": False, "message": f"单次扣分上限为{limits['max_subtract']}分"}
|
||||
default_deduction = {
|
||||
"absent": settings.DEDUCTION_ATTENDANCE_ABSENT,
|
||||
"late": settings.DEDUCTION_ATTENDANCE_LATE,
|
||||
"leave": settings.DEDUCTION_ATTENDANCE_LEAVE
|
||||
}.get(status, 0)
|
||||
if default_deduction > limits["max_subtract"]:
|
||||
return {"success": False, "message": f"单次扣分上限为{limits['max_subtract']}分"}
|
||||
|
||||
# 获取当前活跃学期,用于记录归属
|
||||
from models.semester import SemesterModel
|
||||
active_semester = await SemesterModel.get_active()
|
||||
semester_id = active_semester['semester_id'] if active_semester else None
|
||||
|
||||
# 添加考勤记录
|
||||
attendance_id = await AttendanceModel.create_record(
|
||||
@@ -72,7 +88,8 @@ class AttendanceService:
|
||||
status=status,
|
||||
reason=reason,
|
||||
recorder_id=recorder_id,
|
||||
slot=slot
|
||||
slot=slot,
|
||||
semester_id=semester_id
|
||||
)
|
||||
|
||||
if not attendance_id:
|
||||
@@ -108,7 +125,8 @@ class AttendanceService:
|
||||
recorder_id=recorder_id,
|
||||
recorder_name=recorder_name,
|
||||
related_type="attendance",
|
||||
related_id=attendance_id
|
||||
related_id=attendance_id,
|
||||
semester_id=semester_id
|
||||
)
|
||||
|
||||
# 更新学生总分
|
||||
@@ -128,18 +146,9 @@ class AttendanceService:
|
||||
slot: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""获取考勤记录"""
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
|
||||
if role in ["班主任", "考勤委员"]:
|
||||
records = await AttendanceModel.get_class_records(
|
||||
date=date,
|
||||
student_id=student_id,
|
||||
slot=slot
|
||||
)
|
||||
elif student_id:
|
||||
# 管理员可查看指定学生
|
||||
records = await AttendanceModel.get_student_records(student_id)
|
||||
else:
|
||||
records = []
|
||||
|
||||
return {"records": records}
|
||||
@@ -11,12 +11,18 @@
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from html import escape as html_escape
|
||||
import secrets
|
||||
|
||||
from config import settings
|
||||
from models.user import UserModel
|
||||
from models.student import StudentModel
|
||||
from models.admin_role import AdminRoleModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from services.log_service import LogService
|
||||
from utils.security import security
|
||||
from utils.validators import is_valid_email
|
||||
from utils.email_sender import EmailSender
|
||||
from utils.jwt_handler import jwt_handler
|
||||
from utils.redis_client import RedisClient
|
||||
from utils.database import execute_update
|
||||
@@ -25,6 +31,19 @@ from utils.logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def _build_group_info(group: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""构建权限组摘要信息(用于登录响应与Session)"""
|
||||
return {
|
||||
"group_id": group.get("group_id"),
|
||||
"group_name": group.get("group_name") or group.get("role_type"),
|
||||
"max_add_points": group.get("max_add_points"),
|
||||
"max_subtract_points": group.get("max_subtract_points"),
|
||||
"can_add_points": bool(group.get("can_add_points")),
|
||||
"can_subtract_points": bool(group.get("can_subtract_points")),
|
||||
"is_locked": bool(group.get("is_locked"))
|
||||
}
|
||||
|
||||
|
||||
class AuthService:
|
||||
"""认证服务"""
|
||||
|
||||
@@ -72,11 +91,16 @@ class AuthService:
|
||||
# 更新最后登录信息
|
||||
await UserModel.update_last_login(user["user_id"], ip)
|
||||
|
||||
# 获取用户角色(如果是管理员)
|
||||
# 获取用户角色与权限(如果是管理员)
|
||||
role = None
|
||||
permissions = {}
|
||||
group_info = None
|
||||
if user["user_type"] == "admin":
|
||||
admin_role = await AdminRoleModel.get_by_user_id(user["user_id"])
|
||||
role = admin_role["role_type"] if admin_role else None
|
||||
group = await PermissionChecker.get_user_group(user["user_id"])
|
||||
if group:
|
||||
role = group.get("group_name") or group.get("role_type")
|
||||
permissions = group.get("permissions_data", {})
|
||||
group_info = _build_group_info(group)
|
||||
|
||||
# 生成Token
|
||||
token = jwt_handler.create_token(
|
||||
@@ -105,6 +129,9 @@ class AuthService:
|
||||
"user_type": user["user_type"],
|
||||
"student_id": user["student_id"],
|
||||
"role": role,
|
||||
"permissions": permissions,
|
||||
"group": group_info,
|
||||
"email": user.get("email"),
|
||||
"need_change_password": user["need_change_password"] == 1,
|
||||
"redirect": redirect
|
||||
}
|
||||
@@ -164,6 +191,7 @@ class AuthService:
|
||||
"username": user["username"],
|
||||
"real_name": user["real_name"],
|
||||
"user_type": user["user_type"],
|
||||
"email": user.get("email"),
|
||||
"need_change_password": user["need_change_password"] == 1
|
||||
}
|
||||
|
||||
@@ -175,14 +203,147 @@ class AuthService:
|
||||
result["student_name"] = student["name"]
|
||||
result["total_points"] = student["total_points"]
|
||||
|
||||
# 获取管理员角色
|
||||
# 获取管理员角色与权限
|
||||
if user["user_type"] == "admin":
|
||||
admin_role = await AdminRoleModel.get_by_user_id(user_id)
|
||||
if admin_role:
|
||||
result["role"] = admin_role["role_type"]
|
||||
group = await PermissionChecker.get_user_group(user_id)
|
||||
if group:
|
||||
result["role"] = group.get("group_name") or group.get("role_type")
|
||||
result["permissions"] = group.get("permissions_data", {})
|
||||
result["group"] = _build_group_info(group)
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
async def request_password_reset(username: str, ip: str = None) -> Dict[str, Any]:
|
||||
"""管理员通过绑定邮箱找回密码(SMTP)"""
|
||||
generic_success = {
|
||||
"success": True,
|
||||
"message": f"如果该账号已绑定邮箱,重置链接已发送,请留意查收({settings.PASSWORD_RESET_EXPIRE_MINUTES}分钟内有效)"
|
||||
}
|
||||
if not EmailSender.is_configured():
|
||||
return {"success": False, "message": "系统未配置邮件服务,请联系班主任或系统管理员"}
|
||||
if not settings.FRONTEND_URL:
|
||||
return {"success": False, "message": "系统未配置站点地址(FRONTEND_URL),无法生成重置链接"}
|
||||
|
||||
# 频率限制:同一账号 60 秒内只允许请求一次
|
||||
limit_key = f"pwd_reset_req:{username}"
|
||||
if await RedisClient.exists(limit_key):
|
||||
return generic_success
|
||||
await RedisClient.set(limit_key, "1", expire=60)
|
||||
|
||||
user = await UserModel.get_by_username(username)
|
||||
if not user or user.get("user_type") != "admin" or not user.get("email"):
|
||||
logger.info(f"找回密码请求未发送(账号不存在/非管理员/未绑定邮箱): {username}, IP={ip}")
|
||||
return generic_success
|
||||
|
||||
# 生成一次性令牌,并作废该用户此前的令牌
|
||||
token = secrets.token_urlsafe(32)
|
||||
expire_seconds = settings.PASSWORD_RESET_EXPIRE_MINUTES * 60
|
||||
old_token = await RedisClient.get(f"pwd_reset_user:{user['user_id']}")
|
||||
if old_token:
|
||||
await RedisClient.delete(f"pwd_reset:{old_token}")
|
||||
await RedisClient.set(f"pwd_reset:{token}", user["user_id"], expire=expire_seconds)
|
||||
await RedisClient.set(f"pwd_reset_user:{user['user_id']}", token, expire=expire_seconds)
|
||||
|
||||
reset_url = f"{settings.FRONTEND_URL}/reset_password.php?token={token}"
|
||||
html_body = f"""
|
||||
<div style="max-width:560px;margin:0 auto;font-family:'Microsoft YaHei',Arial,sans-serif;color:#333;">
|
||||
<h2 style="color:#667eea;">{html_escape(settings.APP_NAME)} - 密码重置</h2>
|
||||
<p>{html_escape(user.get('real_name') or user['username'])},您好:</p>
|
||||
<p>我们收到了您账号({html_escape(user['username'])})的密码重置请求。请点击下方按钮设置新密码:</p>
|
||||
<p style="text-align:center;margin:28px 0;">
|
||||
<a href="{reset_url}" style="display:inline-block;padding:12px 28px;background:#667eea;color:#fff;text-decoration:none;border-radius:6px;">重置密码</a>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#888;">链接 {settings.PASSWORD_RESET_EXPIRE_MINUTES} 分钟内有效,且只能使用一次。如果按钮无法点击,请复制以下链接到浏览器打开:</p>
|
||||
<p style="font-size:12px;color:#888;word-break:break-all;">{reset_url}</p>
|
||||
<p style="font-size:13px;color:#888;">如果并非您本人操作,请忽略本邮件,您的密码不会被修改。</p>
|
||||
</div>
|
||||
"""
|
||||
ok, message_text = await EmailSender.send(
|
||||
user["email"],
|
||||
f"{settings.APP_NAME} - 密码重置",
|
||||
html_body
|
||||
)
|
||||
if not ok:
|
||||
await RedisClient.delete(f"pwd_reset:{token}")
|
||||
await RedisClient.delete(f"pwd_reset_user:{user['user_id']}")
|
||||
logger.error(f"密码重置邮件发送失败: {username} - {message_text}")
|
||||
return {"success": False, "message": "重置邮件发送失败,请稍后重试或联系系统管理员"}
|
||||
|
||||
logger.info(f"已向用户[{username}]的绑定邮箱发送密码重置链接, IP={ip}")
|
||||
return generic_success
|
||||
|
||||
@staticmethod
|
||||
async def check_reset_token(token: str) -> Dict[str, Any]:
|
||||
"""校验密码重置令牌是否有效"""
|
||||
if not token:
|
||||
return {"valid": False}
|
||||
user_id_raw = await RedisClient.get(f"pwd_reset:{token}")
|
||||
if not user_id_raw:
|
||||
return {"valid": False}
|
||||
user = await UserModel.get_by_user_id(int(user_id_raw))
|
||||
if not user or user.get("user_type") != "admin" or user.get("status") != 1:
|
||||
return {"valid": False}
|
||||
return {
|
||||
"valid": True,
|
||||
"username": user["username"],
|
||||
"real_name": user["real_name"]
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def reset_password_by_token(token: str, new_password: str) -> Dict[str, Any]:
|
||||
"""使用邮件令牌重置管理员密码"""
|
||||
if not token:
|
||||
return {"success": False, "message": "重置链接无效"}
|
||||
user_id_raw = await RedisClient.get(f"pwd_reset:{token}")
|
||||
if not user_id_raw:
|
||||
return {"success": False, "message": "重置链接无效或已过期,请重新申请"}
|
||||
user_id = int(user_id_raw)
|
||||
user = await UserModel.get_by_user_id(user_id)
|
||||
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)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": message}
|
||||
|
||||
updated = await UserModel.update_password(user_id, new_password)
|
||||
if not updated:
|
||||
return {"success": False, "message": "密码重置失败"}
|
||||
|
||||
# 令牌一次性使用;重置后强制所有会话重新登录
|
||||
await RedisClient.delete(f"pwd_reset:{token}")
|
||||
await RedisClient.delete(f"pwd_reset_user:{user_id}")
|
||||
await RedisClient.delete_user_token(user_id)
|
||||
logger.info(f"用户[{user_id}] 通过邮箱重置密码成功")
|
||||
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
|
||||
|
||||
@staticmethod
|
||||
async def bind_email(user_id: int, password: str, email: str) -> Dict[str, Any]:
|
||||
"""管理员绑定/修改/解除绑定邮箱(需验证当前密码)"""
|
||||
user = await UserModel.get_by_user_id(user_id)
|
||||
if not user or user.get("user_type") != "admin":
|
||||
return {"success": False, "message": "仅管理员可绑定邮箱"}
|
||||
|
||||
is_valid, _ = security.verify_password_v2(password, user["password_hash"])
|
||||
if not is_valid:
|
||||
return {"success": False, "message": "当前密码错误"}
|
||||
|
||||
normalized_email = (email or "").strip() or None
|
||||
if normalized_email and not is_valid_email(normalized_email):
|
||||
return {"success": False, "message": "邮箱格式不正确"}
|
||||
|
||||
updated = await UserModel.update_email(user_id, normalized_email)
|
||||
if not updated:
|
||||
return {"success": False, "message": "邮箱更新失败"}
|
||||
|
||||
logger.info(f"用户[{user_id}] 更新绑定邮箱: {normalized_email or '(解除绑定)'}")
|
||||
return {
|
||||
"success": True,
|
||||
"message": "邮箱绑定成功" if normalized_email else "邮箱已解除绑定",
|
||||
"email": normalized_email
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_redirect_path(user_type: str, role: str = None) -> str:
|
||||
"""获取跳转路径"""
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Dict, Any, List, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from models.student import StudentModel
|
||||
from models.conduct import ConductModel
|
||||
from models.conduct import ConductModel, _append_semester_filter
|
||||
from models.user import UserModel
|
||||
from models.semester import SemesterModel
|
||||
from middleware.permission import PermissionChecker
|
||||
@@ -26,6 +26,18 @@ logger = get_logger(__name__)
|
||||
class ConductService:
|
||||
"""操行分服务"""
|
||||
|
||||
@staticmethod
|
||||
def _resolve_semester_range(semester: Dict[str, Any]) -> tuple:
|
||||
"""解析学期日期范围;结束日期缺失时以今天兜底(用于未关联记录的匹配)"""
|
||||
start = str(semester.get('start_date')) if semester.get('start_date') else None
|
||||
if semester.get('end_date'):
|
||||
end = str(semester.get('end_date'))
|
||||
elif start:
|
||||
end = datetime.now().strftime('%Y-%m-%d')
|
||||
else:
|
||||
end = None
|
||||
return start, end
|
||||
|
||||
@staticmethod
|
||||
async def add_points(
|
||||
student_ids: List[int],
|
||||
@@ -48,39 +60,23 @@ class ConductService:
|
||||
if abs(points_change) > 100:
|
||||
return {"success": False, "message": "单次加减分不能超过100分"}
|
||||
|
||||
# 获取操作人角色
|
||||
role = await PermissionChecker.get_user_role(recorder_id)
|
||||
# 获取操作人权限组与加减分上限
|
||||
limits = await PermissionChecker.get_score_limits(recorder_id)
|
||||
if not limits["can_manage_conduct"]:
|
||||
return {"success": False, "message": "无权进行加减分操作"}
|
||||
|
||||
# 权限验证
|
||||
if role == "班主任":
|
||||
# 班主任无限制
|
||||
pass
|
||||
elif role == "班长":
|
||||
# 班长限制 ±5分
|
||||
if points_change > settings.MONITOR_MAX_ADD or points_change < settings.MONITOR_MAX_SUBTRACT:
|
||||
return {"success": False, "message": f"班长单次只能加减{settings.MONITOR_MAX_ADD}分以内"}
|
||||
elif role == "劳动委员":
|
||||
# 劳动委员可加减分,±LABOR_REP_MAX_POINTS以内
|
||||
if abs(points_change) > settings.LABOR_REP_MAX_POINTS:
|
||||
return {"success": False, "message": f"劳动委员单次只能加减{settings.LABOR_REP_MAX_POINTS}分以内"}
|
||||
elif role == "志愿委员":
|
||||
# 志愿委员只能加分,上限VOLUNTEER_REP_MAX_POINTS
|
||||
if points_change < 0:
|
||||
return {"success": False, "message": "志愿委员只能加分"}
|
||||
if points_change > settings.VOLUNTEER_REP_MAX_POINTS:
|
||||
return {"success": False, "message": f"志愿委员单次最多加{settings.VOLUNTEER_REP_MAX_POINTS}分"}
|
||||
elif role == "学习委员":
|
||||
# 学习委员可加减分,±STUDY_COMMISSIONER_MAX_POINTS以内
|
||||
if abs(points_change) > settings.STUDY_COMMISSIONER_MAX_POINTS:
|
||||
return {"success": False, "message": f"学习委员单次只能加减{settings.STUDY_COMMISSIONER_MAX_POINTS}分以内"}
|
||||
elif role == "考勤委员":
|
||||
# 考勤委员只能扣分,上限ATTENDANCE_REP_MAX_POINTS
|
||||
if points_change > 0:
|
||||
return {"success": False, "message": "考勤委员只能进行扣分操作"}
|
||||
if abs(points_change) > settings.ATTENDANCE_REP_MAX_POINTS:
|
||||
return {"success": False, "message": f"考勤委员单次最多扣{settings.ATTENDANCE_REP_MAX_POINTS}分"}
|
||||
if not limits["can_add"]:
|
||||
return {"success": False, "message": "当前权限组不允许加分"}
|
||||
max_add = limits["max_add"]
|
||||
if max_add is not None and points_change > max_add:
|
||||
return {"success": False, "message": f"单次加分不能超过{max_add}分"}
|
||||
else:
|
||||
return {"success": False, "message": "无权进行此操作"}
|
||||
if not limits["can_subtract"]:
|
||||
return {"success": False, "message": "当前权限组不允许扣分"}
|
||||
max_subtract = limits["max_subtract"]
|
||||
if max_subtract is not None and abs(points_change) > max_subtract:
|
||||
return {"success": False, "message": f"单次扣分不能超过{max_subtract}分"}
|
||||
|
||||
# 批量处理
|
||||
success_count = 0
|
||||
@@ -106,20 +102,10 @@ class ConductService:
|
||||
reason=reason,
|
||||
recorder_id=recorder_id,
|
||||
recorder_name=recorder_name,
|
||||
related_type=related_type
|
||||
related_type=related_type,
|
||||
semester_id=semester_id
|
||||
)
|
||||
|
||||
# 自动关联到当前学期
|
||||
if semester_id and record_id:
|
||||
try:
|
||||
from utils.database import execute_update as _exec_update
|
||||
await _exec_update(
|
||||
"UPDATE conduct_records SET semester_id = %s WHERE record_id = %s AND semester_id IS NULL",
|
||||
(semester_id, record_id)
|
||||
)
|
||||
except Exception:
|
||||
pass # 关联失败不影响主流程
|
||||
|
||||
# 更新学生总分
|
||||
await StudentModel.update_total_points(student_id, points_change)
|
||||
|
||||
@@ -186,10 +172,9 @@ class ConductService:
|
||||
if not record_id or record_id <= 0:
|
||||
return {"success": False, "message": "无效的记录ID"}
|
||||
|
||||
# 检查权限:只有班主任可以反撤销
|
||||
role = await PermissionChecker.get_user_role(restorer_id)
|
||||
if role != "班主任":
|
||||
return {"success": False, "message": "仅班主任可反撤销记录"}
|
||||
# 检查权限:需要反撤销权限
|
||||
if not await PermissionChecker.check_can_restore(restorer_id):
|
||||
return {"success": False, "message": "无权限反撤销记录"}
|
||||
|
||||
# 获取原记录信息
|
||||
record = await ConductModel.get_record_by_id(record_id)
|
||||
@@ -231,7 +216,8 @@ class ConductService:
|
||||
related_type: Optional[str] = None,
|
||||
reason_prefix: Optional[str] = None,
|
||||
is_revoked: Optional[int] = None,
|
||||
reason_search: Optional[str] = None
|
||||
reason_search: Optional[str] = None,
|
||||
semester_id: Optional[int] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""获取历史记录"""
|
||||
# 空字符串转为None
|
||||
@@ -248,11 +234,20 @@ class ConductService:
|
||||
if related_type and related_type not in ('manual', 'homework', 'attendance'):
|
||||
return {"records": [], "page": page, "page_size": page_size, "total": 0, "total_pages": 0}
|
||||
|
||||
role = await PermissionChecker.get_user_role(user_id)
|
||||
# 解析学期过滤条件(未关联学期的历史记录按学期日期范围兜底)
|
||||
semester_start_date = None
|
||||
semester_end_date = None
|
||||
if semester_id:
|
||||
semester = await SemesterModel.get_by_id(semester_id)
|
||||
if not semester:
|
||||
return {"records": [], "page": page, "page_size": page_size, "total": 0, "total_pages": 0}
|
||||
semester_start_date, semester_end_date = ConductService._resolve_semester_range(semester)
|
||||
|
||||
can_view_all = await PermissionChecker.check_permission(user_id, "view_all_records")
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
# 班主任/班长/志愿委员可查看全班
|
||||
if role in ["班主任", "班长", "志愿委员"]:
|
||||
# 拥有查看全班权限的权限组可查看全班记录
|
||||
if can_view_all:
|
||||
if grouped:
|
||||
return await ConductModel.get_grouped_records(
|
||||
student_id=student_id,
|
||||
@@ -263,7 +258,10 @@ class ConductService:
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
is_revoked=is_revoked,
|
||||
reason_search=reason_search
|
||||
reason_search=reason_search,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
|
||||
records = await ConductModel.get_all_records(
|
||||
@@ -275,7 +273,10 @@ class ConductService:
|
||||
related_type=related_type,
|
||||
reason_prefix=reason_prefix,
|
||||
is_revoked=is_revoked,
|
||||
reason_search=reason_search
|
||||
reason_search=reason_search,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
|
||||
# 获取总数
|
||||
@@ -303,7 +304,10 @@ class ConductService:
|
||||
if is_revoked is not None:
|
||||
count_conditions.append("cr.is_revoked = %s")
|
||||
count_params.append(1 if is_revoked else 0)
|
||||
count_where = " AND ".join(count_conditions)
|
||||
count_where, count_params = _append_semester_filter(
|
||||
" AND ".join(count_conditions), count_params,
|
||||
semester_id, semester_start_date, semester_end_date
|
||||
)
|
||||
count_sql = f"""
|
||||
SELECT COUNT(*) as total FROM conduct_records cr
|
||||
JOIN students s ON cr.student_id = s.student_id
|
||||
@@ -320,13 +324,19 @@ class ConductService:
|
||||
offset=offset,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
recorder_id=user_id
|
||||
recorder_id=user_id,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
total = await ConductModel.count_student_records(
|
||||
student_id=student_id,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
recorder_id=user_id
|
||||
recorder_id=user_id,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
else:
|
||||
# 查看自己提交的记录
|
||||
@@ -335,12 +345,18 @@ class ConductService:
|
||||
limit=page_size,
|
||||
offset=offset,
|
||||
start_date=start_date,
|
||||
end_date=end_date
|
||||
end_date=end_date,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
total = await ConductModel.count_records_by_recorder(
|
||||
recorder_id=user_id,
|
||||
start_date=start_date,
|
||||
end_date=end_date
|
||||
end_date=end_date,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -350,3 +366,117 @@ class ConductService:
|
||||
"total": total,
|
||||
"total_pages": (total + page_size - 1) // page_size
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def get_student_summary(
|
||||
user_id: int,
|
||||
student_id: int,
|
||||
semester_id: Optional[int] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""获取学生个人操行分汇总(基础分/加分/减分/月度分/月度理由汇总)"""
|
||||
if not await PermissionChecker.check_permission(user_id, "view_all_records"):
|
||||
return {"success": False, "message": "无权查看学生操行分汇总"}
|
||||
|
||||
student = await StudentModel.get_by_id(student_id)
|
||||
if not student:
|
||||
return {"success": False, "message": "学生不存在"}
|
||||
|
||||
semester_info = None
|
||||
semester_start_date = None
|
||||
semester_end_date = None
|
||||
if semester_id:
|
||||
semester = await SemesterModel.get_by_id(semester_id)
|
||||
if not semester:
|
||||
return {"success": False, "message": "学期不存在"}
|
||||
semester_info = {
|
||||
"semester_id": semester["semester_id"],
|
||||
"semester_name": semester["semester_name"],
|
||||
"start_date": semester.get("start_date"),
|
||||
"end_date": semester.get("end_date"),
|
||||
"is_archived": bool(semester.get("is_archived"))
|
||||
}
|
||||
semester_start_date, semester_end_date = ConductService._resolve_semester_range(semester)
|
||||
|
||||
stats = await ConductModel.get_student_monthly_stats(
|
||||
student_id=student_id,
|
||||
semester_id=semester_id,
|
||||
semester_start_date=semester_start_date,
|
||||
semester_end_date=semester_end_date
|
||||
)
|
||||
|
||||
base_points = settings.STUDENT_INITIAL_POINTS
|
||||
months_map: Dict[str, Dict[str, Any]] = {}
|
||||
bonus_total = 0
|
||||
deduction_total = 0
|
||||
record_count = 0
|
||||
|
||||
for row in stats:
|
||||
month = row.get("month") or "未记录"
|
||||
points_change = int(row.get("points_change") or 0)
|
||||
cnt = int(row.get("cnt") or 0)
|
||||
subtotal = points_change * cnt
|
||||
|
||||
entry = months_map.setdefault(month, {
|
||||
"month": month,
|
||||
"bonus": 0,
|
||||
"deduction": 0,
|
||||
"record_count": 0,
|
||||
"bonus_reasons": [],
|
||||
"deduction_reasons": []
|
||||
})
|
||||
entry["record_count"] += cnt
|
||||
|
||||
reasons = entry["bonus_reasons"] if points_change > 0 else entry["deduction_reasons"]
|
||||
matched = None
|
||||
for item in reasons:
|
||||
if item["reason"] == (row.get("reason") or ""):
|
||||
matched = item
|
||||
break
|
||||
if matched:
|
||||
matched["points"] += subtotal
|
||||
matched["count"] += cnt
|
||||
else:
|
||||
reasons.append({
|
||||
"reason": row.get("reason") or "",
|
||||
"points": subtotal,
|
||||
"count": cnt
|
||||
})
|
||||
|
||||
if points_change > 0:
|
||||
entry["bonus"] += subtotal
|
||||
bonus_total += subtotal
|
||||
else:
|
||||
entry["deduction"] += subtotal
|
||||
deduction_total += subtotal
|
||||
record_count += cnt
|
||||
|
||||
months = []
|
||||
running_score = base_points
|
||||
for month in sorted(months_map.keys()):
|
||||
entry = months_map[month]
|
||||
entry["start_score"] = running_score
|
||||
entry["net"] = entry["bonus"] + entry["deduction"]
|
||||
running_score += entry["net"]
|
||||
entry["end_score"] = running_score
|
||||
months.append(entry)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"student": {
|
||||
"student_id": student["student_id"],
|
||||
"student_no": student["student_no"],
|
||||
"name": student["name"],
|
||||
"total_points": student["total_points"]
|
||||
},
|
||||
"semester": semester_info,
|
||||
"base_points": base_points,
|
||||
"summary": {
|
||||
"bonus_total": bonus_total,
|
||||
"deduction_total": deduction_total,
|
||||
"net_change": bonus_total + deduction_total,
|
||||
"computed_total": base_points + bonus_total + deduction_total,
|
||||
"current_total_points": student["total_points"],
|
||||
"record_count": record_count
|
||||
},
|
||||
"months": months
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 邮件发送工具(SMTP)
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
import asyncio
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
from email.utils import formataddr
|
||||
from typing import Tuple
|
||||
|
||||
from config import settings
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class EmailSender:
|
||||
"""SMTP 邮件发送(标准库实现,无需额外依赖)"""
|
||||
|
||||
@staticmethod
|
||||
def is_configured() -> bool:
|
||||
"""检查 SMTP 是否已完整配置"""
|
||||
return bool(
|
||||
settings.SMTP_ENABLED
|
||||
and settings.SMTP_HOST
|
||||
and settings.SMTP_USER
|
||||
and settings.SMTP_PASSWORD
|
||||
and settings.SMTP_FROM
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _send_sync(to_email: str, subject: str, html_body: str) -> None:
|
||||
"""同步发送邮件(在线程池中执行)"""
|
||||
msg = EmailMessage()
|
||||
msg["Subject"] = subject
|
||||
msg["From"] = formataddr((settings.SMTP_FROM_NAME, settings.SMTP_FROM))
|
||||
msg["To"] = to_email
|
||||
msg.set_content("您的邮件客户端不支持 HTML,请使用支持 HTML 的客户端查看本邮件。")
|
||||
msg.add_alternative(html_body, subtype="html")
|
||||
|
||||
if settings.SMTP_SSL:
|
||||
with smtplib.SMTP_SSL(settings.SMTP_HOST, settings.SMTP_PORT, timeout=15) as smtp:
|
||||
smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
|
||||
smtp.send_message(msg)
|
||||
else:
|
||||
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=15) as smtp:
|
||||
smtp.ehlo()
|
||||
if settings.SMTP_STARTTLS:
|
||||
smtp.starttls()
|
||||
smtp.ehlo()
|
||||
smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
|
||||
smtp.send_message(msg)
|
||||
|
||||
@staticmethod
|
||||
async def send(to_email: str, subject: str, html_body: str) -> Tuple[bool, str]:
|
||||
"""异步发送邮件,返回 (是否成功, 提示信息)"""
|
||||
if not EmailSender.is_configured():
|
||||
return False, "邮件服务未配置"
|
||||
try:
|
||||
await asyncio.to_thread(EmailSender._send_sync, to_email, subject, html_body)
|
||||
logger.info(f"邮件发送成功: {to_email} - {subject}")
|
||||
return True, "发送成功"
|
||||
except Exception as e:
|
||||
logger.error(f"邮件发送失败: {to_email} - {e}")
|
||||
return False, f"邮件发送失败: {str(e)}"
|
||||
@@ -0,0 +1,21 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 通用校验工具
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
import re
|
||||
|
||||
EMAIL_PATTERN = re.compile(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$")
|
||||
|
||||
|
||||
def is_valid_email(email: str) -> bool:
|
||||
"""校验邮箱格式"""
|
||||
if not email or len(email) > 100:
|
||||
return False
|
||||
return bool(EMAIL_PATTERN.match(email))
|
||||
+24
-11
@@ -13,13 +13,15 @@
|
||||
|
||||
## 角色权限一览
|
||||
|
||||
| 角色 | 操行分管理 | 历史记录 | 作业扣分 | 考勤管理 | 科目管理 |
|
||||
|------|-----------|---------|---------|---------|---------|
|
||||
| 班长 | ±5分以内 | 全部(可撤销) | - | - | - |
|
||||
| 学习委员 | ±5分以内 | 自己的 | ✓ | - | ✓ |
|
||||
| 考勤委员 | - | 自己的 | - | ✓ | - |
|
||||
| 劳动委员 | ±1分(卫生值日) | 自己的 | - | - | - |
|
||||
| 志愿委员 | 仅加分 | 自己的 | - | - | - |
|
||||
> v4.0 起,班干部账号绑定权限组,功能权限与加减分上限由班主任在「管理员管理 → 权限组」中动态配置;下表为预置权限组的默认值。
|
||||
|
||||
| 角色 | 操行分管理 | 历史记录 | 个人查询 | 作业扣分 | 考勤管理 | 科目管理 |
|
||||
|------|-----------|---------|---------|---------|---------|---------|
|
||||
| 班长 | ±5分以内 | 全部(可撤销) | 可查全班 | - | - | - |
|
||||
| 学习委员 | ±5分以内 | 自己的 | - | ✓ | - | ✓ |
|
||||
| 考勤委员 | - | 自己的 | - | - | ✓ | - |
|
||||
| 劳动委员 | ±1分(卫生值日) | 自己的 | - | - | - | - |
|
||||
| 志愿委员 | 仅加分 | 自己的 | 可查全班 | - | - | - |
|
||||
|
||||
---
|
||||
|
||||
@@ -35,14 +37,20 @@
|
||||
3. 填写分数变动(±5分以内)和原因
|
||||
4. 点击"确认提交"
|
||||
|
||||
**加减分限制**:每次操作不超过±5分。
|
||||
**加减分限制**:默认每次操作不超过±5分(上限可由班主任在权限组中调整)。
|
||||
|
||||
#### 历史记录 (history.php)
|
||||
|
||||
- 可查看全班所有操行分变动记录
|
||||
- 可按时间范围和学生筛选
|
||||
- 可按时间范围、学期和学生筛选
|
||||
- **可撤销**任何人的扣分记录
|
||||
|
||||
#### 个人查询 (record_query.php)
|
||||
|
||||
- 选择学生和学期,查看该学生的基础分、加分合计、减分合计
|
||||
- 查看月度操行分(月初分/加分/减分/月末分)及每月加减分理由汇总
|
||||
- 可撤销/反撤销该学生的记录,可导出个人记录
|
||||
|
||||
---
|
||||
|
||||
### 学习委员
|
||||
@@ -121,7 +129,7 @@
|
||||
3. 以卫生值日为由进行 ±1 分操作
|
||||
4. 点击"确认提交"
|
||||
|
||||
> 限制:固定 ±1 分。
|
||||
> 限制:默认固定 ±1 分,可由班主任在权限组中调整。
|
||||
|
||||
#### 历史记录
|
||||
|
||||
@@ -139,12 +147,17 @@
|
||||
3. 以服务时长为由进行加分
|
||||
4. 点击"确认提交"
|
||||
|
||||
> 限制:仅限加分操作。
|
||||
> 限制:默认仅限加分,可由班主任在权限组中调整。
|
||||
|
||||
#### 历史记录
|
||||
|
||||
- 仅可查看自己提交的操作记录
|
||||
|
||||
#### 个人查询 (record_query.php)
|
||||
|
||||
- 选择学生和学期,查看该学生的基础分、加分、月度分及月度理由汇总
|
||||
- 可导出个人记录
|
||||
|
||||
---
|
||||
|
||||
## 修改密码 (password.php)
|
||||
|
||||
+11
-7
@@ -14,19 +14,22 @@
|
||||
|
||||
## 角色权限
|
||||
|
||||
| 角色 | 操行分管理 | 历史记录 | 作业扣分 | 考勤管理 | 科目管理 |
|
||||
|------|-----------|---------|---------|---------|---------|
|
||||
| 班长 | ±5分以内 | 全部(可撤销) | - | - | - |
|
||||
| 学习委员 | ±5分以内 | 自己的 | ✓ | - | ✓ |
|
||||
| 考勤委员 | - | 自己的 | - | ✓ | - |
|
||||
| 劳动委员 | ±1分(卫生值日) | 自己的 | - | - | - |
|
||||
| 志愿委员 | 仅加分 | 自己的 | - | - | - |
|
||||
> 功能权限与加减分上限由班主任在「管理员管理 → 权限组」中配置;下表为预置权限组的默认值。
|
||||
|
||||
| 角色 | 操行分管理 | 历史记录 | 个人查询 | 作业扣分 | 考勤管理 | 科目管理 |
|
||||
|------|-----------|---------|---------|---------|---------|---------|
|
||||
| 班长 | ±5分以内 | 全部(可撤销) | 可查全班 | - | - | - |
|
||||
| 学习委员 | ±5分以内 | 自己的 | - | ✓ | - | ✓ |
|
||||
| 考勤委员 | - | 自己的 | - | - | ✓ | - |
|
||||
| 劳动委员 | ±1分(卫生值日) | 自己的 | - | - | - | - |
|
||||
| 志愿委员 | 仅加分 | 自己的 | 可查全班 | - | - | - |
|
||||
|
||||
## 常用操作
|
||||
|
||||
### 班长
|
||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值(±5分以内)和原因
|
||||
- **撤销记录**:历史记录页 → 点击撤销按钮
|
||||
- **个人查询**:个人查询页 → 选择学生 → 查看基础分/加分/月度分及理由汇总
|
||||
|
||||
### 学习委员
|
||||
- **作业扣分**:勾选学生 → 批量加减分 → 选择未交/迟交/自定义 → 填写原因
|
||||
@@ -42,6 +45,7 @@
|
||||
|
||||
### 志愿委员
|
||||
- **加分**:以服务时长为由进行加分操作
|
||||
- **个人查询**:个人查询页 → 选择学生 → 查看基础分/加分/月度分及理由汇总
|
||||
|
||||
## 常见问题
|
||||
|
||||
|
||||
+11
-6
@@ -20,24 +20,29 @@
|
||||
|------|------|
|
||||
| 首页 | 查看学生总数、排行榜、快捷入口 |
|
||||
| 操行分管理 | 对学生加减分(无限制)、导出德育分记录 |
|
||||
| 历史记录 | 查看/导出/撤销全班记录,支持按扣分类型筛选 |
|
||||
| 历史记录 | 查看/导出/撤销全班记录,支持按学期/扣分类型筛选 |
|
||||
| 个人查询 | 按学生查询基础分、加分、月度分、月度理由汇总及明细,可导出 |
|
||||
| 作业扣分 | 发布缺交作业记录、关联扣分 |
|
||||
| 考勤管理 | 按时段(早上/中午/晚修)记录考勤、自定义扣分值 |
|
||||
| 学生管理 | 新增/编辑/删除/批量导入学生 |
|
||||
| 科目管理 | 增删改科目信息 |
|
||||
| 管理员管理 | 添加/编辑姓名和角色/删除/重置密码班干部账号 |
|
||||
| 管理员管理 | 添加/编辑姓名和权限组/禁用启用/重置密码/管理自定义权限组与加减分上限 |
|
||||
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数 |
|
||||
| 修改密码 | 修改登录密码 |
|
||||
|
||||
## 常用操作
|
||||
|
||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值和原因
|
||||
- **导出德育分**:操行分管理页 → 导出德育分记录(CSV)
|
||||
- **导出历史记录**:历史记录页 → 导出历史记录(CSV,可按日期/学生筛选)
|
||||
- **撤销记录**:历史记录页 → 点击撤销按钮
|
||||
- **导出德育分**:操行分管理页 → 导出德育分记录 → 选择学期(默认当前学期)
|
||||
- **导出历史记录**:历史记录页 → 导出(CSV,可按学期/日期/学生筛选,导出全部匹配记录)
|
||||
- **个人查询**:个人查询页 → 选择学生和学期 → 查询基础分/加分/月度分/理由汇总,点击学生姓名可直接进入
|
||||
- **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮
|
||||
- **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`)
|
||||
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息和角色
|
||||
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组
|
||||
- **绑定邮箱/找回密码**:修改密码页 → 绑定邮箱;忘记密码时在登录页点击"忘记密码?"通过邮箱重置
|
||||
- **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码
|
||||
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
||||
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
||||
- **学期管理**:学期管理页 → 创建学期(可快捷填充日期)→ 关联历史数据 → 归档(可选重置分数)
|
||||
- **排行榜筛选**:首页 → 输入百分比 → 点击筛选(抹零法,如15%显示前15%的学生)
|
||||
|
||||
|
||||
+88
-19
@@ -8,6 +8,8 @@
|
||||
4. 首次登录系统会强制要求修改密码
|
||||
|
||||
> **密码要求**:长度6-20位,必须包含大写字母、小写字母、数字、特殊符号中的至少3种。
|
||||
>
|
||||
> **忘记密码**:已绑定邮箱的管理员可点击登录页"忘记密码?",输入用户名后系统会向绑定邮箱发送重置链接(30分钟内有效、仅可使用一次)。未绑定邮箱请联系班主任处理。
|
||||
|
||||
---
|
||||
|
||||
@@ -42,13 +44,16 @@
|
||||
- **原因**:填写加减分原因(必填)
|
||||
4. 点击"确认提交"
|
||||
|
||||
> 班主任加减分无限制。
|
||||
> 加减分上限按当前账号所属权限组动态校验(允许加分/加分上限/允许扣分/扣分上限),班主任组默认无限制。弹窗中会显示本账号的具体上限。
|
||||
|
||||
#### 导出德育分记录
|
||||
1. 点击"导出德育分记录"按钮
|
||||
2. 系统自动生成CSV文件并下载
|
||||
3. 文件格式:`学号,姓名,分数,加分历史,减分记录`
|
||||
4. 历史记录以分号分隔,包含原因和分值
|
||||
2. 在弹窗中选择**学期范围**(默认当前学期,可选择某个历史学期或全部学期)
|
||||
3. 系统自动生成CSV文件并下载
|
||||
4. 文件格式:`学号,姓名,学期,基础分,加分合计,减分合计,学期得分,当前总分,加分历史,减分记录`
|
||||
5. 历史记录以分号分隔,包含原因和分值;已撤销记录不会导出
|
||||
|
||||
> 默认只导出当前学期数据,学期迭代归档后不会混入以往学期的记录。
|
||||
|
||||
---
|
||||
|
||||
@@ -57,6 +62,7 @@
|
||||
#### 查看历史记录
|
||||
- 展示所有操行分变动记录
|
||||
- 支持筛选条件:
|
||||
- **学期**:默认当前学期,可切换历史学期或全部学期
|
||||
- **开始日期** / **结束日期**:按时间范围筛选
|
||||
- **学生**:按学生筛选
|
||||
- **扣分类型**:按来源筛选(手动加减分 / 作业 / 考勤)
|
||||
@@ -66,8 +72,8 @@
|
||||
#### 导出历史记录
|
||||
1. 设置筛选条件(可选)
|
||||
2. 点击"导出历史记录"按钮
|
||||
3. 系统自动生成CSV文件并下载
|
||||
4. 文件格式:`时间,学号,姓名,分数变动,原因,操作人`
|
||||
3. 系统自动生成CSV文件并下载(导出全部匹配记录,不受分页限制)
|
||||
4. 文件格式:`时间,学号,姓名,学期,类型,分数变动,原因,操作人`
|
||||
|
||||
#### 撤销记录
|
||||
1. 在历史记录列表中找到目标记录
|
||||
@@ -153,7 +159,13 @@
|
||||
4. 系统自动解析并导入
|
||||
5. 导入结果展示成功/失败数量
|
||||
|
||||
> 导入的学生初始操行分为60分,系统自动创建学生登录账号和密码。
|
||||
> 导入的学生初始操行分为系统配置的初始分(默认60分),系统自动创建学生登录账号和密码。
|
||||
|
||||
#### 导出学生名单
|
||||
1. 点击"导出学生名单"按钮
|
||||
2. 在弹窗中勾选需要导出的字段(学号、姓名必选;宿舍号、当前操行分、家长手机号、状态可选)
|
||||
3. 点击"开始导出",生成CSV文件
|
||||
4. 文件名:`学生名单_日期.csv`
|
||||
|
||||
---
|
||||
|
||||
@@ -183,20 +195,44 @@
|
||||
- **用户名**:登录账号
|
||||
- **姓名**:真实姓名
|
||||
- **密码**:留空则自动生成8位随机密码
|
||||
- **角色**:选择角色类型
|
||||
- **绑定邮箱**:选填,绑定后该管理员可自助找回密码
|
||||
- **权限组**:选择该账号所属权限组
|
||||
3. 点击"添加"
|
||||
4. 添加成功后会显示管理员信息和初始密码(请妥善保存)
|
||||
|
||||
#### 编辑管理员
|
||||
- 点击"编辑"按钮可修改**姓名**和**角色类型**
|
||||
- 点击"编辑"按钮可修改**姓名**、**绑定邮箱**和**权限组**(邮箱留空表示解除绑定)
|
||||
- 不能修改自己的权限组;锁定权限组(班主任)的账号不可编辑
|
||||
|
||||
#### 重置密码
|
||||
1. 点击"重置密码"按钮
|
||||
2. 输入新密码
|
||||
3. 点击"确认重置"
|
||||
|
||||
#### 删除管理员
|
||||
- 点击"删除"按钮确认删除(不可恢复)
|
||||
#### 禁用/启用管理员
|
||||
- 点击"禁用/启用"切换账号状态,禁用后无法登录
|
||||
- 不能禁用当前登录的账号
|
||||
|
||||
#### 权限组管理
|
||||
页面下方为权限组列表,可查看每个组的权限项、加减分上限、成员数与说明。
|
||||
|
||||
**新建权限组**:
|
||||
1. 点击"新建权限组"
|
||||
2. 填写权限组名称(如"纪律委员")和说明
|
||||
3. 勾选功能权限(学生管理、导出学生名单、操行分加减、撤销记录、反撤销、作业扣分、考勤管理、科目管理、管理员管理、学期管理、查看全班/个人查询、数据导出、系统升级等)
|
||||
4. 设置加减分上限:
|
||||
- **允许加分** + **单次加分上限**(留空为无限制)
|
||||
- **允许扣分** + **单次扣分上限**(留空为无限制)
|
||||
5. 点击"保存"
|
||||
|
||||
**编辑权限组**:
|
||||
- 点击预置组或自定义组的"编辑"可随时调整权限与上限
|
||||
- 班主任组为系统锁定组,不可编辑、不可删除、不可分配给其他账号
|
||||
|
||||
**删除权限组**:
|
||||
- 仅自定义组可删除;组内仍有管理员时需先调整成员权限组
|
||||
|
||||
> 权限组调整后,相关管理员刷新页面或最多60秒后自动生效。
|
||||
|
||||
---
|
||||
|
||||
@@ -252,21 +288,45 @@
|
||||
|
||||
---
|
||||
|
||||
### 10. 修改密码 (password.php)
|
||||
### 10. 个人查询 (record_query.php)
|
||||
|
||||
用于快速查询单个学生的完整操行分情况。
|
||||
|
||||
#### 查询方式
|
||||
1. 选择**学生**
|
||||
2. 选择**学期**(默认当前学期,可选历史学期或全部学期)
|
||||
3. 点击"查询"
|
||||
|
||||
也可在"学生管理"或"操行分管理"页面点击学生姓名直接跳转到该学生的查询页。
|
||||
|
||||
#### 查询内容
|
||||
- **汇总卡片**:基础分、加分合计、减分合计、得分(基础分+加减分)、当前实时总分
|
||||
- **月度操行分**:月份、月初分、加分、减分、月末分、记录数
|
||||
- **月度加减分理由汇总**:按月份分别列出加分理由、减分理由(含次数与合计分值)
|
||||
- **明细记录**:该学生的所有操行分记录(分页),班主任/班长可直接撤销或反撤销
|
||||
|
||||
#### 导出个人记录
|
||||
点击"导出个人记录"按钮,生成包含汇总信息与全部明细的CSV文件(受当前学生/学期筛选影响)。
|
||||
|
||||
---
|
||||
|
||||
### 11. 修改密码 (password.php)
|
||||
|
||||
- 输入原密码和新密码
|
||||
- 新密码需符合密码强度要求
|
||||
- 修改成功后需重新登录
|
||||
- 页面下方可**绑定邮箱**(需输入当前密码):绑定后忘记密码时可在登录页自助申请重置邮件;留空保存则解除绑定
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 忘记密码怎么办?
|
||||
请联系系统管理员通过调试接口重置。
|
||||
1. 已在管理端绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送重置链接(30分钟内有效);
|
||||
2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。
|
||||
|
||||
### Q: 如何导出全班德育分记录?
|
||||
在"操行分管理"页面点击"导出德育分记录"按钮,系统会生成包含所有学生当前分数及加减分历史的CSV文件。
|
||||
在"操行分管理"页面点击"导出德育分记录"按钮,在弹窗中选择学期范围(默认当前学期),系统会生成包含所选学期内所有学生基础分、加/减分合计及加减分历史的CSV文件。
|
||||
|
||||
### Q: 如何撤销错误的加减分?
|
||||
在"历史记录"页面找到对应记录,点击"撤销"按钮。
|
||||
@@ -284,12 +344,21 @@
|
||||
### 德育分记录导出
|
||||
- **位置**:操行分管理页面
|
||||
- **格式**:CSV(UTF-8编码)
|
||||
- **字段**:学号、姓名、分数、加分历史、减分记录
|
||||
- **文件名**:`德育分记录_日期.csv`
|
||||
- **学期范围**:默认当前学期,可选历史学期或全部学期
|
||||
- **字段**:学号、姓名、学期、基础分、加分合计、减分合计、学期得分、当前总分、加分历史、减分记录
|
||||
- **说明**:已撤销记录不导出;全部学期导出时按"学生+学期"分行
|
||||
- **文件名**:`德育分记录_学期_日期.csv`
|
||||
|
||||
### 历史记录导出
|
||||
- **位置**:历史记录页面
|
||||
- **格式**:CSV(UTF-8编码)
|
||||
- **字段**:时间、学号、姓名、分数变动、原因、操作人
|
||||
- **支持筛选**:可按时间范围和学生筛选后导出
|
||||
- **文件名**:`历史记录_日期.csv`
|
||||
- **字段**:时间、学号、姓名、学期、类型、分数变动、原因、操作人
|
||||
- **支持筛选**:可按学期、时间范围、学生、类型、原因关键词筛选后导出
|
||||
- **说明**:导出全部匹配记录(不受分页限制),已撤销记录不导出
|
||||
- **文件名**:`历史记录_学期_日期.csv`
|
||||
|
||||
### 个人记录导出
|
||||
- **位置**:个人查询页面
|
||||
- **格式**:CSV(UTF-8编码)
|
||||
- **内容**:学生汇总(基础分、加分合计、减分合计、得分、当前总分)+ 全部明细记录
|
||||
- **文件名**:`个人记录_姓名_学期_日期.csv`
|
||||
+81
-22
@@ -17,11 +17,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
exit();
|
||||
}
|
||||
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
if ($role !== '班主任') {
|
||||
header('Location: /admin/dashboard.php');
|
||||
exit();
|
||||
}
|
||||
$role = current_group_name();
|
||||
require_perm('manage_admins');
|
||||
|
||||
$page_title = '管理员管理';
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
@@ -37,12 +34,26 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>用户名</th><th>姓名</th><th>角色</th><th>状态</th><th>操作</th></tr>
|
||||
<tr><th>用户名</th><th>姓名</th><th>绑定邮箱</th><th>权限组</th><th>加减分上限</th><th>状态</th><th>操作</th></tr>
|
||||
</thead>
|
||||
<tbody id="adminList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="action-bar">
|
||||
<button class="btn btn-primary" onclick="showAddGroupModal()">新建权限组</button>
|
||||
</div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>权限组</th><th>权限项</th><th>加分</th><th>扣分</th><th>成员</th><th>说明</th><th>操作</th></tr>
|
||||
</thead>
|
||||
<tbody id="groupList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加管理员模态框 -->
|
||||
@@ -61,20 +72,20 @@ include __DIR__ . '/../includes/header.php';
|
||||
<label>姓名</label>
|
||||
<input type="text" id="adminRealName" required placeholder="真实姓名">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>绑定邮箱</label>
|
||||
<input type="email" id="adminEmail" maxlength="100" placeholder="选填,用于找回密码">
|
||||
<small>绑定后可通过登录页"忘记密码"重置密码</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码</label>
|
||||
<input type="text" id="adminPassword" placeholder="留空则自动生成">
|
||||
<small>自动生成8位随机密码</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>角色</label>
|
||||
<select id="adminRole" required>
|
||||
<option value="">请选择角色</option>
|
||||
<option value='班长'>班长</option>
|
||||
<option value='学习委员'>学习委员</option>
|
||||
<option value='考勤委员'>考勤委员</option>
|
||||
<option value='劳动委员'>劳动委员</option>
|
||||
<option value='志愿委员'>志愿委员</option>
|
||||
<label>权限组</label>
|
||||
<select id="adminGroupId" required>
|
||||
<option value="">请选择权限组</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
@@ -103,14 +114,13 @@ include __DIR__ . '/../includes/header.php';
|
||||
<input type="text" id="editAdminRealName" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>角色</label>
|
||||
<select id="editAdminRole" required>
|
||||
<option value="">请选择角色</option>
|
||||
<option value='班长'>班长</option>
|
||||
<option value='学习委员'>学习委员</option>
|
||||
<option value='考勤委员'>考勤委员</option>
|
||||
<option value='劳动委员'>劳动委员</option>
|
||||
<option value='志愿委员'>志愿委员</option>
|
||||
<label>绑定邮箱</label>
|
||||
<input type="email" id="editAdminEmail" maxlength="100" placeholder="留空解除绑定">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>权限组</label>
|
||||
<select id="editAdminGroupId" required>
|
||||
<option value="">请选择权限组</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
@@ -121,6 +131,55 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 权限组模态框 -->
|
||||
<div id="groupModal" class="modal">
|
||||
<div class="modal-content" style="max-width: 640px;">
|
||||
<div class="modal-header">
|
||||
<h3 id="groupModalTitle">新建权限组</h3>
|
||||
<button class="modal-close" onclick="closeModal('groupModal')">×</button>
|
||||
</div>
|
||||
<form onsubmit="event.preventDefault(); submitGroupForm()">
|
||||
<input type="hidden" id="editGroupId">
|
||||
<div class="form-group">
|
||||
<label>权限组名称 <span style="color:red;">*</span></label>
|
||||
<input type="text" id="groupName" required maxlength="50" placeholder="如:纪律委员">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>说明</label>
|
||||
<input type="text" id="groupDescription" maxlength="255" placeholder="选填">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>权限项</label>
|
||||
<div id="groupPermissionList" style="display:grid; grid-template-columns: repeat(2, 1fr); gap:8px;"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>加减分上限</label>
|
||||
<div style="display:flex; flex-wrap:wrap; gap:16px; align-items:center;">
|
||||
<label style="display:flex; align-items:center; gap:6px;">
|
||||
<input type="checkbox" id="groupCanAdd" checked onchange="onGroupCapChange()"> 允许加分
|
||||
</label>
|
||||
<label style="display:flex; align-items:center; gap:6px;">
|
||||
单次加分上限
|
||||
<input type="number" id="groupMaxAdd" min="1" max="100" style="width:90px;" placeholder="留空=不限">
|
||||
</label>
|
||||
<label style="display:flex; align-items:center; gap:6px;">
|
||||
<input type="checkbox" id="groupCanSubtract" checked onchange="onGroupCapChange()"> 允许扣分
|
||||
</label>
|
||||
<label style="display:flex; align-items:center; gap:6px;">
|
||||
单次扣分上限
|
||||
<input type="number" id="groupMaxSubtract" min="1" max="100" style="width:90px;" placeholder="留空=不限">
|
||||
</label>
|
||||
</div>
|
||||
<small>上限必须在1-100之间,留空表示无限制</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">保存</button>
|
||||
<button type="button" class="btn" onclick="closeModal('groupModal')">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 重置密码模态框 -->
|
||||
<div id="resetPasswordModal" class="modal">
|
||||
<div class="modal-content">
|
||||
|
||||
@@ -18,12 +18,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
}
|
||||
|
||||
$page_title = '考勤管理';
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
|
||||
if (!in_array($role, ['班主任', '考勤委员'])) {
|
||||
header('Location: /admin/dashboard.php');
|
||||
exit();
|
||||
}
|
||||
$role = current_group_name();
|
||||
require_perm('manage_attendance');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
+26
-18
@@ -18,12 +18,7 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
}
|
||||
|
||||
$page_title = '操行分管理';
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
|
||||
if (!in_array($role, ['班主任', '班长', '学习委员', '考勤委员', '劳动委员', '志愿委员'])) {
|
||||
header('Location: /admin/dashboard.php');
|
||||
exit();
|
||||
}
|
||||
$role = current_group_name();
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
@@ -34,10 +29,12 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="card">
|
||||
<div class="action-bar">
|
||||
<div class="action-buttons">
|
||||
<?php if (has_perm('manage_conduct')): ?>
|
||||
<button class="btn btn-primary" onclick="showBatchPointsModal()">批量加减分</button>
|
||||
<button class="btn btn-secondary" onclick="showDormitoryPointsModal()">宿舍加分</button>
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<button class="btn btn-secondary" onclick="exportMoralityRecords()">导出德育分记录</button>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('export_data')): ?>
|
||||
<button class="btn btn-secondary" onclick="showExportMoralityModal()">导出德育分记录</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
@@ -59,6 +56,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
||||
<script src="/assets/js/modules/utils.js"></script>
|
||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
||||
@@ -92,16 +90,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>分数变动</label>
|
||||
<input type="number" id="pointsChange" required placeholder="正数为加分,负数为扣分">
|
||||
<small><?php
|
||||
$hints = [
|
||||
'班长' => '班长单次±5分以内',
|
||||
'学习委员' => '学习委员单次±5分以内',
|
||||
'考勤委员' => '考勤委员仅限扣分,单次最多扣8分',
|
||||
'劳动委员' => '劳动委员单次±1分以内',
|
||||
'志愿委员' => '志愿委员仅限加分,最多+5分',
|
||||
];
|
||||
echo $hints[$role] ?? '班主任无限制';
|
||||
?></small>
|
||||
<small id="pointsLimitHint"></small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>原因</label>
|
||||
@@ -115,6 +104,25 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 导出德育分记录模态框 -->
|
||||
<div id="exportMoralityModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3>导出德育分记录</h3>
|
||||
<button class="modal-close" onclick="closeModal('exportMoralityModal')">×</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>学期范围</label>
|
||||
<select id="exportSemesterSelect"></select>
|
||||
<small>默认导出当前学期,避免混入以往学期的记录;可选择某个历史学期或全部学期。</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" onclick="exportMoralityRecords()">开始导出</button>
|
||||
<button type="button" class="btn" onclick="closeModal('exportMoralityModal')">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 宿舍集体加分模态框 -->
|
||||
<div id="dormitoryPointsModal" class="modal">
|
||||
<div class="modal-content">
|
||||
|
||||
@@ -52,7 +52,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<?php if (has_perm('manage_upgrade')): ?>
|
||||
<!-- 升级提示模态框 -->
|
||||
<div id="upgradeModal" class="modal" style="display:none;">
|
||||
<div class="modal-content" style="max-width:520px;">
|
||||
@@ -79,10 +79,10 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</script>
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="/assets/js/dashboard.js"></script>
|
||||
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<?php if (has_perm('manage_upgrade')): ?>
|
||||
<script>
|
||||
(function() {
|
||||
var upgradeSteps = [];
|
||||
|
||||
@@ -32,7 +32,13 @@ include __DIR__ . '/../includes/header.php';
|
||||
<label class="history-grouped-label">
|
||||
<input type="checkbox" id="historyGrouped" checked onchange="loadHistory(1)"> 批次合并
|
||||
</label>
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<label class="history-grouped-label" style="display:flex; align-items:center; gap:6px;">
|
||||
学期
|
||||
<select id="historySemesterFilter" onchange="loadHistory(1)" style="padding:4px 8px; border:1px solid var(--color-border); border-radius:4px;">
|
||||
<option value="">全部学期</option>
|
||||
</select>
|
||||
</label>
|
||||
<?php if (has_perm('export_data')): ?>
|
||||
<button class="btn btn-secondary" onclick="exportHistoryRecords()">导出</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
@@ -76,7 +82,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<option value="志愿">志愿</option>
|
||||
</select>
|
||||
</div>
|
||||
<?php if ($role === '班主任' || $role === '班长'): ?>
|
||||
<?php if (has_perm('revoke_any') || has_perm('restore_records')): ?>
|
||||
<div class="filter-group">
|
||||
<label>状态</label>
|
||||
<select id="historyStatusFilter">
|
||||
@@ -99,7 +105,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<th>学生</th>
|
||||
<th style="white-space: nowrap; min-width: 80px;">操作人</th>
|
||||
<th>时间</th>
|
||||
<?php if ($role === '班主任' || $role === '班长' || $role === '考勤委员'): ?>
|
||||
<?php if (has_perm('revoke_any') || has_perm('revoke_own')): ?>
|
||||
<th>操作</th>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
|
||||
@@ -18,12 +18,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
}
|
||||
|
||||
$page_title = '作业扣分';
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
|
||||
if (!in_array($role, ['班主任', '学习委员'])) {
|
||||
header('Location: /admin/dashboard.php');
|
||||
exit();
|
||||
}
|
||||
$role = current_group_name();
|
||||
require_perm('manage_homework');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
@@ -31,6 +27,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<?php if (has_perm('manage_subjects')): ?>
|
||||
<!-- 科目管理折叠面板 -->
|
||||
<div class="card collapsible-card" style="margin-bottom: 20px;">
|
||||
<div class="collapsible-header" id="subjectPanelHeader">
|
||||
@@ -44,6 +41,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div id="subjectList" class="subject-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card">
|
||||
<div class="action-bar">
|
||||
@@ -79,14 +77,12 @@ include __DIR__ . '/../includes/header.php';
|
||||
<label>已选学生</label>
|
||||
<div id="selectedStudentsCount" class="selected-info">未选择学生</div>
|
||||
</div>
|
||||
<?php if (in_array($role, ['班主任', '学习委员'])): ?>
|
||||
<div class="form-group">
|
||||
<label>科目</label>
|
||||
<select id="hwSubjectSelect">
|
||||
<option value="">不选择科目</option>
|
||||
</select>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="form-group">
|
||||
<label>扣分类型</label>
|
||||
<div class="deduction-types" style="display: flex; flex-wrap: wrap; gap: 6px;">
|
||||
@@ -98,7 +94,6 @@ include __DIR__ . '/../includes/header.php';
|
||||
<button type="button" class="btn btn-sm" onclick="selectDeductionType(0, '')">自定义</button>
|
||||
</div>
|
||||
</div>
|
||||
<?php if (in_array($role, ['班主任', '学习委员'])): ?>
|
||||
<div class="form-group">
|
||||
<label>具体作业</label>
|
||||
<input type="text" id="hwTitle" placeholder="选填,如:第三章练习">
|
||||
@@ -107,14 +102,10 @@ include __DIR__ . '/../includes/header.php';
|
||||
<label>缴交时间</label>
|
||||
<input type="date" id="hwDeadline" value="<?php echo date('Y-m-d'); ?>">
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="form-group">
|
||||
<label>分数变动</label>
|
||||
<input type="number" id="pointsChange" required min="-5" max="5" step="1" placeholder="正数加分,负数扣分">
|
||||
<small><?php
|
||||
if ($role === '学习委员') echo '学习委员单次±5分以内';
|
||||
else echo '班主任无限制';
|
||||
?></small>
|
||||
<input type="number" id="pointsChange" required step="1" placeholder="正数加分,负数扣分">
|
||||
<small class="hw-max"></small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>原因</label>
|
||||
|
||||
@@ -18,7 +18,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
}
|
||||
|
||||
$page_title = '修改密码';
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
$role = current_group_name();
|
||||
$bound_email = $_SESSION['email'] ?? '';
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
@@ -44,6 +45,29 @@ include __DIR__ . '/../includes/header.php';
|
||||
<button type="submit" class="btn btn-primary">确认修改</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">绑定邮箱(找回密码)</div>
|
||||
<p style="font-size:13px; color:var(--color-text-secondary); margin-bottom:12px;">
|
||||
绑定邮箱后,忘记密码时可在登录页通过“忘记密码”向该邮箱发送重置链接。
|
||||
</p>
|
||||
<div class="form-group">
|
||||
<label>当前绑定邮箱</label>
|
||||
<div id="currentEmail"><?php echo $bound_email ? htmlspecialchars($bound_email) : '未绑定'; ?></div>
|
||||
</div>
|
||||
<form id="emailForm">
|
||||
<div class="form-group">
|
||||
<label>新邮箱</label>
|
||||
<input type="email" id="bindEmail" maxlength="100" placeholder="留空则解除绑定">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>当前密码 <span style="color:red;">*</span></label>
|
||||
<input type="password" id="emailPassword" required>
|
||||
<small>安全验证:绑定邮箱需要输入当前登录密码</small>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">保存邮箱</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
@@ -76,6 +100,29 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
||||
showToast(res?.message || '密码修改失败', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('emailForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const email = document.getElementById('bindEmail').value.trim();
|
||||
const password = document.getElementById('emailPassword').value;
|
||||
if (!password) {
|
||||
showToast('请输入当前密码', 'warning');
|
||||
return;
|
||||
}
|
||||
const res = await apiPost('/api/auth/bind-email', {
|
||||
password: password,
|
||||
email: email
|
||||
});
|
||||
if (res && res.success) {
|
||||
const bound = res.data && res.data.email ? res.data.email : '';
|
||||
document.getElementById('currentEmail').textContent = bound || '未绑定';
|
||||
document.getElementById('bindEmail').value = '';
|
||||
document.getElementById('emailPassword').value = '';
|
||||
showToast(res.message || '邮箱保存成功');
|
||||
} else {
|
||||
showToast(res?.message || '邮箱保存失败', 'error');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -0,0 +1,114 @@
|
||||
<?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" style="min-width: 220px;">
|
||||
<label>学生</label>
|
||||
<select id="queryStudentId" onchange="onQueryStudentChange()">
|
||||
<option value="">-- 请选择学生 --</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>学期</label>
|
||||
<select id="querySemesterId" onchange="onQuerySemesterChange()"></select>
|
||||
</div>
|
||||
<div class="filter-group" style="flex: 0 0 auto;">
|
||||
<button class="btn btn-primary" onclick="queryStudentRecords(1)">查询</button>
|
||||
</div>
|
||||
<div class="filter-group" style="flex: 0 0 auto;">
|
||||
<button class="btn btn-secondary" onclick="exportStudentRecords()">导出个人记录</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="queryPlaceholder" style="text-align: center; color: var(--color-text-secondary); padding: 32px 0;">
|
||||
请选择学生后点击“查询”,查看基础分、加分、月度分及月度加减分理由汇总
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="queryResult" style="display: none;">
|
||||
<div class="card">
|
||||
<div class="card-title" id="queryStudentTitle">学生汇总</div>
|
||||
<div class="stats-grid" id="querySummaryCards"></div>
|
||||
<div id="querySummaryHint" style="font-size: 12px; color: var(--color-text-secondary);"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">月度操行分</div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>月份</th>
|
||||
<th>月初分</th>
|
||||
<th>加分</th>
|
||||
<th>减分</th>
|
||||
<th>月末分</th>
|
||||
<th>记录数</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="queryMonthlyList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">月度加减分理由汇总</div>
|
||||
<div id="queryReasonSummary"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">明细记录</div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>类型</th>
|
||||
<th>分值</th>
|
||||
<th>原因</th>
|
||||
<th>操作人</th>
|
||||
<th style="white-space: nowrap;">时间</th>
|
||||
<?php if (has_perm('revoke_any') || has_perm('revoke_own')): ?>
|
||||
<th>状态/操作</th>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="queryRecordList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pagination" id="queryPagination"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>', userId: <?php echo intval($_SESSION['user_id']); ?> };</script>
|
||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
||||
<script src="/assets/js/modules/utils.js"></script>
|
||||
<script src="/assets/js/record-query.js"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -17,11 +17,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
exit();
|
||||
}
|
||||
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
if ($role !== '班主任') {
|
||||
header('Location: /admin/dashboard.php');
|
||||
exit();
|
||||
}
|
||||
$role = current_group_name();
|
||||
require_perm('manage_semesters');
|
||||
|
||||
$page_title = '学期管理';
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
|
||||
+36
-14
@@ -18,7 +18,7 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
}
|
||||
|
||||
$page_title = '学生管理';
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
$role = current_group_name();
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
@@ -28,10 +28,13 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="card">
|
||||
<div class="action-bar">
|
||||
<div class="action-buttons">
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<?php if (has_perm('manage_students')): ?>
|
||||
<button class="btn btn-primary" onclick="showImportModal()">导入学生</button>
|
||||
<button class="btn btn-primary" onclick="showAddStudentModal()">新增学生</button>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('export_students')): ?>
|
||||
<button class="btn btn-secondary" onclick="showExportStudentsModal()">导出学生名单</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="search-bar">
|
||||
<input type="text" id="searchInput" placeholder="搜索姓名/学号">
|
||||
@@ -48,7 +51,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<th>姓名</th>
|
||||
<th>宿舍号</th>
|
||||
<th>操行分</th>
|
||||
<?php if ($role === '班主任'): ?><th>家长手机号</th><?php endif; ?>
|
||||
<?php if (has_perm('manage_students')): ?><th>家长手机号</th><?php endif; ?>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -170,13 +173,41 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</script>
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
||||
<script src="/assets/js/modules/utils.js"></script>
|
||||
<script src="/assets/js/modules/student-mgmt.js"></script>
|
||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
||||
<script src="/assets/js/students-manage.js"></script>
|
||||
|
||||
<!-- 导出学生名单模态框 -->
|
||||
<div id="exportStudentsModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3>导出学生名单</h3>
|
||||
<button class="modal-close" onclick="closeModal('exportStudentsModal')">×</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>导出字段</label>
|
||||
<div style="display:grid; grid-template-columns: repeat(2, 1fr); gap:8px;">
|
||||
<label><input type="checkbox" class="export-student-col" value="student_no" checked disabled> 学号</label>
|
||||
<label><input type="checkbox" class="export-student-col" value="name" checked disabled> 姓名</label>
|
||||
<label><input type="checkbox" class="export-student-col" value="dormitory_number" checked> 宿舍号</label>
|
||||
<label><input type="checkbox" class="export-student-col" value="total_points" checked> 当前操行分</label>
|
||||
<?php if (has_perm('manage_students')): ?>
|
||||
<label><input type="checkbox" class="export-student-col" value="parent_phone"> 家长手机号</label>
|
||||
<?php endif; ?>
|
||||
<label><input type="checkbox" class="export-student-col" value="status" checked> 状态</label>
|
||||
</div>
|
||||
<small>导出全班学生名单(CSV,可用Excel打开)</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" onclick="exportStudents()">开始导出</button>
|
||||
<button type="button" class="btn" onclick="closeModal('exportStudentsModal')">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 批量加减分模态框(共用) -->
|
||||
<div id="batchPointsModal" class="modal">
|
||||
<div class="modal-content">
|
||||
@@ -192,16 +223,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>分数变动</label>
|
||||
<input type="number" id="pointsChange" required placeholder="正数为加分,负数为扣分">
|
||||
<small><?php
|
||||
$hints = [
|
||||
'班长' => '班长单次±5分以内',
|
||||
'学习委员' => '学习委员单次±5分以内',
|
||||
'考勤委员' => '考勤委员仅限扣分,单次最多扣8分',
|
||||
'劳动委员' => '劳动委员单次±1分以内',
|
||||
'志愿委员' => '志愿委员仅限加分,最多+5分',
|
||||
];
|
||||
echo $hints[$role] ?? '班主任无限制';
|
||||
?></small>
|
||||
<small id="pointsLimitHint"></small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>原因</label>
|
||||
|
||||
@@ -13,8 +13,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
exit();
|
||||
}
|
||||
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
if ($role !== '班主任') {
|
||||
$role = current_group_name();
|
||||
if (!has_perm('manage_upgrade')) {
|
||||
echo json_encode(['needs_upgrade' => false]);
|
||||
exit();
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
exit();
|
||||
}
|
||||
|
||||
$role = $_SESSION['role'] ?? '';
|
||||
if ($role !== '班主任') {
|
||||
$role = current_group_name();
|
||||
if (!has_perm('manage_upgrade')) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['success' => false, 'error' => '权限不足']);
|
||||
exit();
|
||||
|
||||
@@ -153,12 +153,17 @@ if ($tokenUserId === null || intval($tokenUserId) !== intval($data['user_id']))
|
||||
exit();
|
||||
}
|
||||
|
||||
// 设置 Session 变量
|
||||
$_SESSION['user_id'] = $data['user_id'];
|
||||
$_SESSION['user_type'] = $data['user_type'];
|
||||
$_SESSION['username'] = $data['username'];
|
||||
$_SESSION['real_name'] = $data['real_name'] ?? '';
|
||||
$_SESSION['role'] = $data['role'] ?? '';
|
||||
// 设置 Session 变量(权限组与权限以后端返回为准,避免客户端伪造)
|
||||
$apiUser = $tokenData['data'] ?? [];
|
||||
$_SESSION['user_id'] = $apiUser['user_id'] ?? $data['user_id'];
|
||||
$_SESSION['user_type'] = $apiUser['user_type'] ?? $data['user_type'];
|
||||
$_SESSION['username'] = $apiUser['username'] ?? $data['username'];
|
||||
$_SESSION['real_name'] = $apiUser['real_name'] ?? ($data['real_name'] ?? '');
|
||||
$_SESSION['email'] = $apiUser['email'] ?? '';
|
||||
$_SESSION['role'] = $apiUser['role'] ?? '';
|
||||
$_SESSION['permissions'] = is_array($apiUser['permissions'] ?? null) ? $apiUser['permissions'] : [];
|
||||
$_SESSION['group'] = $apiUser['group'] ?? null;
|
||||
$_SESSION['permissions_synced_at'] = time();
|
||||
$_SESSION['login_time'] = time();
|
||||
$_SESSION['jwt_token'] = $token;
|
||||
|
||||
|
||||
@@ -746,6 +746,15 @@ tr:hover {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
/* 分值颜色(表格/统计卡片通用) */
|
||||
.plus {
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
.minus {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.record-reason {
|
||||
flex: 1;
|
||||
margin: 0 15px;
|
||||
|
||||
+232
-10
@@ -10,8 +10,99 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const PERMISSION_LABELS = {
|
||||
manage_students: '学生管理',
|
||||
export_students: '导出学生名单',
|
||||
manage_conduct: '操行分加减',
|
||||
revoke_any: '撤销任何记录',
|
||||
revoke_own: '撤销自己的记录',
|
||||
restore_records: '反撤销记录',
|
||||
manage_homework: '作业扣分',
|
||||
manage_attendance: '考勤管理',
|
||||
manage_subjects: '科目管理',
|
||||
manage_admins: '管理员/权限组管理',
|
||||
manage_semesters: '学期管理',
|
||||
view_all_records: '查看全班/个人查询',
|
||||
export_data: '导出德育分/历史',
|
||||
manage_upgrade: '系统升级'
|
||||
};
|
||||
|
||||
let currentEditUserId = null;
|
||||
let currentResetUserId = null;
|
||||
let groupsCache = [];
|
||||
|
||||
function groupCapsText(group) {
|
||||
const add = group.can_add_points
|
||||
? (group.max_add_points ? ('+' + group.max_add_points + '以内') : '不限')
|
||||
: '禁止';
|
||||
const subtract = group.can_subtract_points
|
||||
? (group.max_subtract_points ? ('-' + group.max_subtract_points + '以内') : '不限')
|
||||
: '禁止';
|
||||
return { add: add, subtract: subtract };
|
||||
}
|
||||
|
||||
function permissionSummary(group) {
|
||||
const permissions = group.permissions_data || {};
|
||||
const names = Object.keys(PERMISSION_LABELS)
|
||||
.filter(key => permissions[key])
|
||||
.map(key => PERMISSION_LABELS[key]);
|
||||
return names.length ? names.join('、') : '无';
|
||||
}
|
||||
|
||||
async function loadGroups() {
|
||||
const res = await apiGet('/api/admin/permission-groups');
|
||||
if (!res || !res.success) {
|
||||
showToast((res && res.message) || '获取权限组失败', 'error');
|
||||
return;
|
||||
}
|
||||
groupsCache = res.data.groups || [];
|
||||
|
||||
const options = groupsCache
|
||||
.filter(group => !group.is_locked)
|
||||
.map(group => `<option value="${group.group_id}">${escapeHtml(group.group_name)}</option>`)
|
||||
.join('');
|
||||
const placeholder = '<option value="">请选择权限组</option>';
|
||||
document.getElementById('adminGroupId').innerHTML = placeholder + options;
|
||||
document.getElementById('editAdminGroupId').innerHTML = placeholder + options;
|
||||
|
||||
renderGroupTable();
|
||||
}
|
||||
|
||||
function renderGroupTable() {
|
||||
let html = '';
|
||||
groupsCache.forEach(group => {
|
||||
const caps = groupCapsText(group);
|
||||
const badges = [];
|
||||
if (group.is_locked) {
|
||||
badges.push('<span class="subject-status subject-status-active">锁定</span>');
|
||||
} else if (group.is_system) {
|
||||
badges.push('<span class="subject-status">预置</span>');
|
||||
}
|
||||
let actions = '<span class="text-muted">-</span>';
|
||||
if (!group.is_locked) {
|
||||
const deleteItem = group.is_system
|
||||
? ''
|
||||
: `<a class="danger" onclick="deleteGroup(${group.group_id}, '${escapeHtml(group.group_name)}')">删除</a>`;
|
||||
actions = `<div class="action-dropdown">
|
||||
<button class="btn btn-sm action-dropdown-toggle" onclick="toggleActionDropdown(this)">操作 ▼</button>
|
||||
<div class="action-dropdown-menu">
|
||||
<a onclick="showEditGroupModal(${group.group_id})">编辑</a>
|
||||
${deleteItem}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
html += `<tr>
|
||||
<td>${escapeHtml(group.group_name)} ${badges.join(' ')}</td>
|
||||
<td style="max-width: 340px; white-space: normal;">${escapeHtml(permissionSummary(group))}</td>
|
||||
<td>${caps.add}</td>
|
||||
<td>${caps.subtract}</td>
|
||||
<td>${group.member_count || 0}</td>
|
||||
<td>${escapeHtml(group.description || '-')}</td>
|
||||
<td>${actions}</td>
|
||||
</tr>`;
|
||||
});
|
||||
document.getElementById('groupList').innerHTML = html || '<tr><td colspan="7" style="text-align:center;">暂无权限组</td></tr>';
|
||||
}
|
||||
|
||||
async function loadAdmins() {
|
||||
const res = await apiGet('/api/admin/list');
|
||||
@@ -21,16 +112,26 @@ async function loadAdmins() {
|
||||
const isActive = admin.status === 1;
|
||||
const statusClass = isActive ? 'subject-status-active' : 'subject-status-inactive';
|
||||
const statusText = isActive ? '启用' : '禁用';
|
||||
const caps = {
|
||||
add: admin.can_add_points ? (admin.max_add_points ? ('+' + admin.max_add_points + '以内') : '不限') : '禁止',
|
||||
subtract: admin.can_subtract_points ? (admin.max_subtract_points ? ('-' + admin.max_subtract_points + '以内') : '不限') : '禁止'
|
||||
};
|
||||
const canEdit = !admin.is_locked && admin.group_id;
|
||||
const editItem = canEdit
|
||||
? `<a onclick="showEditAdminModal(${admin.user_id}, '${escapeHtml(admin.username)}', '${escapeHtml(admin.real_name)}', ${admin.group_id}, '${escapeHtml(admin.email || '')}')">编辑</a>`
|
||||
: '';
|
||||
html += `<tr>
|
||||
<td>${escapeHtml(admin.username)}</td>
|
||||
<td>${escapeHtml(admin.real_name)}</td>
|
||||
<td>${escapeHtml(admin.role_type)}</td>
|
||||
<td>${admin.email ? escapeHtml(admin.email) : '<span class="text-muted">未绑定</span>'}</td>
|
||||
<td>${escapeHtml(admin.group_name || admin.role_type || '-')}${admin.is_locked ? ' <span class="subject-status subject-status-active">锁定</span>' : ''}</td>
|
||||
<td>加${caps.add} / 扣${caps.subtract}</td>
|
||||
<td><span class="subject-status ${statusClass}">${statusText}</span></td>
|
||||
<td>
|
||||
<div class="action-dropdown">
|
||||
<button class="btn btn-sm action-dropdown-toggle" onclick="toggleActionDropdown(this)">操作 ▼</button>
|
||||
<div class="action-dropdown-menu">
|
||||
<a onclick="showEditAdminModal(${admin.user_id}, '${escapeHtml(admin.username)}', '${escapeHtml(admin.real_name)}', '${escapeHtml(admin.role_type)}')">编辑</a>
|
||||
${editItem}
|
||||
<a onclick="resetAdminPassword(${admin.user_id}, '${escapeHtml(admin.real_name)}')">重置密码</a>
|
||||
<a onclick="unlockUser('${escapeHtml(admin.username)}', '${escapeHtml(admin.real_name)}')">解锁</a>
|
||||
<a class="${isActive ? 'danger' : ''}" onclick="toggleAdminStatus(${admin.user_id}, '${escapeHtml(admin.real_name)}', ${isActive ? 1 : 0})">${isActive ? '禁用' : '启用'}</a>
|
||||
@@ -40,33 +141,35 @@ async function loadAdmins() {
|
||||
</tr>`;
|
||||
});
|
||||
if (res.data.admins.length === 0) {
|
||||
html = '<tr><td colspan="5" style="text-align:center;">暂无管理员</td></tr>';
|
||||
html = '<tr><td colspan="7" style="text-align:center;">暂无管理员</td></tr>';
|
||||
}
|
||||
document.getElementById('adminList').innerHTML = html;
|
||||
}
|
||||
}
|
||||
|
||||
function showEditAdminModal(userId, username, realName, roleType) {
|
||||
function showEditAdminModal(userId, username, realName, groupId, email) {
|
||||
currentEditUserId = userId;
|
||||
document.getElementById('editAdminUserId').value = userId;
|
||||
document.getElementById('editAdminUsername').value = username;
|
||||
document.getElementById('editAdminRealName').value = realName;
|
||||
document.getElementById('editAdminRole').value = roleType;
|
||||
document.getElementById('editAdminGroupId').value = groupId || '';
|
||||
document.getElementById('editAdminEmail').value = email || '';
|
||||
document.getElementById('editAdminModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
async function submitEditAdmin() {
|
||||
if (!currentEditUserId) return;
|
||||
|
||||
const roleType = document.getElementById('editAdminRole').value;
|
||||
if (!roleType) {
|
||||
showToast('请选择角色', 'warning');
|
||||
const groupId = parseInt(document.getElementById('editAdminGroupId').value);
|
||||
if (!groupId) {
|
||||
showToast('请选择权限组', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await apiPut(`/api/admin/update/${currentEditUserId}`, {
|
||||
real_name: document.getElementById('editAdminRealName').value,
|
||||
role_type: roleType
|
||||
real_name: document.getElementById('editAdminRealName').value.trim(),
|
||||
group_id: groupId,
|
||||
email: document.getElementById('editAdminEmail').value.trim()
|
||||
});
|
||||
|
||||
if (res && res.success) {
|
||||
@@ -141,14 +244,133 @@ async function submitResetPassword() {
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 权限组管理 ==========
|
||||
|
||||
function renderPermissionCheckboxes(permissions) {
|
||||
const container = document.getElementById('groupPermissionList');
|
||||
container.innerHTML = Object.keys(PERMISSION_LABELS).map(key =>
|
||||
`<label style="display:flex; align-items:center; gap:6px;">
|
||||
<input type="checkbox" class="group-perm" value="${key}"${permissions[key] ? ' checked' : ''}> ${PERMISSION_LABELS[key]}
|
||||
</label>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
function onGroupCapChange() {
|
||||
const canAdd = document.getElementById('groupCanAdd').checked;
|
||||
const canSubtract = document.getElementById('groupCanSubtract').checked;
|
||||
document.getElementById('groupMaxAdd').disabled = !canAdd;
|
||||
document.getElementById('groupMaxSubtract').disabled = !canSubtract;
|
||||
if (!canAdd) document.getElementById('groupMaxAdd').value = '';
|
||||
if (!canSubtract) document.getElementById('groupMaxSubtract').value = '';
|
||||
}
|
||||
|
||||
function showAddGroupModal() {
|
||||
document.getElementById('groupModalTitle').textContent = '新建权限组';
|
||||
document.getElementById('editGroupId').value = '';
|
||||
document.getElementById('groupName').value = '';
|
||||
document.getElementById('groupDescription').value = '';
|
||||
document.getElementById('groupCanAdd').checked = true;
|
||||
document.getElementById('groupCanSubtract').checked = true;
|
||||
document.getElementById('groupMaxAdd').value = '';
|
||||
document.getElementById('groupMaxSubtract').value = '';
|
||||
renderPermissionCheckboxes({});
|
||||
onGroupCapChange();
|
||||
document.getElementById('groupModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function showEditGroupModal(groupId) {
|
||||
const group = groupsCache.find(item => item.group_id === groupId);
|
||||
if (!group) return;
|
||||
if (group.is_locked) {
|
||||
showToast('该权限组已锁定,不可编辑', 'warning');
|
||||
return;
|
||||
}
|
||||
document.getElementById('groupModalTitle').textContent = '编辑权限组 - ' + group.group_name;
|
||||
document.getElementById('editGroupId').value = group.group_id;
|
||||
document.getElementById('groupName').value = group.group_name;
|
||||
document.getElementById('groupDescription').value = group.description || '';
|
||||
document.getElementById('groupCanAdd').checked = !!group.can_add_points;
|
||||
document.getElementById('groupCanSubtract').checked = !!group.can_subtract_points;
|
||||
document.getElementById('groupMaxAdd').value = group.max_add_points || '';
|
||||
document.getElementById('groupMaxSubtract').value = group.max_subtract_points || '';
|
||||
renderPermissionCheckboxes(group.permissions_data || {});
|
||||
onGroupCapChange();
|
||||
document.getElementById('groupModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
async function submitGroupForm() {
|
||||
const groupId = document.getElementById('editGroupId').value;
|
||||
const canAdd = document.getElementById('groupCanAdd').checked;
|
||||
const canSubtract = document.getElementById('groupCanSubtract').checked;
|
||||
const maxAddRaw = document.getElementById('groupMaxAdd').value;
|
||||
const maxSubtractRaw = document.getElementById('groupMaxSubtract').value;
|
||||
const maxAdd = canAdd && maxAddRaw !== '' ? parseInt(maxAddRaw) : null;
|
||||
const maxSubtract = canSubtract && maxSubtractRaw !== '' ? parseInt(maxSubtractRaw) : null;
|
||||
|
||||
if (maxAdd !== null && (isNaN(maxAdd) || maxAdd < 1 || maxAdd > 100)) {
|
||||
showToast('加分上限必须在1-100之间', 'warning');
|
||||
return;
|
||||
}
|
||||
if (maxSubtract !== null && (isNaN(maxSubtract) || maxSubtract < 1 || maxSubtract > 100)) {
|
||||
showToast('扣分上限必须在1-100之间', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
group_name: document.getElementById('groupName').value.trim(),
|
||||
description: document.getElementById('groupDescription').value.trim() || null,
|
||||
permissions: Array.from(document.querySelectorAll('.group-perm:checked')).map(el => el.value),
|
||||
can_add_points: canAdd,
|
||||
max_add_points: maxAdd,
|
||||
can_subtract_points: canSubtract,
|
||||
max_subtract_points: maxSubtract
|
||||
};
|
||||
if (!payload.group_name) {
|
||||
showToast('请填写权限组名称', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const res = groupId
|
||||
? await apiPut(`/api/admin/permission-groups/${groupId}`, payload)
|
||||
: await apiPost('/api/admin/permission-groups', payload);
|
||||
|
||||
if (res && res.success) {
|
||||
showToast(groupId ? '权限组更新成功' : '权限组创建成功');
|
||||
closeModal('groupModal');
|
||||
loadGroups();
|
||||
} else {
|
||||
showToast(res?.message || '保存失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteGroup(groupId, groupName) {
|
||||
if (!confirm(`确定要删除权限组 "${groupName}" 吗?删除后不可恢复。`)) {
|
||||
return;
|
||||
}
|
||||
const res = await apiDelete(`/api/admin/permission-groups/${groupId}`);
|
||||
if (res && res.success) {
|
||||
showToast('权限组已删除');
|
||||
loadGroups();
|
||||
} else {
|
||||
showToast(res?.message || '删除失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
loadGroups();
|
||||
loadAdmins();
|
||||
|
||||
window.loadAdmins = loadAdmins;
|
||||
window.loadGroups = loadGroups;
|
||||
window.showEditAdminModal = showEditAdminModal;
|
||||
window.submitEditAdmin = submitEditAdmin;
|
||||
window.toggleAdminStatus = toggleAdminStatus;
|
||||
window.resetAdminPassword = resetAdminPassword;
|
||||
window.unlockUser = unlockUser;
|
||||
window.submitResetPassword = submitResetPassword;
|
||||
window.showAddGroupModal = showAddGroupModal;
|
||||
window.showEditGroupModal = showEditGroupModal;
|
||||
window.submitGroupForm = submitGroupForm;
|
||||
window.deleteGroup = deleteGroup;
|
||||
window.onGroupCapChange = onGroupCapChange;
|
||||
|
||||
})();
|
||||
@@ -32,6 +32,17 @@ function initAttendanceButtons() {
|
||||
if (attendanceDeductionMap.absent > 0) {
|
||||
document.getElementById('customDeduction').value = attendanceDeductionMap.absent;
|
||||
}
|
||||
// 按权限组动态扣分上限限制自定义扣分输入
|
||||
const limits = getScoreLimits();
|
||||
const deductionInput = document.getElementById('customDeduction');
|
||||
if (deductionInput) {
|
||||
if (limits.max_subtract !== null && limits.max_subtract !== undefined) {
|
||||
deductionInput.max = limits.max_subtract;
|
||||
}
|
||||
if (!limits.can_subtract) {
|
||||
deductionInput.disabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function selectStatus(btn) {
|
||||
|
||||
@@ -112,6 +112,161 @@ function apiDelete(url) {
|
||||
return apiRequest(url, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页拉取接口全部记录(用于导出等需要完整数据的场景)
|
||||
* @param {string} url 接口地址
|
||||
* @param {object} params 查询参数(page/page_size 会被自动覆盖)
|
||||
* @returns {Promise<Array>} 全部记录
|
||||
*/
|
||||
async function apiGetAll(url, params = {}) {
|
||||
const allRecords = [];
|
||||
const pageSize = 1000;
|
||||
let page = 1;
|
||||
while (page <= 100) {
|
||||
const pageParams = { ...params, page: page, page_size: pageSize };
|
||||
const res = await apiGet(url, pageParams);
|
||||
if (!res || !res.success || !res.data || !Array.isArray(res.data.records)) {
|
||||
break;
|
||||
}
|
||||
allRecords.push(...res.data.records);
|
||||
const total = res.data.total || 0;
|
||||
if (allRecords.length >= total || res.data.records.length < pageSize) {
|
||||
break;
|
||||
}
|
||||
page++;
|
||||
}
|
||||
return allRecords;
|
||||
}
|
||||
|
||||
/**
|
||||
* CSV字段转义
|
||||
*/
|
||||
function csvEscape(value) {
|
||||
if (value === null || value === undefined) return '';
|
||||
let str = String(value).replace(/[\r\n]+/g, ' ');
|
||||
str = str.replace(/"/g, '""');
|
||||
if (/[\,\;\"\s]/.test(str)) {
|
||||
str = '"' + str + '"';
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载CSV文件(自动添加BOM以兼容Excel)
|
||||
*/
|
||||
function downloadCsv(filename, csvContent) {
|
||||
const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载学期下拉选项
|
||||
* @param {string|HTMLElement} select 下拉框DOM或ID
|
||||
* @param {object} options { includeAll: 是否包含"全部学期", selectedValue: 默认选中值 }
|
||||
* @returns {Promise<Array>} 学期列表
|
||||
*/
|
||||
async function loadSemesterOptions(select, options = {}) {
|
||||
const el = typeof select === 'string' ? document.getElementById(select) : select;
|
||||
if (!el) return [];
|
||||
const res = await apiGet('/api/semester/options');
|
||||
const semesters = (res && res.success && Array.isArray(res.data)) ? res.data : [];
|
||||
const sorted = semesters.slice().sort((a, b) => (b.is_active ? 1 : 0) - (a.is_active ? 1 : 0));
|
||||
const includeAll = options.includeAll !== false;
|
||||
let html = includeAll ? '<option value="">全部学期</option>' : '';
|
||||
sorted.forEach(s => {
|
||||
const suffix = s.is_active ? '(当前)' : (s.is_archived ? '(已归档)' : '');
|
||||
html += '<option value="' + s.semester_id + '">' + escapeHtml(s.semester_name + suffix) + '</option>';
|
||||
});
|
||||
el.innerHTML = html;
|
||||
let value = options.selectedValue;
|
||||
if (value === undefined) {
|
||||
const active = sorted.find(s => s.is_active);
|
||||
value = active ? active.semester_id : '';
|
||||
}
|
||||
el.value = (value === null || value === undefined) ? '' : String(value);
|
||||
return semesters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前用户是否拥有指定权限
|
||||
*/
|
||||
function hasPermission(perm) {
|
||||
return !!(window.USER_PERMISSIONS && window.USER_PERMISSIONS[perm]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前权限组加减分上限配置
|
||||
*/
|
||||
function getScoreLimits() {
|
||||
return window.USER_SCORE_LIMITS || {
|
||||
can_add: true, max_add: null,
|
||||
can_subtract: true, max_subtract: null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成加减分上限提示文本
|
||||
*/
|
||||
function describeScoreLimits() {
|
||||
const limits = getScoreLimits();
|
||||
if (!limits.can_add && !limits.can_subtract) return '当前权限组不允许加减分';
|
||||
if (!limits.can_add) {
|
||||
return '仅限扣分' + (limits.max_subtract ? (',单次最多扣' + limits.max_subtract + '分') : '');
|
||||
}
|
||||
if (!limits.can_subtract) {
|
||||
return '仅限加分' + (limits.max_add ? (',单次最多加' + limits.max_add + '分') : '');
|
||||
}
|
||||
const parts = [];
|
||||
parts.push(limits.max_add ? ('单次加分上限' + limits.max_add + '分') : '加分无限制');
|
||||
parts.push(limits.max_subtract ? ('单次扣分上限' + limits.max_subtract + '分') : '扣分无限制');
|
||||
return parts.join(',');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将权限组上限应用到分数输入框(min/max)
|
||||
*/
|
||||
function applyScoreLimits(inputEl) {
|
||||
if (!inputEl) return;
|
||||
const limits = getScoreLimits();
|
||||
if (limits.max_add !== null && limits.max_add !== undefined) {
|
||||
inputEl.max = limits.max_add;
|
||||
} else {
|
||||
inputEl.removeAttribute('max');
|
||||
}
|
||||
if (limits.max_subtract !== null && limits.max_subtract !== undefined) {
|
||||
inputEl.min = -limits.max_subtract;
|
||||
} else {
|
||||
inputEl.removeAttribute('min');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验分值是否符合权限组上限,返回错误信息(空字符串表示通过)
|
||||
*/
|
||||
function validateScoreChange(value) {
|
||||
const limits = getScoreLimits();
|
||||
if (!value || value === 0) return '分值不能为0';
|
||||
if (value > 0) {
|
||||
if (!limits.can_add) return '当前权限组仅允许扣分';
|
||||
if (limits.max_add !== null && limits.max_add !== undefined && value > limits.max_add) {
|
||||
return '单次加分不能超过' + limits.max_add + '分';
|
||||
}
|
||||
} else {
|
||||
if (!limits.can_subtract) return '当前权限组仅允许加分';
|
||||
if (limits.max_subtract !== null && limits.max_subtract !== undefined && Math.abs(value) > limits.max_subtract) {
|
||||
return '单次扣分不能超过' + limits.max_subtract + '分';
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function showToast(message, type = 'success') {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast-${type}`;
|
||||
|
||||
@@ -10,17 +10,26 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const canViewPersonalQuery = hasPermission('view_all_records');
|
||||
const canManageConduct = hasPermission('manage_conduct');
|
||||
|
||||
async function loadStudents() {
|
||||
const res = await apiGet('/api/admin/students', {page_size: 1000});
|
||||
if (res && res.success) {
|
||||
let html = '';
|
||||
res.data.students.forEach(student => {
|
||||
const detailUrl = canViewPersonalQuery
|
||||
? `/admin/record_query.php?student_id=${student.student_id}`
|
||||
: `/admin/history.php?student_id=${student.student_id}`;
|
||||
const pointsButton = canManageConduct
|
||||
? `<button class="btn btn-sm btn-outline" onclick="showSinglePointsModal(${student.student_id}, '${escapeHtml(student.name)}')">加减分</button>`
|
||||
: '<span class="text-muted">-</span>';
|
||||
html += `<tr>
|
||||
<td><input type="checkbox" class="student-checkbox" data-id="${student.student_id}"></td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td><a href="/admin/history.php?student_id=${student.student_id}" class="link">${escapeHtml(student.name)}</a></td>
|
||||
<td><a href="${detailUrl}" class="link">${escapeHtml(student.name)}</a></td>
|
||||
<td>${student.total_points}</td>
|
||||
<td><button class="btn btn-sm btn-outline" onclick="showSinglePointsModal(${student.student_id}, '${escapeHtml(student.name)}')">加减分</button></td>
|
||||
<td>${pointsButton}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (res.data.students.length === 0) {
|
||||
@@ -35,10 +44,45 @@ function showSinglePointsModal(studentId, studentName) {
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
if (typeof preparePointsLimitHint === 'function') preparePointsLimitHint();
|
||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function initPointsLimitHint() {
|
||||
const hintEl = document.getElementById('pointsLimitHint');
|
||||
if (hintEl) hintEl.textContent = describeScoreLimits();
|
||||
}
|
||||
|
||||
async function showExportMoralityModal() {
|
||||
await loadSemesterOptions('exportSemesterSelect', { includeAll: true });
|
||||
document.getElementById('exportMoralityModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function buildExportRow(student, semesterLabel, records, basePoints) {
|
||||
const positiveRecords = records.filter(r => r.points_change > 0);
|
||||
const negativeRecords = records.filter(r => r.points_change < 0);
|
||||
const bonus = positiveRecords.reduce((sum, r) => sum + r.points_change, 0);
|
||||
const deduction = negativeRecords.reduce((sum, r) => sum + r.points_change, 0);
|
||||
return {
|
||||
student_no: student.student_no,
|
||||
name: student.name,
|
||||
semester: semesterLabel,
|
||||
base: basePoints,
|
||||
bonus: bonus,
|
||||
deduction: deduction,
|
||||
score: records.length ? basePoints + bonus + deduction : (student.total_points || 0),
|
||||
current: student.total_points || 0,
|
||||
positive: positiveRecords.map(r => `${r.reason}(+${r.points_change})`).join('; '),
|
||||
negative: negativeRecords.map(r => `${r.reason}(${r.points_change})`).join('; ')
|
||||
};
|
||||
}
|
||||
|
||||
async function exportMoralityRecords() {
|
||||
const select = document.getElementById('exportSemesterSelect');
|
||||
const semesterId = select ? select.value : '';
|
||||
const selectedOption = select && select.selectedIndex >= 0 ? select.options[select.selectedIndex] : null;
|
||||
const semesterName = selectedOption ? selectedOption.textContent.replace(/((当前|已归档))$/, '') : '全部学期';
|
||||
|
||||
showToast('正在导出德育分记录...', 'info');
|
||||
|
||||
try {
|
||||
@@ -54,65 +98,49 @@ async function exportMoralityRecords() {
|
||||
return;
|
||||
}
|
||||
|
||||
const historyRes = await apiGet('/api/admin/conduct/history', { page: 1, page_size: 1000 });
|
||||
if (!historyRes || !historyRes.success) {
|
||||
showToast('获取历史记录失败', 'error');
|
||||
return;
|
||||
}
|
||||
const params = { is_revoked: 0 };
|
||||
if (semesterId) params.semester_id = semesterId;
|
||||
const allRecords = await apiGetAll('/api/admin/conduct/history', params);
|
||||
|
||||
const allRecords = historyRes.data.records || [];
|
||||
const basePoints = parseInt(window.STUDENT_INITIAL_POINTS || 60, 10) || 60;
|
||||
|
||||
const recordsByStudent = {};
|
||||
// 按 学生 + 学期 分组
|
||||
const groups = {};
|
||||
allRecords.forEach(record => {
|
||||
const sid = record.student_id;
|
||||
if (!recordsByStudent[sid]) {
|
||||
recordsByStudent[sid] = [];
|
||||
}
|
||||
recordsByStudent[sid].push(record);
|
||||
const label = semesterId ? semesterName : (record.semester_name || '未关联学期');
|
||||
const key = record.student_id + '|' + label;
|
||||
if (!groups[key]) groups[key] = [];
|
||||
groups[key].push(record);
|
||||
});
|
||||
|
||||
const studentRecords = [];
|
||||
for (const student of students) {
|
||||
const studentRecords_list = recordsByStudent[student.student_id] || [];
|
||||
const positiveRecords = studentRecords_list.filter(r => r.points_change > 0).map(r => `${r.reason}(+${r.points_change})`);
|
||||
const negativeRecords = studentRecords_list.filter(r => r.points_change < 0).map(r => `${r.reason}(${r.points_change})`);
|
||||
|
||||
studentRecords.push({
|
||||
student_no: student.student_no,
|
||||
name: student.name,
|
||||
total_points: student.total_points || 0,
|
||||
positive_history: positiveRecords.join('; '),
|
||||
negative_history: negativeRecords.join('; ')
|
||||
const rows = [];
|
||||
students.forEach(student => {
|
||||
if (semesterId) {
|
||||
const key = student.student_id + '|' + semesterName;
|
||||
rows.push(buildExportRow(student, semesterName, groups[key] || [], basePoints));
|
||||
} else {
|
||||
const prefix = student.student_id + '|';
|
||||
const labels = Object.keys(groups).filter(k => k.indexOf(prefix) === 0);
|
||||
if (labels.length === 0) {
|
||||
rows.push(buildExportRow(student, '-', [], basePoints));
|
||||
} else {
|
||||
labels.forEach(key => {
|
||||
rows.push(buildExportRow(student, key.substring(prefix.length), groups[key], basePoints));
|
||||
});
|
||||
}
|
||||
|
||||
function escapeCsvField(field) {
|
||||
if (field === null || field === undefined) return '';
|
||||
let str = String(field).replace(/[\r\n]+/g, ' ');
|
||||
str = str.replace(/"/g, '""');
|
||||
if (/[\,\;\"\s]/.test(str)) {
|
||||
str = '"' + str + '"';
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
let csv = '\uFEFF';
|
||||
csv += '学号,姓名,分数,加分历史,减分记录\n';
|
||||
studentRecords.forEach(s => {
|
||||
csv += `${escapeCsvField(s.student_no)},${escapeCsvField(s.name)},${escapeCsvField(s.total_points)},${escapeCsvField(s.positive_history)},${escapeCsvField(s.negative_history)}\n`;
|
||||
});
|
||||
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `德育分记录_${new Date().toISOString().slice(0,10)}.csv`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
let csv = '学号,姓名,学期,基础分,加分合计,减分合计,学期得分,当前总分,加分历史,减分记录\n';
|
||||
rows.forEach(r => {
|
||||
csv += [r.student_no, r.name, r.semester, r.base, r.bonus, r.deduction, r.score, r.current, r.positive, r.negative]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
|
||||
showToast(`导出成功,共${studentRecords.length}名学生`);
|
||||
const safeSemester = (semesterName || '全部学期').replace(/[\\/:*?"<>|]/g, '_');
|
||||
downloadCsv(`德育分记录_${safeSemester}_${new Date().toISOString().slice(0,10)}.csv`, csv);
|
||||
closeModal('exportMoralityModal');
|
||||
showToast(`导出成功,共${rows.length}条学生记录`);
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
console.error('导出失败:', err);
|
||||
@@ -212,7 +240,8 @@ async function submitDormitoryPoints() {
|
||||
if (res && res.success) {
|
||||
showToast(`操作成功: ${res.data.success_count} 人成功`);
|
||||
closeModal('dormitoryPointsModal');
|
||||
loadStudents();
|
||||
loadStudents();
|
||||
initPointsLimitHint();
|
||||
} else {
|
||||
showToast(res?.message || '操作失败', 'error');
|
||||
}
|
||||
@@ -222,6 +251,7 @@ loadStudents();
|
||||
|
||||
window.loadStudents = loadStudents;
|
||||
window.showSinglePointsModal = showSinglePointsModal;
|
||||
window.showExportMoralityModal = showExportMoralityModal;
|
||||
window.exportMoralityRecords = exportMoralityRecords;
|
||||
window.showDormitoryPointsModal = showDormitoryPointsModal;
|
||||
window.onDormitorySelected = onDormitorySelected;
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const role = window.PAGE_CONFIG.role;
|
||||
let totalStudents = 0;
|
||||
|
||||
async function loadDashboard() {
|
||||
@@ -49,19 +48,27 @@ async function loadDashboard() {
|
||||
document.getElementById('dashboardStats').innerHTML = statsHtml;
|
||||
|
||||
let quickActions = '';
|
||||
if (role === '班主任' || role === '班长' || role === '学习委员' || role === '劳动委员' || role === '志愿委员') {
|
||||
if (hasPermission('manage_conduct')) {
|
||||
quickActions += '<button class="btn btn-primary" onclick="location.href=\'/admin/conduct.php\'">操行分管理</button>';
|
||||
}
|
||||
if (role === '班主任' || role === '学习委员') {
|
||||
if (hasPermission('manage_homework')) {
|
||||
quickActions += '<button class="btn btn-primary" onclick="location.href=\'/admin/homework.php\'">作业扣分</button>';
|
||||
}
|
||||
if (role === '班主任' || role === '考勤委员') {
|
||||
if (hasPermission('manage_attendance')) {
|
||||
quickActions += '<button class="btn btn-primary" onclick="location.href=\'/admin/attendance.php\'">考勤管理</button>';
|
||||
}
|
||||
if (role === '班主任') {
|
||||
quickActions += '<button class="btn btn-outline" onclick="location.href=\'/admin/students.php\'">导入学生</button>';
|
||||
if (hasPermission('manage_students')) {
|
||||
quickActions += '<button class="btn btn-outline" onclick="location.href=\'/admin/students.php\'">学生管理</button>';
|
||||
}
|
||||
if (hasPermission('manage_semesters')) {
|
||||
quickActions += '<button class="btn btn-outline" onclick="location.href=\'/admin/semesters.php\'">学期管理</button>';
|
||||
}
|
||||
if (hasPermission('export_data')) {
|
||||
quickActions += '<button class="btn btn-secondary" onclick="location.href=\'/admin/conduct.php\'">导出德育分记录</button>';
|
||||
}
|
||||
if (hasPermission('export_students')) {
|
||||
quickActions += '<button class="btn btn-secondary" onclick="location.href=\'/admin/students.php\'">导出学生名单</button>';
|
||||
}
|
||||
document.getElementById('quickActions').innerHTML = quickActions || '<p>暂无快捷操作</p>';
|
||||
|
||||
const rankingRes = await apiGet('/api/student/ranking', { limit: 100 });
|
||||
|
||||
@@ -10,8 +10,11 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const role = window.PAGE_CONFIG.role;
|
||||
const currentUserId = window.PAGE_CONFIG.userId;
|
||||
const canRevokeAny = hasPermission('revoke_any');
|
||||
const canRevokeOwn = hasPermission('revoke_own');
|
||||
const canRestore = hasPermission('restore_records');
|
||||
const canRevoke = canRevokeAny || canRevokeOwn;
|
||||
let currentHistoryPage = 1;
|
||||
let totalHistoryPages = 1;
|
||||
|
||||
@@ -52,6 +55,11 @@ async function loadSubjectsForFilter() {
|
||||
}
|
||||
}
|
||||
|
||||
// 加载学期下拉列表(默认选中当前学期)
|
||||
async function loadSemestersForFilter() {
|
||||
await loadSemesterOptions('historySemesterFilter', { includeAll: true });
|
||||
}
|
||||
|
||||
// 筛选学生时自动取消合并记录
|
||||
function onStudentFilterChange() {
|
||||
var studentId = document.getElementById('historyStudentId').value;
|
||||
@@ -89,6 +97,7 @@ async function loadHistory(page) {
|
||||
var startDate = document.getElementById('historyStartDate').value;
|
||||
var endDate = document.getElementById('historyEndDate').value;
|
||||
var studentId = document.getElementById('historyStudentId').value;
|
||||
var semesterId = document.getElementById('historySemesterFilter') ? document.getElementById('historySemesterFilter').value : '';
|
||||
var reasonFilter = document.getElementById('historyReasonFilter').value;
|
||||
var subjectFilter = document.getElementById('historySubjectFilter').value;
|
||||
var reasonSearch = document.getElementById('historyReasonSearch').value.trim();
|
||||
@@ -103,6 +112,7 @@ async function loadHistory(page) {
|
||||
start_date: startDate,
|
||||
end_date: endDate
|
||||
};
|
||||
if (semesterId) params.semester_id = semesterId;
|
||||
if (studentId) params.student_id = studentId;
|
||||
|
||||
// 科目筛选优先于扣分类型筛选
|
||||
@@ -123,12 +133,12 @@ async function loadHistory(page) {
|
||||
var headHtml = '';
|
||||
if (isGrouped) {
|
||||
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生名单</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
||||
if (role === '班主任' || role === '班长') {
|
||||
if (canRevoke) {
|
||||
headHtml += '<th>操作</th>';
|
||||
}
|
||||
} else {
|
||||
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
||||
if (role === '班主任' || role === '班长' || role === '考勤委员') {
|
||||
if (canRevoke) {
|
||||
headHtml += '<th>操作</th>';
|
||||
}
|
||||
}
|
||||
@@ -149,17 +159,19 @@ async function loadHistory(page) {
|
||||
'<td class="history-students">' + escapeHtml(names) + '</td>' +
|
||||
'<td>' + escapeHtml(record.recorder_name || '') + '</td>' +
|
||||
'<td class="history-time">' + formatDateTime(record.created_at) + '</td>';
|
||||
if (role === '班主任' || role === '班长') {
|
||||
if (canRevoke) {
|
||||
if (allRevoked) {
|
||||
html += '<td><span class="text-muted">已撤销</span></td>';
|
||||
} else {
|
||||
} else if (canRevokeAny) {
|
||||
html += '<td><button class="btn btn-sm btn-outline" onclick="batchRevokeGrouped(\'' + escapeHtml(record.reason).replace(/'/g, "\\'") + '\',' + record.points_change + ',\'' + escapeHtml(record.recorder_name || '').replace(/'/g, "\\'") + '\',\'' + formatDateTime(record.created_at) + '\')">批量撤销</button></td>';
|
||||
} else {
|
||||
html += '<td><span class="text-muted">-</span></td>';
|
||||
}
|
||||
}
|
||||
html += '</tr>';
|
||||
});
|
||||
if (res.data.records.length === 0) {
|
||||
var colSpan = (role === '班主任' || role === '班长') ? 7 : 6;
|
||||
var colSpan = canRevoke ? 7 : 6;
|
||||
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
||||
}
|
||||
} else {
|
||||
@@ -174,24 +186,15 @@ async function loadHistory(page) {
|
||||
'<td>' + escapeHtml(record.student_name) + '</td>' +
|
||||
'<td>' + escapeHtml(record.recorder_name) + '</td>' +
|
||||
'<td class="history-time">' + formatDateTime(record.created_at) + '</td>';
|
||||
if (role === '班主任') {
|
||||
if (canRevoke) {
|
||||
if (record.is_revoked == 1) {
|
||||
var revokerInfo = record.revoker_name ? '由 ' + escapeHtml(record.revoker_name) + ' 撤销' : '已撤销';
|
||||
if (canRestore) {
|
||||
html += '<td><span class="text-muted" style="margin-right:4px;">' + revokerInfo + '</span><button class="btn btn-sm btn-outline" onclick="restoreRecord(' + record.record_id + ')">反撤销</button></td>';
|
||||
} else {
|
||||
html += '<td><button class="btn btn-sm btn-outline" onclick="revokeRecord(' + record.record_id + ')">撤销</button></td>';
|
||||
}
|
||||
} else if (role === '班长') {
|
||||
if (record.is_revoked == 1) {
|
||||
var revokerInfo = record.revoker_name ? '由 ' + escapeHtml(record.revoker_name) + ' 撤销' : '已撤销';
|
||||
html += '<td><span class="text-muted">' + revokerInfo + '</span></td>';
|
||||
} else {
|
||||
html += '<td><button class="btn btn-sm btn-outline" onclick="revokeRecord(' + record.record_id + ')">撤销</button></td>';
|
||||
}
|
||||
} else if (role === '考勤委员') {
|
||||
if (record.is_revoked == 1) {
|
||||
html += '<td><span class="text-muted">已撤销</span></td>';
|
||||
} else if (record.recorder_id == currentUserId) {
|
||||
} else if (canRevokeAny || (canRevokeOwn && record.recorder_id == currentUserId)) {
|
||||
html += '<td><button class="btn btn-sm btn-outline" onclick="revokeRecord(' + record.record_id + ')">撤销</button></td>';
|
||||
} else {
|
||||
html += '<td><span class="text-muted">-</span></td>';
|
||||
@@ -201,7 +204,7 @@ async function loadHistory(page) {
|
||||
});
|
||||
|
||||
if (res.data.records.length === 0) {
|
||||
var colSpan = (role === '班主任' || role === '班长' || role === '考勤委员') ? 7 : 6;
|
||||
var colSpan = canRevoke ? 7 : 6;
|
||||
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
||||
}
|
||||
}
|
||||
@@ -223,6 +226,8 @@ async function exportHistoryRecords() {
|
||||
var startDate = document.getElementById('historyStartDate').value;
|
||||
var endDate = document.getElementById('historyEndDate').value;
|
||||
var studentId = document.getElementById('historyStudentId').value;
|
||||
var semesterSelect = document.getElementById('historySemesterFilter');
|
||||
var semesterId = semesterSelect ? semesterSelect.value : '';
|
||||
|
||||
showToast('正在导出历史记录...', 'info');
|
||||
|
||||
@@ -230,10 +235,11 @@ async function exportHistoryRecords() {
|
||||
var reasonFilter = document.getElementById('historyReasonFilter').value;
|
||||
var subjectFilter = document.getElementById('historySubjectFilter').value;
|
||||
var reasonSearch = document.getElementById('historyReasonSearch').value.trim();
|
||||
var params = { page: 1, page_size: 1000 };
|
||||
var params = { is_revoked: 0 };
|
||||
if (startDate) params.start_date = startDate;
|
||||
if (endDate) params.end_date = endDate;
|
||||
if (studentId) params.student_id = studentId;
|
||||
if (semesterId) params.semester_id = semesterId;
|
||||
if (subjectFilter) {
|
||||
params.reason_prefix = '[' + subjectFilter + ']';
|
||||
} else if (reasonFilter) {
|
||||
@@ -241,35 +247,34 @@ async function exportHistoryRecords() {
|
||||
}
|
||||
if (reasonSearch) params.reason_search = reasonSearch;
|
||||
|
||||
var res = await apiGet('/api/admin/conduct/history', params);
|
||||
if (res && res.success && res.data.records) {
|
||||
var records = res.data.records;
|
||||
if (records.length === 0) {
|
||||
var records = await apiGetAll('/api/admin/conduct/history', params);
|
||||
if (!records || records.length === 0) {
|
||||
showToast('没有找到记录', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
var csv = '\uFEFF';
|
||||
csv += '时间,学号,姓名,分数变动,原因,操作人\n';
|
||||
var csv = '时间,学号,姓名,学期,类型,分数变动,原因,操作人\n';
|
||||
records.forEach(function(r) {
|
||||
if (r.is_revoked == 1) return;
|
||||
csv += (r.created_at || '') + ',' + (r.student_no || '') + ',' + (r.student_name || '') + ',' + (r.points_change > 0 ? '+' : '') + r.points_change + ',' + (r.reason || '').replace(/,/g, ';') + ',' + (r.recorder_name || '') + '\n';
|
||||
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 blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
var url = URL.createObjectURL(blob);
|
||||
var link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = '历史记录_' + new Date().toISOString().slice(0,10) + '.csv';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
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 + '条记录');
|
||||
} else {
|
||||
showToast('导出失败:' + (res && res.message || '未知错误'), 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
}
|
||||
@@ -289,6 +294,8 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
||||
reason_prefix: reason.substring(0, 4),
|
||||
grouped: false
|
||||
};
|
||||
var semesterSelect = document.getElementById('historySemesterFilter');
|
||||
if (semesterSelect && semesterSelect.value) params.semester_id = semesterSelect.value;
|
||||
|
||||
var res = await apiGet('/api/admin/conduct/history', params);
|
||||
if (!res || !res.success || !res.data.records) {
|
||||
@@ -320,8 +327,8 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化:并行加载学生和科目列表,然后加载历史记录
|
||||
Promise.all([loadStudentsForSelect(), loadSubjectsForFilter()]).then(function() {
|
||||
// 初始化:并行加载学生、科目、学期列表,然后加载历史记录
|
||||
Promise.all([loadStudentsForSelect(), loadSubjectsForFilter(), loadSemestersForFilter()]).then(function() {
|
||||
var urlParams = new URLSearchParams(window.location.search);
|
||||
var preStudentId = urlParams.get('student_id');
|
||||
if (preStudentId) {
|
||||
|
||||
@@ -10,21 +10,16 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const hwRole = window.PAGE_CONFIG.role;
|
||||
|
||||
// 初始化扣分配置
|
||||
const hwMaxPoints = hwRole === '班主任' ? 100 : 5;
|
||||
const hwNotSubmit = window.DEDUCTION_HOMEWORK_NOT_SUBMIT || 2;
|
||||
const hwLate = window.DEDUCTION_HOMEWORK_LATE || 1;
|
||||
|
||||
// 更新页面中的配置值显示
|
||||
// 更新页面中的配置值显示(加减分上限来自权限组动态配置)
|
||||
document.querySelectorAll('.hw-not-submit').forEach(el => el.textContent = hwNotSubmit);
|
||||
document.querySelectorAll('.hw-late').forEach(el => el.textContent = hwLate);
|
||||
document.querySelectorAll('.hw-max').forEach(el => el.textContent = hwMaxPoints);
|
||||
document.querySelectorAll('.hw-max').forEach(el => el.textContent = describeScoreLimits());
|
||||
|
||||
// 更新输入框的 min/max
|
||||
document.getElementById('pointsChange').setAttribute('min', -hwMaxPoints);
|
||||
document.getElementById('pointsChange').setAttribute('max', hwMaxPoints);
|
||||
// 更新输入框的 min/max(按权限组动态上限)
|
||||
applyScoreLimits(document.getElementById('pointsChange'));
|
||||
|
||||
// 加载科目列表(学习委员)
|
||||
async function loadSubjectsForHomework() {
|
||||
@@ -71,17 +66,13 @@ function showSinglePointsModal(studentId, studentName) {
|
||||
|
||||
function handleSubmitPoints() {
|
||||
const pointsChange = parseInt(document.getElementById('pointsChange').value);
|
||||
if (isNaN(pointsChange) || pointsChange === 0) {
|
||||
showToast('请输入有效的加减分值', 'warning');
|
||||
return;
|
||||
}
|
||||
if (Math.abs(pointsChange) > hwMaxPoints) {
|
||||
showToast(`每次加减分不超过${hwMaxPoints}分`, 'warning');
|
||||
const limitError = validateScoreChange(pointsChange);
|
||||
if (limitError) {
|
||||
showToast(limitError, 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
// 学习委员附加科目前缀、具体作业和缴交时间
|
||||
if (hwRole === '学习委员' || hwRole === '班主任') {
|
||||
// 附加科目前缀、具体作业和缴交时间
|
||||
const subjectSelect = document.getElementById('hwSubjectSelect');
|
||||
const subjectName = subjectSelect ? subjectSelect.value : '';
|
||||
const hwTitle = document.getElementById('hwTitle').value.trim();
|
||||
@@ -101,7 +92,6 @@ function handleSubmitPoints() {
|
||||
if (prefix) {
|
||||
reasonEl.value = prefix + ' ' + reasonEl.value;
|
||||
}
|
||||
}
|
||||
|
||||
submitBatchPoints({ related_type: 'homework' });
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
// 显示添加管理员模态框
|
||||
function showAddAdminModal() {
|
||||
document.getElementById('addAdminModal').style.display = 'flex';
|
||||
document.getElementById('addAdminForm')?.reset();
|
||||
}
|
||||
|
||||
// 提交添加管理员
|
||||
@@ -23,9 +22,10 @@
|
||||
const username = document.getElementById('adminUsername').value.trim();
|
||||
const realName = document.getElementById('adminRealName').value.trim();
|
||||
const password = document.getElementById('adminPassword').value;
|
||||
const roleType = document.getElementById('adminRole').value;
|
||||
const groupId = parseInt(document.getElementById('adminGroupId').value);
|
||||
const email = document.getElementById('adminEmail').value.trim();
|
||||
|
||||
if (!username || !realName || !roleType) {
|
||||
if (!username || !realName || !groupId) {
|
||||
showToast('请填写完整信息', 'warning');
|
||||
return;
|
||||
}
|
||||
@@ -34,7 +34,8 @@
|
||||
username: username,
|
||||
real_name: realName,
|
||||
password: password || undefined,
|
||||
role_type: roleType
|
||||
group_id: groupId,
|
||||
email: email || undefined
|
||||
});
|
||||
|
||||
if (res && res.success) {
|
||||
@@ -46,6 +47,11 @@
|
||||
}
|
||||
showToast(msg);
|
||||
closeModal('addAdminModal');
|
||||
document.getElementById('adminUsername').value = '';
|
||||
document.getElementById('adminRealName').value = '';
|
||||
document.getElementById('adminPassword').value = '';
|
||||
document.getElementById('adminGroupId').value = '';
|
||||
document.getElementById('adminEmail').value = '';
|
||||
loadAdmins();
|
||||
} else {
|
||||
showToast(res?.message || '添加失败', 'error');
|
||||
|
||||
@@ -31,16 +31,26 @@
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${selectedStudentIds.length} 人`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
preparePointsLimitHint();
|
||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
// 应用动态加减分上限提示与输入限制
|
||||
function preparePointsLimitHint() {
|
||||
var inputEl = document.getElementById('pointsChange');
|
||||
applyScoreLimits(inputEl);
|
||||
var hintEl = document.getElementById('pointsLimitHint');
|
||||
if (hintEl) hintEl.textContent = describeScoreLimits();
|
||||
}
|
||||
|
||||
// 提交批量加减分
|
||||
async function submitBatchPoints(options = {}) {
|
||||
const pointsChange = parseInt(document.getElementById('pointsChange').value);
|
||||
const reason = document.getElementById('pointsReason').value;
|
||||
|
||||
if (isNaN(pointsChange) || pointsChange === 0) {
|
||||
showToast('分值不能为0', 'error');
|
||||
const limitError = validateScoreChange(pointsChange);
|
||||
if (limitError) {
|
||||
showToast(limitError, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -97,6 +107,7 @@
|
||||
|
||||
window.showBatchPointsModal = showBatchPointsModal;
|
||||
window.submitBatchPoints = submitBatchPoints;
|
||||
window.preparePointsLimitHint = preparePointsLimitHint;
|
||||
window.revokeRecord = revokeRecord;
|
||||
window.restoreRecord = restoreRecord;
|
||||
})();
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 个人记录查询页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const canRevokeAny = hasPermission('revoke_any');
|
||||
const canRevokeOwn = hasPermission('revoke_own');
|
||||
const canRestore = hasPermission('restore_records');
|
||||
const canManage = canRevokeAny || canRevokeOwn;
|
||||
let currentStudentId = null;
|
||||
let currentPage = 1;
|
||||
|
||||
function typeMap(relatedType) {
|
||||
var map = { manual: '手动', homework: '作业', attendance: '考勤' };
|
||||
return map[relatedType] || '手动';
|
||||
}
|
||||
|
||||
function monthLabel(month) {
|
||||
if (!month || month.indexOf('-') < 0) return month || '-';
|
||||
var parts = month.split('-');
|
||||
return parts[0] + '年' + parseInt(parts[1], 10) + '月';
|
||||
}
|
||||
|
||||
async function loadStudents() {
|
||||
const res = await apiGet('/api/admin/students', { page_size: 1000 });
|
||||
if (res && res.success) {
|
||||
let html = '<option value="">-- 请选择学生 --</option>';
|
||||
res.data.students.forEach(s => {
|
||||
html += '<option value="' + s.student_id + '">' + escapeHtml(s.student_no) + ' - ' + escapeHtml(s.name) + '</option>';
|
||||
});
|
||||
document.getElementById('queryStudentId').innerHTML = html;
|
||||
}
|
||||
}
|
||||
|
||||
async function queryStudentRecords(page) {
|
||||
const studentId = document.getElementById('queryStudentId').value;
|
||||
if (!studentId) {
|
||||
showToast('请先选择学生', 'warning');
|
||||
return;
|
||||
}
|
||||
currentStudentId = studentId;
|
||||
currentPage = page || 1;
|
||||
const semesterId = document.getElementById('querySemesterId').value;
|
||||
|
||||
document.getElementById('queryPlaceholder').style.display = 'none';
|
||||
document.getElementById('queryResult').style.display = 'block';
|
||||
|
||||
await Promise.all([
|
||||
loadSummary(studentId, semesterId),
|
||||
loadRecords(studentId, semesterId, currentPage)
|
||||
]);
|
||||
}
|
||||
|
||||
function onQueryStudentChange() {
|
||||
if (!document.getElementById('queryStudentId').value) {
|
||||
document.getElementById('queryResult').style.display = 'none';
|
||||
document.getElementById('queryPlaceholder').style.display = 'block';
|
||||
return;
|
||||
}
|
||||
queryStudentRecords(1);
|
||||
}
|
||||
|
||||
function onQuerySemesterChange() {
|
||||
if (document.getElementById('queryStudentId').value) {
|
||||
queryStudentRecords(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSummary(studentId, semesterId) {
|
||||
const params = { student_id: studentId };
|
||||
if (semesterId) params.semester_id = semesterId;
|
||||
|
||||
const res = await apiGet('/api/admin/conduct/student-summary', params);
|
||||
if (!res || !res.success) {
|
||||
showToast((res && res.message) || '获取汇总失败', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = res.data;
|
||||
const semesterName = data.semester ? data.semester.semester_name : '全部学期';
|
||||
document.getElementById('queryStudentTitle').textContent =
|
||||
data.student.name + '(' + data.student.student_no + ') - ' + semesterName;
|
||||
|
||||
const s = data.summary;
|
||||
document.getElementById('querySummaryCards').innerHTML =
|
||||
'<div class="stat-card"><div class="stat-label">基础分</div><div class="stat-value">' + data.base_points + '</div></div>' +
|
||||
'<div class="stat-card"><div class="stat-label">加分合计</div><div class="stat-value plus">+' + s.bonus_total + '</div></div>' +
|
||||
'<div class="stat-card"><div class="stat-label">减分合计</div><div class="stat-value minus">' + s.deduction_total + '</div></div>' +
|
||||
'<div class="stat-card"><div class="stat-label">得分(基础分+加减分)</div><div class="stat-value">' + s.computed_total + '</div></div>' +
|
||||
'<div class="stat-card"><div class="stat-label">当前实时总分</div><div class="stat-value">' + s.current_total_points + '</div></div>';
|
||||
|
||||
document.getElementById('querySummaryHint').textContent =
|
||||
'共 ' + s.record_count + ' 条有效记录(不含已撤销)。' +
|
||||
(data.semester ? '学期得分按“基础分 + 学期内加分 - 学期内减分”计算。' : '全部学期得分按“基础分 + 全部加分 - 全部减分”计算,仅供参考。');
|
||||
|
||||
renderMonthly(data.months);
|
||||
renderReasonSummary(data.months);
|
||||
}
|
||||
|
||||
function renderMonthly(months) {
|
||||
let html = '';
|
||||
if (!months || months.length === 0) {
|
||||
html = '<tr><td colspan="6" style="text-align:center;">暂无记录</td></tr>';
|
||||
} else {
|
||||
months.forEach(m => {
|
||||
html += '<tr>' +
|
||||
'<td>' + escapeHtml(monthLabel(m.month)) + '</td>' +
|
||||
'<td>' + m.start_score + '</td>' +
|
||||
'<td class="plus">+' + m.bonus + '</td>' +
|
||||
'<td class="minus">' + m.deduction + '</td>' +
|
||||
'<td><strong>' + m.end_score + '</strong></td>' +
|
||||
'<td>' + m.record_count + '</td>' +
|
||||
'</tr>';
|
||||
});
|
||||
}
|
||||
document.getElementById('queryMonthlyList').innerHTML = html;
|
||||
}
|
||||
|
||||
function renderReasonTable(reasons, emptyText) {
|
||||
if (!reasons || reasons.length === 0) {
|
||||
return '<div style="color:var(--color-text-secondary); font-size:12px; padding:8px 0;">' + emptyText + '</div>';
|
||||
}
|
||||
let html = '<table class="table"><thead><tr><th>理由</th><th style="width:60px;">次数</th><th style="width:80px;">合计</th></tr></thead><tbody>';
|
||||
reasons.forEach(r => {
|
||||
html += '<tr>' +
|
||||
'<td>' + escapeHtml(r.reason) + '</td>' +
|
||||
'<td>' + r.count + '</td>' +
|
||||
'<td class="' + (r.points > 0 ? 'plus' : 'minus') + '">' + (r.points > 0 ? '+' : '') + r.points + '</td>' +
|
||||
'</tr>';
|
||||
});
|
||||
html += '</tbody></table>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function renderReasonSummary(months) {
|
||||
const container = document.getElementById('queryReasonSummary');
|
||||
if (!months || months.length === 0) {
|
||||
container.innerHTML = '<div style="text-align:center; color:var(--color-text-secondary); padding:16px 0;">暂无记录</div>';
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
months.forEach(m => {
|
||||
html += '<div style="margin-bottom: 20px;">' +
|
||||
'<div style="font-weight: bold; margin-bottom: 8px;">' + escapeHtml(monthLabel(m.month)) +
|
||||
' <span style="font-weight: normal; font-size: 12px; color: var(--color-text-secondary);">' +
|
||||
'加分 +' + m.bonus + ' / 减分 ' + m.deduction + '</span></div>' +
|
||||
'<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px;">' +
|
||||
'<div><div style="color:var(--color-success); font-size:13px; margin-bottom:4px;">加分理由</div>' + renderReasonTable(m.bonus_reasons, '本月无加分') + '</div>' +
|
||||
'<div><div style="color:var(--color-danger); font-size:13px; margin-bottom:4px;">减分理由</div>' + renderReasonTable(m.deduction_reasons, '本月无减分') + '</div>' +
|
||||
'</div></div>';
|
||||
});
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
async function loadRecords(studentId, semesterId, page) {
|
||||
const params = { student_id: studentId, page: page || 1, page_size: 20 };
|
||||
if (semesterId) params.semester_id = semesterId;
|
||||
|
||||
const res = await apiGet('/api/admin/conduct/history', params);
|
||||
if (!res || !res.success) {
|
||||
showToast('获取明细记录失败', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const records = res.data.records || [];
|
||||
let html = '';
|
||||
records.forEach(record => {
|
||||
const pointsClass = record.points_change > 0 ? 'plus' : 'minus';
|
||||
const revokedStyle = record.is_revoked == 1 ? ' style="opacity:0.5;text-decoration:line-through;"' : '';
|
||||
html += '<tr' + revokedStyle + '>' +
|
||||
'<td>' + typeMap(record.related_type) + '</td>' +
|
||||
'<td class="' + pointsClass + '">' + (record.points_change > 0 ? '+' : '') + record.points_change + '</td>' +
|
||||
'<td>' + escapeHtml(record.reason) + '</td>' +
|
||||
'<td>' + escapeHtml(record.recorder_name || '') + '</td>' +
|
||||
'<td style="white-space:nowrap;">' + formatDateTime(record.created_at) + '</td>';
|
||||
if (canManage) {
|
||||
if (record.is_revoked == 1) {
|
||||
if (canRestore) {
|
||||
html += '<td><span class="text-muted">已撤销</span> <button class="btn btn-sm btn-outline" onclick="restoreQueryRecord(' + record.record_id + ')">反撤销</button></td>';
|
||||
} else {
|
||||
html += '<td><span class="text-muted">已撤销</span></td>';
|
||||
}
|
||||
} else if (canRevokeAny || (canRevokeOwn && record.recorder_id == window.PAGE_CONFIG.userId)) {
|
||||
html += '<td><button class="btn btn-sm btn-outline" onclick="revokeQueryRecord(' + record.record_id + ')">撤销</button></td>';
|
||||
} else {
|
||||
html += '<td><span class="text-muted">-</span></td>';
|
||||
}
|
||||
}
|
||||
html += '</tr>';
|
||||
});
|
||||
|
||||
if (records.length === 0) {
|
||||
html = '<tr><td colspan="' + (canManage ? 6 : 5) + '" style="text-align:center;">暂无记录</td></tr>';
|
||||
}
|
||||
document.getElementById('queryRecordList').innerHTML = html;
|
||||
|
||||
const totalPages = res.data.total_pages || 1;
|
||||
renderSmartPagination('queryPagination', page || 1, totalPages, function(p) {
|
||||
currentPage = p;
|
||||
loadRecords(currentStudentId, document.getElementById('querySemesterId').value, p);
|
||||
});
|
||||
}
|
||||
|
||||
async function revokeQueryRecord(recordId) {
|
||||
if (!confirm('确定要撤销这条记录吗?撤销后学生分数将恢复。')) return;
|
||||
const res = await apiPost('/api/admin/conduct/revoke', { record_id: recordId });
|
||||
if (res && res.success) {
|
||||
showToast('撤销成功');
|
||||
queryStudentRecords(currentPage);
|
||||
} else {
|
||||
showToast((res && res.message) || '撤销失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreQueryRecord(recordId) {
|
||||
if (!confirm('确定要反撤销这条记录吗?分数变动将重新生效。')) return;
|
||||
const res = await apiPost('/api/admin/conduct/restore', { record_id: recordId });
|
||||
if (res && res.success) {
|
||||
showToast('反撤销成功');
|
||||
queryStudentRecords(currentPage);
|
||||
} else {
|
||||
showToast((res && res.message) || '反撤销失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function exportStudentRecords() {
|
||||
const studentId = document.getElementById('queryStudentId').value;
|
||||
if (!studentId) {
|
||||
showToast('请先选择学生', 'warning');
|
||||
return;
|
||||
}
|
||||
const semesterSelect = document.getElementById('querySemesterId');
|
||||
const semesterId = semesterSelect.value;
|
||||
const semesterName = (semesterSelect.selectedIndex >= 0)
|
||||
? semesterSelect.options[semesterSelect.selectedIndex].textContent.replace(/((当前|已归档))$/, '')
|
||||
: '全部学期';
|
||||
const studentName = document.getElementById('queryStudentId').selectedOptions[0].textContent.trim();
|
||||
|
||||
showToast('正在导出个人记录...', 'info');
|
||||
|
||||
try {
|
||||
const params = { student_id: studentId, is_revoked: 0 };
|
||||
if (semesterId) params.semester_id = semesterId;
|
||||
const records = await apiGetAll('/api/admin/conduct/history', params);
|
||||
|
||||
let summaryLines = [];
|
||||
const summaryParams = { student_id: studentId };
|
||||
if (semesterId) summaryParams.semester_id = semesterId;
|
||||
const summaryRes = await apiGet('/api/admin/conduct/student-summary', summaryParams);
|
||||
if (summaryRes && summaryRes.success) {
|
||||
const d = summaryRes.data;
|
||||
summaryLines = [
|
||||
['学生', studentName],
|
||||
['学期', semesterName],
|
||||
['基础分', d.base_points],
|
||||
['加分合计', d.summary.bonus_total],
|
||||
['减分合计', d.summary.deduction_total],
|
||||
['得分(基础分+加减分)', d.summary.computed_total],
|
||||
['当前实时总分', d.summary.current_total_points]
|
||||
];
|
||||
}
|
||||
|
||||
let csv = '';
|
||||
summaryLines.forEach(line => {
|
||||
csv += [line[0], line[1]].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
csv += '\n时间,类型,分值,原因,操作人,状态\n';
|
||||
records.forEach(r => {
|
||||
csv += [
|
||||
r.created_at || '',
|
||||
typeMap(r.related_type),
|
||||
(r.points_change > 0 ? '+' : '') + r.points_change,
|
||||
r.reason || '',
|
||||
r.recorder_name || '',
|
||||
r.is_revoked == 1 ? '已撤销' : '正常'
|
||||
].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
|
||||
const safeLabel = (semesterName || '全部学期').replace(/[\\/:*?"<>|]/g, '_');
|
||||
downloadCsv('个人记录_' + studentName + '_' + safeLabel + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
showToast('导出成功,共' + records.length + '条明细记录');
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
(async function init() {
|
||||
await Promise.all([
|
||||
loadStudents(),
|
||||
loadSemesterOptions('querySemesterId', { includeAll: true })
|
||||
]);
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const preStudentId = urlParams.get('student_id');
|
||||
if (preStudentId) {
|
||||
document.getElementById('queryStudentId').value = preStudentId;
|
||||
queryStudentRecords(1);
|
||||
}
|
||||
})();
|
||||
|
||||
window.queryStudentRecords = queryStudentRecords;
|
||||
window.onQueryStudentChange = onQueryStudentChange;
|
||||
window.onQuerySemesterChange = onQuerySemesterChange;
|
||||
window.exportStudentRecords = exportStudentRecords;
|
||||
window.revokeQueryRecord = revokeQueryRecord;
|
||||
window.restoreQueryRecord = restoreQueryRecord;
|
||||
|
||||
})();
|
||||
@@ -10,7 +10,10 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const userRole = window.PAGE_CONFIG.role;
|
||||
const canViewPersonalQuery = hasPermission('view_all_records');
|
||||
const canManageStudents = hasPermission('manage_students');
|
||||
const canManageConduct = hasPermission('manage_conduct');
|
||||
const canExportStudents = hasPermission('export_students');
|
||||
let currentPage = 1;
|
||||
let totalPages = 1;
|
||||
|
||||
@@ -22,30 +25,38 @@ async function loadStudents(page = 1) {
|
||||
if (res && res.success) {
|
||||
let html = '';
|
||||
res.data.students.forEach(student => {
|
||||
html += `<tr>
|
||||
<td><input type="checkbox" class="student-checkbox" data-id="${student.student_id}"></td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td><a href="/admin/history.php?student_id=${student.student_id}" class="link">${escapeHtml(student.name)}</a></td>
|
||||
<td>${escapeHtml(student.dormitory_number || '-')}</td>
|
||||
<td>${student.total_points}</td>
|
||||
${userRole === '班主任' ? `<td>${student.parent_phone ? student.parent_phone.slice(0,3) + '******' + student.parent_phone.slice(-2) : '-'}</td>` : ''}
|
||||
<td>
|
||||
<div class="action-dropdown">
|
||||
<button class="btn btn-sm btn-outline" onclick="showSinglePointsModal(${student.student_id}, '${escapeHtml(student.name)}')">加减分</button>
|
||||
${userRole === '班主任' ? `<button class="btn btn-sm action-dropdown-toggle" onclick="toggleActionDropdown(this)">更多 ▼</button>
|
||||
const detailUrl = canViewPersonalQuery
|
||||
? `/admin/record_query.php?student_id=${student.student_id}`
|
||||
: `/admin/history.php?student_id=${student.student_id}`;
|
||||
const pointsButton = canManageConduct
|
||||
? `<button class="btn btn-sm btn-outline" onclick="showSinglePointsModal(${student.student_id}, '${escapeHtml(student.name)}')">加减分</button>`
|
||||
: '';
|
||||
const moreButton = canManageStudents ? `<button class="btn btn-sm action-dropdown-toggle" onclick="toggleActionDropdown(this)">更多 ▼</button>
|
||||
<div class="action-dropdown-menu">
|
||||
<a onclick="showEditStudentModal(${student.student_id}, '${escapeHtml(student.student_no)}', '${escapeHtml(student.name)}', '${escapeHtml(student.parent_phone || '')}', '${escapeHtml(student.dormitory_number || '')}')">编辑</a>
|
||||
<a onclick="showResetStudentPasswordModal(${student.student_id}, '${escapeHtml(student.name)}')">重置密码</a>
|
||||
<a onclick="unlockStudent('${escapeHtml(student.student_no)}', '${escapeHtml(student.name)}')">解锁</a>
|
||||
<a class="danger" onclick="deleteStudent(${student.student_id}, '${escapeHtml(student.name)}')">删除</a>
|
||||
</div>` : ''}
|
||||
</div>` : '';
|
||||
html += `<tr>
|
||||
<td><input type="checkbox" class="student-checkbox" data-id="${student.student_id}"></td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td><a href="${detailUrl}" class="link">${escapeHtml(student.name)}</a></td>
|
||||
<td>${escapeHtml(student.dormitory_number || '-')}</td>
|
||||
<td>${student.total_points}</td>
|
||||
${canManageStudents ? `<td>${student.parent_phone ? student.parent_phone.slice(0,3) + '******' + student.parent_phone.slice(-2) : '-'}</td>` : ''}
|
||||
<td>
|
||||
<div class="action-dropdown">
|
||||
${pointsButton}
|
||||
${moreButton}
|
||||
</div>
|
||||
</td>
|
||||
</tr>`;
|
||||
});
|
||||
|
||||
if (res.data.students.length === 0) {
|
||||
html = `<tr><td colspan="${userRole === '班主任' ? '7' : '6'}" style="text-align:center;">暂无学生数据</td></tr>`;
|
||||
const colCount = canManageStudents ? 7 : 6;
|
||||
html = `<tr><td colspan="${colCount}" style="text-align:center;">暂无学生数据</td></tr>`;
|
||||
}
|
||||
|
||||
document.getElementById('studentList').innerHTML = html;
|
||||
@@ -66,6 +77,7 @@ function showSinglePointsModal(studentId, studentName) {
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
if (typeof preparePointsLimitHint === 'function') preparePointsLimitHint();
|
||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
@@ -85,6 +97,83 @@ async function unlockStudent(studentNo, studentName) {
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 导出学生名单 ==========
|
||||
|
||||
const EXPORT_COLUMNS = {
|
||||
student_no: '学号',
|
||||
name: '姓名',
|
||||
dormitory_number: '宿舍号',
|
||||
total_points: '当前操行分',
|
||||
parent_phone: '家长手机号',
|
||||
status: '状态'
|
||||
};
|
||||
|
||||
function showExportStudentsModal() {
|
||||
if (!canExportStudents) {
|
||||
showToast('无导出学生名单权限', 'error');
|
||||
return;
|
||||
}
|
||||
document.getElementById('exportStudentsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
async function fetchAllStudentsForExport() {
|
||||
const allStudents = [];
|
||||
let page = 1;
|
||||
while (page <= 100) {
|
||||
const res = await apiGet('/api/admin/students', { page: page, page_size: 1000 });
|
||||
if (!res || !res.success || !Array.isArray(res.data.students)) {
|
||||
break;
|
||||
}
|
||||
allStudents.push(...res.data.students);
|
||||
const total = res.data.total || 0;
|
||||
if (allStudents.length >= total || res.data.students.length < 1000) {
|
||||
break;
|
||||
}
|
||||
page++;
|
||||
}
|
||||
return allStudents;
|
||||
}
|
||||
|
||||
async function exportStudents() {
|
||||
if (!canExportStudents) {
|
||||
showToast('无导出学生名单权限', 'error');
|
||||
return;
|
||||
}
|
||||
const checked = Array.from(document.querySelectorAll('.export-student-col:checked')).map(el => el.value);
|
||||
if (checked.length === 0) {
|
||||
showToast('请至少选择一个导出字段', 'warning');
|
||||
return;
|
||||
}
|
||||
const selected = ['student_no', 'name'].filter(v => checked.indexOf(v) === -1).concat(checked);
|
||||
|
||||
showToast('正在导出学生名单...', 'info');
|
||||
|
||||
try {
|
||||
const students = await fetchAllStudentsForExport();
|
||||
if (!students || students.length === 0) {
|
||||
showToast('没有找到学生', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
let csv = selected.map(key => EXPORT_COLUMNS[key]).join(',') + '\n';
|
||||
students.forEach(student => {
|
||||
const row = selected.map(key => {
|
||||
if (key === 'status') {
|
||||
return student.status === 1 ? '正常' : '停用';
|
||||
}
|
||||
return student[key] !== null && student[key] !== undefined ? student[key] : '';
|
||||
});
|
||||
csv += row.map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
|
||||
downloadCsv('学生名单_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
closeModal('exportStudentsModal');
|
||||
showToast('导出成功,共' + students.length + '名学生');
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
loadStudents();
|
||||
|
||||
let searchTimeout;
|
||||
@@ -96,5 +185,7 @@ document.getElementById('searchInput').addEventListener('input', () => {
|
||||
window.loadStudents = loadStudents;
|
||||
window.showSinglePointsModal = showSinglePointsModal;
|
||||
window.unlockStudent = unlockStudent;
|
||||
window.showExportStudentsModal = showExportStudentsModal;
|
||||
window.exportStudents = exportStudents;
|
||||
|
||||
})();
|
||||
@@ -77,3 +77,83 @@ date_default_timezone_set('Asia/Shanghai');
|
||||
// 生产环境关闭错误显示
|
||||
error_reporting(0);
|
||||
ini_set('display_errors', 0);
|
||||
|
||||
// ========== 管理员权限(权限组)辅助 ==========
|
||||
|
||||
/**
|
||||
* 从后端同步当前管理员的权限、权限组与加减分上限
|
||||
* 权限变更后最多 60 秒内自动生效
|
||||
*/
|
||||
function refresh_admin_permissions($force = false): void {
|
||||
if (($_SESSION['user_type'] ?? '') !== 'admin') {
|
||||
return;
|
||||
}
|
||||
$lastSync = (int)($_SESSION['permissions_synced_at'] ?? 0);
|
||||
if (!$force && isset($_SESSION['permissions']) && (time() - $lastSync) < 60) {
|
||||
return;
|
||||
}
|
||||
$token = $_SESSION['jwt_token'] ?? '';
|
||||
if (empty($token)) {
|
||||
return;
|
||||
}
|
||||
$ch = curl_init();
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_URL => API_BASE_URL . '/api/auth/me',
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Authorization: Bearer ' . $token,
|
||||
'Content-Type: application/json'
|
||||
],
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => 0
|
||||
]);
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
if ($httpCode !== 200 || empty($response)) {
|
||||
return;
|
||||
}
|
||||
$data = json_decode($response, true);
|
||||
if (!is_array($data) || empty($data['success']) || empty($data['data'])) {
|
||||
return;
|
||||
}
|
||||
$info = $data['data'];
|
||||
$_SESSION['real_name'] = $info['real_name'] ?? ($_SESSION['real_name'] ?? '');
|
||||
$_SESSION['email'] = $info['email'] ?? '';
|
||||
$_SESSION['role'] = $info['role'] ?? '';
|
||||
$_SESSION['permissions'] = is_array($info['permissions'] ?? null) ? $info['permissions'] : [];
|
||||
$_SESSION['group'] = $info['group'] ?? null;
|
||||
$_SESSION['permissions_synced_at'] = time();
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前登录管理员是否拥有指定权限
|
||||
*/
|
||||
function has_perm($perm) {
|
||||
if (($_SESSION['user_type'] ?? '') !== 'admin') {
|
||||
return false;
|
||||
}
|
||||
$permissions = $_SESSION['permissions'] ?? [];
|
||||
return !empty($permissions[$perm]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面守卫:无权限时跳转管理端首页
|
||||
*/
|
||||
function require_perm($perm) {
|
||||
if (!has_perm($perm)) {
|
||||
header('Location: /admin/dashboard.php');
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前权限组名称
|
||||
*/
|
||||
function current_group_name() {
|
||||
return $_SESSION['role'] ?? '';
|
||||
}
|
||||
|
||||
// 管理员页面自动同步权限(权限组变更后自动生效)
|
||||
refresh_admin_permissions();
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 忘记密码
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/config.php';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||
<title><?php echo SITE_NAME; ?> - 忘记密码</title>
|
||||
<link rel="stylesheet" href="/assets/css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-container">
|
||||
<div class="login-header">
|
||||
<h1><?php echo SITE_NAME; ?></h1>
|
||||
<p>管理员找回密码</p>
|
||||
</div>
|
||||
|
||||
<form id="forgotForm" class="login-form">
|
||||
<div class="form-group">
|
||||
<label>管理员账号</label>
|
||||
<input type="text" id="username" name="username" required autocomplete="off" placeholder="请输入管理员用户名">
|
||||
<small>重置链接将发送到该账号绑定的邮箱</small>
|
||||
</div>
|
||||
<button type="submit" class="btn-login" id="submitBtn">发送重置链接</button>
|
||||
<div id="tipMsg" class="error-msg" style="display: none;"></div>
|
||||
<p style="text-align:center; margin-top:14px;">
|
||||
<a href="/index.php" style="color:#667eea; font-size:14px;">返回登录</a>
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<div class="login-footer">
|
||||
<p>© <?php echo date('Y'); ?> Sea Network Technology Studio</p>
|
||||
<?php if (defined('ICP_ENABLED') && ICP_ENABLED && defined('ICP_NUMBER') && ICP_NUMBER): ?>
|
||||
<p><a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer"><?php echo htmlspecialchars(ICP_NUMBER); ?></a></p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.API_BASE_URL = '<?php echo API_BASE_URL; ?>';
|
||||
|
||||
function showTip(msg, isError) {
|
||||
const tip = document.getElementById('tipMsg');
|
||||
tip.textContent = msg;
|
||||
tip.style.display = 'block';
|
||||
tip.style.color = isError ? '' : '#38a169';
|
||||
}
|
||||
|
||||
document.getElementById('forgotForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const username = document.getElementById('username').value.trim();
|
||||
if (!username) {
|
||||
showTip('请输入管理员账号', true);
|
||||
return;
|
||||
}
|
||||
const btn = document.getElementById('submitBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '发送中...';
|
||||
try {
|
||||
const response = await fetch(`${window.API_BASE_URL}/api/auth/forgot-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username })
|
||||
});
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
showTip(data.message || '重置链接已发送,请查收邮箱', false);
|
||||
} else {
|
||||
showTip(data.message || '发送失败', true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('找回密码请求失败:', error);
|
||||
showTip('网络错误,请稍后重试', true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '发送重置链接';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -77,3 +77,28 @@ $page_title = $page_title ?? '首页';
|
||||
</script>
|
||||
<script src="/assets/js/common.js"></script>
|
||||
<script src="/assets/js/modules/utils.js"></script>
|
||||
<?php if ($user_type === 'admin'): ?>
|
||||
<script>
|
||||
window.USER_PERMISSIONS = <?php
|
||||
echo json_encode(
|
||||
$_SESSION['permissions'] ?? [],
|
||||
JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
||||
);
|
||||
?>;
|
||||
window.USER_GROUP = <?php
|
||||
echo json_encode(
|
||||
$_SESSION['group'] ?? null,
|
||||
JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
||||
);
|
||||
?>;
|
||||
window.USER_SCORE_LIMITS = <?php
|
||||
$group = $_SESSION['group'] ?? [];
|
||||
echo json_encode([
|
||||
'can_add' => !empty($group['can_add_points']),
|
||||
'max_add' => $group['max_add_points'] ?? null,
|
||||
'can_subtract' => !empty($group['can_subtract_points']),
|
||||
'max_subtract' => $group['max_subtract_points'] ?? null
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
?>;
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
@@ -1,21 +1,22 @@
|
||||
<div class="nav">
|
||||
<a href="/admin/dashboard.php" class="nav-item<?php echo $current_page === 'dashboard' ? ' active' : ''; ?>">首页</a>
|
||||
<a href="/admin/students.php" class="nav-item<?php echo $current_page === 'students' ? ' active' : ''; ?>">学生管理</a>
|
||||
<?php if ($role === '班主任' || $role === '班长' || $role === '学习委员' || $role === '考勤委员' || $role === '劳动委员' || $role === '志愿委员'): ?>
|
||||
<a href="/admin/conduct.php" class="nav-item<?php echo $current_page === 'conduct' ? ' active' : ''; ?>">操行分管理</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($role === '班主任' || $role === '学习委员'): ?>
|
||||
<?php if (has_perm('manage_homework')): ?>
|
||||
<a href="/admin/homework.php" class="nav-item<?php echo $current_page === 'homework' ? ' active' : ''; ?>">作业扣分</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($role === '班主任' || $role === '考勤委员'): ?>
|
||||
<?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 ($role === '班主任'): ?>
|
||||
<?php if (has_perm('manage_admins')): ?>
|
||||
<a href="/admin/admins.php" class="nav-item<?php echo $current_page === 'admins' ? ' active' : ''; ?>">管理员管理</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<?php if (has_perm('manage_semesters')): ?>
|
||||
<a href="/admin/semesters.php" class="nav-item<?php echo $current_page === 'semesters' ? ' 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>
|
||||
<?php endif; ?>
|
||||
<a href="/admin/password.php" class="nav-item<?php echo $current_page === 'password' ? ' active' : ''; ?>">修改密码</a>
|
||||
</div>
|
||||
@@ -47,6 +47,9 @@ if (isset($_SESSION['user_id']) && isset($_SESSION['user_type'])) {
|
||||
<input type="password" id="password" name="password" required placeholder="请输入密码">
|
||||
</div>
|
||||
<button type="submit" class="btn-login">登 录</button>
|
||||
<p style="text-align:center; margin-top:14px;">
|
||||
<a href="/forgot_password.php" style="color:#667eea; font-size:14px;">忘记密码?(管理员)</a>
|
||||
</p>
|
||||
<div id="errorMsg" class="error-msg" style="display: none;"></div>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 重置密码
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/config.php';
|
||||
|
||||
$token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['token']) : '';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||
<title><?php echo SITE_NAME; ?> - 重置密码</title>
|
||||
<link rel="stylesheet" href="/assets/css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-container">
|
||||
<div class="login-header">
|
||||
<h1><?php echo SITE_NAME; ?></h1>
|
||||
<p>重置管理员密码</p>
|
||||
</div>
|
||||
|
||||
<div id="loadingBox" class="login-form" style="text-align:center; color:#888;">正在校验链接...</div>
|
||||
|
||||
<form id="resetForm" class="login-form" style="display:none;">
|
||||
<div class="form-group">
|
||||
<label>账号</label>
|
||||
<input type="text" id="accountName" disabled>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>新密码 <span style="color:red;">*</span></label>
|
||||
<input type="password" id="newPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码 <span style="color:red;">*</span></label>
|
||||
<input type="password" id="confirmPassword" required>
|
||||
</div>
|
||||
<button type="submit" class="btn-login" id="submitBtn">确认重置</button>
|
||||
<div id="tipMsg" class="error-msg" style="display: none;"></div>
|
||||
</form>
|
||||
|
||||
<div id="invalidBox" class="login-form" style="display:none; text-align:center;">
|
||||
<p style="color:#e53e3e; margin-bottom:16px;">重置链接无效或已过期,请重新申请。</p>
|
||||
<a href="/forgot_password.php" style="color:#667eea;">重新申请</a>
|
||||
</div>
|
||||
|
||||
<div class="login-footer">
|
||||
<p>© <?php echo date('Y'); ?> Sea Network Technology Studio</p>
|
||||
<?php if (defined('ICP_ENABLED') && ICP_ENABLED && defined('ICP_NUMBER') && ICP_NUMBER): ?>
|
||||
<p><a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer"><?php echo htmlspecialchars(ICP_NUMBER); ?></a></p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.API_BASE_URL = '<?php echo API_BASE_URL; ?>';
|
||||
const RESET_TOKEN = '<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>';
|
||||
|
||||
function showTip(msg, isError) {
|
||||
const tip = document.getElementById('tipMsg');
|
||||
tip.textContent = msg;
|
||||
tip.style.display = 'block';
|
||||
tip.style.color = isError ? '' : '#38a169';
|
||||
}
|
||||
|
||||
(async function verifyToken() {
|
||||
if (!RESET_TOKEN) {
|
||||
document.getElementById('loadingBox').style.display = 'none';
|
||||
document.getElementById('invalidBox').style.display = 'block';
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(`${window.API_BASE_URL}/api/auth/reset-token/check?token=${encodeURIComponent(RESET_TOKEN)}`);
|
||||
const data = await response.json();
|
||||
const info = data && data.success ? data.data : null;
|
||||
document.getElementById('loadingBox').style.display = 'none';
|
||||
if (info && info.valid) {
|
||||
document.getElementById('accountName').value =
|
||||
(info.real_name || '') + '(' + info.username + ')';
|
||||
document.getElementById('resetForm').style.display = 'block';
|
||||
} else {
|
||||
document.getElementById('invalidBox').style.display = 'block';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('令牌校验失败:', error);
|
||||
document.getElementById('loadingBox').style.display = 'none';
|
||||
document.getElementById('invalidBox').style.display = 'block';
|
||||
}
|
||||
})();
|
||||
|
||||
document.getElementById('resetForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const newPassword = document.getElementById('newPassword').value;
|
||||
const confirmPassword = document.getElementById('confirmPassword').value;
|
||||
if (newPassword !== confirmPassword) {
|
||||
showTip('两次输入的密码不一致', true);
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 6 || newPassword.length > 20) {
|
||||
showTip('密码长度需为6-20位', true);
|
||||
return;
|
||||
}
|
||||
const btn = document.getElementById('submitBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '提交中...';
|
||||
try {
|
||||
const response = await fetch(`${window.API_BASE_URL}/api/auth/reset-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: RESET_TOKEN, new_password: newPassword })
|
||||
});
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
showTip(data.message || '密码重置成功', false);
|
||||
setTimeout(() => { window.location.href = '/index.php'; }, 1800);
|
||||
} else {
|
||||
showTip(data.message || '重置失败', true);
|
||||
btn.disabled = false;
|
||||
btn.textContent = '确认重置';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('重置密码失败:', error);
|
||||
showTip('网络错误,请稍后重试', true);
|
||||
btn.disabled = false;
|
||||
btn.textContent = '确认重置';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+49
-5
@@ -61,6 +61,7 @@ CREATE TABLE IF NOT EXISTS `users` (
|
||||
`username` VARCHAR(50) NOT NULL UNIQUE,
|
||||
`password_hash` VARCHAR(255) NOT NULL,
|
||||
`real_name` VARCHAR(50) NOT NULL,
|
||||
`email` VARCHAR(100) DEFAULT NULL COMMENT '绑定邮箱(用于找回密码)',
|
||||
`user_type` ENUM('student', 'parent', 'admin') NOT NULL,
|
||||
`student_id` INT DEFAULT NULL,
|
||||
`status` TINYINT DEFAULT 1,
|
||||
@@ -68,19 +69,40 @@ CREATE TABLE IF NOT EXISTS `users` (
|
||||
`last_login_time` DATETIME DEFAULT NULL,
|
||||
`last_login_ip` VARCHAR(45) DEFAULT NULL,
|
||||
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX `idx_user_email` (`email`),
|
||||
FOREIGN KEY (`student_id`) REFERENCES `students`(`student_id`) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 权限组表
|
||||
CREATE TABLE IF NOT EXISTS `permission_groups` (
|
||||
`group_id` INT PRIMARY KEY AUTO_INCREMENT,
|
||||
`group_name` VARCHAR(50) NOT NULL COMMENT '权限组名称',
|
||||
`description` VARCHAR(255) DEFAULT NULL COMMENT '说明',
|
||||
`permissions` TEXT NOT NULL COMMENT '权限配置(JSON)',
|
||||
`can_add_points` TINYINT(1) DEFAULT 1 COMMENT '是否允许加分',
|
||||
`max_add_points` INT DEFAULT NULL COMMENT '单次加分上限,NULL=无限制',
|
||||
`can_subtract_points` TINYINT(1) DEFAULT 1 COMMENT '是否允许扣分',
|
||||
`max_subtract_points` INT DEFAULT NULL COMMENT '单次扣分上限,NULL=无限制',
|
||||
`is_system` TINYINT(1) DEFAULT 0 COMMENT '系统预置组',
|
||||
`is_locked` TINYINT(1) DEFAULT 0 COMMENT '锁定组(不可编辑/删除/分配)',
|
||||
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY `uk_group_name` (`group_name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 管理员角色表(无班级ID)
|
||||
CREATE TABLE IF NOT EXISTS `admin_roles` (
|
||||
`admin_role_id` INT PRIMARY KEY AUTO_INCREMENT,
|
||||
`user_id` INT NOT NULL,
|
||||
`role_type` ENUM('班主任', '班长', '学习委员', '考勤委员', '劳动委员', '志愿委员') NOT NULL,
|
||||
`role_type` VARCHAR(50) NOT NULL COMMENT '权限组名称(冗余显示字段)',
|
||||
`group_id` INT DEFAULT NULL COMMENT '权限组ID',
|
||||
`subject_id` INT DEFAULT NULL,
|
||||
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`user_id`) ON DELETE CASCADE,
|
||||
FOREIGN KEY (`subject_id`) REFERENCES `subjects`(`subject_id`) ON DELETE CASCADE,
|
||||
UNIQUE KEY `uk_user_subject` (`user_id`, `subject_id`)
|
||||
FOREIGN KEY (`group_id`) REFERENCES `permission_groups`(`group_id`),
|
||||
UNIQUE KEY `uk_user_subject` (`user_id`, `subject_id`),
|
||||
INDEX `idx_admin_role_group` (`group_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 操行分记录表
|
||||
@@ -230,10 +252,32 @@ INSERT IGNORE INTO `subjects` (`subject_name`, `subject_code`, `sort_order`) VAL
|
||||
('数学', 'MATH', 2),
|
||||
('英语', 'ENG', 3);
|
||||
|
||||
-- 初始化系统版本号
|
||||
-- 插入预置权限组(与原有六种角色对应)
|
||||
INSERT IGNORE INTO `permission_groups`
|
||||
(`group_name`, `description`, `permissions`, `can_add_points`, `max_add_points`, `can_subtract_points`, `max_subtract_points`, `is_system`, `is_locked`)
|
||||
VALUES
|
||||
('班主任', '班主任(系统锁定组,拥有全部权限)',
|
||||
'{"manage_students":true,"export_students":true,"manage_conduct":true,"revoke_any":true,"revoke_own":true,"restore_records":true,"manage_homework":true,"manage_attendance":true,"manage_subjects":true,"manage_admins":true,"manage_semesters":true,"view_all_records":true,"export_data":true,"manage_upgrade":true}',
|
||||
1, NULL, 1, NULL, 1, 1),
|
||||
('班长', '班长(可调整权限与上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":true,"revoke_own":false,"restore_records":false,"manage_homework":false,"manage_attendance":false,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":true,"export_data":false,"manage_upgrade":false}',
|
||||
1, 5, 1, 5, 1, 0),
|
||||
('学习委员', '学习委员(可调整权限与上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":false,"restore_records":false,"manage_homework":true,"manage_attendance":false,"manage_subjects":true,"manage_admins":false,"manage_semesters":false,"view_all_records":false,"export_data":false,"manage_upgrade":false}',
|
||||
1, 5, 1, 5, 1, 0),
|
||||
('考勤委员', '考勤委员(仅扣分,可调整上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":true,"restore_records":false,"manage_homework":false,"manage_attendance":true,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":false,"export_data":false,"manage_upgrade":false}',
|
||||
0, NULL, 1, 8, 1, 0),
|
||||
('劳动委员', '劳动委员(可调整权限与上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":false,"restore_records":false,"manage_homework":false,"manage_attendance":false,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":false,"export_data":false,"manage_upgrade":false}',
|
||||
1, 1, 1, 1, 1, 0),
|
||||
('志愿委员', '志愿委员(仅加分,可调整上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":false,"restore_records":false,"manage_homework":false,"manage_attendance":false,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":true,"export_data":false,"manage_upgrade":false}',
|
||||
1, 5, 0, NULL, 1, 0);
|
||||
|
||||
-- 初始化系统版本号
|
||||
INSERT INTO `system_settings` (`setting_key`, `setting_value`)
|
||||
VALUES ('db_version', '2.7')
|
||||
ON DUPLICATE KEY UPDATE `setting_value` = '2.7';
|
||||
VALUES ('db_version', '4.1')
|
||||
ON DUPLICATE KEY UPDATE `setting_value` = '4.1';
|
||||
-- 控制台输出初始化结果(含版本号)
|
||||
SELECT CONCAT('数据库初始化完成!版本: v', (SELECT setting_value FROM system_settings WHERE setting_key = 'db_version')) AS message;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- ===========================================
|
||||
-- 班级操行分管理系统 - v2.9 → v3.0 升级脚本
|
||||
-- 字符集: utf8mb4
|
||||
--
|
||||
-- 说明: v3.0 为功能优化版本,无数据库 schema 变更。
|
||||
-- 主要变更:
|
||||
-- 1. 导出(德育分记录 / 历史记录)默认仅导出当前学期,可选历史学期/全部学期
|
||||
-- 2. 新增"个人查询"页面:基础分、加分、减分、月度分、月度加减分理由汇总
|
||||
-- 3. 历史记录接口支持 semester_id 过滤(兼容未关联学期的历史记录,按日期范围兜底)
|
||||
-- 4. 加减分/考勤记录创建时自动写入 semester_id
|
||||
-- ===========================================
|
||||
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,66 @@
|
||||
-- ===========================================
|
||||
-- 班级操行分管理系统 - v3.0 → v4.0 升级脚本
|
||||
-- 字符集: utf8mb4
|
||||
--
|
||||
-- 说明: v4.0 权限体系重构
|
||||
-- 1. 新增权限组表 permission_groups(自定义权限组 + 动态加减分上限)
|
||||
-- 2. admin_roles 增加 group_id,并将原有六种角色迁移为六个预置权限组
|
||||
-- (班主任组锁定不可编辑/删除/分配,其余预置组可编辑,可新建自定义组)
|
||||
-- 3. 每个权限组可配置:允许加分/加分上限/允许扣分/扣分上限
|
||||
-- 4. 新增学生名单导出能力(export_students)
|
||||
-- ===========================================
|
||||
|
||||
-- 权限组表
|
||||
CREATE TABLE IF NOT EXISTS `permission_groups` (
|
||||
`group_id` INT PRIMARY KEY AUTO_INCREMENT,
|
||||
`group_name` VARCHAR(50) NOT NULL COMMENT '权限组名称',
|
||||
`description` VARCHAR(255) DEFAULT NULL COMMENT '说明',
|
||||
`permissions` TEXT NOT NULL COMMENT '权限配置(JSON)',
|
||||
`can_add_points` TINYINT(1) DEFAULT 1 COMMENT '是否允许加分',
|
||||
`max_add_points` INT DEFAULT NULL COMMENT '单次加分上限,NULL=无限制',
|
||||
`can_subtract_points` TINYINT(1) DEFAULT 1 COMMENT '是否允许扣分',
|
||||
`max_subtract_points` INT DEFAULT NULL COMMENT '单次扣分上限,NULL=无限制',
|
||||
`is_system` TINYINT(1) DEFAULT 0 COMMENT '系统预置组',
|
||||
`is_locked` TINYINT(1) DEFAULT 0 COMMENT '锁定组(不可编辑/删除/分配)',
|
||||
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY `uk_group_name` (`group_name`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- 预置权限组(与原有六种角色一一对应)
|
||||
INSERT INTO `permission_groups`
|
||||
(`group_name`, `description`, `permissions`, `can_add_points`, `max_add_points`, `can_subtract_points`, `max_subtract_points`, `is_system`, `is_locked`)
|
||||
VALUES
|
||||
('班主任', '班主任(系统锁定组,拥有全部权限)',
|
||||
'{"manage_students":true,"export_students":true,"manage_conduct":true,"revoke_any":true,"revoke_own":true,"restore_records":true,"manage_homework":true,"manage_attendance":true,"manage_subjects":true,"manage_admins":true,"manage_semesters":true,"view_all_records":true,"export_data":true,"manage_upgrade":true}',
|
||||
1, NULL, 1, NULL, 1, 1),
|
||||
('班长', '班长(可调整权限与上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":true,"revoke_own":false,"restore_records":false,"manage_homework":false,"manage_attendance":false,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":true,"export_data":false,"manage_upgrade":false}',
|
||||
1, 5, 1, 5, 1, 0),
|
||||
('学习委员', '学习委员(可调整权限与上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":false,"restore_records":false,"manage_homework":true,"manage_attendance":false,"manage_subjects":true,"manage_admins":false,"manage_semesters":false,"view_all_records":false,"export_data":false,"manage_upgrade":false}',
|
||||
1, 5, 1, 5, 1, 0),
|
||||
('考勤委员', '考勤委员(仅扣分,可调整上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":true,"restore_records":false,"manage_homework":false,"manage_attendance":true,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":false,"export_data":false,"manage_upgrade":false}',
|
||||
0, NULL, 1, 8, 1, 0),
|
||||
('劳动委员', '劳动委员(可调整权限与上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":false,"restore_records":false,"manage_homework":false,"manage_attendance":false,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":false,"export_data":false,"manage_upgrade":false}',
|
||||
1, 1, 1, 1, 1, 0),
|
||||
('志愿委员', '志愿委员(仅加分,可调整上限)',
|
||||
'{"manage_students":false,"export_students":false,"manage_conduct":true,"revoke_any":false,"revoke_own":false,"restore_records":false,"manage_homework":false,"manage_attendance":false,"manage_subjects":false,"manage_admins":false,"manage_semesters":false,"view_all_records":true,"export_data":false,"manage_upgrade":false}',
|
||||
1, 5, 0, NULL, 1, 0)
|
||||
ON DUPLICATE KEY UPDATE `group_name` = `group_name`;
|
||||
|
||||
-- admin_roles 增加权限组关联
|
||||
ALTER TABLE `admin_roles` MODIFY COLUMN `role_type` VARCHAR(50) NOT NULL COMMENT '权限组名称(冗余显示字段)';
|
||||
|
||||
ALTER TABLE `admin_roles` ADD COLUMN `group_id` INT DEFAULT NULL COMMENT '权限组ID' AFTER `role_type`;
|
||||
|
||||
UPDATE `admin_roles` ar
|
||||
JOIN `permission_groups` pg ON pg.`group_name` = ar.`role_type`
|
||||
SET ar.`group_id` = pg.`group_id`
|
||||
WHERE ar.`group_id` IS NULL;
|
||||
|
||||
ALTER TABLE `admin_roles` ADD INDEX `idx_admin_role_group` (`group_id`);
|
||||
|
||||
ALTER TABLE `admin_roles` ADD CONSTRAINT `fk_admin_role_group` FOREIGN KEY (`group_id`) REFERENCES `permission_groups`(`group_id`);
|
||||
@@ -0,0 +1,12 @@
|
||||
-- ===========================================
|
||||
-- 班级操行分管理系统 - v4.0 → v4.1 升级脚本
|
||||
-- 字符集: utf8mb4
|
||||
--
|
||||
-- 说明: v4.1 邮箱与找回密码
|
||||
-- 1. users 表新增 email 字段(管理员可绑定邮箱)
|
||||
-- 2. 配合 SMTP 配置提供管理员找回密码功能
|
||||
-- ===========================================
|
||||
|
||||
ALTER TABLE `users` ADD COLUMN `email` VARCHAR(100) DEFAULT NULL COMMENT '绑定邮箱(用于找回密码)' AFTER `real_name`;
|
||||
|
||||
ALTER TABLE `users` ADD INDEX `idx_user_email` (`email`);
|
||||
@@ -33,6 +33,9 @@ $UPGRADE_VERSIONS = [
|
||||
'2.7' => __DIR__ . '/sql/upgrades/v2.7.sql',
|
||||
'2.8' => __DIR__ . '/sql/upgrades/v2.8.sql',
|
||||
'2.9' => __DIR__ . '/sql/upgrades/v2.9.sql',
|
||||
'3.0' => __DIR__ . '/sql/upgrades/v3.0.sql',
|
||||
'4.0' => __DIR__ . '/sql/upgrades/v4.0.sql',
|
||||
'4.1' => __DIR__ . '/sql/upgrades/v4.1.sql',
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user