Compare commits
33
Commits
3067542e53
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7304d151e | ||
|
|
0ac933a3a5 | ||
|
|
97f2de5d83 | ||
|
|
ad50f82c7b | ||
|
|
d9dd7bf7e8 | ||
|
|
928c86bd5a | ||
|
|
f624219cba | ||
|
|
db278188c6 | ||
|
|
2d3513b246 | ||
|
|
c87f62baf7 | ||
|
|
250acf35fd | ||
|
|
71c3263335 | ||
|
|
d0cdb5b928 | ||
|
|
dbf70f602e | ||
|
|
3a13656cfb | ||
|
|
fbd34b3d14 | ||
|
|
982e6ad70f | ||
|
|
4c1ca13a3f | ||
|
|
4c57ba3a30 | ||
|
|
c12381bd0b | ||
|
|
a51c8233ae | ||
|
|
768ea281e0 | ||
|
|
9a19add6c1 | ||
|
|
05790c1882 | ||
|
|
1068bc6def | ||
|
|
990f44bf22 | ||
|
|
ed3189096d | ||
|
|
8cd2c83412 | ||
|
|
6c8fd2b432 | ||
|
|
7d22b2b922 | ||
|
|
09c585e229 | ||
|
|
058dee9dc4 | ||
|
|
3588b4c28c |
No files matched your search
+13
@@ -332,6 +332,19 @@ 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 |
|
||||
| `EMAIL_CODE_EXPIRE_MINUTES` | 邮箱绑定验证码有效期(分钟) | 10 |
|
||||
|
||||
> 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -21,37 +21,29 @@
|
||||
### 管理端
|
||||
|
||||
**班主任权限:**
|
||||
- 学生管理:新增/编辑/删除学生、批量导入学生(JSON)
|
||||
- 操行分管理:对学生进行加减分、撤销任何扣分记录、查看全班历史记录、导出德育分记录
|
||||
- 作业管理:发布作业、查看提交情况
|
||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值
|
||||
- 学生管理:新增/编辑/删除学生、批量导入学生(JSON)、按自选字段导出学生名单(CSV)
|
||||
- 操行分管理:对学生进行加减分、撤销任何扣分记录、查看全班历史记录、按学期导出德育分记录(含基础分/加分/减分拆分)
|
||||
- 作业管理:批量加减分(未交/迟交/自定义扣分);按次登记(一次登记覆盖多次作业,配置总提交次数,按每人缺交次数自动扣分并写入提交数据,供作业统计报表使用)
|
||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值;支持"默认出勤"按日期范围批量补全(跳过周末与法定节假日,调休补班与手动补课日照常)及节假日/补课校历设置
|
||||
- 科目管理:动态增删学科
|
||||
- 管理员管理:添加/编辑/禁用-启用/重置密码班长/科代表/考勤委员/劳动委员/志愿委员
|
||||
- 权限组管理:权限组全部可自定义(编辑权限项、加减分上限,任意组可编辑/删除/分配),管理员账号绑定权限组与邮箱
|
||||
- 密码找回:管理员绑定邮箱(自助绑定需 SMTP 邮箱验证码,无需密码),忘记密码时可在登录页通过邮箱获取一次性重置链接(限时、仅可使用一次)
|
||||
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
||||
- 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法)
|
||||
- 数据导出:导出历史记录、导出德育分记录(含加分/减分历史)
|
||||
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
||||
- 排行榜:支持总分排行与月度分排行(可选月份查看当月加分/减分/月度分),支持百分比筛选显示前N%的学生(抹零法)与一键导出CSV
|
||||
- 数据报表:考勤统计与作业统计(按日期范围),含汇总与每人明细,可导出CSV
|
||||
- 操作日志:管理端可查询操作日志(操作类型/操作人/日期筛选,分页展示)
|
||||
- 系统设置:密码策略可配置(长度范围与最少字符种类数),全站即时生效
|
||||
- 学期归档对比:查看归档数据时展示与上一归档学期的分数变化与名次升降
|
||||
- 数据导出:按学期导出历史记录、导出德育分记录(默认当前学期,可选历史学期/全部学期)
|
||||
- 默认出勤:按日期范围给缺失学生批量补"出勤"记录(跳过周末/法定节假日,调休补班与手动补课日照常,已有记录不覆盖);节假日数据来自在线接口,支持手动添加放假/补课
|
||||
|
||||
**班长权限:**
|
||||
- 操行分管理:对学生进行加减分(±5分以内)、撤销任何人的扣分记录、查看全班历史记录
|
||||
**管理员/班干部权限(v4.0 起由权限组动态控制):**
|
||||
- 管理员账号绑定一个权限组,权限组可自定义以下能力与上限:
|
||||
- 功能权限:学生管理、导出学生名单、操行分加减、撤销他人/撤销自己记录、反撤销、作业扣分、作业按次登记、考勤管理、考勤默认出勤、节假日/补课设置、科目管理、查看全班/个人查询、数据报表查看、数据导出、操作日志查看、系统设置、管理员管理、学期管理、系统升级
|
||||
- 加减分上限:是否允许加分、单次加分上限、是否允许扣分、单次扣分上限(留空为无限制)
|
||||
- 系统预置六个权限组(班主任/班长/学习委员/考勤委员/劳动委员/志愿委员),默认权限与原角色一致,可随时调整上限或新建自定义组
|
||||
|
||||
**学习委员权限:**
|
||||
- 作业管理:更新作业提交状态、关联扣分(仅扣分,按规则)
|
||||
- 科目管理:动态增删学科
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
**考勤委员权限:**
|
||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤状态、关联扣分(仅扣分,按规则)
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
**劳动委员权限:**
|
||||
- 操行分管理:以卫生值日为理由进行加减分(固定 ±1 分)
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
**志愿委员权限:**
|
||||
- 操行分管理:以服务时长为由进行加分(仅加分)
|
||||
- 历史记录:仅查看自己提交的操作记录
|
||||
|
||||
## 技术栈
|
||||
## 安全特性
|
||||
|
||||
- JWT Token + PHP Session 双轨制认证
|
||||
@@ -69,7 +61,9 @@
|
||||
| 后端框架 | FastAPI | 0.104+ |
|
||||
| 数据库 | MySQL | 5.7 |
|
||||
| 缓存 | Redis | 7.x |
|
||||
| 前端 | PHP | 8.0 |
|
||||
| 前端 | PHP | 8.4 |
|
||||
|
||||
> 前端要求 **PHP 8.4+**:旧版本已停止安全维护、存在已知 CVE,低于 8.4 时前端将拒绝运行并提示升级。
|
||||
| Web服务器 | Nginx | 1.28+ |
|
||||
## 文件结构
|
||||
|
||||
@@ -102,9 +96,12 @@ classmanager/
|
||||
│ │ ├── conduct.py # 操行分模型
|
||||
│ │ ├── homework.py # 作业模型
|
||||
│ │ ├── log.py # 日志模型
|
||||
│ │ ├── permission_group.py # 权限组模型(功能权限+加减分上限)
|
||||
│ │ ├── report.py # 统计报表模型
|
||||
│ │ ├── semester.py # 学期模型
|
||||
│ │ ├── student.py # 学生模型
|
||||
│ │ ├── subject.py # 科目模型
|
||||
│ │ ├── system_setting.py # 系统设置模型(密码策略等)
|
||||
│ │ └── user.py # 用户模型
|
||||
│ │
|
||||
│ ├── routes/ # API 路由
|
||||
@@ -113,6 +110,7 @@ classmanager/
|
||||
│ │ ├── auth.py # 认证接口
|
||||
│ │ ├── debug.py # 调试入口
|
||||
│ │ ├── parent.py # 家长端接口
|
||||
│ │ ├── report.py # 统计报表接口
|
||||
│ │ ├── semester.py # 学期管理接口
|
||||
│ │ ├── student.py # 学生端接口
|
||||
│ │ └── subject.py # 科目管理接口
|
||||
@@ -135,26 +133,33 @@ classmanager/
|
||||
│ │ ├── auth_service.py
|
||||
│ │ ├── conduct_service.py
|
||||
│ │ ├── homework_service.py
|
||||
│ │ ├── holiday_service.py # 节假日接口服务(缓存+降级)
|
||||
│ │ ├── log_service.py
|
||||
│ │ ├── parent_service.py
|
||||
│ │ ├── semester_service.py # 学期服务
|
||||
│ │ ├── report_service.py # 统计报表服务
|
||||
│ │ ├── semester_service.py # 学期服务
|
||||
│ │ ├── setting_service.py # 系统设置服务
|
||||
│ │ ├── student_service.py
|
||||
│ │ └── subject_service.py
|
||||
│ │
|
||||
│ └── 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 # 管理员管理
|
||||
@@ -163,8 +168,12 @@ classmanager/
|
||||
│ │ ├── dashboard.php # 管理端首页
|
||||
│ │ ├── history.php # 历史记录
|
||||
│ │ ├── homework.php # 作业管理
|
||||
│ │ ├── logs.php # 操作日志
|
||||
│ │ ├── password.php # 修改密码
|
||||
│ │ ├── record_query.php # 个人记录查询(基础分/月度分/理由汇总)
|
||||
│ │ ├── reports.php # 数据报表(考勤/作业)
|
||||
│ │ ├── semesters.php # 学期管理
|
||||
│ │ ├── settings.php # 系统设置(密码策略)
|
||||
│ │ ├── students.php # 学生管理
|
||||
│ │ └── subjects.php # 科目管理
|
||||
│ │
|
||||
@@ -176,9 +185,12 @@ classmanager/
|
||||
│ │ │ ├── admin.css # 管理端样式
|
||||
│ │ │ └── style.css # 全局样式
|
||||
│ │ ├── js/
|
||||
│ │ │ ├── admin.js # 管理端 JS
|
||||
│ │ │ ├── common.js # 公共 JS
|
||||
│ │ │ ├── logs.js # 操作日志 JS
|
||||
│ │ │ ├── parent.js # 家长端 JS
|
||||
│ │ │ ├── record-query.js # 个人记录查询 JS
|
||||
│ │ │ ├── reports.js # 数据报表 JS
|
||||
│ │ │ ├── settings.js # 系统设置 JS
|
||||
│ │ │ └── student.js # 学生端 JS
|
||||
│ │ └── uploads/
|
||||
│ │ └── sample_import.json # 学生导入示例
|
||||
@@ -202,7 +214,9 @@ classmanager/
|
||||
│ └── semester_history.php # 学期记录
|
||||
│
|
||||
├── sql/ # 数据库脚本
|
||||
│ └── init.sql # 初始化表结构
|
||||
│ ├── init.sql # 初始化表结构
|
||||
│ └── upgrades/ # 增量升级脚本
|
||||
│ └── v3.0.sql # 最新升级脚本
|
||||
│
|
||||
├── docs/ # 文档
|
||||
│ ├── student.md # 学生端详细文档
|
||||
@@ -222,16 +236,26 @@ classmanager/
|
||||
|
||||
```
|
||||
|
||||
## 角色权限一览表
|
||||
## 权限说明(v4.0 权限组)
|
||||
|
||||
| 角色 | 操行分查看 | 操行分加减 | 撤销扣分 | 历史记录查看 | 其他权限 |
|
||||
| 项目 | 说明 |
|
||||
|------|------|
|
||||
| 权限模型 | 管理员账号绑定一个权限组;权限组由「功能权限 + 加减分上限」组成,可在管理端动态配置 |
|
||||
| 预置权限组 | 系统预置六个权限组(班主任/班长/学习委员/考勤委员/劳动委员/志愿委员)作为初始模板,全部可编辑、删除、分配给任意账号 |
|
||||
| 自定义权限组 | 可新建自定义组(如"纪律委员"),自由勾选 14 项功能权限并设置加分/扣分上限 |
|
||||
| 加减分上限 | 每项操作按权限组的"允许加分/加分上限/允许扣分/扣分上限"校验(前后端一致),留空表示无限制 |
|
||||
| 生效方式 | 权限组调整后,相关管理员刷新页面或最多 60 秒后自动生效 |
|
||||
|
||||
### 预置权限组默认权限
|
||||
|
||||
| 权限组 | 操行分查看 | 操行分加减 | 撤销扣分 | 历史记录查看 | 其他权限 |
|
||||
|------|-----------|-----------|---------|-------------|---------|
|
||||
| 班主任 | 全班 | 无限制 | 可撤销任何记录 | 全班所有记录 | 学生/管理员/科目管理、数据导出 |
|
||||
| 班长 | 全班 | ±5分 | 可撤销任何记录 | 全班所有记录 | - |
|
||||
| 班主任 | 全班 | 无限制 | 可撤销任何记录 | 全班所有记录 | 全部权限(可调整) |
|
||||
| 班长 | 全班 | ±5分 | 可撤销任何记录 | 全班所有记录 | 个人查询 |
|
||||
| 学习委员 | 全班 | ±5分以内(加减分) | 不可撤销 | 仅自己提交的 | 作业管理、科目管理 |
|
||||
| 考勤委员 | 全班 | 仅扣分,最多扣8分 | 不可撤销 | 仅自己提交的 | 考勤管理 |
|
||||
| 考勤委员 | 全班 | 仅扣分,最多扣8分 | 仅撤销自己的记录 | 仅自己提交的 | 考勤管理 |
|
||||
| 劳动委员 | 全班 | ±1分以内 | 不可撤销 | 仅自己提交的 | - |
|
||||
| 志愿委员 | 全班 | 仅加分,最多+5分 | 不可撤销 | 仅自己提交的 | - |
|
||||
| 志愿委员 | 全班 | 仅加分,最多+5分 | 不可撤销 | 仅自己提交的 | 个人查询 |
|
||||
| 学生 | 自己 | 无 | 无 | 自己的历史 | 修改密码 |
|
||||
| 家长 | 子女总分 | 无 | 无 | 不可见详情 | - |
|
||||
|
||||
@@ -281,6 +305,13 @@ 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.18 | 管理员可绑定邮箱;自助绑定采用 SMTP 验证码(10分钟有效、限流+尝试次数限制,无需密码),忘记密码使用一次性重置链接(30分钟有效);权限组全部可自定义(可编辑/删除/分配,无锁定预置);个人查询月度分独立计算(与基础分无关,总分=基础分+加减分);登录链路不依赖新表新列,旧库可登录后弹窗升级 |
|
||||
| v4.2 | 2026.9.18 | 科目管理优化:科目代码长度放宽至50(数据库+校验)、编辑可清空代码、重命名查重、支持 ↑↓ 快捷排序(批量重排接口);新增邮件测试入口;密码加密改用 bcrypt 库直连(修复 passlib 兼容问题);前端统一展示422校验错误 |
|
||||
| v4.3 | 2026.10.9 | 新增月度分排行:管理端首页可在"总分排行/月度分排行"间切换,月度排行可按月份查看加分、减分、月度分并支持百分比筛选;SMTP 配置读取加固(显式 backend/.env、兼容 BOM 与布尔拼写)、邮件日志降噪、/api/config 公开路径修复 |
|
||||
| v4.4 | 2026.10.9 | 新增数据报表(考勤/作业统计,可按日期范围查询与导出)、操作日志查看页、系统设置(密码策略可配置并全站生效);排行榜支持导出CSV;学期归档展示与上一学期的分数/名次环比;历史记录导出支持"按学生分表";移动端适配优化(导航横向滚动、表格触控滚动、弹窗与字号调整) |
|
||||
| v4.5 | 2026.10.10 | 新增考勤"默认出勤"批量补全:按日期范围给缺失学生补出勤(跳过周末与法定节假日,调休补班与手动补课日照常,已有记录不覆盖);节假日数据在线接口获取(缓存+失败降级);支持手动添加放假/补课校历设置;新增作业"按次登记":一次登记覆盖多次作业,配置总提交次数,按每人缺交次数自动扣分并写入作业提交数据;将数据报表/操作日志/系统设置等新功能拆分为独立权限项(共20项功能权限可配置) |
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
+29
-26
@@ -1,5 +1,5 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 前端配置
|
||||
# 班级操行分管理系统 - 后端配置
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
@@ -35,7 +35,6 @@ DB_USER=class_admin
|
||||
DB_PASSWORD=your-strong-db-password
|
||||
DB_NAME=classmanagerdb
|
||||
DB_POOL_SIZE=10
|
||||
DB_MAX_OVERFLOW=20
|
||||
|
||||
# ===========================================
|
||||
# Redis 缓存配置
|
||||
@@ -92,40 +91,44 @@ DEDUCTION_ATTENDANCE_LATE=1
|
||||
DEDUCTION_ATTENDANCE_LEAVE=0
|
||||
|
||||
# ===========================================
|
||||
# 劳动委员固定分值配置
|
||||
# 站点地址与 SMTP 邮件配置(管理员找回密码)
|
||||
# ===========================================
|
||||
|
||||
LABOR_POINTS_ADD=1
|
||||
LABOR_POINTS_SUBTRACT=-1
|
||||
# 前端站点地址 - 用于生成密码重置链接(注意结尾不要带斜杠)
|
||||
FRONTEND_URL=https://class.example.com
|
||||
|
||||
# ===========================================
|
||||
# 各角色加减分限制配置
|
||||
# ===========================================
|
||||
|
||||
# 班长单次加分上限
|
||||
MONITOR_MAX_ADD=5
|
||||
# 班长单次扣分上限(负数)
|
||||
MONITOR_MAX_SUBTRACT=-5
|
||||
|
||||
# 学习委员单次加减分上限(绝对值)
|
||||
STUDY_COMMISSIONER_MAX_POINTS=5
|
||||
|
||||
# 考勤委员单次扣分上限(绝对值)
|
||||
ATTENDANCE_REP_MAX_POINTS=8
|
||||
|
||||
# 劳动委员单次加减分上限(绝对值)
|
||||
LABOR_REP_MAX_POINTS=1
|
||||
|
||||
# 志愿委员单次加分上限
|
||||
VOLUNTEER_REP_MAX_POINTS=5
|
||||
# 是否启用邮件功能 - 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
|
||||
# 邮箱绑定验证码有效期(分钟)
|
||||
EMAIL_CODE_EXPIRE_MINUTES=10
|
||||
|
||||
# ===========================================
|
||||
# 日志配置
|
||||
# ===========================================
|
||||
|
||||
# 控制台日志级别:DEBUG/INFO/WARNING/ERROR
|
||||
# 不填写时跟随 DEBUG(DEBUG=true 时为 DEBUG,否则 INFO);文件 app.log 始终记录 DEBUG
|
||||
LOG_LEVEL=INFO
|
||||
# 单文件日志大小上限(字节),超过后轮转
|
||||
LOG_MAX_BYTES=104857600
|
||||
LOG_BACKUP_COUNT=30
|
||||
LOG_RETENTION_DAYS=365
|
||||
|
||||
# ===========================================
|
||||
|
||||
+34
-17
@@ -13,14 +13,26 @@ import os
|
||||
from dotenv import load_dotenv
|
||||
from typing import List
|
||||
|
||||
load_dotenv()
|
||||
# 始终加载 backend/.env(显式路径,避免受工作目录影响)
|
||||
# encoding 用 utf-8-sig,兼容 Windows 记事本保存的 UTF-8 BOM
|
||||
_ENV_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
|
||||
load_dotenv(_ENV_FILE, encoding="utf-8-sig")
|
||||
|
||||
def _env_bool(name: str, default: bool = False) -> bool:
|
||||
"""布尔环境变量:仅显式的 false/0/no/off 视为关闭,其余(含拼写容错)视为开启"""
|
||||
value = (os.getenv(name) or "").strip().lower()
|
||||
if value == "":
|
||||
return default
|
||||
return value not in ("false", "0", "no", "off")
|
||||
|
||||
class Settings:
|
||||
APP_NAME: str = os.getenv("APP_NAME", "班级操行分管理系统")
|
||||
APP_ENV: str = os.getenv("APP_ENV", "production")
|
||||
DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"
|
||||
DEBUG: bool = _env_bool("DEBUG", False)
|
||||
SECRET_KEY: str = os.getenv("SECRET_KEY", "")
|
||||
API_VERSION: str = os.getenv("API_VERSION", "v1")
|
||||
# 当前加载的配置文件路径(用于启动日志排查)
|
||||
ENV_FILE: str = _ENV_FILE
|
||||
|
||||
DB_HOST: str = os.getenv("DB_HOST", "127.0.0.1")
|
||||
DB_PORT: int = int(os.getenv("DB_PORT", "3306"))
|
||||
@@ -28,7 +40,6 @@ class Settings:
|
||||
DB_PASSWORD: str = os.getenv("DB_PASSWORD", "")
|
||||
DB_NAME: str = os.getenv("DB_NAME", "classmanagerdb")
|
||||
DB_POOL_SIZE: int = int(os.getenv("DB_POOL_SIZE", "10"))
|
||||
DB_MAX_OVERFLOW: int = int(os.getenv("DB_MAX_OVERFLOW", "20"))
|
||||
|
||||
REDIS_HOST: str = os.getenv("REDIS_HOST", "127.0.0.1")
|
||||
REDIS_PORT: int = int(os.getenv("REDIS_PORT", "6379"))
|
||||
@@ -48,29 +59,35 @@ class Settings:
|
||||
JWT_IDLE_TIMEOUT_MINUTES: int = int(os.getenv("JWT_IDLE_TIMEOUT_MINUTES", "10"))
|
||||
|
||||
PASSWORD_SALT: str = os.getenv("PASSWORD_SALT", "")
|
||||
DEBUG_ENABLED: bool = os.getenv("DEBUG_ENABLED", "False").lower() == "true"
|
||||
DEBUG_ENABLED: bool = _env_bool("DEBUG_ENABLED", False)
|
||||
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 = _env_bool("SMTP_ENABLED", False)
|
||||
SMTP_HOST: str = os.getenv("SMTP_HOST", "").strip()
|
||||
SMTP_PORT: int = int(os.getenv("SMTP_PORT", "465"))
|
||||
SMTP_USER: str = os.getenv("SMTP_USER", "").strip()
|
||||
SMTP_PASSWORD: str = os.getenv("SMTP_PASSWORD", "")
|
||||
# 发件人邮箱默认与登录账号一致
|
||||
SMTP_FROM: str = os.getenv("SMTP_FROM", "").strip() or SMTP_USER
|
||||
SMTP_FROM_NAME: str = os.getenv("SMTP_FROM_NAME", os.getenv("APP_NAME", "班级操行分管理系统"))
|
||||
SMTP_SSL: bool = _env_bool("SMTP_SSL", True)
|
||||
SMTP_STARTTLS: bool = _env_bool("SMTP_STARTTLS", False)
|
||||
# 密码重置链接有效期(分钟)
|
||||
PASSWORD_RESET_EXPIRE_MINUTES: int = int(os.getenv("PASSWORD_RESET_EXPIRE_MINUTES", "30"))
|
||||
# 邮箱验证码有效期(分钟)
|
||||
EMAIL_CODE_EXPIRE_MINUTES: int = int(os.getenv("EMAIL_CODE_EXPIRE_MINUTES", "10"))
|
||||
|
||||
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"))
|
||||
DEDUCTION_ATTENDANCE_LATE: int = int(os.getenv("DEDUCTION_ATTENDANCE_LATE", "1"))
|
||||
DEDUCTION_ATTENDANCE_LEAVE: int = int(os.getenv("DEDUCTION_ATTENDANCE_LEAVE", "0"))
|
||||
|
||||
LABOR_POINTS_ADD: int = int(os.getenv("LABOR_POINTS_ADD", "1"))
|
||||
LABOR_POINTS_SUBTRACT: int = int(os.getenv("LABOR_POINTS_SUBTRACT", "-1"))
|
||||
|
||||
MONITOR_MAX_ADD: int = int(os.getenv("MONITOR_MAX_ADD", "5"))
|
||||
MONITOR_MAX_SUBTRACT: int = int(os.getenv("MONITOR_MAX_SUBTRACT", "-5"))
|
||||
|
||||
STUDY_COMMISSIONER_MAX_POINTS: int = int(os.getenv("STUDY_COMMISSIONER_MAX_POINTS", "5"))
|
||||
ATTENDANCE_REP_MAX_POINTS: int = int(os.getenv("ATTENDANCE_REP_MAX_POINTS", "8"))
|
||||
LABOR_REP_MAX_POINTS: int = int(os.getenv("LABOR_REP_MAX_POINTS", "1"))
|
||||
VOLUNTEER_REP_MAX_POINTS: int = int(os.getenv("VOLUNTEER_REP_MAX_POINTS", "5"))
|
||||
|
||||
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "DEBUG" if _env_bool("DEBUG", False) else "INFO")
|
||||
LOG_MAX_BYTES: int = int(os.getenv("LOG_MAX_BYTES", "104857600"))
|
||||
LOG_BACKUP_COUNT: int = int(os.getenv("LOG_BACKUP_COUNT", "30"))
|
||||
LOG_RETENTION_DAYS: int = int(os.getenv("LOG_RETENTION_DAYS", "365"))
|
||||
|
||||
@property
|
||||
|
||||
+26
-3
@@ -15,13 +15,15 @@ from fastapi.responses import JSONResponse
|
||||
from contextlib import asynccontextmanager
|
||||
import traceback
|
||||
import uvicorn
|
||||
from pymysql import err as pymysql_err
|
||||
|
||||
from config import settings
|
||||
from utils.logger import setup_logger, log_access
|
||||
from utils.database import init_db_pool, close_db_pool
|
||||
from utils.redis_client import init_redis_pool, close_redis_pool
|
||||
from utils.email_sender import EmailSender
|
||||
from middleware.auth_middleware import AuthMiddleware
|
||||
from routes import auth, student, parent, admin, subject, semester, debug, upgrade
|
||||
from routes import auth, student, parent, admin, subject, semester, debug, upgrade, report
|
||||
from routes.config import router as config_router
|
||||
|
||||
|
||||
@@ -36,6 +38,15 @@ async def lifespan(app: FastAPI):
|
||||
await init_db_pool()
|
||||
await init_redis_pool()
|
||||
logger.info(f"CORS 允许域名: {settings.CORS_ORIGINS}")
|
||||
logger.info(f"配置文件: {settings.ENV_FILE}")
|
||||
missing_email = EmailSender.missing_config()
|
||||
if missing_email:
|
||||
logger.warning(f"邮件服务: 未启用或配置不完整,需设置: {', '.join(missing_email)}")
|
||||
else:
|
||||
logger.info(
|
||||
f"邮件服务: 已启用 {settings.SMTP_HOST}:{settings.SMTP_PORT} "
|
||||
f"(账号 {settings.SMTP_USER}, 发件人 {settings.SMTP_FROM})"
|
||||
)
|
||||
logger.info(f"{settings.APP_NAME} 启动完成")
|
||||
|
||||
yield
|
||||
@@ -85,7 +96,18 @@ app.add_middleware(
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
"""全局异常处理器 - 捕获所有未处理异常"""
|
||||
logger.error(f"未处理异常: {exc}", exc_info=True)
|
||||
# 数据库缺表/缺列的常见错误码(1064/1146 等),提示先完成系统升级
|
||||
missing_schema_errnos = {1054, 1146}
|
||||
errno = None
|
||||
if isinstance(exc, pymysql_err.MySQLError) and exc.args:
|
||||
errno = exc.args[0]
|
||||
|
||||
if errno in missing_schema_errnos:
|
||||
logger.error(f"数据库结构不匹配(可能待升级): {request.method} {request.url.path} - {exc}")
|
||||
message = "数据库待升级,请先完成系统升级"
|
||||
else:
|
||||
logger.error(f"未处理异常: {exc}", exc_info=True)
|
||||
message = f"服务器内部错误: {str(exc)}"
|
||||
|
||||
# 获取origin用于CORS头
|
||||
origin = request.headers.get("origin", "")
|
||||
@@ -104,7 +126,7 @@ async def global_exception_handler(request: Request, exc: Exception):
|
||||
content={
|
||||
"success": False,
|
||||
"code": 500,
|
||||
"message": f"服务器内部错误: {str(exc)}",
|
||||
"message": message,
|
||||
"detail": traceback.format_exc() if settings.DEBUG else None
|
||||
},
|
||||
headers=headers
|
||||
@@ -118,6 +140,7 @@ app.include_router(parent.router, prefix="/api/parent", tags=["家长端"])
|
||||
app.include_router(admin.router, prefix="/api/admin", tags=["管理端"])
|
||||
app.include_router(subject.router, prefix="/api/subject", tags=["科目管理"])
|
||||
app.include_router(semester.router, prefix="/api/semester", tags=["学期管理"])
|
||||
app.include_router(report.router, prefix="/api/report", tags=["统计报表"])
|
||||
app.include_router(config_router, prefix="/api/config", tags=["配置"])
|
||||
app.include_router(upgrade.router, prefix="/api/upgrade", tags=["升级管理"])
|
||||
app.include_router(debug.router, tags=["调试"])
|
||||
|
||||
@@ -11,24 +11,24 @@
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from typing import Optional, Dict, Any
|
||||
import re
|
||||
|
||||
from config import settings
|
||||
from utils.jwt_handler import jwt_handler
|
||||
from utils.redis_client import RedisClient
|
||||
from utils.response import unauthorized_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 不需要认证的路由
|
||||
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$',
|
||||
r'^/api/config/deduction-rules$',
|
||||
]
|
||||
def is_public_path(path: str) -> bool:
|
||||
"""检查是否为公开路径"""
|
||||
@@ -57,30 +57,30 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
logger.debug(f"[Auth] {request.method} {path} - 公开路径,跳过认证")
|
||||
return await call_next(request)
|
||||
|
||||
logger.info(f"[Auth] {request.method} {path} - 开始认证")
|
||||
logger.debug(f"[Auth] {request.method} {path} - 开始认证")
|
||||
|
||||
try:
|
||||
# 获取Authorization头
|
||||
auth_header = request.headers.get("Authorization")
|
||||
|
||||
if not auth_header:
|
||||
logger.warning(f"[Auth] {path} - 缺少Authorization header")
|
||||
logger.debug(f"[Auth] {path} - 缺少Authorization header")
|
||||
return self._cors_response(request, 401, "缺少认证令牌")
|
||||
|
||||
# 解析Bearer Token
|
||||
try:
|
||||
scheme, token = auth_header.split()
|
||||
if scheme.lower() != "bearer":
|
||||
logger.warning(f"[Auth] {path} - Authorization header格式错误")
|
||||
logger.debug(f"[Auth] {path} - Authorization header格式错误")
|
||||
return self._cors_response(request, 401, "认证格式错误")
|
||||
except ValueError:
|
||||
logger.warning(f"[Auth] {path} - Authorization header格式错误")
|
||||
logger.debug(f"[Auth] {path} - Authorization header格式错误")
|
||||
return self._cors_response(request, 401, "认证格式错误")
|
||||
|
||||
# 验证Token
|
||||
payload = jwt_handler.verify_token(token)
|
||||
if not payload:
|
||||
logger.warning(f"[Auth] {path} - JWT验证失败")
|
||||
logger.debug(f"[Auth] {path} - JWT验证失败")
|
||||
return self._cors_response(request, 401, "令牌无效或已过期")
|
||||
|
||||
# 验证Redis中的Token
|
||||
@@ -88,7 +88,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
stored_token = await RedisClient.get_user_token(user_id)
|
||||
|
||||
if not stored_token or stored_token != token:
|
||||
logger.warning(f"[Auth] {path} - Redis Token不匹配, user_id={user_id}, stored={'有' if stored_token else '无'}")
|
||||
logger.debug(f"[Auth] {path} - Redis Token不匹配, user_id={user_id}")
|
||||
return self._cors_response(request, 401, "令牌已失效,请重新登录")
|
||||
|
||||
# 将用户信息存储到request.state
|
||||
|
||||
@@ -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")
|
||||
@@ -1,138 +0,0 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from typing import Dict, Any
|
||||
import re
|
||||
|
||||
|
||||
class SanitizeMiddleware(BaseHTTPMiddleware):
|
||||
"""输入过滤中间件"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
# 只处理POST、PUT、PATCH请求
|
||||
if request.method in ["POST", "PUT", "PATCH"]:
|
||||
# 获取请求体
|
||||
body = await request.body()
|
||||
if body:
|
||||
import json
|
||||
try:
|
||||
data = json.loads(body)
|
||||
# 清理数据
|
||||
cleaned_data = self._sanitize_data(data)
|
||||
# 替换请求体
|
||||
request._body = json.dumps(cleaned_data).encode()
|
||||
except:
|
||||
pass
|
||||
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
def _sanitize_data(self, data: Any) -> Any:
|
||||
"""递归清理数据"""
|
||||
if isinstance(data, dict):
|
||||
return {k: self._sanitize_data(v) for k, v in data.items()}
|
||||
elif isinstance(data, list):
|
||||
return [self._sanitize_data(item) for item in data]
|
||||
elif isinstance(data, str):
|
||||
return self._sanitize_string(data)
|
||||
else:
|
||||
return data
|
||||
|
||||
def _sanitize_string(self, value: str) -> str:
|
||||
"""清理字符串"""
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
# 去除首尾空格
|
||||
value = value.strip()
|
||||
|
||||
# SQL注入模式检测
|
||||
sql_patterns = [
|
||||
r'(?i)(\bunion\b\s+\bselect\b)',
|
||||
r'(?i)(\bor\b\s+\d+\s*=\s*\d+)',
|
||||
r'(?i)(\bdrop\b\s+\btable\b)',
|
||||
r'(?i)(\bdelete\b\s+\bfrom\b)',
|
||||
r'(?i)(\binsert\b\s+\binto\b)',
|
||||
r'(?i)(\bupdate\b\s+\w+\s+\bset\b)',
|
||||
]
|
||||
for pattern in sql_patterns:
|
||||
value = re.sub(pattern, '', value)
|
||||
|
||||
# 路径遍历检测
|
||||
value = value.replace('../', '').replace('..\\', '')
|
||||
|
||||
# 限制长度
|
||||
if len(value) > 1000:
|
||||
value = value[:1000]
|
||||
|
||||
# 转义HTML特殊字符
|
||||
html_chars = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/'
|
||||
}
|
||||
for char, escape in html_chars.items():
|
||||
value = value.replace(char, escape)
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def sanitize_input(value: str, max_length: int = 255) -> str:
|
||||
"""清理单个输入值"""
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
value = value.strip()
|
||||
if len(value) > max_length:
|
||||
value = value[:max_length]
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def validate_points(points: int, min_val: int = -100, max_val: int = 100) -> tuple:
|
||||
"""
|
||||
验证分值
|
||||
返回: (是否有效, 错误信息)
|
||||
"""
|
||||
if points == 0:
|
||||
return False, "分值不能为0"
|
||||
if points < min_val or points > max_val:
|
||||
return False, f"分值必须在{min_val}到{max_val}之间"
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_reason(reason: str) -> tuple:
|
||||
"""
|
||||
验证原因
|
||||
返回: (是否有效, 错误信息)
|
||||
"""
|
||||
if not reason or not reason.strip():
|
||||
return False, "原因不能为空"
|
||||
# 计算可见字符长度(不含换行符),支持多行输入
|
||||
visible_length = len(reason.replace('\n', ''))
|
||||
if visible_length > 255:
|
||||
return False, "原因长度不能超过255个字符"
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_date(date_str: str) -> bool:
|
||||
"""验证日期格式 YYYY-MM-DD"""
|
||||
if not date_str:
|
||||
return False
|
||||
pattern = r'^\d{4}-\d{2}-\d{2}$'
|
||||
if not re.match(pattern, date_str):
|
||||
return False
|
||||
return True
|
||||
@@ -11,52 +11,95 @@
|
||||
|
||||
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
|
||||
from models.permission_group import apply_legacy_group_fields
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
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
|
||||
"""
|
||||
return await execute_one(sql, (user_id,))
|
||||
try:
|
||||
return await execute_one(sql, (user_id,))
|
||||
except Exception as e:
|
||||
# 数据库尚未升级(缺少 group_id / permission_groups)时按旧角色降级
|
||||
logger.warning(f"读取管理员角色失败,按旧角色降级(数据库可能待升级): {e}")
|
||||
legacy_sql = """
|
||||
SELECT ar.*, s.subject_name
|
||||
FROM admin_roles ar
|
||||
LEFT JOIN subjects s ON ar.subject_id = s.subject_id
|
||||
WHERE ar.user_id = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
return apply_legacy_group_fields(await execute_one(legacy_sql, (user_id,)))
|
||||
|
||||
@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)
|
||||
try:
|
||||
return await execute_query(sql)
|
||||
except Exception as e:
|
||||
# 数据库尚未升级(缺少 group_id / permission_groups / users.email)时降级
|
||||
logger.warning(f"读取管理员列表失败,按旧角色降级(数据库可能待升级): {e}")
|
||||
legacy_sql = """
|
||||
SELECT ar.*, u.real_name, u.username, u.status, s.subject_name
|
||||
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.user_id
|
||||
"""
|
||||
rows = await execute_query(legacy_sql)
|
||||
return [apply_legacy_group_fields(row) for row in rows]
|
||||
|
||||
@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:
|
||||
sql = "DELETE FROM admin_roles WHERE user_id = %s"
|
||||
result = await execute_update(sql, (user_id,))
|
||||
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
|
||||
@@ -9,8 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
|
||||
|
||||
@@ -41,9 +40,22 @@ class AttendanceModel:
|
||||
slot: str = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
sql = """
|
||||
SELECT ar.*, s.name as student_name, s.student_no
|
||||
SELECT ar.*, s.name as student_name, s.student_no,
|
||||
u.real_name as recorder_name,
|
||||
COALESCE(cr.points_change, (
|
||||
SELECT cr2.points_change FROM conduct_records cr2
|
||||
WHERE cr2.related_type = 'attendance' AND cr2.related_id = ar.attendance_id
|
||||
ORDER BY cr2.record_id DESC LIMIT 1
|
||||
)) as deduction_points,
|
||||
COALESCE(cr.is_revoked, (
|
||||
SELECT cr3.is_revoked FROM conduct_records cr3
|
||||
WHERE cr3.related_type = 'attendance' AND cr3.related_id = ar.attendance_id
|
||||
ORDER BY cr3.record_id DESC LIMIT 1
|
||||
)) as deduction_revoked
|
||||
FROM attendance_records ar
|
||||
JOIN students s ON ar.student_id = s.student_id
|
||||
LEFT JOIN users u ON ar.recorder_id = u.user_id
|
||||
LEFT JOIN conduct_records cr ON ar.deduction_record_id = cr.record_id
|
||||
WHERE 1=1
|
||||
"""
|
||||
params = []
|
||||
@@ -71,7 +83,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,21 +96,82 @@ 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:
|
||||
sql = "UPDATE attendance_records SET deduction_applied = 1 WHERE attendance_id = %s"
|
||||
result = await execute_update(sql, (attendance_id,))
|
||||
async def mark_deduction_applied(attendance_id: int, deduction_record_id: int = None) -> bool:
|
||||
"""标记考勤已扣分,并记录关联的扣分记录ID"""
|
||||
if deduction_record_id:
|
||||
sql = (
|
||||
"UPDATE attendance_records "
|
||||
"SET deduction_applied = 1, deduction_record_id = %s "
|
||||
"WHERE attendance_id = %s"
|
||||
)
|
||||
result = await execute_update(sql, (deduction_record_id, attendance_id))
|
||||
else:
|
||||
sql = "UPDATE attendance_records SET deduction_applied = 1 WHERE attendance_id = %s"
|
||||
result = await execute_update(sql, (attendance_id,))
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def get_existing_keys(
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
slots: List[str]
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""查询日期范围内已存在的考勤记录(学生+日期+时段)"""
|
||||
placeholders = ", ".join(["%s"] * len(slots))
|
||||
sql = f"""
|
||||
SELECT student_id, date, slot
|
||||
FROM attendance_records
|
||||
WHERE date BETWEEN %s AND %s AND slot IN ({placeholders})
|
||||
"""
|
||||
rows = await execute_query(sql, (start_date, end_date, *slots))
|
||||
|
||||
result = []
|
||||
for row in rows:
|
||||
d = row['date']
|
||||
result.append({
|
||||
'student_id': row['student_id'],
|
||||
'date': d.isoformat() if hasattr(d, 'isoformat') else str(d),
|
||||
'slot': row['slot']
|
||||
})
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
async def bulk_create_present(rows: List[tuple]) -> int:
|
||||
"""批量插入出勤记录
|
||||
|
||||
rows: (student_id, date, slot, recorder_id, semester_id) 列表
|
||||
"""
|
||||
if not rows:
|
||||
return 0
|
||||
|
||||
created = 0
|
||||
chunk_size = 200
|
||||
for i in range(0, len(rows), chunk_size):
|
||||
chunk = rows[i:i + chunk_size]
|
||||
values = ", ".join(["(%s, %s, 'present', '默认出勤', %s, %s, %s, 0)"] * len(chunk))
|
||||
params = []
|
||||
for student_id, day, slot, recorder_id, semester_id in chunk:
|
||||
params.extend([student_id, day, slot, recorder_id, semester_id])
|
||||
|
||||
sql = f"""
|
||||
INSERT INTO attendance_records
|
||||
(student_id, date, status, reason, slot, recorder_id, semester_id, deduction_applied)
|
||||
VALUES {values}
|
||||
"""
|
||||
created += await execute_update(sql, tuple(params))
|
||||
|
||||
return created
|
||||
+113
-50
@@ -10,13 +10,40 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
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 +55,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 +75,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 +94,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 +106,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 +120,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 +136,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 +155,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 +176,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 +190,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 +205,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 +216,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 +235,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 +275,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 +324,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 +370,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
|
||||
@@ -358,36 +454,3 @@ class ConductModel:
|
||||
except Exception as e:
|
||||
logger.error(f"恢复记录失败: {e}")
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
async def batch_create_records(records_data: List[Dict]) -> List[Dict]:
|
||||
"""批量创建操行分记录"""
|
||||
results = []
|
||||
for record in records_data:
|
||||
try:
|
||||
record_id = await ConductModel.create_record(
|
||||
student_id=record.get('student_id'),
|
||||
points_change=record.get('points_change'),
|
||||
reason=record.get('reason'),
|
||||
recorder_id=record.get('recorder_id'),
|
||||
recorder_name=record.get('recorder_name')
|
||||
)
|
||||
results.append({
|
||||
'student_id': record.get('student_id'),
|
||||
'success': True,
|
||||
'record_id': record_id
|
||||
})
|
||||
except Exception as e:
|
||||
results.append({
|
||||
'student_id': record.get('student_id'),
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
})
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_student_total_points(student_id: int) -> int:
|
||||
"""获取学生当前总分"""
|
||||
sql = "SELECT total_points FROM students WHERE student_id = %s"
|
||||
result = await execute_one(sql, (student_id,))
|
||||
return result['total_points'] if result else 100
|
||||
@@ -0,0 +1,75 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 作业数据模型
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import List
|
||||
from utils.database import execute_insert, execute_update
|
||||
|
||||
|
||||
class HomeworkModel:
|
||||
"""作业数据模型(作业记录与提交数据)"""
|
||||
|
||||
@staticmethod
|
||||
async def create_assignments(
|
||||
subject_id: int,
|
||||
titles: List[str],
|
||||
deadline: str,
|
||||
created_by: int
|
||||
) -> List[int]:
|
||||
"""批量创建作业记录,返回 assignment_id 列表"""
|
||||
ids = []
|
||||
for title in titles:
|
||||
assignment_id = await execute_insert(
|
||||
"INSERT INTO assignments (subject_id, title, deadline, created_by) VALUES (%s, %s, %s, %s)",
|
||||
(subject_id, title, deadline, created_by)
|
||||
)
|
||||
ids.append(assignment_id)
|
||||
return ids
|
||||
|
||||
@staticmethod
|
||||
async def bulk_create_submissions(rows: List[tuple]) -> int:
|
||||
"""批量创建提交记录
|
||||
|
||||
rows: (assignment_id, student_id, status, updated_by) 列表
|
||||
"""
|
||||
if not rows:
|
||||
return 0
|
||||
|
||||
created = 0
|
||||
chunk_size = 200
|
||||
for i in range(0, len(rows), chunk_size):
|
||||
chunk = rows[i:i + chunk_size]
|
||||
values = ", ".join(["(%s, %s, %s, %s)"] * len(chunk))
|
||||
params = []
|
||||
for assignment_id, student_id, status, updated_by in chunk:
|
||||
params.extend([assignment_id, student_id, status, updated_by])
|
||||
|
||||
sql = f"""
|
||||
INSERT INTO homework_submissions
|
||||
(assignment_id, student_id, status, updated_by)
|
||||
VALUES {values}
|
||||
"""
|
||||
created += await execute_update(sql, tuple(params))
|
||||
|
||||
return created
|
||||
|
||||
@staticmethod
|
||||
async def mark_not_submitted_deducted(assignment_ids: List[int], student_id: int) -> int:
|
||||
"""标记某学生在该批次中的缺交记录已扣分"""
|
||||
if not assignment_ids:
|
||||
return 0
|
||||
|
||||
placeholders = ", ".join(["%s"] * len(assignment_ids))
|
||||
sql = f"""
|
||||
UPDATE homework_submissions
|
||||
SET deduction_applied = 1
|
||||
WHERE assignment_id IN ({placeholders}) AND student_id = %s AND status = 'not_submitted'
|
||||
"""
|
||||
return await execute_update(sql, (*assignment_ids, student_id))
|
||||
+80
-1
@@ -9,7 +9,8 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from utils.database import execute_insert
|
||||
from typing import Dict, Any, List
|
||||
from utils.database import execute_insert, execute_one, execute_query
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -62,3 +63,81 @@ class OperationLogModel:
|
||||
"""
|
||||
return await execute_insert(sql, (operator_id, operator_name, operator_role,
|
||||
operation_type, target_type, target_id, details, ip_address))
|
||||
|
||||
@staticmethod
|
||||
def _build_filters(
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
keyword: str = None
|
||||
):
|
||||
conditions = ["1=1"]
|
||||
params = []
|
||||
if operation_type:
|
||||
conditions.append("operation_type = %s")
|
||||
params.append(operation_type)
|
||||
if operator:
|
||||
conditions.append("(operator_name LIKE %s OR operator_role LIKE %s)")
|
||||
params.extend([f"%{operator}%", f"%{operator}%"])
|
||||
if keyword:
|
||||
conditions.append("details LIKE %s")
|
||||
params.append(f"%{keyword}%")
|
||||
if start_date:
|
||||
conditions.append("DATE(created_at) >= %s")
|
||||
params.append(start_date)
|
||||
if end_date:
|
||||
conditions.append("DATE(created_at) <= %s")
|
||||
params.append(end_date)
|
||||
return " AND ".join(conditions), params
|
||||
|
||||
@staticmethod
|
||||
async def get_logs(
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
keyword: str = None,
|
||||
limit: int = 20,
|
||||
offset: int = 0
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""查询操作日志(分页)"""
|
||||
where, params = OperationLogModel._build_filters(
|
||||
operation_type, operator, start_date, end_date, keyword
|
||||
)
|
||||
sql = f"""
|
||||
SELECT log_id, operator_id, operator_name, operator_role,
|
||||
operation_type, target_type, target_id, details, ip_address, created_at
|
||||
FROM operation_logs
|
||||
WHERE {where}
|
||||
ORDER BY log_id DESC
|
||||
LIMIT %s OFFSET %s
|
||||
"""
|
||||
params.extend([limit, offset])
|
||||
return await execute_query(sql, tuple(params))
|
||||
|
||||
@staticmethod
|
||||
async def count_logs(
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
keyword: str = None
|
||||
) -> int:
|
||||
"""统计操作日志数量"""
|
||||
where, params = OperationLogModel._build_filters(
|
||||
operation_type, operator, start_date, end_date, keyword
|
||||
)
|
||||
result = await execute_one(
|
||||
f"SELECT COUNT(*) AS total FROM operation_logs WHERE {where}",
|
||||
tuple(params)
|
||||
)
|
||||
return result["total"] if result else 0
|
||||
|
||||
@staticmethod
|
||||
async def get_types() -> List[str]:
|
||||
"""获取所有操作类型(用于筛选项)"""
|
||||
rows = await execute_query(
|
||||
"SELECT DISTINCT operation_type FROM operation_logs ORDER BY operation_type"
|
||||
)
|
||||
return [row["operation_type"] for row in rows]
|
||||
@@ -0,0 +1,268 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 权限组数据模型
|
||||
#
|
||||
# 开发者: 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", # 作业扣分
|
||||
"homework_register", # 作业按次登记
|
||||
"manage_attendance", # 考勤管理
|
||||
"default_attendance", # 考勤默认出勤(批量补全)
|
||||
"manage_calendar", # 节假日/补课校历设置
|
||||
"manage_subjects", # 科目管理
|
||||
"manage_admins", # 管理员与权限组管理
|
||||
"manage_semesters", # 学期管理
|
||||
"view_all_records", # 查看全班记录/个人查询
|
||||
"view_reports", # 数据报表查看(考勤/作业统计)
|
||||
"export_data", # 导出德育分记录/历史记录
|
||||
"view_logs", # 操作日志查看
|
||||
"manage_settings", # 系统设置(密码策略等)
|
||||
"manage_upgrade", # 系统升级
|
||||
]
|
||||
|
||||
# 预置权限组默认配置(数据库尚未升级时按旧角色降级使用,与 sql/init.sql 种子一致)
|
||||
DEFAULT_GROUP_PERMISSIONS = {
|
||||
"班主任": {key: True for key in PERMISSION_KEYS},
|
||||
"班长": {"manage_conduct": True, "revoke_any": True, "view_all_records": True, "view_reports": True},
|
||||
"学习委员": {"manage_conduct": True, "manage_homework": True, "homework_register": True, "manage_subjects": True},
|
||||
"考勤委员": {"manage_conduct": True, "manage_attendance": True, "default_attendance": True, "revoke_own": True},
|
||||
"劳动委员": {"manage_conduct": True},
|
||||
"志愿委员": {"manage_conduct": True, "view_all_records": True, "view_reports": True},
|
||||
}
|
||||
|
||||
DEFAULT_GROUP_CAPS = {
|
||||
"班主任": (True, None, True, None),
|
||||
"班长": (True, 5, True, 5),
|
||||
"学习委员": (True, 5, True, 5),
|
||||
"考勤委员": (False, None, True, 8),
|
||||
"劳动委员": (True, 1, True, 1),
|
||||
"志愿委员": (True, 5, False, None),
|
||||
}
|
||||
|
||||
|
||||
def build_legacy_group(role_type: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
"""数据库未升级时,按旧角色名构建内置权限组(仅用于过渡期)"""
|
||||
if not role_type:
|
||||
return None
|
||||
base_permissions = DEFAULT_GROUP_PERMISSIONS.get(role_type, {})
|
||||
can_add, max_add, can_subtract, max_subtract = DEFAULT_GROUP_CAPS.get(
|
||||
role_type, (False, None, False, None)
|
||||
)
|
||||
return {
|
||||
"group_id": None,
|
||||
"group_name": role_type,
|
||||
"role_type": role_type,
|
||||
"description": "内置权限(数据库待升级)",
|
||||
"permissions_data": {key: bool(base_permissions.get(key, False)) for key in PERMISSION_KEYS},
|
||||
"can_add_points": can_add,
|
||||
"max_add_points": max_add,
|
||||
"can_subtract_points": can_subtract,
|
||||
"max_subtract_points": max_subtract,
|
||||
"is_system": 0,
|
||||
"is_locked": 0,
|
||||
}
|
||||
|
||||
|
||||
def apply_legacy_group_fields(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""为旧库查询结果补充内置权限组展示字段(不覆盖已有真实权限组字段)"""
|
||||
if not row:
|
||||
return row
|
||||
group = build_legacy_group(row.get("role_type"))
|
||||
if not group:
|
||||
return row
|
||||
row.setdefault("email", None)
|
||||
row["group_name"] = row.get("group_name") or group["group_name"]
|
||||
row["is_system"] = group["is_system"]
|
||||
row["is_locked"] = group["is_locked"]
|
||||
row["can_add_points"] = group["can_add_points"]
|
||||
row["max_add_points"] = group["max_add_points"]
|
||||
row["can_subtract_points"] = group["can_subtract_points"]
|
||||
row["max_subtract_points"] = group["max_subtract_points"]
|
||||
return row
|
||||
|
||||
|
||||
class PermissionGroupModel:
|
||||
"""权限组数据模型"""
|
||||
|
||||
@staticmethod
|
||||
def parse_group(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""解析权限组数据(JSON字符串 -> 布尔字典)
|
||||
|
||||
存储中缺失的权限项:预置权限组按预设默认值补齐,其余按 False。
|
||||
这样新增权限项无需数据库迁移即可对预置组生效。
|
||||
"""
|
||||
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 = {}
|
||||
preset_defaults = DEFAULT_GROUP_PERMISSIONS.get(row.get("group_name"), {})
|
||||
row["permissions_data"] = {
|
||||
key: bool(parsed.get(key, preset_defaults.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]]:
|
||||
try:
|
||||
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]
|
||||
except Exception as e:
|
||||
# 数据库尚未升级:返回内置预置组(只读占位),升级后自动切换真实权限组
|
||||
logger.warning(f"读取权限组列表失败,返回内置预置组(数据库可能待升级): {e}")
|
||||
fallback_groups = []
|
||||
for group_name in DEFAULT_GROUP_PERMISSIONS:
|
||||
group = build_legacy_group(group_name)
|
||||
group["readonly"] = True # 待升级期间只读,避免误操作
|
||||
group["member_count"] = 0
|
||||
fallback_groups.append(group)
|
||||
return fallback_groups
|
||||
|
||||
@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
|
||||
"""
|
||||
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",
|
||||
(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
|
||||
"""
|
||||
try:
|
||||
row = await execute_one(sql, (user_id,))
|
||||
except Exception as e:
|
||||
# 数据库尚未升级(缺少 admin_roles.group_id / permission_groups)时按旧角色降级
|
||||
logger.warning(f"读取权限组失败,按旧角色降级(数据库可能待升级): {e}")
|
||||
try:
|
||||
legacy = await execute_one(
|
||||
"SELECT role_type FROM admin_roles WHERE user_id = %s LIMIT 1",
|
||||
(user_id,)
|
||||
)
|
||||
except Exception as legacy_error:
|
||||
logger.error(f"读取旧角色失败: {legacy_error}")
|
||||
return None
|
||||
return build_legacy_group(legacy.get("role_type") if legacy else None)
|
||||
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)
|
||||
@@ -0,0 +1,52 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 统计报表数据模型
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, List
|
||||
from utils.database import execute_query
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ReportModel:
|
||||
"""统计报表数据模型"""
|
||||
|
||||
@staticmethod
|
||||
async def get_active_students() -> List[Dict[str, Any]]:
|
||||
"""获取所有在读学生(报表左表,保证无记录学生也展示)"""
|
||||
return await execute_query(
|
||||
"SELECT student_id, student_no, name FROM students WHERE status = 1 ORDER BY student_no"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def get_attendance_stats(start_date: str, end_date: str) -> List[Dict[str, Any]]:
|
||||
"""按学生+状态统计日期范围内的考勤次数"""
|
||||
sql = """
|
||||
SELECT ar.student_id, ar.status, COUNT(*) AS cnt
|
||||
FROM attendance_records ar
|
||||
JOIN students s ON ar.student_id = s.student_id
|
||||
WHERE ar.date BETWEEN %s AND %s AND s.status = 1
|
||||
GROUP BY ar.student_id, ar.status
|
||||
"""
|
||||
return await execute_query(sql, (start_date, end_date))
|
||||
|
||||
@staticmethod
|
||||
async def get_homework_stats(start_date: str, end_date: str) -> List[Dict[str, Any]]:
|
||||
"""按学生+状态统计日期范围内(按作业截止日期)的作业提交情况"""
|
||||
sql = """
|
||||
SELECT hs.student_id, hs.status, COUNT(*) AS cnt
|
||||
FROM homework_submissions hs
|
||||
JOIN students s ON hs.student_id = s.student_id
|
||||
JOIN assignments a ON hs.assignment_id = a.assignment_id
|
||||
WHERE a.deadline BETWEEN %s AND %s AND s.status = 1
|
||||
GROUP BY hs.student_id, hs.status
|
||||
"""
|
||||
return await execute_query(sql, (start_date, end_date))
|
||||
@@ -115,6 +115,23 @@ class SemesterModel:
|
||||
result = await execute_one(sql, (record_id,))
|
||||
return result['semester_id'] if result else None
|
||||
|
||||
@staticmethod
|
||||
async def get_previous_archived_semester(semester_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""获取上一个已归档学期(按开始日期/创建日期比较,用于归档对比)"""
|
||||
sql = """
|
||||
SELECT semester_id, semester_name, start_date, end_date, archived_at
|
||||
FROM semesters
|
||||
WHERE is_archived = 1
|
||||
AND semester_id <> %s
|
||||
AND COALESCE(start_date, DATE(created_at)) < COALESCE(
|
||||
(SELECT start_date FROM semesters x WHERE x.semester_id = %s),
|
||||
(SELECT DATE(x.created_at) FROM semesters x WHERE x.semester_id = %s)
|
||||
)
|
||||
ORDER BY COALESCE(start_date, DATE(created_at)) DESC, semester_id DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
return await execute_one(sql, (semester_id, semester_id, semester_id))
|
||||
|
||||
@staticmethod
|
||||
async def get_attendance_stats_by_semester(semester_id: int, start_date: str, end_date: str) -> List[Dict]:
|
||||
"""批量查询学期内所有学生的考勤统计"""
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, List, Dict, Any
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update, execute_many
|
||||
from utils.security import security
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -171,6 +170,32 @@ class StudentModel:
|
||||
row['rank'] = i + 1
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_monthly_ranking(month: str, limit: int = 100) -> List[Dict[str, Any]]:
|
||||
"""获取月度操行分排行(月度分 = 当月加分 - 当月减分,与基础分无关)"""
|
||||
sql = """
|
||||
SELECT s.student_id, s.student_no, s.name,
|
||||
COALESCE(SUM(CASE WHEN cr.points_change > 0 THEN cr.points_change ELSE 0 END), 0) AS bonus,
|
||||
COALESCE(SUM(CASE WHEN cr.points_change < 0 THEN cr.points_change ELSE 0 END), 0) AS deduction,
|
||||
COALESCE(SUM(cr.points_change), 0) AS month_score
|
||||
FROM students s
|
||||
LEFT JOIN conduct_records cr
|
||||
ON cr.student_id = s.student_id
|
||||
AND cr.is_revoked = 0
|
||||
AND DATE_FORMAT(cr.created_at, '%%Y-%%m') = %s
|
||||
WHERE s.status = 1
|
||||
GROUP BY s.student_id, s.student_no, s.name
|
||||
ORDER BY month_score DESC, s.student_id ASC
|
||||
LIMIT %s
|
||||
"""
|
||||
results = await execute_query(sql, (month, limit))
|
||||
for i, row in enumerate(results):
|
||||
row['rank'] = i + 1
|
||||
row['bonus'] = int(row.get('bonus') or 0)
|
||||
row['deduction'] = int(row.get('deduction') or 0)
|
||||
row['month_score'] = int(row.get('month_score') or 0)
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_total_count() -> int:
|
||||
"""获取活跃学生总数"""
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, Dict, Any, List
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update, execute_many
|
||||
|
||||
|
||||
class SubjectModel:
|
||||
@@ -67,7 +67,20 @@ class SubjectModel:
|
||||
params.append(subject_id)
|
||||
sql = f"UPDATE subjects SET {', '.join(updates)} WHERE subject_id = %s"
|
||||
result = await execute_update(sql, tuple(params))
|
||||
return result > 0
|
||||
if result > 0:
|
||||
return True
|
||||
# 内容未变化时 rowcount 为 0,确认科目仍存在即视为成功
|
||||
exists = await execute_one("SELECT 1 FROM subjects WHERE subject_id = %s", (subject_id,))
|
||||
return exists is not None
|
||||
|
||||
@staticmethod
|
||||
async def reorder(subject_ids: List[int]) -> bool:
|
||||
"""按给定顺序批量更新排序序号(按10递增)"""
|
||||
if not subject_ids:
|
||||
return False
|
||||
params_list = [(index * 10, subject_id) for index, subject_id in enumerate(subject_ids)]
|
||||
await execute_many("UPDATE subjects SET sort_order = %s WHERE subject_id = %s", params_list)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def has_related_data(subject_id: int) -> bool:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 系统设置数据模型
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, Dict, List
|
||||
from utils.database import execute_one, execute_query, execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class SystemSettingModel:
|
||||
"""system_settings 键值表数据模型"""
|
||||
|
||||
@staticmethod
|
||||
async def get(key: str) -> Optional[str]:
|
||||
result = await execute_one(
|
||||
"SELECT setting_value FROM system_settings WHERE setting_key = %s", (key,)
|
||||
)
|
||||
return result["setting_value"] if result else None
|
||||
|
||||
@staticmethod
|
||||
async def get_many(keys: List[str]) -> Dict[str, str]:
|
||||
if not keys:
|
||||
return {}
|
||||
placeholders = ", ".join(["%s"] * len(keys))
|
||||
rows = await execute_query(
|
||||
f"SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ({placeholders})",
|
||||
tuple(keys)
|
||||
)
|
||||
return {row["setting_key"]: row["setting_value"] for row in rows}
|
||||
|
||||
@staticmethod
|
||||
async def get_by_prefix(prefix: str) -> Dict[str, str]:
|
||||
"""按前缀查询设置项"""
|
||||
rows = await execute_query(
|
||||
"SELECT setting_key, setting_value FROM system_settings WHERE setting_key LIKE %s",
|
||||
(prefix + '%',)
|
||||
)
|
||||
return {row["setting_key"]: row["setting_value"] for row in rows}
|
||||
|
||||
@staticmethod
|
||||
async def delete(key: str) -> bool:
|
||||
"""删除设置项"""
|
||||
result = await execute_update(
|
||||
"DELETE FROM system_settings WHERE setting_key = %s", (key,)
|
||||
)
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def upsert(key: str, value: str) -> bool:
|
||||
sql = """
|
||||
INSERT INTO system_settings (setting_key, setting_value)
|
||||
VALUES (%s, %s)
|
||||
ON DUPLICATE KEY UPDATE setting_value = %s
|
||||
"""
|
||||
result = await execute_update(sql, (key, value, value))
|
||||
return result >= 0
|
||||
+50
-13
@@ -9,6 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional
|
||||
from utils.database import execute_one, execute_insert, execute_update
|
||||
from utils.security import security
|
||||
from utils.logger import get_logger
|
||||
@@ -21,7 +22,7 @@ class UserModel:
|
||||
|
||||
@staticmethod
|
||||
async def get_by_username(username: str) -> dict:
|
||||
"""根据用户名获取用户"""
|
||||
"""根据用户名获取用户(登录主链路,不查询邮箱)"""
|
||||
sql = """
|
||||
SELECT user_id, username, password_hash, real_name, user_type,
|
||||
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||
@@ -32,7 +33,7 @@ class UserModel:
|
||||
|
||||
@staticmethod
|
||||
async def get_by_user_id(user_id: int) -> dict:
|
||||
"""根据用户ID获取用户"""
|
||||
"""根据用户ID获取用户(不查询邮箱)"""
|
||||
sql = """
|
||||
SELECT user_id, username, password_hash, real_name, user_type, student_id,
|
||||
need_change_password, status
|
||||
@@ -41,6 +42,12 @@ class UserModel:
|
||||
"""
|
||||
return await execute_one(sql, (user_id,))
|
||||
|
||||
@staticmethod
|
||||
async def get_email_by_user_id(user_id: int) -> Optional[str]:
|
||||
"""获取用户绑定邮箱(仅找回密码/绑定邮箱功能使用)"""
|
||||
result = await execute_one("SELECT email FROM users WHERE user_id = %s", (user_id,))
|
||||
return result.get("email") if result else None
|
||||
|
||||
@staticmethod
|
||||
async def create_student(username: str, password: str, real_name: str, student_id: int) -> int:
|
||||
"""创建学生账号"""
|
||||
@@ -62,9 +69,15 @@ 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:
|
||||
"""创建管理员账号(不传邮箱时不写 email 列)"""
|
||||
password_hash = security.bcrypt_password(password)
|
||||
if email:
|
||||
sql = """
|
||||
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, email))
|
||||
sql = """
|
||||
INSERT INTO users (username, password_hash, real_name, user_type, need_change_password)
|
||||
VALUES (%s, %s, %s, 'admin', 1)
|
||||
@@ -73,14 +86,38 @@ class UserModel:
|
||||
|
||||
@staticmethod
|
||||
async def update_password(user_id: int, new_password: str) -> bool:
|
||||
"""更新密码"""
|
||||
password_hash = security.bcrypt_password(new_password)
|
||||
"""更新密码(加密失败会抛出异常;rowcount 为 0 时再确认用户是否存在)"""
|
||||
try:
|
||||
password_hash = security.bcrypt_password(new_password)
|
||||
except Exception as e:
|
||||
logger.error(f"密码加密失败: {e}")
|
||||
raise
|
||||
sql = """
|
||||
UPDATE users
|
||||
SET password_hash = %s, need_change_password = 0
|
||||
WHERE user_id = %s
|
||||
"""
|
||||
result = await execute_update(sql, (password_hash, user_id))
|
||||
if result > 0:
|
||||
return True
|
||||
exists = await execute_one("SELECT 1 FROM users WHERE user_id = %s", (user_id,))
|
||||
return exists is not None
|
||||
|
||||
@staticmethod
|
||||
async def upgrade_password_hash(user_id: int, password: str) -> bool:
|
||||
"""仅升级密码哈希格式(bcrypt),不改变 need_change_password 标记
|
||||
|
||||
登录时自动升级旧哈希不等于用户主动改密,不能清除"密码待修改"标记。
|
||||
"""
|
||||
try:
|
||||
password_hash = security.bcrypt_password(password)
|
||||
except Exception as e:
|
||||
logger.error(f"密码加密失败: {e}")
|
||||
raise
|
||||
result = await execute_update(
|
||||
"UPDATE users SET password_hash = %s WHERE user_id = %s",
|
||||
(password_hash, user_id)
|
||||
)
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
@@ -104,13 +141,6 @@ class UserModel:
|
||||
"""
|
||||
return await execute_one(sql, (username,))
|
||||
|
||||
@staticmethod
|
||||
async def check_username_exists(username: str) -> bool:
|
||||
"""检查用户名是否存在"""
|
||||
sql = "SELECT 1 FROM users WHERE username = %s"
|
||||
result = await execute_one(sql, (username,))
|
||||
return result is not None
|
||||
|
||||
@staticmethod
|
||||
async def update_status(user_id: int, status: int) -> bool:
|
||||
"""更新用户状态(0=禁用,1=启用)"""
|
||||
@@ -124,3 +154,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
|
||||
+558
-102
@@ -10,27 +10,33 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query, UploadFile, File
|
||||
from typing import Optional, List
|
||||
from typing import Optional
|
||||
import json
|
||||
|
||||
from middleware.permission import (
|
||||
get_current_user,
|
||||
require_teacher,
|
||||
PermissionChecker
|
||||
)
|
||||
from services.admin_service import AdminService
|
||||
from services.conduct_service import ConductService
|
||||
from services.attendance_service import AttendanceService
|
||||
from services.homework_service import HomeworkService
|
||||
from services.log_service import LogService
|
||||
from services.setting_service import SettingService
|
||||
from models.student import StudentModel
|
||||
from utils.database import execute_update
|
||||
from utils.redis_client import RedisClient
|
||||
from schemas.admin import (
|
||||
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
||||
AddStudentRequest, UpdateStudentRequest,
|
||||
AddAttendanceRequest,
|
||||
UpdateAdminRequest, DeleteAdminRequest, ResetPasswordRequest,
|
||||
UnlockUserRequest
|
||||
AddAttendanceRequest, DefaultAttendanceRequest, FullDayLeaveRequest, CalendarDayRequest,
|
||||
HomeworkRegisterRequest,
|
||||
UpdateAdminRequest, ResetPasswordRequest,
|
||||
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
||||
PasswordPolicyRequest
|
||||
)
|
||||
from utils.response import success_response, error_response
|
||||
from utils.validators import is_valid_email
|
||||
from utils.logger import get_logger
|
||||
from config import settings
|
||||
|
||||
@@ -38,6 +44,19 @@ router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def _students_brief(student_ids: list, limit: int = 10) -> str:
|
||||
"""操作日志用:学生姓名(学号)摘要"""
|
||||
names = []
|
||||
for sid in student_ids[:limit]:
|
||||
student = await StudentModel.get_by_id(sid)
|
||||
if student:
|
||||
names.append(f"{student['name']}({student['student_no']})")
|
||||
if not names:
|
||||
return "-"
|
||||
suffix = f" 等{len(student_ids)}人" if len(student_ids) > limit else ""
|
||||
return "、".join(names) + suffix
|
||||
|
||||
|
||||
# ========== 学生管理 ==========
|
||||
|
||||
@router.get("/students/dormitories")
|
||||
@@ -65,16 +84,23 @@ async def get_students(
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可查看学生列表", code=403)
|
||||
result = await AdminService.get_students(page=page, page_size=page_size, search=search, dormitory_number=dormitory_number)
|
||||
# 家长手机号仅对拥有学生管理/导出名单权限的账号下发
|
||||
can_view_phone = (
|
||||
await PermissionChecker.check_permission(user["user_id"], "manage_students")
|
||||
or await PermissionChecker.check_permission(user["user_id"], "export_students")
|
||||
)
|
||||
if not can_view_phone:
|
||||
for student in result.get("students", []):
|
||||
student.pop("parent_phone", None)
|
||||
return success_response(data=result)
|
||||
|
||||
|
||||
@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 +126,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 +142,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 +168,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 +182,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 +194,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 +215,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 +227,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
|
||||
@@ -239,7 +261,10 @@ async def add_conduct_points(request: Request, req: AddPointsRequest):
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role=role, operation_type="add_points",
|
||||
target_type="conduct",
|
||||
details=f"批量加减分: {req.points_change}分, 原因: {req.reason}, 对象: {req.student_ids}",
|
||||
details=(
|
||||
f"批量加减分: {req.points_change}分, 原因: {req.reason}, "
|
||||
f"学生({len(req.student_ids)}人): {await _students_brief(req.student_ids)}"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
except Exception as e:
|
||||
@@ -263,15 +288,18 @@ async def revoke_conduct_record(request: Request, req: RevokeRequest):
|
||||
if result["success"]:
|
||||
role = await PermissionChecker.get_user_role(user["user_id"])
|
||||
record = result.get("record", {})
|
||||
student = await StudentModel.get_by_id(record.get("student_id")) if record.get("student_id") else None
|
||||
student_text = f"{student['name']}({student['student_no']})" if student else f"ID:{record.get('student_id')}"
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role=role, operation_type="revoke_record",
|
||||
target_type="conduct", target_id=req.record_id,
|
||||
details=(
|
||||
f"撤销记录ID: {req.record_id}, "
|
||||
f"撤销记录: {student_text}, "
|
||||
f"分值变动: {'+' if record.get('points_change', 0) > 0 else ''}{record.get('points_change', 0)}分, "
|
||||
f"原因: {record.get('reason', '-')}, "
|
||||
f"原操作人: {record.get('recorder_name', '未知')}, "
|
||||
f"原分值变动: {'+' if record.get('points_change', 0) > 0 else ''}{record.get('points_change', 0)}分, "
|
||||
f"撤销操作人: {user['username']}"
|
||||
f"操作人: {user['username']}"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
@@ -293,15 +321,18 @@ async def restore_conduct_record(request: Request, req: RevokeRequest):
|
||||
)
|
||||
if result["success"]:
|
||||
record = result.get("record", {})
|
||||
student = await StudentModel.get_by_id(record.get("student_id")) if record.get("student_id") else None
|
||||
student_text = f"{student['name']}({student['student_no']})" if student else f"ID:{record.get('student_id')}"
|
||||
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}, "
|
||||
f"反撤销记录: {student_text}, "
|
||||
f"分值变动: {'+' if record.get('points_change', 0) > 0 else ''}{record.get('points_change', 0)}分, "
|
||||
f"原因: {record.get('reason', '-')}, "
|
||||
f"原操作人: {record.get('recorder_name', '未知')}, "
|
||||
f"原分值变动: {'+' if record.get('points_change', 0) > 0 else ''}{record.get('points_change', 0)}分, "
|
||||
f"反撤销操作人: {user['username']}"
|
||||
f"操作人: {user['username']}"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
@@ -322,7 +353,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 +372,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 +381,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):
|
||||
"""批量撤销操行分记录"""
|
||||
@@ -378,6 +435,19 @@ async def batch_revoke_conduct_records(request: Request):
|
||||
fail_count += 1
|
||||
errors.append({"record_id": record_id, "error": result["message"]})
|
||||
|
||||
if success_count > 0:
|
||||
ids_preview = ", ".join(str(i) for i in record_ids[:10]) + ("..." if len(record_ids) > 10 else "")
|
||||
try:
|
||||
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="batch_revoke", target_type="conduct",
|
||||
details=f"批量撤销 {success_count} 条记录(记录ID: {ids_preview})",
|
||||
ip=request.client.host
|
||||
)
|
||||
except Exception as log_error:
|
||||
logger.error(f"写入批量撤销日志失败: {log_error}")
|
||||
|
||||
return success_response(data={
|
||||
"success_count": success_count,
|
||||
"fail_count": fail_count,
|
||||
@@ -418,6 +488,19 @@ async def batch_restore_conduct_records(request: Request):
|
||||
fail_count += 1
|
||||
errors.append({"record_id": record_id, "error": result["message"]})
|
||||
|
||||
if success_count > 0:
|
||||
ids_preview = ", ".join(str(i) for i in record_ids[:10]) + ("..." if len(record_ids) > 10 else "")
|
||||
try:
|
||||
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="batch_restore", target_type="conduct",
|
||||
details=f"批量反撤销 {success_count} 条记录(记录ID: {ids_preview})",
|
||||
ip=request.client.host
|
||||
)
|
||||
except Exception as log_error:
|
||||
logger.error(f"写入批量反撤销日志失败: {log_error}")
|
||||
|
||||
return success_response(data={
|
||||
"success_count": success_count,
|
||||
"fail_count": fail_count,
|
||||
@@ -433,11 +516,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 +553,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,
|
||||
@@ -482,32 +564,195 @@ async def get_attendance_records(
|
||||
return success_response(data=result)
|
||||
|
||||
|
||||
@router.post("/attendance/default")
|
||||
async def default_attendance(request: Request, req: DefaultAttendanceRequest):
|
||||
"""批量默认出勤(跳过周末/节假日,调休补课日照常,已有记录不覆盖)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "default_attendance"):
|
||||
return error_response(message="无默认出勤权限", code=403)
|
||||
role = await PermissionChecker.get_user_role(user["user_id"]) or "管理员"
|
||||
result = await AttendanceService.batch_default_attendance(
|
||||
start_date=str(req.start_date),
|
||||
end_date=str(req.end_date),
|
||||
slots=req.slots,
|
||||
recorder_id=user["user_id"]
|
||||
)
|
||||
if result["success"]:
|
||||
data = result.get("data", {})
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role=role, operation_type="default_attendance",
|
||||
target_type="attendance",
|
||||
details=(
|
||||
f"默认出勤: {req.start_date} ~ {req.end_date}, "
|
||||
f"上课日{data.get('days', 0)}天, 新增{data.get('created', 0)}条"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(data=data, message=result["message"])
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.post("/attendance/full-day-leave")
|
||||
async def full_day_leave(request: Request, req: FullDayLeaveRequest):
|
||||
"""整天请假:按当天实际考勤时段提交请假(正常日3段/假前1段/节前上课2段/返校晚修1段)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_attendance"):
|
||||
return error_response(message="无考勤管理权限", code=403)
|
||||
result = await AttendanceService.full_day_leave(
|
||||
date_str=str(req.date),
|
||||
student_ids=req.student_ids,
|
||||
reason=req.reason,
|
||||
recorder_id=user["user_id"]
|
||||
)
|
||||
if result["success"]:
|
||||
data = result.get("data", {})
|
||||
try:
|
||||
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="add_attendance", target_type="attendance",
|
||||
details=(
|
||||
f"全天请假: {req.date}, {data.get('students', 0)}人 × "
|
||||
f"{len(data.get('slots', []))}时段, 共{data.get('created', 0)}条"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"写入全天请假日志失败: {e}")
|
||||
return success_response(data=data, message=result["message"])
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.get("/attendance/calendar")
|
||||
async def get_attendance_calendar(
|
||||
request: Request,
|
||||
start_date: str = Query(...),
|
||||
end_date: str = Query(...)
|
||||
):
|
||||
"""获取校历:法定节假日、调休补班与手动设置"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_calendar"):
|
||||
return error_response(message="无校历设置权限", code=403)
|
||||
try:
|
||||
data = await AttendanceService.get_calendar(start_date, end_date)
|
||||
except ValueError:
|
||||
return error_response(message="日期格式不正确")
|
||||
return success_response(data=data)
|
||||
|
||||
|
||||
@router.post("/attendance/calendar")
|
||||
async def add_attendance_calendar(request: Request, req: CalendarDayRequest):
|
||||
"""添加手动校历设置(放假/补课)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_calendar"):
|
||||
return error_response(message="无校历设置权限", code=403)
|
||||
result = await AttendanceService.add_calendar_day(
|
||||
day=str(req.date),
|
||||
day_type=req.day_type,
|
||||
note=req.note,
|
||||
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="add_calendar_day", target_type="attendance",
|
||||
details=f"校历设置: {req.date} -> {'放假' if req.day_type == 'holiday' else '补课'}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message=result["message"])
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.delete("/attendance/calendar")
|
||||
async def remove_attendance_calendar(request: Request, date: str = Query(...)):
|
||||
"""删除手动校历设置"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_calendar"):
|
||||
return error_response(message="无校历设置权限", code=403)
|
||||
result = await AttendanceService.remove_calendar_day(
|
||||
day=date, 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="remove_calendar_day", target_type="attendance",
|
||||
details=f"删除校历设置: {date}",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message=result["message"])
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
# ========== 作业管理 ==========
|
||||
|
||||
@router.post("/homework/register")
|
||||
async def register_homework(request: Request, req: HomeworkRegisterRequest):
|
||||
"""作业按次登记:配置总提交次数,按每人缺交次数扣分并写入提交统计"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "homework_register"):
|
||||
return error_response(message="无作业按次登记权限", code=403)
|
||||
result = await HomeworkService.register_batch(
|
||||
records=[item.model_dump() for item in req.records],
|
||||
deadline=str(req.deadline),
|
||||
total_times=req.total_times,
|
||||
per_deduction=req.per_deduction,
|
||||
title=req.title,
|
||||
subject_id=req.subject_id,
|
||||
note=req.note,
|
||||
operator_id=user["user_id"],
|
||||
operator_name=user["real_name"]
|
||||
)
|
||||
if result["success"]:
|
||||
data = result.get("data", {})
|
||||
try:
|
||||
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="homework_register", target_type="homework",
|
||||
details=(
|
||||
f"按次登记[{req.title or '作业登记'}]: 共{req.total_times}次, "
|
||||
f"缺交{data.get('deducted_students', 0)}人, 合计扣{data.get('total_deduction', 0)}分"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
except Exception as log_error:
|
||||
logger.error(f"写入作业按次登记日志失败: {log_error}")
|
||||
return success_response(data=data, message=result["message"])
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
# ========== 管理员管理 ==========
|
||||
|
||||
@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 +762,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 +774,167 @@ 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)
|
||||
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)}")
|
||||
|
||||
|
||||
@router.post("/permission-groups")
|
||||
async def create_permission_group(request: Request, req: PermissionGroupRequest):
|
||||
"""新建权限组"""
|
||||
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)
|
||||
|
||||
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
|
||||
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.post("/email/test")
|
||||
async def send_test_email(request: Request, req: EmailTestRequest):
|
||||
"""发送测试邮件(验证 SMTP 配置)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
from utils.email_sender import EmailSender
|
||||
missing = EmailSender.missing_config()
|
||||
if missing:
|
||||
return error_response(message="邮件服务未配置,需设置:" + "、".join(missing))
|
||||
if not is_valid_email(req.email):
|
||||
return error_response(message="邮箱格式不正确")
|
||||
ok, message = await EmailSender.send(
|
||||
req.email,
|
||||
f"{settings.APP_NAME} - 邮件测试",
|
||||
"<p>这是一封来自班级操行分管理系统的测试邮件,收到即表示 SMTP 配置可用。</p>"
|
||||
)
|
||||
if ok:
|
||||
return success_response(message=f"测试邮件已发送至 {req.email},请查收")
|
||||
return error_response(message=f"发送失败:{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)
|
||||
is_self = (user_id == user["user_id"])
|
||||
|
||||
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,
|
||||
keep_group=is_self
|
||||
)
|
||||
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}(本人账号,权限组不变)"
|
||||
if is_self else
|
||||
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 +959,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 +970,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
|
||||
|
||||
@@ -623,12 +985,22 @@ async def reset_admin_password(request: Request, user_id: int, req: ResetPasswor
|
||||
if target_user["user_type"] != "admin":
|
||||
return error_response(message="只能重置管理员密码", code=400)
|
||||
|
||||
policy_check = await AdminService.validate_new_password(req.new_password)
|
||||
if not policy_check["success"]:
|
||||
return error_response(message=policy_check["message"])
|
||||
|
||||
# 使用传入的新密码(UserModel.update_password 内部会进行哈希)
|
||||
updated = await UserModel.update_password(user_id, req.new_password)
|
||||
if updated:
|
||||
# 重置后下次登录需重新设置密码(无需原密码)
|
||||
await execute_update(
|
||||
"UPDATE users SET need_change_password = 1 WHERE user_id = %s",
|
||||
(user_id,)
|
||||
)
|
||||
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,19 +1014,103 @@ 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
|
||||
)
|
||||
return success_response(message=f"已解除用户 {req.username} 的登录锁定")
|
||||
|
||||
|
||||
# ========== 系统设置 ==========
|
||||
|
||||
@router.get("/settings/password-policy")
|
||||
async def get_password_policy(request: Request):
|
||||
"""获取密码策略"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_settings"):
|
||||
return error_response(message="无系统设置权限", code=403)
|
||||
policy = await SettingService.get_password_policy()
|
||||
return success_response(data=policy)
|
||||
|
||||
|
||||
@router.put("/settings/password-policy")
|
||||
async def update_password_policy(request: Request, req: PasswordPolicyRequest):
|
||||
"""更新密码策略"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_settings"):
|
||||
return error_response(message="无系统设置权限", code=403)
|
||||
result = await SettingService.update_password_policy(
|
||||
min_length=req.min_length,
|
||||
max_length=req.max_length,
|
||||
min_types=req.min_types,
|
||||
operator_id=user["user_id"]
|
||||
)
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="update_password_policy",
|
||||
target_type="setting",
|
||||
details=f"密码策略: {req.min_length}-{req.max_length}位, 至少{req.min_types}种字符",
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message=result["message"])
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
# ========== 操作日志查看 ==========
|
||||
|
||||
@router.get("/operation-logs")
|
||||
async def get_operation_logs(
|
||||
request: Request,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=200),
|
||||
operation_type: Optional[str] = None,
|
||||
operator: Optional[str] = None,
|
||||
start_date: Optional[str] = None,
|
||||
end_date: Optional[str] = None,
|
||||
keyword: Optional[str] = None
|
||||
):
|
||||
"""查询操作日志(需操作日志查看权限)"""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "view_logs"):
|
||||
return error_response(message="无操作日志查看权限", code=403)
|
||||
result = await LogService.get_operation_logs(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
operation_type=operation_type,
|
||||
operator=operator,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
keyword=keyword
|
||||
)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"查询操作日志失败: {e}", exc_info=True)
|
||||
return error_response(message=f"查询操作日志失败: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/operation-logs/types")
|
||||
async def get_operation_log_types(request: Request):
|
||||
"""获取操作日志类型列表(用于筛选项)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "view_logs"):
|
||||
return error_response(message="无操作日志查看权限", code=403)
|
||||
result = await LogService.get_operation_log_types()
|
||||
return success_response(data=result)
|
||||
+112
-4
@@ -9,13 +9,16 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from typing import Dict, Any
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from schemas.auth import LoginRequest, ChangePasswordRequest
|
||||
from schemas.auth import (
|
||||
LoginRequest, ChangePasswordRequest, InitPasswordRequest,
|
||||
ForgotPasswordRequest, ResetPasswordRequest,
|
||||
SendEmailCodeRequest, ConfirmBindEmailRequest, UnbindEmailRequest
|
||||
)
|
||||
from services.auth_service import AuthService
|
||||
from middleware.permission import get_current_user
|
||||
from utils.response import success_response, error_response, unauthorized_response
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
@@ -48,6 +51,8 @@ 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"),
|
||||
"need_change_password": result["need_change_password"],
|
||||
"redirect": result["redirect"]
|
||||
},
|
||||
@@ -93,6 +98,22 @@ async def change_password(request: Request, req: ChangePasswordRequest):
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.post("/init-passwd")
|
||||
async def init_password(request: Request, req: InitPasswordRequest):
|
||||
"""
|
||||
首次登录初始化密码(无需原密码,仅首次登录/重置后可调用)
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
result = await AuthService.init_password(
|
||||
user_id=user["user_id"],
|
||||
new_password=req.new_password
|
||||
)
|
||||
if result["success"]:
|
||||
return success_response(message=result["message"])
|
||||
else:
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_current_user_info(request: Request):
|
||||
"""
|
||||
@@ -105,3 +126,90 @@ 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("/email/send-code")
|
||||
async def send_bind_email_code(request: Request, req: SendEmailCodeRequest):
|
||||
"""
|
||||
发送邮箱绑定验证码(验证码发送至待绑定邮箱)
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可绑定邮箱", code=403)
|
||||
result = await AuthService.send_bind_email_code(
|
||||
user_id=user["user_id"],
|
||||
email=req.email
|
||||
)
|
||||
if result["success"]:
|
||||
return success_response(message=result["message"])
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.post("/email/confirm")
|
||||
async def confirm_bind_email(request: Request, req: ConfirmBindEmailRequest):
|
||||
"""
|
||||
校验验证码并绑定邮箱
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可绑定邮箱", code=403)
|
||||
result = await AuthService.confirm_bind_email(
|
||||
user_id=user["user_id"],
|
||||
email=req.email,
|
||||
code=req.code
|
||||
)
|
||||
if result["success"]:
|
||||
return success_response(data={"email": result.get("email")}, message=result["message"])
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.post("/email/unbind")
|
||||
async def unbind_email(request: Request, req: UnbindEmailRequest):
|
||||
"""
|
||||
解除绑定邮箱(需当前密码)
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
if user["user_type"] != "admin":
|
||||
return error_response(message="仅管理员可绑定邮箱", code=403)
|
||||
result = await AuthService.unbind_email(
|
||||
user_id=user["user_id"],
|
||||
password=req.password
|
||||
)
|
||||
if result["success"]:
|
||||
return success_response(data={"email": None}, message=result["message"])
|
||||
return error_response(message=result["message"])
|
||||
@@ -11,13 +11,21 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
from config import settings
|
||||
from services.setting_service import SettingService
|
||||
from utils.response import success_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@router.get("/deduction-rules")
|
||||
async def get_deduction_rules():
|
||||
"""获取扣分规则配置(公开接口)"""
|
||||
"""获取扣分规则与密码策略配置(公开接口)"""
|
||||
policy = {"min_length": 6, "max_length": 20, "min_types": 3}
|
||||
try:
|
||||
policy = await SettingService.get_password_policy()
|
||||
except Exception as e:
|
||||
logger.warning(f"读取密码策略失败,使用默认值: {e}")
|
||||
data = {
|
||||
"DEDUCTION_HOMEWORK_NOT_SUBMIT": settings.DEDUCTION_HOMEWORK_NOT_SUBMIT,
|
||||
"DEDUCTION_HOMEWORK_LATE": settings.DEDUCTION_HOMEWORK_LATE,
|
||||
@@ -25,5 +33,8 @@ async def get_deduction_rules():
|
||||
"DEDUCTION_ATTENDANCE_LATE": settings.DEDUCTION_ATTENDANCE_LATE,
|
||||
"DEDUCTION_ATTENDANCE_LEAVE": settings.DEDUCTION_ATTENDANCE_LEAVE,
|
||||
"STUDENT_INITIAL_POINTS": settings.STUDENT_INITIAL_POINTS,
|
||||
"PASSWORD_MIN_LENGTH": policy["min_length"],
|
||||
"PASSWORD_MAX_LENGTH": policy["max_length"],
|
||||
"PASSWORD_MIN_TYPES": policy["min_types"],
|
||||
}
|
||||
return success_response(data=data)
|
||||
+14
-5
@@ -11,7 +11,7 @@
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List
|
||||
from typing import Optional
|
||||
|
||||
from config import settings
|
||||
from services.admin_service import AdminService
|
||||
@@ -42,10 +42,18 @@ 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)}")
|
||||
try:
|
||||
group = await PermissionGroupModel.get_by_name(req.role_type)
|
||||
except Exception as e:
|
||||
logger.error(f"读取权限组失败(数据库可能待升级): {e}")
|
||||
return error_response(message="数据库待升级,请先完成系统升级")
|
||||
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,7 +63,7 @@ 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,
|
||||
group_id=group["group_id"],
|
||||
operator_id=0
|
||||
)
|
||||
|
||||
@@ -65,7 +73,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} 创建成功"
|
||||
)
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from typing import Optional
|
||||
|
||||
from middleware.permission import get_current_user
|
||||
from services.parent_service import ParentService
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 统计报表路由
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from middleware.permission import get_current_user, PermissionChecker
|
||||
from services.report_service import ReportService
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def _check_report_permission(request: Request):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "view_reports"):
|
||||
return user, error_response(message="无查看报表权限", code=403)
|
||||
return user, None
|
||||
|
||||
|
||||
@router.get("/attendance")
|
||||
async def attendance_report(
|
||||
request: Request,
|
||||
start_date: str = Query(..., description="开始日期 YYYY-MM-DD"),
|
||||
end_date: str = Query(..., description="结束日期 YYYY-MM-DD")
|
||||
):
|
||||
"""考勤统计报表"""
|
||||
try:
|
||||
_, denied = await _check_report_permission(request)
|
||||
if denied:
|
||||
return denied
|
||||
result = await ReportService.attendance_report(start_date, end_date)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"考勤报表生成失败: {e}", exc_info=True)
|
||||
return error_response(message=f"考勤报表生成失败: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/homework")
|
||||
async def homework_report(
|
||||
request: Request,
|
||||
start_date: str = Query(..., description="开始日期 YYYY-MM-DD"),
|
||||
end_date: str = Query(..., description="结束日期 YYYY-MM-DD")
|
||||
):
|
||||
"""作业统计报表"""
|
||||
try:
|
||||
_, denied = await _check_report_permission(request)
|
||||
if denied:
|
||||
return denied
|
||||
result = await ReportService.homework_report(start_date, end_date)
|
||||
return success_response(data=result)
|
||||
except Exception as e:
|
||||
logger.error(f"作业报表生成失败: {e}", exc_info=True)
|
||||
return error_response(message=f"作业报表生成失败: {str(e)}")
|
||||
+33
-31
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from typing import Optional
|
||||
|
||||
from middleware.permission import (
|
||||
get_current_user,
|
||||
@@ -30,9 +29,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 +66,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 +93,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 +107,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 +117,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 +131,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 +144,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 +158,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 +168,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 +182,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 +192,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 +210,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 +224,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 +243,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,
|
||||
|
||||
+22
-11
@@ -12,7 +12,7 @@
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from typing import Optional
|
||||
|
||||
from middleware.permission import get_current_user
|
||||
from middleware.permission import get_current_user, PermissionChecker
|
||||
from services.student_service import StudentService
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
@@ -21,6 +21,15 @@ router = APIRouter()
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
async def _check_view_permission(user: dict, student_id: int) -> bool:
|
||||
"""查看学生数据权限:学生仅限本人;管理员需查看全班权限"""
|
||||
if user.get("user_type") == "student":
|
||||
return user.get("student_id") == student_id
|
||||
if user.get("user_type") == "admin":
|
||||
return await PermissionChecker.check_permission(user["user_id"], "view_all_records")
|
||||
return False
|
||||
|
||||
|
||||
@router.get("/conduct/{student_id}")
|
||||
async def get_conduct_history(
|
||||
request: Request,
|
||||
@@ -34,9 +43,9 @@ async def get_conduct_history(
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
|
||||
# 权限检查:只能查看自己的信息(学生)或同班(管理员)
|
||||
if user["user_type"] == "student" and user["student_id"] != student_id:
|
||||
return error_response(message="无权查看其他学生信息", code=403)
|
||||
# 权限检查:学生只能查看本人;管理员需查看全班权限
|
||||
if not await _check_view_permission(user, student_id):
|
||||
return error_response(message="无权查看该学生信息", code=403)
|
||||
|
||||
result = await StudentService.get_conduct_history(
|
||||
student_id=student_id,
|
||||
@@ -58,8 +67,8 @@ async def get_homework_status(request: Request, student_id: int):
|
||||
user = await get_current_user(request)
|
||||
|
||||
# 权限检查
|
||||
if user["user_type"] == "student" and user["student_id"] != student_id:
|
||||
return error_response(message="无权查看其他学生信息", code=403)
|
||||
if not await _check_view_permission(user, student_id):
|
||||
return error_response(message="无权查看该学生信息", code=403)
|
||||
|
||||
result = await StudentService.get_homework_status(student_id)
|
||||
|
||||
@@ -78,8 +87,8 @@ async def get_attendance_records(
|
||||
user = await get_current_user(request)
|
||||
|
||||
# 权限检查
|
||||
if user["user_type"] == "student" and user["student_id"] != student_id:
|
||||
return error_response(message="无权查看其他学生信息", code=403)
|
||||
if not await _check_view_permission(user, student_id):
|
||||
return error_response(message="无权查看该学生信息", code=403)
|
||||
|
||||
result = await StudentService.get_attendance_records(
|
||||
student_id=student_id,
|
||||
@@ -92,16 +101,18 @@ async def get_attendance_records(
|
||||
@router.get("/ranking")
|
||||
async def get_ranking(
|
||||
request: Request,
|
||||
limit: int = Query(50, ge=1, le=100)
|
||||
limit: int = Query(50, ge=1, le=1000),
|
||||
month: Optional[str] = Query(None, pattern=r'^\d{4}-\d{2}$')
|
||||
):
|
||||
"""
|
||||
获取操行分排行榜
|
||||
获取操行分排行榜(传 month=YYYY-MM 时为月度分排行)
|
||||
"""
|
||||
user = await get_current_user(request)
|
||||
|
||||
result = await StudentService.get_ranking(
|
||||
user_id=user["user_id"],
|
||||
limit=limit
|
||||
limit=limit,
|
||||
month=month
|
||||
)
|
||||
|
||||
return success_response(data=result)
|
||||
|
||||
@@ -13,7 +13,7 @@ from fastapi import APIRouter, Request
|
||||
from typing import Optional
|
||||
from middleware.permission import get_current_user, PermissionChecker
|
||||
from services.subject_service import SubjectService
|
||||
from schemas.subject import CreateSubjectRequest, UpdateSubjectRequest
|
||||
from schemas.subject import CreateSubjectRequest, UpdateSubjectRequest, ReorderSubjectsRequest
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
@@ -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,15 +41,23 @@ 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"])
|
||||
|
||||
@router.put("/reorder")
|
||||
async def reorder_subjects(request: Request, req: ReorderSubjectsRequest):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_subjects"):
|
||||
return error_response(message="无权限", code=403)
|
||||
result = await SubjectService.reorder_subjects(req.subject_ids)
|
||||
return success_response(message="排序已更新") if result["success"] else error_response(message=result["message"])
|
||||
|
||||
@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"])
|
||||
+47
-18
@@ -42,15 +42,44 @@ 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',
|
||||
'4.2': 'v4.2.sql',
|
||||
'4.3': 'v4.3.sql',
|
||||
'4.4': 'v4.4.sql',
|
||||
'4.5': 'v4.5.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'),
|
||||
]
|
||||
|
||||
|
||||
def _get_all_versions() -> dict:
|
||||
"""获取版本映射:以代码内映射为基础,并实时扫描 sql/upgrades 目录。
|
||||
|
||||
拉取新版本代码后无需重启后端,磁盘上新增的升级脚本即可被识别与执行。
|
||||
"""
|
||||
versions = dict(ALL_VERSIONS)
|
||||
try:
|
||||
sql_dir = os.path.normpath(
|
||||
os.path.join(os.path.dirname(os.path.dirname(__file__)), '..', 'sql', 'upgrades')
|
||||
)
|
||||
if os.path.isdir(sql_dir):
|
||||
for name in os.listdir(sql_dir):
|
||||
m = re.match(r'^v(\d+(?:\.\d+)*)\.sql$', name, re.IGNORECASE)
|
||||
if m:
|
||||
versions.setdefault(m.group(1), name)
|
||||
except Exception as e:
|
||||
logger.warning(f"扫描升级脚本目录失败: {e}")
|
||||
return versions
|
||||
|
||||
|
||||
async def _detect_current_version() -> str:
|
||||
"""检测当前数据库版本,优先从 system_settings 读取,否则通过列特征推断"""
|
||||
# 1. 尝试从 system_settings 读取 db_version
|
||||
@@ -104,16 +133,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()
|
||||
@@ -133,7 +161,8 @@ async def check_upgrade(request: Request):
|
||||
needs_upgrade = _compare_versions(target_version, current_version) > 0
|
||||
|
||||
steps = []
|
||||
for version, file_name in sorted(ALL_VERSIONS.items(), key=lambda x: _version_tuple(x[0])):
|
||||
all_versions = _get_all_versions()
|
||||
for version, file_name in sorted(all_versions.items(), key=lambda x: _version_tuple(x[0])):
|
||||
if _compare_versions(version, current_version) > 0 and _compare_versions(version, target_version) <= 0:
|
||||
steps.append({'version': version, 'file': file_name})
|
||||
|
||||
@@ -171,16 +200,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', '')
|
||||
@@ -188,15 +216,16 @@ async def execute_upgrade_step(request: Request):
|
||||
if not version:
|
||||
return error_response(message='缺少版本号参数', code=400)
|
||||
|
||||
if version not in ALL_VERSIONS:
|
||||
all_versions = _get_all_versions()
|
||||
if version not in all_versions:
|
||||
return error_response(message=f'未知版本: {version}', code=400)
|
||||
|
||||
# SQL 文件路径
|
||||
sql_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), '..', 'sql', 'upgrades')
|
||||
sql_file = os.path.normpath(os.path.join(sql_dir, ALL_VERSIONS[version]))
|
||||
sql_file = os.path.normpath(os.path.join(sql_dir, all_versions[version]))
|
||||
|
||||
if not os.path.exists(sql_file):
|
||||
return error_response(message=f'SQL 文件不存在: {ALL_VERSIONS[version]}', code=500)
|
||||
return error_response(message=f'SQL 文件不存在: {all_versions[version]}', code=500)
|
||||
|
||||
last_error = None
|
||||
|
||||
@@ -224,11 +253,11 @@ async def execute_upgrade_step(request: Request):
|
||||
verify = await _verify_upgrade(version)
|
||||
if verify['ok']:
|
||||
new_version = version
|
||||
logger.info(f"数据库升级成功: v{version} ({ALL_VERSIONS[version]})")
|
||||
logger.info(f"数据库升级成功: v{version} ({all_versions[version]})")
|
||||
return success_response(data={
|
||||
'success': True,
|
||||
'version': version,
|
||||
'message': f"升级至 v{version} 成功 ({ALL_VERSIONS[version]})",
|
||||
'message': f"升级至 v{version} 成功 ({all_versions[version]})",
|
||||
'current': new_version
|
||||
})
|
||||
|
||||
|
||||
+66
-36
@@ -11,7 +11,7 @@
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import date, datetime
|
||||
from datetime import date
|
||||
|
||||
|
||||
class AddPointsRequest(BaseModel):
|
||||
@@ -22,46 +22,37 @@ class AddPointsRequest(BaseModel):
|
||||
related_type: Optional[str] = Field(default='manual', pattern=r'^(manual|homework|attendance)$', description="关联类型: manual/homework/attendance")
|
||||
|
||||
|
||||
class AddPointsResponse(BaseModel):
|
||||
"""加减分响应"""
|
||||
success_count: int
|
||||
fail_count: int
|
||||
details: List[dict]
|
||||
|
||||
|
||||
class RevokeRequest(BaseModel):
|
||||
"""撤销请求"""
|
||||
record_id: int = Field(..., description="记录ID")
|
||||
|
||||
|
||||
class ImportStudentsRequest(BaseModel):
|
||||
"""导入学生请求"""
|
||||
students: List[dict] = Field(..., description="学生列表")
|
||||
|
||||
|
||||
class ImportResult(BaseModel):
|
||||
"""导入结果"""
|
||||
total: int
|
||||
success: int
|
||||
failed: int
|
||||
errors: List[str]
|
||||
|
||||
|
||||
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(科代表需要)")
|
||||
|
||||
|
||||
class AddAdminResponse(BaseModel):
|
||||
"""添加管理员响应"""
|
||||
success: bool
|
||||
username: str
|
||||
password: Optional[str] = None
|
||||
message: str
|
||||
class UpdateAdminRequest(BaseModel):
|
||||
"""更新管理员请求"""
|
||||
real_name: str = Field(..., min_length=1, max_length=50, 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 AddStudentRequest(BaseModel):
|
||||
@@ -83,20 +74,47 @@ class AddAttendanceRequest(BaseModel):
|
||||
custom_deduction: Optional[int] = Field(default=None, gt=0, le=20, description="自定义扣分值")
|
||||
|
||||
|
||||
class UpdateAdminRequest(BaseModel):
|
||||
"""更新管理员请求"""
|
||||
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
||||
role_type: str = Field(..., pattern=r'^(班长|学习委员|考勤委员|劳动委员|志愿委员)$', description="角色类型")
|
||||
class DefaultAttendanceRequest(BaseModel):
|
||||
"""批量默认出勤请求"""
|
||||
start_date: date
|
||||
end_date: date
|
||||
slots: Optional[List[str]] = Field(None, description="时段列表(morning/afternoon/evening),默认全部")
|
||||
|
||||
|
||||
class DeleteAdminRequest(BaseModel):
|
||||
"""删除管理员请求"""
|
||||
user_id: int = Field(..., description="用户ID")
|
||||
class FullDayLeaveRequest(BaseModel):
|
||||
"""整天请假请求"""
|
||||
date: date
|
||||
student_ids: List[int] = Field(..., min_length=1, max_length=200, description="请假学生ID列表")
|
||||
reason: Optional[str] = Field(None, max_length=255, description="原因")
|
||||
|
||||
|
||||
class CalendarDayRequest(BaseModel):
|
||||
"""校历手动设置请求"""
|
||||
date: date
|
||||
day_type: str = Field(..., pattern=r'^(holiday|makeup)$', description="类型: holiday=放假, makeup=补课")
|
||||
note: Optional[str] = Field(None, max_length=100, description="备注")
|
||||
|
||||
|
||||
class HomeworkRegisterItem(BaseModel):
|
||||
"""按次登记-缺交学生"""
|
||||
student_id: int = Field(..., gt=0, description="学生ID")
|
||||
miss_count: int = Field(..., ge=1, le=99, description="缺交次数")
|
||||
|
||||
|
||||
class HomeworkRegisterRequest(BaseModel):
|
||||
"""作业按次登记请求"""
|
||||
subject_id: int = Field(..., gt=0, description="科目ID")
|
||||
title: Optional[str] = Field(None, max_length=100, description="作业名称/批次名")
|
||||
deadline: date = Field(..., description="缴交/截止日期(用于统计归属)")
|
||||
total_times: int = Field(..., ge=1, le=99, description="总提交次数")
|
||||
per_deduction: Optional[int] = Field(None, ge=1, le=20, description="单次缺交扣分(默认取系统配置)")
|
||||
note: Optional[str] = Field(None, max_length=100, description="备注")
|
||||
records: List[HomeworkRegisterItem] = Field(default_factory=list, max_length=200, description="缺交学生与缺交次数(可为空,空=全班已交)")
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
"""重置密码请求"""
|
||||
new_password: str = Field(..., min_length=6, max_length=50, description="新密码")
|
||||
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
|
||||
|
||||
class UpdateStudentRequest(BaseModel):
|
||||
@@ -109,3 +127,15 @@ class UpdateStudentRequest(BaseModel):
|
||||
class UnlockUserRequest(BaseModel):
|
||||
"""解除用户登录锁定请求"""
|
||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
||||
|
||||
|
||||
class EmailTestRequest(BaseModel):
|
||||
"""邮件测试请求"""
|
||||
email: str = Field(..., min_length=3, max_length=100, description="接收测试邮件的邮箱")
|
||||
|
||||
|
||||
class PasswordPolicyRequest(BaseModel):
|
||||
"""密码策略请求"""
|
||||
min_length: int = Field(..., ge=4, le=64, description="密码最小长度")
|
||||
max_length: int = Field(..., ge=8, le=100, description="密码最大长度")
|
||||
min_types: int = Field(..., ge=1, le=4, description="最少字符种类数")
|
||||
+29
-27
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
@@ -19,37 +18,40 @@ class LoginRequest(BaseModel):
|
||||
password: str = Field(..., min_length=1, max_length=50, description="密码")
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
"""登录响应"""
|
||||
success: bool
|
||||
token: str
|
||||
user_id: int
|
||||
username: str
|
||||
real_name: str
|
||||
user_type: str
|
||||
need_change_password: bool
|
||||
redirect: str
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
"""修改密码请求"""
|
||||
old_password: str = Field(default="", max_length=50, description="原密码")
|
||||
new_password: str = Field(..., min_length=6, max_length=20, description="新密码")
|
||||
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
force: bool = Field(default=False, description="是否强制修改(首次登录)")
|
||||
|
||||
|
||||
class ChangePasswordResponse(BaseModel):
|
||||
"""修改密码响应"""
|
||||
success: bool
|
||||
message: str
|
||||
class InitPasswordRequest(BaseModel):
|
||||
"""首次登录初始化密码请求(无需原密码)"""
|
||||
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
|
||||
|
||||
class UserInfo(BaseModel):
|
||||
"""用户信息"""
|
||||
user_id: int
|
||||
username: str
|
||||
real_name: str
|
||||
user_type: str
|
||||
student_id: Optional[int] = None
|
||||
role: 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=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||
|
||||
|
||||
class SendEmailCodeRequest(BaseModel):
|
||||
"""发送邮箱绑定验证码请求"""
|
||||
email: str = Field(..., min_length=3, max_length=100, description="待绑定的邮箱")
|
||||
|
||||
|
||||
class ConfirmBindEmailRequest(BaseModel):
|
||||
"""确认绑定邮箱请求"""
|
||||
email: str = Field(..., min_length=3, max_length=100, description="待绑定的邮箱")
|
||||
code: str = Field(..., min_length=4, max_length=10, description="邮箱验证码")
|
||||
|
||||
|
||||
class UnbindEmailRequest(BaseModel):
|
||||
"""解除绑定邮箱请求"""
|
||||
password: str = Field(..., min_length=1, max_length=50, description="当前密码")
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
class DeductionConfigResponse(BaseModel):
|
||||
"""扣分规则配置响应"""
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List
|
||||
from datetime import date, datetime
|
||||
|
||||
|
||||
@@ -25,14 +25,14 @@ class SubjectInfo(BaseModel):
|
||||
class CreateSubjectRequest(BaseModel):
|
||||
"""创建科目请求"""
|
||||
subject_name: str = Field(..., min_length=1, max_length=50, description="科目名称")
|
||||
subject_code: Optional[str] = Field(None, max_length=20, description="科目代码")
|
||||
subject_code: Optional[str] = Field(None, max_length=50, description="科目代码")
|
||||
sort_order: int = Field(0, description="排序序号")
|
||||
|
||||
|
||||
class UpdateSubjectRequest(BaseModel):
|
||||
"""更新科目请求"""
|
||||
subject_name: Optional[str] = Field(None, max_length=50, description="科目名称")
|
||||
subject_code: Optional[str] = Field(None, max_length=20, description="科目代码")
|
||||
subject_name: Optional[str] = Field(None, min_length=1, max_length=50, description="科目名称")
|
||||
subject_code: Optional[str] = Field(None, max_length=50, description="科目代码(传空字符串表示清空)")
|
||||
is_active: Optional[bool] = Field(None, description="是否启用")
|
||||
sort_order: Optional[int] = Field(None, description="排序序号")
|
||||
|
||||
@@ -41,3 +41,8 @@ class SubjectListResponse(BaseModel):
|
||||
"""科目列表响应"""
|
||||
subjects: List[SubjectInfo]
|
||||
total: int
|
||||
|
||||
|
||||
class ReorderSubjectsRequest(BaseModel):
|
||||
"""科目排序请求"""
|
||||
subject_ids: List[int] = Field(..., min_length=1, max_length=100, description="按新顺序排列的科目ID列表")
|
||||
@@ -14,11 +14,75 @@ 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 services.setting_service import SettingService
|
||||
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 +306,27 @@ 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
|
||||
) -> Dict[str, Any]:
|
||||
"""添加管理员(支持重新激活已删除的管理员)"""
|
||||
try:
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
except Exception as e:
|
||||
logger.error(f"读取权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
if not group:
|
||||
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,35 +335,48 @@ 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:
|
||||
try:
|
||||
await UserModel.update_email(existing['user_id'], normalized_email)
|
||||
except Exception as e:
|
||||
logger.error(f"更新绑定邮箱失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级后再设置邮箱"}
|
||||
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:
|
||||
password = security.generate_random_password()
|
||||
|
||||
user_id = await UserModel.create_admin(
|
||||
username=username,
|
||||
password=password,
|
||||
real_name=real_name
|
||||
)
|
||||
try:
|
||||
user_id = await UserModel.create_admin(
|
||||
username=username,
|
||||
password=password,
|
||||
real_name=real_name,
|
||||
email=normalized_email
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"创建管理员账号失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级后再设置邮箱"}
|
||||
|
||||
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 +386,193 @@ 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,
|
||||
keep_group: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
"""更新管理员姓名、权限组与绑定邮箱(keep_group=True 时仅改姓名/邮箱,权限组保持不变)"""
|
||||
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": "管理员不存在"}
|
||||
|
||||
if keep_group:
|
||||
# 本人账号:保留原权限组,避免误操作把自己锁死
|
||||
current_role = await AdminRoleModel.get_by_user_id(user_id)
|
||||
if not current_role or not current_role.get("group_id"):
|
||||
return {"success": False, "message": "无法确定当前账号的权限组,请先完成系统升级"}
|
||||
group_id = current_role["group_id"]
|
||||
|
||||
try:
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
except Exception as e:
|
||||
logger.error(f"读取权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
if not group:
|
||||
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": "邮箱格式不正确"}
|
||||
|
||||
try:
|
||||
if not keep_group:
|
||||
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)
|
||||
except Exception as e:
|
||||
logger.error(f"更新管理员失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级后再设置邮箱"}
|
||||
|
||||
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"]
|
||||
try:
|
||||
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"]
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"创建权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
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]:
|
||||
"""编辑权限组(锁定组不可编辑)"""
|
||||
try:
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
except Exception as e:
|
||||
logger.error(f"读取权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
if not group:
|
||||
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"]
|
||||
try:
|
||||
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)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"更新权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
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]:
|
||||
"""删除权限组(系统预置组不可删除,有成员时不可删除)"""
|
||||
try:
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
except Exception as e:
|
||||
logger.error(f"读取权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
if not group:
|
||||
return {"success": False, "message": "权限组不存在"}
|
||||
|
||||
try:
|
||||
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": "权限组删除失败"}
|
||||
except Exception as e:
|
||||
logger.error(f"删除权限组失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||
logger.info(f"用户[{operator_id}] 删除权限组 ID={group_id}")
|
||||
return {"success": True, "message": "权限组已删除"}
|
||||
|
||||
@staticmethod
|
||||
async def get_admins() -> Dict[str, Any]:
|
||||
"""获取管理员列表"""
|
||||
@@ -338,9 +617,23 @@ class AdminService:
|
||||
logger.error(f"删除学生失败: {e}")
|
||||
return {"success": False, "message": f"删除失败: {str(e)}"}
|
||||
|
||||
@staticmethod
|
||||
async def validate_new_password(new_password: str) -> Dict[str, Any]:
|
||||
"""按系统密码策略校验新密码"""
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, msg = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": msg}
|
||||
return {"success": True}
|
||||
|
||||
@staticmethod
|
||||
async def reset_student_password(student_id: int, new_password: str) -> Dict[str, Any]:
|
||||
"""重置学生密码"""
|
||||
policy_check = await AdminService.validate_new_password(new_password)
|
||||
if not policy_check["success"]:
|
||||
return policy_check
|
||||
try:
|
||||
user = await execute_one(
|
||||
"SELECT user_id FROM users WHERE student_id = %s AND user_type = 'student'",
|
||||
|
||||
@@ -9,13 +9,16 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
import json
|
||||
from datetime import date, timedelta
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from models.attendance import AttendanceModel
|
||||
from models.student import StudentModel
|
||||
from models.conduct import ConductModel
|
||||
from models.user import UserModel
|
||||
from models.system_setting import SystemSettingModel
|
||||
from services.holiday_service import get_range_data
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
from utils.logger import get_logger
|
||||
@@ -29,6 +32,12 @@ ATTENDANCE_STATUS_MAP = {
|
||||
"leave": "请假"
|
||||
}
|
||||
|
||||
# 手动校历设置的存储前缀与类型
|
||||
CALENDAR_KEY_PREFIX = 'calendar_day:'
|
||||
CALENDAR_TYPES = ('holiday', 'makeup')
|
||||
VALID_SLOTS = ('morning', 'afternoon', 'evening')
|
||||
MAX_DEFAULT_DAYS = 180
|
||||
|
||||
|
||||
class AttendanceService:
|
||||
"""考勤服务"""
|
||||
@@ -56,14 +65,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 +97,8 @@ class AttendanceService:
|
||||
status=status,
|
||||
reason=reason,
|
||||
recorder_id=recorder_id,
|
||||
slot=slot
|
||||
slot=slot,
|
||||
semester_id=semester_id
|
||||
)
|
||||
|
||||
if not attendance_id:
|
||||
@@ -101,21 +127,22 @@ class AttendanceService:
|
||||
recorder_name = user.get("real_name", "班主任") if user else "班主任"
|
||||
# 使用中文状态
|
||||
status_text = ATTENDANCE_STATUS_MAP.get(status, status)
|
||||
await ConductModel.create_record(
|
||||
deduction_record_id = await ConductModel.create_record(
|
||||
student_id=student_id,
|
||||
points_change=points_change,
|
||||
reason=f"考勤:{status_text}",
|
||||
recorder_id=recorder_id,
|
||||
recorder_name=recorder_name,
|
||||
related_type="attendance",
|
||||
related_id=attendance_id
|
||||
related_id=attendance_id,
|
||||
semester_id=semester_id
|
||||
)
|
||||
|
||||
# 更新学生总分
|
||||
await StudentModel.update_total_points(student_id, points_change)
|
||||
|
||||
# 标记已应用扣分
|
||||
await AttendanceModel.mark_deduction_applied(attendance_id)
|
||||
# 标记已应用扣分(并记录扣分记录ID)
|
||||
await AttendanceModel.mark_deduction_applied(attendance_id, deduction_record_id)
|
||||
logger.info(f"用户[{recorder_id}] 添加考勤记录[{attendance_id}] -> {status}")
|
||||
|
||||
return {"success": True, "message": "考勤记录添加成功"}
|
||||
@@ -128,18 +155,282 @@ 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 = []
|
||||
|
||||
records = await AttendanceModel.get_class_records(
|
||||
date=date,
|
||||
student_id=student_id,
|
||||
slot=slot
|
||||
)
|
||||
return {"records": records}
|
||||
|
||||
# ========== 校历(节假日/补课)==========
|
||||
|
||||
@staticmethod
|
||||
async def get_calendar(start_date: str, end_date: str) -> Dict[str, Any]:
|
||||
"""获取日期范围内的校历:法定节假日、调休补班、手动设置"""
|
||||
start = date.fromisoformat(start_date)
|
||||
end = date.fromisoformat(end_date)
|
||||
|
||||
api_data = await get_range_data(start, end)
|
||||
|
||||
manual_map: Dict[str, Dict[str, str]] = {}
|
||||
manual_rows = await SystemSettingModel.get_by_prefix(CALENDAR_KEY_PREFIX)
|
||||
for key, value in manual_rows.items():
|
||||
day = key[len(CALENDAR_KEY_PREFIX):]
|
||||
if not (start_date <= day <= end_date):
|
||||
continue
|
||||
try:
|
||||
item = json.loads(value)
|
||||
except (ValueError, TypeError):
|
||||
item = {}
|
||||
manual_map[day] = {
|
||||
'type': item.get('type', 'makeup'),
|
||||
'note': item.get('note', '')
|
||||
}
|
||||
|
||||
return {
|
||||
'holidays': api_data['holidays'],
|
||||
'workdays': api_data['workdays'],
|
||||
'manual': manual_map,
|
||||
'api_ok': api_data['api_ok']
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def add_calendar_day(
|
||||
day: str,
|
||||
day_type: str,
|
||||
note: Optional[str],
|
||||
operator_id: int
|
||||
) -> Dict[str, Any]:
|
||||
"""添加手动校历设置(放假/补课)"""
|
||||
try:
|
||||
date.fromisoformat(day)
|
||||
except ValueError:
|
||||
return {"success": False, "message": "日期格式不正确"}
|
||||
if day_type not in CALENDAR_TYPES:
|
||||
return {"success": False, "message": "无效的日期类型"}
|
||||
|
||||
value = json.dumps(
|
||||
{'type': day_type, 'note': (note or '').strip()},
|
||||
ensure_ascii=False
|
||||
)
|
||||
await SystemSettingModel.upsert(CALENDAR_KEY_PREFIX + day, value)
|
||||
logger.info(f"用户[{operator_id}] 添加校历设置 {day} -> {day_type}")
|
||||
return {"success": True, "message": "已保存"}
|
||||
|
||||
@staticmethod
|
||||
async def remove_calendar_day(day: str, operator_id: int) -> Dict[str, Any]:
|
||||
"""删除手动校历设置"""
|
||||
deleted = await SystemSettingModel.delete(CALENDAR_KEY_PREFIX + day)
|
||||
if not deleted:
|
||||
return {"success": False, "message": "该日期没有手动设置"}
|
||||
logger.info(f"用户[{operator_id}] 删除校历设置 {day}")
|
||||
return {"success": True, "message": "已删除"}
|
||||
|
||||
@staticmethod
|
||||
def _is_school_day(day: date, calendar_info: Dict[str, Any]) -> bool:
|
||||
"""判断某天是否为上课日:手动设置优先于接口,接口优先于默认工作日"""
|
||||
iso = day.isoformat()
|
||||
manual = calendar_info['manual'].get(iso)
|
||||
if manual:
|
||||
return manual['type'] == 'makeup'
|
||||
if iso in calendar_info['holidays']:
|
||||
return False
|
||||
if iso in calendar_info['workdays']:
|
||||
return True
|
||||
return day.weekday() < 5
|
||||
|
||||
@staticmethod
|
||||
def _slots_for_date(
|
||||
day: date,
|
||||
calendar_info: Dict[str, Any],
|
||||
selected_slots: Optional[list] = None
|
||||
) -> list:
|
||||
"""按学校常规作息返回某天实际考勤时段
|
||||
|
||||
- 上课日且次日仍上课:所选时段(早/中/晚)
|
||||
- 放假前一天(次日不上课):仅上午
|
||||
- 返校日(非上课日、次日上课):仅晚修
|
||||
- 其他休息日:无
|
||||
"""
|
||||
selected = [s for s in (selected_slots or VALID_SLOTS) if s in VALID_SLOTS]
|
||||
next_day = day + timedelta(days=1)
|
||||
school_today = AttendanceService._is_school_day(day, calendar_info)
|
||||
school_next = AttendanceService._is_school_day(next_day, calendar_info)
|
||||
|
||||
if school_today:
|
||||
if school_next:
|
||||
return list(selected)
|
||||
return [s for s in selected if s == 'morning']
|
||||
if school_next:
|
||||
return [s for s in selected if s == 'evening']
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
async def full_day_leave(
|
||||
date_str: str,
|
||||
student_ids: list,
|
||||
reason: Optional[str],
|
||||
recorder_id: int
|
||||
) -> Dict[str, Any]:
|
||||
"""全天请假:按当天实际考勤时段为选中学生提交请假(每个时段按请假配置扣分)"""
|
||||
try:
|
||||
day = date.fromisoformat(date_str)
|
||||
except ValueError:
|
||||
return {"success": False, "message": "日期格式不正确"}
|
||||
if not student_ids:
|
||||
return {"success": False, "message": "请选择请假的学生"}
|
||||
if len(student_ids) > 200:
|
||||
return {"success": False, "message": "单次最多选择200名学生"}
|
||||
|
||||
calendar_info = await AttendanceService.get_calendar(
|
||||
date_str, (day + timedelta(days=1)).isoformat()
|
||||
)
|
||||
slots = AttendanceService._slots_for_date(day, calendar_info)
|
||||
if not slots:
|
||||
return {"success": False, "message": "该日期没有考勤时段(休息日)"}
|
||||
|
||||
effective_reason = (reason or '').strip() or '请假(整天)'
|
||||
created_count = 0
|
||||
last_error = None
|
||||
for student_id in student_ids:
|
||||
for slot in slots:
|
||||
result = await AttendanceService.add_attendance(
|
||||
student_id=student_id,
|
||||
date=date_str,
|
||||
status='leave',
|
||||
reason=effective_reason,
|
||||
apply_deduction=True,
|
||||
recorder_id=recorder_id,
|
||||
custom_deduction=None,
|
||||
slot=slot
|
||||
)
|
||||
if result.get("success"):
|
||||
created_count += 1
|
||||
else:
|
||||
last_error = result.get("message", "未知错误")
|
||||
|
||||
if created_count == 0:
|
||||
return {"success": False, "message": last_error or "提交失败"}
|
||||
|
||||
per_student = len(slots) * settings.DEDUCTION_ATTENDANCE_LEAVE
|
||||
points_text = f",每人{per_student}分" if per_student > 0 else ""
|
||||
logger.info(
|
||||
f"用户[{recorder_id}] 全天请假 {date_str}: {len(student_ids)}人 × {len(slots)}时段"
|
||||
f"({','.join(slots)}), 共{created_count}条"
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"整天请假提交成功:{len(student_ids)}人 × {len(slots)}个时段,共{created_count}条{points_text}",
|
||||
"data": {
|
||||
"slots": slots,
|
||||
"created": created_count,
|
||||
"students": len(student_ids),
|
||||
"deduction_per_student": per_student
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def batch_default_attendance(
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
slots: Optional[list],
|
||||
recorder_id: int
|
||||
) -> Dict[str, Any]:
|
||||
"""批量默认出勤:给日期范围内所有上课日缺失的学生补出勤记录
|
||||
|
||||
跳过周末与节假日(接口+手动),调休补班与手动补课日照常;已有记录不覆盖。
|
||||
"""
|
||||
try:
|
||||
start = date.fromisoformat(start_date)
|
||||
end = date.fromisoformat(end_date)
|
||||
except ValueError:
|
||||
return {"success": False, "message": "日期格式不正确"}
|
||||
|
||||
if start > end:
|
||||
return {"success": False, "message": "开始日期不能晚于结束日期"}
|
||||
if (end - start).days > MAX_DEFAULT_DAYS:
|
||||
return {"success": False, "message": f"日期范围过长(最长{MAX_DEFAULT_DAYS}天)"}
|
||||
|
||||
selected_slots = [s for s in (slots or VALID_SLOTS) if s in VALID_SLOTS]
|
||||
if not selected_slots:
|
||||
return {"success": False, "message": "请至少选择一个时段"}
|
||||
|
||||
students = await StudentModel.get_all()
|
||||
if not students:
|
||||
return {"success": False, "message": "暂无在读学生"}
|
||||
|
||||
# 校历多取一天,用于判断"次日是否上课"(决定节前半日/返校晚修)
|
||||
calendar_info = await AttendanceService.get_calendar(
|
||||
start_date, (end + timedelta(days=1)).isoformat()
|
||||
)
|
||||
|
||||
# 常规作息:
|
||||
# 返校日(非上课日、次日上课)→ 仅晚修
|
||||
# 上课日且次日仍上课 → 按所选时段(早/中/晚)
|
||||
# 上课日且次日不上课(放假前一天)→ 仅上午(中午走人,无下午/晚修)
|
||||
day_slots = []
|
||||
full_days = 0
|
||||
half_days = 0
|
||||
return_evenings = 0
|
||||
rest_days = 0
|
||||
cursor_day = start
|
||||
while cursor_day <= end:
|
||||
slots_today = AttendanceService._slots_for_date(cursor_day, calendar_info, selected_slots)
|
||||
if slots_today:
|
||||
school_today = AttendanceService._is_school_day(cursor_day, calendar_info)
|
||||
school_next = AttendanceService._is_school_day(cursor_day + timedelta(days=1), calendar_info)
|
||||
if school_today and school_next:
|
||||
full_days += 1
|
||||
elif school_today:
|
||||
half_days += 1
|
||||
elif school_next:
|
||||
return_evenings += 1
|
||||
day_slots.append((cursor_day, slots_today))
|
||||
else:
|
||||
rest_days += 1
|
||||
cursor_day += timedelta(days=1)
|
||||
|
||||
if not day_slots:
|
||||
return {"success": False, "message": "所选范围内没有需要默认出勤的时段(均为休息日或未选对应时段)"}
|
||||
|
||||
from models.semester import SemesterModel
|
||||
active_semester = await SemesterModel.get_active()
|
||||
semester_id = active_semester['semester_id'] if active_semester else None
|
||||
|
||||
student_ids = [s['student_id'] for s in students]
|
||||
existing = await AttendanceModel.get_existing_keys(start_date, end_date, selected_slots)
|
||||
existing_set = {(r['student_id'], r['date'], r['slot']) for r in existing}
|
||||
|
||||
rows = []
|
||||
total_combos = 0
|
||||
for day, slots_today in day_slots:
|
||||
day_iso = day.isoformat()
|
||||
for student_id in student_ids:
|
||||
total_combos += len(slots_today)
|
||||
for slot in slots_today:
|
||||
if (student_id, day_iso, slot) not in existing_set:
|
||||
rows.append((student_id, day_iso, slot, recorder_id, semester_id))
|
||||
|
||||
created = await AttendanceModel.bulk_create_present(rows)
|
||||
skipped_existing = total_combos - len(rows)
|
||||
|
||||
summary = (
|
||||
f"上课日{full_days + half_days}天(其中节前半日{half_days}天)、"
|
||||
f"返校晚修{return_evenings}天,新增{created}条,跳过已有{skipped_existing}条"
|
||||
)
|
||||
logger.info(
|
||||
f"用户[{recorder_id}] 批量默认出勤 {start_date}~{end_date} 时段{','.join(selected_slots)}: {summary}"
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"默认出勤完成:{summary}",
|
||||
"data": {
|
||||
"days": full_days + half_days,
|
||||
"half_days": half_days,
|
||||
"return_evenings": return_evenings,
|
||||
"rest_days": rest_days,
|
||||
"created": created,
|
||||
"skipped_existing": skipped_existing,
|
||||
"api_ok": calendar_info['api_ok']
|
||||
}
|
||||
}
|
||||
@@ -10,21 +10,38 @@
|
||||
# ===========================================
|
||||
|
||||
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 services.setting_service import SettingService
|
||||
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
|
||||
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:
|
||||
"""认证服务"""
|
||||
|
||||
@@ -54,10 +71,10 @@ class AuthService:
|
||||
await LogService.write_login_log(username, 0, ip, user_agent, "用户名或密码错误")
|
||||
return {"success": False, "message": "用户名或密码错误"}
|
||||
|
||||
# 自动升级旧哈希密码
|
||||
# 自动升级旧哈希密码(仅升级哈希,不能清除"密码待修改"标记)
|
||||
if needs_upgrade:
|
||||
try:
|
||||
await UserModel.update_password(user["user_id"], password)
|
||||
await UserModel.upgrade_password_hash(user["user_id"], password)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -72,11 +89,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 +127,8 @@ class AuthService:
|
||||
"user_type": user["user_type"],
|
||||
"student_id": user["student_id"],
|
||||
"role": role,
|
||||
"permissions": permissions,
|
||||
"group": group_info,
|
||||
"need_change_password": user["need_change_password"] == 1,
|
||||
"redirect": redirect
|
||||
}
|
||||
@@ -124,21 +148,24 @@ class AuthService:
|
||||
return {"success": False, "message": "用户不存在"}
|
||||
|
||||
# 验证原密码
|
||||
# force=True 仅在 need_change_password=1 时允许(首次登录强制改密)
|
||||
# 其他情况必须验证旧密码
|
||||
# 仅当"密码待修改"(need_change_password=1:初始密码/被重置后未修改)且 force=True 时免原密码
|
||||
# 其他情况必须验证原密码
|
||||
if force and user.get("need_change_password") == 1:
|
||||
# 首次登录强制改密,跳过旧密码验证
|
||||
# 密码待修改:免原密码
|
||||
pass
|
||||
else:
|
||||
# 正常改密,必须验证旧密码
|
||||
# 常规改密:必须验证原密码
|
||||
if not old_password:
|
||||
return {"success": False, "message": "请输入原密码"}
|
||||
is_valid, _ = security.verify_password_v2(old_password, user["password_hash"])
|
||||
if not is_valid:
|
||||
return {"success": False, "message": "原密码错误"}
|
||||
|
||||
# 验证新密码强度
|
||||
is_valid, msg = security.validate_password_strength(new_password)
|
||||
# 验证新密码强度(策略可配置)
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, msg = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": msg}
|
||||
|
||||
@@ -146,12 +173,36 @@ class AuthService:
|
||||
result = await UserModel.update_password(user_id, new_password)
|
||||
|
||||
if result:
|
||||
# 清除所有Token
|
||||
# 清除旧Token
|
||||
await RedisClient.delete_user_token(user_id)
|
||||
return {"success": True, "message": "密码修改成功"}
|
||||
else:
|
||||
return {"success": False, "message": "密码修改失败"}
|
||||
|
||||
@staticmethod
|
||||
async def init_password(user_id: int, new_password: str) -> Dict[str, Any]:
|
||||
"""密码待修改时初始化新密码(无需原密码,仅 need_change_password=1 时可用)"""
|
||||
user = await UserModel.get_by_user_id(user_id)
|
||||
if not user:
|
||||
return {"success": False, "message": "用户不存在"}
|
||||
|
||||
if user.get("need_change_password") != 1:
|
||||
return {"success": False, "message": "当前账号无需初始化改密,请使用修改密码功能"}
|
||||
|
||||
# 校验密码强度(策略可配置)
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, msg = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": msg}
|
||||
|
||||
result = await UserModel.update_password(user_id, new_password)
|
||||
if result:
|
||||
await RedisClient.delete_user_token(user_id)
|
||||
return {"success": True, "message": "密码设置成功,请重新登录"}
|
||||
return {"success": False, "message": "密码设置失败"}
|
||||
|
||||
@staticmethod
|
||||
async def get_user_info(user_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""获取用户信息"""
|
||||
@@ -175,14 +226,275 @@ 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)
|
||||
# 绑定邮箱为可选展示字段,单独查询,避免影响登录/会话链路
|
||||
try:
|
||||
result["email"] = await UserModel.get_email_by_user_id(user_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"读取绑定邮箱失败(数据库可能尚未升级): {e}")
|
||||
result["email"] = None
|
||||
|
||||
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}分钟内有效)"
|
||||
}
|
||||
missing = EmailSender.missing_config()
|
||||
if missing:
|
||||
return {"success": False, "message": "系统未配置邮件服务,需设置:" + "、".join(missing)}
|
||||
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":
|
||||
logger.debug(f"找回密码请求未发送(账号不存在/非管理员): {username}, IP={ip}")
|
||||
return generic_success
|
||||
|
||||
# 绑定邮箱仅在找回密码功能中查询
|
||||
try:
|
||||
bound_email = await UserModel.get_email_by_user_id(user["user_id"])
|
||||
except Exception as e:
|
||||
logger.error(f"读取绑定邮箱失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,找回密码功能暂不可用"}
|
||||
if not bound_email:
|
||||
logger.debug(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(
|
||||
bound_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.debug(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": "账号不存在或不可重置密码"}
|
||||
|
||||
policy = await SettingService.get_password_policy()
|
||||
is_valid, message = security.validate_password_strength(
|
||||
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||
)
|
||||
if not is_valid:
|
||||
return {"success": False, "message": message}
|
||||
|
||||
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.debug(f"用户[{user_id}] 通过邮箱重置密码成功")
|
||||
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
|
||||
|
||||
@staticmethod
|
||||
async def _get_admin_by_password(user_id: int, password: str):
|
||||
"""校验当前密码,返回管理员用户(用于邮箱绑定/解绑)"""
|
||||
user = await UserModel.get_by_user_id(user_id)
|
||||
if not user or user.get("user_type") != "admin":
|
||||
return None, "仅管理员可绑定邮箱"
|
||||
is_valid, _ = security.verify_password_v2(password, user["password_hash"])
|
||||
if not is_valid:
|
||||
return None, "当前密码错误"
|
||||
return user, None
|
||||
|
||||
@staticmethod
|
||||
async def send_bind_email_code(user_id: int, email: str) -> Dict[str, Any]:
|
||||
"""向待绑定邮箱发送验证码(验证码绑定邮箱第一步,无需密码)"""
|
||||
missing = EmailSender.missing_config()
|
||||
if missing:
|
||||
return {"success": False, "message": "系统未配置邮件服务,需设置:" + "、".join(missing)}
|
||||
|
||||
user = await UserModel.get_by_user_id(user_id)
|
||||
if not user or user.get("user_type") != "admin":
|
||||
return {"success": False, "message": "仅管理员可绑定邮箱"}
|
||||
|
||||
normalized_email = (email or "").strip()
|
||||
if not is_valid_email(normalized_email):
|
||||
return {"success": False, "message": "邮箱格式不正确"}
|
||||
|
||||
# 数据库未升级(users.email 不存在)时提前返回明确提示,避免发送无效验证码
|
||||
try:
|
||||
await UserModel.get_email_by_user_id(user_id)
|
||||
except Exception as e:
|
||||
logger.error(f"邮箱绑定失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级后再绑定邮箱"}
|
||||
|
||||
# 频率限制:同一账号 60 秒内只能发送一次
|
||||
limit_key = f"email_bind_req:{user_id}"
|
||||
if await RedisClient.exists(limit_key):
|
||||
return {"success": False, "message": "验证码发送过于频繁,请稍后再试"}
|
||||
await RedisClient.set(limit_key, "1", expire=60)
|
||||
|
||||
code = f"{secrets.randbelow(1000000):06d}"
|
||||
expire_seconds = settings.EMAIL_CODE_EXPIRE_MINUTES * 60
|
||||
await RedisClient.set(
|
||||
f"email_bind_code:{user_id}",
|
||||
{"code": code, "email": normalized_email, "attempts": 0},
|
||||
expire=expire_seconds
|
||||
)
|
||||
|
||||
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>您好,您正在绑定本邮箱用于找回密码,验证码为:</p>
|
||||
<p style="text-align:center;margin:24px 0;">
|
||||
<span style="display:inline-block;padding:10px 28px;background:#f3f4ff;border-radius:6px;font-size:28px;font-weight:bold;letter-spacing:6px;color:#667eea;">{code}</span>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#888;">验证码 {settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效,请勿泄露给他人。</p>
|
||||
<p style="font-size:13px;color:#888;">如果并非您本人操作,请忽略本邮件。</p>
|
||||
</div>
|
||||
"""
|
||||
ok, message = await EmailSender.send(
|
||||
normalized_email,
|
||||
f"{settings.APP_NAME} - 邮箱绑定验证码",
|
||||
html_body
|
||||
)
|
||||
if not ok:
|
||||
await RedisClient.delete(f"email_bind_code:{user_id}")
|
||||
logger.error(f"邮箱验证码发送失败: 用户[{user_id}] -> {normalized_email} - {message}")
|
||||
return {"success": False, "message": "验证码发送失败,请检查邮箱地址或稍后重试"}
|
||||
|
||||
logger.debug(f"用户[{user_id}] 邮箱绑定验证码已发送至 {normalized_email}")
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"验证码已发送至 {normalized_email},{settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效"
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def confirm_bind_email(user_id: int, email: str, code: str) -> Dict[str, Any]:
|
||||
"""校验验证码并绑定邮箱(验证码绑定邮箱第二步)"""
|
||||
normalized_email = (email or "").strip()
|
||||
normalized_code = (code or "").strip()
|
||||
if not is_valid_email(normalized_email):
|
||||
return {"success": False, "message": "邮箱格式不正确"}
|
||||
if not normalized_code:
|
||||
return {"success": False, "message": "请输入验证码"}
|
||||
|
||||
cached = await RedisClient.get_json(f"email_bind_code:{user_id}")
|
||||
if not cached or not isinstance(cached, dict):
|
||||
return {"success": False, "message": "验证码已过期,请重新发送"}
|
||||
if cached.get("email") != normalized_email:
|
||||
return {"success": False, "message": "邮箱与验证码不匹配,请重新发送"}
|
||||
|
||||
attempts = int(cached.get("attempts", 0))
|
||||
if attempts >= 5:
|
||||
await RedisClient.delete(f"email_bind_code:{user_id}")
|
||||
return {"success": False, "message": "验证码尝试次数过多,请重新发送"}
|
||||
if cached.get("code") != normalized_code:
|
||||
cached["attempts"] = attempts + 1
|
||||
await RedisClient.set(
|
||||
f"email_bind_code:{user_id}",
|
||||
cached,
|
||||
expire=settings.EMAIL_CODE_EXPIRE_MINUTES * 60
|
||||
)
|
||||
return {"success": False, "message": "验证码错误"}
|
||||
|
||||
try:
|
||||
updated = await UserModel.update_email(user_id, normalized_email)
|
||||
except Exception as e:
|
||||
logger.error(f"绑定邮箱失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级后再绑定邮箱"}
|
||||
if not updated:
|
||||
return {"success": False, "message": "邮箱绑定失败"}
|
||||
|
||||
await RedisClient.delete(f"email_bind_code:{user_id}")
|
||||
logger.debug(f"用户[{user_id}] 邮箱绑定成功: {normalized_email}")
|
||||
return {"success": True, "message": "邮箱绑定成功", "email": normalized_email}
|
||||
|
||||
@staticmethod
|
||||
async def unbind_email(user_id: int, password: str) -> Dict[str, Any]:
|
||||
"""解除绑定邮箱(验证当前密码)"""
|
||||
_, error = await AuthService._get_admin_by_password(user_id, password)
|
||||
if error:
|
||||
return {"success": False, "message": error}
|
||||
|
||||
await RedisClient.delete(f"email_bind_code:{user_id}")
|
||||
try:
|
||||
updated = await UserModel.update_email(user_id, None)
|
||||
except Exception as e:
|
||||
logger.error(f"解除绑定邮箱失败(数据库可能待升级): {e}")
|
||||
return {"success": False, "message": "数据库待升级,请先完成系统升级后再操作邮箱"}
|
||||
if not updated:
|
||||
return {"success": False, "message": "解除绑定失败"}
|
||||
|
||||
logger.debug(f"用户[{user_id}] 已解除邮箱绑定")
|
||||
return {"success": True, "message": "邮箱已解除绑定", "email": None}
|
||||
|
||||
@staticmethod
|
||||
def _get_redirect_path(user_type: str, role: str = None) -> str:
|
||||
"""获取跳转路径"""
|
||||
|
||||
@@ -13,8 +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.user import UserModel
|
||||
from models.conduct import ConductModel, _append_semester_filter
|
||||
from models.semester import SemesterModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
@@ -26,6 +25,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 +59,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 points_change > 0:
|
||||
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 +101,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 +171,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 +215,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 +233,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 +257,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 +272,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 +303,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 +323,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 +344,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 +365,115 @@ 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 = []
|
||||
for month in sorted(months_map.keys()):
|
||||
entry = months_map[month]
|
||||
# 月度分独立计算,与基础分无关;总分才使用基础分
|
||||
entry["month_score"] = entry["bonus"] + entry["deduction"]
|
||||
entry["net"] = entry["month_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,167 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
"""节假日服务:优先使用国内接口获取法定节假日与调休补班(缓存 + 失败降级)"""
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import time
|
||||
import asyncio
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import date
|
||||
from typing import Dict, Any
|
||||
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 国内节假日接口(apihubs.cn,国内节点、无 Cloudflare)
|
||||
HOLIDAY_API_DOMESTIC = 'https://api.apihubs.cn/holiday/get?year={year}&size=400'
|
||||
# 备用接口(节假曰 API),仅在主接口不可用时使用
|
||||
HOLIDAY_API_FALLBACK = 'https://api.jiejiariapi.com/v1/holidays/{year}'
|
||||
CACHE_TTL = 12 * 3600
|
||||
FAIL_CACHE_TTL = 600
|
||||
REQUEST_TIMEOUT = 6
|
||||
|
||||
_cache: Dict[int, Dict[str, Any]] = {}
|
||||
|
||||
|
||||
def _urlopen_json(url: str) -> Any:
|
||||
"""请求 JSON(证书校验失败时回退为不校验重试一次)"""
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
except (ssl.SSLError, urllib.error.URLError) as e:
|
||||
logger.warning(f"节假日接口证书校验失败,回退重试: {e}")
|
||||
context = ssl._create_unverified_context()
|
||||
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT, context=context) as response:
|
||||
return json.loads(response.read().decode('utf-8'))
|
||||
|
||||
|
||||
def _fetch_domestic(year: int) -> Dict[str, Any]:
|
||||
"""国内接口(apihubs.cn):按 workday/weekend 标志解析放假与调休补班"""
|
||||
payload = _urlopen_json(HOLIDAY_API_DOMESTIC.format(year=year))
|
||||
items = (payload.get('data') or {}).get('list') or []
|
||||
if not items:
|
||||
raise ValueError("国内接口未返回数据")
|
||||
|
||||
holidays: Dict[str, str] = {}
|
||||
workdays: Dict[str, str] = {}
|
||||
for item in items:
|
||||
try:
|
||||
date_int = int(item.get('date') or 0)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if date_int < 20000101:
|
||||
continue
|
||||
s = str(date_int)
|
||||
day = f'{s[0:4]}-{s[4:6]}-{s[6:8]}'
|
||||
# workday: 1=上班, 2=休息;weekend: 1=周六/日, 2=工作日
|
||||
if item.get('workday') == 2 and item.get('weekend') == 2:
|
||||
holidays[day] = '法定节假日'
|
||||
elif item.get('workday') == 1 and item.get('weekend') == 1:
|
||||
workdays[day] = '调休补班'
|
||||
|
||||
if not holidays:
|
||||
raise ValueError("国内接口未解析到节假日数据")
|
||||
return {'holidays': holidays, 'workdays': workdays, 'api_ok': True}
|
||||
|
||||
|
||||
def _fetch_fallback(year: int) -> Dict[str, Any]:
|
||||
"""备用接口(节假曰 API):放假 + 调休补班"""
|
||||
payload = _urlopen_json(HOLIDAY_API_FALLBACK.format(year=year))
|
||||
if not isinstance(payload, dict) or not payload:
|
||||
raise ValueError("备用接口返回数据为空")
|
||||
|
||||
holidays: Dict[str, str] = {}
|
||||
workdays: Dict[str, str] = {}
|
||||
for key, info in payload.items():
|
||||
if not isinstance(info, dict):
|
||||
continue
|
||||
day = str(info.get('date') or key)[:10]
|
||||
name = info.get('name') or ('节假日' if info.get('isOffDay') else '调休补班')
|
||||
if info.get('isOffDay'):
|
||||
holidays[day] = name
|
||||
else:
|
||||
workdays[day] = name
|
||||
|
||||
if not holidays:
|
||||
raise ValueError("备用接口未返回节假日数据")
|
||||
return {'holidays': holidays, 'workdays': workdays, 'api_ok': True}
|
||||
|
||||
|
||||
def _fetch_year_sync(year: int) -> Dict[str, Any]:
|
||||
"""同步获取某年节假日数据:国内接口优先,失败后尝试备用接口"""
|
||||
try:
|
||||
return _fetch_domestic(year)
|
||||
except Exception as e:
|
||||
logger.warning(f"国内节假日接口获取失败({year}),尝试备用接口: {e}")
|
||||
|
||||
try:
|
||||
return _fetch_fallback(year)
|
||||
except Exception as e:
|
||||
logger.warning(f"备用节假日接口获取失败({year}): {e}")
|
||||
|
||||
return {'holidays': {}, 'workdays': {}, 'api_ok': False}
|
||||
|
||||
|
||||
async def get_year_data(year: int) -> Dict[str, Any]:
|
||||
"""获取某年的节假日/调休数据(内存缓存,接口失败自动降级)"""
|
||||
now = time.time()
|
||||
cached = _cache.get(year)
|
||||
if cached:
|
||||
ttl = CACHE_TTL if cached.get('api_ok') else FAIL_CACHE_TTL
|
||||
if now - cached['fetched_at'] < ttl:
|
||||
return cached
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
data = await loop.run_in_executor(None, _fetch_year_sync, year)
|
||||
data['fetched_at'] = now
|
||||
_cache[year] = data
|
||||
if data['api_ok']:
|
||||
logger.info(
|
||||
f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天"
|
||||
)
|
||||
else:
|
||||
logger.warning(f"节假日数据获取失败: {year}年(接口均不可用)")
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.warning(f"节假日数据获取异常({year}): {e}")
|
||||
failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now}
|
||||
_cache[year] = failed
|
||||
return failed
|
||||
|
||||
|
||||
async def get_range_data(start: date, end: date) -> Dict[str, Any]:
|
||||
"""获取日期范围内的节假日/调休数据"""
|
||||
holidays: Dict[str, str] = {}
|
||||
workdays: Dict[str, str] = {}
|
||||
api_ok = True
|
||||
|
||||
for year in range(start.year, end.year + 1):
|
||||
data = await get_year_data(year)
|
||||
holidays.update(data['holidays'])
|
||||
workdays.update(data['workdays'])
|
||||
api_ok = api_ok and data['api_ok']
|
||||
|
||||
start_iso = start.isoformat()
|
||||
end_iso = end.isoformat()
|
||||
return {
|
||||
'holidays': {d: n for d, n in holidays.items() if start_iso <= d <= end_iso},
|
||||
'workdays': {d: n for d, n in workdays.items() if start_iso <= d <= end_iso},
|
||||
'api_ok': api_ok
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
"""作业服务:按次登记(一次登记覆盖多次作业,按缺交次数扣分并写入提交统计)"""
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
from models.homework import HomeworkModel
|
||||
from models.student import StudentModel
|
||||
from models.subject import SubjectModel
|
||||
from models.conduct import ConductModel
|
||||
from models.semester import SemesterModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
MAX_TOTAL_TIMES = 99
|
||||
|
||||
|
||||
class HomeworkService:
|
||||
"""作业服务"""
|
||||
|
||||
@staticmethod
|
||||
async def register_batch(
|
||||
records: List[Dict[str, int]],
|
||||
deadline: str,
|
||||
total_times: int,
|
||||
per_deduction: Optional[int],
|
||||
title: Optional[str],
|
||||
subject_id: int,
|
||||
note: Optional[str],
|
||||
operator_id: int,
|
||||
operator_name: str
|
||||
) -> Dict[str, Any]:
|
||||
"""按次登记作业
|
||||
|
||||
一次登记覆盖 total_times 次作业:缺交学生前 miss_count 次记为未交,
|
||||
其余学生全部记为已交;按 缺交次数 × 单次扣分 生成扣分记录。
|
||||
"""
|
||||
if total_times < 1 or total_times > MAX_TOTAL_TIMES:
|
||||
return {"success": False, "message": f"总提交次数需在1-{MAX_TOTAL_TIMES}之间"}
|
||||
|
||||
# 学生去重与缺交次数校验
|
||||
miss_map: Dict[int, int] = {}
|
||||
for item in records:
|
||||
sid = item.get("student_id")
|
||||
miss = item.get("miss_count")
|
||||
if not sid or not isinstance(miss, int) or miss < 1 or miss > total_times:
|
||||
return {"success": False, "message": "缺交次数不合法(需在1~总提交次数之间)"}
|
||||
if sid in miss_map:
|
||||
return {"success": False, "message": "同一学生请勿重复提交"}
|
||||
miss_map[sid] = miss
|
||||
|
||||
# 科目校验(作业记录必须归属科目)
|
||||
subject = await SubjectModel.get_by_id(subject_id)
|
||||
if not subject:
|
||||
return {"success": False, "message": "科目不存在"}
|
||||
subject_name = subject["subject_name"]
|
||||
|
||||
# 权限与扣分上限校验
|
||||
limits = await PermissionChecker.get_score_limits(operator_id)
|
||||
if not limits["can_manage_conduct"]:
|
||||
return {"success": False, "message": "无权进行扣分操作"}
|
||||
if not limits["can_subtract"]:
|
||||
return {"success": False, "message": "当前权限组不允许扣分"}
|
||||
|
||||
deduction = per_deduction or settings.DEDUCTION_HOMEWORK_NOT_SUBMIT
|
||||
if deduction < 1 or deduction > 20:
|
||||
return {"success": False, "message": "单次缺交扣分需在1-20之间"}
|
||||
|
||||
students = await StudentModel.get_all()
|
||||
student_map = {s["student_id"]: s for s in students}
|
||||
for sid in miss_map:
|
||||
if sid not in student_map:
|
||||
return {"success": False, "message": "存在无效学生(不存在或已禁用)"}
|
||||
|
||||
# 单次扣分上限按"每次缺交"校验:按次登记中一次缺交视为一次扣分,合计分可超过单次上限
|
||||
if limits["max_subtract"] is not None and deduction > limits["max_subtract"]:
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"单次缺交扣分不能超过{limits['max_subtract']}分"
|
||||
}
|
||||
|
||||
# 创建作业记录(每次一条)
|
||||
base_title = (title or "作业登记").strip() or "作业登记"
|
||||
if total_times == 1:
|
||||
titles = [base_title]
|
||||
else:
|
||||
titles = [f"{base_title} #{i}" for i in range(1, total_times + 1)]
|
||||
assignment_ids = await HomeworkModel.create_assignments(
|
||||
subject_id=subject_id,
|
||||
titles=titles,
|
||||
deadline=deadline,
|
||||
created_by=operator_id
|
||||
)
|
||||
|
||||
# 写入提交数据:缺交学生前 k 次记为未交,其他学生全部记为已交
|
||||
rows = []
|
||||
for student in students:
|
||||
sid = student["student_id"]
|
||||
miss = miss_map.get(sid, 0)
|
||||
for index, assignment_id in enumerate(assignment_ids):
|
||||
status = "not_submitted" if index < miss else "submitted"
|
||||
rows.append((assignment_id, sid, status, operator_id))
|
||||
submission_count = await HomeworkModel.bulk_create_submissions(rows)
|
||||
|
||||
# 生成扣分记录并更新总分
|
||||
active_semester = await SemesterModel.get_active()
|
||||
semester_id = active_semester["semester_id"] if active_semester else None
|
||||
|
||||
total_deduction = 0
|
||||
deducted_students = 0
|
||||
for sid, miss in miss_map.items():
|
||||
points_change = -(miss * deduction)
|
||||
reason = f"[{subject_name}]{base_title} 缺交 {miss}/{total_times} 次"
|
||||
if note and note.strip():
|
||||
reason += f"({note.strip()})"
|
||||
reason = reason[:255]
|
||||
|
||||
await ConductModel.create_record(
|
||||
student_id=sid,
|
||||
points_change=points_change,
|
||||
reason=reason,
|
||||
recorder_id=operator_id,
|
||||
recorder_name=operator_name,
|
||||
related_type="homework",
|
||||
semester_id=semester_id
|
||||
)
|
||||
await StudentModel.update_total_points(sid, points_change)
|
||||
await HomeworkModel.mark_not_submitted_deducted(assignment_ids, sid)
|
||||
|
||||
total_deduction += -points_change
|
||||
deducted_students += 1
|
||||
|
||||
logger.info(
|
||||
f"用户[{operator_id}] 按次登记作业[{base_title}] 共{total_times}次,"
|
||||
f"缺交{deducted_students}人,合计扣{total_deduction}分"
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"登记完成:共{total_times}次作业,缺交{deducted_students}人,合计扣{total_deduction}分",
|
||||
"data": {
|
||||
"assignments": len(assignment_ids),
|
||||
"submissions": submission_count,
|
||||
"deducted_students": deducted_students,
|
||||
"total_deduction": total_deduction
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from models.log import LoginLogModel, OperationLogModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -55,3 +54,44 @@ class LogService:
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"写入操作日志失败: {e}")
|
||||
|
||||
@staticmethod
|
||||
async def get_operation_logs(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
operation_type: str = None,
|
||||
operator: str = None,
|
||||
start_date: str = None,
|
||||
end_date: str = None,
|
||||
keyword: str = None
|
||||
) -> dict:
|
||||
"""查询操作日志(分页 + 筛选)"""
|
||||
if operation_type == "":
|
||||
operation_type = None
|
||||
if operator == "":
|
||||
operator = None
|
||||
if start_date == "":
|
||||
start_date = None
|
||||
if end_date == "":
|
||||
end_date = None
|
||||
if keyword == "":
|
||||
keyword = None
|
||||
offset = (page - 1) * page_size
|
||||
total = await OperationLogModel.count_logs(
|
||||
operation_type, operator, start_date, end_date, keyword
|
||||
)
|
||||
logs = await OperationLogModel.get_logs(
|
||||
operation_type, operator, start_date, end_date, keyword, page_size, offset
|
||||
)
|
||||
return {
|
||||
"logs": logs,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def get_operation_log_types() -> dict:
|
||||
"""获取操作日志类型列表(用于筛选下拉)"""
|
||||
return {"types": await OperationLogModel.get_types()}
|
||||
@@ -10,7 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
import math
|
||||
from typing import Dict, Any, Optional, List
|
||||
from typing import Dict, Any
|
||||
|
||||
from models.user import UserModel
|
||||
from models.student import StudentModel
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 统计报表服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any
|
||||
from models.report import ReportModel
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
ATTENDANCE_STATUSES = ["present", "absent", "late", "leave"]
|
||||
HOMEWORK_STATUSES = ["submitted", "not_submitted", "late"]
|
||||
|
||||
|
||||
class ReportService:
|
||||
"""统计报表服务"""
|
||||
|
||||
@staticmethod
|
||||
async def attendance_report(start_date: str, end_date: str) -> Dict[str, Any]:
|
||||
"""考勤统计报表:出勤/缺勤/迟到/请假与出勤率"""
|
||||
students = await ReportModel.get_active_students()
|
||||
stats = await ReportModel.get_attendance_stats(start_date, end_date)
|
||||
|
||||
counts_map: Dict[int, Dict[str, int]] = {}
|
||||
for stat in stats:
|
||||
sid = stat["student_id"]
|
||||
entry = counts_map.setdefault(sid, {key: 0 for key in ATTENDANCE_STATUSES})
|
||||
if stat["status"] in entry:
|
||||
entry[stat["status"]] = int(stat["cnt"] or 0)
|
||||
|
||||
rows = []
|
||||
summary = {key: 0 for key in ATTENDANCE_STATUSES}
|
||||
for student in students:
|
||||
counts = counts_map.get(student["student_id"], {key: 0 for key in ATTENDANCE_STATUSES})
|
||||
total = sum(counts.values())
|
||||
present = counts["present"]
|
||||
rate = round(present / total * 100, 1) if total else None
|
||||
rows.append({
|
||||
"student_id": student["student_id"],
|
||||
"student_no": student["student_no"],
|
||||
"name": student["name"],
|
||||
"present": present,
|
||||
"absent": counts["absent"],
|
||||
"late": counts["late"],
|
||||
"leave": counts["leave"],
|
||||
"total": total,
|
||||
"rate": rate
|
||||
})
|
||||
for key in ATTENDANCE_STATUSES:
|
||||
summary[key] += counts[key]
|
||||
|
||||
rows.sort(key=lambda r: (-r["absent"], -r["late"], r["student_no"]))
|
||||
summary["total"] = sum(summary.values())
|
||||
summary["rate"] = (
|
||||
round(summary["present"] / summary["total"] * 100, 1)
|
||||
if summary["total"] else None
|
||||
)
|
||||
return {
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"rows": rows,
|
||||
"summary": summary
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def homework_report(start_date: str, end_date: str) -> Dict[str, Any]:
|
||||
"""作业统计报表:已交/未交/迟交与未交率"""
|
||||
students = await ReportModel.get_active_students()
|
||||
stats = await ReportModel.get_homework_stats(start_date, end_date)
|
||||
|
||||
counts_map: Dict[int, Dict[str, int]] = {}
|
||||
for stat in stats:
|
||||
sid = stat["student_id"]
|
||||
entry = counts_map.setdefault(sid, {key: 0 for key in HOMEWORK_STATUSES})
|
||||
if stat["status"] in entry:
|
||||
entry[stat["status"]] = int(stat["cnt"] or 0)
|
||||
|
||||
rows = []
|
||||
summary = {key: 0 for key in HOMEWORK_STATUSES}
|
||||
for student in students:
|
||||
counts = counts_map.get(student["student_id"], {key: 0 for key in HOMEWORK_STATUSES})
|
||||
total = sum(counts.values())
|
||||
miss_rate = round(counts["not_submitted"] / total * 100, 1) if total else None
|
||||
rows.append({
|
||||
"student_id": student["student_id"],
|
||||
"student_no": student["student_no"],
|
||||
"name": student["name"],
|
||||
"submitted": counts["submitted"],
|
||||
"not_submitted": counts["not_submitted"],
|
||||
"late": counts["late"],
|
||||
"total": total,
|
||||
"miss_rate": miss_rate
|
||||
})
|
||||
for key in HOMEWORK_STATUSES:
|
||||
summary[key] += counts[key]
|
||||
|
||||
rows.sort(key=lambda r: (-r["not_submitted"], -r["late"], r["student_no"]))
|
||||
summary["total"] = sum(summary.values())
|
||||
summary["miss_rate"] = (
|
||||
round(summary["not_submitted"] / summary["total"] * 100, 1)
|
||||
if summary["total"] else None
|
||||
)
|
||||
return {
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"rows": rows,
|
||||
"summary": summary
|
||||
}
|
||||
@@ -10,14 +10,12 @@
|
||||
# ===========================================
|
||||
|
||||
import datetime
|
||||
from typing import Dict, Any, List, Optional
|
||||
from typing import Dict, Any
|
||||
|
||||
from models.semester import SemesterModel, SemesterArchiveModel
|
||||
from models.student import StudentModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
from utils.logger import get_logger
|
||||
from utils.database import execute_query
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -389,6 +387,25 @@ class SemesterService:
|
||||
|
||||
archives = await SemesterArchiveModel.get_by_semester(semester_id)
|
||||
|
||||
# 归档对比:与上一个已归档学期比较分数与名次
|
||||
previous_semester = await SemesterModel.get_previous_archived_semester(semester_id)
|
||||
if previous_semester:
|
||||
prev_archives = await SemesterArchiveModel.get_by_semester(previous_semester["semester_id"])
|
||||
prev_map = {a["student_id"]: a for a in prev_archives}
|
||||
for archive in archives:
|
||||
prev = prev_map.get(archive["student_id"])
|
||||
if prev:
|
||||
archive["prev_final_points"] = prev["final_points"]
|
||||
archive["points_change"] = (archive["final_points"] or 0) - (prev["final_points"] or 0)
|
||||
archive["prev_rank_position"] = prev["rank_position"]
|
||||
# 正数表示名次进步
|
||||
archive["rank_change"] = (prev["rank_position"] or 0) - (archive["rank_position"] or 0)
|
||||
else:
|
||||
archive["prev_final_points"] = None
|
||||
archive["points_change"] = None
|
||||
archive["prev_rank_position"] = None
|
||||
archive["rank_change"] = None
|
||||
|
||||
total = len(archives)
|
||||
offset = (page - 1) * page_size
|
||||
paged_archives = archives[offset:offset + page_size]
|
||||
@@ -403,6 +420,10 @@ class SemesterService:
|
||||
"end_date": semester.get('end_date'),
|
||||
"is_archived": bool(semester['is_archived'])
|
||||
},
|
||||
"previous_semester": {
|
||||
"semester_id": previous_semester["semester_id"],
|
||||
"semester_name": previous_semester["semester_name"]
|
||||
} if previous_semester else None,
|
||||
"archives": paged_archives,
|
||||
"total": total,
|
||||
"page": page,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 系统设置服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any
|
||||
from models.system_setting import SystemSettingModel
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 密码策略默认值(未配置时使用)
|
||||
DEFAULT_PASSWORD_POLICY = {
|
||||
"min_length": 6,
|
||||
"max_length": 20,
|
||||
"min_types": 3
|
||||
}
|
||||
|
||||
|
||||
class SettingService:
|
||||
"""系统设置服务"""
|
||||
|
||||
@staticmethod
|
||||
async def get_password_policy() -> Dict[str, int]:
|
||||
"""获取密码策略(长度范围与最少字符种类数)"""
|
||||
values = await SystemSettingModel.get_many([
|
||||
"password_min_length", "password_max_length", "password_min_types"
|
||||
])
|
||||
policy = dict(DEFAULT_PASSWORD_POLICY)
|
||||
|
||||
def parse_int(key: str, default: int, low: int, high: int) -> int:
|
||||
try:
|
||||
value = int(values.get(key, ""))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return max(low, min(high, value))
|
||||
|
||||
policy["min_length"] = parse_int("password_min_length", policy["min_length"], 4, 64)
|
||||
policy["max_length"] = parse_int("password_max_length", policy["max_length"], 8, 100)
|
||||
policy["min_types"] = parse_int("password_min_types", policy["min_types"], 1, 4)
|
||||
if policy["min_length"] > policy["max_length"]:
|
||||
policy["min_length"] = policy["max_length"]
|
||||
return policy
|
||||
|
||||
@staticmethod
|
||||
async def update_password_policy(
|
||||
min_length: int,
|
||||
max_length: int,
|
||||
min_types: int,
|
||||
operator_id: int = None
|
||||
) -> Dict[str, Any]:
|
||||
"""更新密码策略"""
|
||||
if not (4 <= min_length <= 64):
|
||||
return {"success": False, "message": "最小长度需在4-64之间"}
|
||||
if not (8 <= max_length <= 100):
|
||||
return {"success": False, "message": "最大长度需在8-100之间"}
|
||||
if min_length > max_length:
|
||||
return {"success": False, "message": "最小长度不能大于最大长度"}
|
||||
if not (1 <= min_types <= 4):
|
||||
return {"success": False, "message": "字符种类数需在1-4之间"}
|
||||
|
||||
await SystemSettingModel.upsert("password_min_length", str(min_length))
|
||||
await SystemSettingModel.upsert("password_max_length", str(max_length))
|
||||
await SystemSettingModel.upsert("password_min_types", str(min_types))
|
||||
logger.info(
|
||||
f"用户[{operator_id}] 更新密码策略: {min_length}-{max_length}位, 至少{min_types}种字符"
|
||||
)
|
||||
return {"success": True, "message": "密码策略已保存"}
|
||||
@@ -9,13 +9,11 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from models.student import StudentModel
|
||||
from models.conduct import ConductModel
|
||||
from models.attendance import AttendanceModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from utils.database import execute_query
|
||||
from utils.logger import get_logger
|
||||
|
||||
@@ -123,15 +121,20 @@ class StudentService:
|
||||
@staticmethod
|
||||
async def get_ranking(
|
||||
user_id: int,
|
||||
limit: int = 50
|
||||
limit: int = 50,
|
||||
month: str = None
|
||||
) -> Dict[str, Any]:
|
||||
"""获取排行榜(单班级系统)"""
|
||||
ranking = await StudentModel.get_ranking(limit=limit)
|
||||
"""获取排行榜(单班级系统);传 month 时返回月度分排行"""
|
||||
if month:
|
||||
ranking = await StudentModel.get_monthly_ranking(month=month, limit=limit)
|
||||
else:
|
||||
ranking = await StudentModel.get_ranking(limit=limit)
|
||||
total_students = await StudentModel.get_total_count()
|
||||
|
||||
return {
|
||||
"ranking": ranking,
|
||||
"total_students": total_students
|
||||
"total_students": total_students,
|
||||
"month": month
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
from typing import Dict, Any, Optional, List
|
||||
|
||||
from models.subject import SubjectModel
|
||||
from utils.logger import get_logger
|
||||
@@ -36,27 +36,47 @@ class SubjectService:
|
||||
subject_code: Optional[str],
|
||||
sort_order: int = 0
|
||||
) -> Dict[str, Any]:
|
||||
"""创建科目"""
|
||||
"""创建科目(科目代码留空存 NULL)"""
|
||||
name = (subject_name or "").strip()
|
||||
if not name:
|
||||
return {"success": False, "message": "科目名称不能为空"}
|
||||
code = (subject_code or "").strip() or None
|
||||
|
||||
# 检查是否已存在
|
||||
existing = await SubjectModel.get_by_name(subject_name)
|
||||
existing = await SubjectModel.get_by_name(name)
|
||||
if existing:
|
||||
return {"success": False, "message": "科目名称已存在"}
|
||||
|
||||
subject_id = await SubjectModel.create(
|
||||
subject_name=subject_name,
|
||||
subject_code=subject_code,
|
||||
subject_name=name,
|
||||
subject_code=code,
|
||||
sort_order=sort_order
|
||||
)
|
||||
|
||||
if subject_id:
|
||||
logger.info(f"创建科目: {subject_name}")
|
||||
logger.info(f"创建科目: {name}")
|
||||
return {"success": True, "subject_id": subject_id}
|
||||
else:
|
||||
return {"success": False, "message": "创建科目失败"}
|
||||
|
||||
@staticmethod
|
||||
async def update_subject(subject_id: int, **kwargs) -> Dict[str, Any]:
|
||||
"""更新科目"""
|
||||
"""更新科目(科目代码传空字符串表示清空)"""
|
||||
subject = await SubjectModel.get_by_id(subject_id)
|
||||
if not subject:
|
||||
return {"success": False, "message": "科目不存在"}
|
||||
|
||||
if "subject_name" in kwargs:
|
||||
name = (kwargs.get("subject_name") or "").strip()
|
||||
if not name:
|
||||
return {"success": False, "message": "科目名称不能为空"}
|
||||
existing = await SubjectModel.get_by_name(name)
|
||||
if existing and existing["subject_id"] != subject_id:
|
||||
return {"success": False, "message": "科目名称已存在"}
|
||||
kwargs["subject_name"] = name
|
||||
if "subject_code" in kwargs:
|
||||
kwargs["subject_code"] = (kwargs.get("subject_code") or "").strip() or None
|
||||
|
||||
result = await SubjectModel.update(subject_id, **kwargs)
|
||||
|
||||
if result:
|
||||
@@ -65,6 +85,15 @@ class SubjectService:
|
||||
else:
|
||||
return {"success": False, "message": "更新科目失败"}
|
||||
|
||||
@staticmethod
|
||||
async def reorder_subjects(subject_ids: List[int]) -> Dict[str, Any]:
|
||||
"""按新顺序批量更新科目排序"""
|
||||
if not subject_ids:
|
||||
return {"success": False, "message": "排序列表不能为空"}
|
||||
await SubjectModel.reorder(subject_ids)
|
||||
logger.info(f"科目排序已更新: {subject_ids}")
|
||||
return {"success": True}
|
||||
|
||||
@staticmethod
|
||||
async def delete_subject(subject_id: int) -> Dict[str, Any]:
|
||||
"""删除科目(真正删除记录)"""
|
||||
|
||||
@@ -83,20 +83,6 @@ async def get_connection():
|
||||
await conn.commit()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_transaction():
|
||||
"""获取事务连接"""
|
||||
pool = get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.cursor() as cursor:
|
||||
try:
|
||||
yield cursor
|
||||
await conn.commit()
|
||||
except Exception:
|
||||
await conn.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def execute_query(sql: str, params: tuple = None) -> List[Dict[str, Any]]:
|
||||
"""执行查询SQL"""
|
||||
async with get_connection() as cursor:
|
||||
@@ -132,19 +118,3 @@ async def execute_many(sql: str, params_list: list) -> int:
|
||||
async with get_connection() as cursor:
|
||||
await cursor.executemany(sql, params_list)
|
||||
return cursor.rowcount
|
||||
|
||||
|
||||
async def call_procedure(proc_name: str, args: tuple = None) -> List[Dict[str, Any]]:
|
||||
"""调用存储过程"""
|
||||
async with get_connection() as cursor:
|
||||
if args:
|
||||
await cursor.callproc(proc_name, args)
|
||||
else:
|
||||
await cursor.callproc(proc_name)
|
||||
|
||||
# 获取结果
|
||||
result = []
|
||||
for result_set in cursor.fetchall():
|
||||
if result_set:
|
||||
result.extend(result_set)
|
||||
return result
|
||||
@@ -0,0 +1,80 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 邮件发送工具(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 missing_config() -> list:
|
||||
"""返回缺失/未启用的邮件配置项名称(不含敏感值)"""
|
||||
if not settings.SMTP_ENABLED:
|
||||
return ["SMTP_ENABLED=true"]
|
||||
missing = []
|
||||
if not settings.SMTP_HOST:
|
||||
missing.append("SMTP_HOST")
|
||||
if not settings.SMTP_USER:
|
||||
missing.append("SMTP_USER")
|
||||
if not settings.SMTP_PASSWORD:
|
||||
missing.append("SMTP_PASSWORD")
|
||||
return missing
|
||||
|
||||
@staticmethod
|
||||
def is_configured() -> bool:
|
||||
"""检查 SMTP 是否已完整配置"""
|
||||
return not EmailSender.missing_config()
|
||||
|
||||
@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.debug(f"邮件发送成功: {to_email} - {subject}")
|
||||
return True, "发送成功"
|
||||
except Exception as e:
|
||||
logger.error(f"邮件发送失败: {to_email} - {e}")
|
||||
return False, f"邮件发送失败: {str(e)}"
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from jose import jwt, JWTError
|
||||
from jose import jwt
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Any, Optional, Dict, List
|
||||
from typing import Any
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
@@ -54,53 +54,3 @@ def error_response(
|
||||
"data": data
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def unauthorized_response(message: str = "未授权,请重新登录") -> JSONResponse:
|
||||
"""未授权响应"""
|
||||
return JSONResponse(
|
||||
status_code=ResponseCode.UNAUTHORIZED,
|
||||
content={
|
||||
"success": False,
|
||||
"code": ResponseCode.UNAUTHORIZED,
|
||||
"message": message,
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def forbidden_response(message: str = "权限不足") -> JSONResponse:
|
||||
"""禁止访问响应"""
|
||||
return JSONResponse(
|
||||
status_code=ResponseCode.FORBIDDEN,
|
||||
content={
|
||||
"success": False,
|
||||
"code": ResponseCode.FORBIDDEN,
|
||||
"message": message,
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def not_found_response(message: str = "资源不存在") -> JSONResponse:
|
||||
"""资源不存在响应"""
|
||||
return JSONResponse(
|
||||
status_code=ResponseCode.NOT_FOUND,
|
||||
content={
|
||||
"success": False,
|
||||
"code": ResponseCode.NOT_FOUND,
|
||||
"message": message,
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def paginated_response(items: List[Any], total: int, page: int, page_size: int) -> Dict:
|
||||
"""分页响应数据"""
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size
|
||||
}
|
||||
+40
-15
@@ -15,6 +15,16 @@ import re
|
||||
from passlib.hash import bcrypt as bcrypt_hash
|
||||
from config import settings
|
||||
|
||||
try:
|
||||
import bcrypt as _bcrypt_lib
|
||||
except Exception:
|
||||
_bcrypt_lib = None
|
||||
|
||||
|
||||
def _bcrypt_bytes(password: str) -> bytes:
|
||||
"""bcrypt 仅使用前 72 字节(与历史行为一致)"""
|
||||
return password.encode('utf-8')[:72]
|
||||
|
||||
|
||||
class SecurityUtils:
|
||||
"""安全工具类"""
|
||||
@@ -35,7 +45,9 @@ class SecurityUtils:
|
||||
|
||||
@staticmethod
|
||||
def bcrypt_password(password: str) -> str:
|
||||
"""使用bcrypt加密密码"""
|
||||
"""使用bcrypt加密密码(优先使用 bcrypt 库,回退 passlib,避免版本兼容问题)"""
|
||||
if _bcrypt_lib is not None:
|
||||
return _bcrypt_lib.hashpw(_bcrypt_bytes(password), _bcrypt_lib.gensalt(rounds=12)).decode('utf-8')
|
||||
return bcrypt_hash.using(rounds=12).hash(password)
|
||||
|
||||
@staticmethod
|
||||
@@ -44,11 +56,19 @@ class SecurityUtils:
|
||||
验证密码(支持bcrypt和旧哈希)
|
||||
返回: (是否验证成功, 是否需要升级哈希)
|
||||
"""
|
||||
try:
|
||||
if bcrypt_hash.verify(plain_password, hashed_password):
|
||||
return True, False
|
||||
except Exception:
|
||||
pass
|
||||
if hashed_password and hashed_password.startswith(('$2a$', '$2b$', '$2y$')):
|
||||
if _bcrypt_lib is not None:
|
||||
try:
|
||||
if _bcrypt_lib.checkpw(_bcrypt_bytes(plain_password), hashed_password.encode('utf-8')):
|
||||
return True, False
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
if bcrypt_hash.verify(plain_password, hashed_password):
|
||||
return True, False
|
||||
except Exception:
|
||||
pass
|
||||
# 回退到旧的sha1_md5验证
|
||||
if SecurityUtils.sha1_md5_password(plain_password) == hashed_password:
|
||||
return True, True
|
||||
@@ -66,16 +86,21 @@ class SecurityUtils:
|
||||
return ''.join(secrets.choice(alphabet) for _ in range(length))
|
||||
|
||||
@staticmethod
|
||||
def validate_password_strength(password: str) -> tuple:
|
||||
def validate_password_strength(
|
||||
password: str,
|
||||
min_length: int = 6,
|
||||
max_length: int = 20,
|
||||
min_types: int = 3
|
||||
) -> tuple:
|
||||
"""
|
||||
验证密码强度
|
||||
要求:大小写字母、数字、特殊符号 至少包含其中3种
|
||||
验证密码强度(策略可配置)
|
||||
要求:由 大写字母/小写字母/数字/特殊符号 中至少 min_types 种组成
|
||||
返回: (是否有效, 错误信息)
|
||||
"""
|
||||
if len(password) < 6:
|
||||
return False, "密码长度至少6位"
|
||||
if len(password) > 20:
|
||||
return False, "密码长度不能超过20位"
|
||||
if len(password) < min_length:
|
||||
return False, f"密码长度至少{min_length}位"
|
||||
if len(password) > max_length:
|
||||
return False, f"密码长度不能超过{max_length}位"
|
||||
|
||||
# 检查四种字符类型
|
||||
has_upper = any(c.isupper() for c in password) # 大写字母
|
||||
@@ -86,8 +111,8 @@ class SecurityUtils:
|
||||
# 统计满足的字符类型数量
|
||||
char_types = sum([has_upper, has_lower, has_digit, has_special])
|
||||
|
||||
if char_types < 3:
|
||||
return False, "密码必须包含大写字母、小写字母、数字、特殊符号中的至少3种"
|
||||
if char_types < min_types:
|
||||
return False, f"密码必须包含大写字母、小写字母、数字、特殊符号中的至少{min_types}种"
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
@@ -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))
|
||||
+31
-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)
|
||||
|
||||
- 选择学生和学期,查看该学生的基础分、加分合计、减分合计
|
||||
- 查看月度操行分(月初分/加分/减分/月末分)及每月加减分理由汇总
|
||||
- 可撤销/反撤销该学生的记录,可导出个人记录
|
||||
|
||||
---
|
||||
|
||||
### 学习委员
|
||||
@@ -62,6 +70,11 @@
|
||||
|
||||
> 扣分限制:每次加减分不超过3分。
|
||||
|
||||
**按次登记**(一次登记覆盖多次作业):
|
||||
1. 先勾选缺交学生,点击"按次登记"
|
||||
2. 选择科目、总提交次数,填写每位缺交学生的缺交次数
|
||||
3. 系统按 缺交次数 × 单次缺交扣分 自动生成扣分记录(受单次扣分上限限制)
|
||||
|
||||
#### 操行分管理 (conduct.php)
|
||||
|
||||
**加减分操作**:
|
||||
@@ -97,6 +110,8 @@
|
||||
5. 在学生方格中**点击选择**有考勤异常的学生
|
||||
6. 点击"提交考勤"批量提交
|
||||
|
||||
> 考勤页还提供"默认出勤"(按日期范围批量补出勤,自动跳过周末/节假日)与"节假日/补课"校历设置,考勤委员可一并使用。
|
||||
|
||||
**默认扣分规则**:
|
||||
|
||||
| 考勤状态 | 默认扣分 |
|
||||
@@ -121,7 +136,7 @@
|
||||
3. 以卫生值日为由进行 ±1 分操作
|
||||
4. 点击"确认提交"
|
||||
|
||||
> 限制:固定 ±1 分。
|
||||
> 限制:默认固定 ±1 分,可由班主任在权限组中调整。
|
||||
|
||||
#### 历史记录
|
||||
|
||||
@@ -139,12 +154,17 @@
|
||||
3. 以服务时长为由进行加分
|
||||
4. 点击"确认提交"
|
||||
|
||||
> 限制:仅限加分操作。
|
||||
> 限制:默认仅限加分,可由班主任在权限组中调整。
|
||||
|
||||
#### 历史记录
|
||||
|
||||
- 仅可查看自己提交的操作记录
|
||||
|
||||
#### 个人查询 (record_query.php)
|
||||
|
||||
- 选择学生和学期,查看该学生的基础分、加分、月度分及月度理由汇总
|
||||
- 可导出个人记录
|
||||
|
||||
---
|
||||
|
||||
## 修改密码 (password.php)
|
||||
|
||||
+13
-7
@@ -14,27 +14,32 @@
|
||||
|
||||
## 角色权限
|
||||
|
||||
| 角色 | 操行分管理 | 历史记录 | 作业扣分 | 考勤管理 | 科目管理 |
|
||||
|------|-----------|---------|---------|---------|---------|
|
||||
| 班长 | ±5分以内 | 全部(可撤销) | - | - | - |
|
||||
| 学习委员 | ±5分以内 | 自己的 | ✓ | - | ✓ |
|
||||
| 考勤委员 | - | 自己的 | - | ✓ | - |
|
||||
| 劳动委员 | ±1分(卫生值日) | 自己的 | - | - | - |
|
||||
| 志愿委员 | 仅加分 | 自己的 | - | - | - |
|
||||
> 功能权限与加减分上限由班主任在「管理员管理 → 权限组」中配置;下表为预置权限组的默认值。
|
||||
|
||||
| 角色 | 操行分管理 | 历史记录 | 个人查询 | 作业扣分 | 考勤管理 | 科目管理 |
|
||||
|------|-----------|---------|---------|---------|---------|---------|
|
||||
| 班长 | ±5分以内 | 全部(可撤销) | 可查全班 | - | - | - |
|
||||
| 学习委员 | ±5分以内 | 自己的 | - | ✓ | - | ✓ |
|
||||
| 考勤委员 | - | 自己的 | - | - | ✓ | - |
|
||||
| 劳动委员 | ±1分(卫生值日) | 自己的 | - | - | - | - |
|
||||
| 志愿委员 | 仅加分 | 自己的 | 可查全班 | - | - | - |
|
||||
|
||||
## 常用操作
|
||||
|
||||
### 班长
|
||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值(±5分以内)和原因
|
||||
- **撤销记录**:历史记录页 → 点击撤销按钮
|
||||
- **个人查询**:个人查询页 → 选择学生 → 查看基础分/加分/月度分及理由汇总
|
||||
|
||||
### 学习委员
|
||||
- **作业扣分**:勾选学生 → 批量加减分 → 选择未交/迟交/自定义 → 填写原因
|
||||
- **按次登记**:勾选缺交学生 → 按次登记 → 填总提交次数与每人缺交次数 → 自动按次数扣分
|
||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值(±5分以内)和原因
|
||||
- **科目管理**:添加/编辑/删除科目
|
||||
|
||||
### 考勤委员
|
||||
- **添加考勤**:选择日期和时段(早上7:15/中午14:00/晚修19:30)→ 选择状态 → 点击选择异常学生 → 提交考勤
|
||||
- **默认出勤**:点「默认出勤」选日期范围批量补出勤(自动跳过周末/节假日);「节假日/补课」可查看与手动添加校历
|
||||
- 默认扣分:缺勤3分、迟到1分、请假0分
|
||||
|
||||
### 劳动委员
|
||||
@@ -42,6 +47,7 @@
|
||||
|
||||
### 志愿委员
|
||||
- **加分**:以服务时长为由进行加分操作
|
||||
- **个人查询**:个人查询页 → 选择学生 → 查看基础分/加分/月度分及理由汇总
|
||||
|
||||
## 常见问题
|
||||
|
||||
|
||||
+25
-10
@@ -20,26 +20,41 @@
|
||||
|------|------|
|
||||
| 首页 | 查看学生总数、排行榜、快捷入口 |
|
||||
| 操行分管理 | 对学生加减分(无限制)、导出德育分记录 |
|
||||
| 历史记录 | 查看/导出/撤销全班记录,支持按扣分类型筛选 |
|
||||
| 作业扣分 | 发布缺交作业记录、关联扣分 |
|
||||
| 考勤管理 | 按时段(早上/中午/晚修)记录考勤、自定义扣分值 |
|
||||
| 历史记录 | 查看/导出/撤销全班记录,支持按学期/扣分类型筛选 |
|
||||
| 个人查询 | 按学生查询基础分、加分、月度分、月度理由汇总及明细,可导出 |
|
||||
| 作业扣分 | 勾选学生批量加减分;按次登记(总提交次数 + 每人缺交次数自动扣分,写入作业统计) |
|
||||
| 考勤管理 | 按时段(早上/中午/晚修)记录考勤、自定义扣分值;默认出勤批量补全(跳过节假日)、节假日/补课设置 |
|
||||
| 学生管理 | 新增/编辑/删除/批量导入学生 |
|
||||
| 科目管理 | 增删改科目信息 |
|
||||
| 管理员管理 | 添加/编辑姓名和角色/删除/重置密码班干部账号 |
|
||||
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数 |
|
||||
| 管理员管理 | 添加/编辑姓名和权限组/禁用启用/重置密码/管理自定义权限组与加减分上限 |
|
||||
| 操作日志 | 查询关键操作记录(类型/操作人/日期筛选) |
|
||||
| 数据报表 | 考勤/作业统计(按日期范围,支持导出) |
|
||||
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数、归档环比 |
|
||||
| 系统设置 | 配置密码策略(长度与字符种类) |
|
||||
| 修改密码 | 修改登录密码 |
|
||||
|
||||
## 常用操作
|
||||
|
||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值和原因
|
||||
- **导出德育分**:操行分管理页 → 导出德育分记录(CSV)
|
||||
- **导出历史记录**:历史记录页 → 导出历史记录(CSV,可按日期/学生筛选)
|
||||
- **撤销记录**:历史记录页 → 点击撤销按钮
|
||||
- **作业按次登记**:作业扣分页 → 勾选缺交学生 → 按次登记 → 填总提交次数与每人缺交次数 → 确认登记
|
||||
- **导出德育分**:操行分管理页 → 导出德育分记录 → 选择学期(默认当前学期)
|
||||
- **导出历史记录**:历史记录页 → 导出(CSV,可按学期/日期/学生筛选,导出全部匹配记录)
|
||||
- **个人查询**:个人查询页 → 选择学生和学期 → 查询基础分/加分/月度分/理由汇总,点击学生姓名可直接进入
|
||||
- **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮
|
||||
- **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`)
|
||||
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息和角色
|
||||
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组
|
||||
- **绑定邮箱/找回密码**:修改密码页 → 输入新邮箱 → 发送验证码 → 输入验证码确认绑定(无需密码);忘记密码时在登录页点击"忘记密码?"通过邮箱获取一次性重置链接
|
||||
- **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码
|
||||
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
||||
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
||||
- **学期管理**:学期管理页 → 创建学期(可快捷填充日期)→ 关联历史数据 → 归档(可选重置分数)
|
||||
- **排行榜筛选**:首页 → 输入百分比 → 点击筛选(抹零法,如15%显示前15%的学生)
|
||||
- **排行榜筛选/导出**:首页 → 选择"总分排行/月度分排行"(月度可选月份)→ 输入百分比筛选,或点「导出」下载CSV
|
||||
- **默认出勤**:考勤管理 → 点「默认出勤」→ 选日期范围与时段 → 开始补全(自动跳过周末/节假日)
|
||||
- **校历设置**:考勤管理 → 点「节假日/补课」→ 查看接口节假日/调休,手动添加放假或补课日
|
||||
- **数据报表**:数据报表页 → 选择日期范围 → 查询考勤/作业统计 → 各表右上角导出CSV
|
||||
- **操作日志**:操作日志页 → 选择类型/操作人/日期 → 查询
|
||||
- **密码策略**:系统设置页 → 修改长度与字符种类 → 保存(全站即时生效)
|
||||
- **归档对比**:学期管理 → 已归档学期「查看归档」→ 查看与上一学期的分数/名次环比
|
||||
|
||||
## 常见问题
|
||||
|
||||
|
||||
+219
-30
@@ -8,6 +8,8 @@
|
||||
4. 首次登录系统会强制要求修改密码
|
||||
|
||||
> **密码要求**:长度6-20位,必须包含大写字母、小写字母、数字、特殊符号中的至少3种。
|
||||
>
|
||||
> **忘记密码**:已绑定邮箱的管理员可点击登录页"忘记密码?",输入用户名后系统会向绑定邮箱发送重置链接(30分钟内有效、仅可使用一次)。未绑定邮箱请联系班主任处理。
|
||||
|
||||
---
|
||||
|
||||
@@ -24,7 +26,10 @@
|
||||
- 操行分管理
|
||||
- 导入学生
|
||||
- 导出德育分记录
|
||||
- **操行分排行榜**:展示前100名学生的排名、学号、姓名和操行分。排行榜上方提供百分比筛选框,可输入1-100的数字筛选显示前N%的学生(抹零法:如49人×15%=7.35,显示前7人)。
|
||||
- **操行分排行榜**:支持两种排行方式:
|
||||
- **总分排行**:按当前操行分排名(展示前100名)
|
||||
- **月度分排行**:选择月份后按当月净得分排名(月度分 = 当月加分 - 当月减分,与基础分无关),同时展示当月加分/减分
|
||||
- 排行榜上方提供百分比筛选框(抹零法),并支持「导出」按钮将当前排行导出为CSV
|
||||
|
||||
---
|
||||
|
||||
@@ -42,13 +47,16 @@
|
||||
- **原因**:填写加减分原因(必填)
|
||||
4. 点击"确认提交"
|
||||
|
||||
> 班主任加减分无限制。
|
||||
> 加减分上限按当前账号所属权限组动态校验(允许加分/加分上限/允许扣分/扣分上限),班主任组默认无限制。弹窗中会显示本账号的具体上限。
|
||||
|
||||
#### 导出德育分记录
|
||||
1. 点击"导出德育分记录"按钮
|
||||
2. 系统自动生成CSV文件并下载
|
||||
3. 文件格式:`学号,姓名,分数,加分历史,减分记录`
|
||||
4. 历史记录以分号分隔,包含原因和分值
|
||||
2. 在弹窗中选择**学期范围**(默认当前学期,可选择某个历史学期或全部学期)
|
||||
3. 系统自动生成CSV文件并下载
|
||||
4. 文件格式:`学号,姓名,学期,基础分,加分合计,减分合计,学期得分,当前总分,加分历史,减分记录`
|
||||
5. 历史记录以分号分隔,包含原因和分值;已撤销记录不会导出
|
||||
|
||||
> 默认只导出当前学期数据,学期迭代归档后不会混入以往学期的记录。
|
||||
|
||||
---
|
||||
|
||||
@@ -57,6 +65,7 @@
|
||||
#### 查看历史记录
|
||||
- 展示所有操行分变动记录
|
||||
- 支持筛选条件:
|
||||
- **学期**:默认当前学期,可切换历史学期或全部学期
|
||||
- **开始日期** / **结束日期**:按时间范围筛选
|
||||
- **学生**:按学生筛选
|
||||
- **扣分类型**:按来源筛选(手动加减分 / 作业 / 考勤)
|
||||
@@ -65,14 +74,27 @@
|
||||
|
||||
#### 导出历史记录
|
||||
1. 设置筛选条件(可选)
|
||||
2. 点击"导出历史记录"按钮
|
||||
3. 系统自动生成CSV文件并下载
|
||||
4. 文件格式:`时间,学号,姓名,分数变动,原因,操作人`
|
||||
2. 点击"导出"按钮,在弹窗中选择导出方式:
|
||||
- **明细记录**:每行一条记录(默认)
|
||||
- **按学生分表**:每个学生一段,包含加分/减分合计与明细,便于发给家长
|
||||
3. 系统自动生成CSV文件并下载(导出全部匹配记录,不受分页限制)
|
||||
4. 明细导出格式:`时间,学号,姓名,学期,类型,分数变动,原因,操作人`
|
||||
|
||||
#### 撤销记录
|
||||
1. 在历史记录列表中找到目标记录
|
||||
2. 点击右侧"撤销"按钮
|
||||
3. 确认撤销操作
|
||||
4. 撤销后记录会移入"已撤销"(状态筛选选"已撤销"可查看并反撤销),学生分数自动恢复
|
||||
|
||||
#### 批量撤销 / 批量反撤销(批次合并视图)
|
||||
1. 勾选"批次合并"后,同一批次的记录会合并为一行
|
||||
2. 点击该行的"批量撤销"可一次撤销整批记录
|
||||
3. 查看"已撤销"状态的批次时,点击"批量反撤销"可一次恢复整批记录
|
||||
4. 撤销/反撤销操作均会写入操作日志(批量操作记录条数与记录ID)
|
||||
|
||||
#### 反撤销(恢复记录)
|
||||
1. 状态筛选选择"已撤销",找到被撤销的记录
|
||||
2. 点击"反撤销"按钮,确认后分数变动重新生效
|
||||
|
||||
---
|
||||
|
||||
@@ -97,6 +119,26 @@
|
||||
|
||||
> 扣分限制:每次加减分不超过3分。
|
||||
|
||||
#### 作业按次登记
|
||||
用于"一次登记覆盖多次作业":先勾选缺交学生,再填写每人缺交次数,系统按 `缺交次数 × 单次缺交扣分` 自动扣分,并写入作业提交数据供"数据报表-作业统计"使用。
|
||||
|
||||
1. 在学生列表中勾选**缺交的学生**
|
||||
2. 点击"按次登记"按钮
|
||||
3. 填写:
|
||||
- **科目**(必选,作业记录归属科目)
|
||||
- **作业名称**(选填,如:第5周数学作业)
|
||||
- **缴交/截止日期**(作业统计按该日期归属)
|
||||
- **总提交次数**(本次登记覆盖几次作业,默认5次)
|
||||
- **单次缺交扣分**(默认取系统配置,可临时调整)
|
||||
- **每位缺交学生的缺交次数**(1 ~ 总提交次数)
|
||||
- 备注(选填)
|
||||
4. 点击"确认登记"
|
||||
|
||||
规则说明:
|
||||
- 未勾选的其他学生自动记为**已交**;缺交学生缺 k 次则记为 k 次未交、其余已交
|
||||
- 扣分生成一条记录(原因如:`[数学]第5周数学作业 缺交 2/5 次`),超过权限组单次扣分上限会被拦截
|
||||
- 与"批量加减分"的区别:批量加减分是所有人同一分值;按次登记是每人按缺交次数自动计算分值
|
||||
|
||||
---
|
||||
|
||||
### 5. 考勤管理 (attendance.php)
|
||||
@@ -120,9 +162,44 @@
|
||||
6. 点击"全选"可快速选中所有未记录的学生
|
||||
7. 点击"提交考勤"批量提交
|
||||
|
||||
#### 请假(整天)
|
||||
按学生**当天实际考勤时段**一键请假(不再固定 3 条):
|
||||
|
||||
1. 在学生方格中**点击选择**请假的学生
|
||||
2. 点击工具栏"请假(整天)"按钮,系统按当天作息提交:
|
||||
- 正常上课日(次日仍上课)→ **早/中/晚 3 条**
|
||||
- 放假前一天(半天)→ **仅上午 1 条**
|
||||
- 返校日晚修 → **晚修 1 条**
|
||||
3. 每个时段按"请假"配置扣分(如 1 分/次:半天 1 分、正常日 3 分)
|
||||
|
||||
> 已有的对应时段记录会被更新为请假;如需只标记某个时段,仍用普通"请假"按钮 + 时段选择。
|
||||
|
||||
#### 查看考勤记录
|
||||
- 按日期筛选考勤记录
|
||||
- 每条记录显示:学号、姓名、状态、原因、记录人、扣分情况
|
||||
- 每条记录显示:学号、姓名、状态、原因、记录人、扣分金额(如"扣3分",已撤销的注明)
|
||||
|
||||
#### 默认出勤(批量补全)
|
||||
用于给一段时间内没有异常的学生批量补"出勤"记录,让统计报表的出勤率有意义。
|
||||
|
||||
1. 点击工具栏"默认出勤"按钮
|
||||
2. 选择**日期范围**(默认本月1日至今)与**时段**(默认全选早/中/晚)
|
||||
3. 点击"开始补全",完成后提示:上课日/节前半日/返校晚修数量、新增条数、跳过已有条数
|
||||
|
||||
作息规则(常规情况):
|
||||
- **返校日**(非上课日、次日上课,如周日)→ 仅生成**晚修**出勤
|
||||
- **上课日且次日仍上课** → 按所选时段生成(早/中/晚)
|
||||
- **放假前一天**(上课日、次日不上课)→ 仅生成**上午**出勤(中午离校,无下午/晚修);少数需要下午上课的,按正常流程单独补录下午记录即可
|
||||
- **跳过周末与法定节假日**(节假日/调休补班来自国内在线接口,失败时自动切换备用接口)
|
||||
- **调休补班日照常**(接口中的补班日按上课处理);**手动补课日照常**、手动放假日跳过
|
||||
- 已有的考勤记录(含缺勤/迟到/请假)**不会被覆盖**
|
||||
- 单次最长支持 180 天;接口暂时不可用时会提示,本次仅按周末与手动设置判断
|
||||
|
||||
#### 节假日 / 补课设置
|
||||
点击工具栏"节假日/补课"按钮打开校历设置:
|
||||
|
||||
- **查询范围**:查看范围内的法定节假日(放假)、调休补班(按上课)——来自国内在线接口(失败时自动切换备用接口),只读
|
||||
- **手动添加**:添加学校自己的安排,可选择「补课(按上课)」或「放假(按休息)」,可填写备注;手动设置**优先于接口**(例如把某天调休补班改回放假)
|
||||
- 手动添加的记录可随时删除
|
||||
|
||||
**默认扣分规则**:
|
||||
|
||||
@@ -130,7 +207,7 @@
|
||||
|---------|---------|
|
||||
| 缺勤 | 3分 |
|
||||
| 迟到 | 1分 |
|
||||
| 请假 | 0分 |
|
||||
| 请假 | 按系统配置(如配置为1分,整天请假=3分) |
|
||||
|
||||
---
|
||||
|
||||
@@ -153,23 +230,33 @@
|
||||
4. 系统自动解析并导入
|
||||
5. 导入结果展示成功/失败数量
|
||||
|
||||
> 导入的学生初始操行分为60分,系统自动创建学生登录账号和密码。
|
||||
> 导入的学生初始操行分为系统配置的初始分(默认60分),系统自动创建学生登录账号和密码。
|
||||
|
||||
#### 导出学生名单
|
||||
1. 点击"导出学生名单"按钮
|
||||
2. 在弹窗中勾选需要导出的字段(学号、姓名必选;宿舍号、当前操行分、家长手机号、状态可选)
|
||||
3. 点击"开始导出",生成CSV文件
|
||||
4. 文件名:`学生名单_日期.csv`
|
||||
|
||||
---
|
||||
|
||||
### 7. 科目管理 (subjects.php)
|
||||
### 7. 科目管理(作业扣分页内)
|
||||
|
||||
科目管理已合并到"作业扣分"页面顶部的折叠面板中。
|
||||
|
||||
#### 查看科目列表
|
||||
- 展示所有科目及其状态
|
||||
- 展示所有科目的名称、代码、状态与排序序号
|
||||
- 代码为空时不显示占位
|
||||
|
||||
#### 添加科目
|
||||
1. 点击"添加科目"按钮
|
||||
2. 填写科目名称
|
||||
3. 可选填科目编码和排序
|
||||
1. 展开"科目管理"面板,点击"添加科目"
|
||||
2. 填写科目名称(必填)
|
||||
3. 可选填科目代码(最多50字符,用于标识,如 CHI)
|
||||
4. 点击"确认"
|
||||
|
||||
#### 管理科目
|
||||
- 编辑:修改科目信息
|
||||
- 编辑:修改名称、代码、排序序号(**代码留空可清空**)
|
||||
- 排序:点击科目右侧的 ↑ / ↓ 按钮快速调整顺序
|
||||
- 删除:删除科目(已有作业关联的科目不可删除)
|
||||
- 启用/禁用:控制科目状态
|
||||
|
||||
@@ -183,20 +270,50 @@
|
||||
- **用户名**:登录账号
|
||||
- **姓名**:真实姓名
|
||||
- **密码**:留空则自动生成8位随机密码
|
||||
- **角色**:选择角色类型
|
||||
- **绑定邮箱**:选填,绑定后该管理员可自助找回密码
|
||||
- **权限组**:选择该账号所属权限组
|
||||
3. 点击"添加"
|
||||
4. 添加成功后会显示管理员信息和初始密码(请妥善保存)
|
||||
|
||||
#### 编辑管理员
|
||||
- 点击"编辑"按钮可修改**姓名**和**角色类型**
|
||||
- 点击"编辑"按钮可修改**姓名**、**绑定邮箱**和**权限组**(邮箱留空表示解除绑定)
|
||||
- 编辑自己的账号时:姓名和邮箱可正常修改,**权限组不可修改**(防止把自己锁死;如需调整自己的权限,直接编辑所属权限组本身)
|
||||
|
||||
#### 重置密码
|
||||
1. 点击"重置密码"按钮
|
||||
2. 输入新密码
|
||||
3. 点击"确认重置"
|
||||
4. 重置后该账号**下次登录需重新设置密码**(弹窗设置,无需输入原密码)
|
||||
|
||||
#### 删除管理员
|
||||
- 点击"删除"按钮确认删除(不可恢复)
|
||||
#### 禁用/启用管理员
|
||||
- 点击"禁用/启用"切换账号状态,禁用后无法登录
|
||||
- 不能禁用当前登录的账号
|
||||
|
||||
#### 邮件测试
|
||||
- 点击页面上方"邮件测试"按钮,输入接收邮箱,可验证 SMTP 配置是否可用
|
||||
- 发送失败时会显示具体错误(如授权码错误、连接超时等),便于排查配置
|
||||
|
||||
#### 权限组管理
|
||||
页面下方为权限组列表,可查看每个组的权限项、加减分上限、成员数与说明。
|
||||
|
||||
**新建权限组**:
|
||||
1. 点击"新建权限组"
|
||||
2. 填写权限组名称(如"纪律委员")和说明
|
||||
3. 勾选功能权限(学生管理、导出学生名单、操行分加减、撤销记录、反撤销、作业扣分、作业按次登记、考勤管理、考勤默认出勤、节假日/补课设置、科目管理、查看全班/个人查询、数据报表查看、数据导出、操作日志查看、系统设置、管理员管理、学期管理、系统升级等)
|
||||
4. 设置加减分上限:
|
||||
- **允许加分** + **单次加分上限**(留空为无限制)
|
||||
- **允许扣分** + **单次扣分上限**(留空为无限制)
|
||||
5. 点击"保存"
|
||||
|
||||
**编辑权限组**:
|
||||
- 点击任意权限组的"编辑"可随时调整权限与上限(含预置组)
|
||||
- 权限项按"学生 / 操行分 / 教务 / 系统管理"分组展示,支持一键全选/清空
|
||||
- 预置组默认:学习委员含"作业按次登记",考勤委员含"考勤默认出勤",班长/志愿委员含"数据报表查看";"节假日/补课设置""操作日志查看""系统设置"默认仅班主任(均可在编辑中调整)
|
||||
|
||||
**删除权限组**:
|
||||
- 任何权限组均可删除;组内仍有管理员时需先把成员调整到其他组
|
||||
|
||||
> 权限组调整后,相关管理员刷新页面或最多60秒后自动生效。
|
||||
|
||||
---
|
||||
|
||||
@@ -249,24 +366,87 @@
|
||||
#### 查看归档数据
|
||||
- 已归档学期显示"查看归档"按钮
|
||||
- 展示归档时的学生排名、操行分、考勤统计、作业统计
|
||||
- **环比上次**:同时展示与上一个已归档学期的「分数变化」(+/-)与「排名变化」(↑进步 / ↓退步)
|
||||
|
||||
---
|
||||
|
||||
### 10. 修改密码 (password.php)
|
||||
### 10. 个人查询 (record_query.php)
|
||||
|
||||
用于快速查询单个学生的完整操行分情况。
|
||||
|
||||
#### 查询方式
|
||||
1. 选择**学生**
|
||||
2. 选择**学期**(默认当前学期,可选历史学期或全部学期)
|
||||
3. 点击"查询"
|
||||
|
||||
也可在"学生管理"或"操行分管理"页面点击学生姓名直接跳转到该学生的查询页。
|
||||
|
||||
#### 查询内容
|
||||
- **汇总卡片**:基础分、加分合计、减分合计、总分(基础分 + 加分 - 减分)、当前实时总分
|
||||
- **月度操行分**:月份、加分、减分、月度分(当月净得分,与基础分无关)、记录数
|
||||
- **月度加减分理由汇总**:按月份分别列出加分理由、减分理由(含次数与合计分值)
|
||||
- **明细记录**:该学生的所有操行分记录(分页),班主任/班长可直接撤销或反撤销
|
||||
|
||||
> 月度分是每个月独立的加/减分净得分;基础分只参与总分的计算。
|
||||
|
||||
#### 导出个人记录
|
||||
点击"导出个人记录"按钮,生成包含汇总信息与全部明细的CSV文件(受当前学生/学期筛选影响)。
|
||||
|
||||
---
|
||||
|
||||
### 11. 修改密码 (password.php)
|
||||
|
||||
- 输入原密码和新密码
|
||||
- 新密码需符合密码强度要求
|
||||
- 新密码需符合密码强度要求(密码策略可在「系统设置」中调整)
|
||||
- 修改成功后需重新登录
|
||||
- **密码待修改时(首次使用或被管理员重置后)**:登录时会弹窗要求设置新密码(**无需输入原密码**);日常主动改密仍需原密码
|
||||
- 页面下方可**绑定邮箱**(找回密码用):
|
||||
1. 输入新邮箱,点击"发送验证码"(无需密码)
|
||||
2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效)
|
||||
3. 输入验证码后点击"确认绑定"
|
||||
4. 输入当前密码后点击"解除绑定"可解除已绑定邮箱
|
||||
- 管理员管理页添加/编辑账号时也可由班主任直接填写绑定邮箱
|
||||
|
||||
---
|
||||
|
||||
### 12. 数据报表 (reports.php)
|
||||
|
||||
用于按日期范围统计全班考勤与作业情况。
|
||||
|
||||
- 选择**开始日期 / 结束日期**(默认当前学期至今),点击"查询"
|
||||
- **考勤统计**:每人出勤/缺勤/迟到/请假次数、记录数、出勤率,按缺勤与迟到降序排列
|
||||
- **作业统计**:每人已交/未交/迟交次数、记录数、未交率,按未交与迟交降序排列
|
||||
- 各表右上角「导出」按钮可导出对应CSV
|
||||
|
||||
> 作业统计按作业截止日期归属;考勤按考勤记录日期归属。
|
||||
|
||||
---
|
||||
|
||||
### 13. 操作日志 (logs.php)
|
||||
|
||||
用于审计管理端所有关键操作。
|
||||
|
||||
- 支持按**操作类型**、**操作人/角色关键词**、**详情关键词**(学生姓名/记录原因等)、**日期范围**筛选
|
||||
- 分页展示:时间、操作人、角色、操作类型、对象、详情、IP
|
||||
- 操行分相关日志详情包含:学生姓名(学号)、分值变动、原因、原操作人;批量撤销/反撤销会记录条数与记录ID
|
||||
|
||||
---
|
||||
|
||||
### 14. 系统设置 (settings.php)
|
||||
|
||||
- **密码策略**:配置密码最小长度、最大长度、最少字符种类数(大写/小写/数字/特殊符号)
|
||||
- 保存后立即生效:修改密码、重置密码、邮箱重置等所有入口统一按该策略校验,前端提示同步更新
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 忘记密码怎么办?
|
||||
请联系系统管理员通过调试接口重置。
|
||||
1. 已绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送**一次性重置链接**(30分钟内有效、仅可使用一次);
|
||||
2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。
|
||||
|
||||
### Q: 如何导出全班德育分记录?
|
||||
在"操行分管理"页面点击"导出德育分记录"按钮,系统会生成包含所有学生当前分数及加减分历史的CSV文件。
|
||||
在"操行分管理"页面点击"导出德育分记录"按钮,在弹窗中选择学期范围(默认当前学期),系统会生成包含所选学期内所有学生基础分、加/减分合计及加减分历史的CSV文件。
|
||||
|
||||
### Q: 如何撤销错误的加减分?
|
||||
在"历史记录"页面找到对应记录,点击"撤销"按钮。
|
||||
@@ -284,12 +464,21 @@
|
||||
### 德育分记录导出
|
||||
- **位置**:操行分管理页面
|
||||
- **格式**:CSV(UTF-8编码)
|
||||
- **字段**:学号、姓名、分数、加分历史、减分记录
|
||||
- **文件名**:`德育分记录_日期.csv`
|
||||
- **学期范围**:默认当前学期,可选历史学期或全部学期
|
||||
- **字段**:学号、姓名、学期、基础分、加分合计、减分合计、学期得分、当前总分、加分历史、减分记录
|
||||
- **说明**:已撤销记录不导出;全部学期导出时按"学生+学期"分行
|
||||
- **文件名**:`德育分记录_学期_日期.csv`
|
||||
|
||||
### 历史记录导出
|
||||
- **位置**:历史记录页面
|
||||
- **格式**:CSV(UTF-8编码)
|
||||
- **字段**:时间、学号、姓名、分数变动、原因、操作人
|
||||
- **支持筛选**:可按时间范围和学生筛选后导出
|
||||
- **文件名**:`历史记录_日期.csv`
|
||||
- **字段**:时间、学号、姓名、学期、类型、分数变动、原因、操作人
|
||||
- **支持筛选**:可按学期、时间范围、学生、类型、原因关键词筛选后导出
|
||||
- **说明**:导出全部匹配记录(不受分页限制),已撤销记录不导出
|
||||
- **文件名**:`历史记录_学期_日期.csv`
|
||||
|
||||
### 个人记录导出
|
||||
- **位置**:个人查询页面
|
||||
- **格式**:CSV(UTF-8编码)
|
||||
- **内容**:学生汇总(基础分、加分合计、减分合计、得分、当前总分)+ 全部明细记录
|
||||
- **文件名**:`个人记录_姓名_学期_日期.csv`
|
||||
@@ -24,12 +24,8 @@ USER_STORAGE_KEY=class_system_user
|
||||
# 站点名称
|
||||
SITE_NAME=班级操行分管理系统
|
||||
|
||||
# 会话超时时间(分钟)
|
||||
SESSION_TIMEOUT=30
|
||||
|
||||
# ICP备案号配置
|
||||
# 是否启用ICP备案号显示 - true/false
|
||||
ICP_ENABLED=false
|
||||
# ICP备案号
|
||||
ICP_NUMBER=京ICP备1234567890号-x
|
||||
STUDENT_INITIAL_POINTS=60
|
||||
+104
-28
@@ -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';
|
||||
@@ -32,17 +29,36 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="action-bar">
|
||||
<button class="btn btn-primary" onclick="showAddAdminModal()">添加管理员</button>
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-primary" onclick="showAddAdminModal()">添加管理员</button>
|
||||
<button class="btn btn-secondary" onclick="testSmtpEmail()">邮件测试</button>
|
||||
</div>
|
||||
</div>
|
||||
<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">
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-primary" onclick="showAddGroupModal()">新建权限组</button>
|
||||
</div>
|
||||
</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 +77,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,15 +119,15 @@ 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>
|
||||
<small id="editAdminGroupHint" style="display:none;">当前登录账号的权限组不可修改(可编辑权限组本身来调整)</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">保存</button>
|
||||
@@ -121,6 +137,65 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 权限组模态框 -->
|
||||
<div id="groupModal" class="modal">
|
||||
<div class="modal-content" style="width: 760px; max-width: 92%;">
|
||||
<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 style="display:flex; gap:12px; flex-wrap:wrap;">
|
||||
<div class="form-group" style="flex:1; min-width:220px;">
|
||||
<label>权限组名称 <span style="color:red;">*</span></label>
|
||||
<input type="text" id="groupName" required maxlength="50" placeholder="如:纪律委员">
|
||||
</div>
|
||||
<div class="form-group" style="flex:2; min-width:260px;">
|
||||
<label>说明</label>
|
||||
<input type="text" id="groupDescription" maxlength="255" placeholder="选填">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div class="perm-header">
|
||||
<label style="margin:0;">权限项</label>
|
||||
<div>
|
||||
<button type="button" class="btn btn-sm btn-ghost" onclick="selectAllPermissions(true)">全选</button>
|
||||
<button type="button" class="btn btn-sm btn-ghost" onclick="selectAllPermissions(false)">清空</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="groupPermissionList"></div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>加减分上限</label>
|
||||
<div class="perm-cap-row">
|
||||
<label class="check-item">
|
||||
<input type="checkbox" id="groupCanAdd" checked onchange="onGroupCapChange()"> 允许加分
|
||||
</label>
|
||||
<label class="check-item">
|
||||
单次加分上限
|
||||
<input type="number" id="groupMaxAdd" min="1" max="100" style="width:100px;" placeholder="留空=不限">
|
||||
</label>
|
||||
</div>
|
||||
<div class="perm-cap-row">
|
||||
<label class="check-item">
|
||||
<input type="checkbox" id="groupCanSubtract" checked onchange="onGroupCapChange()"> 允许扣分
|
||||
</label>
|
||||
<label class="check-item">
|
||||
单次扣分上限
|
||||
<input type="number" id="groupMaxSubtract" min="1" max="100" style="width:100px;" 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">
|
||||
@@ -136,8 +211,8 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="text" id="newPassword" required minlength="6" placeholder="请输入新密码(至少6位)">
|
||||
<small>密码长度至少6位</small>
|
||||
<input type="text" id="newPassword" required placeholder="请输入新密码">
|
||||
<small class="pwd-policy">密码长度至少6位</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">确认重置</button>
|
||||
@@ -147,8 +222,9 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
||||
<script src="/assets/js/modules/admin-mgmt.js"></script>
|
||||
<script src="/assets/js/admins.js"></script>
|
||||
<script>window.PAGE_CONFIG = { userId: <?php echo intval($_SESSION['user_id']); ?> };</script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/admin-mgmt.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/admins.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -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';
|
||||
?>
|
||||
@@ -51,6 +47,13 @@ include __DIR__ . '/../includes/header.php';
|
||||
<button class="status-btn" data-status="late" onclick="selectStatus(this)" id="btnLate">迟到</button>
|
||||
<button class="status-btn" data-status="leave" onclick="selectStatus(this)" id="btnLeave">请假</button>
|
||||
</div>
|
||||
<?php if (has_perm('default_attendance')): ?>
|
||||
<button class="btn btn-success" onclick="openDefaultAttendanceModal()">默认出勤</button>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_calendar')): ?>
|
||||
<button class="btn btn-ghost" onclick="openCalendarModal()">节假日/补课</button>
|
||||
<?php endif; ?>
|
||||
<button class="btn btn-secondary" onclick="submitFullDayLeave()">请假(整天)</button>
|
||||
<button class="btn btn-danger" onclick="submitAttendance()">提交考勤</button>
|
||||
</div>
|
||||
<div class="attendance-toolbar">
|
||||
@@ -69,7 +72,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
|
||||
<!-- 学生方格网格 -->
|
||||
<div class="card">
|
||||
<div class="card-title">点击选择有考勤异常的学生</div>
|
||||
<div class="card-title">点击选择有考勤异常的学生(默认出勤记录也可选中覆盖为异常)</div>
|
||||
<div class="student-grid" id="studentGrid">
|
||||
<!-- JS 动态生成 -->
|
||||
</div>
|
||||
@@ -94,7 +97,75 @@ include __DIR__ . '/../includes/header.php';
|
||||
.student-cell-name { font-size: 14px; font-weight: 500; }
|
||||
.student-cell-no { font-size: 11px; color: #999; }
|
||||
</style>
|
||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
||||
<script src="/assets/js/attendance-manage.js"></script>
|
||||
|
||||
<!-- 默认出勤模态框 -->
|
||||
<div id="defaultAttendanceModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3>默认出勤(批量补全)</h3>
|
||||
<button class="modal-close" onclick="closeModal('defaultAttendanceModal')">×</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>日期范围</label>
|
||||
<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
|
||||
<input type="date" id="defaultStartDate" style="width:auto;">
|
||||
<span style="color:#999;">至</span>
|
||||
<input type="date" id="defaultEndDate" style="width:auto;">
|
||||
</div>
|
||||
<small>按学校常规作息生成:返校日晚修、放假前一天仅上午(中午离校)、其余上课日按所选时段;跳过周末与法定节假日(调休补课日照常),已有记录不覆盖</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>时段</label>
|
||||
<div class="check-grid" style="grid-template-columns: repeat(3, 1fr);">
|
||||
<label class="check-item"><input type="checkbox" class="defaultSlot" value="morning" checked> 早上 7:15</label>
|
||||
<label class="check-item"><input type="checkbox" class="defaultSlot" value="afternoon" checked> 中午 14:00</label>
|
||||
<label class="check-item"><input type="checkbox" class="defaultSlot" value="evening" checked> 晚修 19:30</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" id="defaultAttendanceBtn" onclick="submitDefaultAttendance()">开始补全</button>
|
||||
<button type="button" class="btn" onclick="closeModal('defaultAttendanceModal')">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 节假日/补课模态框 -->
|
||||
<div id="calendarModal" class="modal">
|
||||
<div class="modal-content" style="width: 640px;">
|
||||
<div class="modal-header">
|
||||
<h3>节假日 / 补课设置</h3>
|
||||
<button class="modal-close" onclick="closeModal('calendarModal')">×</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>查询范围</label>
|
||||
<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
|
||||
<input type="date" id="calendarStartDate" style="width:auto;">
|
||||
<span style="color:#999;">至</span>
|
||||
<input type="date" id="calendarEndDate" style="width:auto;">
|
||||
<button type="button" class="btn btn-sm btn-secondary" onclick="loadCalendar()">查询</button>
|
||||
</div>
|
||||
<small>法定节假日与调休补班来自在线接口(只读);手动添加用于学校自己的安排,优先于接口</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>手动添加</label>
|
||||
<div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
|
||||
<input type="date" id="calendarNewDate" style="width:auto;">
|
||||
<select id="calendarNewType" style="width:auto;">
|
||||
<option value="makeup">补课(按上课)</option>
|
||||
<option value="holiday">放假(按休息)</option>
|
||||
</select>
|
||||
<input type="text" id="calendarNewNote" placeholder="备注(选填)" maxlength="100" style="flex:1; min-width:120px;">
|
||||
<button type="button" class="btn btn-sm btn-primary" onclick="addCalendarDay()">添加</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="calendarListArea" style="max-height:320px; overflow-y:auto; border:1px solid var(--color-border-light); border-radius:8px;"></div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn" onclick="closeModal('calendarModal')">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/attendance-manage.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
+31
-23
@@ -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_conduct');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
@@ -34,10 +30,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,10 +57,10 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<script src="/assets/js/conduct.js"></script>
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/conduct.js'); ?>"></script>
|
||||
|
||||
<!-- 批量加减分模态框 -->
|
||||
<div id="batchPointsModal" class="modal">
|
||||
@@ -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">
|
||||
@@ -131,7 +139,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
<div class="form-group" id="dormitoryStudentsGroup" style="display:none;">
|
||||
<label>宿舍成员</label>
|
||||
<div id="dormitoryStudentsList" style="max-height: 150px; overflow-y: auto; border: 1px solid var(--border-color); border-radius: 4px; padding: 8px;">
|
||||
<div id="dormitoryStudentsList" style="max-height: 150px; overflow-y: auto; border: 1px solid var(--color-border); border-radius: 4px; padding: 8px;">
|
||||
</div>
|
||||
<small id="dormitoryStudentsCount"></small>
|
||||
</div>
|
||||
|
||||
@@ -35,16 +35,24 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="card">
|
||||
<div class="card-title">操行分排行榜</div>
|
||||
<div class="table-wrapper">
|
||||
<div style="display: flex; align-items: center; margin-bottom: 12px; gap: 8px;">
|
||||
<span style="font-size: 14px; color: #666;">显示前</span>
|
||||
<input type="number" id="percentileFilter" style="width: 70px; padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px;" min="1" max="100" value="100" placeholder="1-100">
|
||||
<span style="font-size: 14px; color: #666;">% 的学生</span>
|
||||
<div class="ranking-toolbar">
|
||||
<select id="rankingType" onchange="onRankingTypeChange()">
|
||||
<option value="total">总分排行</option>
|
||||
<option value="monthly">月度分排行</option>
|
||||
</select>
|
||||
<input type="month" id="rankingMonth" style="display:none;" onchange="loadRanking()">
|
||||
<span class="ranking-tip">显示前</span>
|
||||
<input type="number" id="percentileFilter" style="width: 70px;" min="1" max="100" value="100" placeholder="1-100">
|
||||
<span class="ranking-tip">% 的学生</span>
|
||||
<button class="btn btn-sm btn-primary" onclick="applyPercentileFilter()">筛选</button>
|
||||
<button class="btn btn-sm btn-ghost" onclick="resetPercentileFilter()">显示全部</button>
|
||||
<?php if (has_perm('export_data')): ?>
|
||||
<button class="btn btn-sm btn-secondary" onclick="exportRanking()">导出</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>排名</th><th>学号</th><th>姓名</th><th>操行分</th></tr>
|
||||
<tr id="rankingHead"><th>排名</th><th>学号</th><th>姓名</th><th>操行分</th></tr>
|
||||
</thead>
|
||||
<tbody id="rankingList"></tbody>
|
||||
</table>
|
||||
@@ -52,7 +60,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 +87,10 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</script>
|
||||
<script src="/assets/js/dashboard.js"></script>
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="<?php echo asset_url('/assets/js/dashboard.js'); ?>"></script>
|
||||
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<?php if (has_perm('manage_upgrade')): ?>
|
||||
<script>
|
||||
(function() {
|
||||
var upgradeSteps = [];
|
||||
|
||||
@@ -32,8 +32,14 @@ include __DIR__ . '/../includes/header.php';
|
||||
<label class="history-grouped-label">
|
||||
<input type="checkbox" id="historyGrouped" checked onchange="loadHistory(1)"> 批次合并
|
||||
</label>
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<button class="btn btn-secondary" onclick="exportHistoryRecords()">导出</button>
|
||||
<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="showExportHistoryModal()">导出</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') || has_perm('restore_records')): ?>
|
||||
<th>操作</th>
|
||||
<?php endif; ?>
|
||||
</tr>
|
||||
@@ -112,9 +118,34 @@ include __DIR__ . '/../includes/header.php';
|
||||
</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/modules/points-mgmt.js"></script>
|
||||
<script src="/assets/js/history.js"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/history.js'); ?>"></script>
|
||||
|
||||
<!-- 导出历史记录模态框 -->
|
||||
<div id="exportHistoryModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3>导出历史记录</h3>
|
||||
<button class="modal-close" onclick="closeModal('exportHistoryModal')">×</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>导出方式</label>
|
||||
<div class="check-grid" style="grid-template-columns: 1fr;">
|
||||
<label class="check-item">
|
||||
<input type="radio" name="historyExportMode" value="detail" checked> 明细记录(每行一条记录)
|
||||
</label>
|
||||
<label class="check-item">
|
||||
<input type="radio" name="historyExportMode" value="per_student"> 按学生分表(每人一段,便于发给家长)
|
||||
</label>
|
||||
</div>
|
||||
<small>导出内容跟随当前筛选条件;已撤销记录不导出</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" onclick="exportHistoryRecords()">开始导出</button>
|
||||
<button type="button" class="btn" onclick="closeModal('exportHistoryModal')">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
+79
-38
@@ -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,11 +41,15 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div id="subjectList" class="subject-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card">
|
||||
<div class="action-bar">
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-primary" onclick="showBatchPointsModal()">批量加减分</button>
|
||||
<?php if (has_perm('homework_register')): ?>
|
||||
<button class="btn btn-success" onclick="showHomeworkRegisterModal()">按次登记</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-wrapper">
|
||||
@@ -79,14 +80,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 +97,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 +105,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>
|
||||
@@ -128,6 +122,57 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 作业按次登记模态框 -->
|
||||
<div id="homeworkRegisterModal" class="modal">
|
||||
<div class="modal-content" style="width: 560px;">
|
||||
<div class="modal-header">
|
||||
<h3>作业按次登记</h3>
|
||||
<button class="modal-close" onclick="closeModal('homeworkRegisterModal')">×</button>
|
||||
</div>
|
||||
<form onsubmit="event.preventDefault(); submitHomeworkRegister()">
|
||||
<div class="form-group">
|
||||
<label>科目 <span class="text-danger">*</span></label>
|
||||
<select id="hwRegSubject" required>
|
||||
<option value="">请选择科目</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>作业名称</label>
|
||||
<input type="text" id="hwRegTitle" maxlength="100" placeholder="选填,如:第5周数学作业">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>缴交/截止日期</label>
|
||||
<input type="date" id="hwRegDeadline">
|
||||
<small>作业统计按该日期归属</small>
|
||||
</div>
|
||||
<div class="form-group" style="display:flex; gap:12px;">
|
||||
<div style="flex:1;">
|
||||
<label>总提交次数</label>
|
||||
<input type="number" id="hwRegTotal" min="1" max="99" value="5" required>
|
||||
</div>
|
||||
<div style="flex:1;">
|
||||
<label>单次缺交扣分</label>
|
||||
<input type="number" id="hwRegPerDeduction" min="1" max="20">
|
||||
<small>默认取系统配置</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>缺交学生与次数</label>
|
||||
<div id="hwRegStudentList" class="hw-reg-list"></div>
|
||||
<small>默认全部学生按已交处理;在列表中为缺交学生填写缺交次数(0 或留空 = 已交),缺交次数不超过总提交次数</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>备注</label>
|
||||
<input type="text" id="hwRegNote" maxlength="100" placeholder="选填">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary" id="hwRegisterSubmitBtn">确认登记</button>
|
||||
<button type="button" class="btn" onclick="closeModal('homeworkRegisterModal')">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加科目模态框 -->
|
||||
<div id="addSubjectModal" class="modal">
|
||||
<div class="modal-content">
|
||||
@@ -138,12 +183,12 @@ include __DIR__ . '/../includes/header.php';
|
||||
<form id="addSubjectFormInHw" onsubmit="event.preventDefault(); submitAddSubject()">
|
||||
<div class="form-group">
|
||||
<label>科目名称</label>
|
||||
<input type="text" id="subjectName" required placeholder="例如:语文、数学">
|
||||
<input type="text" id="subjectName" required maxlength="50" placeholder="例如:语文、数学">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>科目代码</label>
|
||||
<input type="text" id="subjectCode" placeholder="例如:CHI、MATH">
|
||||
<small>可选,用于排序和标识</small>
|
||||
<input type="text" id="subjectCode" maxlength="50" placeholder="例如:CHI、MATH">
|
||||
<small>可选,用于标识科目;排序可用列表中的 ↑ ↓ 调整</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">添加</button>
|
||||
@@ -164,11 +209,11 @@ include __DIR__ . '/../includes/header.php';
|
||||
<input type="hidden" id="editSubjectId">
|
||||
<div class="form-group">
|
||||
<label>科目名称</label>
|
||||
<input type="text" id="editSubjectName" required placeholder="例如:语文、数学">
|
||||
<input type="text" id="editSubjectName" required maxlength="50" placeholder="例如:语文、数学">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>科目代码</label>
|
||||
<input type="text" id="editSubjectCode" placeholder="例如:CHI、MATH">
|
||||
<input type="text" id="editSubjectCode" maxlength="50" placeholder="例如:CHI、MATH">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>排序序号</label>
|
||||
@@ -194,7 +239,17 @@ include __DIR__ . '/../includes/header.php';
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 15px;
|
||||
}
|
||||
.subject-order {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.subject-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.subject-name {
|
||||
font-weight: 500;
|
||||
@@ -204,19 +259,6 @@ include __DIR__ . '/../includes/header.php';
|
||||
color: var(--color-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.subject-status {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.subject-status-active {
|
||||
background: #c6f6d5;
|
||||
color: #22543d;
|
||||
}
|
||||
.subject-status-inactive {
|
||||
background: #fed7d7;
|
||||
color: #742a2a;
|
||||
}
|
||||
.collapsible-card .collapsible-header {
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
@@ -247,9 +289,8 @@ include __DIR__ . '/../includes/header.php';
|
||||
</style>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</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>
|
||||
<script src="/assets/js/homework-manage.js"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/homework-manage.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -0,0 +1,81 @@
|
||||
<?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_logs');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<div class="filter-group">
|
||||
<label>操作类型</label>
|
||||
<select id="logTypeFilter">
|
||||
<option value="">全部</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>操作人 / 角色</label>
|
||||
<input type="text" id="logOperatorFilter" placeholder="关键词">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>详情关键词</label>
|
||||
<input type="text" id="logKeywordFilter" placeholder="学生 / 原因等">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>开始日期</label>
|
||||
<input type="date" id="logStartDate">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>结束日期</label>
|
||||
<input type="date" id="logEndDate">
|
||||
</div>
|
||||
<div class="filter-group" style="flex: 0 0 auto;">
|
||||
<button class="btn btn-primary" onclick="loadLogs(1)">查询</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="white-space: nowrap;">时间</th>
|
||||
<th>操作人</th>
|
||||
<th>角色</th>
|
||||
<th>操作</th>
|
||||
<th>对象</th>
|
||||
<th>详情</th>
|
||||
<th>IP</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="logList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="pagination" id="logPagination"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="<?php echo asset_url('/assets/js/logs.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
+107
-4
@@ -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';
|
||||
?>
|
||||
|
||||
@@ -35,7 +36,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<div class="form-group">
|
||||
<label>新密码 <span style="color:red;">*</span></label>
|
||||
<input type="password" id="newPassword" required>
|
||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码 <span style="color:red;">*</span></label>
|
||||
@@ -44,6 +45,40 @@ 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>
|
||||
<div class="form-group">
|
||||
<label>新邮箱</label>
|
||||
<input type="email" id="bindEmail" maxlength="100" placeholder="请输入要绑定的邮箱">
|
||||
</div>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||
<button type="button" class="btn btn-secondary" onclick="sendBindEmailCode()">发送验证码</button>
|
||||
</div>
|
||||
<div class="form-group" style="margin-top:16px;">
|
||||
<label>邮箱验证码</label>
|
||||
<input type="text" id="emailCode" maxlength="6" inputmode="numeric" placeholder="请输入6位验证码">
|
||||
</div>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||
<button type="button" class="btn btn-primary" onclick="confirmBindEmail()">确认绑定</button>
|
||||
</div>
|
||||
|
||||
<hr style="border:none; border-top:1px solid var(--color-border-light); margin:18px 0;">
|
||||
<div class="form-group">
|
||||
<label>当前密码</label>
|
||||
<input type="password" id="emailPassword" placeholder="解除绑定邮箱需验证当前密码">
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" class="btn btn-sm btn-outline-danger" onclick="unbindEmail()">解除绑定</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
@@ -59,8 +94,9 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword.length < 6 || newPassword.length > 20) {
|
||||
showToast('密码长度需为6-20位', 'error');
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -76,6 +112,73 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
||||
showToast(res?.message || '密码修改失败', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
async function sendBindEmailCode() {
|
||||
const email = document.getElementById('bindEmail').value.trim();
|
||||
if (!email) {
|
||||
showToast('请输入要绑定的邮箱', 'warning');
|
||||
return;
|
||||
}
|
||||
const res = await apiPost('/api/auth/email/send-code', {
|
||||
email: email
|
||||
});
|
||||
if (res && res.success) {
|
||||
showToast(res.message || '验证码已发送,请查收邮箱');
|
||||
document.getElementById('emailCode').focus();
|
||||
} else {
|
||||
showToast(res?.message || '验证码发送失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBindEmail() {
|
||||
const email = document.getElementById('bindEmail').value.trim();
|
||||
const code = document.getElementById('emailCode').value.trim();
|
||||
if (!email) {
|
||||
showToast('请输入要绑定的邮箱', 'warning');
|
||||
return;
|
||||
}
|
||||
if (!code) {
|
||||
showToast('请输入邮箱验证码', 'warning');
|
||||
return;
|
||||
}
|
||||
const res = await apiPost('/api/auth/email/confirm', {
|
||||
email: email,
|
||||
code: code
|
||||
});
|
||||
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 = '';
|
||||
document.getElementById('emailCode').value = '';
|
||||
showToast(res.message || '邮箱绑定成功');
|
||||
} else {
|
||||
showToast(res?.message || '邮箱绑定失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function unbindEmail() {
|
||||
const password = document.getElementById('emailPassword').value;
|
||||
if (!password) {
|
||||
showToast('请输入当前密码', 'warning');
|
||||
return;
|
||||
}
|
||||
if (!confirm('确定解除绑定邮箱吗?解除后将无法通过邮箱找回密码。')) {
|
||||
return;
|
||||
}
|
||||
const res = await apiPost('/api/auth/email/unbind', {
|
||||
password: password
|
||||
});
|
||||
if (res && res.success) {
|
||||
document.getElementById('currentEmail').textContent = '未绑定';
|
||||
document.getElementById('bindEmail').value = '';
|
||||
document.getElementById('emailPassword').value = '';
|
||||
document.getElementById('emailCode').value = '';
|
||||
showToast(res.message || '邮箱已解除绑定');
|
||||
} else {
|
||||
showToast(res?.message || '解除绑定失败', 'error');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -0,0 +1,112 @@
|
||||
<?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>
|
||||
</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="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/record-query.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 管理端数据报表
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
|
||||
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
header('Location: /index.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$page_title = '数据报表';
|
||||
$role = current_group_name();
|
||||
require_perm('view_reports');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<div class="filter-bar">
|
||||
<div class="filter-group">
|
||||
<label>开始日期</label>
|
||||
<input type="date" id="reportStartDate">
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<label>结束日期</label>
|
||||
<input type="date" id="reportEndDate">
|
||||
</div>
|
||||
<div class="filter-group" style="flex: 0 0 auto;">
|
||||
<button class="btn btn-primary" onclick="loadReports()">查询</button>
|
||||
</div>
|
||||
</div>
|
||||
<p style="font-size: 12px; color: var(--color-text-secondary);" id="reportRangeHint">
|
||||
默认统计当前学期范围;考勤按记录日期统计,作业按作业截止日期统计
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title" style="display:flex; justify-content:space-between; align-items:center;">
|
||||
<span>考勤统计</span>
|
||||
<button class="btn btn-sm btn-secondary" onclick="exportReport('attendance')">导出</button>
|
||||
</div>
|
||||
<div id="attendanceSummary" class="report-summary"></div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>序号</th>
|
||||
<th>学号</th>
|
||||
<th>姓名</th>
|
||||
<th>出勤</th>
|
||||
<th>缺勤</th>
|
||||
<th>迟到</th>
|
||||
<th>请假</th>
|
||||
<th>记录数</th>
|
||||
<th>出勤率</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="attendanceReportList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title" style="display:flex; justify-content:space-between; align-items:center;">
|
||||
<span>作业统计</span>
|
||||
<button class="btn btn-sm btn-secondary" onclick="exportReport('homework')">导出</button>
|
||||
</div>
|
||||
<div id="homeworkSummary" class="report-summary"></div>
|
||||
<div class="table-wrapper">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>序号</th>
|
||||
<th>学号</th>
|
||||
<th>姓名</th>
|
||||
<th>已交</th>
|
||||
<th>未交</th>
|
||||
<th>迟交</th>
|
||||
<th>记录数</th>
|
||||
<th>未交率</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="homeworkReportList"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="<?php echo asset_url('/assets/js/reports.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';
|
||||
@@ -173,12 +170,15 @@ include __DIR__ . '/../includes/header.php';
|
||||
<th colspan="2" style="text-align:center; border-bottom: none;">基本信息</th>
|
||||
<th rowspan="2" style="vertical-align: middle;">姓名</th>
|
||||
<th rowspan="2" style="vertical-align: middle;">操行分</th>
|
||||
<th colspan="2" style="text-align:center; border-bottom: none;">环比上次</th>
|
||||
<th colspan="4" style="text-align:center; border-bottom: none;">考勤统计</th>
|
||||
<th colspan="3" style="text-align:center; border-bottom: none;">作业统计</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>排名</th>
|
||||
<th>学号</th>
|
||||
<th>分数变化</th>
|
||||
<th>排名变化</th>
|
||||
<th>出勤</th>
|
||||
<th>缺勤</th>
|
||||
<th>迟到</th>
|
||||
@@ -198,7 +198,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
||||
<script src="/assets/js/semesters.js"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/semesters.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* 班级操行分管理系统 - 管理端系统设置
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 联系方式: admin@sea-studio.top
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
* 许可证: MIT License
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
|
||||
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
||||
header('Location: /index.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$page_title = '系统设置';
|
||||
$role = current_group_name();
|
||||
require_perm('manage_settings');
|
||||
|
||||
include __DIR__ . '/../includes/header.php';
|
||||
?>
|
||||
|
||||
<?php include __DIR__ . '/../includes/nav.php'; ?>
|
||||
|
||||
<div class="container">
|
||||
<div class="card" style="max-width: 640px;">
|
||||
<div class="card-title">密码策略</div>
|
||||
<form id="passwordPolicyForm">
|
||||
<div class="form-group">
|
||||
<label>密码最小长度</label>
|
||||
<input type="number" id="pwdMinLength" min="4" max="64" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码最大长度</label>
|
||||
<input type="number" id="pwdMaxLength" min="8" max="100" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>最少字符种类数</label>
|
||||
<input type="number" id="pwdMinTypes" min="1" max="4" required>
|
||||
<small>可选种类:大写字母 / 小写字母 / 数字 / 特殊符号</small>
|
||||
</div>
|
||||
<small class="pwd-policy"></small>
|
||||
<div style="margin-top: 14px;">
|
||||
<button type="submit" class="btn btn-primary">保存</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="<?php echo asset_url('/assets/js/settings.js'); ?>"></script>
|
||||
|
||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||
+43
-22
@@ -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>
|
||||
@@ -70,8 +73,8 @@ include __DIR__ . '/../includes/header.php';
|
||||
<p>点击选择JSON文件</p>
|
||||
<p class="import-label">或点击此处上传</p>
|
||||
<input type="file" id="importFile" accept=".json">
|
||||
<p style="margin-top: 10px; font-size: 12px; color: #999;">
|
||||
<a href="/assets/uploads/sample_import.json" download style="color: #667eea;">下载示例文件</a>
|
||||
<p style="margin-top: 10px; font-size: 12px; color: var(--color-text-muted);">
|
||||
<a href="/assets/uploads/sample_import.json" download class="link">下载示例文件</a>
|
||||
</p>
|
||||
</div>
|
||||
<div id="importPreview" class="preview-table" style="display: none;"></div>
|
||||
@@ -160,7 +163,7 @@ include __DIR__ . '/../includes/header.php';
|
||||
<p id="resetStudentInfo" style="margin: 10px 0;"></p>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" id="newStudentPassword" required minlength="6" maxlength="20">
|
||||
<input type="password" id="newStudentPassword" required>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-warning">确认重置</button>
|
||||
@@ -170,12 +173,39 @@ include __DIR__ . '/../includes/header.php';
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</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>
|
||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/student-mgmt.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/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 class="check-grid">
|
||||
<label class="check-item"><input type="checkbox" class="export-student-col" value="student_no" checked disabled> 学号</label>
|
||||
<label class="check-item"><input type="checkbox" class="export-student-col" value="name" checked disabled> 姓名</label>
|
||||
<label class="check-item"><input type="checkbox" class="export-student-col" value="dormitory_number" checked> 宿舍号</label>
|
||||
<label class="check-item"><input type="checkbox" class="export-student-col" value="total_points" checked> 当前操行分</label>
|
||||
<?php if (has_perm('manage_students')): ?>
|
||||
<label class="check-item"><input type="checkbox" class="export-student-col" value="parent_phone"> 家长手机号</label>
|
||||
<?php endif; ?>
|
||||
<label class="check-item"><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">
|
||||
@@ -192,16 +222,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;
|
||||
|
||||
|
||||
@@ -263,3 +263,173 @@
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* ========== 权限组编辑 ========== */
|
||||
.perm-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.perm-section {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.perm-section-title {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-secondary);
|
||||
border-left: 3px solid var(--color-primary);
|
||||
padding-left: 6px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.check-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 6px 12px;
|
||||
}
|
||||
.form-group .check-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 0;
|
||||
font-weight: normal;
|
||||
font-size: 13px;
|
||||
}
|
||||
.perm-cap-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.check-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
/* ========== 状态徽标(管理员/科目通用) ========== */
|
||||
.subject-status {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.subject-status-active {
|
||||
background: #c6f6d5;
|
||||
color: #22543d;
|
||||
}
|
||||
.subject-status-inactive {
|
||||
background: #fed7d7;
|
||||
color: #742a2a;
|
||||
}
|
||||
|
||||
/* 已选学生信息条 */
|
||||
.selected-info {
|
||||
padding: 8px 12px;
|
||||
background: var(--color-hover);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* 表格长文本单元格 */
|
||||
.cell-wrap {
|
||||
max-width: 340px;
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
}
|
||||
/* 排行榜工具栏 */
|
||||
.ranking-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.ranking-toolbar select,
|
||||
.ranking-toolbar input[type="number"],
|
||||
.ranking-toolbar input[type="month"] {
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.ranking-tip {
|
||||
font-size: 14px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
/* 报表汇总说明 */
|
||||
.report-summary {
|
||||
font-size: 13px;
|
||||
color: var(--color-text-secondary);
|
||||
background: var(--color-hover);
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
/* 校历(节假日/补课)列表 */
|
||||
.calendar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
font-size: 13px;
|
||||
}
|
||||
.calendar-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.calendar-date {
|
||||
font-weight: 600;
|
||||
min-width: 92px;
|
||||
}
|
||||
.calendar-name {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
.calendar-source {
|
||||
color: #bbb;
|
||||
font-size: 12px;
|
||||
}
|
||||
.calendar-tag {
|
||||
padding: 1px 8px;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.calendar-tag-holiday {
|
||||
background: var(--color-danger-light);
|
||||
color: var(--color-danger-dark);
|
||||
}
|
||||
.calendar-tag-makeup {
|
||||
background: var(--color-primary-light);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
/* 作业按次登记-缺交学生列表 */
|
||||
.hw-reg-list {
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: 8px;
|
||||
padding: 6px 10px;
|
||||
background: var(--color-hover);
|
||||
}
|
||||
.hw-reg-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 0;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
font-size: 13px;
|
||||
}
|
||||
.hw-reg-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.hw-reg-name small {
|
||||
color: var(--color-text-muted);
|
||||
margin-left: 4px;
|
||||
}
|
||||
.hw-reg-miss-label {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
@@ -289,6 +289,7 @@ body {
|
||||
.table-wrapper {
|
||||
overflow-x: auto;
|
||||
overflow-y: visible;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
table {
|
||||
@@ -442,16 +443,6 @@ tr:hover {
|
||||
border-color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.btn-outline-danger {
|
||||
background: transparent;
|
||||
color: var(--color-danger);
|
||||
border: 1px solid var(--color-danger);
|
||||
}
|
||||
|
||||
.btn-outline-danger:hover {
|
||||
background: var(--color-danger-light);
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
@@ -746,6 +737,15 @@ tr:hover {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
/* 分值颜色(表格/统计卡片通用) */
|
||||
.plus {
|
||||
color: var(--color-success);
|
||||
}
|
||||
|
||||
.minus {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.record-reason {
|
||||
flex: 1;
|
||||
margin: 0 15px;
|
||||
@@ -799,12 +799,40 @@ tr:hover {
|
||||
}
|
||||
|
||||
.nav {
|
||||
padding: 0 16px;
|
||||
padding: 0 12px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.nav::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.user-role {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
padding: 18px;
|
||||
max-width: 94%;
|
||||
}
|
||||
|
||||
.action-bar {
|
||||
@@ -992,3 +1020,24 @@ td.history-reason {
|
||||
border-color: var(--color-danger-dark);
|
||||
}
|
||||
|
||||
|
||||
/* 成功提示(登录/找回密码页) */
|
||||
.success-msg {
|
||||
background: var(--color-success-light);
|
||||
color: var(--color-success);
|
||||
padding: 10px;
|
||||
border-radius: 8px;
|
||||
margin-top: 15px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 复选框/单选框不受 .form-group input 宽度影响 */
|
||||
.form-group input[type="checkbox"],
|
||||
.form-group input[type="radio"] {
|
||||
width: auto;
|
||||
height: auto;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* admin.js - 管理端公共函数库
|
||||
*
|
||||
* 此文件已拆分为独立模块,各模块文件位于 /assets/js/modules/ 目录
|
||||
* 各页面通过引用对应模块获取所需功能
|
||||
*
|
||||
* 模块列表:
|
||||
* - modules/modal-utils.js - 模态框工具函数
|
||||
* - modules/utils.js - 通用工具函数(escapeHtml, toggleSelectAll等)
|
||||
* - modules/student-mgmt.js - 学生管理函数
|
||||
* - modules/admin-mgmt.js - 管理员管理函数
|
||||
* - modules/subject-mgmt.js - 科目管理函数
|
||||
* - modules/points-mgmt.js - 加减分管理函数
|
||||
*/
|
||||
+265
-12
@@ -10,8 +10,105 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const PERMISSION_LABELS = {
|
||||
manage_students: '学生管理',
|
||||
export_students: '导出学生名单',
|
||||
manage_conduct: '操行分加减',
|
||||
revoke_any: '撤销任何记录',
|
||||
revoke_own: '撤销自己的记录',
|
||||
restore_records: '反撤销记录',
|
||||
manage_homework: '作业扣分',
|
||||
homework_register: '作业按次登记',
|
||||
manage_attendance: '考勤管理',
|
||||
default_attendance: '考勤默认出勤',
|
||||
manage_calendar: '节假日/补课设置',
|
||||
manage_subjects: '科目管理',
|
||||
manage_admins: '管理员/权限组管理',
|
||||
manage_semesters: '学期管理',
|
||||
view_all_records: '查看全班/个人查询',
|
||||
view_reports: '数据报表查看',
|
||||
export_data: '导出德育分/历史',
|
||||
view_logs: '操作日志查看',
|
||||
manage_settings: '系统设置',
|
||||
manage_upgrade: '系统升级'
|
||||
};
|
||||
|
||||
const PERMISSION_SECTIONS = [
|
||||
{ title: '学生', keys: ['manage_students', 'export_students'] },
|
||||
{ title: '操行分', keys: ['manage_conduct', 'revoke_any', 'revoke_own', 'restore_records', 'view_all_records', 'export_data'] },
|
||||
{ title: '教务', keys: ['manage_homework', 'homework_register', 'manage_attendance', 'default_attendance', 'manage_calendar', 'manage_subjects'] },
|
||||
{ title: '报表与审计', keys: ['view_reports', 'view_logs'] },
|
||||
{ title: '系统管理', keys: ['manage_admins', 'manage_semesters', 'manage_settings', 'manage_upgrade'] }
|
||||
];
|
||||
|
||||
let currentEditUserId = null;
|
||||
let currentResetUserId = null;
|
||||
let groupsCache = [];
|
||||
const currentUserId = (window.PAGE_CONFIG && window.PAGE_CONFIG.userId) ? parseInt(window.PAGE_CONFIG.userId) : null;
|
||||
|
||||
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.group_id)
|
||||
.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);
|
||||
let actions = '<span class="text-muted">-</span>';
|
||||
if (!group.readonly && group.group_id) {
|
||||
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>
|
||||
<a class="danger" onclick="deleteGroup(${group.group_id}, '${escapeHtml(group.group_name)}')">删除</a>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
html += `<tr>
|
||||
<td>${escapeHtml(group.group_name)}</td>
|
||||
<td class="cell-wrap">${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 +118,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.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 || '-')}</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 +147,40 @@ 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;
|
||||
const groupSelect = document.getElementById('editAdminGroupId');
|
||||
groupSelect.value = groupId || '';
|
||||
const isSelf = currentUserId !== null && parseInt(userId) === currentUserId;
|
||||
groupSelect.disabled = isSelf;
|
||||
const hint = document.getElementById('editAdminGroupHint');
|
||||
if (hint) hint.style.display = isSelf ? 'block' : 'none';
|
||||
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) {
|
||||
@@ -124,8 +238,9 @@ async function submitResetPassword() {
|
||||
if (!currentResetUserId) return;
|
||||
|
||||
const newPassword = document.getElementById('newPassword').value;
|
||||
if (!newPassword || newPassword.length < 6) {
|
||||
showToast('密码长度至少6位', 'warning');
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -141,14 +256,152 @@ async function submitResetPassword() {
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 权限组管理 ==========
|
||||
|
||||
function renderPermissionCheckboxes(permissions) {
|
||||
const container = document.getElementById('groupPermissionList');
|
||||
container.innerHTML = PERMISSION_SECTIONS.map(section => {
|
||||
const items = section.keys.map(key =>
|
||||
`<label class="check-item">
|
||||
<input type="checkbox" class="group-perm" value="${key}"${permissions[key] ? ' checked' : ''}> ${PERMISSION_LABELS[key]}
|
||||
</label>`
|
||||
).join('');
|
||||
return `<div class="perm-section">
|
||||
<div class="perm-section-title">${section.title}</div>
|
||||
<div class="check-grid">${items}</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function selectAllPermissions(checked) {
|
||||
document.querySelectorAll('.group-perm').forEach(el => { el.checked = !!checked; });
|
||||
}
|
||||
|
||||
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;
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
async function testSmtpEmail() {
|
||||
const email = prompt('请输入接收测试邮件的邮箱地址:');
|
||||
if (!email) return;
|
||||
const res = await apiPost('/api/admin/email/test', { email: email.trim() });
|
||||
if (res && res.success) {
|
||||
showToast(res.message || '测试邮件已发送');
|
||||
} else {
|
||||
alert('邮件发送失败:\n' + ((res && res.message) || '未知错误'));
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
window.selectAllPermissions = selectAllPermissions;
|
||||
window.testSmtpEmail = testSmtpEmail;
|
||||
|
||||
})();
|
||||
@@ -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) {
|
||||
@@ -154,13 +165,22 @@ async function loadAttendanceRecords() {
|
||||
let html = '';
|
||||
const records = res.data.records || [];
|
||||
records.forEach(record => {
|
||||
let deductionText = '-';
|
||||
if (record.deduction_points) {
|
||||
deductionText = '扣' + Math.abs(record.deduction_points) + '分';
|
||||
if (record.deduction_revoked) {
|
||||
deductionText += '(已撤销)';
|
||||
}
|
||||
} else if (record.deduction_applied) {
|
||||
deductionText = '已扣分';
|
||||
}
|
||||
html += `<tr>
|
||||
<td>${escapeHtml(record.student_no)}</td>
|
||||
<td>${escapeHtml(record.student_name)}</td>
|
||||
<td>${getStatusBadge(record.status, 'attendance')}</td>
|
||||
<td>${escapeHtml(record.reason || '-')}</td>
|
||||
<td>${escapeHtml(record.recorder_name || '-')}</td>
|
||||
<td>${record.deduction_applied ? '已扣分' : '-'}</td>
|
||||
<td>${deductionText}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (records.length === 0) {
|
||||
@@ -179,6 +199,229 @@ document.getElementById('attendanceSlot').addEventListener('change', function()
|
||||
loadExistingRecords();
|
||||
});
|
||||
|
||||
// ========== 日期工具 ==========
|
||||
|
||||
function formatDateValue(d) {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return y + '-' + m + '-' + day;
|
||||
}
|
||||
|
||||
// ========== 默认出勤(批量补全) ==========
|
||||
|
||||
function openDefaultAttendanceModal() {
|
||||
const startInput = document.getElementById('defaultStartDate');
|
||||
const endInput = document.getElementById('defaultEndDate');
|
||||
if (!startInput.value) {
|
||||
const today = new Date();
|
||||
startInput.value = formatDateValue(new Date(today.getFullYear(), today.getMonth(), 1));
|
||||
endInput.value = formatDateValue(today);
|
||||
}
|
||||
document.getElementById('defaultAttendanceModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
async function submitDefaultAttendance() {
|
||||
const startDate = document.getElementById('defaultStartDate').value;
|
||||
const endDate = document.getElementById('defaultEndDate').value;
|
||||
const slots = Array.from(document.querySelectorAll('.defaultSlot:checked')).map(el => el.value);
|
||||
|
||||
if (!startDate || !endDate) {
|
||||
showToast('请选择日期范围', 'warning');
|
||||
return;
|
||||
}
|
||||
if (startDate > endDate) {
|
||||
showToast('开始日期不能晚于结束日期', 'warning');
|
||||
return;
|
||||
}
|
||||
if (slots.length === 0) {
|
||||
showToast('请至少选择一个时段', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.getElementById('defaultAttendanceBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '补全中...';
|
||||
|
||||
try {
|
||||
const res = await apiPost('/api/admin/attendance/default', {
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
slots: slots
|
||||
});
|
||||
if (res && res.success) {
|
||||
showToast(res.message || '默认出勤完成');
|
||||
if (res.data && res.data.api_ok === false) {
|
||||
setTimeout(function() {
|
||||
showToast('节假日接口暂时不可用,本次仅按周末与手动设置判断', 'warning');
|
||||
}, 500);
|
||||
}
|
||||
closeModal('defaultAttendanceModal');
|
||||
await loadExistingRecords();
|
||||
loadAttendanceRecords();
|
||||
} else {
|
||||
showToast((res && (res.message || res.detail)) || '默认出勤失败', 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('默认出勤失败:' + (err && err.message ? err.message : '未知错误'), 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '开始补全';
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 校历(节假日/补课) ==========
|
||||
|
||||
function openCalendarModal() {
|
||||
const startInput = document.getElementById('calendarStartDate');
|
||||
const endInput = document.getElementById('calendarEndDate');
|
||||
if (!startInput.value) {
|
||||
const year = new Date().getFullYear();
|
||||
startInput.value = year + '-01-01';
|
||||
endInput.value = year + '-12-31';
|
||||
}
|
||||
document.getElementById('calendarModal').style.display = 'flex';
|
||||
loadCalendar();
|
||||
}
|
||||
|
||||
async function loadCalendar() {
|
||||
const startDate = document.getElementById('calendarStartDate').value;
|
||||
const endDate = document.getElementById('calendarEndDate').value;
|
||||
const area = document.getElementById('calendarListArea');
|
||||
|
||||
if (!startDate || !endDate || startDate > endDate) {
|
||||
area.innerHTML = '<div style="padding:16px;text-align:center;color:#999;font-size:13px;">请选择正确的日期范围</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
area.innerHTML = '<div style="padding:16px;text-align:center;color:#999;font-size:13px;">加载中...</div>';
|
||||
const res = await apiGet('/api/admin/attendance/calendar', { start_date: startDate, end_date: endDate });
|
||||
if (!res || !res.success) {
|
||||
area.innerHTML = '<div style="padding:16px;text-align:center;color:#c33;font-size:13px;">' +
|
||||
escapeHtml((res && res.message) || '加载失败') + '</div>';
|
||||
return;
|
||||
}
|
||||
renderCalendar(res.data);
|
||||
}
|
||||
|
||||
function renderCalendar(data) {
|
||||
const holidays = (data && data.holidays) || {};
|
||||
const workdays = (data && data.workdays) || {};
|
||||
const manual = (data && data.manual) || {};
|
||||
const items = [];
|
||||
|
||||
Object.keys(holidays).forEach(function(d) {
|
||||
items.push({ date: d, type: 'holiday', label: '放假', name: holidays[d], manual: false });
|
||||
});
|
||||
Object.keys(workdays).forEach(function(d) {
|
||||
items.push({ date: d, type: 'makeup', label: '调休', name: workdays[d], manual: false });
|
||||
});
|
||||
Object.keys(manual).forEach(function(d) {
|
||||
items.push({
|
||||
date: d,
|
||||
type: manual[d].type,
|
||||
label: manual[d].type === 'holiday' ? '放假' : '补课',
|
||||
name: manual[d].note || '',
|
||||
manual: true
|
||||
});
|
||||
});
|
||||
|
||||
items.sort(function(a, b) { return a.date < b.date ? -1 : (a.date > b.date ? 1 : 0); });
|
||||
|
||||
const area = document.getElementById('calendarListArea');
|
||||
let html = '';
|
||||
if (data && data.api_ok === false) {
|
||||
html += '<div style="padding:6px 12px;color:#ad6800;font-size:12px;border-bottom:1px solid var(--color-border-light);">节假日接口暂时不可用,仅显示手动设置</div>';
|
||||
}
|
||||
if (items.length === 0) {
|
||||
html += '<div style="padding:16px;text-align:center;color:#999;font-size:13px;">范围内没有节假日/补课记录</div>';
|
||||
}
|
||||
items.forEach(function(item) {
|
||||
const tagClass = item.type === 'holiday' ? 'calendar-tag-holiday' : 'calendar-tag-makeup';
|
||||
html += '<div class="calendar-item">' +
|
||||
'<span class="calendar-date">' + escapeHtml(item.date) + '</span>' +
|
||||
'<span class="calendar-tag ' + tagClass + '">' + item.label + '</span>' +
|
||||
'<span class="calendar-name">' + escapeHtml(item.name) + '</span>' +
|
||||
(item.manual
|
||||
? '<span class="calendar-source">手动</span>' +
|
||||
'<button class="btn btn-sm btn-ghost" style="margin-left:auto;" onclick="deleteCalendarDay(\'' + item.date + '\')">删除</button>'
|
||||
: '<span class="calendar-source" style="margin-left:auto;">接口</span>') +
|
||||
'</div>';
|
||||
});
|
||||
area.innerHTML = html;
|
||||
}
|
||||
|
||||
async function addCalendarDay() {
|
||||
const day = document.getElementById('calendarNewDate').value;
|
||||
const dayType = document.getElementById('calendarNewType').value;
|
||||
const note = document.getElementById('calendarNewNote').value.trim();
|
||||
|
||||
if (!day) {
|
||||
showToast('请选择日期', 'warning');
|
||||
return;
|
||||
}
|
||||
const res = await apiPost('/api/admin/attendance/calendar', {
|
||||
date: day,
|
||||
day_type: dayType,
|
||||
note: note
|
||||
});
|
||||
if (res && res.success) {
|
||||
showToast('已保存');
|
||||
document.getElementById('calendarNewNote').value = '';
|
||||
loadCalendar();
|
||||
} else {
|
||||
showToast((res && res.message) || '保存失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteCalendarDay(day) {
|
||||
const res = await apiDelete('/api/admin/attendance/calendar?date=' + encodeURIComponent(day));
|
||||
if (res && res.success) {
|
||||
showToast('已删除');
|
||||
loadCalendar();
|
||||
} else {
|
||||
showToast((res && res.message) || '删除失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 请假(整天) ==========
|
||||
|
||||
async function submitFullDayLeave() {
|
||||
const selectedCells = document.querySelectorAll('.student-cell.selected');
|
||||
if (selectedCells.length === 0) {
|
||||
showToast('请先选择请假的学生', 'warning');
|
||||
return;
|
||||
}
|
||||
const date = document.getElementById('attendanceDate').value;
|
||||
if (!date) {
|
||||
showToast('请选择日期', 'warning');
|
||||
return;
|
||||
}
|
||||
if (!confirm('确定为选中的学生提交整天请假吗?(按当天实际考勤时段生成:正常上课日3条、假前半天1条、节前上课2条、返校晚修1条;每时段按请假扣分)')) return;
|
||||
|
||||
const studentIds = Array.from(selectedCells).map(cell => parseInt(cell.dataset.id));
|
||||
const reason = document.getElementById('attendanceReason').value;
|
||||
|
||||
try {
|
||||
const res = await apiPost('/api/admin/attendance/full-day-leave', {
|
||||
date: date,
|
||||
student_ids: studentIds,
|
||||
reason: reason
|
||||
});
|
||||
if (res && res.success) {
|
||||
showToast(res.message || '整天请假提交成功');
|
||||
} else {
|
||||
showToast((res && (res.message || res.detail)) || '提交失败', 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('提交失败:' + (err && err.message ? err.message : '未知错误'), 'error');
|
||||
}
|
||||
|
||||
deselectAllStudents();
|
||||
await loadExistingRecords();
|
||||
loadAttendanceRecords();
|
||||
}
|
||||
|
||||
// 页面初始化
|
||||
initAttendanceButtons();
|
||||
loadStudents();
|
||||
@@ -191,5 +434,12 @@ window.selectAllStudents = selectAllStudents;
|
||||
window.deselectAllStudents = deselectAllStudents;
|
||||
window.submitAttendance = submitAttendance;
|
||||
window.loadAttendanceRecords = loadAttendanceRecords;
|
||||
window.openDefaultAttendanceModal = openDefaultAttendanceModal;
|
||||
window.submitDefaultAttendance = submitDefaultAttendance;
|
||||
window.submitFullDayLeave = submitFullDayLeave;
|
||||
window.openCalendarModal = openCalendarModal;
|
||||
window.loadCalendar = loadCalendar;
|
||||
window.addCalendarDay = addCalendarDay;
|
||||
window.deleteCalendarDay = deleteCalendarDay;
|
||||
|
||||
})();
|
||||
@@ -23,10 +23,6 @@ function getUserInfo() {
|
||||
}
|
||||
}
|
||||
|
||||
function setUserInfo(user) {
|
||||
localStorage.setItem(window.USER_STORAGE_KEY || 'class_system_user', JSON.stringify(user));
|
||||
}
|
||||
|
||||
function clearAuth() {
|
||||
localStorage.removeItem(window.JWT_STORAGE_KEY || 'class_system_token');
|
||||
localStorage.removeItem(window.USER_STORAGE_KEY || 'class_system_user');
|
||||
@@ -49,6 +45,18 @@ async function apiRequest(url, options = {}) {
|
||||
const response = await fetch(fullUrl, { ...options, headers });
|
||||
const data = await response.json();
|
||||
|
||||
// FastAPI 参数校验错误(422)统一转为可读 message
|
||||
if (data && !data.success && !data.message && data.detail) {
|
||||
if (Array.isArray(data.detail)) {
|
||||
data.message = data.detail.map(item => {
|
||||
const field = Array.isArray(item.loc) ? item.loc.filter(p => p !== 'body').join('.') : '';
|
||||
return (field ? field + ': ' : '') + (item.msg || '参数错误');
|
||||
}).join(';');
|
||||
} else if (typeof data.detail === 'string') {
|
||||
data.message = data.detail;
|
||||
}
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
clearAuth();
|
||||
|
||||
@@ -112,6 +120,200 @@ 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 getPasswordPolicy() {
|
||||
return {
|
||||
minLength: window.PASSWORD_MIN_LENGTH || 6,
|
||||
maxLength: window.PASSWORD_MAX_LENGTH || 20,
|
||||
minTypes: window.PASSWORD_MIN_TYPES || 3
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码策略提示文本
|
||||
*/
|
||||
function describePasswordPolicy() {
|
||||
const p = getPasswordPolicy();
|
||||
return '密码长度' + p.minLength + '-' + p.maxLength + '位,需包含大写字母、小写字母、数字、特殊符号中的至少' + p.minTypes + '种';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按密码策略校验,返回错误信息(空字符串表示通过)
|
||||
*/
|
||||
function validatePasswordByPolicy(password) {
|
||||
const p = getPasswordPolicy();
|
||||
if (!password || password.length < p.minLength) {
|
||||
return '密码长度至少' + p.minLength + '位';
|
||||
}
|
||||
if (password.length > p.maxLength) {
|
||||
return '密码长度不能超过' + p.maxLength + '位';
|
||||
}
|
||||
const types = [/[A-Z]/, /[a-z]/, /[0-9]/, /[^A-Za-z0-9]/].filter(function(re) {
|
||||
return re.test(password);
|
||||
}).length;
|
||||
if (types < p.minTypes) {
|
||||
return '密码需包含大写字母、小写字母、数字、特殊符号中的至少' + p.minTypes + '种';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function showToast(message, type = 'success') {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast toast-${type}`;
|
||||
@@ -327,6 +529,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
if (logoutBtn) {
|
||||
logoutBtn.addEventListener('click', logout);
|
||||
}
|
||||
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||
el.textContent = describePasswordPolicy();
|
||||
});
|
||||
});
|
||||
|
||||
function toggleActionDropdown(el) {
|
||||
|
||||
@@ -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) {
|
||||
@@ -30,15 +39,41 @@ async function loadStudents() {
|
||||
}
|
||||
}
|
||||
|
||||
function showSinglePointsModal(studentId, studentName) {
|
||||
window.selectedStudentIds = [studentId];
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
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 +89,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('; ')
|
||||
});
|
||||
}
|
||||
|
||||
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 + '"';
|
||||
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));
|
||||
});
|
||||
}
|
||||
}
|
||||
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);
|
||||
@@ -163,21 +182,21 @@ async function onDormitorySelected() {
|
||||
if (res && res.success && res.data.students) {
|
||||
const students = res.data.students;
|
||||
if (students.length === 0) {
|
||||
studentsList.innerHTML = '<p style="color: var(--text-secondary);">该宿舍暂无学生</p>';
|
||||
studentsList.innerHTML = '<p style="color: var(--color-text-secondary);">该宿舍暂无学生</p>';
|
||||
studentsCount.textContent = '';
|
||||
} else {
|
||||
students.forEach(s => {
|
||||
dormitoryStudentIds.push(s.student_id);
|
||||
const div = document.createElement('div');
|
||||
div.style.cssText = 'display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--border-color);';
|
||||
div.innerHTML = `<span>${escapeHtml(s.name)}</span><span style="color: var(--text-secondary);">${escapeHtml(s.student_no)}</span>`;
|
||||
div.style.cssText = 'display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--color-border);';
|
||||
div.innerHTML = `<span>${escapeHtml(s.name)}</span><span style="color: var(--color-text-secondary);">${escapeHtml(s.student_no)}</span>`;
|
||||
studentsList.appendChild(div);
|
||||
});
|
||||
studentsCount.textContent = `共 ${students.length} 人`;
|
||||
}
|
||||
studentsGroup.style.display = 'block';
|
||||
} else {
|
||||
studentsList.innerHTML = '<p style="color: var(--text-secondary);">加载失败</p>';
|
||||
studentsList.innerHTML = '<p style="color: var(--color-text-secondary);">加载失败</p>';
|
||||
studentsGroup.style.display = 'block';
|
||||
}
|
||||
}
|
||||
@@ -212,7 +231,8 @@ async function submitDormitoryPoints() {
|
||||
if (res && res.success) {
|
||||
showToast(`操作成功: ${res.data.success_count} 人成功`);
|
||||
closeModal('dormitoryPointsModal');
|
||||
loadStudents();
|
||||
loadStudents();
|
||||
initPointsLimitHint();
|
||||
} else {
|
||||
showToast(res?.message || '操作失败', 'error');
|
||||
}
|
||||
@@ -221,7 +241,7 @@ async function submitDormitoryPoints() {
|
||||
loadStudents();
|
||||
|
||||
window.loadStudents = loadStudents;
|
||||
window.showSinglePointsModal = showSinglePointsModal;
|
||||
window.showExportMoralityModal = showExportMoralityModal;
|
||||
window.exportMoralityRecords = exportMoralityRecords;
|
||||
window.showDormitoryPointsModal = showDormitoryPointsModal;
|
||||
window.onDormitorySelected = onDormitorySelected;
|
||||
|
||||
+111
-16
@@ -10,7 +10,6 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const role = window.PAGE_CONFIG.role;
|
||||
let totalStudents = 0;
|
||||
|
||||
async function loadDashboard() {
|
||||
@@ -49,39 +48,132 @@ 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 });
|
||||
if (rankingRes && rankingRes.success) {
|
||||
totalStudents = rankingRes.data.total_students || 0;
|
||||
let html = '';
|
||||
rankingRes.data.ranking.forEach((student, index) => {
|
||||
const rank = index + 1;
|
||||
await loadRanking();
|
||||
}
|
||||
|
||||
async function loadRanking() {
|
||||
const type = document.getElementById('rankingType').value;
|
||||
const params = { limit: 100 };
|
||||
if (type === 'monthly') {
|
||||
const monthInput = document.getElementById('rankingMonth');
|
||||
if (monthInput.value) params.month = monthInput.value;
|
||||
}
|
||||
|
||||
const rankingRes = await apiGet('/api/student/ranking', params);
|
||||
const head = document.getElementById('rankingHead');
|
||||
if (type === 'monthly') {
|
||||
head.innerHTML = '<th>排名</th><th>学号</th><th>姓名</th><th>加分</th><th>减分</th><th>月度分</th>';
|
||||
} else {
|
||||
head.innerHTML = '<th>排名</th><th>学号</th><th>姓名</th><th>操行分</th>';
|
||||
}
|
||||
if (!rankingRes || !rankingRes.success) return;
|
||||
|
||||
totalStudents = rankingRes.data.total_students || 0;
|
||||
let html = '';
|
||||
rankingRes.data.ranking.forEach((student, index) => {
|
||||
const rank = index + 1;
|
||||
if (type === 'monthly') {
|
||||
const score = student.month_score || 0;
|
||||
const cls = score > 0 ? 'plus' : (score < 0 ? 'minus' : '');
|
||||
html += `<tr>
|
||||
<td>${rank}</td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td>${escapeHtml(student.name)}</td>
|
||||
<td class="plus">+${student.bonus || 0}</td>
|
||||
<td class="minus">${student.deduction || 0}</td>
|
||||
<td class="${cls}">${score > 0 ? '+' : ''}${score}</td>
|
||||
</tr>`;
|
||||
} else {
|
||||
html += `<tr>
|
||||
<td>${rank}</td>
|
||||
<td>${escapeHtml(student.student_no)}</td>
|
||||
<td>${escapeHtml(student.name)}</td>
|
||||
<td>${student.total_points}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (rankingRes.data.ranking.length === 0) {
|
||||
html = '<tr><td colspan="4" style="text-align:center;">暂无数据</td></tr>';
|
||||
}
|
||||
document.getElementById('rankingList').innerHTML = html;
|
||||
});
|
||||
if (rankingRes.data.ranking.length === 0) {
|
||||
const cols = type === 'monthly' ? 6 : 4;
|
||||
html = `<tr><td colspan="${cols}" style="text-align:center;">暂无数据</td></tr>`;
|
||||
}
|
||||
document.getElementById('rankingList').innerHTML = html;
|
||||
}
|
||||
|
||||
function onRankingTypeChange() {
|
||||
const isMonthly = document.getElementById('rankingType').value === 'monthly';
|
||||
const monthInput = document.getElementById('rankingMonth');
|
||||
monthInput.style.display = isMonthly ? '' : 'none';
|
||||
if (isMonthly && !monthInput.value) {
|
||||
const now = new Date();
|
||||
monthInput.value = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
|
||||
}
|
||||
resetPercentileFilter();
|
||||
loadRanking();
|
||||
}
|
||||
|
||||
async function exportRanking() {
|
||||
const type = document.getElementById('rankingType').value;
|
||||
const params = { limit: 1000 };
|
||||
let label = '总分排行';
|
||||
if (type === 'monthly') {
|
||||
const month = document.getElementById('rankingMonth').value;
|
||||
if (!month) {
|
||||
showToast('请先选择月份', 'warning');
|
||||
return;
|
||||
}
|
||||
params.month = month;
|
||||
label = '月度排行_' + month;
|
||||
}
|
||||
|
||||
const res = await apiGet('/api/student/ranking', params);
|
||||
if (!res || !res.success) {
|
||||
showToast('导出失败', 'error');
|
||||
return;
|
||||
}
|
||||
const ranking = res.data.ranking || [];
|
||||
if (ranking.length === 0) {
|
||||
showToast('没有可导出的数据', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
let csv = type === 'monthly'
|
||||
? '排名,学号,姓名,加分,减分,月度分\n'
|
||||
: '排名,学号,姓名,操行分\n';
|
||||
ranking.forEach(function(s, index) {
|
||||
if (type === 'monthly') {
|
||||
csv += [index + 1, s.student_no, s.name, s.bonus || 0, s.deduction || 0, s.month_score || 0]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
} else {
|
||||
csv += [index + 1, s.student_no, s.name, s.total_points]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
}
|
||||
});
|
||||
|
||||
downloadCsv('排行榜_' + label + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
showToast('导出成功,共' + ranking.length + '人');
|
||||
}
|
||||
|
||||
function applyPercentileFilter() {
|
||||
@@ -114,6 +206,9 @@ document.getElementById('percentileFilter').addEventListener('keypress', functio
|
||||
loadDashboard();
|
||||
|
||||
window.loadDashboard = loadDashboard;
|
||||
window.loadRanking = loadRanking;
|
||||
window.onRankingTypeChange = onRankingTypeChange;
|
||||
window.exportRanking = exportRanking;
|
||||
window.applyPercentileFilter = applyPercentileFilter;
|
||||
window.resetPercentileFilter = resetPercentileFilter;
|
||||
|
||||
|
||||
+181
-64
@@ -10,18 +10,15 @@
|
||||
(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;
|
||||
const canAct = canRevoke || canRestore;
|
||||
let currentHistoryPage = 1;
|
||||
let totalHistoryPages = 1;
|
||||
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
var el = document.createElement('span');
|
||||
el.appendChild(document.createTextNode(str));
|
||||
return el.innerHTML;
|
||||
}
|
||||
|
||||
function typeMap(relatedType) {
|
||||
var map = { manual: '手动', homework: '作业', attendance: '考勤' };
|
||||
return map[relatedType] || '手动';
|
||||
@@ -52,6 +49,11 @@ async function loadSubjectsForFilter() {
|
||||
}
|
||||
}
|
||||
|
||||
// 加载学期下拉列表(默认选中当前学期)
|
||||
async function loadSemestersForFilter() {
|
||||
await loadSemesterOptions('historySemesterFilter', { includeAll: true });
|
||||
}
|
||||
|
||||
// 筛选学生时自动取消合并记录
|
||||
function onStudentFilterChange() {
|
||||
var studentId = document.getElementById('historyStudentId').value;
|
||||
@@ -89,6 +91,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 +106,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 +127,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 (canAct) {
|
||||
headHtml += '<th>操作</th>';
|
||||
}
|
||||
} else {
|
||||
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
||||
if (role === '班主任' || role === '班长' || role === '考勤委员') {
|
||||
if (canAct) {
|
||||
headHtml += '<th>操作</th>';
|
||||
}
|
||||
}
|
||||
@@ -149,17 +153,23 @@ 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 (canAct) {
|
||||
if (allRevoked) {
|
||||
html += '<td><span class="text-muted">已撤销</span></td>';
|
||||
} else {
|
||||
if (canRestore) {
|
||||
html += '<td><button class="btn btn-sm btn-outline" onclick="batchRestoreGrouped(\'' + escapeHtml(record.reason).replace(/'/g, "\\'") + '\',' + record.points_change + ',\'' + escapeHtml(record.recorder_name || '').replace(/'/g, "\\'") + '\')">批量反撤销</button></td>';
|
||||
} else {
|
||||
html += '<td><span class="text-muted">已撤销</span></td>';
|
||||
}
|
||||
} 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 = canAct ? 7 : 6;
|
||||
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
||||
}
|
||||
} else {
|
||||
@@ -174,24 +184,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 (canAct) {
|
||||
if (record.is_revoked == 1) {
|
||||
var revokerInfo = record.revoker_name ? '由 ' + escapeHtml(record.revoker_name) + ' 撤销' : '已撤销';
|
||||
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) {
|
||||
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><span class="text-muted">' + revokerInfo + '</span></td>';
|
||||
}
|
||||
} 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 +202,7 @@ async function loadHistory(page) {
|
||||
});
|
||||
|
||||
if (res.data.records.length === 0) {
|
||||
var colSpan = (role === '班主任' || role === '班长' || role === '考勤委员') ? 7 : 6;
|
||||
var colSpan = canAct ? 7 : 6;
|
||||
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
||||
}
|
||||
}
|
||||
@@ -223,6 +224,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 +233,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,40 +245,99 @@ 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) {
|
||||
showToast('没有找到记录', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
var csv = '\uFEFF';
|
||||
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';
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
showToast('导出成功,共' + records.length + '条记录');
|
||||
} else {
|
||||
showToast('导出失败:' + (res && res.message || '未知错误'), 'error');
|
||||
var records = await apiGetAll('/api/admin/conduct/history', params);
|
||||
if (!records || records.length === 0) {
|
||||
showToast('没有找到记录', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
var mode = getHistoryExportMode();
|
||||
var csv;
|
||||
if (mode === 'per_student') {
|
||||
csv = buildPerStudentCsv(records);
|
||||
} else {
|
||||
csv = '时间,学号,姓名,学期,类型,分数变动,原因,操作人\n';
|
||||
records.forEach(function(r) {
|
||||
csv += [
|
||||
r.created_at || '',
|
||||
r.student_no || '',
|
||||
r.student_name || '',
|
||||
r.semester_name || '',
|
||||
typeMap(r.related_type),
|
||||
(r.points_change > 0 ? '+' : '') + r.points_change,
|
||||
r.reason || '',
|
||||
r.recorder_name || ''
|
||||
].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
}
|
||||
|
||||
var semesterLabel = '全部学期';
|
||||
if (semesterSelect && semesterId && semesterSelect.selectedIndex >= 0) {
|
||||
semesterLabel = semesterSelect.options[semesterSelect.selectedIndex].textContent.replace(/((当前|已归档))$/, '');
|
||||
}
|
||||
var safeLabel = semesterLabel.replace(/[\\/:*?"<>|]/g, '_');
|
||||
var modeLabel = mode === 'per_student' ? '_按学生分表' : '';
|
||||
downloadCsv('历史记录_' + safeLabel + modeLabel + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
||||
|
||||
closeModal('exportHistoryModal');
|
||||
showToast('导出成功,共' + records.length + '条记录');
|
||||
} catch (err) {
|
||||
showToast('导出失败:' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function showExportHistoryModal() {
|
||||
document.getElementById('exportHistoryModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function getHistoryExportMode() {
|
||||
var el = document.querySelector('input[name="historyExportMode"]:checked');
|
||||
return el ? el.value : 'detail';
|
||||
}
|
||||
|
||||
// 按学生分表:每个学生一段(汇总 + 明细),便于发给家长
|
||||
function buildPerStudentCsv(records) {
|
||||
var groups = {};
|
||||
var order = [];
|
||||
records.forEach(function(r) {
|
||||
var key = r.student_id;
|
||||
if (!groups[key]) {
|
||||
groups[key] = { no: r.student_no || '', name: r.student_name || '', records: [] };
|
||||
order.push(key);
|
||||
}
|
||||
groups[key].records.push(r);
|
||||
});
|
||||
order.sort(function(a, b) {
|
||||
return String(groups[a].no).localeCompare(String(groups[b].no));
|
||||
});
|
||||
|
||||
var csv = '';
|
||||
order.forEach(function(key) {
|
||||
var group = groups[key];
|
||||
var bonus = 0;
|
||||
var deduction = 0;
|
||||
group.records.forEach(function(r) {
|
||||
if (r.points_change > 0) bonus += r.points_change;
|
||||
else deduction += r.points_change;
|
||||
});
|
||||
csv += ['学生', group.no + ' ' + group.name, '加分合计', '+' + bonus, '减分合计', deduction]
|
||||
.map(csvEscape).join(',') + '\n';
|
||||
csv += '时间,学期,类型,分值,原因,操作人\n';
|
||||
group.records.forEach(function(r) {
|
||||
csv += [
|
||||
r.created_at || '',
|
||||
r.semester_name || '',
|
||||
typeMap(r.related_type),
|
||||
(r.points_change > 0 ? '+' : '') + r.points_change,
|
||||
r.reason || '',
|
||||
r.recorder_name || ''
|
||||
].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
csv += '\n';
|
||||
});
|
||||
return csv;
|
||||
}
|
||||
|
||||
// 批量撤销合并记录(按条件查找并撤销)
|
||||
async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt) {
|
||||
if (!confirm('确定要撤销所有"' + reason + '"(' + (pointsChange > 0 ? '+' : '') + pointsChange + '分)的记录吗?')) return;
|
||||
@@ -289,6 +352,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) {
|
||||
@@ -298,7 +363,8 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
||||
|
||||
var matchedIds = [];
|
||||
res.data.records.forEach(function(r) {
|
||||
if (r.reason === reason && r.points_change === pointsChange && r.is_revoked == 0) {
|
||||
if (r.reason === reason && r.points_change === pointsChange && r.is_revoked == 0
|
||||
&& (!recorderName || r.recorder_name === recorderName)) {
|
||||
matchedIds.push(r.record_id);
|
||||
}
|
||||
});
|
||||
@@ -310,7 +376,7 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
||||
|
||||
var revokeRes = await apiPost('/api/admin/conduct/batch-revoke', { record_ids: matchedIds });
|
||||
if (revokeRes && revokeRes.success) {
|
||||
showToast('批量撤销完成: ' + (revokeRes.data ? revokeRes.data.success_count : 0) + '条成功');
|
||||
showToast('批量撤销完成: ' + (revokeRes.data ? revokeRes.data.success_count : 0) + '条(已移入“已撤销”,可筛选查看/批量反撤销)');
|
||||
loadHistory(currentHistoryPage);
|
||||
} else {
|
||||
showToast(revokeRes && revokeRes.message || '批量撤销失败', 'error');
|
||||
@@ -320,8 +386,57 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化:并行加载学生和科目列表,然后加载历史记录
|
||||
Promise.all([loadStudentsForSelect(), loadSubjectsForFilter()]).then(function() {
|
||||
// 批量反撤销合并记录(按条件查找并恢复)
|
||||
async function batchRestoreGrouped(reason, pointsChange, recorderName) {
|
||||
if (!confirm('确定要反撤销所有"' + reason + '"(' + (pointsChange > 0 ? '+' : '') + pointsChange + '分)的记录吗?')) return;
|
||||
|
||||
showToast('正在批量反撤销...', 'info');
|
||||
|
||||
try {
|
||||
var params = {
|
||||
page: 1, page_size: 1000,
|
||||
start_date: document.getElementById('historyStartDate').value,
|
||||
end_date: document.getElementById('historyEndDate').value,
|
||||
reason_prefix: reason.substring(0, 4),
|
||||
grouped: false,
|
||||
is_revoked: 1
|
||||
};
|
||||
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) {
|
||||
showToast('查询记录失败', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
var matchedIds = [];
|
||||
res.data.records.forEach(function(r) {
|
||||
if (r.reason === reason && r.points_change === pointsChange && r.is_revoked == 1
|
||||
&& (!recorderName || r.recorder_name === recorderName)) {
|
||||
matchedIds.push(r.record_id);
|
||||
}
|
||||
});
|
||||
|
||||
if (matchedIds.length === 0) {
|
||||
showToast('没有找到可反撤销的记录', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
var restoreRes = await apiPost('/api/admin/conduct/batch-restore', { record_ids: matchedIds });
|
||||
if (restoreRes && restoreRes.success) {
|
||||
showToast('批量反撤销完成: ' + (restoreRes.data ? restoreRes.data.success_count : 0) + '条成功(记录已恢复正常)');
|
||||
loadHistory(currentHistoryPage);
|
||||
} else {
|
||||
showToast((restoreRes && restoreRes.message) || '批量反撤销失败', 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('批量反撤销失败: ' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化:并行加载学生、科目、学期列表,然后加载历史记录
|
||||
Promise.all([loadStudentsForSelect(), loadSubjectsForFilter(), loadSemestersForFilter()]).then(function() {
|
||||
var urlParams = new URLSearchParams(window.location.search);
|
||||
var preStudentId = urlParams.get('student_id');
|
||||
if (preStudentId) {
|
||||
@@ -333,8 +448,10 @@ Promise.all([loadStudentsForSelect(), loadSubjectsForFilter()]).then(function()
|
||||
|
||||
window.loadHistory = loadHistory;
|
||||
window.loadStudentsForSelect = loadStudentsForSelect;
|
||||
window.showExportHistoryModal = showExportHistoryModal;
|
||||
window.exportHistoryRecords = exportHistoryRecords;
|
||||
window.batchRevokeGrouped = batchRevokeGrouped;
|
||||
window.batchRestoreGrouped = batchRestoreGrouped;
|
||||
window.onStudentFilterChange = onStudentFilterChange;
|
||||
window.onSubjectFilterChange = onSubjectFilterChange;
|
||||
window.toggleFilterPanel = toggleFilterPanel;
|
||||
|
||||
@@ -10,21 +10,22 @@
|
||||
(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;
|
||||
|
||||
// 更新页面中的配置值显示
|
||||
let studentsData = [];
|
||||
|
||||
// 更新页面中的配置值显示(加减分上限来自权限组动态配置)
|
||||
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'));
|
||||
|
||||
// 按次登记默认单次缺交扣分
|
||||
const regPerInput = document.getElementById('hwRegPerDeduction');
|
||||
if (regPerInput) regPerInput.value = hwNotSubmit;
|
||||
|
||||
// 加载科目列表(学习委员)
|
||||
async function loadSubjectsForHomework() {
|
||||
@@ -44,6 +45,7 @@ async function loadSubjectsForHomework() {
|
||||
async function loadStudents() {
|
||||
const res = await apiGet('/api/admin/students', {page_size: 1000});
|
||||
if (res && res.success) {
|
||||
studentsData = res.data.students || [];
|
||||
let html = '';
|
||||
res.data.students.forEach(student => {
|
||||
html += `<tr>
|
||||
@@ -61,46 +63,33 @@ async function loadStudents() {
|
||||
}
|
||||
}
|
||||
|
||||
function showSinglePointsModal(studentId, studentName) {
|
||||
window.selectedStudentIds = [studentId];
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
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();
|
||||
const hwDeadline = document.getElementById('hwDeadline').value;
|
||||
const reasonEl = document.getElementById('pointsReason');
|
||||
// 附加科目前缀、具体作业和缴交时间
|
||||
const subjectSelect = document.getElementById('hwSubjectSelect');
|
||||
const subjectName = subjectSelect ? subjectSelect.value : '';
|
||||
const hwTitle = document.getElementById('hwTitle').value.trim();
|
||||
const hwDeadline = document.getElementById('hwDeadline').value;
|
||||
const reasonEl = document.getElementById('pointsReason');
|
||||
|
||||
let prefix = '';
|
||||
if (subjectName) {
|
||||
prefix = `[${subjectName}]`;
|
||||
}
|
||||
if (hwTitle) {
|
||||
prefix += `[${hwTitle}]`;
|
||||
}
|
||||
if (hwDeadline) {
|
||||
prefix += ` 缴交:${hwDeadline}`;
|
||||
}
|
||||
if (prefix) {
|
||||
reasonEl.value = prefix + ' ' + reasonEl.value;
|
||||
}
|
||||
let prefix = '';
|
||||
if (subjectName) {
|
||||
prefix = `[${subjectName}]`;
|
||||
}
|
||||
if (hwTitle) {
|
||||
prefix += `[${hwTitle}]`;
|
||||
}
|
||||
if (hwDeadline) {
|
||||
prefix += ` 缴交:${hwDeadline}`;
|
||||
}
|
||||
if (prefix) {
|
||||
reasonEl.value = prefix + ' ' + reasonEl.value;
|
||||
}
|
||||
|
||||
submitBatchPoints({ related_type: 'homework' });
|
||||
@@ -126,37 +115,68 @@ function toggleSubjectPanel() {
|
||||
}
|
||||
}
|
||||
|
||||
let subjectsCache = [];
|
||||
|
||||
async function loadSubjectList() {
|
||||
const res = await apiGet('/api/subject/list');
|
||||
if (res && res.success && res.data) {
|
||||
subjectsCache = res.data.subjects || [];
|
||||
let html = '';
|
||||
const subjects = res.data.subjects || [];
|
||||
subjects.forEach(sub => {
|
||||
subjectsCache.forEach((sub, index) => {
|
||||
const safeName = escapeHtml(sub.subject_name || '');
|
||||
const safeCode = escapeHtml(sub.subject_code || '');
|
||||
const sortOrder = sub.sort_order || 0;
|
||||
const codeHtml = safeCode ? `<span class="subject-code">${safeCode}</span>` : '';
|
||||
const upBtn = index > 0
|
||||
? `<button class="btn btn-sm btn-ghost" title="上移" onclick="moveSubject(${sub.subject_id}, -1)">↑</button>`
|
||||
: '';
|
||||
const downBtn = index < subjectsCache.length - 1
|
||||
? `<button class="btn btn-sm btn-ghost" title="下移" onclick="moveSubject(${sub.subject_id}, 1)">↓</button>`
|
||||
: '';
|
||||
html += `
|
||||
<div class="subject-item">
|
||||
<span class="subject-name">${safeName}</span>
|
||||
<span class="subject-code">${safeCode}</span>
|
||||
${codeHtml}
|
||||
<span class="subject-status ${sub.is_active ? 'subject-status-active' : 'subject-status-inactive'}">
|
||||
${sub.is_active ? '启用' : '禁用'}
|
||||
</span>
|
||||
<button class="btn btn-sm btn-outline" onclick="showEditSubjectModal(${sub.subject_id}, '${safeName.replace(/'/g, "\\'")}', '${safeCode.replace(/'/g, "\\'")}', ${sortOrder})">编辑</button>
|
||||
<button class="btn btn-sm btn-ghost" onclick="toggleSubjectStatus(${sub.subject_id}, ${sub.is_active ? 'false' : 'true'})">
|
||||
${sub.is_active ? '禁用' : '启用'}
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteSubject(${sub.subject_id})">删除</button>
|
||||
<span class="subject-order">排序 ${sortOrder}</span>
|
||||
<span class="subject-actions">
|
||||
${upBtn}
|
||||
${downBtn}
|
||||
<button class="btn btn-sm btn-outline" onclick="showEditSubjectModal(${sub.subject_id}, '${safeName.replace(/'/g, "\\'")}', '${safeCode.replace(/'/g, "\\'")}', ${sortOrder})">编辑</button>
|
||||
<button class="btn btn-sm btn-ghost" onclick="toggleSubjectStatus(${sub.subject_id}, ${sub.is_active ? 'false' : 'true'})">
|
||||
${sub.is_active ? '禁用' : '启用'}
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteSubject(${sub.subject_id})">删除</button>
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
if (subjects.length === 0) {
|
||||
if (subjectsCache.length === 0) {
|
||||
html = '<p style="text-align:center;padding:40px;">暂无科目,请点击"添加科目"</p>';
|
||||
}
|
||||
document.getElementById('subjectList').innerHTML = html;
|
||||
}
|
||||
}
|
||||
|
||||
async function moveSubject(subjectId, direction) {
|
||||
const index = subjectsCache.findIndex(s => s.subject_id === subjectId);
|
||||
if (index < 0) return;
|
||||
const targetIndex = index + direction;
|
||||
if (targetIndex < 0 || targetIndex >= subjectsCache.length) return;
|
||||
const ids = subjectsCache.map(s => s.subject_id);
|
||||
ids[index] = subjectsCache[targetIndex].subject_id;
|
||||
ids[targetIndex] = subjectId;
|
||||
const res = await apiPut('/api/subject/reorder', { subject_ids: ids });
|
||||
if (res && res.success) {
|
||||
loadSubjectList();
|
||||
loadSubjectsForHomework();
|
||||
} else {
|
||||
showToast(res?.message || '排序失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function showAddSubjectModal() {
|
||||
const form = document.getElementById('addSubjectFormInHw');
|
||||
if (form) form.reset();
|
||||
@@ -229,8 +249,10 @@ async function submitEditSubject() {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = { subject_name: subjectName };
|
||||
if (subjectCode) data.subject_code = subjectCode;
|
||||
const data = {
|
||||
subject_name: subjectName,
|
||||
subject_code: subjectCode
|
||||
};
|
||||
if (sortOrder !== '') data.sort_order = parseInt(sortOrder);
|
||||
|
||||
const res = await apiPut(`/api/subject/update/${subjectId}`, data);
|
||||
@@ -244,6 +266,109 @@ async function submitEditSubject() {
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 作业按次登记 ==========
|
||||
|
||||
async function showHomeworkRegisterModal() {
|
||||
if (!studentsData || studentsData.length === 0) {
|
||||
showToast('学生列表尚未加载,请稍后重试', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
// 科目下拉(值为科目ID)
|
||||
const subjectSelect = document.getElementById('hwRegSubject');
|
||||
const subRes = await apiGet('/api/subject/list', { is_active: true });
|
||||
let options = '<option value="">请选择科目</option>';
|
||||
if (subRes && subRes.success && subRes.data && subRes.data.subjects) {
|
||||
subRes.data.subjects.forEach(s => {
|
||||
options += `<option value="${s.subject_id}">${escapeHtml(s.subject_name)}</option>`;
|
||||
});
|
||||
}
|
||||
subjectSelect.innerHTML = options;
|
||||
|
||||
// 默认列出全部学生,缺交次数默认 0(0 = 已交)
|
||||
let html = '';
|
||||
studentsData.forEach(student => {
|
||||
html += `<div class="hw-reg-item">
|
||||
<span class="hw-reg-name">${escapeHtml(student.name)} <small>${escapeHtml(student.student_no)}</small></span>
|
||||
<span class="hw-reg-miss-label" style="margin-left:auto;">缺交</span>
|
||||
<input type="number" class="hw-reg-miss" data-id="${student.student_id}" min="0" value="0" style="width:64px;">
|
||||
<span class="hw-reg-miss-label">次</span>
|
||||
</div>`;
|
||||
});
|
||||
document.getElementById('hwRegStudentList').innerHTML = html;
|
||||
|
||||
const deadlineInput = document.getElementById('hwRegDeadline');
|
||||
if (!deadlineInput.value) {
|
||||
const now = new Date();
|
||||
deadlineInput.value = now.getFullYear() + '-' +
|
||||
String(now.getMonth() + 1).padStart(2, '0') + '-' +
|
||||
String(now.getDate()).padStart(2, '0');
|
||||
}
|
||||
|
||||
document.getElementById('homeworkRegisterModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
async function submitHomeworkRegister() {
|
||||
const subjectId = parseInt(document.getElementById('hwRegSubject').value);
|
||||
const title = document.getElementById('hwRegTitle').value.trim();
|
||||
const deadline = document.getElementById('hwRegDeadline').value;
|
||||
const totalTimes = parseInt(document.getElementById('hwRegTotal').value);
|
||||
const perDeductionRaw = document.getElementById('hwRegPerDeduction').value;
|
||||
const note = document.getElementById('hwRegNote').value.trim();
|
||||
|
||||
if (!subjectId) { showToast('请选择科目', 'warning'); return; }
|
||||
if (!deadline) { showToast('请选择缴交/截止日期', 'warning'); return; }
|
||||
if (!totalTimes || totalTimes < 1 || totalTimes > 99) {
|
||||
showToast('总提交次数需在1-99之间', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const inputs = Array.from(document.querySelectorAll('.hw-reg-miss'));
|
||||
const records = [];
|
||||
for (const input of inputs) {
|
||||
const miss = parseInt(input.value) || 0;
|
||||
if (miss < 0 || miss > totalTimes) {
|
||||
showToast('缺交次数需在0~总提交次数之间', 'warning');
|
||||
return;
|
||||
}
|
||||
if (miss > 0) {
|
||||
records.push({ student_id: parseInt(input.dataset.id), miss_count: miss });
|
||||
}
|
||||
}
|
||||
|
||||
const payload = {
|
||||
subject_id: subjectId,
|
||||
deadline: deadline,
|
||||
total_times: totalTimes,
|
||||
records: records
|
||||
};
|
||||
if (title) payload.title = title;
|
||||
if (perDeductionRaw) payload.per_deduction = parseInt(perDeductionRaw);
|
||||
if (note) payload.note = note;
|
||||
|
||||
const btn = document.getElementById('hwRegisterSubmitBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '提交中...';
|
||||
try {
|
||||
const res = await apiPost('/api/admin/homework/register', payload);
|
||||
if (res && res.success) {
|
||||
showToast(res.message || '登记完成');
|
||||
closeModal('homeworkRegisterModal');
|
||||
document.querySelectorAll('.student-checkbox').forEach(cb => cb.checked = false);
|
||||
const selectAll = document.getElementById('selectAll');
|
||||
if (selectAll) selectAll.checked = false;
|
||||
loadStudents();
|
||||
} else {
|
||||
showToast((res && (res.message || res.detail)) || '登记失败', 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('登记失败:' + (err && err.message ? err.message : '未知错误'), 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '确认登记';
|
||||
}
|
||||
}
|
||||
|
||||
// 绑定科目管理折叠面板
|
||||
var subjectHeader = document.getElementById('subjectPanelHeader');
|
||||
if (subjectHeader) {
|
||||
@@ -254,7 +379,6 @@ loadStudents();
|
||||
loadSubjectsForHomework();
|
||||
|
||||
window.loadStudents = loadStudents;
|
||||
window.showSinglePointsModal = showSinglePointsModal;
|
||||
window.handleSubmitPoints = handleSubmitPoints;
|
||||
window.toggleSubjectPanel = toggleSubjectPanel;
|
||||
window.showAddSubjectModal = showAddSubjectModal;
|
||||
@@ -263,5 +387,8 @@ window.toggleSubjectStatus = toggleSubjectStatus;
|
||||
window.deleteSubject = deleteSubject;
|
||||
window.showEditSubjectModal = showEditSubjectModal;
|
||||
window.submitEditSubject = submitEditSubject;
|
||||
window.moveSubject = moveSubject;
|
||||
window.showHomeworkRegisterModal = showHomeworkRegisterModal;
|
||||
window.submitHomeworkRegister = submitHomeworkRegister;
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 操作日志页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
const OPERATION_TYPES = {
|
||||
add_student: '新增学生',
|
||||
update_student: '编辑学生',
|
||||
delete_student: '删除学生',
|
||||
import_students: '导入学生',
|
||||
reset_student_password: '重置学生密码',
|
||||
add_points: '加减分',
|
||||
revoke_record: '撤销记录',
|
||||
restore_record: '反撤销记录',
|
||||
add_attendance: '添加考勤',
|
||||
default_attendance: '默认出勤',
|
||||
add_calendar_day: '添加校历设置',
|
||||
remove_calendar_day: '删除校历设置',
|
||||
homework_register: '作业按次登记',
|
||||
batch_revoke: '批量撤销记录',
|
||||
batch_restore: '批量反撤销记录',
|
||||
add_admin: '添加管理员',
|
||||
reactivate_admin: '重新激活管理员',
|
||||
update_admin: '编辑管理员',
|
||||
toggle_admin_status: '启用/禁用管理员',
|
||||
reset_password: '重置管理员密码',
|
||||
unlock_user: '解除登录锁定',
|
||||
create_semester: '创建学期',
|
||||
update_semester: '编辑学期',
|
||||
delete_semester: '删除学期',
|
||||
activate_semester: '激活学期',
|
||||
associate_records: '关联学期数据',
|
||||
archive_semester: '归档学期',
|
||||
create_permission_group: '新建权限组',
|
||||
update_permission_group: '编辑权限组',
|
||||
delete_permission_group: '删除权限组',
|
||||
update_password_policy: '修改密码策略'
|
||||
};
|
||||
|
||||
const TARGET_TYPES = {
|
||||
student: '学生',
|
||||
admin: '管理员',
|
||||
conduct: '操行分',
|
||||
attendance: '考勤',
|
||||
homework: '作业',
|
||||
semester: '学期',
|
||||
subject: '科目',
|
||||
permission_group: '权限组',
|
||||
user: '用户',
|
||||
setting: '系统设置'
|
||||
};
|
||||
|
||||
let currentPage = 1;
|
||||
|
||||
function operationLabel(type) {
|
||||
return OPERATION_TYPES[type] || type;
|
||||
}
|
||||
|
||||
function targetLabel(type) {
|
||||
return type ? (TARGET_TYPES[type] || type) : '-';
|
||||
}
|
||||
|
||||
async function loadLogTypes() {
|
||||
const res = await apiGet('/api/admin/operation-logs/types');
|
||||
if (res && res.success && res.data && res.data.types) {
|
||||
const select = document.getElementById('logTypeFilter');
|
||||
let html = '<option value="">全部</option>';
|
||||
res.data.types.forEach(function(type) {
|
||||
html += '<option value="' + escapeHtml(type) + '">' + escapeHtml(operationLabel(type)) + '</option>';
|
||||
});
|
||||
select.innerHTML = html;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLogs(page) {
|
||||
currentPage = page || 1;
|
||||
const params = {
|
||||
page: currentPage,
|
||||
page_size: 20,
|
||||
operation_type: document.getElementById('logTypeFilter').value,
|
||||
operator: document.getElementById('logOperatorFilter').value.trim(),
|
||||
keyword: document.getElementById('logKeywordFilter') ? document.getElementById('logKeywordFilter').value.trim() : '',
|
||||
start_date: document.getElementById('logStartDate').value,
|
||||
end_date: document.getElementById('logEndDate').value
|
||||
};
|
||||
|
||||
const res = await apiGet('/api/admin/operation-logs', params);
|
||||
if (!res || !res.success) {
|
||||
showToast((res && res.message) || '加载操作日志失败', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
(res.data.logs || []).forEach(function(log) {
|
||||
const targetText = targetLabel(log.target_type) + (log.target_id ? '#' + log.target_id : '');
|
||||
html += `<tr>
|
||||
<td style="white-space: nowrap;">${formatDateTime(log.created_at)}</td>
|
||||
<td>${escapeHtml(log.operator_name || '-')}</td>
|
||||
<td>${escapeHtml(log.operator_role || '-')}</td>
|
||||
<td>${escapeHtml(operationLabel(log.operation_type))}</td>
|
||||
<td style="white-space: nowrap;">${escapeHtml(targetText)}</td>
|
||||
<td class="cell-wrap">${escapeHtml(log.details || '-')}</td>
|
||||
<td>${escapeHtml(log.ip_address || '-')}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if ((res.data.logs || []).length === 0) {
|
||||
html = '<tr><td colspan="7" style="text-align:center;">暂无日志</td></tr>';
|
||||
}
|
||||
document.getElementById('logList').innerHTML = html;
|
||||
|
||||
renderSmartPagination('logPagination', currentPage, res.data.total_pages || 1, function(page) {
|
||||
loadLogs(page);
|
||||
});
|
||||
}
|
||||
|
||||
loadLogTypes();
|
||||
loadLogs(1);
|
||||
|
||||
window.loadLogs = loadLogs;
|
||||
|
||||
})();
|
||||
@@ -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,6 +31,25 @@
|
||||
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();
|
||||
}
|
||||
|
||||
// 显示单人加减分模态框(各页面共用)
|
||||
function showSinglePointsModal(studentId, studentName) {
|
||||
selectedStudentIds = [studentId];
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
preparePointsLimitHint();
|
||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
@@ -39,8 +58,9 @@
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -75,7 +95,7 @@
|
||||
|
||||
const res = await apiPost('/api/admin/conduct/revoke', { record_id: recordId });
|
||||
if (res && res.success) {
|
||||
showToast('撤销成功');
|
||||
showToast('撤销成功,该记录已移入“已撤销”(可筛选查看/反撤销)');
|
||||
loadHistory(currentHistoryPage);
|
||||
} else {
|
||||
showToast(res?.message || '撤销失败', 'error');
|
||||
@@ -88,7 +108,7 @@
|
||||
|
||||
const res = await apiPost('/api/admin/conduct/restore', { record_id: recordId });
|
||||
if (res && res.success) {
|
||||
showToast('反撤销成功');
|
||||
showToast('反撤销成功,该记录已恢复正常');
|
||||
loadHistory(currentHistoryPage);
|
||||
} else {
|
||||
showToast(res?.message || '反撤销失败', 'error');
|
||||
@@ -96,7 +116,9 @@
|
||||
}
|
||||
|
||||
window.showBatchPointsModal = showBatchPointsModal;
|
||||
window.showSinglePointsModal = showSinglePointsModal;
|
||||
window.submitBatchPoints = submitBatchPoints;
|
||||
window.preparePointsLimitHint = preparePointsLimitHint;
|
||||
window.revokeRecord = revokeRecord;
|
||||
window.restoreRecord = restoreRecord;
|
||||
})();
|
||||
@@ -94,8 +94,9 @@
|
||||
const studentId = document.getElementById('resetStudentId').value;
|
||||
const newPassword = document.getElementById('newStudentPassword').value;
|
||||
|
||||
if (!newPassword || newPassword.length < 6) {
|
||||
showToast('密码至少6位', 'warning');
|
||||
const policyError = validatePasswordByPolicy(newPassword);
|
||||
if (policyError) {
|
||||
showToast(policyError, 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,14 +12,6 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// HTML转义
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
var el = document.createElement('span');
|
||||
el.appendChild(document.createTextNode(str));
|
||||
return el.innerHTML;
|
||||
}
|
||||
|
||||
// 全选功能
|
||||
function toggleSelectAll() {
|
||||
const selectAll = document.getElementById('selectAll');
|
||||
@@ -30,6 +22,5 @@
|
||||
}
|
||||
}
|
||||
|
||||
window.escapeHtml = escapeHtml;
|
||||
window.toggleSelectAll = toggleSelectAll;
|
||||
})();
|
||||
@@ -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 + ' 条有效记录(不含已撤销)。' +
|
||||
'月度分为当月加分与减分的净得分,与基础分无关;总分 = 基础分 + 全部加分 - 全部减分。';
|
||||
|
||||
renderMonthly(data.months);
|
||||
renderReasonSummary(data.months);
|
||||
}
|
||||
|
||||
function renderMonthly(months) {
|
||||
let html = '';
|
||||
if (!months || months.length === 0) {
|
||||
html = '<tr><td colspan="5" style="text-align:center;">暂无记录</td></tr>';
|
||||
} else {
|
||||
months.forEach(m => {
|
||||
const monthScore = (typeof m.month_score === 'number') ? m.month_score : ((m.bonus || 0) + (m.deduction || 0));
|
||||
html += '<tr>' +
|
||||
'<td>' + escapeHtml(monthLabel(m.month)) + '</td>' +
|
||||
'<td class="plus">+' + m.bonus + '</td>' +
|
||||
'<td class="minus">' + m.deduction + '</td>' +
|
||||
'<td><strong>' + (monthScore > 0 ? '+' : '') + monthScore + '</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;
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 数据报表页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
let attendanceCache = null;
|
||||
let homeworkCache = null;
|
||||
|
||||
function formatDateValue(date) {
|
||||
return date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
|
||||
}
|
||||
|
||||
async function initReportDates() {
|
||||
const startInput = document.getElementById('reportStartDate');
|
||||
const endInput = document.getElementById('reportEndDate');
|
||||
const today = new Date();
|
||||
let start = new Date(today.getFullYear(), today.getMonth(), 1);
|
||||
|
||||
try {
|
||||
const res = await apiGet('/api/semester/active');
|
||||
if (res && res.success && res.data && res.data.start_date) {
|
||||
start = new Date(res.data.start_date);
|
||||
}
|
||||
} catch (e) { /* 使用默认月初 */ }
|
||||
|
||||
startInput.value = formatDateValue(start);
|
||||
endInput.value = formatDateValue(today);
|
||||
}
|
||||
|
||||
async function loadReports() {
|
||||
const startDate = document.getElementById('reportStartDate').value;
|
||||
const endDate = document.getElementById('reportEndDate').value;
|
||||
if (!startDate || !endDate) {
|
||||
showToast('请选择开始和结束日期', 'warning');
|
||||
return;
|
||||
}
|
||||
if (startDate > endDate) {
|
||||
showToast('开始日期不能晚于结束日期', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
document.getElementById('reportRangeHint').textContent = `统计范围:${startDate} ~ ${endDate}`;
|
||||
|
||||
const [attendanceRes, homeworkRes] = await Promise.all([
|
||||
apiGet('/api/report/attendance', { start_date: startDate, end_date: endDate }),
|
||||
apiGet('/api/report/homework', { start_date: startDate, end_date: endDate })
|
||||
]);
|
||||
|
||||
if (attendanceRes && attendanceRes.success) {
|
||||
attendanceCache = attendanceRes.data;
|
||||
renderAttendance(attendanceRes.data);
|
||||
} else {
|
||||
showToast((attendanceRes && attendanceRes.message) || '考勤报表加载失败', 'error');
|
||||
}
|
||||
if (homeworkRes && homeworkRes.success) {
|
||||
homeworkCache = homeworkRes.data;
|
||||
renderHomework(homeworkRes.data);
|
||||
} else {
|
||||
showToast((homeworkRes && homeworkRes.message) || '作业报表加载失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function rateText(rate) {
|
||||
return (rate === null || rate === undefined) ? '-' : rate + '%';
|
||||
}
|
||||
|
||||
function renderAttendance(data) {
|
||||
const rows = data.rows || [];
|
||||
const summary = data.summary || {};
|
||||
document.getElementById('attendanceSummary').textContent =
|
||||
`共 ${rows.length} 人,${summary.total || 0} 条记录:出勤 ${summary.present || 0}、缺勤 ${summary.absent || 0}、迟到 ${summary.late || 0}、请假 ${summary.leave || 0},出勤率 ${rateText(summary.rate)}`;
|
||||
|
||||
let html = '';
|
||||
rows.forEach((row, index) => {
|
||||
html += `<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td>${escapeHtml(row.student_no)}</td>
|
||||
<td>${escapeHtml(row.name)}</td>
|
||||
<td class="plus">${row.present}</td>
|
||||
<td class="minus">${row.absent}</td>
|
||||
<td>${row.late}</td>
|
||||
<td>${row.leave}</td>
|
||||
<td>${row.total}</td>
|
||||
<td>${rateText(row.rate)}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (rows.length === 0) {
|
||||
html = '<tr><td colspan="9" style="text-align:center;">暂无数据</td></tr>';
|
||||
}
|
||||
document.getElementById('attendanceReportList').innerHTML = html;
|
||||
}
|
||||
|
||||
function renderHomework(data) {
|
||||
const rows = data.rows || [];
|
||||
const summary = data.summary || {};
|
||||
document.getElementById('homeworkSummary').textContent =
|
||||
`共 ${rows.length} 人,${summary.total || 0} 条记录:已交 ${summary.submitted || 0}、未交 ${summary.not_submitted || 0}、迟交 ${summary.late || 0},未交率 ${rateText(summary.miss_rate)}`;
|
||||
|
||||
let html = '';
|
||||
rows.forEach((row, index) => {
|
||||
html += `<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td>${escapeHtml(row.student_no)}</td>
|
||||
<td>${escapeHtml(row.name)}</td>
|
||||
<td class="plus">${row.submitted}</td>
|
||||
<td class="minus">${row.not_submitted}</td>
|
||||
<td>${row.late}</td>
|
||||
<td>${row.total}</td>
|
||||
<td>${rateText(row.miss_rate)}</td>
|
||||
</tr>`;
|
||||
});
|
||||
if (rows.length === 0) {
|
||||
html = '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
|
||||
}
|
||||
document.getElementById('homeworkReportList').innerHTML = html;
|
||||
}
|
||||
|
||||
function exportReport(type) {
|
||||
const data = type === 'attendance' ? attendanceCache : homeworkCache;
|
||||
if (!data || !data.rows || data.rows.length === 0) {
|
||||
showToast('请先查询报表数据', 'warning');
|
||||
return;
|
||||
}
|
||||
let csv = '';
|
||||
if (type === 'attendance') {
|
||||
csv += '序号,学号,姓名,出勤,缺勤,迟到,请假,记录数,出勤率(%)\n';
|
||||
data.rows.forEach((row, index) => {
|
||||
csv += [index + 1, row.student_no, row.name, row.present, row.absent, row.late, row.leave, row.total,
|
||||
(row.rate === null || row.rate === undefined) ? '' : row.rate].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
} else {
|
||||
csv += '序号,学号,姓名,已交,未交,迟交,记录数,未交率(%)\n';
|
||||
data.rows.forEach((row, index) => {
|
||||
csv += [index + 1, row.student_no, row.name, row.submitted, row.not_submitted, row.late, row.total,
|
||||
(row.miss_rate === null || row.miss_rate === undefined) ? '' : row.miss_rate].map(csvEscape).join(',') + '\n';
|
||||
});
|
||||
}
|
||||
const label = type === 'attendance' ? '考勤统计' : '作业统计';
|
||||
downloadCsv(`${label}_${data.start_date}_${data.end_date}.csv`, csv);
|
||||
showToast('导出成功,共' + data.rows.length + '人');
|
||||
}
|
||||
|
||||
initReportDates().then(loadReports);
|
||||
|
||||
window.loadReports = loadReports;
|
||||
window.exportReport = exportReport;
|
||||
|
||||
})();
|
||||
@@ -253,13 +253,33 @@ async function viewArchiveData(semesterId, semesterName, page) {
|
||||
if (res && res.success) {
|
||||
const data = res.data || {};
|
||||
const archives = data.archives || [];
|
||||
const prevName = data.previous_semester ? data.previous_semester.semester_name : null;
|
||||
document.getElementById('archiveDataTitle').textContent =
|
||||
`归档数据 - ${semesterName}` + (prevName ? `(对比:${prevName})` : '(无对比学期)');
|
||||
let html = '';
|
||||
archives.forEach(a => {
|
||||
const points = a.points_change;
|
||||
const hasPoints = (points !== null && points !== undefined);
|
||||
const pointsText = hasPoints ? (points > 0 ? '+' + points : String(points)) : '-';
|
||||
const pointsClass = hasPoints ? (points > 0 ? 'plus' : (points < 0 ? 'minus' : '')) : '';
|
||||
|
||||
const rankChange = a.rank_change;
|
||||
const hasRank = (rankChange !== null && rankChange !== undefined);
|
||||
let rankText = '-';
|
||||
let rankClass = '';
|
||||
if (hasRank) {
|
||||
if (rankChange > 0) { rankText = '↑' + rankChange; rankClass = 'plus'; }
|
||||
else if (rankChange < 0) { rankText = '↓' + Math.abs(rankChange); rankClass = 'minus'; }
|
||||
else { rankText = '-'; }
|
||||
}
|
||||
|
||||
html += `<tr>
|
||||
<td>${a.rank_position || '-'}</td>
|
||||
<td>${escapeHtml(a.student_no)}</td>
|
||||
<td>${escapeHtml(a.student_name)}</td>
|
||||
<td>${a.final_points}</td>
|
||||
<td class="${pointsClass}">${pointsText}</td>
|
||||
<td class="${rankClass}">${rankText}</td>
|
||||
<td>${a.attendance_present || 0}</td>
|
||||
<td>${a.attendance_absent || 0}</td>
|
||||
<td>${a.attendance_late || 0}</td>
|
||||
@@ -270,7 +290,7 @@ async function viewArchiveData(semesterId, semesterName, page) {
|
||||
</tr>`;
|
||||
});
|
||||
if (archives.length === 0) {
|
||||
html = '<tr><td colspan="11" style="text-align:center;">暂无归档数据</td></tr>';
|
||||
html = '<tr><td colspan="13" style="text-align:center;">暂无归档数据</td></tr>';
|
||||
}
|
||||
document.getElementById('archiveDataList').innerHTML = html;
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 班级操行分管理系统 - 系统设置页JS
|
||||
*
|
||||
* 开发者: Canglan
|
||||
* 版权归属: Sea Network Technology Studio
|
||||
*
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
async function loadPasswordPolicy() {
|
||||
const res = await apiGet('/api/admin/settings/password-policy');
|
||||
if (!res || !res.success) {
|
||||
showToast((res && res.message) || '获取密码策略失败', 'error');
|
||||
return;
|
||||
}
|
||||
document.getElementById('pwdMinLength').value = res.data.min_length;
|
||||
document.getElementById('pwdMaxLength').value = res.data.max_length;
|
||||
document.getElementById('pwdMinTypes').value = res.data.min_types;
|
||||
applyPolicyGlobals(res.data);
|
||||
}
|
||||
|
||||
function applyPolicyGlobals(policy) {
|
||||
window.PASSWORD_MIN_LENGTH = policy.min_length;
|
||||
window.PASSWORD_MAX_LENGTH = policy.max_length;
|
||||
window.PASSWORD_MIN_TYPES = policy.min_types;
|
||||
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||
el.textContent = describePasswordPolicy();
|
||||
});
|
||||
}
|
||||
|
||||
async function savePasswordPolicy() {
|
||||
const minLength = parseInt(document.getElementById('pwdMinLength').value);
|
||||
const maxLength = parseInt(document.getElementById('pwdMaxLength').value);
|
||||
const minTypes = parseInt(document.getElementById('pwdMinTypes').value);
|
||||
|
||||
if (isNaN(minLength) || isNaN(maxLength) || isNaN(minTypes)) {
|
||||
showToast('请填写完整的密码策略', 'warning');
|
||||
return;
|
||||
}
|
||||
if (minLength < 4 || minLength > 64) {
|
||||
showToast('最小长度需在4-64之间', 'warning');
|
||||
return;
|
||||
}
|
||||
if (maxLength < 8 || maxLength > 100) {
|
||||
showToast('最大长度需在8-100之间', 'warning');
|
||||
return;
|
||||
}
|
||||
if (minLength > maxLength) {
|
||||
showToast('最小长度不能大于最大长度', 'warning');
|
||||
return;
|
||||
}
|
||||
if (minTypes < 1 || minTypes > 4) {
|
||||
showToast('字符种类数需在1-4之间', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await apiPut('/api/admin/settings/password-policy', {
|
||||
min_length: minLength,
|
||||
max_length: maxLength,
|
||||
min_types: minTypes
|
||||
});
|
||||
if (res && res.success) {
|
||||
applyPolicyGlobals({ min_length: minLength, max_length: maxLength, min_types: minTypes });
|
||||
showToast(res.message || '密码策略已保存');
|
||||
} else {
|
||||
showToast((res && res.message) || '保存失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('passwordPolicyForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
savePasswordPolicy();
|
||||
});
|
||||
|
||||
loadPasswordPolicy();
|
||||
|
||||
window.savePasswordPolicy = savePasswordPolicy;
|
||||
|
||||
})();
|
||||
@@ -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;
|
||||
@@ -61,14 +72,6 @@ function renderPagination() {
|
||||
});
|
||||
}
|
||||
|
||||
function showSinglePointsModal(studentId, studentName) {
|
||||
window.selectedStudentIds = [studentId];
|
||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
||||
document.getElementById('pointsChange').value = '';
|
||||
document.getElementById('pointsReason').value = '';
|
||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
||||
}
|
||||
|
||||
async function unlockStudent(studentNo, studentName) {
|
||||
if (!confirm(`确定要解除学生 "${studentName}" 的登录锁定吗?\n(适用于多次登录失败被禁止登录的情况)`)) {
|
||||
return;
|
||||
@@ -85,6 +88,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;
|
||||
@@ -94,7 +174,8 @@ document.getElementById('searchInput').addEventListener('input', () => {
|
||||
});
|
||||
|
||||
window.loadStudents = loadStudents;
|
||||
window.showSinglePointsModal = showSinglePointsModal;
|
||||
window.unlockStudent = unlockStudent;
|
||||
window.showExportStudentsModal = showExportStudentsModal;
|
||||
window.exportStudents = exportStudents;
|
||||
|
||||
})();
|
||||
+98
-3
@@ -10,6 +10,12 @@
|
||||
* 版权所有 © Sea Network Technology Studio
|
||||
*/
|
||||
|
||||
// PHP 版本要求:8.4+(旧版本已停止安全维护,存在已知漏洞)
|
||||
if (PHP_VERSION_ID < 80400) {
|
||||
http_response_code(500);
|
||||
die('系统要求 PHP 8.4 或更高版本(当前版本:' . PHP_VERSION . ')。请先升级服务器 PHP 版本以规避已知安全漏洞。');
|
||||
}
|
||||
|
||||
// 读取.env文件
|
||||
$envFile = __DIR__ . '/.env';
|
||||
$config = [];
|
||||
@@ -38,7 +44,7 @@ foreach ($lines as $line) {
|
||||
}
|
||||
|
||||
// 检查必要配置是否存在
|
||||
$requiredKeys = ['API_BASE_URL', 'API_TIMEOUT', 'JWT_STORAGE_KEY', 'USER_STORAGE_KEY', 'SITE_NAME', 'SESSION_TIMEOUT', 'ICP_ENABLED', 'ICP_NUMBER'];
|
||||
$requiredKeys = ['API_BASE_URL', 'API_TIMEOUT', 'JWT_STORAGE_KEY', 'USER_STORAGE_KEY', 'SITE_NAME', 'ICP_ENABLED', 'ICP_NUMBER'];
|
||||
$missingKeys = [];
|
||||
|
||||
foreach ($requiredKeys as $key) {
|
||||
@@ -57,11 +63,9 @@ define('API_TIMEOUT', (int)$config['API_TIMEOUT']);
|
||||
define('JWT_STORAGE_KEY', $config['JWT_STORAGE_KEY']);
|
||||
define('USER_STORAGE_KEY', $config['USER_STORAGE_KEY']);
|
||||
define('SITE_NAME', $config['SITE_NAME']);
|
||||
define('SESSION_TIMEOUT', (int)$config['SESSION_TIMEOUT']);
|
||||
define('ICP_ENABLED', $config['ICP_ENABLED'] !== 'false');
|
||||
define('ICP_NUMBER', $config['ICP_NUMBER'] ?? '');
|
||||
// 会话配置
|
||||
// 会话配置
|
||||
ini_set('session.cookie_httponly', 1);
|
||||
ini_set('session.use_only_cookies', 1);
|
||||
ini_set('session.cookie_secure', 1);
|
||||
@@ -77,3 +81,94 @@ 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'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态资源版本号:按文件修改时间附加 ?v=,部署更新后浏览器自动拉取新文件,避免旧 JS/CSS 缓存
|
||||
*/
|
||||
function asset_url($path) {
|
||||
$file = __DIR__ . $path;
|
||||
if (is_file($file)) {
|
||||
return $path . '?v=' . filemtime($file);
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
// 管理员页面自动同步权限(权限组变更后自动生效)
|
||||
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="<?php echo asset_url('/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" class="link" style="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.className = isError ? 'error-msg' : 'success-msg';
|
||||
tip.style.display = 'block';
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -25,9 +25,9 @@ $page_title = $page_title ?? '首页';
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||
<title><?php echo SITE_NAME; ?> - <?php echo $page_title; ?></title>
|
||||
<link rel="stylesheet" href="/assets/css/style.css">
|
||||
<link rel="stylesheet" href="<?php echo asset_url('/assets/css/style.css'); ?>">
|
||||
<?php if ($user_type === 'admin'): ?>
|
||||
<link rel="stylesheet" href="/assets/css/admin.css">
|
||||
<link rel="stylesheet" href="<?php echo asset_url('/assets/css/admin.css'); ?>">
|
||||
<?php endif; ?>
|
||||
</head>
|
||||
<body>
|
||||
@@ -62,6 +62,9 @@ $page_title = $page_title ?? '首页';
|
||||
window.DEDUCTION_ATTENDANCE_LATE = resp.data.DEDUCTION_ATTENDANCE_LATE;
|
||||
window.DEDUCTION_ATTENDANCE_LEAVE = resp.data.DEDUCTION_ATTENDANCE_LEAVE;
|
||||
window.STUDENT_INITIAL_POINTS = resp.data.STUDENT_INITIAL_POINTS;
|
||||
window.PASSWORD_MIN_LENGTH = resp.data.PASSWORD_MIN_LENGTH;
|
||||
window.PASSWORD_MAX_LENGTH = resp.data.PASSWORD_MAX_LENGTH;
|
||||
window.PASSWORD_MIN_TYPES = resp.data.PASSWORD_MIN_TYPES;
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
@@ -72,8 +75,104 @@ $page_title = $page_title ?? '首页';
|
||||
window.DEDUCTION_ATTENDANCE_LATE = 1;
|
||||
window.DEDUCTION_ATTENDANCE_LEAVE = 0;
|
||||
window.STUDENT_INITIAL_POINTS = 60;
|
||||
window.PASSWORD_MIN_LENGTH = 6;
|
||||
window.PASSWORD_MAX_LENGTH = 20;
|
||||
window.PASSWORD_MIN_TYPES = 3;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script src="/assets/js/common.js"></script>
|
||||
<script src="/assets/js/modules/utils.js"></script>
|
||||
<script src="<?php echo asset_url('/assets/js/common.js'); ?>"></script>
|
||||
<script src="<?php echo asset_url('/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; ?>
|
||||
<?php if ($user_type === 'admin'): ?>
|
||||
<!-- 密码待修改(初始密码/被重置后):设置新密码(无需原密码) -->
|
||||
<div id="initPasswordModal" class="modal" style="display:none;">
|
||||
<div class="modal-content" style="max-width:420px;">
|
||||
<div class="modal-header">
|
||||
<h3>请设置新密码</h3>
|
||||
</div>
|
||||
<p style="font-size:13px;color:var(--color-text-muted);margin:0 0 12px;">首次使用或密码被管理员重置后,需要先设置新密码(无需输入原密码)</p>
|
||||
<div class="form-group">
|
||||
<label>新密码</label>
|
||||
<input type="password" id="initNewPassword" autocomplete="new-password">
|
||||
<small>密码要求:<span class="pwd-policy"></span></small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>确认新密码</label>
|
||||
<input type="password" id="initConfirmPassword" autocomplete="new-password">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" id="initPasswordBtn" onclick="submitInitPassword()">确认修改</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function() {
|
||||
// 以服务端标记为准判断是否首次登录(避免本地旧标记误弹)
|
||||
(async function() {
|
||||
var user = (typeof getUserInfo === 'function') ? getUserInfo() : null;
|
||||
var need = user && user.need_change_password;
|
||||
try {
|
||||
var res = await apiGet('/api/auth/me');
|
||||
if (res && res.success && res.data) {
|
||||
need = !!res.data.need_change_password;
|
||||
}
|
||||
} catch (e) { /* 接口异常时退回本地标记 */ }
|
||||
if (!need) return;
|
||||
document.getElementById('initPasswordModal').style.display = 'flex';
|
||||
})();
|
||||
|
||||
window.submitInitPassword = async function() {
|
||||
var p1 = document.getElementById('initNewPassword').value;
|
||||
var p2 = document.getElementById('initConfirmPassword').value;
|
||||
if (!p1) { showToast('请输入新密码', 'warning'); return; }
|
||||
if (p1 !== p2) { showToast('两次输入的密码不一致', 'warning'); return; }
|
||||
var err = (typeof validatePasswordByPolicy === 'function') ? validatePasswordByPolicy(p1) : '';
|
||||
if (err) { showToast(err, 'warning'); return; }
|
||||
|
||||
var btn = document.getElementById('initPasswordBtn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = '提交中...';
|
||||
try {
|
||||
var res = await apiPost('/api/auth/init-passwd', { new_password: p1 });
|
||||
if (res && res.success) {
|
||||
showToast(res.message || '密码设置成功,请重新登录');
|
||||
setTimeout(function() { logout(); }, 1200);
|
||||
} else {
|
||||
showToast((res && (res.message || res.detail)) || '设置失败', 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = '确认修改';
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('设置失败:' + (e && e.message ? e.message : '未知错误'), 'error');
|
||||
btn.disabled = false;
|
||||
btn.textContent = '确认修改';
|
||||
}
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
@@ -1,21 +1,33 @@
|
||||
<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 === '志愿委员'): ?>
|
||||
<?php if (has_perm('manage_conduct')): ?>
|
||||
<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('view_reports')): ?>
|
||||
<a href="/admin/reports.php" class="nav-item<?php echo $current_page === 'reports' ? ' active' : ''; ?>">数据报表</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_admins')): ?>
|
||||
<a href="/admin/admins.php" class="nav-item<?php echo $current_page === 'admins' ? ' active' : ''; ?>">管理员管理</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($role === '班主任'): ?>
|
||||
<?php if (has_perm('view_logs')): ?>
|
||||
<a href="/admin/logs.php" class="nav-item<?php echo $current_page === 'logs' ? ' active' : ''; ?>">操作日志</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_semesters')): ?>
|
||||
<a href="/admin/semesters.php" class="nav-item<?php echo $current_page === 'semesters' ? ' active' : ''; ?>">学期管理</a>
|
||||
<?php endif; ?>
|
||||
<?php if (has_perm('manage_settings')): ?>
|
||||
<a href="/admin/settings.php" class="nav-item<?php echo $current_page === 'settings' ? ' active' : ''; ?>">系统设置</a>
|
||||
<?php endif; ?>
|
||||
<a href="/admin/history.php" class="nav-item<?php echo $current_page === 'history' ? ' active' : ''; ?>">历史记录</a>
|
||||
<?php if (has_perm('view_all_records')): ?>
|
||||
<a href="/admin/record_query.php" class="nav-item<?php echo $current_page === 'record_query' ? ' active' : ''; ?>">个人查询</a>
|
||||
<?php endif; ?>
|
||||
<a href="/admin/password.php" class="nav-item<?php echo $current_page === 'password' ? ' active' : ''; ?>">修改密码</a>
|
||||
</div>
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user