Compare commits
31
Commits
058dee9dc4
...
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 |
No files matched your search
@@ -342,6 +342,7 @@ sudo systemctl restart nginx
|
|||||||
| `SMTP_SSL` | 是否使用SSL直连 | true |
|
| `SMTP_SSL` | 是否使用SSL直连 | true |
|
||||||
| `SMTP_STARTTLS` | 是否使用STARTTLS | false |
|
| `SMTP_STARTTLS` | 是否使用STARTTLS | false |
|
||||||
| `PASSWORD_RESET_EXPIRE_MINUTES` | 重置链接有效期(分钟) | 30 |
|
| `PASSWORD_RESET_EXPIRE_MINUTES` | 重置链接有效期(分钟) | 30 |
|
||||||
|
| `EMAIL_CODE_EXPIRE_MINUTES` | 邮箱绑定验证码有效期(分钟) | 10 |
|
||||||
|
|
||||||
> 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。
|
> 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。
|
||||||
|
|
||||||
|
|||||||
@@ -23,23 +23,27 @@
|
|||||||
**班主任权限:**
|
**班主任权限:**
|
||||||
- 学生管理:新增/编辑/删除学生、批量导入学生(JSON)、按自选字段导出学生名单(CSV)
|
- 学生管理:新增/编辑/删除学生、批量导入学生(JSON)、按自选字段导出学生名单(CSV)
|
||||||
- 操行分管理:对学生进行加减分、撤销任何扣分记录、查看全班历史记录、按学期导出德育分记录(含基础分/加分/减分拆分)
|
- 操行分管理:对学生进行加减分、撤销任何扣分记录、查看全班历史记录、按学期导出德育分记录(含基础分/加分/减分拆分)
|
||||||
- 作业管理:发布作业、查看提交情况
|
- 作业管理:批量加减分(未交/迟交/自定义扣分);按次登记(一次登记覆盖多次作业,配置总提交次数,按每人缺交次数自动扣分并写入提交数据,供作业统计报表使用)
|
||||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值
|
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值;支持"默认出勤"按日期范围批量补全(跳过周末与法定节假日,调休补班与手动补课日照常)及节假日/补课校历设置
|
||||||
- 科目管理:动态增删学科
|
- 科目管理:动态增删学科
|
||||||
- 权限组管理:自定义权限组(勾选功能权限 + 配置加分/扣分上限),管理员账号绑定权限组与邮箱;班主任组为锁定系统组,其余预置组可编辑
|
- 权限组管理:权限组全部可自定义(编辑权限项、加减分上限,任意组可编辑/删除/分配),管理员账号绑定权限组与邮箱
|
||||||
- 密码找回:管理员绑定邮箱后,可在登录页通过 SMTP 邮件自助重置密码(链接一次性、限时有效)
|
- 密码找回:管理员绑定邮箱(自助绑定需 SMTP 邮箱验证码,无需密码),忘记密码时可在登录页通过邮箱获取一次性重置链接(限时、仅可使用一次)
|
||||||
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
||||||
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
||||||
- 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法)
|
- 排行榜:支持总分排行与月度分排行(可选月份查看当月加分/减分/月度分),支持百分比筛选显示前N%的学生(抹零法)与一键导出CSV
|
||||||
|
- 数据报表:考勤统计与作业统计(按日期范围),含汇总与每人明细,可导出CSV
|
||||||
|
- 操作日志:管理端可查询操作日志(操作类型/操作人/日期筛选,分页展示)
|
||||||
|
- 系统设置:密码策略可配置(长度范围与最少字符种类数),全站即时生效
|
||||||
|
- 学期归档对比:查看归档数据时展示与上一归档学期的分数变化与名次升降
|
||||||
- 数据导出:按学期导出历史记录、导出德育分记录(默认当前学期,可选历史学期/全部学期)
|
- 数据导出:按学期导出历史记录、导出德育分记录(默认当前学期,可选历史学期/全部学期)
|
||||||
|
- 默认出勤:按日期范围给缺失学生批量补"出勤"记录(跳过周末/法定节假日,调休补班与手动补课日照常,已有记录不覆盖);节假日数据来自在线接口,支持手动添加放假/补课
|
||||||
|
|
||||||
**管理员/班干部权限(v4.0 起由权限组动态控制):**
|
**管理员/班干部权限(v4.0 起由权限组动态控制):**
|
||||||
- 管理员账号绑定一个权限组,权限组可自定义以下能力与上限:
|
- 管理员账号绑定一个权限组,权限组可自定义以下能力与上限:
|
||||||
- 功能权限:学生管理、导出学生名单、操行分加减、撤销他人/撤销自己记录、反撤销、作业扣分、考勤管理、科目管理、管理员管理、学期管理、查看全班/个人查询、数据导出、系统升级
|
- 功能权限:学生管理、导出学生名单、操行分加减、撤销他人/撤销自己记录、反撤销、作业扣分、作业按次登记、考勤管理、考勤默认出勤、节假日/补课设置、科目管理、查看全班/个人查询、数据报表查看、数据导出、操作日志查看、系统设置、管理员管理、学期管理、系统升级
|
||||||
- 加减分上限:是否允许加分、单次加分上限、是否允许扣分、单次扣分上限(留空为无限制)
|
- 加减分上限:是否允许加分、单次加分上限、是否允许扣分、单次扣分上限(留空为无限制)
|
||||||
- 系统预置六个权限组(班主任/班长/学习委员/考勤委员/劳动委员/志愿委员),默认权限与原角色一致,可随时调整上限或新建自定义组
|
- 系统预置六个权限组(班主任/班长/学习委员/考勤委员/劳动委员/志愿委员),默认权限与原角色一致,可随时调整上限或新建自定义组
|
||||||
|
|
||||||
## 技术栈
|
|
||||||
## 安全特性
|
## 安全特性
|
||||||
|
|
||||||
- JWT Token + PHP Session 双轨制认证
|
- JWT Token + PHP Session 双轨制认证
|
||||||
@@ -57,7 +61,9 @@
|
|||||||
| 后端框架 | FastAPI | 0.104+ |
|
| 后端框架 | FastAPI | 0.104+ |
|
||||||
| 数据库 | MySQL | 5.7 |
|
| 数据库 | MySQL | 5.7 |
|
||||||
| 缓存 | Redis | 7.x |
|
| 缓存 | Redis | 7.x |
|
||||||
| 前端 | PHP | 8.0 |
|
| 前端 | PHP | 8.4 |
|
||||||
|
|
||||||
|
> 前端要求 **PHP 8.4+**:旧版本已停止安全维护、存在已知 CVE,低于 8.4 时前端将拒绝运行并提示升级。
|
||||||
| Web服务器 | Nginx | 1.28+ |
|
| Web服务器 | Nginx | 1.28+ |
|
||||||
## 文件结构
|
## 文件结构
|
||||||
|
|
||||||
@@ -91,9 +97,11 @@ classmanager/
|
|||||||
│ │ ├── homework.py # 作业模型
|
│ │ ├── homework.py # 作业模型
|
||||||
│ │ ├── log.py # 日志模型
|
│ │ ├── log.py # 日志模型
|
||||||
│ │ ├── permission_group.py # 权限组模型(功能权限+加减分上限)
|
│ │ ├── permission_group.py # 权限组模型(功能权限+加减分上限)
|
||||||
|
│ │ ├── report.py # 统计报表模型
|
||||||
│ │ ├── semester.py # 学期模型
|
│ │ ├── semester.py # 学期模型
|
||||||
│ │ ├── student.py # 学生模型
|
│ │ ├── student.py # 学生模型
|
||||||
│ │ ├── subject.py # 科目模型
|
│ │ ├── subject.py # 科目模型
|
||||||
|
│ │ ├── system_setting.py # 系统设置模型(密码策略等)
|
||||||
│ │ └── user.py # 用户模型
|
│ │ └── user.py # 用户模型
|
||||||
│ │
|
│ │
|
||||||
│ ├── routes/ # API 路由
|
│ ├── routes/ # API 路由
|
||||||
@@ -102,6 +110,7 @@ classmanager/
|
|||||||
│ │ ├── auth.py # 认证接口
|
│ │ ├── auth.py # 认证接口
|
||||||
│ │ ├── debug.py # 调试入口
|
│ │ ├── debug.py # 调试入口
|
||||||
│ │ ├── parent.py # 家长端接口
|
│ │ ├── parent.py # 家长端接口
|
||||||
|
│ │ ├── report.py # 统计报表接口
|
||||||
│ │ ├── semester.py # 学期管理接口
|
│ │ ├── semester.py # 学期管理接口
|
||||||
│ │ ├── student.py # 学生端接口
|
│ │ ├── student.py # 学生端接口
|
||||||
│ │ └── subject.py # 科目管理接口
|
│ │ └── subject.py # 科目管理接口
|
||||||
@@ -124,9 +133,12 @@ classmanager/
|
|||||||
│ │ ├── auth_service.py
|
│ │ ├── auth_service.py
|
||||||
│ │ ├── conduct_service.py
|
│ │ ├── conduct_service.py
|
||||||
│ │ ├── homework_service.py
|
│ │ ├── homework_service.py
|
||||||
|
│ │ ├── holiday_service.py # 节假日接口服务(缓存+降级)
|
||||||
│ │ ├── log_service.py
|
│ │ ├── log_service.py
|
||||||
│ │ ├── parent_service.py
|
│ │ ├── parent_service.py
|
||||||
│ │ ├── semester_service.py # 学期服务
|
│ │ ├── report_service.py # 统计报表服务
|
||||||
|
│ │ ├── semester_service.py # 学期服务
|
||||||
|
│ │ ├── setting_service.py # 系统设置服务
|
||||||
│ │ ├── student_service.py
|
│ │ ├── student_service.py
|
||||||
│ │ └── subject_service.py
|
│ │ └── subject_service.py
|
||||||
│ │
|
│ │
|
||||||
@@ -156,9 +168,12 @@ classmanager/
|
|||||||
│ │ ├── dashboard.php # 管理端首页
|
│ │ ├── dashboard.php # 管理端首页
|
||||||
│ │ ├── history.php # 历史记录
|
│ │ ├── history.php # 历史记录
|
||||||
│ │ ├── homework.php # 作业管理
|
│ │ ├── homework.php # 作业管理
|
||||||
|
│ │ ├── logs.php # 操作日志
|
||||||
│ │ ├── password.php # 修改密码
|
│ │ ├── password.php # 修改密码
|
||||||
│ │ ├── record_query.php # 个人记录查询(基础分/月度分/理由汇总)
|
│ │ ├── record_query.php # 个人记录查询(基础分/月度分/理由汇总)
|
||||||
|
│ │ ├── reports.php # 数据报表(考勤/作业)
|
||||||
│ │ ├── semesters.php # 学期管理
|
│ │ ├── semesters.php # 学期管理
|
||||||
|
│ │ ├── settings.php # 系统设置(密码策略)
|
||||||
│ │ ├── students.php # 学生管理
|
│ │ ├── students.php # 学生管理
|
||||||
│ │ └── subjects.php # 科目管理
|
│ │ └── subjects.php # 科目管理
|
||||||
│ │
|
│ │
|
||||||
@@ -170,10 +185,12 @@ classmanager/
|
|||||||
│ │ │ ├── admin.css # 管理端样式
|
│ │ │ ├── admin.css # 管理端样式
|
||||||
│ │ │ └── style.css # 全局样式
|
│ │ │ └── style.css # 全局样式
|
||||||
│ │ ├── js/
|
│ │ ├── js/
|
||||||
│ │ │ ├── admin.js # 管理端 JS
|
|
||||||
│ │ │ ├── common.js # 公共 JS
|
│ │ │ ├── common.js # 公共 JS
|
||||||
|
│ │ │ ├── logs.js # 操作日志 JS
|
||||||
│ │ │ ├── parent.js # 家长端 JS
|
│ │ │ ├── parent.js # 家长端 JS
|
||||||
│ │ │ ├── record-query.js # 个人记录查询 JS
|
│ │ │ ├── record-query.js # 个人记录查询 JS
|
||||||
|
│ │ │ ├── reports.js # 数据报表 JS
|
||||||
|
│ │ │ ├── settings.js # 系统设置 JS
|
||||||
│ │ │ └── student.js # 学生端 JS
|
│ │ │ └── student.js # 学生端 JS
|
||||||
│ │ └── uploads/
|
│ │ └── uploads/
|
||||||
│ │ └── sample_import.json # 学生导入示例
|
│ │ └── sample_import.json # 学生导入示例
|
||||||
@@ -224,7 +241,7 @@ classmanager/
|
|||||||
| 项目 | 说明 |
|
| 项目 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| 权限模型 | 管理员账号绑定一个权限组;权限组由「功能权限 + 加减分上限」组成,可在管理端动态配置 |
|
| 权限模型 | 管理员账号绑定一个权限组;权限组由「功能权限 + 加减分上限」组成,可在管理端动态配置 |
|
||||||
| 预置权限组 | 班主任(锁定不可编辑)、班长、学习委员、考勤委员、劳动委员、志愿委员,默认权限如下表,上限可随时调整 |
|
| 预置权限组 | 系统预置六个权限组(班主任/班长/学习委员/考勤委员/劳动委员/志愿委员)作为初始模板,全部可编辑、删除、分配给任意账号 |
|
||||||
| 自定义权限组 | 可新建自定义组(如"纪律委员"),自由勾选 14 项功能权限并设置加分/扣分上限 |
|
| 自定义权限组 | 可新建自定义组(如"纪律委员"),自由勾选 14 项功能权限并设置加分/扣分上限 |
|
||||||
| 加减分上限 | 每项操作按权限组的"允许加分/加分上限/允许扣分/扣分上限"校验(前后端一致),留空表示无限制 |
|
| 加减分上限 | 每项操作按权限组的"允许加分/加分上限/允许扣分/扣分上限"校验(前后端一致),留空表示无限制 |
|
||||||
| 生效方式 | 权限组调整后,相关管理员刷新页面或最多 60 秒后自动生效 |
|
| 生效方式 | 权限组调整后,相关管理员刷新页面或最多 60 秒后自动生效 |
|
||||||
@@ -233,7 +250,7 @@ classmanager/
|
|||||||
|
|
||||||
| 权限组 | 操行分查看 | 操行分加减 | 撤销扣分 | 历史记录查看 | 其他权限 |
|
| 权限组 | 操行分查看 | 操行分加减 | 撤销扣分 | 历史记录查看 | 其他权限 |
|
||||||
|------|-----------|-----------|---------|-------------|---------|
|
|------|-----------|-----------|---------|-------------|---------|
|
||||||
| 班主任 | 全班 | 无限制 | 可撤销任何记录 | 全班所有记录 | 全部权限(锁定) |
|
| 班主任 | 全班 | 无限制 | 可撤销任何记录 | 全班所有记录 | 全部权限(可调整) |
|
||||||
| 班长 | 全班 | ±5分 | 可撤销任何记录 | 全班所有记录 | 个人查询 |
|
| 班长 | 全班 | ±5分 | 可撤销任何记录 | 全班所有记录 | 个人查询 |
|
||||||
| 学习委员 | 全班 | ±5分以内(加减分) | 不可撤销 | 仅自己提交的 | 作业管理、科目管理 |
|
| 学习委员 | 全班 | ±5分以内(加减分) | 不可撤销 | 仅自己提交的 | 作业管理、科目管理 |
|
||||||
| 考勤委员 | 全班 | 仅扣分,最多扣8分 | 仅撤销自己的记录 | 仅自己提交的 | 考勤管理 |
|
| 考勤委员 | 全班 | 仅扣分,最多扣8分 | 仅撤销自己的记录 | 仅自己提交的 | 考勤管理 |
|
||||||
@@ -290,7 +307,11 @@ classmanager/
|
|||||||
| v2.9 | 2026.6.8 | 历史记录表头优化:合并/非合并视图统一新增"类型"列(手动/作业/考勤),列顺序统一为"类型、分值、原因、学生、操作人、时间" |
|
| v2.9 | 2026.6.8 | 历史记录表头优化:合并/非合并视图统一新增"类型"列(手动/作业/考勤),列顺序统一为"类型、分值、原因、学生、操作人、时间" |
|
||||||
| v3.0 | 2026.9.17 | 导出按学期隔离(默认当前学期,可选历史/全部,历史导出不再受1000条限制);新增管理端"个人查询"页面(基础分/加分/减分/月度分/月度理由汇总/明细,可导出,支持学生列表直达);加减分与考勤记录自动关联当前学期,历史记录页新增学期筛选 |
|
| v3.0 | 2026.9.17 | 导出按学期隔离(默认当前学期,可选历史/全部,历史导出不再受1000条限制);新增管理端"个人查询"页面(基础分/加分/减分/月度分/月度理由汇总/明细,可导出,支持学生列表直达);加减分与考勤记录自动关联当前学期,历史记录页新增学期筛选 |
|
||||||
| v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 |
|
| v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 |
|
||||||
| v4.1 | 2026.9.17 | 管理员可绑定邮箱;新增找回密码(SMTP邮件重置链接,一次性、30分钟有效);登录页新增忘记密码入口,管理端支持添加/编辑管理员邮箱与自助绑定 |
|
| 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项功能权限可配置) |
|
||||||
|
|
||||||
## 许可证
|
## 许可证
|
||||||
|
|
||||||
|
|||||||
+6
-34
@@ -1,5 +1,5 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
# 班级操行分管理系统 - 前端配置
|
# 班级操行分管理系统 - 后端配置
|
||||||
#
|
#
|
||||||
# 开发者: Canglan
|
# 开发者: Canglan
|
||||||
# 联系方式: admin@sea-studio.top
|
# 联系方式: admin@sea-studio.top
|
||||||
@@ -35,7 +35,6 @@ DB_USER=class_admin
|
|||||||
DB_PASSWORD=your-strong-db-password
|
DB_PASSWORD=your-strong-db-password
|
||||||
DB_NAME=classmanagerdb
|
DB_NAME=classmanagerdb
|
||||||
DB_POOL_SIZE=10
|
DB_POOL_SIZE=10
|
||||||
DB_MAX_OVERFLOW=20
|
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
# Redis 缓存配置
|
# Redis 缓存配置
|
||||||
@@ -91,37 +90,6 @@ DEDUCTION_ATTENDANCE_LATE=1
|
|||||||
# 请假扣分 - 学生请假时扣除的操行分(设为0表示不扣分)
|
# 请假扣分 - 学生请假时扣除的操行分(设为0表示不扣分)
|
||||||
DEDUCTION_ATTENDANCE_LEAVE=0
|
DEDUCTION_ATTENDANCE_LEAVE=0
|
||||||
|
|
||||||
# ===========================================
|
|
||||||
# 劳动委员固定分值配置
|
|
||||||
# ===========================================
|
|
||||||
|
|
||||||
LABOR_POINTS_ADD=1
|
|
||||||
LABOR_POINTS_SUBTRACT=-1
|
|
||||||
|
|
||||||
# ===========================================
|
|
||||||
# 加减分上限配置(v4.0 起废弃)
|
|
||||||
#
|
|
||||||
# 各权限组的加减分上限改为在系统内「管理员管理 → 权限组」中动态配置,
|
|
||||||
# 以下环境变量不再生效,仅保留以兼容旧配置文件。
|
|
||||||
# ===========================================
|
|
||||||
|
|
||||||
# 班长单次加分上限
|
|
||||||
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
|
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
# 站点地址与 SMTP 邮件配置(管理员找回密码)
|
# 站点地址与 SMTP 邮件配置(管理员找回密码)
|
||||||
# ===========================================
|
# ===========================================
|
||||||
@@ -149,14 +117,18 @@ SMTP_SSL=true
|
|||||||
SMTP_STARTTLS=false
|
SMTP_STARTTLS=false
|
||||||
# 密码重置链接有效期(分钟)
|
# 密码重置链接有效期(分钟)
|
||||||
PASSWORD_RESET_EXPIRE_MINUTES=30
|
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_LEVEL=INFO
|
||||||
|
# 单文件日志大小上限(字节),超过后轮转
|
||||||
LOG_MAX_BYTES=104857600
|
LOG_MAX_BYTES=104857600
|
||||||
LOG_BACKUP_COUNT=30
|
|
||||||
LOG_RETENTION_DAYS=365
|
LOG_RETENTION_DAYS=365
|
||||||
|
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|||||||
+25
-25
@@ -13,14 +13,26 @@ import os
|
|||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from typing import List
|
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:
|
class Settings:
|
||||||
APP_NAME: str = os.getenv("APP_NAME", "班级操行分管理系统")
|
APP_NAME: str = os.getenv("APP_NAME", "班级操行分管理系统")
|
||||||
APP_ENV: str = os.getenv("APP_ENV", "production")
|
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", "")
|
SECRET_KEY: str = os.getenv("SECRET_KEY", "")
|
||||||
API_VERSION: str = os.getenv("API_VERSION", "v1")
|
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_HOST: str = os.getenv("DB_HOST", "127.0.0.1")
|
||||||
DB_PORT: int = int(os.getenv("DB_PORT", "3306"))
|
DB_PORT: int = int(os.getenv("DB_PORT", "3306"))
|
||||||
@@ -28,7 +40,6 @@ class Settings:
|
|||||||
DB_PASSWORD: str = os.getenv("DB_PASSWORD", "")
|
DB_PASSWORD: str = os.getenv("DB_PASSWORD", "")
|
||||||
DB_NAME: str = os.getenv("DB_NAME", "classmanagerdb")
|
DB_NAME: str = os.getenv("DB_NAME", "classmanagerdb")
|
||||||
DB_POOL_SIZE: int = int(os.getenv("DB_POOL_SIZE", "10"))
|
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_HOST: str = os.getenv("REDIS_HOST", "127.0.0.1")
|
||||||
REDIS_PORT: int = int(os.getenv("REDIS_PORT", "6379"))
|
REDIS_PORT: int = int(os.getenv("REDIS_PORT", "6379"))
|
||||||
@@ -48,23 +59,26 @@ class Settings:
|
|||||||
JWT_IDLE_TIMEOUT_MINUTES: int = int(os.getenv("JWT_IDLE_TIMEOUT_MINUTES", "10"))
|
JWT_IDLE_TIMEOUT_MINUTES: int = int(os.getenv("JWT_IDLE_TIMEOUT_MINUTES", "10"))
|
||||||
|
|
||||||
PASSWORD_SALT: str = os.getenv("PASSWORD_SALT", "")
|
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")
|
DEBUG_PATH: str = os.getenv("DEBUG_PATH", "/debug_add_admin")
|
||||||
|
|
||||||
# ========== 站点地址与邮件(找回密码) ==========
|
# ========== 站点地址与邮件(找回密码) ==========
|
||||||
# 前端站点地址,用于生成密码重置链接,如 https://class.example.com
|
# 前端站点地址,用于生成密码重置链接,如 https://class.example.com
|
||||||
FRONTEND_URL: str = os.getenv("FRONTEND_URL", "").rstrip("/")
|
FRONTEND_URL: str = os.getenv("FRONTEND_URL", "").rstrip("/")
|
||||||
SMTP_ENABLED: bool = os.getenv("SMTP_ENABLED", "False").lower() == "true"
|
SMTP_ENABLED: bool = _env_bool("SMTP_ENABLED", False)
|
||||||
SMTP_HOST: str = os.getenv("SMTP_HOST", "")
|
SMTP_HOST: str = os.getenv("SMTP_HOST", "").strip()
|
||||||
SMTP_PORT: int = int(os.getenv("SMTP_PORT", "465"))
|
SMTP_PORT: int = int(os.getenv("SMTP_PORT", "465"))
|
||||||
SMTP_USER: str = os.getenv("SMTP_USER", "")
|
SMTP_USER: str = os.getenv("SMTP_USER", "").strip()
|
||||||
SMTP_PASSWORD: str = os.getenv("SMTP_PASSWORD", "")
|
SMTP_PASSWORD: str = os.getenv("SMTP_PASSWORD", "")
|
||||||
SMTP_FROM: str = os.getenv("SMTP_FROM", "")
|
# 发件人邮箱默认与登录账号一致
|
||||||
|
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_FROM_NAME: str = os.getenv("SMTP_FROM_NAME", os.getenv("APP_NAME", "班级操行分管理系统"))
|
||||||
SMTP_SSL: bool = os.getenv("SMTP_SSL", "True").lower() == "true"
|
SMTP_SSL: bool = _env_bool("SMTP_SSL", True)
|
||||||
SMTP_STARTTLS: bool = os.getenv("SMTP_STARTTLS", "False").lower() == "true"
|
SMTP_STARTTLS: bool = _env_bool("SMTP_STARTTLS", False)
|
||||||
# 密码重置链接有效期(分钟)
|
# 密码重置链接有效期(分钟)
|
||||||
PASSWORD_RESET_EXPIRE_MINUTES: int = int(os.getenv("PASSWORD_RESET_EXPIRE_MINUTES", "30"))
|
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_NOT_SUBMIT: int = int(os.getenv("DEDUCTION_HOMEWORK_NOT_SUBMIT", "2"))
|
||||||
DEDUCTION_HOMEWORK_LATE: int = int(os.getenv("DEDUCTION_HOMEWORK_LATE", "1"))
|
DEDUCTION_HOMEWORK_LATE: int = int(os.getenv("DEDUCTION_HOMEWORK_LATE", "1"))
|
||||||
@@ -72,22 +86,8 @@ class Settings:
|
|||||||
DEDUCTION_ATTENDANCE_LATE: int = int(os.getenv("DEDUCTION_ATTENDANCE_LATE", "1"))
|
DEDUCTION_ATTENDANCE_LATE: int = int(os.getenv("DEDUCTION_ATTENDANCE_LATE", "1"))
|
||||||
DEDUCTION_ATTENDANCE_LEAVE: int = int(os.getenv("DEDUCTION_ATTENDANCE_LEAVE", "0"))
|
DEDUCTION_ATTENDANCE_LEAVE: int = int(os.getenv("DEDUCTION_ATTENDANCE_LEAVE", "0"))
|
||||||
|
|
||||||
LABOR_POINTS_ADD: int = int(os.getenv("LABOR_POINTS_ADD", "1"))
|
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "DEBUG" if _env_bool("DEBUG", False) else "INFO")
|
||||||
LABOR_POINTS_SUBTRACT: int = int(os.getenv("LABOR_POINTS_SUBTRACT", "-1"))
|
|
||||||
|
|
||||||
# 以下加减分上限自 v4.0 起废弃:权限组上限存于数据库 permission_groups 表,
|
|
||||||
# 通过「管理员管理 → 权限组」动态配置,保留字段仅为兼容旧 .env 文件。
|
|
||||||
MONITOR_MAX_ADD: int = int(os.getenv("MONITOR_MAX_ADD", "5"))
|
|
||||||
MONITOR_MAX_SUBTRACT: int = int(os.getenv("MONITOR_MAX_SUBTRACT", "-5"))
|
|
||||||
|
|
||||||
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_MAX_BYTES: int = int(os.getenv("LOG_MAX_BYTES", "104857600"))
|
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"))
|
LOG_RETENTION_DAYS: int = int(os.getenv("LOG_RETENTION_DAYS", "365"))
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|||||||
+26
-3
@@ -15,13 +15,15 @@ from fastapi.responses import JSONResponse
|
|||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
import traceback
|
import traceback
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
from pymysql import err as pymysql_err
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from utils.logger import setup_logger, log_access
|
from utils.logger import setup_logger, log_access
|
||||||
from utils.database import init_db_pool, close_db_pool
|
from utils.database import init_db_pool, close_db_pool
|
||||||
from utils.redis_client import init_redis_pool, close_redis_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 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
|
from routes.config import router as config_router
|
||||||
|
|
||||||
|
|
||||||
@@ -36,6 +38,15 @@ async def lifespan(app: FastAPI):
|
|||||||
await init_db_pool()
|
await init_db_pool()
|
||||||
await init_redis_pool()
|
await init_redis_pool()
|
||||||
logger.info(f"CORS 允许域名: {settings.CORS_ORIGINS}")
|
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} 启动完成")
|
logger.info(f"{settings.APP_NAME} 启动完成")
|
||||||
|
|
||||||
yield
|
yield
|
||||||
@@ -85,7 +96,18 @@ app.add_middleware(
|
|||||||
@app.exception_handler(Exception)
|
@app.exception_handler(Exception)
|
||||||
async def global_exception_handler(request: Request, exc: 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用于CORS头
|
||||||
origin = request.headers.get("origin", "")
|
origin = request.headers.get("origin", "")
|
||||||
@@ -104,7 +126,7 @@ async def global_exception_handler(request: Request, exc: Exception):
|
|||||||
content={
|
content={
|
||||||
"success": False,
|
"success": False,
|
||||||
"code": 500,
|
"code": 500,
|
||||||
"message": f"服务器内部错误: {str(exc)}",
|
"message": message,
|
||||||
"detail": traceback.format_exc() if settings.DEBUG else None
|
"detail": traceback.format_exc() if settings.DEBUG else None
|
||||||
},
|
},
|
||||||
headers=headers
|
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(admin.router, prefix="/api/admin", tags=["管理端"])
|
||||||
app.include_router(subject.router, prefix="/api/subject", tags=["科目管理"])
|
app.include_router(subject.router, prefix="/api/subject", tags=["科目管理"])
|
||||||
app.include_router(semester.router, prefix="/api/semester", 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(config_router, prefix="/api/config", tags=["配置"])
|
||||||
app.include_router(upgrade.router, prefix="/api/upgrade", tags=["升级管理"])
|
app.include_router(upgrade.router, prefix="/api/upgrade", tags=["升级管理"])
|
||||||
app.include_router(debug.router, tags=["调试"])
|
app.include_router(debug.router, tags=["调试"])
|
||||||
|
|||||||
@@ -11,19 +11,15 @@
|
|||||||
|
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
from starlette.responses import Response
|
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from typing import Optional, Dict, Any
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from utils.jwt_handler import jwt_handler
|
from utils.jwt_handler import jwt_handler
|
||||||
from utils.redis_client import RedisClient
|
from utils.redis_client import RedisClient
|
||||||
from utils.response import unauthorized_response
|
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
# 不需要认证的路由
|
# 不需要认证的路由
|
||||||
PUBLIC_PATHS = [
|
PUBLIC_PATHS = [
|
||||||
r'^/$',
|
r'^/$',
|
||||||
@@ -32,6 +28,7 @@ PUBLIC_PATHS = [
|
|||||||
r'^/api/auth/forgot-password$',
|
r'^/api/auth/forgot-password$',
|
||||||
r'^/api/auth/reset-password$',
|
r'^/api/auth/reset-password$',
|
||||||
r'^/api/auth/reset-token/check$',
|
r'^/api/auth/reset-token/check$',
|
||||||
|
r'^/api/config/deduction-rules$',
|
||||||
]
|
]
|
||||||
def is_public_path(path: str) -> bool:
|
def is_public_path(path: str) -> bool:
|
||||||
"""检查是否为公开路径"""
|
"""检查是否为公开路径"""
|
||||||
@@ -60,30 +57,30 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|||||||
logger.debug(f"[Auth] {request.method} {path} - 公开路径,跳过认证")
|
logger.debug(f"[Auth] {request.method} {path} - 公开路径,跳过认证")
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
logger.info(f"[Auth] {request.method} {path} - 开始认证")
|
logger.debug(f"[Auth] {request.method} {path} - 开始认证")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 获取Authorization头
|
# 获取Authorization头
|
||||||
auth_header = request.headers.get("Authorization")
|
auth_header = request.headers.get("Authorization")
|
||||||
|
|
||||||
if not auth_header:
|
if not auth_header:
|
||||||
logger.warning(f"[Auth] {path} - 缺少Authorization header")
|
logger.debug(f"[Auth] {path} - 缺少Authorization header")
|
||||||
return self._cors_response(request, 401, "缺少认证令牌")
|
return self._cors_response(request, 401, "缺少认证令牌")
|
||||||
|
|
||||||
# 解析Bearer Token
|
# 解析Bearer Token
|
||||||
try:
|
try:
|
||||||
scheme, token = auth_header.split()
|
scheme, token = auth_header.split()
|
||||||
if scheme.lower() != "bearer":
|
if scheme.lower() != "bearer":
|
||||||
logger.warning(f"[Auth] {path} - Authorization header格式错误")
|
logger.debug(f"[Auth] {path} - Authorization header格式错误")
|
||||||
return self._cors_response(request, 401, "认证格式错误")
|
return self._cors_response(request, 401, "认证格式错误")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
logger.warning(f"[Auth] {path} - Authorization header格式错误")
|
logger.debug(f"[Auth] {path} - Authorization header格式错误")
|
||||||
return self._cors_response(request, 401, "认证格式错误")
|
return self._cors_response(request, 401, "认证格式错误")
|
||||||
|
|
||||||
# 验证Token
|
# 验证Token
|
||||||
payload = jwt_handler.verify_token(token)
|
payload = jwt_handler.verify_token(token)
|
||||||
if not payload:
|
if not payload:
|
||||||
logger.warning(f"[Auth] {path} - JWT验证失败")
|
logger.debug(f"[Auth] {path} - JWT验证失败")
|
||||||
return self._cors_response(request, 401, "令牌无效或已过期")
|
return self._cors_response(request, 401, "令牌无效或已过期")
|
||||||
|
|
||||||
# 验证Redis中的Token
|
# 验证Redis中的Token
|
||||||
@@ -91,7 +88,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
|||||||
stored_token = await RedisClient.get_user_token(user_id)
|
stored_token = await RedisClient.get_user_token(user_id)
|
||||||
|
|
||||||
if not stored_token or stored_token != token:
|
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, "令牌已失效,请重新登录")
|
return self._cors_response(request, 401, "令牌已失效,请重新登录")
|
||||||
|
|
||||||
# 将用户信息存储到request.state
|
# 将用户信息存储到request.state
|
||||||
|
|||||||
@@ -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,6 +11,10 @@
|
|||||||
|
|
||||||
from typing import Optional, Dict, Any, List
|
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
|
||||||
|
from utils.logger import get_logger
|
||||||
|
from models.permission_group import apply_legacy_group_fields
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class AdminRoleModel:
|
class AdminRoleModel:
|
||||||
@@ -30,7 +34,19 @@ class AdminRoleModel:
|
|||||||
WHERE ar.user_id = %s
|
WHERE ar.user_id = %s
|
||||||
LIMIT 1
|
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
|
@staticmethod
|
||||||
async def get_all() -> List[Dict[str, Any]]:
|
async def get_all() -> List[Dict[str, Any]]:
|
||||||
@@ -45,7 +61,20 @@ class AdminRoleModel:
|
|||||||
LEFT JOIN permission_groups pg ON ar.group_id = pg.group_id
|
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
|
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
|
@staticmethod
|
||||||
async def create(
|
async def create(
|
||||||
@@ -60,12 +89,6 @@ class AdminRoleModel:
|
|||||||
"""
|
"""
|
||||||
return await execute_insert(sql, (user_id, role_type, group_id, 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
|
@staticmethod
|
||||||
async def update_role(
|
async def update_role(
|
||||||
user_id: int,
|
user_id: int,
|
||||||
|
|||||||
@@ -9,8 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Optional, Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
from datetime import datetime
|
|
||||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||||
|
|
||||||
|
|
||||||
@@ -41,9 +40,22 @@ class AttendanceModel:
|
|||||||
slot: str = None
|
slot: str = None
|
||||||
) -> List[Dict[str, Any]]:
|
) -> List[Dict[str, Any]]:
|
||||||
sql = """
|
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
|
FROM attendance_records ar
|
||||||
JOIN students s ON ar.student_id = s.student_id
|
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
|
WHERE 1=1
|
||||||
"""
|
"""
|
||||||
params = []
|
params = []
|
||||||
@@ -98,7 +110,68 @@ class AttendanceModel:
|
|||||||
return await execute_insert(sql, (student_id, date, slot, status, reason, recorder_id, semester_id))
|
return await execute_insert(sql, (student_id, date, slot, status, reason, recorder_id, semester_id))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def mark_deduction_applied(attendance_id: int) -> bool:
|
async def mark_deduction_applied(attendance_id: int, deduction_record_id: int = None) -> bool:
|
||||||
sql = "UPDATE attendance_records SET deduction_applied = 1 WHERE attendance_id = %s"
|
"""标记考勤已扣分,并记录关联的扣分记录ID"""
|
||||||
result = await execute_update(sql, (attendance_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
|
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
|
||||||
@@ -10,7 +10,6 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Optional, List, Dict, Any
|
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.database import execute_one, execute_query, execute_insert, execute_update
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
@@ -455,36 +454,3 @@ class ConductModel:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"恢复记录失败: {e}")
|
logger.error(f"恢复记录失败: {e}")
|
||||||
return False
|
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
|
# 版权所有 © 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
|
from utils.logger import get_logger
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
@@ -62,3 +63,81 @@ class OperationLogModel:
|
|||||||
"""
|
"""
|
||||||
return await execute_insert(sql, (operator_id, operator_name, operator_role,
|
return await execute_insert(sql, (operator_id, operator_name, operator_role,
|
||||||
operation_type, target_type, target_id, details, ip_address))
|
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]
|
||||||
@@ -26,22 +26,92 @@ PERMISSION_KEYS = [
|
|||||||
"revoke_own", # 仅撤销自己提交的记录
|
"revoke_own", # 仅撤销自己提交的记录
|
||||||
"restore_records", # 反撤销记录
|
"restore_records", # 反撤销记录
|
||||||
"manage_homework", # 作业扣分
|
"manage_homework", # 作业扣分
|
||||||
|
"homework_register", # 作业按次登记
|
||||||
"manage_attendance", # 考勤管理
|
"manage_attendance", # 考勤管理
|
||||||
|
"default_attendance", # 考勤默认出勤(批量补全)
|
||||||
|
"manage_calendar", # 节假日/补课校历设置
|
||||||
"manage_subjects", # 科目管理
|
"manage_subjects", # 科目管理
|
||||||
"manage_admins", # 管理员与权限组管理
|
"manage_admins", # 管理员与权限组管理
|
||||||
"manage_semesters", # 学期管理
|
"manage_semesters", # 学期管理
|
||||||
"view_all_records", # 查看全班记录/个人查询
|
"view_all_records", # 查看全班记录/个人查询
|
||||||
|
"view_reports", # 数据报表查看(考勤/作业统计)
|
||||||
"export_data", # 导出德育分记录/历史记录
|
"export_data", # 导出德育分记录/历史记录
|
||||||
|
"view_logs", # 操作日志查看
|
||||||
|
"manage_settings", # 系统设置(密码策略等)
|
||||||
"manage_upgrade", # 系统升级
|
"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:
|
class PermissionGroupModel:
|
||||||
"""权限组数据模型"""
|
"""权限组数据模型"""
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def parse_group(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
def parse_group(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||||
"""解析权限组数据(JSON字符串 -> 布尔字典)"""
|
"""解析权限组数据(JSON字符串 -> 布尔字典)
|
||||||
|
|
||||||
|
存储中缺失的权限项:预置权限组按预设默认值补齐,其余按 False。
|
||||||
|
这样新增权限项无需数据库迁移即可对预置组生效。
|
||||||
|
"""
|
||||||
if not row:
|
if not row:
|
||||||
return row
|
return row
|
||||||
raw = row.get("permissions")
|
raw = row.get("permissions")
|
||||||
@@ -54,7 +124,11 @@ class PermissionGroupModel:
|
|||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
logger.warning(f"权限组[{row.get('group_id')}]权限配置解析失败")
|
logger.warning(f"权限组[{row.get('group_id')}]权限配置解析失败")
|
||||||
parsed = {}
|
parsed = {}
|
||||||
row["permissions_data"] = {key: bool(parsed.get(key, False)) for key in PERMISSION_KEYS}
|
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_add_points"] = bool(row.get("can_add_points"))
|
||||||
row["can_subtract_points"] = bool(row.get("can_subtract_points"))
|
row["can_subtract_points"] = bool(row.get("can_subtract_points"))
|
||||||
return row
|
return row
|
||||||
@@ -73,14 +147,25 @@ class PermissionGroupModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_all() -> List[Dict[str, Any]]:
|
async def get_all() -> List[Dict[str, Any]]:
|
||||||
rows = await execute_query(
|
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
|
SELECT pg.*, (SELECT COUNT(*) FROM admin_roles ar WHERE ar.group_id = pg.group_id) AS member_count
|
||||||
ORDER BY pg.is_locked DESC, pg.is_system DESC, pg.group_id ASC
|
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]
|
)
|
||||||
|
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
|
@staticmethod
|
||||||
async def create(
|
async def create(
|
||||||
@@ -120,7 +205,7 @@ class PermissionGroupModel:
|
|||||||
SET group_name = %s, description = %s, permissions = %s,
|
SET group_name = %s, description = %s, permissions = %s,
|
||||||
can_add_points = %s, max_add_points = %s,
|
can_add_points = %s, max_add_points = %s,
|
||||||
can_subtract_points = %s, max_subtract_points = %s
|
can_subtract_points = %s, max_subtract_points = %s
|
||||||
WHERE group_id = %s AND is_locked = 0
|
WHERE group_id = %s
|
||||||
"""
|
"""
|
||||||
result = await execute_update(sql, (
|
result = await execute_update(sql, (
|
||||||
group_name, description or None, json.dumps(permissions, ensure_ascii=False),
|
group_name, description or None, json.dumps(permissions, ensure_ascii=False),
|
||||||
@@ -133,7 +218,7 @@ class PermissionGroupModel:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
async def delete(group_id: int) -> bool:
|
async def delete(group_id: int) -> bool:
|
||||||
result = await execute_update(
|
result = await execute_update(
|
||||||
"DELETE FROM permission_groups WHERE group_id = %s AND is_system = 0 AND is_locked = 0",
|
"DELETE FROM permission_groups WHERE group_id = %s",
|
||||||
(group_id,)
|
(group_id,)
|
||||||
)
|
)
|
||||||
return result > 0
|
return result > 0
|
||||||
@@ -147,7 +232,7 @@ class PermissionGroupModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_by_user_id(user_id: int) -> Optional[Dict[str, Any]]:
|
async def get_by_user_id(user_id: int) -> Optional[Dict[str, Any]]:
|
||||||
"""获取用户绑定权限组(兼容仅有 role_type 的旧数据)"""
|
"""获取用户绑定权限组(兼容仅有 role_type 的旧数据/未升级数据库)"""
|
||||||
sql = """
|
sql = """
|
||||||
SELECT ar.role_type,
|
SELECT ar.role_type,
|
||||||
pg.group_id, pg.group_name, pg.description, pg.permissions,
|
pg.group_id, pg.group_name, pg.description, pg.permissions,
|
||||||
@@ -159,7 +244,20 @@ class PermissionGroupModel:
|
|||||||
WHERE ar.user_id = %s
|
WHERE ar.user_id = %s
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
"""
|
"""
|
||||||
row = await execute_one(sql, (user_id,))
|
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:
|
if not row:
|
||||||
return None
|
return None
|
||||||
if not row.get("group_id") and row.get("role_type"):
|
if not row.get("group_id") and row.get("role_type"):
|
||||||
|
|||||||
@@ -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,))
|
result = await execute_one(sql, (record_id,))
|
||||||
return result['semester_id'] if result else None
|
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
|
@staticmethod
|
||||||
async def get_attendance_stats_by_semester(semester_id: int, start_date: str, end_date: str) -> List[Dict]:
|
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 typing import Optional, List, Dict, Any
|
||||||
from utils.database import execute_one, execute_query, execute_insert, execute_update, execute_many
|
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||||
from utils.security import security
|
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
@@ -171,6 +170,32 @@ class StudentModel:
|
|||||||
row['rank'] = i + 1
|
row['rank'] = i + 1
|
||||||
return results
|
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
|
@staticmethod
|
||||||
async def get_total_count() -> int:
|
async def get_total_count() -> int:
|
||||||
"""获取活跃学生总数"""
|
"""获取活跃学生总数"""
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Optional, Dict, Any, List
|
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:
|
class SubjectModel:
|
||||||
@@ -67,7 +67,20 @@ class SubjectModel:
|
|||||||
params.append(subject_id)
|
params.append(subject_id)
|
||||||
sql = f"UPDATE subjects SET {', '.join(updates)} WHERE subject_id = %s"
|
sql = f"UPDATE subjects SET {', '.join(updates)} WHERE subject_id = %s"
|
||||||
result = await execute_update(sql, tuple(params))
|
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
|
@staticmethod
|
||||||
async def has_related_data(subject_id: int) -> bool:
|
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
|
||||||
+49
-19
@@ -1,4 +1,4 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
# 班级操行分管理系统 - 后端服务
|
# 班级操行分管理系统 - 后端服务
|
||||||
#
|
#
|
||||||
# 开发者: Canglan
|
# 开发者: Canglan
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
from utils.database import execute_one, execute_insert, execute_update
|
from utils.database import execute_one, execute_insert, execute_update
|
||||||
from utils.security import security
|
from utils.security import security
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
@@ -21,9 +22,9 @@ class UserModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_by_username(username: str) -> dict:
|
async def get_by_username(username: str) -> dict:
|
||||||
"""根据用户名获取用户"""
|
"""根据用户名获取用户(登录主链路,不查询邮箱)"""
|
||||||
sql = """
|
sql = """
|
||||||
SELECT user_id, username, password_hash, real_name, email, user_type,
|
SELECT user_id, username, password_hash, real_name, user_type,
|
||||||
student_id, status, need_change_password, last_login_time, last_login_ip
|
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||||
FROM users
|
FROM users
|
||||||
WHERE username = %s AND status = 1
|
WHERE username = %s AND status = 1
|
||||||
@@ -32,15 +33,21 @@ class UserModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_by_user_id(user_id: int) -> dict:
|
async def get_by_user_id(user_id: int) -> dict:
|
||||||
"""根据用户ID获取用户"""
|
"""根据用户ID获取用户(不查询邮箱)"""
|
||||||
sql = """
|
sql = """
|
||||||
SELECT user_id, username, password_hash, real_name, email, user_type, student_id,
|
SELECT user_id, username, password_hash, real_name, user_type, student_id,
|
||||||
need_change_password, status
|
need_change_password, status
|
||||||
FROM users
|
FROM users
|
||||||
WHERE user_id = %s
|
WHERE user_id = %s
|
||||||
"""
|
"""
|
||||||
return await execute_one(sql, (user_id,))
|
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
|
@staticmethod
|
||||||
async def create_student(username: str, password: str, real_name: str, student_id: int) -> int:
|
async def create_student(username: str, password: str, real_name: str, student_id: int) -> int:
|
||||||
"""创建学生账号"""
|
"""创建学生账号"""
|
||||||
@@ -63,24 +70,54 @@ class UserModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def create_admin(username: str, password: str, real_name: str, email: str = None) -> int:
|
async def create_admin(username: str, password: str, real_name: str, email: str = None) -> int:
|
||||||
"""创建管理员账号"""
|
"""创建管理员账号(不传邮箱时不写 email 列)"""
|
||||||
password_hash = security.bcrypt_password(password)
|
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 = """
|
sql = """
|
||||||
INSERT INTO users (username, password_hash, real_name, email, user_type, need_change_password)
|
INSERT INTO users (username, password_hash, real_name, user_type, need_change_password)
|
||||||
VALUES (%s, %s, %s, %s, 'admin', 1)
|
VALUES (%s, %s, %s, 'admin', 1)
|
||||||
"""
|
"""
|
||||||
return await execute_insert(sql, (username, password_hash, real_name, email))
|
return await execute_insert(sql, (username, password_hash, real_name))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def update_password(user_id: int, new_password: str) -> bool:
|
async def update_password(user_id: int, new_password: str) -> bool:
|
||||||
"""更新密码"""
|
"""更新密码(加密失败会抛出异常;rowcount 为 0 时再确认用户是否存在)"""
|
||||||
password_hash = security.bcrypt_password(new_password)
|
try:
|
||||||
|
password_hash = security.bcrypt_password(new_password)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"密码加密失败: {e}")
|
||||||
|
raise
|
||||||
sql = """
|
sql = """
|
||||||
UPDATE users
|
UPDATE users
|
||||||
SET password_hash = %s, need_change_password = 0
|
SET password_hash = %s, need_change_password = 0
|
||||||
WHERE user_id = %s
|
WHERE user_id = %s
|
||||||
"""
|
"""
|
||||||
result = await execute_update(sql, (password_hash, user_id))
|
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
|
return result > 0
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -97,20 +134,13 @@ class UserModel:
|
|||||||
async def get_by_username_any(username: str) -> dict:
|
async def get_by_username_any(username: str) -> dict:
|
||||||
"""根据用户名获取用户(含已禁用)"""
|
"""根据用户名获取用户(含已禁用)"""
|
||||||
sql = """
|
sql = """
|
||||||
SELECT user_id, username, password_hash, real_name, email, user_type,
|
SELECT user_id, username, password_hash, real_name, user_type,
|
||||||
student_id, status, need_change_password, last_login_time, last_login_ip
|
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||||
FROM users
|
FROM users
|
||||||
WHERE username = %s
|
WHERE username = %s
|
||||||
"""
|
"""
|
||||||
return await execute_one(sql, (username,))
|
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
|
@staticmethod
|
||||||
async def update_status(user_id: int, status: int) -> bool:
|
async def update_status(user_id: int, status: int) -> bool:
|
||||||
"""更新用户状态(0=禁用,1=启用)"""
|
"""更新用户状态(0=禁用,1=启用)"""
|
||||||
|
|||||||
+361
-18
@@ -10,7 +10,7 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from fastapi import APIRouter, Request, Query, UploadFile, File
|
from fastapi import APIRouter, Request, Query, UploadFile, File
|
||||||
from typing import Optional, List
|
from typing import Optional
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from middleware.permission import (
|
from middleware.permission import (
|
||||||
@@ -20,16 +20,23 @@ from middleware.permission import (
|
|||||||
from services.admin_service import AdminService
|
from services.admin_service import AdminService
|
||||||
from services.conduct_service import ConductService
|
from services.conduct_service import ConductService
|
||||||
from services.attendance_service import AttendanceService
|
from services.attendance_service import AttendanceService
|
||||||
|
from services.homework_service import HomeworkService
|
||||||
from services.log_service import LogService
|
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 utils.redis_client import RedisClient
|
||||||
from schemas.admin import (
|
from schemas.admin import (
|
||||||
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
||||||
AddStudentRequest, UpdateStudentRequest,
|
AddStudentRequest, UpdateStudentRequest,
|
||||||
AddAttendanceRequest,
|
AddAttendanceRequest, DefaultAttendanceRequest, FullDayLeaveRequest, CalendarDayRequest,
|
||||||
UpdateAdminRequest, DeleteAdminRequest, ResetPasswordRequest,
|
HomeworkRegisterRequest,
|
||||||
UnlockUserRequest, PermissionGroupRequest
|
UpdateAdminRequest, ResetPasswordRequest,
|
||||||
|
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
||||||
|
PasswordPolicyRequest
|
||||||
)
|
)
|
||||||
from utils.response import success_response, error_response
|
from utils.response import success_response, error_response
|
||||||
|
from utils.validators import is_valid_email
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
from config import settings
|
from config import settings
|
||||||
|
|
||||||
@@ -37,6 +44,19 @@ router = APIRouter()
|
|||||||
logger = get_logger(__name__)
|
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")
|
@router.get("/students/dormitories")
|
||||||
@@ -64,6 +84,14 @@ async def get_students(
|
|||||||
if user["user_type"] != "admin":
|
if user["user_type"] != "admin":
|
||||||
return error_response(message="仅管理员可查看学生列表", code=403)
|
return error_response(message="仅管理员可查看学生列表", code=403)
|
||||||
result = await AdminService.get_students(page=page, page_size=page_size, search=search, dormitory_number=dormitory_number)
|
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)
|
return success_response(data=result)
|
||||||
|
|
||||||
|
|
||||||
@@ -233,7 +261,10 @@ async def add_conduct_points(request: Request, req: AddPointsRequest):
|
|||||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||||
operator_role=role, operation_type="add_points",
|
operator_role=role, operation_type="add_points",
|
||||||
target_type="conduct",
|
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
|
ip=request.client.host
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -257,15 +288,18 @@ async def revoke_conduct_record(request: Request, req: RevokeRequest):
|
|||||||
if result["success"]:
|
if result["success"]:
|
||||||
role = await PermissionChecker.get_user_role(user["user_id"])
|
role = await PermissionChecker.get_user_role(user["user_id"])
|
||||||
record = result.get("record", {})
|
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(
|
await LogService.write_operation_log(
|
||||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||||
operator_role=role, operation_type="revoke_record",
|
operator_role=role, operation_type="revoke_record",
|
||||||
target_type="conduct", target_id=req.record_id,
|
target_type="conduct", target_id=req.record_id,
|
||||||
details=(
|
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"原操作人: {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
|
ip=request.client.host
|
||||||
)
|
)
|
||||||
@@ -287,15 +321,18 @@ async def restore_conduct_record(request: Request, req: RevokeRequest):
|
|||||||
)
|
)
|
||||||
if result["success"]:
|
if result["success"]:
|
||||||
record = result.get("record", {})
|
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(
|
await LogService.write_operation_log(
|
||||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||||
operator_role=(await PermissionChecker.get_user_role(user["user_id"]) or "管理员"), 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,
|
target_type="conduct", target_id=req.record_id,
|
||||||
details=(
|
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"原操作人: {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
|
ip=request.client.host
|
||||||
)
|
)
|
||||||
@@ -398,6 +435,19 @@ async def batch_revoke_conduct_records(request: Request):
|
|||||||
fail_count += 1
|
fail_count += 1
|
||||||
errors.append({"record_id": record_id, "error": result["message"]})
|
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={
|
return success_response(data={
|
||||||
"success_count": success_count,
|
"success_count": success_count,
|
||||||
"fail_count": fail_count,
|
"fail_count": fail_count,
|
||||||
@@ -438,6 +488,19 @@ async def batch_restore_conduct_records(request: Request):
|
|||||||
fail_count += 1
|
fail_count += 1
|
||||||
errors.append({"record_id": record_id, "error": result["message"]})
|
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={
|
return success_response(data={
|
||||||
"success_count": success_count,
|
"success_count": success_count,
|
||||||
"fail_count": fail_count,
|
"fail_count": fail_count,
|
||||||
@@ -501,6 +564,171 @@ async def get_attendance_records(
|
|||||||
return success_response(data=result)
|
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")
|
@router.post("/add")
|
||||||
@@ -645,21 +873,43 @@ async def delete_permission_group(request: Request, group_id: int):
|
|||||||
return error_response(message=result["message"])
|
return error_response(message=result["message"])
|
||||||
|
|
||||||
|
|
||||||
@router.put("/update/{user_id}")
|
@router.post("/email/test")
|
||||||
async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
async def send_test_email(request: Request, req: EmailTestRequest):
|
||||||
"""更新管理员信息"""
|
"""发送测试邮件(验证 SMTP 配置)"""
|
||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||||
return error_response(message="无管理员管理权限", code=403)
|
return error_response(message="无管理员管理权限", code=403)
|
||||||
if user_id == user["user_id"]:
|
from utils.email_sender import EmailSender
|
||||||
return error_response(message="不能修改当前登录管理员的权限组", code=400)
|
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(
|
result = await AdminService.update_admin(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
real_name=req.real_name,
|
real_name=req.real_name,
|
||||||
group_id=req.group_id,
|
group_id=req.group_id,
|
||||||
operator_id=user["user_id"],
|
operator_id=user["user_id"],
|
||||||
email=req.email
|
email=req.email,
|
||||||
|
keep_group=is_self
|
||||||
)
|
)
|
||||||
if result["success"]:
|
if result["success"]:
|
||||||
await LogService.write_operation_log(
|
await LogService.write_operation_log(
|
||||||
@@ -667,7 +917,11 @@ async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
|||||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||||
operation_type="update_admin",
|
operation_type="update_admin",
|
||||||
target_type="admin", target_id=user_id,
|
target_type="admin", target_id=user_id,
|
||||||
details=f"更新管理员姓名: {req.real_name}, 权限组ID: {req.group_id}",
|
details=(
|
||||||
|
f"更新管理员姓名: {req.real_name}(本人账号,权限组不变)"
|
||||||
|
if is_self else
|
||||||
|
f"更新管理员姓名: {req.real_name}, 权限组ID: {req.group_id}"
|
||||||
|
),
|
||||||
ip=request.client.host
|
ip=request.client.host
|
||||||
)
|
)
|
||||||
return success_response(message="管理员更新成功")
|
return success_response(message="管理员更新成功")
|
||||||
@@ -731,9 +985,18 @@ async def reset_admin_password(request: Request, user_id: int, req: ResetPasswor
|
|||||||
if target_user["user_type"] != "admin":
|
if target_user["user_type"] != "admin":
|
||||||
return error_response(message="只能重置管理员密码", code=400)
|
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 内部会进行哈希)
|
# 使用传入的新密码(UserModel.update_password 内部会进行哈希)
|
||||||
updated = await UserModel.update_password(user_id, req.new_password)
|
updated = await UserModel.update_password(user_id, req.new_password)
|
||||||
if updated:
|
if updated:
|
||||||
|
# 重置后下次登录需重新设置密码(无需原密码)
|
||||||
|
await execute_update(
|
||||||
|
"UPDATE users SET need_change_password = 1 WHERE user_id = %s",
|
||||||
|
(user_id,)
|
||||||
|
)
|
||||||
await LogService.write_operation_log(
|
await LogService.write_operation_log(
|
||||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||||
@@ -771,3 +1034,83 @@ async def unlock_user(request: Request, req: UnlockUserRequest):
|
|||||||
ip=request.client.host
|
ip=request.client.host
|
||||||
)
|
)
|
||||||
return success_response(message=f"已解除用户 {req.username} 的登录锁定")
|
return success_response(message=f"已解除用户 {req.username} 的登录锁定")
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 系统设置 ==========
|
||||||
|
|
||||||
|
@router.get("/settings/password-policy")
|
||||||
|
async def get_password_policy(request: Request):
|
||||||
|
"""获取密码策略"""
|
||||||
|
user = await get_current_user(request)
|
||||||
|
if not await PermissionChecker.check_permission(user["user_id"], "manage_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)
|
||||||
+60
-11
@@ -9,16 +9,16 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from fastapi import APIRouter, Request, HTTPException
|
from fastapi import APIRouter, Request
|
||||||
from typing import Dict, Any
|
|
||||||
|
|
||||||
from schemas.auth import (
|
from schemas.auth import (
|
||||||
LoginRequest, ChangePasswordRequest,
|
LoginRequest, ChangePasswordRequest, InitPasswordRequest,
|
||||||
ForgotPasswordRequest, ResetPasswordRequest, BindEmailRequest
|
ForgotPasswordRequest, ResetPasswordRequest,
|
||||||
|
SendEmailCodeRequest, ConfirmBindEmailRequest, UnbindEmailRequest
|
||||||
)
|
)
|
||||||
from services.auth_service import AuthService
|
from services.auth_service import AuthService
|
||||||
from middleware.permission import get_current_user
|
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
|
from utils.logger import get_logger
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -53,7 +53,6 @@ async def login(request: LoginRequest, http_request: Request):
|
|||||||
"role": result.get("role"),
|
"role": result.get("role"),
|
||||||
"permissions": result.get("permissions", {}),
|
"permissions": result.get("permissions", {}),
|
||||||
"group": result.get("group"),
|
"group": result.get("group"),
|
||||||
"email": result.get("email"),
|
|
||||||
"need_change_password": result["need_change_password"],
|
"need_change_password": result["need_change_password"],
|
||||||
"redirect": result["redirect"]
|
"redirect": result["redirect"]
|
||||||
},
|
},
|
||||||
@@ -99,6 +98,22 @@ async def change_password(request: Request, req: ChangePasswordRequest):
|
|||||||
return error_response(message=result["message"])
|
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")
|
@router.get("/me")
|
||||||
async def get_current_user_info(request: Request):
|
async def get_current_user_info(request: Request):
|
||||||
"""
|
"""
|
||||||
@@ -148,19 +163,53 @@ async def reset_password_by_token(request: Request, req: ResetPasswordRequest):
|
|||||||
return error_response(message=result["message"], code=400)
|
return error_response(message=result["message"], code=400)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/bind-email")
|
@router.post("/email/send-code")
|
||||||
async def bind_email(request: Request, req: BindEmailRequest):
|
async def send_bind_email_code(request: Request, req: SendEmailCodeRequest):
|
||||||
"""
|
"""
|
||||||
管理员绑定/修改绑定邮箱(需验证当前密码)
|
发送邮箱绑定验证码(验证码发送至待绑定邮箱)
|
||||||
"""
|
"""
|
||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
if user["user_type"] != "admin":
|
if user["user_type"] != "admin":
|
||||||
return error_response(message="仅管理员可绑定邮箱", code=403)
|
return error_response(message="仅管理员可绑定邮箱", code=403)
|
||||||
result = await AuthService.bind_email(
|
result = await AuthService.send_bind_email_code(
|
||||||
user_id=user["user_id"],
|
user_id=user["user_id"],
|
||||||
password=req.password,
|
|
||||||
email=req.email
|
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"]:
|
if result["success"]:
|
||||||
return success_response(data={"email": result.get("email")}, message=result["message"])
|
return success_response(data={"email": result.get("email")}, message=result["message"])
|
||||||
return error_response(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 fastapi import APIRouter
|
||||||
from config import settings
|
from config import settings
|
||||||
|
from services.setting_service import SettingService
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
|
from utils.logger import get_logger
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
@router.get("/deduction-rules")
|
@router.get("/deduction-rules")
|
||||||
async def 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 = {
|
data = {
|
||||||
"DEDUCTION_HOMEWORK_NOT_SUBMIT": settings.DEDUCTION_HOMEWORK_NOT_SUBMIT,
|
"DEDUCTION_HOMEWORK_NOT_SUBMIT": settings.DEDUCTION_HOMEWORK_NOT_SUBMIT,
|
||||||
"DEDUCTION_HOMEWORK_LATE": settings.DEDUCTION_HOMEWORK_LATE,
|
"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_LATE": settings.DEDUCTION_ATTENDANCE_LATE,
|
||||||
"DEDUCTION_ATTENDANCE_LEAVE": settings.DEDUCTION_ATTENDANCE_LEAVE,
|
"DEDUCTION_ATTENDANCE_LEAVE": settings.DEDUCTION_ATTENDANCE_LEAVE,
|
||||||
"STUDENT_INITIAL_POINTS": settings.STUDENT_INITIAL_POINTS,
|
"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)
|
return success_response(data=data)
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
|
|
||||||
from fastapi import APIRouter, Request
|
from fastapi import APIRouter, Request
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import Optional, List
|
from typing import Optional
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from services.admin_service import AdminService
|
from services.admin_service import AdminService
|
||||||
@@ -45,7 +45,11 @@ async def debug_add_admin(request: Request, req: AddAdminDebugRequest):
|
|||||||
from models.permission_group import PermissionGroupModel
|
from models.permission_group import PermissionGroupModel
|
||||||
|
|
||||||
valid_roles = ["班主任", "班长", "学习委员", "考勤委员", "劳动委员", "志愿委员"]
|
valid_roles = ["班主任", "班长", "学习委员", "考勤委员", "劳动委员", "志愿委员"]
|
||||||
group = await PermissionGroupModel.get_by_name(req.role_type)
|
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:
|
if not group and req.role_type not in valid_roles:
|
||||||
return error_response(message=f"无效的权限组,可选: {', '.join(valid_roles)} 或已有自定义权限组")
|
return error_response(message=f"无效的权限组,可选: {', '.join(valid_roles)} 或已有自定义权限组")
|
||||||
if not group:
|
if not group:
|
||||||
@@ -60,8 +64,7 @@ async def debug_add_admin(request: Request, req: AddAdminDebugRequest):
|
|||||||
real_name=req.real_name,
|
real_name=req.real_name,
|
||||||
password=req.password,
|
password=req.password,
|
||||||
group_id=group["group_id"],
|
group_id=group["group_id"],
|
||||||
operator_id=0,
|
operator_id=0
|
||||||
allow_locked=True
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if result["success"]:
|
if result["success"]:
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from fastapi import APIRouter, Request, Query
|
from fastapi import APIRouter, Request, Query
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from middleware.permission import get_current_user
|
from middleware.permission import get_current_user
|
||||||
from services.parent_service import ParentService
|
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)}")
|
||||||
@@ -10,7 +10,6 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from fastapi import APIRouter, Request, Query
|
from fastapi import APIRouter, Request, Query
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from middleware.permission import (
|
from middleware.permission import (
|
||||||
get_current_user,
|
get_current_user,
|
||||||
|
|||||||
+22
-11
@@ -12,7 +12,7 @@
|
|||||||
from fastapi import APIRouter, Request, Query
|
from fastapi import APIRouter, Request, Query
|
||||||
from typing import Optional
|
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 services.student_service import StudentService
|
||||||
from utils.response import success_response, error_response
|
from utils.response import success_response, error_response
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
@@ -21,6 +21,15 @@ router = APIRouter()
|
|||||||
logger = get_logger(__name__)
|
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}")
|
@router.get("/conduct/{student_id}")
|
||||||
async def get_conduct_history(
|
async def get_conduct_history(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -34,9 +43,9 @@ async def get_conduct_history(
|
|||||||
try:
|
try:
|
||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
|
|
||||||
# 权限检查:只能查看自己的信息(学生)或同班(管理员)
|
# 权限检查:学生只能查看本人;管理员需查看全班权限
|
||||||
if user["user_type"] == "student" and user["student_id"] != student_id:
|
if not await _check_view_permission(user, student_id):
|
||||||
return error_response(message="无权查看其他学生信息", code=403)
|
return error_response(message="无权查看该学生信息", code=403)
|
||||||
|
|
||||||
result = await StudentService.get_conduct_history(
|
result = await StudentService.get_conduct_history(
|
||||||
student_id=student_id,
|
student_id=student_id,
|
||||||
@@ -58,8 +67,8 @@ async def get_homework_status(request: Request, student_id: int):
|
|||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
|
|
||||||
# 权限检查
|
# 权限检查
|
||||||
if user["user_type"] == "student" and user["student_id"] != student_id:
|
if not await _check_view_permission(user, student_id):
|
||||||
return error_response(message="无权查看其他学生信息", code=403)
|
return error_response(message="无权查看该学生信息", code=403)
|
||||||
|
|
||||||
result = await StudentService.get_homework_status(student_id)
|
result = await StudentService.get_homework_status(student_id)
|
||||||
|
|
||||||
@@ -78,8 +87,8 @@ async def get_attendance_records(
|
|||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
|
|
||||||
# 权限检查
|
# 权限检查
|
||||||
if user["user_type"] == "student" and user["student_id"] != student_id:
|
if not await _check_view_permission(user, student_id):
|
||||||
return error_response(message="无权查看其他学生信息", code=403)
|
return error_response(message="无权查看该学生信息", code=403)
|
||||||
|
|
||||||
result = await StudentService.get_attendance_records(
|
result = await StudentService.get_attendance_records(
|
||||||
student_id=student_id,
|
student_id=student_id,
|
||||||
@@ -92,16 +101,18 @@ async def get_attendance_records(
|
|||||||
@router.get("/ranking")
|
@router.get("/ranking")
|
||||||
async def get_ranking(
|
async def get_ranking(
|
||||||
request: Request,
|
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)
|
user = await get_current_user(request)
|
||||||
|
|
||||||
result = await StudentService.get_ranking(
|
result = await StudentService.get_ranking(
|
||||||
user_id=user["user_id"],
|
user_id=user["user_id"],
|
||||||
limit=limit
|
limit=limit,
|
||||||
|
month=month
|
||||||
)
|
)
|
||||||
|
|
||||||
return success_response(data=result)
|
return success_response(data=result)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
# 班级操行分管理系统 - 后端服务
|
# 班级操行分管理系统 - 后端服务
|
||||||
#
|
#
|
||||||
# 开发者: Canglan
|
# 开发者: Canglan
|
||||||
@@ -13,7 +13,7 @@ from fastapi import APIRouter, Request
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
from middleware.permission import get_current_user, PermissionChecker
|
from middleware.permission import get_current_user, PermissionChecker
|
||||||
from services.subject_service import SubjectService
|
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.response import success_response, error_response
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
@@ -46,6 +46,14 @@ async def update_subject(request: Request, subject_id: int, req: UpdateSubjectRe
|
|||||||
result = await SubjectService.update_subject(subject_id, **req.dict(exclude_none=True))
|
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"])
|
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}")
|
@router.delete("/delete/{subject_id}")
|
||||||
async def delete_subject(request: Request, subject_id: int):
|
async def delete_subject(request: Request, subject_id: int):
|
||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
|
|||||||
@@ -45,6 +45,10 @@ ALL_VERSIONS = {
|
|||||||
'3.0': 'v3.0.sql',
|
'3.0': 'v3.0.sql',
|
||||||
'4.0': 'v4.0.sql',
|
'4.0': 'v4.0.sql',
|
||||||
'4.1': 'v4.1.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 = [
|
VERSION_MARKERS = [
|
||||||
@@ -56,6 +60,26 @@ VERSION_MARKERS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
async def _detect_current_version() -> str:
|
||||||
"""检测当前数据库版本,优先从 system_settings 读取,否则通过列特征推断"""
|
"""检测当前数据库版本,优先从 system_settings 读取,否则通过列特征推断"""
|
||||||
# 1. 尝试从 system_settings 读取 db_version
|
# 1. 尝试从 system_settings 读取 db_version
|
||||||
@@ -137,7 +161,8 @@ async def check_upgrade(request: Request):
|
|||||||
needs_upgrade = _compare_versions(target_version, current_version) > 0
|
needs_upgrade = _compare_versions(target_version, current_version) > 0
|
||||||
|
|
||||||
steps = []
|
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:
|
if _compare_versions(version, current_version) > 0 and _compare_versions(version, target_version) <= 0:
|
||||||
steps.append({'version': version, 'file': file_name})
|
steps.append({'version': version, 'file': file_name})
|
||||||
|
|
||||||
@@ -191,15 +216,16 @@ async def execute_upgrade_step(request: Request):
|
|||||||
if not version:
|
if not version:
|
||||||
return error_response(message='缺少版本号参数', code=400)
|
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)
|
return error_response(message=f'未知版本: {version}', code=400)
|
||||||
|
|
||||||
# SQL 文件路径
|
# SQL 文件路径
|
||||||
sql_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), '..', 'sql', 'upgrades')
|
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):
|
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
|
last_error = None
|
||||||
|
|
||||||
@@ -227,11 +253,11 @@ async def execute_upgrade_step(request: Request):
|
|||||||
verify = await _verify_upgrade(version)
|
verify = await _verify_upgrade(version)
|
||||||
if verify['ok']:
|
if verify['ok']:
|
||||||
new_version = version
|
new_version = version
|
||||||
logger.info(f"数据库升级成功: v{version} ({ALL_VERSIONS[version]})")
|
logger.info(f"数据库升级成功: v{version} ({all_versions[version]})")
|
||||||
return success_response(data={
|
return success_response(data={
|
||||||
'success': True,
|
'success': True,
|
||||||
'version': version,
|
'version': version,
|
||||||
'message': f"升级至 v{version} 成功 ({ALL_VERSIONS[version]})",
|
'message': f"升级至 v{version} 成功 ({all_versions[version]})",
|
||||||
'current': new_version
|
'current': new_version
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
+62
-45
@@ -11,7 +11,7 @@
|
|||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from datetime import date, datetime
|
from datetime import date
|
||||||
|
|
||||||
|
|
||||||
class AddPointsRequest(BaseModel):
|
class AddPointsRequest(BaseModel):
|
||||||
@@ -22,31 +22,11 @@ class AddPointsRequest(BaseModel):
|
|||||||
related_type: Optional[str] = Field(default='manual', pattern=r'^(manual|homework|attendance)$', description="关联类型: manual/homework/attendance")
|
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):
|
class RevokeRequest(BaseModel):
|
||||||
"""撤销请求"""
|
"""撤销请求"""
|
||||||
record_id: int = Field(..., description="记录ID")
|
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):
|
class AddAdminRequest(BaseModel):
|
||||||
"""添加管理员请求"""
|
"""添加管理员请求"""
|
||||||
username: str = Field(..., min_length=2, max_length=50, pattern=r'^[a-zA-Z0-9_\u4e00-\u9fa5]+$', description="登录账号")
|
username: str = Field(..., min_length=2, max_length=50, pattern=r'^[a-zA-Z0-9_\u4e00-\u9fa5]+$', description="登录账号")
|
||||||
@@ -57,12 +37,22 @@ class AddAdminRequest(BaseModel):
|
|||||||
subject_id: Optional[int] = Field(None, gt=0, description="科目ID(科代表需要)")
|
subject_id: Optional[int] = Field(None, gt=0, description="科目ID(科代表需要)")
|
||||||
|
|
||||||
|
|
||||||
class AddAdminResponse(BaseModel):
|
class UpdateAdminRequest(BaseModel):
|
||||||
"""添加管理员响应"""
|
"""更新管理员请求"""
|
||||||
success: bool
|
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
||||||
username: str
|
group_id: int = Field(..., gt=0, description="权限组ID")
|
||||||
password: Optional[str] = None
|
email: Optional[str] = Field(None, max_length=100, description="绑定邮箱(留空解除绑定)")
|
||||||
message: str
|
|
||||||
|
|
||||||
|
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):
|
class AddStudentRequest(BaseModel):
|
||||||
@@ -84,32 +74,47 @@ class AddAttendanceRequest(BaseModel):
|
|||||||
custom_deduction: Optional[int] = Field(default=None, gt=0, le=20, description="自定义扣分值")
|
custom_deduction: Optional[int] = Field(default=None, gt=0, le=20, description="自定义扣分值")
|
||||||
|
|
||||||
|
|
||||||
class UpdateAdminRequest(BaseModel):
|
class DefaultAttendanceRequest(BaseModel):
|
||||||
"""更新管理员请求"""
|
"""批量默认出勤请求"""
|
||||||
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
start_date: date
|
||||||
group_id: int = Field(..., gt=0, description="权限组ID")
|
end_date: date
|
||||||
email: Optional[str] = Field(None, max_length=100, description="绑定邮箱(留空解除绑定)")
|
slots: Optional[List[str]] = Field(None, description="时段列表(morning/afternoon/evening),默认全部")
|
||||||
|
|
||||||
|
|
||||||
class PermissionGroupRequest(BaseModel):
|
class FullDayLeaveRequest(BaseModel):
|
||||||
"""权限组创建/编辑请求"""
|
"""整天请假请求"""
|
||||||
group_name: str = Field(..., min_length=1, max_length=50, description="权限组名称")
|
date: date
|
||||||
description: Optional[str] = Field(None, max_length=255, description="说明")
|
student_ids: List[int] = Field(..., min_length=1, max_length=200, description="请假学生ID列表")
|
||||||
permissions: List[str] = Field(default_factory=list, description="权限项列表")
|
reason: Optional[str] = Field(None, max_length=255, description="原因")
|
||||||
can_add_points: bool = Field(True, description="是否允许加分")
|
|
||||||
max_add_points: Optional[int] = Field(None, ge=1, le=100, description="单次加分上限,不填为无限制")
|
|
||||||
can_subtract_points: bool = Field(True, description="是否允许扣分")
|
|
||||||
max_subtract_points: Optional[int] = Field(None, ge=1, le=100, description="单次扣分上限,不填为无限制")
|
|
||||||
|
|
||||||
|
|
||||||
class DeleteAdminRequest(BaseModel):
|
class CalendarDayRequest(BaseModel):
|
||||||
"""删除管理员请求"""
|
"""校历手动设置请求"""
|
||||||
user_id: int = Field(..., description="用户ID")
|
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):
|
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):
|
class UpdateStudentRequest(BaseModel):
|
||||||
@@ -122,3 +127,15 @@ class UpdateStudentRequest(BaseModel):
|
|||||||
class UnlockUserRequest(BaseModel):
|
class UnlockUserRequest(BaseModel):
|
||||||
"""解除用户登录锁定请求"""
|
"""解除用户登录锁定请求"""
|
||||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
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="最少字符种类数")
|
||||||
+18
-34
@@ -10,7 +10,6 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
class LoginRequest(BaseModel):
|
class LoginRequest(BaseModel):
|
||||||
@@ -19,41 +18,16 @@ class LoginRequest(BaseModel):
|
|||||||
password: str = Field(..., min_length=1, max_length=50, description="密码")
|
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):
|
class ChangePasswordRequest(BaseModel):
|
||||||
"""修改密码请求"""
|
"""修改密码请求"""
|
||||||
old_password: str = Field(default="", max_length=50, description="原密码")
|
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="是否强制修改(首次登录)")
|
force: bool = Field(default=False, description="是否强制修改(首次登录)")
|
||||||
|
|
||||||
|
|
||||||
class ChangePasswordResponse(BaseModel):
|
class InitPasswordRequest(BaseModel):
|
||||||
"""修改密码响应"""
|
"""首次登录初始化密码请求(无需原密码)"""
|
||||||
success: bool
|
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||||
message: str
|
|
||||||
|
|
||||||
|
|
||||||
class UserInfo(BaseModel):
|
|
||||||
"""用户信息"""
|
|
||||||
user_id: int
|
|
||||||
username: str
|
|
||||||
real_name: str
|
|
||||||
user_type: str
|
|
||||||
student_id: Optional[int] = None
|
|
||||||
role: Optional[str] = None
|
|
||||||
email: Optional[str] = None
|
|
||||||
need_change_password: bool
|
|
||||||
|
|
||||||
|
|
||||||
class ForgotPasswordRequest(BaseModel):
|
class ForgotPasswordRequest(BaseModel):
|
||||||
@@ -64,10 +38,20 @@ class ForgotPasswordRequest(BaseModel):
|
|||||||
class ResetPasswordRequest(BaseModel):
|
class ResetPasswordRequest(BaseModel):
|
||||||
"""通过邮件令牌重置密码请求"""
|
"""通过邮件令牌重置密码请求"""
|
||||||
token: str = Field(..., min_length=10, max_length=200, description="重置令牌")
|
token: str = Field(..., min_length=10, max_length=200, description="重置令牌")
|
||||||
new_password: str = Field(..., min_length=6, max_length=20, description="新密码")
|
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||||
|
|
||||||
|
|
||||||
class BindEmailRequest(BaseModel):
|
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="当前密码")
|
password: str = Field(..., min_length=1, max_length=50, description="当前密码")
|
||||||
email: str = Field(default="", max_length=100, description="新邮箱(留空解除绑定)")
|
|
||||||
@@ -10,7 +10,6 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
class DeductionConfigResponse(BaseModel):
|
class DeductionConfigResponse(BaseModel):
|
||||||
"""扣分规则配置响应"""
|
"""扣分规则配置响应"""
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
|||||||
@@ -25,14 +25,14 @@ class SubjectInfo(BaseModel):
|
|||||||
class CreateSubjectRequest(BaseModel):
|
class CreateSubjectRequest(BaseModel):
|
||||||
"""创建科目请求"""
|
"""创建科目请求"""
|
||||||
subject_name: str = Field(..., min_length=1, max_length=50, description="科目名称")
|
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="排序序号")
|
sort_order: int = Field(0, description="排序序号")
|
||||||
|
|
||||||
|
|
||||||
class UpdateSubjectRequest(BaseModel):
|
class UpdateSubjectRequest(BaseModel):
|
||||||
"""更新科目请求"""
|
"""更新科目请求"""
|
||||||
subject_name: Optional[str] = Field(None, max_length=50, description="科目名称")
|
subject_name: Optional[str] = Field(None, 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="科目代码(传空字符串表示清空)")
|
||||||
is_active: Optional[bool] = Field(None, description="是否启用")
|
is_active: Optional[bool] = Field(None, description="是否启用")
|
||||||
sort_order: Optional[int] = Field(None, description="排序序号")
|
sort_order: Optional[int] = Field(None, description="排序序号")
|
||||||
|
|
||||||
@@ -41,3 +41,8 @@ class SubjectListResponse(BaseModel):
|
|||||||
"""科目列表响应"""
|
"""科目列表响应"""
|
||||||
subjects: List[SubjectInfo]
|
subjects: List[SubjectInfo]
|
||||||
total: int
|
total: int
|
||||||
|
|
||||||
|
|
||||||
|
class ReorderSubjectsRequest(BaseModel):
|
||||||
|
"""科目排序请求"""
|
||||||
|
subject_ids: List[int] = Field(..., min_length=1, max_length=100, description="按新顺序排列的科目ID列表")
|
||||||
@@ -15,6 +15,7 @@ from models.user import UserModel
|
|||||||
from models.student import StudentModel
|
from models.student import StudentModel
|
||||||
from models.admin_role import AdminRoleModel
|
from models.admin_role import AdminRoleModel
|
||||||
from models.permission_group import PermissionGroupModel, PERMISSION_KEYS
|
from models.permission_group import PermissionGroupModel, PERMISSION_KEYS
|
||||||
|
from services.setting_service import SettingService
|
||||||
from utils.security import security
|
from utils.security import security
|
||||||
from utils.validators import is_valid_email
|
from utils.validators import is_valid_email
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
@@ -307,15 +308,16 @@ class AdminService:
|
|||||||
password: Optional[str],
|
password: Optional[str],
|
||||||
group_id: int,
|
group_id: int,
|
||||||
operator_id: int,
|
operator_id: int,
|
||||||
email: Optional[str] = None,
|
email: Optional[str] = None
|
||||||
allow_locked: bool = False
|
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""添加管理员(支持重新激活已删除的管理员)"""
|
"""添加管理员(支持重新激活已删除的管理员)"""
|
||||||
group = await PermissionGroupModel.get_by_id(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:
|
if not group:
|
||||||
return {"success": False, "message": "权限组不存在"}
|
return {"success": False, "message": "权限组不存在"}
|
||||||
if group.get("is_locked") and not allow_locked:
|
|
||||||
return {"success": False, "message": "该权限组不可分配"}
|
|
||||||
role_type = group["group_name"]
|
role_type = group["group_name"]
|
||||||
|
|
||||||
# 邮箱校验(留空表示不绑定)
|
# 邮箱校验(留空表示不绑定)
|
||||||
@@ -334,7 +336,11 @@ class AdminService:
|
|||||||
await UserModel.update_status(existing['user_id'], 1)
|
await UserModel.update_status(existing['user_id'], 1)
|
||||||
await UserModel.update_real_name(existing['user_id'], real_name)
|
await UserModel.update_real_name(existing['user_id'], real_name)
|
||||||
if email is not None:
|
if email is not None:
|
||||||
await UserModel.update_email(existing['user_id'], normalized_email)
|
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']
|
user_id = existing['user_id']
|
||||||
# 检查是否已有管理员角色
|
# 检查是否已有管理员角色
|
||||||
existing_role = await AdminRoleModel.get_by_user_id(user_id)
|
existing_role = await AdminRoleModel.get_by_user_id(user_id)
|
||||||
@@ -356,12 +362,16 @@ class AdminService:
|
|||||||
if not password:
|
if not password:
|
||||||
password = security.generate_random_password()
|
password = security.generate_random_password()
|
||||||
|
|
||||||
user_id = await UserModel.create_admin(
|
try:
|
||||||
username=username,
|
user_id = await UserModel.create_admin(
|
||||||
password=password,
|
username=username,
|
||||||
real_name=real_name,
|
password=password,
|
||||||
email=normalized_email
|
real_name=real_name,
|
||||||
)
|
email=normalized_email
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"创建管理员账号失败(数据库可能待升级): {e}")
|
||||||
|
return {"success": False, "message": "数据库待升级,请先完成系统升级后再设置邮箱"}
|
||||||
|
|
||||||
await AdminRoleModel.create(
|
await AdminRoleModel.create(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
@@ -387,18 +397,28 @@ class AdminService:
|
|||||||
real_name: str,
|
real_name: str,
|
||||||
group_id: int,
|
group_id: int,
|
||||||
operator_id: int,
|
operator_id: int,
|
||||||
email: Optional[str] = None
|
email: Optional[str] = None,
|
||||||
|
keep_group: bool = False
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""更新管理员姓名、权限组与绑定邮箱"""
|
"""更新管理员姓名、权限组与绑定邮箱(keep_group=True 时仅改姓名/邮箱,权限组保持不变)"""
|
||||||
target_user = await UserModel.get_by_user_id(user_id)
|
target_user = await UserModel.get_by_user_id(user_id)
|
||||||
if not target_user or target_user.get("user_type") != "admin":
|
if not target_user or target_user.get("user_type") != "admin":
|
||||||
return {"success": False, "message": "管理员不存在"}
|
return {"success": False, "message": "管理员不存在"}
|
||||||
|
|
||||||
group = await PermissionGroupModel.get_by_id(group_id)
|
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:
|
if not group:
|
||||||
return {"success": False, "message": "权限组不存在"}
|
return {"success": False, "message": "权限组不存在"}
|
||||||
if group.get("is_locked"):
|
|
||||||
return {"success": False, "message": "该权限组不可分配"}
|
|
||||||
|
|
||||||
# 邮箱校验(留空表示解除绑定)
|
# 邮箱校验(留空表示解除绑定)
|
||||||
normalized_email = None
|
normalized_email = None
|
||||||
@@ -407,11 +427,16 @@ class AdminService:
|
|||||||
if normalized_email and not is_valid_email(normalized_email):
|
if normalized_email and not is_valid_email(normalized_email):
|
||||||
return {"success": False, "message": "邮箱格式不正确"}
|
return {"success": False, "message": "邮箱格式不正确"}
|
||||||
|
|
||||||
await AdminRoleModel.update_role(user_id, group["group_name"], group_id=group_id)
|
try:
|
||||||
if real_name:
|
if not keep_group:
|
||||||
await UserModel.update_real_name(user_id, real_name)
|
await AdminRoleModel.update_role(user_id, group["group_name"], group_id=group_id)
|
||||||
if email is not None:
|
if real_name:
|
||||||
await UserModel.update_email(user_id, normalized_email)
|
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']}")
|
logger.info(f"用户[{operator_id}] 更新管理员[{user_id}]权限组: {group['group_name']}")
|
||||||
return {"success": True, "message": "管理员更新成功"}
|
return {"success": True, "message": "管理员更新成功"}
|
||||||
@@ -445,18 +470,22 @@ class AdminService:
|
|||||||
return normalized
|
return normalized
|
||||||
|
|
||||||
data = normalized["data"]
|
data = normalized["data"]
|
||||||
if await PermissionGroupModel.get_by_name(data["group_name"]):
|
try:
|
||||||
return {"success": False, "message": "权限组名称已存在"}
|
if await PermissionGroupModel.get_by_name(data["group_name"]):
|
||||||
|
return {"success": False, "message": "权限组名称已存在"}
|
||||||
|
|
||||||
group_id = await PermissionGroupModel.create(
|
group_id = await PermissionGroupModel.create(
|
||||||
group_name=data["group_name"],
|
group_name=data["group_name"],
|
||||||
description=data["description"],
|
description=data["description"],
|
||||||
permissions=data["permissions"],
|
permissions=data["permissions"],
|
||||||
can_add_points=data["can_add_points"],
|
can_add_points=data["can_add_points"],
|
||||||
max_add_points=data["max_add_points"],
|
max_add_points=data["max_add_points"],
|
||||||
can_subtract_points=data["can_subtract_points"],
|
can_subtract_points=data["can_subtract_points"],
|
||||||
max_subtract_points=data["max_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})")
|
logger.info(f"用户[{operator_id}] 新建权限组: {data['group_name']} (ID={group_id})")
|
||||||
return {"success": True, "message": "权限组创建成功", "group_id": group_id}
|
return {"success": True, "message": "权限组创建成功", "group_id": group_id}
|
||||||
|
|
||||||
@@ -473,11 +502,13 @@ class AdminService:
|
|||||||
operator_id: int = None
|
operator_id: int = None
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""编辑权限组(锁定组不可编辑)"""
|
"""编辑权限组(锁定组不可编辑)"""
|
||||||
group = await PermissionGroupModel.get_by_id(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:
|
if not group:
|
||||||
return {"success": False, "message": "权限组不存在"}
|
return {"success": False, "message": "权限组不存在"}
|
||||||
if group.get("is_locked"):
|
|
||||||
return {"success": False, "message": "该权限组已锁定,不可编辑"}
|
|
||||||
|
|
||||||
normalized = _normalize_group_payload(
|
normalized = _normalize_group_payload(
|
||||||
group_name, description, permissions,
|
group_name, description, permissions,
|
||||||
@@ -488,47 +519,57 @@ class AdminService:
|
|||||||
return normalized
|
return normalized
|
||||||
|
|
||||||
data = normalized["data"]
|
data = normalized["data"]
|
||||||
same_name = await PermissionGroupModel.get_by_name(data["group_name"])
|
try:
|
||||||
if same_name and same_name["group_id"] != group_id:
|
same_name = await PermissionGroupModel.get_by_name(data["group_name"])
|
||||||
return {"success": False, "message": "权限组名称已存在"}
|
if same_name and same_name["group_id"] != group_id:
|
||||||
|
return {"success": False, "message": "权限组名称已存在"}
|
||||||
|
|
||||||
updated = await PermissionGroupModel.update(
|
updated = await PermissionGroupModel.update(
|
||||||
group_id=group_id,
|
group_id=group_id,
|
||||||
group_name=data["group_name"],
|
group_name=data["group_name"],
|
||||||
description=data["description"],
|
description=data["description"],
|
||||||
permissions=data["permissions"],
|
permissions=data["permissions"],
|
||||||
can_add_points=data["can_add_points"],
|
can_add_points=data["can_add_points"],
|
||||||
max_add_points=data["max_add_points"],
|
max_add_points=data["max_add_points"],
|
||||||
can_subtract_points=data["can_subtract_points"],
|
can_subtract_points=data["can_subtract_points"],
|
||||||
max_subtract_points=data["max_subtract_points"]
|
max_subtract_points=data["max_subtract_points"]
|
||||||
)
|
)
|
||||||
if not updated:
|
if not updated:
|
||||||
return {"success": False, "message": "权限组更新失败"}
|
return {"success": False, "message": "权限组更新失败"}
|
||||||
|
|
||||||
# 同步冗余的 role_type 显示名
|
# 同步冗余的 role_type 显示名
|
||||||
await execute_update(
|
await execute_update(
|
||||||
"UPDATE admin_roles SET role_type = %s WHERE group_id = %s",
|
"UPDATE admin_roles SET role_type = %s WHERE group_id = %s",
|
||||||
(data["group_name"], group_id)
|
(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})")
|
logger.info(f"用户[{operator_id}] 更新权限组: {data['group_name']} (ID={group_id})")
|
||||||
return {"success": True, "message": "权限组更新成功"}
|
return {"success": True, "message": "权限组更新成功"}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def delete_permission_group(group_id: int, operator_id: int = None) -> Dict[str, Any]:
|
async def delete_permission_group(group_id: int, operator_id: int = None) -> Dict[str, Any]:
|
||||||
"""删除权限组(系统预置组不可删除,有成员时不可删除)"""
|
"""删除权限组(系统预置组不可删除,有成员时不可删除)"""
|
||||||
group = await PermissionGroupModel.get_by_id(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:
|
if not group:
|
||||||
return {"success": False, "message": "权限组不存在"}
|
return {"success": False, "message": "权限组不存在"}
|
||||||
if group.get("is_system") or group.get("is_locked"):
|
|
||||||
return {"success": False, "message": "系统预置权限组不可删除"}
|
|
||||||
|
|
||||||
member_count = await PermissionGroupModel.count_members(group_id)
|
try:
|
||||||
if member_count > 0:
|
member_count = await PermissionGroupModel.count_members(group_id)
|
||||||
return {"success": False, "message": f"该权限组下还有 {member_count} 个管理员,请先调整后再删除"}
|
if member_count > 0:
|
||||||
|
return {"success": False, "message": f"该权限组下还有 {member_count} 个管理员,请先调整后再删除"}
|
||||||
|
|
||||||
deleted = await PermissionGroupModel.delete(group_id)
|
deleted = await PermissionGroupModel.delete(group_id)
|
||||||
if not deleted:
|
if not deleted:
|
||||||
return {"success": False, "message": "权限组删除失败"}
|
return {"success": False, "message": "权限组删除失败"}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"删除权限组失败(数据库可能待升级): {e}")
|
||||||
|
return {"success": False, "message": "数据库待升级,请先完成系统升级"}
|
||||||
logger.info(f"用户[{operator_id}] 删除权限组 ID={group_id}")
|
logger.info(f"用户[{operator_id}] 删除权限组 ID={group_id}")
|
||||||
return {"success": True, "message": "权限组已删除"}
|
return {"success": True, "message": "权限组已删除"}
|
||||||
|
|
||||||
@@ -576,9 +617,23 @@ class AdminService:
|
|||||||
logger.error(f"删除学生失败: {e}")
|
logger.error(f"删除学生失败: {e}")
|
||||||
return {"success": False, "message": f"删除失败: {str(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
|
@staticmethod
|
||||||
async def reset_student_password(student_id: int, new_password: str) -> Dict[str, Any]:
|
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:
|
try:
|
||||||
user = await execute_one(
|
user = await execute_one(
|
||||||
"SELECT user_id FROM users WHERE student_id = %s AND user_type = 'student'",
|
"SELECT user_id FROM users WHERE student_id = %s AND user_type = 'student'",
|
||||||
|
|||||||
@@ -9,13 +9,16 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import date, timedelta
|
||||||
from typing import Dict, Any, Optional
|
from typing import Dict, Any, Optional
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from models.attendance import AttendanceModel
|
from models.attendance import AttendanceModel
|
||||||
from models.student import StudentModel
|
from models.student import StudentModel
|
||||||
from models.conduct import ConductModel
|
from models.conduct import ConductModel
|
||||||
from models.user import UserModel
|
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 middleware.permission import PermissionChecker
|
||||||
from config import settings
|
from config import settings
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
@@ -29,6 +32,12 @@ ATTENDANCE_STATUS_MAP = {
|
|||||||
"leave": "请假"
|
"leave": "请假"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 手动校历设置的存储前缀与类型
|
||||||
|
CALENDAR_KEY_PREFIX = 'calendar_day:'
|
||||||
|
CALENDAR_TYPES = ('holiday', 'makeup')
|
||||||
|
VALID_SLOTS = ('morning', 'afternoon', 'evening')
|
||||||
|
MAX_DEFAULT_DAYS = 180
|
||||||
|
|
||||||
|
|
||||||
class AttendanceService:
|
class AttendanceService:
|
||||||
"""考勤服务"""
|
"""考勤服务"""
|
||||||
@@ -118,7 +127,7 @@ class AttendanceService:
|
|||||||
recorder_name = user.get("real_name", "班主任") if user else "班主任"
|
recorder_name = user.get("real_name", "班主任") if user else "班主任"
|
||||||
# 使用中文状态
|
# 使用中文状态
|
||||||
status_text = ATTENDANCE_STATUS_MAP.get(status, status)
|
status_text = ATTENDANCE_STATUS_MAP.get(status, status)
|
||||||
await ConductModel.create_record(
|
deduction_record_id = await ConductModel.create_record(
|
||||||
student_id=student_id,
|
student_id=student_id,
|
||||||
points_change=points_change,
|
points_change=points_change,
|
||||||
reason=f"考勤:{status_text}",
|
reason=f"考勤:{status_text}",
|
||||||
@@ -132,8 +141,8 @@ class AttendanceService:
|
|||||||
# 更新学生总分
|
# 更新学生总分
|
||||||
await StudentModel.update_total_points(student_id, points_change)
|
await StudentModel.update_total_points(student_id, points_change)
|
||||||
|
|
||||||
# 标记已应用扣分
|
# 标记已应用扣分(并记录扣分记录ID)
|
||||||
await AttendanceModel.mark_deduction_applied(attendance_id)
|
await AttendanceModel.mark_deduction_applied(attendance_id, deduction_record_id)
|
||||||
logger.info(f"用户[{recorder_id}] 添加考勤记录[{attendance_id}] -> {status}")
|
logger.info(f"用户[{recorder_id}] 添加考勤记录[{attendance_id}] -> {status}")
|
||||||
|
|
||||||
return {"success": True, "message": "考勤记录添加成功"}
|
return {"success": True, "message": "考勤记录添加成功"}
|
||||||
@@ -152,3 +161,276 @@ class AttendanceService:
|
|||||||
slot=slot
|
slot=slot
|
||||||
)
|
)
|
||||||
return {"records": records}
|
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,22 +10,20 @@
|
|||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Dict, Any, Optional
|
from typing import Dict, Any, Optional
|
||||||
from datetime import datetime
|
|
||||||
from html import escape as html_escape
|
from html import escape as html_escape
|
||||||
import secrets
|
import secrets
|
||||||
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from models.user import UserModel
|
from models.user import UserModel
|
||||||
from models.student import StudentModel
|
from models.student import StudentModel
|
||||||
from models.admin_role import AdminRoleModel
|
|
||||||
from middleware.permission import PermissionChecker
|
from middleware.permission import PermissionChecker
|
||||||
from services.log_service import LogService
|
from services.log_service import LogService
|
||||||
|
from services.setting_service import SettingService
|
||||||
from utils.security import security
|
from utils.security import security
|
||||||
from utils.validators import is_valid_email
|
from utils.validators import is_valid_email
|
||||||
from utils.email_sender import EmailSender
|
from utils.email_sender import EmailSender
|
||||||
from utils.jwt_handler import jwt_handler
|
from utils.jwt_handler import jwt_handler
|
||||||
from utils.redis_client import RedisClient
|
from utils.redis_client import RedisClient
|
||||||
from utils.database import execute_update
|
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
@@ -73,10 +71,10 @@ class AuthService:
|
|||||||
await LogService.write_login_log(username, 0, ip, user_agent, "用户名或密码错误")
|
await LogService.write_login_log(username, 0, ip, user_agent, "用户名或密码错误")
|
||||||
return {"success": False, "message": "用户名或密码错误"}
|
return {"success": False, "message": "用户名或密码错误"}
|
||||||
|
|
||||||
# 自动升级旧哈希密码
|
# 自动升级旧哈希密码(仅升级哈希,不能清除"密码待修改"标记)
|
||||||
if needs_upgrade:
|
if needs_upgrade:
|
||||||
try:
|
try:
|
||||||
await UserModel.update_password(user["user_id"], password)
|
await UserModel.upgrade_password_hash(user["user_id"], password)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -131,7 +129,6 @@ class AuthService:
|
|||||||
"role": role,
|
"role": role,
|
||||||
"permissions": permissions,
|
"permissions": permissions,
|
||||||
"group": group_info,
|
"group": group_info,
|
||||||
"email": user.get("email"),
|
|
||||||
"need_change_password": user["need_change_password"] == 1,
|
"need_change_password": user["need_change_password"] == 1,
|
||||||
"redirect": redirect
|
"redirect": redirect
|
||||||
}
|
}
|
||||||
@@ -151,21 +148,24 @@ class AuthService:
|
|||||||
return {"success": False, "message": "用户不存在"}
|
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:
|
if force and user.get("need_change_password") == 1:
|
||||||
# 首次登录强制改密,跳过旧密码验证
|
# 密码待修改:免原密码
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
# 正常改密,必须验证旧密码
|
# 常规改密:必须验证原密码
|
||||||
if not old_password:
|
if not old_password:
|
||||||
return {"success": False, "message": "请输入原密码"}
|
return {"success": False, "message": "请输入原密码"}
|
||||||
is_valid, _ = security.verify_password_v2(old_password, user["password_hash"])
|
is_valid, _ = security.verify_password_v2(old_password, user["password_hash"])
|
||||||
if not is_valid:
|
if not is_valid:
|
||||||
return {"success": False, "message": "原密码错误"}
|
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:
|
if not is_valid:
|
||||||
return {"success": False, "message": msg}
|
return {"success": False, "message": msg}
|
||||||
|
|
||||||
@@ -173,12 +173,36 @@ class AuthService:
|
|||||||
result = await UserModel.update_password(user_id, new_password)
|
result = await UserModel.update_password(user_id, new_password)
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
# 清除所有Token
|
# 清除旧Token
|
||||||
await RedisClient.delete_user_token(user_id)
|
await RedisClient.delete_user_token(user_id)
|
||||||
return {"success": True, "message": "密码修改成功"}
|
return {"success": True, "message": "密码修改成功"}
|
||||||
else:
|
else:
|
||||||
return {"success": False, "message": "密码修改失败"}
|
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
|
@staticmethod
|
||||||
async def get_user_info(user_id: int) -> Optional[Dict[str, Any]]:
|
async def get_user_info(user_id: int) -> Optional[Dict[str, Any]]:
|
||||||
"""获取用户信息"""
|
"""获取用户信息"""
|
||||||
@@ -191,7 +215,6 @@ class AuthService:
|
|||||||
"username": user["username"],
|
"username": user["username"],
|
||||||
"real_name": user["real_name"],
|
"real_name": user["real_name"],
|
||||||
"user_type": user["user_type"],
|
"user_type": user["user_type"],
|
||||||
"email": user.get("email"),
|
|
||||||
"need_change_password": user["need_change_password"] == 1
|
"need_change_password": user["need_change_password"] == 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,6 +233,12 @@ class AuthService:
|
|||||||
result["role"] = group.get("group_name") or group.get("role_type")
|
result["role"] = group.get("group_name") or group.get("role_type")
|
||||||
result["permissions"] = group.get("permissions_data", {})
|
result["permissions"] = group.get("permissions_data", {})
|
||||||
result["group"] = _build_group_info(group)
|
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
|
return result
|
||||||
|
|
||||||
@@ -220,8 +249,9 @@ class AuthService:
|
|||||||
"success": True,
|
"success": True,
|
||||||
"message": f"如果该账号已绑定邮箱,重置链接已发送,请留意查收({settings.PASSWORD_RESET_EXPIRE_MINUTES}分钟内有效)"
|
"message": f"如果该账号已绑定邮箱,重置链接已发送,请留意查收({settings.PASSWORD_RESET_EXPIRE_MINUTES}分钟内有效)"
|
||||||
}
|
}
|
||||||
if not EmailSender.is_configured():
|
missing = EmailSender.missing_config()
|
||||||
return {"success": False, "message": "系统未配置邮件服务,请联系班主任或系统管理员"}
|
if missing:
|
||||||
|
return {"success": False, "message": "系统未配置邮件服务,需设置:" + "、".join(missing)}
|
||||||
if not settings.FRONTEND_URL:
|
if not settings.FRONTEND_URL:
|
||||||
return {"success": False, "message": "系统未配置站点地址(FRONTEND_URL),无法生成重置链接"}
|
return {"success": False, "message": "系统未配置站点地址(FRONTEND_URL),无法生成重置链接"}
|
||||||
|
|
||||||
@@ -232,8 +262,18 @@ class AuthService:
|
|||||||
await RedisClient.set(limit_key, "1", expire=60)
|
await RedisClient.set(limit_key, "1", expire=60)
|
||||||
|
|
||||||
user = await UserModel.get_by_username(username)
|
user = await UserModel.get_by_username(username)
|
||||||
if not user or user.get("user_type") != "admin" or not user.get("email"):
|
if not user or user.get("user_type") != "admin":
|
||||||
logger.info(f"找回密码请求未发送(账号不存在/非管理员/未绑定邮箱): {username}, IP={ip}")
|
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
|
return generic_success
|
||||||
|
|
||||||
# 生成一次性令牌,并作废该用户此前的令牌
|
# 生成一次性令牌,并作废该用户此前的令牌
|
||||||
@@ -260,7 +300,7 @@ class AuthService:
|
|||||||
</div>
|
</div>
|
||||||
"""
|
"""
|
||||||
ok, message_text = await EmailSender.send(
|
ok, message_text = await EmailSender.send(
|
||||||
user["email"],
|
bound_email,
|
||||||
f"{settings.APP_NAME} - 密码重置",
|
f"{settings.APP_NAME} - 密码重置",
|
||||||
html_body
|
html_body
|
||||||
)
|
)
|
||||||
@@ -270,7 +310,7 @@ class AuthService:
|
|||||||
logger.error(f"密码重置邮件发送失败: {username} - {message_text}")
|
logger.error(f"密码重置邮件发送失败: {username} - {message_text}")
|
||||||
return {"success": False, "message": "重置邮件发送失败,请稍后重试或联系系统管理员"}
|
return {"success": False, "message": "重置邮件发送失败,请稍后重试或联系系统管理员"}
|
||||||
|
|
||||||
logger.info(f"已向用户[{username}]的绑定邮箱发送密码重置链接, IP={ip}")
|
logger.debug(f"已向用户[{username}]的绑定邮箱发送密码重置链接, IP={ip}")
|
||||||
return generic_success
|
return generic_success
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -303,7 +343,10 @@ class AuthService:
|
|||||||
if not user or user.get("user_type") != "admin" or user.get("status") != 1:
|
if not user or user.get("user_type") != "admin" or user.get("status") != 1:
|
||||||
return {"success": False, "message": "账号不存在或不可重置密码"}
|
return {"success": False, "message": "账号不存在或不可重置密码"}
|
||||||
|
|
||||||
is_valid, message = security.validate_password_strength(new_password)
|
policy = await SettingService.get_password_policy()
|
||||||
|
is_valid, message = security.validate_password_strength(
|
||||||
|
new_password, policy["min_length"], policy["max_length"], policy["min_types"]
|
||||||
|
)
|
||||||
if not is_valid:
|
if not is_valid:
|
||||||
return {"success": False, "message": message}
|
return {"success": False, "message": message}
|
||||||
|
|
||||||
@@ -315,35 +358,143 @@ class AuthService:
|
|||||||
await RedisClient.delete(f"pwd_reset:{token}")
|
await RedisClient.delete(f"pwd_reset:{token}")
|
||||||
await RedisClient.delete(f"pwd_reset_user:{user_id}")
|
await RedisClient.delete(f"pwd_reset_user:{user_id}")
|
||||||
await RedisClient.delete_user_token(user_id)
|
await RedisClient.delete_user_token(user_id)
|
||||||
logger.info(f"用户[{user_id}] 通过邮箱重置密码成功")
|
logger.debug(f"用户[{user_id}] 通过邮箱重置密码成功")
|
||||||
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
|
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def bind_email(user_id: int, password: str, email: str) -> Dict[str, Any]:
|
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)
|
user = await UserModel.get_by_user_id(user_id)
|
||||||
if not user or user.get("user_type") != "admin":
|
if not user or user.get("user_type") != "admin":
|
||||||
return {"success": False, "message": "仅管理员可绑定邮箱"}
|
return {"success": False, "message": "仅管理员可绑定邮箱"}
|
||||||
|
|
||||||
is_valid, _ = security.verify_password_v2(password, user["password_hash"])
|
normalized_email = (email or "").strip()
|
||||||
if not is_valid:
|
if not is_valid_email(normalized_email):
|
||||||
return {"success": False, "message": "当前密码错误"}
|
|
||||||
|
|
||||||
normalized_email = (email or "").strip() or None
|
|
||||||
if normalized_email and not is_valid_email(normalized_email):
|
|
||||||
return {"success": False, "message": "邮箱格式不正确"}
|
return {"success": False, "message": "邮箱格式不正确"}
|
||||||
|
|
||||||
updated = await UserModel.update_email(user_id, normalized_email)
|
# 数据库未升级(users.email 不存在)时提前返回明确提示,避免发送无效验证码
|
||||||
if not updated:
|
try:
|
||||||
return {"success": False, "message": "邮箱更新失败"}
|
await UserModel.get_email_by_user_id(user_id)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"邮箱绑定失败(数据库可能待升级): {e}")
|
||||||
|
return {"success": False, "message": "数据库待升级,请先完成系统升级后再绑定邮箱"}
|
||||||
|
|
||||||
logger.info(f"用户[{user_id}] 更新绑定邮箱: {normalized_email or '(解除绑定)'}")
|
# 频率限制:同一账号 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 {
|
return {
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": "邮箱绑定成功" if normalized_email else "邮箱已解除绑定",
|
"message": f"验证码已发送至 {normalized_email},{settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效"
|
||||||
"email": normalized_email
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@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
|
@staticmethod
|
||||||
def _get_redirect_path(user_type: str, role: str = None) -> str:
|
def _get_redirect_path(user_type: str, role: str = None) -> str:
|
||||||
"""获取跳转路径"""
|
"""获取跳转路径"""
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ from datetime import datetime
|
|||||||
|
|
||||||
from models.student import StudentModel
|
from models.student import StudentModel
|
||||||
from models.conduct import ConductModel, _append_semester_filter
|
from models.conduct import ConductModel, _append_semester_filter
|
||||||
from models.user import UserModel
|
|
||||||
from models.semester import SemesterModel
|
from models.semester import SemesterModel
|
||||||
from middleware.permission import PermissionChecker
|
from middleware.permission import PermissionChecker
|
||||||
from config import settings
|
from config import settings
|
||||||
@@ -451,13 +450,11 @@ class ConductService:
|
|||||||
record_count += cnt
|
record_count += cnt
|
||||||
|
|
||||||
months = []
|
months = []
|
||||||
running_score = base_points
|
|
||||||
for month in sorted(months_map.keys()):
|
for month in sorted(months_map.keys()):
|
||||||
entry = months_map[month]
|
entry = months_map[month]
|
||||||
entry["start_score"] = running_score
|
# 月度分独立计算,与基础分无关;总分才使用基础分
|
||||||
entry["net"] = entry["bonus"] + entry["deduction"]
|
entry["month_score"] = entry["bonus"] + entry["deduction"]
|
||||||
running_score += entry["net"]
|
entry["net"] = entry["month_score"]
|
||||||
entry["end_score"] = running_score
|
|
||||||
months.append(entry)
|
months.append(entry)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -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 models.log import LoginLogModel, OperationLogModel
|
||||||
from middleware.permission import PermissionChecker
|
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
@@ -55,3 +54,44 @@ class LogService:
|
|||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"写入操作日志失败: {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
|
import math
|
||||||
from typing import Dict, Any, Optional, List
|
from typing import Dict, Any
|
||||||
|
|
||||||
from models.user import UserModel
|
from models.user import UserModel
|
||||||
from models.student import StudentModel
|
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
|
import datetime
|
||||||
from typing import Dict, Any, List, Optional
|
from typing import Dict, Any
|
||||||
|
|
||||||
from models.semester import SemesterModel, SemesterArchiveModel
|
from models.semester import SemesterModel, SemesterArchiveModel
|
||||||
from models.student import StudentModel
|
from models.student import StudentModel
|
||||||
from middleware.permission import PermissionChecker
|
|
||||||
from config import settings
|
from config import settings
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
from utils.database import execute_query
|
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
@@ -389,6 +387,25 @@ class SemesterService:
|
|||||||
|
|
||||||
archives = await SemesterArchiveModel.get_by_semester(semester_id)
|
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)
|
total = len(archives)
|
||||||
offset = (page - 1) * page_size
|
offset = (page - 1) * page_size
|
||||||
paged_archives = archives[offset:offset + page_size]
|
paged_archives = archives[offset:offset + page_size]
|
||||||
@@ -403,6 +420,10 @@ class SemesterService:
|
|||||||
"end_date": semester.get('end_date'),
|
"end_date": semester.get('end_date'),
|
||||||
"is_archived": bool(semester['is_archived'])
|
"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,
|
"archives": paged_archives,
|
||||||
"total": total,
|
"total": total,
|
||||||
"page": page,
|
"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
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Dict, Any, List, Optional
|
from typing import Dict, Any, Optional
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
from models.student import StudentModel
|
from models.student import StudentModel
|
||||||
from models.conduct import ConductModel
|
from models.conduct import ConductModel
|
||||||
from models.attendance import AttendanceModel
|
from models.attendance import AttendanceModel
|
||||||
from middleware.permission import PermissionChecker
|
|
||||||
from utils.database import execute_query
|
from utils.database import execute_query
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
|
|
||||||
@@ -123,15 +121,20 @@ class StudentService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_ranking(
|
async def get_ranking(
|
||||||
user_id: int,
|
user_id: int,
|
||||||
limit: int = 50
|
limit: int = 50,
|
||||||
|
month: str = None
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""获取排行榜(单班级系统)"""
|
"""获取排行榜(单班级系统);传 month 时返回月度分排行"""
|
||||||
ranking = await StudentModel.get_ranking(limit=limit)
|
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()
|
total_students = await StudentModel.get_total_count()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"ranking": ranking,
|
"ranking": ranking,
|
||||||
"total_students": total_students
|
"total_students": total_students,
|
||||||
|
"month": month
|
||||||
}
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Dict, Any, List, Optional
|
from typing import Dict, Any, Optional, List
|
||||||
|
|
||||||
from models.subject import SubjectModel
|
from models.subject import SubjectModel
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
@@ -36,27 +36,47 @@ class SubjectService:
|
|||||||
subject_code: Optional[str],
|
subject_code: Optional[str],
|
||||||
sort_order: int = 0
|
sort_order: int = 0
|
||||||
) -> Dict[str, Any]:
|
) -> 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:
|
if existing:
|
||||||
return {"success": False, "message": "科目名称已存在"}
|
return {"success": False, "message": "科目名称已存在"}
|
||||||
|
|
||||||
subject_id = await SubjectModel.create(
|
subject_id = await SubjectModel.create(
|
||||||
subject_name=subject_name,
|
subject_name=name,
|
||||||
subject_code=subject_code,
|
subject_code=code,
|
||||||
sort_order=sort_order
|
sort_order=sort_order
|
||||||
)
|
)
|
||||||
|
|
||||||
if subject_id:
|
if subject_id:
|
||||||
logger.info(f"创建科目: {subject_name}")
|
logger.info(f"创建科目: {name}")
|
||||||
return {"success": True, "subject_id": subject_id}
|
return {"success": True, "subject_id": subject_id}
|
||||||
else:
|
else:
|
||||||
return {"success": False, "message": "创建科目失败"}
|
return {"success": False, "message": "创建科目失败"}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def update_subject(subject_id: int, **kwargs) -> Dict[str, Any]:
|
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)
|
result = await SubjectModel.update(subject_id, **kwargs)
|
||||||
|
|
||||||
if result:
|
if result:
|
||||||
@@ -65,6 +85,15 @@ class SubjectService:
|
|||||||
else:
|
else:
|
||||||
return {"success": False, "message": "更新科目失败"}
|
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
|
@staticmethod
|
||||||
async def delete_subject(subject_id: int) -> Dict[str, Any]:
|
async def delete_subject(subject_id: int) -> Dict[str, Any]:
|
||||||
"""删除科目(真正删除记录)"""
|
"""删除科目(真正删除记录)"""
|
||||||
|
|||||||
@@ -83,20 +83,6 @@ async def get_connection():
|
|||||||
await conn.commit()
|
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]]:
|
async def execute_query(sql: str, params: tuple = None) -> List[Dict[str, Any]]:
|
||||||
"""执行查询SQL"""
|
"""执行查询SQL"""
|
||||||
async with get_connection() as cursor:
|
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:
|
async with get_connection() as cursor:
|
||||||
await cursor.executemany(sql, params_list)
|
await cursor.executemany(sql, params_list)
|
||||||
return cursor.rowcount
|
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
|
|
||||||
@@ -24,16 +24,24 @@ logger = get_logger(__name__)
|
|||||||
class EmailSender:
|
class EmailSender:
|
||||||
"""SMTP 邮件发送(标准库实现,无需额外依赖)"""
|
"""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
|
@staticmethod
|
||||||
def is_configured() -> bool:
|
def is_configured() -> bool:
|
||||||
"""检查 SMTP 是否已完整配置"""
|
"""检查 SMTP 是否已完整配置"""
|
||||||
return bool(
|
return not EmailSender.missing_config()
|
||||||
settings.SMTP_ENABLED
|
|
||||||
and settings.SMTP_HOST
|
|
||||||
and settings.SMTP_USER
|
|
||||||
and settings.SMTP_PASSWORD
|
|
||||||
and settings.SMTP_FROM
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _send_sync(to_email: str, subject: str, html_body: str) -> None:
|
def _send_sync(to_email: str, subject: str, html_body: str) -> None:
|
||||||
@@ -65,7 +73,7 @@ class EmailSender:
|
|||||||
return False, "邮件服务未配置"
|
return False, "邮件服务未配置"
|
||||||
try:
|
try:
|
||||||
await asyncio.to_thread(EmailSender._send_sync, to_email, subject, html_body)
|
await asyncio.to_thread(EmailSender._send_sync, to_email, subject, html_body)
|
||||||
logger.info(f"邮件发送成功: {to_email} - {subject}")
|
logger.debug(f"邮件发送成功: {to_email} - {subject}")
|
||||||
return True, "发送成功"
|
return True, "发送成功"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"邮件发送失败: {to_email} - {e}")
|
logger.error(f"邮件发送失败: {to_email} - {e}")
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from jose import jwt, JWTError
|
from jose import jwt
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
from typing import Any, Optional, Dict, List
|
from typing import Any
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
|
||||||
@@ -54,53 +54,3 @@ def error_response(
|
|||||||
"data": data
|
"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 passlib.hash import bcrypt as bcrypt_hash
|
||||||
from config import settings
|
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:
|
class SecurityUtils:
|
||||||
"""安全工具类"""
|
"""安全工具类"""
|
||||||
@@ -35,7 +45,9 @@ class SecurityUtils:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def bcrypt_password(password: str) -> str:
|
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)
|
return bcrypt_hash.using(rounds=12).hash(password)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -44,11 +56,19 @@ class SecurityUtils:
|
|||||||
验证密码(支持bcrypt和旧哈希)
|
验证密码(支持bcrypt和旧哈希)
|
||||||
返回: (是否验证成功, 是否需要升级哈希)
|
返回: (是否验证成功, 是否需要升级哈希)
|
||||||
"""
|
"""
|
||||||
try:
|
if hashed_password and hashed_password.startswith(('$2a$', '$2b$', '$2y$')):
|
||||||
if bcrypt_hash.verify(plain_password, hashed_password):
|
if _bcrypt_lib is not None:
|
||||||
return True, False
|
try:
|
||||||
except Exception:
|
if _bcrypt_lib.checkpw(_bcrypt_bytes(plain_password), hashed_password.encode('utf-8')):
|
||||||
pass
|
return True, False
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
if bcrypt_hash.verify(plain_password, hashed_password):
|
||||||
|
return True, False
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
# 回退到旧的sha1_md5验证
|
# 回退到旧的sha1_md5验证
|
||||||
if SecurityUtils.sha1_md5_password(plain_password) == hashed_password:
|
if SecurityUtils.sha1_md5_password(plain_password) == hashed_password:
|
||||||
return True, True
|
return True, True
|
||||||
@@ -66,16 +86,21 @@ class SecurityUtils:
|
|||||||
return ''.join(secrets.choice(alphabet) for _ in range(length))
|
return ''.join(secrets.choice(alphabet) for _ in range(length))
|
||||||
|
|
||||||
@staticmethod
|
@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:
|
if len(password) < min_length:
|
||||||
return False, "密码长度至少6位"
|
return False, f"密码长度至少{min_length}位"
|
||||||
if len(password) > 20:
|
if len(password) > max_length:
|
||||||
return False, "密码长度不能超过20位"
|
return False, f"密码长度不能超过{max_length}位"
|
||||||
|
|
||||||
# 检查四种字符类型
|
# 检查四种字符类型
|
||||||
has_upper = any(c.isupper() for c in password) # 大写字母
|
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])
|
char_types = sum([has_upper, has_lower, has_digit, has_special])
|
||||||
|
|
||||||
if char_types < 3:
|
if char_types < min_types:
|
||||||
return False, "密码必须包含大写字母、小写字母、数字、特殊符号中的至少3种"
|
return False, f"密码必须包含大写字母、小写字母、数字、特殊符号中的至少{min_types}种"
|
||||||
|
|
||||||
return True, ""
|
return True, ""
|
||||||
|
|
||||||
|
|||||||
@@ -70,6 +70,11 @@
|
|||||||
|
|
||||||
> 扣分限制:每次加减分不超过3分。
|
> 扣分限制:每次加减分不超过3分。
|
||||||
|
|
||||||
|
**按次登记**(一次登记覆盖多次作业):
|
||||||
|
1. 先勾选缺交学生,点击"按次登记"
|
||||||
|
2. 选择科目、总提交次数,填写每位缺交学生的缺交次数
|
||||||
|
3. 系统按 缺交次数 × 单次缺交扣分 自动生成扣分记录(受单次扣分上限限制)
|
||||||
|
|
||||||
#### 操行分管理 (conduct.php)
|
#### 操行分管理 (conduct.php)
|
||||||
|
|
||||||
**加减分操作**:
|
**加减分操作**:
|
||||||
@@ -105,6 +110,8 @@
|
|||||||
5. 在学生方格中**点击选择**有考勤异常的学生
|
5. 在学生方格中**点击选择**有考勤异常的学生
|
||||||
6. 点击"提交考勤"批量提交
|
6. 点击"提交考勤"批量提交
|
||||||
|
|
||||||
|
> 考勤页还提供"默认出勤"(按日期范围批量补出勤,自动跳过周末/节假日)与"节假日/补课"校历设置,考勤委员可一并使用。
|
||||||
|
|
||||||
**默认扣分规则**:
|
**默认扣分规则**:
|
||||||
|
|
||||||
| 考勤状态 | 默认扣分 |
|
| 考勤状态 | 默认扣分 |
|
||||||
|
|||||||
@@ -33,11 +33,13 @@
|
|||||||
|
|
||||||
### 学习委员
|
### 学习委员
|
||||||
- **作业扣分**:勾选学生 → 批量加减分 → 选择未交/迟交/自定义 → 填写原因
|
- **作业扣分**:勾选学生 → 批量加减分 → 选择未交/迟交/自定义 → 填写原因
|
||||||
|
- **按次登记**:勾选缺交学生 → 按次登记 → 填总提交次数与每人缺交次数 → 自动按次数扣分
|
||||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值(±5分以内)和原因
|
- **加减分**:勾选学生 → 批量加减分 → 填写分值(±5分以内)和原因
|
||||||
- **科目管理**:添加/编辑/删除科目
|
- **科目管理**:添加/编辑/删除科目
|
||||||
|
|
||||||
### 考勤委员
|
### 考勤委员
|
||||||
- **添加考勤**:选择日期和时段(早上7:15/中午14:00/晚修19:30)→ 选择状态 → 点击选择异常学生 → 提交考勤
|
- **添加考勤**:选择日期和时段(早上7:15/中午14:00/晚修19:30)→ 选择状态 → 点击选择异常学生 → 提交考勤
|
||||||
|
- **默认出勤**:点「默认出勤」选日期范围批量补出勤(自动跳过周末/节假日);「节假日/补课」可查看与手动添加校历
|
||||||
- 默认扣分:缺勤3分、迟到1分、请假0分
|
- 默认扣分:缺勤3分、迟到1分、请假0分
|
||||||
|
|
||||||
### 劳动委员
|
### 劳动委员
|
||||||
|
|||||||
+15
-5
@@ -22,29 +22,39 @@
|
|||||||
| 操行分管理 | 对学生加减分(无限制)、导出德育分记录 |
|
| 操行分管理 | 对学生加减分(无限制)、导出德育分记录 |
|
||||||
| 历史记录 | 查看/导出/撤销全班记录,支持按学期/扣分类型筛选 |
|
| 历史记录 | 查看/导出/撤销全班记录,支持按学期/扣分类型筛选 |
|
||||||
| 个人查询 | 按学生查询基础分、加分、月度分、月度理由汇总及明细,可导出 |
|
| 个人查询 | 按学生查询基础分、加分、月度分、月度理由汇总及明细,可导出 |
|
||||||
| 作业扣分 | 发布缺交作业记录、关联扣分 |
|
| 作业扣分 | 勾选学生批量加减分;按次登记(总提交次数 + 每人缺交次数自动扣分,写入作业统计) |
|
||||||
| 考勤管理 | 按时段(早上/中午/晚修)记录考勤、自定义扣分值 |
|
| 考勤管理 | 按时段(早上/中午/晚修)记录考勤、自定义扣分值;默认出勤批量补全(跳过节假日)、节假日/补课设置 |
|
||||||
| 学生管理 | 新增/编辑/删除/批量导入学生 |
|
| 学生管理 | 新增/编辑/删除/批量导入学生 |
|
||||||
| 科目管理 | 增删改科目信息 |
|
| 科目管理 | 增删改科目信息 |
|
||||||
| 管理员管理 | 添加/编辑姓名和权限组/禁用启用/重置密码/管理自定义权限组与加减分上限 |
|
| 管理员管理 | 添加/编辑姓名和权限组/禁用启用/重置密码/管理自定义权限组与加减分上限 |
|
||||||
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数 |
|
| 操作日志 | 查询关键操作记录(类型/操作人/日期筛选) |
|
||||||
|
| 数据报表 | 考勤/作业统计(按日期范围,支持导出) |
|
||||||
|
| 学期管理 | 创建/编辑/删除/归档学期、关联历史记录、归档重置分数、归档环比 |
|
||||||
|
| 系统设置 | 配置密码策略(长度与字符种类) |
|
||||||
| 修改密码 | 修改登录密码 |
|
| 修改密码 | 修改登录密码 |
|
||||||
|
|
||||||
## 常用操作
|
## 常用操作
|
||||||
|
|
||||||
- **加减分**:勾选学生 → 批量加减分 → 填写分值和原因
|
- **加减分**:勾选学生 → 批量加减分 → 填写分值和原因
|
||||||
|
- **作业按次登记**:作业扣分页 → 勾选缺交学生 → 按次登记 → 填总提交次数与每人缺交次数 → 确认登记
|
||||||
- **导出德育分**:操行分管理页 → 导出德育分记录 → 选择学期(默认当前学期)
|
- **导出德育分**:操行分管理页 → 导出德育分记录 → 选择学期(默认当前学期)
|
||||||
- **导出历史记录**:历史记录页 → 导出(CSV,可按学期/日期/学生筛选,导出全部匹配记录)
|
- **导出历史记录**:历史记录页 → 导出(CSV,可按学期/日期/学生筛选,导出全部匹配记录)
|
||||||
- **个人查询**:个人查询页 → 选择学生和学期 → 查询基础分/加分/月度分/理由汇总,点击学生姓名可直接进入
|
- **个人查询**:个人查询页 → 选择学生和学期 → 查询基础分/加分/月度分/理由汇总,点击学生姓名可直接进入
|
||||||
- **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮
|
- **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮
|
||||||
- **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`)
|
- **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`)
|
||||||
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组
|
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组
|
||||||
- **绑定邮箱/找回密码**:修改密码页 → 绑定邮箱;忘记密码时在登录页点击"忘记密码?"通过邮箱重置
|
- **绑定邮箱/找回密码**:修改密码页 → 输入新邮箱 → 发送验证码 → 输入验证码确认绑定(无需密码);忘记密码时在登录页点击"忘记密码?"通过邮箱获取一次性重置链接
|
||||||
- **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码
|
- **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码
|
||||||
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
||||||
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
||||||
- **学期管理**:学期管理页 → 创建学期(可快捷填充日期)→ 关联历史数据 → 归档(可选重置分数)
|
- **学期管理**:学期管理页 → 创建学期(可快捷填充日期)→ 关联历史数据 → 归档(可选重置分数)
|
||||||
- **排行榜筛选**:首页 → 输入百分比 → 点击筛选(抹零法,如15%显示前15%的学生)
|
- **排行榜筛选/导出**:首页 → 选择"总分排行/月度分排行"(月度可选月份)→ 输入百分比筛选,或点「导出」下载CSV
|
||||||
|
- **默认出勤**:考勤管理 → 点「默认出勤」→ 选日期范围与时段 → 开始补全(自动跳过周末/节假日)
|
||||||
|
- **校历设置**:考勤管理 → 点「节假日/补课」→ 查看接口节假日/调休,手动添加放假或补课日
|
||||||
|
- **数据报表**:数据报表页 → 选择日期范围 → 查询考勤/作业统计 → 各表右上角导出CSV
|
||||||
|
- **操作日志**:操作日志页 → 选择类型/操作人/日期 → 查询
|
||||||
|
- **密码策略**:系统设置页 → 修改长度与字符种类 → 保存(全站即时生效)
|
||||||
|
- **归档对比**:学期管理 → 已归档学期「查看归档」→ 查看与上一学期的分数/名次环比
|
||||||
|
|
||||||
## 常见问题
|
## 常见问题
|
||||||
|
|
||||||
|
|||||||
+141
-21
@@ -26,7 +26,10 @@
|
|||||||
- 操行分管理
|
- 操行分管理
|
||||||
- 导入学生
|
- 导入学生
|
||||||
- 导出德育分记录
|
- 导出德育分记录
|
||||||
- **操行分排行榜**:展示前100名学生的排名、学号、姓名和操行分。排行榜上方提供百分比筛选框,可输入1-100的数字筛选显示前N%的学生(抹零法:如49人×15%=7.35,显示前7人)。
|
- **操行分排行榜**:支持两种排行方式:
|
||||||
|
- **总分排行**:按当前操行分排名(展示前100名)
|
||||||
|
- **月度分排行**:选择月份后按当月净得分排名(月度分 = 当月加分 - 当月减分,与基础分无关),同时展示当月加分/减分
|
||||||
|
- 排行榜上方提供百分比筛选框(抹零法),并支持「导出」按钮将当前排行导出为CSV
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -71,14 +74,27 @@
|
|||||||
|
|
||||||
#### 导出历史记录
|
#### 导出历史记录
|
||||||
1. 设置筛选条件(可选)
|
1. 设置筛选条件(可选)
|
||||||
2. 点击"导出历史记录"按钮
|
2. 点击"导出"按钮,在弹窗中选择导出方式:
|
||||||
|
- **明细记录**:每行一条记录(默认)
|
||||||
|
- **按学生分表**:每个学生一段,包含加分/减分合计与明细,便于发给家长
|
||||||
3. 系统自动生成CSV文件并下载(导出全部匹配记录,不受分页限制)
|
3. 系统自动生成CSV文件并下载(导出全部匹配记录,不受分页限制)
|
||||||
4. 文件格式:`时间,学号,姓名,学期,类型,分数变动,原因,操作人`
|
4. 明细导出格式:`时间,学号,姓名,学期,类型,分数变动,原因,操作人`
|
||||||
|
|
||||||
#### 撤销记录
|
#### 撤销记录
|
||||||
1. 在历史记录列表中找到目标记录
|
1. 在历史记录列表中找到目标记录
|
||||||
2. 点击右侧"撤销"按钮
|
2. 点击右侧"撤销"按钮
|
||||||
3. 确认撤销操作
|
3. 确认撤销操作
|
||||||
|
4. 撤销后记录会移入"已撤销"(状态筛选选"已撤销"可查看并反撤销),学生分数自动恢复
|
||||||
|
|
||||||
|
#### 批量撤销 / 批量反撤销(批次合并视图)
|
||||||
|
1. 勾选"批次合并"后,同一批次的记录会合并为一行
|
||||||
|
2. 点击该行的"批量撤销"可一次撤销整批记录
|
||||||
|
3. 查看"已撤销"状态的批次时,点击"批量反撤销"可一次恢复整批记录
|
||||||
|
4. 撤销/反撤销操作均会写入操作日志(批量操作记录条数与记录ID)
|
||||||
|
|
||||||
|
#### 反撤销(恢复记录)
|
||||||
|
1. 状态筛选选择"已撤销",找到被撤销的记录
|
||||||
|
2. 点击"反撤销"按钮,确认后分数变动重新生效
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -103,6 +119,26 @@
|
|||||||
|
|
||||||
> 扣分限制:每次加减分不超过3分。
|
> 扣分限制:每次加减分不超过3分。
|
||||||
|
|
||||||
|
#### 作业按次登记
|
||||||
|
用于"一次登记覆盖多次作业":先勾选缺交学生,再填写每人缺交次数,系统按 `缺交次数 × 单次缺交扣分` 自动扣分,并写入作业提交数据供"数据报表-作业统计"使用。
|
||||||
|
|
||||||
|
1. 在学生列表中勾选**缺交的学生**
|
||||||
|
2. 点击"按次登记"按钮
|
||||||
|
3. 填写:
|
||||||
|
- **科目**(必选,作业记录归属科目)
|
||||||
|
- **作业名称**(选填,如:第5周数学作业)
|
||||||
|
- **缴交/截止日期**(作业统计按该日期归属)
|
||||||
|
- **总提交次数**(本次登记覆盖几次作业,默认5次)
|
||||||
|
- **单次缺交扣分**(默认取系统配置,可临时调整)
|
||||||
|
- **每位缺交学生的缺交次数**(1 ~ 总提交次数)
|
||||||
|
- 备注(选填)
|
||||||
|
4. 点击"确认登记"
|
||||||
|
|
||||||
|
规则说明:
|
||||||
|
- 未勾选的其他学生自动记为**已交**;缺交学生缺 k 次则记为 k 次未交、其余已交
|
||||||
|
- 扣分生成一条记录(原因如:`[数学]第5周数学作业 缺交 2/5 次`),超过权限组单次扣分上限会被拦截
|
||||||
|
- 与"批量加减分"的区别:批量加减分是所有人同一分值;按次登记是每人按缺交次数自动计算分值
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 5. 考勤管理 (attendance.php)
|
### 5. 考勤管理 (attendance.php)
|
||||||
@@ -126,9 +162,44 @@
|
|||||||
6. 点击"全选"可快速选中所有未记录的学生
|
6. 点击"全选"可快速选中所有未记录的学生
|
||||||
7. 点击"提交考勤"批量提交
|
7. 点击"提交考勤"批量提交
|
||||||
|
|
||||||
|
#### 请假(整天)
|
||||||
|
按学生**当天实际考勤时段**一键请假(不再固定 3 条):
|
||||||
|
|
||||||
|
1. 在学生方格中**点击选择**请假的学生
|
||||||
|
2. 点击工具栏"请假(整天)"按钮,系统按当天作息提交:
|
||||||
|
- 正常上课日(次日仍上课)→ **早/中/晚 3 条**
|
||||||
|
- 放假前一天(半天)→ **仅上午 1 条**
|
||||||
|
- 返校日晚修 → **晚修 1 条**
|
||||||
|
3. 每个时段按"请假"配置扣分(如 1 分/次:半天 1 分、正常日 3 分)
|
||||||
|
|
||||||
|
> 已有的对应时段记录会被更新为请假;如需只标记某个时段,仍用普通"请假"按钮 + 时段选择。
|
||||||
|
|
||||||
#### 查看考勤记录
|
#### 查看考勤记录
|
||||||
- 按日期筛选考勤记录
|
- 按日期筛选考勤记录
|
||||||
- 每条记录显示:学号、姓名、状态、原因、记录人、扣分情况
|
- 每条记录显示:学号、姓名、状态、原因、记录人、扣分金额(如"扣3分",已撤销的注明)
|
||||||
|
|
||||||
|
#### 默认出勤(批量补全)
|
||||||
|
用于给一段时间内没有异常的学生批量补"出勤"记录,让统计报表的出勤率有意义。
|
||||||
|
|
||||||
|
1. 点击工具栏"默认出勤"按钮
|
||||||
|
2. 选择**日期范围**(默认本月1日至今)与**时段**(默认全选早/中/晚)
|
||||||
|
3. 点击"开始补全",完成后提示:上课日/节前半日/返校晚修数量、新增条数、跳过已有条数
|
||||||
|
|
||||||
|
作息规则(常规情况):
|
||||||
|
- **返校日**(非上课日、次日上课,如周日)→ 仅生成**晚修**出勤
|
||||||
|
- **上课日且次日仍上课** → 按所选时段生成(早/中/晚)
|
||||||
|
- **放假前一天**(上课日、次日不上课)→ 仅生成**上午**出勤(中午离校,无下午/晚修);少数需要下午上课的,按正常流程单独补录下午记录即可
|
||||||
|
- **跳过周末与法定节假日**(节假日/调休补班来自国内在线接口,失败时自动切换备用接口)
|
||||||
|
- **调休补班日照常**(接口中的补班日按上课处理);**手动补课日照常**、手动放假日跳过
|
||||||
|
- 已有的考勤记录(含缺勤/迟到/请假)**不会被覆盖**
|
||||||
|
- 单次最长支持 180 天;接口暂时不可用时会提示,本次仅按周末与手动设置判断
|
||||||
|
|
||||||
|
#### 节假日 / 补课设置
|
||||||
|
点击工具栏"节假日/补课"按钮打开校历设置:
|
||||||
|
|
||||||
|
- **查询范围**:查看范围内的法定节假日(放假)、调休补班(按上课)——来自国内在线接口(失败时自动切换备用接口),只读
|
||||||
|
- **手动添加**:添加学校自己的安排,可选择「补课(按上课)」或「放假(按休息)」,可填写备注;手动设置**优先于接口**(例如把某天调休补班改回放假)
|
||||||
|
- 手动添加的记录可随时删除
|
||||||
|
|
||||||
**默认扣分规则**:
|
**默认扣分规则**:
|
||||||
|
|
||||||
@@ -136,7 +207,7 @@
|
|||||||
|---------|---------|
|
|---------|---------|
|
||||||
| 缺勤 | 3分 |
|
| 缺勤 | 3分 |
|
||||||
| 迟到 | 1分 |
|
| 迟到 | 1分 |
|
||||||
| 请假 | 0分 |
|
| 请假 | 按系统配置(如配置为1分,整天请假=3分) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -169,19 +240,23 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 7. 科目管理 (subjects.php)
|
### 7. 科目管理(作业扣分页内)
|
||||||
|
|
||||||
|
科目管理已合并到"作业扣分"页面顶部的折叠面板中。
|
||||||
|
|
||||||
#### 查看科目列表
|
#### 查看科目列表
|
||||||
- 展示所有科目及其状态
|
- 展示所有科目的名称、代码、状态与排序序号
|
||||||
|
- 代码为空时不显示占位
|
||||||
|
|
||||||
#### 添加科目
|
#### 添加科目
|
||||||
1. 点击"添加科目"按钮
|
1. 展开"科目管理"面板,点击"添加科目"
|
||||||
2. 填写科目名称
|
2. 填写科目名称(必填)
|
||||||
3. 可选填科目编码和排序
|
3. 可选填科目代码(最多50字符,用于标识,如 CHI)
|
||||||
4. 点击"确认"
|
4. 点击"确认"
|
||||||
|
|
||||||
#### 管理科目
|
#### 管理科目
|
||||||
- 编辑:修改科目信息
|
- 编辑:修改名称、代码、排序序号(**代码留空可清空**)
|
||||||
|
- 排序:点击科目右侧的 ↑ / ↓ 按钮快速调整顺序
|
||||||
- 删除:删除科目(已有作业关联的科目不可删除)
|
- 删除:删除科目(已有作业关联的科目不可删除)
|
||||||
- 启用/禁用:控制科目状态
|
- 启用/禁用:控制科目状态
|
||||||
|
|
||||||
@@ -202,35 +277,41 @@
|
|||||||
|
|
||||||
#### 编辑管理员
|
#### 编辑管理员
|
||||||
- 点击"编辑"按钮可修改**姓名**、**绑定邮箱**和**权限组**(邮箱留空表示解除绑定)
|
- 点击"编辑"按钮可修改**姓名**、**绑定邮箱**和**权限组**(邮箱留空表示解除绑定)
|
||||||
- 不能修改自己的权限组;锁定权限组(班主任)的账号不可编辑
|
- 编辑自己的账号时:姓名和邮箱可正常修改,**权限组不可修改**(防止把自己锁死;如需调整自己的权限,直接编辑所属权限组本身)
|
||||||
|
|
||||||
#### 重置密码
|
#### 重置密码
|
||||||
1. 点击"重置密码"按钮
|
1. 点击"重置密码"按钮
|
||||||
2. 输入新密码
|
2. 输入新密码
|
||||||
3. 点击"确认重置"
|
3. 点击"确认重置"
|
||||||
|
4. 重置后该账号**下次登录需重新设置密码**(弹窗设置,无需输入原密码)
|
||||||
|
|
||||||
#### 禁用/启用管理员
|
#### 禁用/启用管理员
|
||||||
- 点击"禁用/启用"切换账号状态,禁用后无法登录
|
- 点击"禁用/启用"切换账号状态,禁用后无法登录
|
||||||
- 不能禁用当前登录的账号
|
- 不能禁用当前登录的账号
|
||||||
|
|
||||||
|
#### 邮件测试
|
||||||
|
- 点击页面上方"邮件测试"按钮,输入接收邮箱,可验证 SMTP 配置是否可用
|
||||||
|
- 发送失败时会显示具体错误(如授权码错误、连接超时等),便于排查配置
|
||||||
|
|
||||||
#### 权限组管理
|
#### 权限组管理
|
||||||
页面下方为权限组列表,可查看每个组的权限项、加减分上限、成员数与说明。
|
页面下方为权限组列表,可查看每个组的权限项、加减分上限、成员数与说明。
|
||||||
|
|
||||||
**新建权限组**:
|
**新建权限组**:
|
||||||
1. 点击"新建权限组"
|
1. 点击"新建权限组"
|
||||||
2. 填写权限组名称(如"纪律委员")和说明
|
2. 填写权限组名称(如"纪律委员")和说明
|
||||||
3. 勾选功能权限(学生管理、导出学生名单、操行分加减、撤销记录、反撤销、作业扣分、考勤管理、科目管理、管理员管理、学期管理、查看全班/个人查询、数据导出、系统升级等)
|
3. 勾选功能权限(学生管理、导出学生名单、操行分加减、撤销记录、反撤销、作业扣分、作业按次登记、考勤管理、考勤默认出勤、节假日/补课设置、科目管理、查看全班/个人查询、数据报表查看、数据导出、操作日志查看、系统设置、管理员管理、学期管理、系统升级等)
|
||||||
4. 设置加减分上限:
|
4. 设置加减分上限:
|
||||||
- **允许加分** + **单次加分上限**(留空为无限制)
|
- **允许加分** + **单次加分上限**(留空为无限制)
|
||||||
- **允许扣分** + **单次扣分上限**(留空为无限制)
|
- **允许扣分** + **单次扣分上限**(留空为无限制)
|
||||||
5. 点击"保存"
|
5. 点击"保存"
|
||||||
|
|
||||||
**编辑权限组**:
|
**编辑权限组**:
|
||||||
- 点击预置组或自定义组的"编辑"可随时调整权限与上限
|
- 点击任意权限组的"编辑"可随时调整权限与上限(含预置组)
|
||||||
- 班主任组为系统锁定组,不可编辑、不可删除、不可分配给其他账号
|
- 权限项按"学生 / 操行分 / 教务 / 系统管理"分组展示,支持一键全选/清空
|
||||||
|
- 预置组默认:学习委员含"作业按次登记",考勤委员含"考勤默认出勤",班长/志愿委员含"数据报表查看";"节假日/补课设置""操作日志查看""系统设置"默认仅班主任(均可在编辑中调整)
|
||||||
|
|
||||||
**删除权限组**:
|
**删除权限组**:
|
||||||
- 仅自定义组可删除;组内仍有管理员时需先调整成员权限组
|
- 任何权限组均可删除;组内仍有管理员时需先把成员调整到其他组
|
||||||
|
|
||||||
> 权限组调整后,相关管理员刷新页面或最多60秒后自动生效。
|
> 权限组调整后,相关管理员刷新页面或最多60秒后自动生效。
|
||||||
|
|
||||||
@@ -285,6 +366,7 @@
|
|||||||
#### 查看归档数据
|
#### 查看归档数据
|
||||||
- 已归档学期显示"查看归档"按钮
|
- 已归档学期显示"查看归档"按钮
|
||||||
- 展示归档时的学生排名、操行分、考勤统计、作业统计
|
- 展示归档时的学生排名、操行分、考勤统计、作业统计
|
||||||
|
- **环比上次**:同时展示与上一个已归档学期的「分数变化」(+/-)与「排名变化」(↑进步 / ↓退步)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -300,11 +382,13 @@
|
|||||||
也可在"学生管理"或"操行分管理"页面点击学生姓名直接跳转到该学生的查询页。
|
也可在"学生管理"或"操行分管理"页面点击学生姓名直接跳转到该学生的查询页。
|
||||||
|
|
||||||
#### 查询内容
|
#### 查询内容
|
||||||
- **汇总卡片**:基础分、加分合计、减分合计、得分(基础分+加减分)、当前实时总分
|
- **汇总卡片**:基础分、加分合计、减分合计、总分(基础分 + 加分 - 减分)、当前实时总分
|
||||||
- **月度操行分**:月份、月初分、加分、减分、月末分、记录数
|
- **月度操行分**:月份、加分、减分、月度分(当月净得分,与基础分无关)、记录数
|
||||||
- **月度加减分理由汇总**:按月份分别列出加分理由、减分理由(含次数与合计分值)
|
- **月度加减分理由汇总**:按月份分别列出加分理由、减分理由(含次数与合计分值)
|
||||||
- **明细记录**:该学生的所有操行分记录(分页),班主任/班长可直接撤销或反撤销
|
- **明细记录**:该学生的所有操行分记录(分页),班主任/班长可直接撤销或反撤销
|
||||||
|
|
||||||
|
> 月度分是每个月独立的加/减分净得分;基础分只参与总分的计算。
|
||||||
|
|
||||||
#### 导出个人记录
|
#### 导出个人记录
|
||||||
点击"导出个人记录"按钮,生成包含汇总信息与全部明细的CSV文件(受当前学生/学期筛选影响)。
|
点击"导出个人记录"按钮,生成包含汇总信息与全部明细的CSV文件(受当前学生/学期筛选影响)。
|
||||||
|
|
||||||
@@ -313,16 +397,52 @@
|
|||||||
### 11. 修改密码 (password.php)
|
### 11. 修改密码 (password.php)
|
||||||
|
|
||||||
- 输入原密码和新密码
|
- 输入原密码和新密码
|
||||||
- 新密码需符合密码强度要求
|
- 新密码需符合密码强度要求(密码策略可在「系统设置」中调整)
|
||||||
- 修改成功后需重新登录
|
- 修改成功后需重新登录
|
||||||
- 页面下方可**绑定邮箱**(需输入当前密码):绑定后忘记密码时可在登录页自助申请重置邮件;留空保存则解除绑定
|
- **密码待修改时(首次使用或被管理员重置后)**:登录时会弹窗要求设置新密码(**无需输入原密码**);日常主动改密仍需原密码
|
||||||
|
- 页面下方可**绑定邮箱**(找回密码用):
|
||||||
|
1. 输入新邮箱,点击"发送验证码"(无需密码)
|
||||||
|
2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效)
|
||||||
|
3. 输入验证码后点击"确认绑定"
|
||||||
|
4. 输入当前密码后点击"解除绑定"可解除已绑定邮箱
|
||||||
|
- 管理员管理页添加/编辑账号时也可由班主任直接填写绑定邮箱
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 12. 数据报表 (reports.php)
|
||||||
|
|
||||||
|
用于按日期范围统计全班考勤与作业情况。
|
||||||
|
|
||||||
|
- 选择**开始日期 / 结束日期**(默认当前学期至今),点击"查询"
|
||||||
|
- **考勤统计**:每人出勤/缺勤/迟到/请假次数、记录数、出勤率,按缺勤与迟到降序排列
|
||||||
|
- **作业统计**:每人已交/未交/迟交次数、记录数、未交率,按未交与迟交降序排列
|
||||||
|
- 各表右上角「导出」按钮可导出对应CSV
|
||||||
|
|
||||||
|
> 作业统计按作业截止日期归属;考勤按考勤记录日期归属。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 13. 操作日志 (logs.php)
|
||||||
|
|
||||||
|
用于审计管理端所有关键操作。
|
||||||
|
|
||||||
|
- 支持按**操作类型**、**操作人/角色关键词**、**详情关键词**(学生姓名/记录原因等)、**日期范围**筛选
|
||||||
|
- 分页展示:时间、操作人、角色、操作类型、对象、详情、IP
|
||||||
|
- 操行分相关日志详情包含:学生姓名(学号)、分值变动、原因、原操作人;批量撤销/反撤销会记录条数与记录ID
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 14. 系统设置 (settings.php)
|
||||||
|
|
||||||
|
- **密码策略**:配置密码最小长度、最大长度、最少字符种类数(大写/小写/数字/特殊符号)
|
||||||
|
- 保存后立即生效:修改密码、重置密码、邮箱重置等所有入口统一按该策略校验,前端提示同步更新
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 常见问题
|
## 常见问题
|
||||||
|
|
||||||
### Q: 忘记密码怎么办?
|
### Q: 忘记密码怎么办?
|
||||||
1. 已在管理端绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送重置链接(30分钟内有效);
|
1. 已绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送**一次性重置链接**(30分钟内有效、仅可使用一次);
|
||||||
2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。
|
2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。
|
||||||
|
|
||||||
### Q: 如何导出全班德育分记录?
|
### Q: 如何导出全班德育分记录?
|
||||||
|
|||||||
@@ -24,12 +24,8 @@ USER_STORAGE_KEY=class_system_user
|
|||||||
# 站点名称
|
# 站点名称
|
||||||
SITE_NAME=班级操行分管理系统
|
SITE_NAME=班级操行分管理系统
|
||||||
|
|
||||||
# 会话超时时间(分钟)
|
|
||||||
SESSION_TIMEOUT=30
|
|
||||||
|
|
||||||
# ICP备案号配置
|
# ICP备案号配置
|
||||||
# 是否启用ICP备案号显示 - true/false
|
# 是否启用ICP备案号显示 - true/false
|
||||||
ICP_ENABLED=false
|
ICP_ENABLED=false
|
||||||
# ICP备案号
|
# ICP备案号
|
||||||
ICP_NUMBER=京ICP备1234567890号-x
|
ICP_NUMBER=京ICP备1234567890号-x
|
||||||
STUDENT_INITIAL_POINTS=60
|
|
||||||
+41
-24
@@ -29,7 +29,10 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="action-bar">
|
<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>
|
||||||
<div class="table-wrapper">
|
<div class="table-wrapper">
|
||||||
<table class="table">
|
<table class="table">
|
||||||
@@ -43,7 +46,9 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="action-bar">
|
<div class="action-bar">
|
||||||
<button class="btn btn-primary" onclick="showAddGroupModal()">新建权限组</button>
|
<div class="action-buttons">
|
||||||
|
<button class="btn btn-primary" onclick="showAddGroupModal()">新建权限组</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="table-wrapper">
|
<div class="table-wrapper">
|
||||||
<table class="table">
|
<table class="table">
|
||||||
@@ -122,6 +127,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<select id="editAdminGroupId" required>
|
<select id="editAdminGroupId" required>
|
||||||
<option value="">请选择权限组</option>
|
<option value="">请选择权限组</option>
|
||||||
</select>
|
</select>
|
||||||
|
<small id="editAdminGroupHint" style="display:none;">当前登录账号的权限组不可修改(可编辑权限组本身来调整)</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="submit" class="btn btn-primary">保存</button>
|
<button type="submit" class="btn btn-primary">保存</button>
|
||||||
@@ -133,41 +139,51 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
|
|
||||||
<!-- 权限组模态框 -->
|
<!-- 权限组模态框 -->
|
||||||
<div id="groupModal" class="modal">
|
<div id="groupModal" class="modal">
|
||||||
<div class="modal-content" style="max-width: 640px;">
|
<div class="modal-content" style="width: 760px; max-width: 92%;">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h3 id="groupModalTitle">新建权限组</h3>
|
<h3 id="groupModalTitle">新建权限组</h3>
|
||||||
<button class="modal-close" onclick="closeModal('groupModal')">×</button>
|
<button class="modal-close" onclick="closeModal('groupModal')">×</button>
|
||||||
</div>
|
</div>
|
||||||
<form onsubmit="event.preventDefault(); submitGroupForm()">
|
<form onsubmit="event.preventDefault(); submitGroupForm()">
|
||||||
<input type="hidden" id="editGroupId">
|
<input type="hidden" id="editGroupId">
|
||||||
<div class="form-group">
|
<div style="display:flex; gap:12px; flex-wrap:wrap;">
|
||||||
<label>权限组名称 <span style="color:red;">*</span></label>
|
<div class="form-group" style="flex:1; min-width:220px;">
|
||||||
<input type="text" id="groupName" required maxlength="50" placeholder="如:纪律委员">
|
<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>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>说明</label>
|
<div class="perm-header">
|
||||||
<input type="text" id="groupDescription" maxlength="255" placeholder="选填">
|
<label style="margin:0;">权限项</label>
|
||||||
</div>
|
<div>
|
||||||
<div class="form-group">
|
<button type="button" class="btn btn-sm btn-ghost" onclick="selectAllPermissions(true)">全选</button>
|
||||||
<label>权限项</label>
|
<button type="button" class="btn btn-sm btn-ghost" onclick="selectAllPermissions(false)">清空</button>
|
||||||
<div id="groupPermissionList" style="display:grid; grid-template-columns: repeat(2, 1fr); gap:8px;"></div>
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="groupPermissionList"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>加减分上限</label>
|
<label>加减分上限</label>
|
||||||
<div style="display:flex; flex-wrap:wrap; gap:16px; align-items:center;">
|
<div class="perm-cap-row">
|
||||||
<label style="display:flex; align-items:center; gap:6px;">
|
<label class="check-item">
|
||||||
<input type="checkbox" id="groupCanAdd" checked onchange="onGroupCapChange()"> 允许加分
|
<input type="checkbox" id="groupCanAdd" checked onchange="onGroupCapChange()"> 允许加分
|
||||||
</label>
|
</label>
|
||||||
<label style="display:flex; align-items:center; gap:6px;">
|
<label class="check-item">
|
||||||
单次加分上限
|
单次加分上限
|
||||||
<input type="number" id="groupMaxAdd" min="1" max="100" style="width:90px;" placeholder="留空=不限">
|
<input type="number" id="groupMaxAdd" min="1" max="100" style="width:100px;" placeholder="留空=不限">
|
||||||
</label>
|
</label>
|
||||||
<label style="display:flex; align-items:center; gap:6px;">
|
</div>
|
||||||
|
<div class="perm-cap-row">
|
||||||
|
<label class="check-item">
|
||||||
<input type="checkbox" id="groupCanSubtract" checked onchange="onGroupCapChange()"> 允许扣分
|
<input type="checkbox" id="groupCanSubtract" checked onchange="onGroupCapChange()"> 允许扣分
|
||||||
</label>
|
</label>
|
||||||
<label style="display:flex; align-items:center; gap:6px;">
|
<label class="check-item">
|
||||||
单次扣分上限
|
单次扣分上限
|
||||||
<input type="number" id="groupMaxSubtract" min="1" max="100" style="width:90px;" placeholder="留空=不限">
|
<input type="number" id="groupMaxSubtract" min="1" max="100" style="width:100px;" placeholder="留空=不限">
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<small>上限必须在1-100之间,留空表示无限制</small>
|
<small>上限必须在1-100之间,留空表示无限制</small>
|
||||||
@@ -195,8 +211,8 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>新密码</label>
|
<label>新密码</label>
|
||||||
<input type="text" id="newPassword" required minlength="6" placeholder="请输入新密码(至少6位)">
|
<input type="text" id="newPassword" required placeholder="请输入新密码">
|
||||||
<small>密码长度至少6位</small>
|
<small class="pwd-policy">密码长度至少6位</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="submit" class="btn btn-primary">确认重置</button>
|
<button type="submit" class="btn btn-primary">确认重置</button>
|
||||||
@@ -206,8 +222,9 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
<script>window.PAGE_CONFIG = { userId: <?php echo intval($_SESSION['user_id']); ?> };</script>
|
||||||
<script src="/assets/js/modules/admin-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/admins.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'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -47,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="late" onclick="selectStatus(this)" id="btnLate">迟到</button>
|
||||||
<button class="status-btn" data-status="leave" onclick="selectStatus(this)" id="btnLeave">请假</button>
|
<button class="status-btn" data-status="leave" onclick="selectStatus(this)" id="btnLeave">请假</button>
|
||||||
</div>
|
</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>
|
<button class="btn btn-danger" onclick="submitAttendance()">提交考勤</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="attendance-toolbar">
|
<div class="attendance-toolbar">
|
||||||
@@ -65,7 +72,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
|
|
||||||
<!-- 学生方格网格 -->
|
<!-- 学生方格网格 -->
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-title">点击选择有考勤异常的学生</div>
|
<div class="card-title">点击选择有考勤异常的学生(默认出勤记录也可选中覆盖为异常)</div>
|
||||||
<div class="student-grid" id="studentGrid">
|
<div class="student-grid" id="studentGrid">
|
||||||
<!-- JS 动态生成 -->
|
<!-- JS 动态生成 -->
|
||||||
</div>
|
</div>
|
||||||
@@ -90,7 +97,75 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
.student-cell-name { font-size: 14px; font-weight: 500; }
|
.student-cell-name { font-size: 14px; font-weight: 500; }
|
||||||
.student-cell-no { font-size: 11px; color: #999; }
|
.student-cell-no { font-size: 11px; color: #999; }
|
||||||
</style>
|
</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'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -19,6 +19,7 @@ if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
|
|||||||
|
|
||||||
$page_title = '操行分管理';
|
$page_title = '操行分管理';
|
||||||
$role = current_group_name();
|
$role = current_group_name();
|
||||||
|
require_perm('manage_conduct');
|
||||||
|
|
||||||
include __DIR__ . '/../includes/header.php';
|
include __DIR__ . '/../includes/header.php';
|
||||||
?>
|
?>
|
||||||
@@ -57,10 +58,9 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/conduct.js'); ?>"></script>
|
||||||
<script src="/assets/js/conduct.js"></script>
|
|
||||||
|
|
||||||
<!-- 批量加减分模态框 -->
|
<!-- 批量加减分模态框 -->
|
||||||
<div id="batchPointsModal" class="modal">
|
<div id="batchPointsModal" class="modal">
|
||||||
@@ -139,7 +139,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
<div class="form-group" id="dormitoryStudentsGroup" style="display:none;">
|
<div class="form-group" id="dormitoryStudentsGroup" style="display:none;">
|
||||||
<label>宿舍成员</label>
|
<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>
|
</div>
|
||||||
<small id="dormitoryStudentsCount"></small>
|
<small id="dormitoryStudentsCount"></small>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -35,16 +35,24 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-title">操行分排行榜</div>
|
<div class="card-title">操行分排行榜</div>
|
||||||
<div class="table-wrapper">
|
<div class="table-wrapper">
|
||||||
<div style="display: flex; align-items: center; margin-bottom: 12px; gap: 8px;">
|
<div class="ranking-toolbar">
|
||||||
<span style="font-size: 14px; color: #666;">显示前</span>
|
<select id="rankingType" onchange="onRankingTypeChange()">
|
||||||
<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">
|
<option value="total">总分排行</option>
|
||||||
<span style="font-size: 14px; color: #666;">% 的学生</span>
|
<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-primary" onclick="applyPercentileFilter()">筛选</button>
|
||||||
<button class="btn btn-sm btn-ghost" onclick="resetPercentileFilter()">显示全部</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>
|
</div>
|
||||||
<table class="table">
|
<table class="table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>排名</th><th>学号</th><th>姓名</th><th>操行分</th></tr>
|
<tr id="rankingHead"><th>排名</th><th>学号</th><th>姓名</th><th>操行分</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="rankingList"></tbody>
|
<tbody id="rankingList"></tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -80,7 +88,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||||
<script src="/assets/js/dashboard.js"></script>
|
<script src="<?php echo asset_url('/assets/js/dashboard.js'); ?>"></script>
|
||||||
|
|
||||||
<?php if (has_perm('manage_upgrade')): ?>
|
<?php if (has_perm('manage_upgrade')): ?>
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<?php if (has_perm('export_data')): ?>
|
<?php if (has_perm('export_data')): ?>
|
||||||
<button class="btn btn-secondary" onclick="exportHistoryRecords()">导出</button>
|
<button class="btn btn-secondary" onclick="showExportHistoryModal()">导出</button>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</div>
|
</div>
|
||||||
<!-- 高级筛选面板(默认折叠) -->
|
<!-- 高级筛选面板(默认折叠) -->
|
||||||
@@ -105,7 +105,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<th>学生</th>
|
<th>学生</th>
|
||||||
<th style="white-space: nowrap; min-width: 80px;">操作人</th>
|
<th style="white-space: nowrap; min-width: 80px;">操作人</th>
|
||||||
<th>时间</th>
|
<th>时间</th>
|
||||||
<?php if (has_perm('revoke_any') || has_perm('revoke_own')): ?>
|
<?php if (has_perm('revoke_any') || has_perm('revoke_own') || has_perm('restore_records')): ?>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -118,9 +118,34 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>', userId: <?php echo intval($_SESSION['user_id']); ?> };</script>
|
<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="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/history.js'); ?>"></script>
|
||||||
<script src="/assets/js/history.js"></script>
|
|
||||||
|
<!-- 导出历史记录模态框 -->
|
||||||
|
<div id="exportHistoryModal" class="modal">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>导出历史记录</h3>
|
||||||
|
<button class="modal-close" onclick="closeModal('exportHistoryModal')">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>导出方式</label>
|
||||||
|
<div class="check-grid" style="grid-template-columns: 1fr;">
|
||||||
|
<label class="check-item">
|
||||||
|
<input type="radio" name="historyExportMode" value="detail" checked> 明细记录(每行一条记录)
|
||||||
|
</label>
|
||||||
|
<label class="check-item">
|
||||||
|
<input type="radio" name="historyExportMode" value="per_student"> 按学生分表(每人一段,便于发给家长)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<small>导出内容跟随当前筛选条件;已撤销记录不导出</small>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-primary" onclick="exportHistoryRecords()">开始导出</button>
|
||||||
|
<button type="button" class="btn" onclick="closeModal('exportHistoryModal')">取消</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
+73
-23
@@ -47,6 +47,9 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="action-bar">
|
<div class="action-bar">
|
||||||
<div class="action-buttons">
|
<div class="action-buttons">
|
||||||
<button class="btn btn-primary" onclick="showBatchPointsModal()">批量加减分</button>
|
<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>
|
</div>
|
||||||
<div class="table-wrapper">
|
<div class="table-wrapper">
|
||||||
@@ -119,6 +122,57 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
</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 id="addSubjectModal" class="modal">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
@@ -129,12 +183,12 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<form id="addSubjectFormInHw" onsubmit="event.preventDefault(); submitAddSubject()">
|
<form id="addSubjectFormInHw" onsubmit="event.preventDefault(); submitAddSubject()">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>科目名称</label>
|
<label>科目名称</label>
|
||||||
<input type="text" id="subjectName" required placeholder="例如:语文、数学">
|
<input type="text" id="subjectName" required maxlength="50" placeholder="例如:语文、数学">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>科目代码</label>
|
<label>科目代码</label>
|
||||||
<input type="text" id="subjectCode" placeholder="例如:CHI、MATH">
|
<input type="text" id="subjectCode" maxlength="50" placeholder="例如:CHI、MATH">
|
||||||
<small>可选,用于排序和标识</small>
|
<small>可选,用于标识科目;排序可用列表中的 ↑ ↓ 调整</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="submit" class="btn btn-primary">添加</button>
|
<button type="submit" class="btn btn-primary">添加</button>
|
||||||
@@ -155,11 +209,11 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<input type="hidden" id="editSubjectId">
|
<input type="hidden" id="editSubjectId">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>科目名称</label>
|
<label>科目名称</label>
|
||||||
<input type="text" id="editSubjectName" required placeholder="例如:语文、数学">
|
<input type="text" id="editSubjectName" required maxlength="50" placeholder="例如:语文、数学">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>科目代码</label>
|
<label>科目代码</label>
|
||||||
<input type="text" id="editSubjectCode" placeholder="例如:CHI、MATH">
|
<input type="text" id="editSubjectCode" maxlength="50" placeholder="例如:CHI、MATH">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>排序序号</label>
|
<label>排序序号</label>
|
||||||
@@ -185,7 +239,17 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
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 {
|
.subject-name {
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
@@ -195,19 +259,6 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
font-size: 12px;
|
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 {
|
.collapsible-card .collapsible-header {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -238,9 +289,8 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</script>
|
<script>window.PAGE_CONFIG = { role: '<?php echo $role; ?>' };</script>
|
||||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/homework-manage.js'); ?>"></script>
|
||||||
<script src="/assets/js/homework-manage.js"></script>
|
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?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'; ?>
|
||||||
+82
-26
@@ -36,7 +36,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>新密码 <span style="color:red;">*</span></label>
|
<label>新密码 <span style="color:red;">*</span></label>
|
||||||
<input type="password" id="newPassword" required>
|
<input type="password" id="newPassword" required>
|
||||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>确认新密码 <span style="color:red;">*</span></label>
|
<label>确认新密码 <span style="color:red;">*</span></label>
|
||||||
@@ -49,24 +49,35 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-title">绑定邮箱(找回密码)</div>
|
<div class="card-title">绑定邮箱(找回密码)</div>
|
||||||
<p style="font-size:13px; color:var(--color-text-secondary); margin-bottom:12px;">
|
<p style="font-size:13px; color:var(--color-text-secondary); margin-bottom:12px;">
|
||||||
绑定邮箱后,忘记密码时可在登录页通过“忘记密码”向该邮箱发送重置链接。
|
绑定邮箱需通过邮箱验证码验证;忘记密码时可在登录页通过该邮箱获取一次性重置链接。
|
||||||
</p>
|
</p>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>当前绑定邮箱</label>
|
<label>当前绑定邮箱</label>
|
||||||
<div id="currentEmail"><?php echo $bound_email ? htmlspecialchars($bound_email) : '未绑定'; ?></div>
|
<div id="currentEmail"><?php echo $bound_email ? htmlspecialchars($bound_email) : '未绑定'; ?></div>
|
||||||
</div>
|
</div>
|
||||||
<form id="emailForm">
|
<div class="form-group">
|
||||||
<div class="form-group">
|
<label>新邮箱</label>
|
||||||
<label>新邮箱</label>
|
<input type="email" id="bindEmail" maxlength="100" placeholder="请输入要绑定的邮箱">
|
||||||
<input type="email" id="bindEmail" maxlength="100" placeholder="留空则解除绑定">
|
</div>
|
||||||
</div>
|
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||||
<div class="form-group">
|
<button type="button" class="btn btn-secondary" onclick="sendBindEmailCode()">发送验证码</button>
|
||||||
<label>当前密码 <span style="color:red;">*</span></label>
|
</div>
|
||||||
<input type="password" id="emailPassword" required>
|
<div class="form-group" style="margin-top:16px;">
|
||||||
<small>安全验证:绑定邮箱需要输入当前登录密码</small>
|
<label>邮箱验证码</label>
|
||||||
</div>
|
<input type="text" id="emailCode" maxlength="6" inputmode="numeric" placeholder="请输入6位验证码">
|
||||||
<button type="submit" class="btn btn-primary">保存邮箱</button>
|
</div>
|
||||||
</form>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -83,8 +94,9 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newPassword.length < 6 || newPassword.length > 20) {
|
const policyError = validatePasswordByPolicy(newPassword);
|
||||||
showToast('密码长度需为6-20位', 'error');
|
if (policyError) {
|
||||||
|
showToast(policyError, 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,28 +113,72 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('emailForm').addEventListener('submit', async (e) => {
|
async function sendBindEmailCode() {
|
||||||
e.preventDefault();
|
|
||||||
const email = document.getElementById('bindEmail').value.trim();
|
const email = document.getElementById('bindEmail').value.trim();
|
||||||
const password = document.getElementById('emailPassword').value;
|
if (!email) {
|
||||||
if (!password) {
|
showToast('请输入要绑定的邮箱', 'warning');
|
||||||
showToast('请输入当前密码', 'warning');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const res = await apiPost('/api/auth/bind-email', {
|
const res = await apiPost('/api/auth/email/send-code', {
|
||||||
password: password,
|
|
||||||
email: email
|
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) {
|
if (res && res.success) {
|
||||||
const bound = res.data && res.data.email ? res.data.email : '';
|
const bound = res.data && res.data.email ? res.data.email : '';
|
||||||
document.getElementById('currentEmail').textContent = bound || '未绑定';
|
document.getElementById('currentEmail').textContent = bound || '未绑定';
|
||||||
document.getElementById('bindEmail').value = '';
|
document.getElementById('bindEmail').value = '';
|
||||||
document.getElementById('emailPassword').value = '';
|
document.getElementById('emailPassword').value = '';
|
||||||
showToast(res.message || '邮箱保存成功');
|
document.getElementById('emailCode').value = '';
|
||||||
|
showToast(res.message || '邮箱绑定成功');
|
||||||
} else {
|
} else {
|
||||||
showToast(res?.message || '邮箱保存失败', 'error');
|
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>
|
</script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -65,10 +65,9 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>月份</th>
|
<th>月份</th>
|
||||||
<th>月初分</th>
|
|
||||||
<th>加分</th>
|
<th>加分</th>
|
||||||
<th>减分</th>
|
<th>减分</th>
|
||||||
<th>月末分</th>
|
<th>月度分</th>
|
||||||
<th>记录数</th>
|
<th>记录数</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -107,8 +106,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>', userId: <?php echo intval($_SESSION['user_id']); ?> };</script>
|
<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="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/record-query.js'); ?>"></script>
|
||||||
<script src="/assets/js/record-query.js"></script>
|
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?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'; ?>
|
||||||
@@ -170,12 +170,15 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<th colspan="2" style="text-align:center; border-bottom: none;">基本信息</th>
|
<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 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="4" style="text-align:center; border-bottom: none;">考勤统计</th>
|
||||||
<th colspan="3" style="text-align:center; border-bottom: none;">作业统计</th>
|
<th colspan="3" style="text-align:center; border-bottom: none;">作业统计</th>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th>排名</th>
|
<th>排名</th>
|
||||||
<th>学号</th>
|
<th>学号</th>
|
||||||
|
<th>分数变化</th>
|
||||||
|
<th>排名变化</th>
|
||||||
<th>出勤</th>
|
<th>出勤</th>
|
||||||
<th>缺勤</th>
|
<th>缺勤</th>
|
||||||
<th>迟到</th>
|
<th>迟到</th>
|
||||||
@@ -195,7 +198,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/semesters.js"></script>
|
<script src="<?php echo asset_url('/assets/js/semesters.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?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'; ?>
|
||||||
+14
-15
@@ -73,8 +73,8 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<p>点击选择JSON文件</p>
|
<p>点击选择JSON文件</p>
|
||||||
<p class="import-label">或点击此处上传</p>
|
<p class="import-label">或点击此处上传</p>
|
||||||
<input type="file" id="importFile" accept=".json">
|
<input type="file" id="importFile" accept=".json">
|
||||||
<p style="margin-top: 10px; font-size: 12px; color: #999;">
|
<p style="margin-top: 10px; font-size: 12px; color: var(--color-text-muted);">
|
||||||
<a href="/assets/uploads/sample_import.json" download style="color: #667eea;">下载示例文件</a>
|
<a href="/assets/uploads/sample_import.json" download class="link">下载示例文件</a>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div id="importPreview" class="preview-table" style="display: none;"></div>
|
<div id="importPreview" class="preview-table" style="display: none;"></div>
|
||||||
@@ -163,7 +163,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<p id="resetStudentInfo" style="margin: 10px 0;"></p>
|
<p id="resetStudentInfo" style="margin: 10px 0;"></p>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>新密码</label>
|
<label>新密码</label>
|
||||||
<input type="password" id="newStudentPassword" required minlength="6" maxlength="20">
|
<input type="password" id="newStudentPassword" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="submit" class="btn btn-warning">确认重置</button>
|
<button type="submit" class="btn btn-warning">确认重置</button>
|
||||||
@@ -174,11 +174,10 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
<script>window.PAGE_CONFIG = { role: '<?php echo htmlspecialchars($role, ENT_QUOTES, 'UTF-8'); ?>' };</script>
|
||||||
<script src="/assets/js/modules/modal-utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/modal-utils.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/student-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/student-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/students-manage.js'); ?>"></script>
|
||||||
<script src="/assets/js/students-manage.js"></script>
|
|
||||||
|
|
||||||
<!-- 导出学生名单模态框 -->
|
<!-- 导出学生名单模态框 -->
|
||||||
<div id="exportStudentsModal" class="modal">
|
<div id="exportStudentsModal" class="modal">
|
||||||
@@ -189,15 +188,15 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>导出字段</label>
|
<label>导出字段</label>
|
||||||
<div style="display:grid; grid-template-columns: repeat(2, 1fr); gap:8px;">
|
<div class="check-grid">
|
||||||
<label><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="student_no" checked disabled> 学号</label>
|
||||||
<label><input type="checkbox" class="export-student-col" value="name" checked disabled> 姓名</label>
|
<label class="check-item"><input type="checkbox" class="export-student-col" value="name" checked disabled> 姓名</label>
|
||||||
<label><input type="checkbox" class="export-student-col" value="dormitory_number" checked> 宿舍号</label>
|
<label class="check-item"><input type="checkbox" class="export-student-col" value="dormitory_number" checked> 宿舍号</label>
|
||||||
<label><input type="checkbox" class="export-student-col" value="total_points" checked> 当前操行分</label>
|
<label class="check-item"><input type="checkbox" class="export-student-col" value="total_points" checked> 当前操行分</label>
|
||||||
<?php if (has_perm('manage_students')): ?>
|
<?php if (has_perm('manage_students')): ?>
|
||||||
<label><input type="checkbox" class="export-student-col" value="parent_phone"> 家长手机号</label>
|
<label class="check-item"><input type="checkbox" class="export-student-col" value="parent_phone"> 家长手机号</label>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<label><input type="checkbox" class="export-student-col" value="status" checked> 状态</label>
|
<label class="check-item"><input type="checkbox" class="export-student-col" value="status" checked> 状态</label>
|
||||||
</div>
|
</div>
|
||||||
<small>导出全班学生名单(CSV,可用Excel打开)</small>
|
<small>导出全班学生名单(CSV,可用Excel打开)</small>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -263,3 +263,173 @@
|
|||||||
white-space: normal;
|
white-space: normal;
|
||||||
word-break: break-word;
|
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 {
|
.table-wrapper {
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
overflow-y: visible;
|
overflow-y: visible;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
}
|
}
|
||||||
|
|
||||||
table {
|
table {
|
||||||
@@ -442,16 +443,6 @@ tr:hover {
|
|||||||
border-color: var(--color-text-muted);
|
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 {
|
.btn-sm {
|
||||||
padding: 4px 10px;
|
padding: 4px 10px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
@@ -808,12 +799,40 @@ tr:hover {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.nav {
|
.nav {
|
||||||
padding: 0 16px;
|
padding: 0 12px;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.nav-item {
|
.nav-item {
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
font-size: 13px;
|
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 {
|
.action-bar {
|
||||||
@@ -1001,3 +1020,24 @@ td.history-reason {
|
|||||||
border-color: var(--color-danger-dark);
|
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 - 加减分管理函数
|
|
||||||
*/
|
|
||||||
@@ -18,18 +18,33 @@ const PERMISSION_LABELS = {
|
|||||||
revoke_own: '撤销自己的记录',
|
revoke_own: '撤销自己的记录',
|
||||||
restore_records: '反撤销记录',
|
restore_records: '反撤销记录',
|
||||||
manage_homework: '作业扣分',
|
manage_homework: '作业扣分',
|
||||||
|
homework_register: '作业按次登记',
|
||||||
manage_attendance: '考勤管理',
|
manage_attendance: '考勤管理',
|
||||||
|
default_attendance: '考勤默认出勤',
|
||||||
|
manage_calendar: '节假日/补课设置',
|
||||||
manage_subjects: '科目管理',
|
manage_subjects: '科目管理',
|
||||||
manage_admins: '管理员/权限组管理',
|
manage_admins: '管理员/权限组管理',
|
||||||
manage_semesters: '学期管理',
|
manage_semesters: '学期管理',
|
||||||
view_all_records: '查看全班/个人查询',
|
view_all_records: '查看全班/个人查询',
|
||||||
|
view_reports: '数据报表查看',
|
||||||
export_data: '导出德育分/历史',
|
export_data: '导出德育分/历史',
|
||||||
|
view_logs: '操作日志查看',
|
||||||
|
manage_settings: '系统设置',
|
||||||
manage_upgrade: '系统升级'
|
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 currentEditUserId = null;
|
||||||
let currentResetUserId = null;
|
let currentResetUserId = null;
|
||||||
let groupsCache = [];
|
let groupsCache = [];
|
||||||
|
const currentUserId = (window.PAGE_CONFIG && window.PAGE_CONFIG.userId) ? parseInt(window.PAGE_CONFIG.userId) : null;
|
||||||
|
|
||||||
function groupCapsText(group) {
|
function groupCapsText(group) {
|
||||||
const add = group.can_add_points
|
const add = group.can_add_points
|
||||||
@@ -58,7 +73,7 @@ async function loadGroups() {
|
|||||||
groupsCache = res.data.groups || [];
|
groupsCache = res.data.groups || [];
|
||||||
|
|
||||||
const options = groupsCache
|
const options = groupsCache
|
||||||
.filter(group => !group.is_locked)
|
.filter(group => group.group_id)
|
||||||
.map(group => `<option value="${group.group_id}">${escapeHtml(group.group_name)}</option>`)
|
.map(group => `<option value="${group.group_id}">${escapeHtml(group.group_name)}</option>`)
|
||||||
.join('');
|
.join('');
|
||||||
const placeholder = '<option value="">请选择权限组</option>';
|
const placeholder = '<option value="">请选择权限组</option>';
|
||||||
@@ -72,28 +87,19 @@ function renderGroupTable() {
|
|||||||
let html = '';
|
let html = '';
|
||||||
groupsCache.forEach(group => {
|
groupsCache.forEach(group => {
|
||||||
const caps = groupCapsText(group);
|
const caps = groupCapsText(group);
|
||||||
const badges = [];
|
|
||||||
if (group.is_locked) {
|
|
||||||
badges.push('<span class="subject-status subject-status-active">锁定</span>');
|
|
||||||
} else if (group.is_system) {
|
|
||||||
badges.push('<span class="subject-status">预置</span>');
|
|
||||||
}
|
|
||||||
let actions = '<span class="text-muted">-</span>';
|
let actions = '<span class="text-muted">-</span>';
|
||||||
if (!group.is_locked) {
|
if (!group.readonly && group.group_id) {
|
||||||
const deleteItem = group.is_system
|
|
||||||
? ''
|
|
||||||
: `<a class="danger" onclick="deleteGroup(${group.group_id}, '${escapeHtml(group.group_name)}')">删除</a>`;
|
|
||||||
actions = `<div class="action-dropdown">
|
actions = `<div class="action-dropdown">
|
||||||
<button class="btn btn-sm action-dropdown-toggle" onclick="toggleActionDropdown(this)">操作 ▼</button>
|
<button class="btn btn-sm action-dropdown-toggle" onclick="toggleActionDropdown(this)">操作 ▼</button>
|
||||||
<div class="action-dropdown-menu">
|
<div class="action-dropdown-menu">
|
||||||
<a onclick="showEditGroupModal(${group.group_id})">编辑</a>
|
<a onclick="showEditGroupModal(${group.group_id})">编辑</a>
|
||||||
${deleteItem}
|
<a class="danger" onclick="deleteGroup(${group.group_id}, '${escapeHtml(group.group_name)}')">删除</a>
|
||||||
</div>
|
</div>
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
html += `<tr>
|
html += `<tr>
|
||||||
<td>${escapeHtml(group.group_name)} ${badges.join(' ')}</td>
|
<td>${escapeHtml(group.group_name)}</td>
|
||||||
<td style="max-width: 340px; white-space: normal;">${escapeHtml(permissionSummary(group))}</td>
|
<td class="cell-wrap">${escapeHtml(permissionSummary(group))}</td>
|
||||||
<td>${caps.add}</td>
|
<td>${caps.add}</td>
|
||||||
<td>${caps.subtract}</td>
|
<td>${caps.subtract}</td>
|
||||||
<td>${group.member_count || 0}</td>
|
<td>${group.member_count || 0}</td>
|
||||||
@@ -116,7 +122,7 @@ async function loadAdmins() {
|
|||||||
add: admin.can_add_points ? (admin.max_add_points ? ('+' + admin.max_add_points + '以内') : '不限') : '禁止',
|
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 + '以内') : '不限') : '禁止'
|
subtract: admin.can_subtract_points ? (admin.max_subtract_points ? ('-' + admin.max_subtract_points + '以内') : '不限') : '禁止'
|
||||||
};
|
};
|
||||||
const canEdit = !admin.is_locked && admin.group_id;
|
const canEdit = !!admin.group_id;
|
||||||
const editItem = canEdit
|
const editItem = canEdit
|
||||||
? `<a onclick="showEditAdminModal(${admin.user_id}, '${escapeHtml(admin.username)}', '${escapeHtml(admin.real_name)}', ${admin.group_id}, '${escapeHtml(admin.email || '')}')">编辑</a>`
|
? `<a onclick="showEditAdminModal(${admin.user_id}, '${escapeHtml(admin.username)}', '${escapeHtml(admin.real_name)}', ${admin.group_id}, '${escapeHtml(admin.email || '')}')">编辑</a>`
|
||||||
: '';
|
: '';
|
||||||
@@ -124,7 +130,7 @@ async function loadAdmins() {
|
|||||||
<td>${escapeHtml(admin.username)}</td>
|
<td>${escapeHtml(admin.username)}</td>
|
||||||
<td>${escapeHtml(admin.real_name)}</td>
|
<td>${escapeHtml(admin.real_name)}</td>
|
||||||
<td>${admin.email ? escapeHtml(admin.email) : '<span class="text-muted">未绑定</span>'}</td>
|
<td>${admin.email ? escapeHtml(admin.email) : '<span class="text-muted">未绑定</span>'}</td>
|
||||||
<td>${escapeHtml(admin.group_name || admin.role_type || '-')}${admin.is_locked ? ' <span class="subject-status subject-status-active">锁定</span>' : ''}</td>
|
<td>${escapeHtml(admin.group_name || admin.role_type || '-')}</td>
|
||||||
<td>加${caps.add} / 扣${caps.subtract}</td>
|
<td>加${caps.add} / 扣${caps.subtract}</td>
|
||||||
<td><span class="subject-status ${statusClass}">${statusText}</span></td>
|
<td><span class="subject-status ${statusClass}">${statusText}</span></td>
|
||||||
<td>
|
<td>
|
||||||
@@ -152,7 +158,12 @@ function showEditAdminModal(userId, username, realName, groupId, email) {
|
|||||||
document.getElementById('editAdminUserId').value = userId;
|
document.getElementById('editAdminUserId').value = userId;
|
||||||
document.getElementById('editAdminUsername').value = username;
|
document.getElementById('editAdminUsername').value = username;
|
||||||
document.getElementById('editAdminRealName').value = realName;
|
document.getElementById('editAdminRealName').value = realName;
|
||||||
document.getElementById('editAdminGroupId').value = groupId || '';
|
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('editAdminEmail').value = email || '';
|
||||||
document.getElementById('editAdminModal').style.display = 'flex';
|
document.getElementById('editAdminModal').style.display = 'flex';
|
||||||
}
|
}
|
||||||
@@ -227,8 +238,9 @@ async function submitResetPassword() {
|
|||||||
if (!currentResetUserId) return;
|
if (!currentResetUserId) return;
|
||||||
|
|
||||||
const newPassword = document.getElementById('newPassword').value;
|
const newPassword = document.getElementById('newPassword').value;
|
||||||
if (!newPassword || newPassword.length < 6) {
|
const policyError = validatePasswordByPolicy(newPassword);
|
||||||
showToast('密码长度至少6位', 'warning');
|
if (policyError) {
|
||||||
|
showToast(policyError, 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,11 +260,21 @@ async function submitResetPassword() {
|
|||||||
|
|
||||||
function renderPermissionCheckboxes(permissions) {
|
function renderPermissionCheckboxes(permissions) {
|
||||||
const container = document.getElementById('groupPermissionList');
|
const container = document.getElementById('groupPermissionList');
|
||||||
container.innerHTML = Object.keys(PERMISSION_LABELS).map(key =>
|
container.innerHTML = PERMISSION_SECTIONS.map(section => {
|
||||||
`<label style="display:flex; align-items:center; gap:6px;">
|
const items = section.keys.map(key =>
|
||||||
<input type="checkbox" class="group-perm" value="${key}"${permissions[key] ? ' checked' : ''}> ${PERMISSION_LABELS[key]}
|
`<label class="check-item">
|
||||||
</label>`
|
<input type="checkbox" class="group-perm" value="${key}"${permissions[key] ? ' checked' : ''}> ${PERMISSION_LABELS[key]}
|
||||||
).join('');
|
</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() {
|
function onGroupCapChange() {
|
||||||
@@ -281,10 +303,6 @@ function showAddGroupModal() {
|
|||||||
function showEditGroupModal(groupId) {
|
function showEditGroupModal(groupId) {
|
||||||
const group = groupsCache.find(item => item.group_id === groupId);
|
const group = groupsCache.find(item => item.group_id === groupId);
|
||||||
if (!group) return;
|
if (!group) return;
|
||||||
if (group.is_locked) {
|
|
||||||
showToast('该权限组已锁定,不可编辑', 'warning');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
document.getElementById('groupModalTitle').textContent = '编辑权限组 - ' + group.group_name;
|
document.getElementById('groupModalTitle').textContent = '编辑权限组 - ' + group.group_name;
|
||||||
document.getElementById('editGroupId').value = group.group_id;
|
document.getElementById('editGroupId').value = group.group_id;
|
||||||
document.getElementById('groupName').value = group.group_name;
|
document.getElementById('groupName').value = group.group_name;
|
||||||
@@ -356,6 +374,17 @@ async function deleteGroup(groupId, groupName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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();
|
loadGroups();
|
||||||
loadAdmins();
|
loadAdmins();
|
||||||
|
|
||||||
@@ -372,5 +401,7 @@ window.showEditGroupModal = showEditGroupModal;
|
|||||||
window.submitGroupForm = submitGroupForm;
|
window.submitGroupForm = submitGroupForm;
|
||||||
window.deleteGroup = deleteGroup;
|
window.deleteGroup = deleteGroup;
|
||||||
window.onGroupCapChange = onGroupCapChange;
|
window.onGroupCapChange = onGroupCapChange;
|
||||||
|
window.selectAllPermissions = selectAllPermissions;
|
||||||
|
window.testSmtpEmail = testSmtpEmail;
|
||||||
|
|
||||||
})();
|
})();
|
||||||
@@ -165,13 +165,22 @@ async function loadAttendanceRecords() {
|
|||||||
let html = '';
|
let html = '';
|
||||||
const records = res.data.records || [];
|
const records = res.data.records || [];
|
||||||
records.forEach(record => {
|
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>
|
html += `<tr>
|
||||||
<td>${escapeHtml(record.student_no)}</td>
|
<td>${escapeHtml(record.student_no)}</td>
|
||||||
<td>${escapeHtml(record.student_name)}</td>
|
<td>${escapeHtml(record.student_name)}</td>
|
||||||
<td>${getStatusBadge(record.status, 'attendance')}</td>
|
<td>${getStatusBadge(record.status, 'attendance')}</td>
|
||||||
<td>${escapeHtml(record.reason || '-')}</td>
|
<td>${escapeHtml(record.reason || '-')}</td>
|
||||||
<td>${escapeHtml(record.recorder_name || '-')}</td>
|
<td>${escapeHtml(record.recorder_name || '-')}</td>
|
||||||
<td>${record.deduction_applied ? '已扣分' : '-'}</td>
|
<td>${deductionText}</td>
|
||||||
</tr>`;
|
</tr>`;
|
||||||
});
|
});
|
||||||
if (records.length === 0) {
|
if (records.length === 0) {
|
||||||
@@ -190,6 +199,229 @@ document.getElementById('attendanceSlot').addEventListener('change', function()
|
|||||||
loadExistingRecords();
|
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();
|
initAttendanceButtons();
|
||||||
loadStudents();
|
loadStudents();
|
||||||
@@ -202,5 +434,12 @@ window.selectAllStudents = selectAllStudents;
|
|||||||
window.deselectAllStudents = deselectAllStudents;
|
window.deselectAllStudents = deselectAllStudents;
|
||||||
window.submitAttendance = submitAttendance;
|
window.submitAttendance = submitAttendance;
|
||||||
window.loadAttendanceRecords = loadAttendanceRecords;
|
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() {
|
function clearAuth() {
|
||||||
localStorage.removeItem(window.JWT_STORAGE_KEY || 'class_system_token');
|
localStorage.removeItem(window.JWT_STORAGE_KEY || 'class_system_token');
|
||||||
localStorage.removeItem(window.USER_STORAGE_KEY || 'class_system_user');
|
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 response = await fetch(fullUrl, { ...options, headers });
|
||||||
const data = await response.json();
|
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) {
|
if (response.status === 401) {
|
||||||
clearAuth();
|
clearAuth();
|
||||||
|
|
||||||
@@ -267,6 +275,45 @@ function validateScoreChange(value) {
|
|||||||
return '';
|
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') {
|
function showToast(message, type = 'success') {
|
||||||
const toast = document.createElement('div');
|
const toast = document.createElement('div');
|
||||||
toast.className = `toast toast-${type}`;
|
toast.className = `toast toast-${type}`;
|
||||||
@@ -482,6 +529,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
if (logoutBtn) {
|
if (logoutBtn) {
|
||||||
logoutBtn.addEventListener('click', logout);
|
logoutBtn.addEventListener('click', logout);
|
||||||
}
|
}
|
||||||
|
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||||
|
el.textContent = describePasswordPolicy();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function toggleActionDropdown(el) {
|
function toggleActionDropdown(el) {
|
||||||
|
|||||||
@@ -39,15 +39,6 @@ async function loadStudents() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showSinglePointsModal(studentId, studentName) {
|
|
||||||
window.selectedStudentIds = [studentId];
|
|
||||||
document.getElementById('selectedStudentsCount').innerHTML = `${studentName} (1人)`;
|
|
||||||
document.getElementById('pointsChange').value = '';
|
|
||||||
document.getElementById('pointsReason').value = '';
|
|
||||||
if (typeof preparePointsLimitHint === 'function') preparePointsLimitHint();
|
|
||||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
|
||||||
}
|
|
||||||
|
|
||||||
function initPointsLimitHint() {
|
function initPointsLimitHint() {
|
||||||
const hintEl = document.getElementById('pointsLimitHint');
|
const hintEl = document.getElementById('pointsLimitHint');
|
||||||
if (hintEl) hintEl.textContent = describeScoreLimits();
|
if (hintEl) hintEl.textContent = describeScoreLimits();
|
||||||
@@ -191,21 +182,21 @@ async function onDormitorySelected() {
|
|||||||
if (res && res.success && res.data.students) {
|
if (res && res.success && res.data.students) {
|
||||||
const students = res.data.students;
|
const students = res.data.students;
|
||||||
if (students.length === 0) {
|
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 = '';
|
studentsCount.textContent = '';
|
||||||
} else {
|
} else {
|
||||||
students.forEach(s => {
|
students.forEach(s => {
|
||||||
dormitoryStudentIds.push(s.student_id);
|
dormitoryStudentIds.push(s.student_id);
|
||||||
const div = document.createElement('div');
|
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.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(--text-secondary);">${escapeHtml(s.student_no)}</span>`;
|
div.innerHTML = `<span>${escapeHtml(s.name)}</span><span style="color: var(--color-text-secondary);">${escapeHtml(s.student_no)}</span>`;
|
||||||
studentsList.appendChild(div);
|
studentsList.appendChild(div);
|
||||||
});
|
});
|
||||||
studentsCount.textContent = `共 ${students.length} 人`;
|
studentsCount.textContent = `共 ${students.length} 人`;
|
||||||
}
|
}
|
||||||
studentsGroup.style.display = 'block';
|
studentsGroup.style.display = 'block';
|
||||||
} else {
|
} else {
|
||||||
studentsList.innerHTML = '<p style="color: var(--text-secondary);">加载失败</p>';
|
studentsList.innerHTML = '<p style="color: var(--color-text-secondary);">加载失败</p>';
|
||||||
studentsGroup.style.display = 'block';
|
studentsGroup.style.display = 'block';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -250,7 +241,6 @@ initPointsLimitHint();
|
|||||||
loadStudents();
|
loadStudents();
|
||||||
|
|
||||||
window.loadStudents = loadStudents;
|
window.loadStudents = loadStudents;
|
||||||
window.showSinglePointsModal = showSinglePointsModal;
|
|
||||||
window.showExportMoralityModal = showExportMoralityModal;
|
window.showExportMoralityModal = showExportMoralityModal;
|
||||||
window.exportMoralityRecords = exportMoralityRecords;
|
window.exportMoralityRecords = exportMoralityRecords;
|
||||||
window.showDormitoryPointsModal = showDormitoryPointsModal;
|
window.showDormitoryPointsModal = showDormitoryPointsModal;
|
||||||
|
|||||||
@@ -71,24 +71,109 @@ async function loadDashboard() {
|
|||||||
}
|
}
|
||||||
document.getElementById('quickActions').innerHTML = quickActions || '<p>暂无快捷操作</p>';
|
document.getElementById('quickActions').innerHTML = quickActions || '<p>暂无快捷操作</p>';
|
||||||
|
|
||||||
const rankingRes = await apiGet('/api/student/ranking', { limit: 100 });
|
await loadRanking();
|
||||||
if (rankingRes && rankingRes.success) {
|
}
|
||||||
totalStudents = rankingRes.data.total_students || 0;
|
|
||||||
let html = '';
|
async function loadRanking() {
|
||||||
rankingRes.data.ranking.forEach((student, index) => {
|
const type = document.getElementById('rankingType').value;
|
||||||
const rank = index + 1;
|
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>
|
html += `<tr>
|
||||||
<td>${rank}</td>
|
<td>${rank}</td>
|
||||||
<td>${escapeHtml(student.student_no)}</td>
|
<td>${escapeHtml(student.student_no)}</td>
|
||||||
<td>${escapeHtml(student.name)}</td>
|
<td>${escapeHtml(student.name)}</td>
|
||||||
<td>${student.total_points}</td>
|
<td>${student.total_points}</td>
|
||||||
</tr>`;
|
</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() {
|
function applyPercentileFilter() {
|
||||||
@@ -121,6 +206,9 @@ document.getElementById('percentileFilter').addEventListener('keypress', functio
|
|||||||
loadDashboard();
|
loadDashboard();
|
||||||
|
|
||||||
window.loadDashboard = loadDashboard;
|
window.loadDashboard = loadDashboard;
|
||||||
|
window.loadRanking = loadRanking;
|
||||||
|
window.onRankingTypeChange = onRankingTypeChange;
|
||||||
|
window.exportRanking = exportRanking;
|
||||||
window.applyPercentileFilter = applyPercentileFilter;
|
window.applyPercentileFilter = applyPercentileFilter;
|
||||||
window.resetPercentileFilter = resetPercentileFilter;
|
window.resetPercentileFilter = resetPercentileFilter;
|
||||||
|
|
||||||
|
|||||||
+142
-32
@@ -15,16 +15,10 @@ const canRevokeAny = hasPermission('revoke_any');
|
|||||||
const canRevokeOwn = hasPermission('revoke_own');
|
const canRevokeOwn = hasPermission('revoke_own');
|
||||||
const canRestore = hasPermission('restore_records');
|
const canRestore = hasPermission('restore_records');
|
||||||
const canRevoke = canRevokeAny || canRevokeOwn;
|
const canRevoke = canRevokeAny || canRevokeOwn;
|
||||||
|
const canAct = canRevoke || canRestore;
|
||||||
let currentHistoryPage = 1;
|
let currentHistoryPage = 1;
|
||||||
let totalHistoryPages = 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) {
|
function typeMap(relatedType) {
|
||||||
var map = { manual: '手动', homework: '作业', attendance: '考勤' };
|
var map = { manual: '手动', homework: '作业', attendance: '考勤' };
|
||||||
return map[relatedType] || '手动';
|
return map[relatedType] || '手动';
|
||||||
@@ -133,12 +127,12 @@ async function loadHistory(page) {
|
|||||||
var headHtml = '';
|
var headHtml = '';
|
||||||
if (isGrouped) {
|
if (isGrouped) {
|
||||||
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生名单</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生名单</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
||||||
if (canRevoke) {
|
if (canAct) {
|
||||||
headHtml += '<th>操作</th>';
|
headHtml += '<th>操作</th>';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
headHtml = '<th>类型</th><th>分值</th><th>原因</th><th>学生</th><th' + nowrapStyle + '>操作人</th><th>时间</th>';
|
||||||
if (canRevoke) {
|
if (canAct) {
|
||||||
headHtml += '<th>操作</th>';
|
headHtml += '<th>操作</th>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -159,9 +153,13 @@ async function loadHistory(page) {
|
|||||||
'<td class="history-students">' + escapeHtml(names) + '</td>' +
|
'<td class="history-students">' + escapeHtml(names) + '</td>' +
|
||||||
'<td>' + escapeHtml(record.recorder_name || '') + '</td>' +
|
'<td>' + escapeHtml(record.recorder_name || '') + '</td>' +
|
||||||
'<td class="history-time">' + formatDateTime(record.created_at) + '</td>';
|
'<td class="history-time">' + formatDateTime(record.created_at) + '</td>';
|
||||||
if (canRevoke) {
|
if (canAct) {
|
||||||
if (allRevoked) {
|
if (allRevoked) {
|
||||||
html += '<td><span class="text-muted">已撤销</span></td>';
|
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) {
|
} 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>';
|
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 {
|
} else {
|
||||||
@@ -171,7 +169,7 @@ async function loadHistory(page) {
|
|||||||
html += '</tr>';
|
html += '</tr>';
|
||||||
});
|
});
|
||||||
if (res.data.records.length === 0) {
|
if (res.data.records.length === 0) {
|
||||||
var colSpan = canRevoke ? 7 : 6;
|
var colSpan = canAct ? 7 : 6;
|
||||||
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -186,7 +184,7 @@ async function loadHistory(page) {
|
|||||||
'<td>' + escapeHtml(record.student_name) + '</td>' +
|
'<td>' + escapeHtml(record.student_name) + '</td>' +
|
||||||
'<td>' + escapeHtml(record.recorder_name) + '</td>' +
|
'<td>' + escapeHtml(record.recorder_name) + '</td>' +
|
||||||
'<td class="history-time">' + formatDateTime(record.created_at) + '</td>';
|
'<td class="history-time">' + formatDateTime(record.created_at) + '</td>';
|
||||||
if (canRevoke) {
|
if (canAct) {
|
||||||
if (record.is_revoked == 1) {
|
if (record.is_revoked == 1) {
|
||||||
var revokerInfo = record.revoker_name ? '由 ' + escapeHtml(record.revoker_name) + ' 撤销' : '已撤销';
|
var revokerInfo = record.revoker_name ? '由 ' + escapeHtml(record.revoker_name) + ' 撤销' : '已撤销';
|
||||||
if (canRestore) {
|
if (canRestore) {
|
||||||
@@ -204,7 +202,7 @@ async function loadHistory(page) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (res.data.records.length === 0) {
|
if (res.data.records.length === 0) {
|
||||||
var colSpan = canRevoke ? 7 : 6;
|
var colSpan = canAct ? 7 : 6;
|
||||||
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
html = '<tr><td colspan="' + colSpan + '" style="text-align:center;">暂无记录</td></tr>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -253,12 +251,81 @@ async function exportHistoryRecords() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var csv = '时间,学号,姓名,学期,类型,分数变动,原因,操作人\n';
|
var mode = getHistoryExportMode();
|
||||||
records.forEach(function(r) {
|
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 += [
|
csv += [
|
||||||
r.created_at || '',
|
r.created_at || '',
|
||||||
r.student_no || '',
|
|
||||||
r.student_name || '',
|
|
||||||
r.semester_name || '',
|
r.semester_name || '',
|
||||||
typeMap(r.related_type),
|
typeMap(r.related_type),
|
||||||
(r.points_change > 0 ? '+' : '') + r.points_change,
|
(r.points_change > 0 ? '+' : '') + r.points_change,
|
||||||
@@ -266,18 +333,9 @@ async function exportHistoryRecords() {
|
|||||||
r.recorder_name || ''
|
r.recorder_name || ''
|
||||||
].map(csvEscape).join(',') + '\n';
|
].map(csvEscape).join(',') + '\n';
|
||||||
});
|
});
|
||||||
|
csv += '\n';
|
||||||
var semesterLabel = '全部学期';
|
});
|
||||||
if (semesterSelect && semesterId && semesterSelect.selectedIndex >= 0) {
|
return csv;
|
||||||
semesterLabel = semesterSelect.options[semesterSelect.selectedIndex].textContent.replace(/((当前|已归档))$/, '');
|
|
||||||
}
|
|
||||||
var safeLabel = semesterLabel.replace(/[\\/:*?"<>|]/g, '_');
|
|
||||||
downloadCsv('历史记录_' + safeLabel + '_' + new Date().toISOString().slice(0,10) + '.csv', csv);
|
|
||||||
|
|
||||||
showToast('导出成功,共' + records.length + '条记录');
|
|
||||||
} catch (err) {
|
|
||||||
showToast('导出失败:' + err.message, 'error');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 批量撤销合并记录(按条件查找并撤销)
|
// 批量撤销合并记录(按条件查找并撤销)
|
||||||
@@ -305,7 +363,8 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
|||||||
|
|
||||||
var matchedIds = [];
|
var matchedIds = [];
|
||||||
res.data.records.forEach(function(r) {
|
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);
|
matchedIds.push(r.record_id);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -317,7 +376,7 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
|||||||
|
|
||||||
var revokeRes = await apiPost('/api/admin/conduct/batch-revoke', { record_ids: matchedIds });
|
var revokeRes = await apiPost('/api/admin/conduct/batch-revoke', { record_ids: matchedIds });
|
||||||
if (revokeRes && revokeRes.success) {
|
if (revokeRes && revokeRes.success) {
|
||||||
showToast('批量撤销完成: ' + (revokeRes.data ? revokeRes.data.success_count : 0) + '条成功');
|
showToast('批量撤销完成: ' + (revokeRes.data ? revokeRes.data.success_count : 0) + '条(已移入“已撤销”,可筛选查看/批量反撤销)');
|
||||||
loadHistory(currentHistoryPage);
|
loadHistory(currentHistoryPage);
|
||||||
} else {
|
} else {
|
||||||
showToast(revokeRes && revokeRes.message || '批量撤销失败', 'error');
|
showToast(revokeRes && revokeRes.message || '批量撤销失败', 'error');
|
||||||
@@ -327,6 +386,55 @@ async function batchRevokeGrouped(reason, pointsChange, recorderName, createdAt)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 批量反撤销合并记录(按条件查找并恢复)
|
||||||
|
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() {
|
Promise.all([loadStudentsForSelect(), loadSubjectsForFilter(), loadSemestersForFilter()]).then(function() {
|
||||||
var urlParams = new URLSearchParams(window.location.search);
|
var urlParams = new URLSearchParams(window.location.search);
|
||||||
@@ -340,8 +448,10 @@ Promise.all([loadStudentsForSelect(), loadSubjectsForFilter(), loadSemestersForF
|
|||||||
|
|
||||||
window.loadHistory = loadHistory;
|
window.loadHistory = loadHistory;
|
||||||
window.loadStudentsForSelect = loadStudentsForSelect;
|
window.loadStudentsForSelect = loadStudentsForSelect;
|
||||||
|
window.showExportHistoryModal = showExportHistoryModal;
|
||||||
window.exportHistoryRecords = exportHistoryRecords;
|
window.exportHistoryRecords = exportHistoryRecords;
|
||||||
window.batchRevokeGrouped = batchRevokeGrouped;
|
window.batchRevokeGrouped = batchRevokeGrouped;
|
||||||
|
window.batchRestoreGrouped = batchRestoreGrouped;
|
||||||
window.onStudentFilterChange = onStudentFilterChange;
|
window.onStudentFilterChange = onStudentFilterChange;
|
||||||
window.onSubjectFilterChange = onSubjectFilterChange;
|
window.onSubjectFilterChange = onSubjectFilterChange;
|
||||||
window.toggleFilterPanel = toggleFilterPanel;
|
window.toggleFilterPanel = toggleFilterPanel;
|
||||||
|
|||||||
@@ -13,6 +13,8 @@
|
|||||||
const hwNotSubmit = window.DEDUCTION_HOMEWORK_NOT_SUBMIT || 2;
|
const hwNotSubmit = window.DEDUCTION_HOMEWORK_NOT_SUBMIT || 2;
|
||||||
const hwLate = window.DEDUCTION_HOMEWORK_LATE || 1;
|
const hwLate = window.DEDUCTION_HOMEWORK_LATE || 1;
|
||||||
|
|
||||||
|
let studentsData = [];
|
||||||
|
|
||||||
// 更新页面中的配置值显示(加减分上限来自权限组动态配置)
|
// 更新页面中的配置值显示(加减分上限来自权限组动态配置)
|
||||||
document.querySelectorAll('.hw-not-submit').forEach(el => el.textContent = hwNotSubmit);
|
document.querySelectorAll('.hw-not-submit').forEach(el => el.textContent = hwNotSubmit);
|
||||||
document.querySelectorAll('.hw-late').forEach(el => el.textContent = hwLate);
|
document.querySelectorAll('.hw-late').forEach(el => el.textContent = hwLate);
|
||||||
@@ -21,6 +23,10 @@ document.querySelectorAll('.hw-max').forEach(el => el.textContent = describeScor
|
|||||||
// 更新输入框的 min/max(按权限组动态上限)
|
// 更新输入框的 min/max(按权限组动态上限)
|
||||||
applyScoreLimits(document.getElementById('pointsChange'));
|
applyScoreLimits(document.getElementById('pointsChange'));
|
||||||
|
|
||||||
|
// 按次登记默认单次缺交扣分
|
||||||
|
const regPerInput = document.getElementById('hwRegPerDeduction');
|
||||||
|
if (regPerInput) regPerInput.value = hwNotSubmit;
|
||||||
|
|
||||||
// 加载科目列表(学习委员)
|
// 加载科目列表(学习委员)
|
||||||
async function loadSubjectsForHomework() {
|
async function loadSubjectsForHomework() {
|
||||||
const subjectSelect = document.getElementById('hwSubjectSelect');
|
const subjectSelect = document.getElementById('hwSubjectSelect');
|
||||||
@@ -39,6 +45,7 @@ async function loadSubjectsForHomework() {
|
|||||||
async function loadStudents() {
|
async function loadStudents() {
|
||||||
const res = await apiGet('/api/admin/students', {page_size: 1000});
|
const res = await apiGet('/api/admin/students', {page_size: 1000});
|
||||||
if (res && res.success) {
|
if (res && res.success) {
|
||||||
|
studentsData = res.data.students || [];
|
||||||
let html = '';
|
let html = '';
|
||||||
res.data.students.forEach(student => {
|
res.data.students.forEach(student => {
|
||||||
html += `<tr>
|
html += `<tr>
|
||||||
@@ -56,14 +63,6 @@ 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() {
|
function handleSubmitPoints() {
|
||||||
const pointsChange = parseInt(document.getElementById('pointsChange').value);
|
const pointsChange = parseInt(document.getElementById('pointsChange').value);
|
||||||
const limitError = validateScoreChange(pointsChange);
|
const limitError = validateScoreChange(pointsChange);
|
||||||
@@ -116,37 +115,68 @@ function toggleSubjectPanel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let subjectsCache = [];
|
||||||
|
|
||||||
async function loadSubjectList() {
|
async function loadSubjectList() {
|
||||||
const res = await apiGet('/api/subject/list');
|
const res = await apiGet('/api/subject/list');
|
||||||
if (res && res.success && res.data) {
|
if (res && res.success && res.data) {
|
||||||
|
subjectsCache = res.data.subjects || [];
|
||||||
let html = '';
|
let html = '';
|
||||||
const subjects = res.data.subjects || [];
|
subjectsCache.forEach((sub, index) => {
|
||||||
subjects.forEach(sub => {
|
|
||||||
const safeName = escapeHtml(sub.subject_name || '');
|
const safeName = escapeHtml(sub.subject_name || '');
|
||||||
const safeCode = escapeHtml(sub.subject_code || '');
|
const safeCode = escapeHtml(sub.subject_code || '');
|
||||||
const sortOrder = sub.sort_order || 0;
|
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 += `
|
html += `
|
||||||
<div class="subject-item">
|
<div class="subject-item">
|
||||||
<span class="subject-name">${safeName}</span>
|
<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'}">
|
<span class="subject-status ${sub.is_active ? 'subject-status-active' : 'subject-status-inactive'}">
|
||||||
${sub.is_active ? '启用' : '禁用'}
|
${sub.is_active ? '启用' : '禁用'}
|
||||||
</span>
|
</span>
|
||||||
<button class="btn btn-sm btn-outline" onclick="showEditSubjectModal(${sub.subject_id}, '${safeName.replace(/'/g, "\\'")}', '${safeCode.replace(/'/g, "\\'")}', ${sortOrder})">编辑</button>
|
<span class="subject-order">排序 ${sortOrder}</span>
|
||||||
<button class="btn btn-sm btn-ghost" onclick="toggleSubjectStatus(${sub.subject_id}, ${sub.is_active ? 'false' : 'true'})">
|
<span class="subject-actions">
|
||||||
${sub.is_active ? '禁用' : '启用'}
|
${upBtn}
|
||||||
</button>
|
${downBtn}
|
||||||
<button class="btn btn-sm btn-outline-danger" onclick="deleteSubject(${sub.subject_id})">删除</button>
|
<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>
|
</div>
|
||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
if (subjects.length === 0) {
|
if (subjectsCache.length === 0) {
|
||||||
html = '<p style="text-align:center;padding:40px;">暂无科目,请点击"添加科目"</p>';
|
html = '<p style="text-align:center;padding:40px;">暂无科目,请点击"添加科目"</p>';
|
||||||
}
|
}
|
||||||
document.getElementById('subjectList').innerHTML = html;
|
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() {
|
function showAddSubjectModal() {
|
||||||
const form = document.getElementById('addSubjectFormInHw');
|
const form = document.getElementById('addSubjectFormInHw');
|
||||||
if (form) form.reset();
|
if (form) form.reset();
|
||||||
@@ -219,8 +249,10 @@ async function submitEditSubject() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = { subject_name: subjectName };
|
const data = {
|
||||||
if (subjectCode) data.subject_code = subjectCode;
|
subject_name: subjectName,
|
||||||
|
subject_code: subjectCode
|
||||||
|
};
|
||||||
if (sortOrder !== '') data.sort_order = parseInt(sortOrder);
|
if (sortOrder !== '') data.sort_order = parseInt(sortOrder);
|
||||||
|
|
||||||
const res = await apiPut(`/api/subject/update/${subjectId}`, data);
|
const res = await apiPut(`/api/subject/update/${subjectId}`, data);
|
||||||
@@ -234,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');
|
var subjectHeader = document.getElementById('subjectPanelHeader');
|
||||||
if (subjectHeader) {
|
if (subjectHeader) {
|
||||||
@@ -244,7 +379,6 @@ loadStudents();
|
|||||||
loadSubjectsForHomework();
|
loadSubjectsForHomework();
|
||||||
|
|
||||||
window.loadStudents = loadStudents;
|
window.loadStudents = loadStudents;
|
||||||
window.showSinglePointsModal = showSinglePointsModal;
|
|
||||||
window.handleSubmitPoints = handleSubmitPoints;
|
window.handleSubmitPoints = handleSubmitPoints;
|
||||||
window.toggleSubjectPanel = toggleSubjectPanel;
|
window.toggleSubjectPanel = toggleSubjectPanel;
|
||||||
window.showAddSubjectModal = showAddSubjectModal;
|
window.showAddSubjectModal = showAddSubjectModal;
|
||||||
@@ -253,5 +387,8 @@ window.toggleSubjectStatus = toggleSubjectStatus;
|
|||||||
window.deleteSubject = deleteSubject;
|
window.deleteSubject = deleteSubject;
|
||||||
window.showEditSubjectModal = showEditSubjectModal;
|
window.showEditSubjectModal = showEditSubjectModal;
|
||||||
window.submitEditSubject = submitEditSubject;
|
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;
|
||||||
|
|
||||||
|
})();
|
||||||
@@ -43,6 +43,16 @@
|
|||||||
if (hintEl) hintEl.textContent = describeScoreLimits();
|
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';
|
||||||
|
}
|
||||||
|
|
||||||
// 提交批量加减分
|
// 提交批量加减分
|
||||||
async function submitBatchPoints(options = {}) {
|
async function submitBatchPoints(options = {}) {
|
||||||
const pointsChange = parseInt(document.getElementById('pointsChange').value);
|
const pointsChange = parseInt(document.getElementById('pointsChange').value);
|
||||||
@@ -85,7 +95,7 @@
|
|||||||
|
|
||||||
const res = await apiPost('/api/admin/conduct/revoke', { record_id: recordId });
|
const res = await apiPost('/api/admin/conduct/revoke', { record_id: recordId });
|
||||||
if (res && res.success) {
|
if (res && res.success) {
|
||||||
showToast('撤销成功');
|
showToast('撤销成功,该记录已移入“已撤销”(可筛选查看/反撤销)');
|
||||||
loadHistory(currentHistoryPage);
|
loadHistory(currentHistoryPage);
|
||||||
} else {
|
} else {
|
||||||
showToast(res?.message || '撤销失败', 'error');
|
showToast(res?.message || '撤销失败', 'error');
|
||||||
@@ -98,7 +108,7 @@
|
|||||||
|
|
||||||
const res = await apiPost('/api/admin/conduct/restore', { record_id: recordId });
|
const res = await apiPost('/api/admin/conduct/restore', { record_id: recordId });
|
||||||
if (res && res.success) {
|
if (res && res.success) {
|
||||||
showToast('反撤销成功');
|
showToast('反撤销成功,该记录已恢复正常');
|
||||||
loadHistory(currentHistoryPage);
|
loadHistory(currentHistoryPage);
|
||||||
} else {
|
} else {
|
||||||
showToast(res?.message || '反撤销失败', 'error');
|
showToast(res?.message || '反撤销失败', 'error');
|
||||||
@@ -106,6 +116,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
window.showBatchPointsModal = showBatchPointsModal;
|
window.showBatchPointsModal = showBatchPointsModal;
|
||||||
|
window.showSinglePointsModal = showSinglePointsModal;
|
||||||
window.submitBatchPoints = submitBatchPoints;
|
window.submitBatchPoints = submitBatchPoints;
|
||||||
window.preparePointsLimitHint = preparePointsLimitHint;
|
window.preparePointsLimitHint = preparePointsLimitHint;
|
||||||
window.revokeRecord = revokeRecord;
|
window.revokeRecord = revokeRecord;
|
||||||
|
|||||||
@@ -94,8 +94,9 @@
|
|||||||
const studentId = document.getElementById('resetStudentId').value;
|
const studentId = document.getElementById('resetStudentId').value;
|
||||||
const newPassword = document.getElementById('newStudentPassword').value;
|
const newPassword = document.getElementById('newStudentPassword').value;
|
||||||
|
|
||||||
if (!newPassword || newPassword.length < 6) {
|
const policyError = validatePasswordByPolicy(newPassword);
|
||||||
showToast('密码至少6位', 'warning');
|
if (policyError) {
|
||||||
|
showToast(policyError, 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,14 +12,6 @@
|
|||||||
(function() {
|
(function() {
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
// HTML转义
|
|
||||||
function escapeHtml(str) {
|
|
||||||
if (!str) return '';
|
|
||||||
var el = document.createElement('span');
|
|
||||||
el.appendChild(document.createTextNode(str));
|
|
||||||
return el.innerHTML;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 全选功能
|
// 全选功能
|
||||||
function toggleSelectAll() {
|
function toggleSelectAll() {
|
||||||
const selectAll = document.getElementById('selectAll');
|
const selectAll = document.getElementById('selectAll');
|
||||||
@@ -30,6 +22,5 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.escapeHtml = escapeHtml;
|
|
||||||
window.toggleSelectAll = toggleSelectAll;
|
window.toggleSelectAll = toggleSelectAll;
|
||||||
})();
|
})();
|
||||||
@@ -98,7 +98,7 @@ async function loadSummary(studentId, semesterId) {
|
|||||||
|
|
||||||
document.getElementById('querySummaryHint').textContent =
|
document.getElementById('querySummaryHint').textContent =
|
||||||
'共 ' + s.record_count + ' 条有效记录(不含已撤销)。' +
|
'共 ' + s.record_count + ' 条有效记录(不含已撤销)。' +
|
||||||
(data.semester ? '学期得分按“基础分 + 学期内加分 - 学期内减分”计算。' : '全部学期得分按“基础分 + 全部加分 - 全部减分”计算,仅供参考。');
|
'月度分为当月加分与减分的净得分,与基础分无关;总分 = 基础分 + 全部加分 - 全部减分。';
|
||||||
|
|
||||||
renderMonthly(data.months);
|
renderMonthly(data.months);
|
||||||
renderReasonSummary(data.months);
|
renderReasonSummary(data.months);
|
||||||
@@ -107,15 +107,15 @@ async function loadSummary(studentId, semesterId) {
|
|||||||
function renderMonthly(months) {
|
function renderMonthly(months) {
|
||||||
let html = '';
|
let html = '';
|
||||||
if (!months || months.length === 0) {
|
if (!months || months.length === 0) {
|
||||||
html = '<tr><td colspan="6" style="text-align:center;">暂无记录</td></tr>';
|
html = '<tr><td colspan="5" style="text-align:center;">暂无记录</td></tr>';
|
||||||
} else {
|
} else {
|
||||||
months.forEach(m => {
|
months.forEach(m => {
|
||||||
|
const monthScore = (typeof m.month_score === 'number') ? m.month_score : ((m.bonus || 0) + (m.deduction || 0));
|
||||||
html += '<tr>' +
|
html += '<tr>' +
|
||||||
'<td>' + escapeHtml(monthLabel(m.month)) + '</td>' +
|
'<td>' + escapeHtml(monthLabel(m.month)) + '</td>' +
|
||||||
'<td>' + m.start_score + '</td>' +
|
|
||||||
'<td class="plus">+' + m.bonus + '</td>' +
|
'<td class="plus">+' + m.bonus + '</td>' +
|
||||||
'<td class="minus">' + m.deduction + '</td>' +
|
'<td class="minus">' + m.deduction + '</td>' +
|
||||||
'<td><strong>' + m.end_score + '</strong></td>' +
|
'<td><strong>' + (monthScore > 0 ? '+' : '') + monthScore + '</strong></td>' +
|
||||||
'<td>' + m.record_count + '</td>' +
|
'<td>' + m.record_count + '</td>' +
|
||||||
'</tr>';
|
'</tr>';
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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) {
|
if (res && res.success) {
|
||||||
const data = res.data || {};
|
const data = res.data || {};
|
||||||
const archives = data.archives || [];
|
const archives = data.archives || [];
|
||||||
|
const prevName = data.previous_semester ? data.previous_semester.semester_name : null;
|
||||||
|
document.getElementById('archiveDataTitle').textContent =
|
||||||
|
`归档数据 - ${semesterName}` + (prevName ? `(对比:${prevName})` : '(无对比学期)');
|
||||||
let html = '';
|
let html = '';
|
||||||
archives.forEach(a => {
|
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>
|
html += `<tr>
|
||||||
<td>${a.rank_position || '-'}</td>
|
<td>${a.rank_position || '-'}</td>
|
||||||
<td>${escapeHtml(a.student_no)}</td>
|
<td>${escapeHtml(a.student_no)}</td>
|
||||||
<td>${escapeHtml(a.student_name)}</td>
|
<td>${escapeHtml(a.student_name)}</td>
|
||||||
<td>${a.final_points}</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_present || 0}</td>
|
||||||
<td>${a.attendance_absent || 0}</td>
|
<td>${a.attendance_absent || 0}</td>
|
||||||
<td>${a.attendance_late || 0}</td>
|
<td>${a.attendance_late || 0}</td>
|
||||||
@@ -270,7 +290,7 @@ async function viewArchiveData(semesterId, semesterName, page) {
|
|||||||
</tr>`;
|
</tr>`;
|
||||||
});
|
});
|
||||||
if (archives.length === 0) {
|
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;
|
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;
|
||||||
|
|
||||||
|
})();
|
||||||
@@ -72,15 +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 = '';
|
|
||||||
if (typeof preparePointsLimitHint === 'function') preparePointsLimitHint();
|
|
||||||
document.getElementById('batchPointsModal').style.display = 'flex';
|
|
||||||
}
|
|
||||||
|
|
||||||
async function unlockStudent(studentNo, studentName) {
|
async function unlockStudent(studentNo, studentName) {
|
||||||
if (!confirm(`确定要解除学生 "${studentName}" 的登录锁定吗?\n(适用于多次登录失败被禁止登录的情况)`)) {
|
if (!confirm(`确定要解除学生 "${studentName}" 的登录锁定吗?\n(适用于多次登录失败被禁止登录的情况)`)) {
|
||||||
return;
|
return;
|
||||||
@@ -183,7 +174,6 @@ document.getElementById('searchInput').addEventListener('input', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
window.loadStudents = loadStudents;
|
window.loadStudents = loadStudents;
|
||||||
window.showSinglePointsModal = showSinglePointsModal;
|
|
||||||
window.unlockStudent = unlockStudent;
|
window.unlockStudent = unlockStudent;
|
||||||
window.showExportStudentsModal = showExportStudentsModal;
|
window.showExportStudentsModal = showExportStudentsModal;
|
||||||
window.exportStudents = exportStudents;
|
window.exportStudents = exportStudents;
|
||||||
|
|||||||
+18
-3
@@ -10,6 +10,12 @@
|
|||||||
* 版权所有 © Sea Network Technology Studio
|
* 版权所有 © Sea Network Technology Studio
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// PHP 版本要求:8.4+(旧版本已停止安全维护,存在已知漏洞)
|
||||||
|
if (PHP_VERSION_ID < 80400) {
|
||||||
|
http_response_code(500);
|
||||||
|
die('系统要求 PHP 8.4 或更高版本(当前版本:' . PHP_VERSION . ')。请先升级服务器 PHP 版本以规避已知安全漏洞。');
|
||||||
|
}
|
||||||
|
|
||||||
// 读取.env文件
|
// 读取.env文件
|
||||||
$envFile = __DIR__ . '/.env';
|
$envFile = __DIR__ . '/.env';
|
||||||
$config = [];
|
$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 = [];
|
$missingKeys = [];
|
||||||
|
|
||||||
foreach ($requiredKeys as $key) {
|
foreach ($requiredKeys as $key) {
|
||||||
@@ -57,11 +63,9 @@ define('API_TIMEOUT', (int)$config['API_TIMEOUT']);
|
|||||||
define('JWT_STORAGE_KEY', $config['JWT_STORAGE_KEY']);
|
define('JWT_STORAGE_KEY', $config['JWT_STORAGE_KEY']);
|
||||||
define('USER_STORAGE_KEY', $config['USER_STORAGE_KEY']);
|
define('USER_STORAGE_KEY', $config['USER_STORAGE_KEY']);
|
||||||
define('SITE_NAME', $config['SITE_NAME']);
|
define('SITE_NAME', $config['SITE_NAME']);
|
||||||
define('SESSION_TIMEOUT', (int)$config['SESSION_TIMEOUT']);
|
|
||||||
define('ICP_ENABLED', $config['ICP_ENABLED'] !== 'false');
|
define('ICP_ENABLED', $config['ICP_ENABLED'] !== 'false');
|
||||||
define('ICP_NUMBER', $config['ICP_NUMBER'] ?? '');
|
define('ICP_NUMBER', $config['ICP_NUMBER'] ?? '');
|
||||||
// 会话配置
|
// 会话配置
|
||||||
// 会话配置
|
|
||||||
ini_set('session.cookie_httponly', 1);
|
ini_set('session.cookie_httponly', 1);
|
||||||
ini_set('session.use_only_cookies', 1);
|
ini_set('session.use_only_cookies', 1);
|
||||||
ini_set('session.cookie_secure', 1);
|
ini_set('session.cookie_secure', 1);
|
||||||
@@ -155,5 +159,16 @@ function current_group_name() {
|
|||||||
return $_SESSION['role'] ?? '';
|
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();
|
refresh_admin_permissions();
|
||||||
@@ -18,7 +18,7 @@ require_once __DIR__ . '/config.php';
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||||
<title><?php echo SITE_NAME; ?> - 忘记密码</title>
|
<title><?php echo SITE_NAME; ?> - 忘记密码</title>
|
||||||
<link rel="stylesheet" href="/assets/css/style.css">
|
<link rel="stylesheet" href="<?php echo asset_url('/assets/css/style.css'); ?>">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="login-container">
|
<div class="login-container">
|
||||||
@@ -36,7 +36,7 @@ require_once __DIR__ . '/config.php';
|
|||||||
<button type="submit" class="btn-login" id="submitBtn">发送重置链接</button>
|
<button type="submit" class="btn-login" id="submitBtn">发送重置链接</button>
|
||||||
<div id="tipMsg" class="error-msg" style="display: none;"></div>
|
<div id="tipMsg" class="error-msg" style="display: none;"></div>
|
||||||
<p style="text-align:center; margin-top:14px;">
|
<p style="text-align:center; margin-top:14px;">
|
||||||
<a href="/index.php" style="color:#667eea; font-size:14px;">返回登录</a>
|
<a href="/index.php" class="link" style="font-size:14px;">返回登录</a>
|
||||||
</p>
|
</p>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -54,8 +54,8 @@ require_once __DIR__ . '/config.php';
|
|||||||
function showTip(msg, isError) {
|
function showTip(msg, isError) {
|
||||||
const tip = document.getElementById('tipMsg');
|
const tip = document.getElementById('tipMsg');
|
||||||
tip.textContent = msg;
|
tip.textContent = msg;
|
||||||
|
tip.className = isError ? 'error-msg' : 'success-msg';
|
||||||
tip.style.display = 'block';
|
tip.style.display = 'block';
|
||||||
tip.style.color = isError ? '' : '#38a169';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('forgotForm').addEventListener('submit', async (e) => {
|
document.getElementById('forgotForm').addEventListener('submit', async (e) => {
|
||||||
|
|||||||
@@ -25,9 +25,9 @@ $page_title = $page_title ?? '首页';
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||||
<title><?php echo SITE_NAME; ?> - <?php echo $page_title; ?></title>
|
<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'): ?>
|
<?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; ?>
|
<?php endif; ?>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -62,6 +62,9 @@ $page_title = $page_title ?? '首页';
|
|||||||
window.DEDUCTION_ATTENDANCE_LATE = resp.data.DEDUCTION_ATTENDANCE_LATE;
|
window.DEDUCTION_ATTENDANCE_LATE = resp.data.DEDUCTION_ATTENDANCE_LATE;
|
||||||
window.DEDUCTION_ATTENDANCE_LEAVE = resp.data.DEDUCTION_ATTENDANCE_LEAVE;
|
window.DEDUCTION_ATTENDANCE_LEAVE = resp.data.DEDUCTION_ATTENDANCE_LEAVE;
|
||||||
window.STUDENT_INITIAL_POINTS = resp.data.STUDENT_INITIAL_POINTS;
|
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) {
|
} catch(e) {
|
||||||
@@ -72,11 +75,14 @@ $page_title = $page_title ?? '首页';
|
|||||||
window.DEDUCTION_ATTENDANCE_LATE = 1;
|
window.DEDUCTION_ATTENDANCE_LATE = 1;
|
||||||
window.DEDUCTION_ATTENDANCE_LEAVE = 0;
|
window.DEDUCTION_ATTENDANCE_LEAVE = 0;
|
||||||
window.STUDENT_INITIAL_POINTS = 60;
|
window.STUDENT_INITIAL_POINTS = 60;
|
||||||
|
window.PASSWORD_MIN_LENGTH = 6;
|
||||||
|
window.PASSWORD_MAX_LENGTH = 20;
|
||||||
|
window.PASSWORD_MIN_TYPES = 3;
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<script src="/assets/js/common.js"></script>
|
<script src="<?php echo asset_url('/assets/js/common.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/utils.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/utils.js'); ?>"></script>
|
||||||
<?php if ($user_type === 'admin'): ?>
|
<?php if ($user_type === 'admin'): ?>
|
||||||
<script>
|
<script>
|
||||||
window.USER_PERMISSIONS = <?php
|
window.USER_PERMISSIONS = <?php
|
||||||
@@ -102,3 +108,71 @@ $page_title = $page_title ?? '首页';
|
|||||||
?>;
|
?>;
|
||||||
</script>
|
</script>
|
||||||
<?php endif; ?>
|
<?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,19 +1,30 @@
|
|||||||
<div class="nav">
|
<div class="nav">
|
||||||
<a href="/admin/dashboard.php" class="nav-item<?php echo $current_page === 'dashboard' ? ' active' : ''; ?>">首页</a>
|
<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>
|
<a href="/admin/students.php" class="nav-item<?php echo $current_page === 'students' ? ' active' : ''; ?>">学生管理</a>
|
||||||
|
<?php if (has_perm('manage_conduct')): ?>
|
||||||
<a href="/admin/conduct.php" class="nav-item<?php echo $current_page === 'conduct' ? ' active' : ''; ?>">操行分管理</a>
|
<a href="/admin/conduct.php" class="nav-item<?php echo $current_page === 'conduct' ? ' active' : ''; ?>">操行分管理</a>
|
||||||
|
<?php endif; ?>
|
||||||
<?php if (has_perm('manage_homework')): ?>
|
<?php if (has_perm('manage_homework')): ?>
|
||||||
<a href="/admin/homework.php" class="nav-item<?php echo $current_page === 'homework' ? ' active' : ''; ?>">作业扣分</a>
|
<a href="/admin/homework.php" class="nav-item<?php echo $current_page === 'homework' ? ' active' : ''; ?>">作业扣分</a>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<?php if (has_perm('manage_attendance')): ?>
|
<?php if (has_perm('manage_attendance')): ?>
|
||||||
<a href="/admin/attendance.php" class="nav-item<?php echo $current_page === 'attendance' ? ' active' : ''; ?>">考勤管理</a>
|
<a href="/admin/attendance.php" class="nav-item<?php echo $current_page === 'attendance' ? ' active' : ''; ?>">考勤管理</a>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
<?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')): ?>
|
<?php if (has_perm('manage_admins')): ?>
|
||||||
<a href="/admin/admins.php" class="nav-item<?php echo $current_page === 'admins' ? ' active' : ''; ?>">管理员管理</a>
|
<a href="/admin/admins.php" class="nav-item<?php echo $current_page === 'admins' ? ' active' : ''; ?>">管理员管理</a>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
<?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')): ?>
|
<?php if (has_perm('manage_semesters')): ?>
|
||||||
<a href="/admin/semesters.php" class="nav-item<?php echo $current_page === 'semesters' ? ' active' : ''; ?>">学期管理</a>
|
<a href="/admin/semesters.php" class="nav-item<?php echo $current_page === 'semesters' ? ' active' : ''; ?>">学期管理</a>
|
||||||
<?php endif; ?>
|
<?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>
|
<a href="/admin/history.php" class="nav-item<?php echo $current_page === 'history' ? ' active' : ''; ?>">历史记录</a>
|
||||||
<?php if (has_perm('view_all_records')): ?>
|
<?php if (has_perm('view_all_records')): ?>
|
||||||
<a href="/admin/record_query.php" class="nav-item<?php echo $current_page === 'record_query' ? ' active' : ''; ?>">个人查询</a>
|
<a href="/admin/record_query.php" class="nav-item<?php echo $current_page === 'record_query' ? ' active' : ''; ?>">个人查询</a>
|
||||||
|
|||||||
+1
-1
@@ -28,7 +28,7 @@ if (isset($_SESSION['user_id']) && isset($_SESSION['user_type'])) {
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||||
<title><?php echo SITE_NAME; ?> - 登录</title>
|
<title><?php echo SITE_NAME; ?> - 登录</title>
|
||||||
<link rel="stylesheet" href="/assets/css/style.css">
|
<link rel="stylesheet" href="<?php echo asset_url('/assets/css/style.css'); ?>">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="login-container">
|
<div class="login-container">
|
||||||
|
|||||||
@@ -78,6 +78,6 @@ async function loadAttendance() {
|
|||||||
}
|
}
|
||||||
loadAttendance();
|
loadAttendance();
|
||||||
</script>
|
</script>
|
||||||
<script src="/assets/js/parent.js"></script>
|
<script src="<?php echo asset_url('/assets/js/parent.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -95,6 +95,6 @@ async function loadDashboard() {
|
|||||||
}
|
}
|
||||||
loadDashboard();
|
loadDashboard();
|
||||||
</script>
|
</script>
|
||||||
<script src="/assets/js/parent.js"></script>
|
<script src="<?php echo asset_url('/assets/js/parent.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -114,6 +114,6 @@ function changePage(delta) {
|
|||||||
|
|
||||||
loadHistory(1);
|
loadHistory(1);
|
||||||
</script>
|
</script>
|
||||||
<script src="/assets/js/parent.js"></script>
|
<script src="<?php echo asset_url('/assets/js/parent.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -20,7 +20,7 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
|
||||||
<title><?php echo SITE_NAME; ?> - 重置密码</title>
|
<title><?php echo SITE_NAME; ?> - 重置密码</title>
|
||||||
<link rel="stylesheet" href="/assets/css/style.css">
|
<link rel="stylesheet" href="<?php echo asset_url('/assets/css/style.css'); ?>">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="login-container">
|
<div class="login-container">
|
||||||
@@ -29,7 +29,7 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
<p>重置管理员密码</p>
|
<p>重置管理员密码</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="loadingBox" class="login-form" style="text-align:center; color:#888;">正在校验链接...</div>
|
<div id="loadingBox" class="login-form text-muted" style="text-align:center;">正在校验链接...</div>
|
||||||
|
|
||||||
<form id="resetForm" class="login-form" style="display:none;">
|
<form id="resetForm" class="login-form" style="display:none;">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -39,7 +39,7 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>新密码 <span style="color:red;">*</span></label>
|
<label>新密码 <span style="color:red;">*</span></label>
|
||||||
<input type="password" id="newPassword" required>
|
<input type="password" id="newPassword" required>
|
||||||
<small>密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
<small class="pwd-policy">密码长度6-20位,需包含大写字母、小写字母、数字、特殊符号中的至少3种</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>确认新密码 <span style="color:red;">*</span></label>
|
<label>确认新密码 <span style="color:red;">*</span></label>
|
||||||
@@ -50,8 +50,8 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div id="invalidBox" class="login-form" style="display:none; text-align:center;">
|
<div id="invalidBox" class="login-form" style="display:none; text-align:center;">
|
||||||
<p style="color:#e53e3e; margin-bottom:16px;">重置链接无效或已过期,请重新申请。</p>
|
<p class="text-danger" style="margin-bottom:16px;">重置链接无效或已过期,请重新申请。</p>
|
||||||
<a href="/forgot_password.php" style="color:#667eea;">重新申请</a>
|
<a href="/forgot_password.php" class="link">重新申请</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="login-footer">
|
<div class="login-footer">
|
||||||
@@ -62,15 +62,31 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script src="<?php echo asset_url('/assets/js/common.js'); ?>"></script>
|
||||||
<script>
|
<script>
|
||||||
window.API_BASE_URL = '<?php echo API_BASE_URL; ?>';
|
window.API_BASE_URL = '<?php echo API_BASE_URL; ?>';
|
||||||
const RESET_TOKEN = '<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>';
|
const RESET_TOKEN = '<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>';
|
||||||
|
|
||||||
|
// 加载密码策略(公开配置)
|
||||||
|
fetch(window.API_BASE_URL + '/api/config/deduction-rules')
|
||||||
|
.then(function(r) { return r.json(); })
|
||||||
|
.then(function(resp) {
|
||||||
|
if (resp && resp.success && resp.data) {
|
||||||
|
window.PASSWORD_MIN_LENGTH = resp.data.PASSWORD_MIN_LENGTH;
|
||||||
|
window.PASSWORD_MAX_LENGTH = resp.data.PASSWORD_MAX_LENGTH;
|
||||||
|
window.PASSWORD_MIN_TYPES = resp.data.PASSWORD_MIN_TYPES;
|
||||||
|
document.querySelectorAll('.pwd-policy').forEach(function(el) {
|
||||||
|
el.textContent = describePasswordPolicy();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function() {});
|
||||||
|
|
||||||
function showTip(msg, isError) {
|
function showTip(msg, isError) {
|
||||||
const tip = document.getElementById('tipMsg');
|
const tip = document.getElementById('tipMsg');
|
||||||
tip.textContent = msg;
|
tip.textContent = msg;
|
||||||
|
tip.className = isError ? 'error-msg' : 'success-msg';
|
||||||
tip.style.display = 'block';
|
tip.style.display = 'block';
|
||||||
tip.style.color = isError ? '' : '#38a169';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
(async function verifyToken() {
|
(async function verifyToken() {
|
||||||
@@ -106,8 +122,9 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
showTip('两次输入的密码不一致', true);
|
showTip('两次输入的密码不一致', true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (newPassword.length < 6 || newPassword.length > 20) {
|
const policyError = validatePasswordByPolicy(newPassword);
|
||||||
showTip('密码长度需为6-20位', true);
|
if (policyError) {
|
||||||
|
showTip(policyError, true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const btn = document.getElementById('submitBtn');
|
const btn = document.getElementById('submitBtn');
|
||||||
|
|||||||
@@ -78,6 +78,6 @@ async function loadAttendance() {
|
|||||||
|
|
||||||
loadAttendance();
|
loadAttendance();
|
||||||
</script>
|
</script>
|
||||||
<script src="/assets/js/student.js"></script>
|
<script src="<?php echo asset_url('/assets/js/student.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user