Compare commits
16
Commits
982e6ad70f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7304d151e | ||
|
|
0ac933a3a5 | ||
|
|
97f2de5d83 | ||
|
|
ad50f82c7b | ||
|
|
d9dd7bf7e8 | ||
|
|
928c86bd5a | ||
|
|
f624219cba | ||
|
|
db278188c6 | ||
|
|
2d3513b246 | ||
|
|
c87f62baf7 | ||
|
|
250acf35fd | ||
|
|
71c3263335 | ||
|
|
d0cdb5b928 | ||
|
|
dbf70f602e | ||
|
|
3a13656cfb | ||
|
|
fbd34b3d14 |
No files matched your search
@@ -61,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+ |
|
||||||
## 文件结构
|
## 文件结构
|
||||||
|
|
||||||
|
|||||||
@@ -40,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 = []
|
||||||
@@ -97,9 +110,18 @@ 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
|
@staticmethod
|
||||||
@@ -140,7 +162,7 @@ class AttendanceModel:
|
|||||||
chunk_size = 200
|
chunk_size = 200
|
||||||
for i in range(0, len(rows), chunk_size):
|
for i in range(0, len(rows), chunk_size):
|
||||||
chunk = rows[i:i + chunk_size]
|
chunk = rows[i:i + chunk_size]
|
||||||
values = ", ".join(["(%s, %s, 'present', NULL, %s, %s, %s, 0)"] * len(chunk))
|
values = ", ".join(["(%s, %s, 'present', '默认出勤', %s, %s, %s, 0)"] * len(chunk))
|
||||||
params = []
|
params = []
|
||||||
for student_id, day, slot, recorder_id, semester_id in chunk:
|
for student_id, day, slot, recorder_id, semester_id in chunk:
|
||||||
params.extend([student_id, day, slot, recorder_id, semester_id])
|
params.extend([student_id, day, slot, recorder_id, semester_id])
|
||||||
|
|||||||
+10
-4
@@ -69,7 +69,8 @@ class OperationLogModel:
|
|||||||
operation_type: str = None,
|
operation_type: str = None,
|
||||||
operator: str = None,
|
operator: str = None,
|
||||||
start_date: str = None,
|
start_date: str = None,
|
||||||
end_date: str = None
|
end_date: str = None,
|
||||||
|
keyword: str = None
|
||||||
):
|
):
|
||||||
conditions = ["1=1"]
|
conditions = ["1=1"]
|
||||||
params = []
|
params = []
|
||||||
@@ -79,6 +80,9 @@ class OperationLogModel:
|
|||||||
if operator:
|
if operator:
|
||||||
conditions.append("(operator_name LIKE %s OR operator_role LIKE %s)")
|
conditions.append("(operator_name LIKE %s OR operator_role LIKE %s)")
|
||||||
params.extend([f"%{operator}%", f"%{operator}%"])
|
params.extend([f"%{operator}%", f"%{operator}%"])
|
||||||
|
if keyword:
|
||||||
|
conditions.append("details LIKE %s")
|
||||||
|
params.append(f"%{keyword}%")
|
||||||
if start_date:
|
if start_date:
|
||||||
conditions.append("DATE(created_at) >= %s")
|
conditions.append("DATE(created_at) >= %s")
|
||||||
params.append(start_date)
|
params.append(start_date)
|
||||||
@@ -93,12 +97,13 @@ class OperationLogModel:
|
|||||||
operator: str = None,
|
operator: str = None,
|
||||||
start_date: str = None,
|
start_date: str = None,
|
||||||
end_date: str = None,
|
end_date: str = None,
|
||||||
|
keyword: str = None,
|
||||||
limit: int = 20,
|
limit: int = 20,
|
||||||
offset: int = 0
|
offset: int = 0
|
||||||
) -> List[Dict[str, Any]]:
|
) -> List[Dict[str, Any]]:
|
||||||
"""查询操作日志(分页)"""
|
"""查询操作日志(分页)"""
|
||||||
where, params = OperationLogModel._build_filters(
|
where, params = OperationLogModel._build_filters(
|
||||||
operation_type, operator, start_date, end_date
|
operation_type, operator, start_date, end_date, keyword
|
||||||
)
|
)
|
||||||
sql = f"""
|
sql = f"""
|
||||||
SELECT log_id, operator_id, operator_name, operator_role,
|
SELECT log_id, operator_id, operator_name, operator_role,
|
||||||
@@ -116,11 +121,12 @@ class OperationLogModel:
|
|||||||
operation_type: str = None,
|
operation_type: str = None,
|
||||||
operator: str = None,
|
operator: str = None,
|
||||||
start_date: str = None,
|
start_date: str = None,
|
||||||
end_date: str = None
|
end_date: str = None,
|
||||||
|
keyword: str = None
|
||||||
) -> int:
|
) -> int:
|
||||||
"""统计操作日志数量"""
|
"""统计操作日志数量"""
|
||||||
where, params = OperationLogModel._build_filters(
|
where, params = OperationLogModel._build_filters(
|
||||||
operation_type, operator, start_date, end_date
|
operation_type, operator, start_date, end_date, keyword
|
||||||
)
|
)
|
||||||
result = await execute_one(
|
result = await execute_one(
|
||||||
f"SELECT COUNT(*) AS total FROM operation_logs WHERE {where}",
|
f"SELECT COUNT(*) AS total FROM operation_logs WHERE {where}",
|
||||||
|
|||||||
@@ -102,6 +102,23 @@ class UserModel:
|
|||||||
return True
|
return True
|
||||||
exists = await execute_one("SELECT 1 FROM users WHERE user_id = %s", (user_id,))
|
exists = await execute_one("SELECT 1 FROM users WHERE user_id = %s", (user_id,))
|
||||||
return exists is not None
|
return exists is not None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def upgrade_password_hash(user_id: int, password: str) -> bool:
|
||||||
|
"""仅升级密码哈希格式(bcrypt),不改变 need_change_password 标记
|
||||||
|
|
||||||
|
登录时自动升级旧哈希不等于用户主动改密,不能清除"密码待修改"标记。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
password_hash = security.bcrypt_password(password)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"密码加密失败: {e}")
|
||||||
|
raise
|
||||||
|
result = await execute_update(
|
||||||
|
"UPDATE users SET password_hash = %s WHERE user_id = %s",
|
||||||
|
(password_hash, user_id)
|
||||||
|
)
|
||||||
|
return result > 0
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def update_last_login(user_id: int, ip: str) -> None:
|
async def update_last_login(user_id: int, ip: str) -> None:
|
||||||
|
|||||||
+112
-20
@@ -23,11 +23,13 @@ from services.attendance_service import AttendanceService
|
|||||||
from services.homework_service import HomeworkService
|
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 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, DefaultAttendanceRequest, CalendarDayRequest,
|
AddAttendanceRequest, DefaultAttendanceRequest, FullDayLeaveRequest, CalendarDayRequest,
|
||||||
HomeworkRegisterRequest,
|
HomeworkRegisterRequest,
|
||||||
UpdateAdminRequest, ResetPasswordRequest,
|
UpdateAdminRequest, ResetPasswordRequest,
|
||||||
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
||||||
@@ -42,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")
|
||||||
@@ -246,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:
|
||||||
@@ -270,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
|
||||||
)
|
)
|
||||||
@@ -300,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
|
||||||
)
|
)
|
||||||
@@ -411,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,
|
||||||
@@ -451,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,
|
||||||
@@ -544,6 +594,38 @@ async def default_attendance(request: Request, req: DefaultAttendanceRequest):
|
|||||||
return error_response(message=result["message"])
|
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")
|
@router.get("/attendance/calendar")
|
||||||
async def get_attendance_calendar(
|
async def get_attendance_calendar(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -629,16 +711,19 @@ async def register_homework(request: Request, req: HomeworkRegisterRequest):
|
|||||||
)
|
)
|
||||||
if result["success"]:
|
if result["success"]:
|
||||||
data = result.get("data", {})
|
data = result.get("data", {})
|
||||||
await LogService.write_operation_log(
|
try:
|
||||||
operator_id=user["user_id"], operator_name=user["real_name"],
|
await LogService.write_operation_log(
|
||||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||||
operation_type="homework_register", target_type="homework",
|
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||||
details=(
|
operation_type="homework_register", target_type="homework",
|
||||||
f"按次登记[{req.title or '作业登记'}]: 共{req.total_times}次, "
|
details=(
|
||||||
f"缺交{data.get('deducted_students', 0)}人, 合计扣{data.get('total_deduction', 0)}分"
|
f"按次登记[{req.title or '作业登记'}]: 共{req.total_times}次, "
|
||||||
),
|
f"缺交{data.get('deducted_students', 0)}人, 合计扣{data.get('total_deduction', 0)}分"
|
||||||
ip=request.client.host
|
),
|
||||||
)
|
ip=request.client.host
|
||||||
|
)
|
||||||
|
except Exception as log_error:
|
||||||
|
logger.error(f"写入作业按次登记日志失败: {log_error}")
|
||||||
return success_response(data=data, message=result["message"])
|
return success_response(data=data, message=result["message"])
|
||||||
else:
|
else:
|
||||||
return error_response(message=result["message"])
|
return error_response(message=result["message"])
|
||||||
@@ -907,6 +992,11 @@ async def reset_admin_password(request: Request, user_id: int, req: ResetPasswor
|
|||||||
# 使用传入的新密码(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 "管理员",
|
||||||
@@ -993,7 +1083,8 @@ async def get_operation_logs(
|
|||||||
operation_type: Optional[str] = None,
|
operation_type: Optional[str] = None,
|
||||||
operator: Optional[str] = None,
|
operator: Optional[str] = None,
|
||||||
start_date: Optional[str] = None,
|
start_date: Optional[str] = None,
|
||||||
end_date: Optional[str] = None
|
end_date: Optional[str] = None,
|
||||||
|
keyword: Optional[str] = None
|
||||||
):
|
):
|
||||||
"""查询操作日志(需操作日志查看权限)"""
|
"""查询操作日志(需操作日志查看权限)"""
|
||||||
try:
|
try:
|
||||||
@@ -1006,7 +1097,8 @@ async def get_operation_logs(
|
|||||||
operation_type=operation_type,
|
operation_type=operation_type,
|
||||||
operator=operator,
|
operator=operator,
|
||||||
start_date=start_date,
|
start_date=start_date,
|
||||||
end_date=end_date
|
end_date=end_date,
|
||||||
|
keyword=keyword
|
||||||
)
|
)
|
||||||
return success_response(data=result)
|
return success_response(data=result)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
+17
-1
@@ -12,7 +12,7 @@
|
|||||||
from fastapi import APIRouter, Request
|
from fastapi import APIRouter, Request
|
||||||
|
|
||||||
from schemas.auth import (
|
from schemas.auth import (
|
||||||
LoginRequest, ChangePasswordRequest,
|
LoginRequest, ChangePasswordRequest, InitPasswordRequest,
|
||||||
ForgotPasswordRequest, ResetPasswordRequest,
|
ForgotPasswordRequest, ResetPasswordRequest,
|
||||||
SendEmailCodeRequest, ConfirmBindEmailRequest, UnbindEmailRequest
|
SendEmailCodeRequest, ConfirmBindEmailRequest, UnbindEmailRequest
|
||||||
)
|
)
|
||||||
@@ -98,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):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -60,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
|
||||||
@@ -141,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})
|
||||||
|
|
||||||
@@ -195,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
|
||||||
|
|
||||||
@@ -231,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
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -81,6 +81,13 @@ class DefaultAttendanceRequest(BaseModel):
|
|||||||
slots: Optional[List[str]] = Field(None, description="时段列表(morning/afternoon/evening),默认全部")
|
slots: Optional[List[str]] = Field(None, description="时段列表(morning/afternoon/evening),默认全部")
|
||||||
|
|
||||||
|
|
||||||
|
class FullDayLeaveRequest(BaseModel):
|
||||||
|
"""整天请假请求"""
|
||||||
|
date: date
|
||||||
|
student_ids: List[int] = Field(..., min_length=1, max_length=200, description="请假学生ID列表")
|
||||||
|
reason: Optional[str] = Field(None, max_length=255, description="原因")
|
||||||
|
|
||||||
|
|
||||||
class CalendarDayRequest(BaseModel):
|
class CalendarDayRequest(BaseModel):
|
||||||
"""校历手动设置请求"""
|
"""校历手动设置请求"""
|
||||||
date: date
|
date: date
|
||||||
@@ -102,7 +109,7 @@ class HomeworkRegisterRequest(BaseModel):
|
|||||||
total_times: int = Field(..., ge=1, le=99, description="总提交次数")
|
total_times: int = Field(..., ge=1, le=99, description="总提交次数")
|
||||||
per_deduction: Optional[int] = Field(None, ge=1, le=20, description="单次缺交扣分(默认取系统配置)")
|
per_deduction: Optional[int] = Field(None, ge=1, le=20, description="单次缺交扣分(默认取系统配置)")
|
||||||
note: Optional[str] = Field(None, max_length=100, description="备注")
|
note: Optional[str] = Field(None, max_length=100, description="备注")
|
||||||
records: List[HomeworkRegisterItem] = Field(..., min_length=1, max_length=200, description="缺交学生与缺交次数")
|
records: List[HomeworkRegisterItem] = Field(default_factory=list, max_length=200, description="缺交学生与缺交次数(可为空,空=全班已交)")
|
||||||
|
|
||||||
|
|
||||||
class ResetPasswordRequest(BaseModel):
|
class ResetPasswordRequest(BaseModel):
|
||||||
|
|||||||
@@ -25,6 +25,11 @@ class ChangePasswordRequest(BaseModel):
|
|||||||
force: bool = Field(default=False, description="是否强制修改(首次登录)")
|
force: bool = Field(default=False, description="是否强制修改(首次登录)")
|
||||||
|
|
||||||
|
|
||||||
|
class InitPasswordRequest(BaseModel):
|
||||||
|
"""首次登录初始化密码请求(无需原密码)"""
|
||||||
|
new_password: str = Field(..., min_length=1, max_length=100, description="新密码(按系统密码策略校验)")
|
||||||
|
|
||||||
|
|
||||||
class ForgotPasswordRequest(BaseModel):
|
class ForgotPasswordRequest(BaseModel):
|
||||||
"""忘记密码请求"""
|
"""忘记密码请求"""
|
||||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
||||||
|
|||||||
@@ -127,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}",
|
||||||
@@ -141,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": "考勤记录添加成功"}
|
||||||
@@ -239,6 +239,96 @@ class AttendanceService:
|
|||||||
return True
|
return True
|
||||||
return day.weekday() < 5
|
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
|
@staticmethod
|
||||||
async def batch_default_attendance(
|
async def batch_default_attendance(
|
||||||
start_date: str,
|
start_date: str,
|
||||||
@@ -269,20 +359,39 @@ class AttendanceService:
|
|||||||
if not students:
|
if not students:
|
||||||
return {"success": False, "message": "暂无在读学生"}
|
return {"success": False, "message": "暂无在读学生"}
|
||||||
|
|
||||||
calendar_info = await AttendanceService.get_calendar(start_date, end_date)
|
# 校历多取一天,用于判断"次日是否上课"(决定节前半日/返校晚修)
|
||||||
|
calendar_info = await AttendanceService.get_calendar(
|
||||||
|
start_date, (end + timedelta(days=1)).isoformat()
|
||||||
|
)
|
||||||
|
|
||||||
school_days = []
|
# 常规作息:
|
||||||
|
# 返校日(非上课日、次日上课)→ 仅晚修
|
||||||
|
# 上课日且次日仍上课 → 按所选时段(早/中/晚)
|
||||||
|
# 上课日且次日不上课(放假前一天)→ 仅上午(中午走人,无下午/晚修)
|
||||||
|
day_slots = []
|
||||||
|
full_days = 0
|
||||||
|
half_days = 0
|
||||||
|
return_evenings = 0
|
||||||
rest_days = 0
|
rest_days = 0
|
||||||
cursor_day = start
|
cursor_day = start
|
||||||
while cursor_day <= end:
|
while cursor_day <= end:
|
||||||
if AttendanceService._is_school_day(cursor_day, calendar_info):
|
slots_today = AttendanceService._slots_for_date(cursor_day, calendar_info, selected_slots)
|
||||||
school_days.append(cursor_day)
|
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:
|
else:
|
||||||
rest_days += 1
|
rest_days += 1
|
||||||
cursor_day += timedelta(days=1)
|
cursor_day += timedelta(days=1)
|
||||||
|
|
||||||
if not school_days:
|
if not day_slots:
|
||||||
return {"success": False, "message": "所选范围内没有上课日(全部为周末/节假日)"}
|
return {"success": False, "message": "所选范围内没有需要默认出勤的时段(均为休息日或未选对应时段)"}
|
||||||
|
|
||||||
from models.semester import SemesterModel
|
from models.semester import SemesterModel
|
||||||
active_semester = await SemesterModel.get_active()
|
active_semester = await SemesterModel.get_active()
|
||||||
@@ -293,26 +402,32 @@ class AttendanceService:
|
|||||||
existing_set = {(r['student_id'], r['date'], r['slot']) for r in existing}
|
existing_set = {(r['student_id'], r['date'], r['slot']) for r in existing}
|
||||||
|
|
||||||
rows = []
|
rows = []
|
||||||
for school_day in school_days:
|
total_combos = 0
|
||||||
day_iso = school_day.isoformat()
|
for day, slots_today in day_slots:
|
||||||
|
day_iso = day.isoformat()
|
||||||
for student_id in student_ids:
|
for student_id in student_ids:
|
||||||
for slot in selected_slots:
|
total_combos += len(slots_today)
|
||||||
|
for slot in slots_today:
|
||||||
if (student_id, day_iso, slot) not in existing_set:
|
if (student_id, day_iso, slot) not in existing_set:
|
||||||
rows.append((student_id, day_iso, slot, recorder_id, semester_id))
|
rows.append((student_id, day_iso, slot, recorder_id, semester_id))
|
||||||
|
|
||||||
total_combos = len(student_ids) * len(school_days) * len(selected_slots)
|
|
||||||
created = await AttendanceModel.bulk_create_present(rows)
|
created = await AttendanceModel.bulk_create_present(rows)
|
||||||
skipped_existing = total_combos - len(rows)
|
skipped_existing = total_combos - len(rows)
|
||||||
|
|
||||||
|
summary = (
|
||||||
|
f"上课日{full_days + half_days}天(其中节前半日{half_days}天)、"
|
||||||
|
f"返校晚修{return_evenings}天,新增{created}条,跳过已有{skipped_existing}条"
|
||||||
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"用户[{recorder_id}] 批量默认出勤 {start_date}~{end_date} 时段{','.join(selected_slots)}: "
|
f"用户[{recorder_id}] 批量默认出勤 {start_date}~{end_date} 时段{','.join(selected_slots)}: {summary}"
|
||||||
f"上课日{len(school_days)}天,新增{created}条,跳过已有{skipped_existing}条"
|
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
"success": True,
|
"success": True,
|
||||||
"message": f"默认出勤完成:{len(school_days)}个上课日,新增{created}条,跳过已有{skipped_existing}条",
|
"message": f"默认出勤完成:{summary}",
|
||||||
"data": {
|
"data": {
|
||||||
"days": len(school_days),
|
"days": full_days + half_days,
|
||||||
|
"half_days": half_days,
|
||||||
|
"return_evenings": return_evenings,
|
||||||
"rest_days": rest_days,
|
"rest_days": rest_days,
|
||||||
"created": created,
|
"created": created,
|
||||||
"skipped_existing": skipped_existing,
|
"skipped_existing": skipped_existing,
|
||||||
|
|||||||
@@ -71,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
|
||||||
|
|
||||||
@@ -148,13 +148,13 @@ 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"])
|
||||||
@@ -173,11 +173,35 @@ 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]]:
|
||||||
|
|||||||
@@ -9,11 +9,13 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
"""节假日服务:在线获取法定节假日与调休补班数据(带缓存与失败降级)"""
|
"""节假日服务:优先使用国内接口获取法定节假日与调休补班(缓存 + 失败降级)"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import ssl
|
||||||
import time
|
import time
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
@@ -22,7 +24,10 @@ from utils.logger import get_logger
|
|||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
HOLIDAY_API = 'https://timor.tech/api/holiday/year/{year}'
|
# 国内节假日接口(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
|
CACHE_TTL = 12 * 3600
|
||||||
FAIL_CACHE_TTL = 600
|
FAIL_CACHE_TTL = 600
|
||||||
REQUEST_TIMEOUT = 6
|
REQUEST_TIMEOUT = 6
|
||||||
@@ -30,30 +35,89 @@ REQUEST_TIMEOUT = 6
|
|||||||
_cache: Dict[int, Dict[str, Any]] = {}
|
_cache: Dict[int, Dict[str, Any]] = {}
|
||||||
|
|
||||||
|
|
||||||
def _fetch_year_sync(year: int) -> Dict[str, Any]:
|
def _urlopen_json(url: str) -> Any:
|
||||||
"""同步请求节假日接口(在线程池中调用)"""
|
"""请求 JSON(证书校验失败时回退为不校验重试一次)"""
|
||||||
request = urllib.request.Request(
|
request = urllib.request.Request(
|
||||||
HOLIDAY_API.format(year=year),
|
url,
|
||||||
headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'}
|
headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'}
|
||||||
)
|
)
|
||||||
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
try:
|
||||||
payload = json.loads(response.read().decode('utf-8'))
|
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'))
|
||||||
|
|
||||||
if payload.get('code') != 0:
|
|
||||||
raise ValueError(f"接口返回错误码: {payload.get('code')}")
|
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] = {}
|
holidays: Dict[str, str] = {}
|
||||||
workdays: Dict[str, str] = {}
|
workdays: Dict[str, str] = {}
|
||||||
for day, info in (payload.get('holiday') or {}).items():
|
for item in items:
|
||||||
d = str(info.get('date') or f'{year}-{day}')[:10]
|
try:
|
||||||
if info.get('holiday'):
|
date_int = int(item.get('date') or 0)
|
||||||
holidays[d] = info.get('name') or '节假日'
|
except (TypeError, ValueError):
|
||||||
else:
|
continue
|
||||||
workdays[d] = info.get('name') or '调休补班'
|
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}
|
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]:
|
async def get_year_data(year: int) -> Dict[str, Any]:
|
||||||
"""获取某年的节假日/调休数据(内存缓存,接口失败自动降级)"""
|
"""获取某年的节假日/调休数据(内存缓存,接口失败自动降级)"""
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -68,12 +132,15 @@ async def get_year_data(year: int) -> Dict[str, Any]:
|
|||||||
data = await loop.run_in_executor(None, _fetch_year_sync, year)
|
data = await loop.run_in_executor(None, _fetch_year_sync, year)
|
||||||
data['fetched_at'] = now
|
data['fetched_at'] = now
|
||||||
_cache[year] = data
|
_cache[year] = data
|
||||||
logger.info(
|
if data['api_ok']:
|
||||||
f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天"
|
logger.info(
|
||||||
)
|
f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.warning(f"节假日数据获取失败: {year}年(接口均不可用)")
|
||||||
return data
|
return data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"节假日接口获取失败({year}): {e}")
|
logger.warning(f"节假日数据获取异常({year}): {e}")
|
||||||
failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now}
|
failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now}
|
||||||
_cache[year] = failed
|
_cache[year] = failed
|
||||||
return failed
|
return failed
|
||||||
|
|||||||
@@ -84,15 +84,12 @@ class HomeworkService:
|
|||||||
if sid not in student_map:
|
if sid not in student_map:
|
||||||
return {"success": False, "message": "存在无效学生(不存在或已禁用)"}
|
return {"success": False, "message": "存在无效学生(不存在或已禁用)"}
|
||||||
|
|
||||||
if limits["max_subtract"] is not None:
|
# 单次扣分上限按"每次缺交"校验:按次登记中一次缺交视为一次扣分,合计分可超过单次上限
|
||||||
for sid, miss in miss_map.items():
|
if limits["max_subtract"] is not None and deduction > limits["max_subtract"]:
|
||||||
total_deduct = miss * deduction
|
return {
|
||||||
if total_deduct > limits["max_subtract"]:
|
"success": False,
|
||||||
name = student_map[sid]["name"]
|
"message": f"单次缺交扣分不能超过{limits['max_subtract']}分"
|
||||||
return {
|
}
|
||||||
"success": False,
|
|
||||||
"message": f"{name} 缺交{miss}次合计扣{total_deduct}分,超过单次扣分上限{limits['max_subtract']}分"
|
|
||||||
}
|
|
||||||
|
|
||||||
# 创建作业记录(每次一条)
|
# 创建作业记录(每次一条)
|
||||||
base_title = (title or "作业登记").strip() or "作业登记"
|
base_title = (title or "作业登记").strip() or "作业登记"
|
||||||
|
|||||||
@@ -62,7 +62,8 @@ class LogService:
|
|||||||
operation_type: str = None,
|
operation_type: str = None,
|
||||||
operator: str = None,
|
operator: str = None,
|
||||||
start_date: str = None,
|
start_date: str = None,
|
||||||
end_date: str = None
|
end_date: str = None,
|
||||||
|
keyword: str = None
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""查询操作日志(分页 + 筛选)"""
|
"""查询操作日志(分页 + 筛选)"""
|
||||||
if operation_type == "":
|
if operation_type == "":
|
||||||
@@ -73,12 +74,14 @@ class LogService:
|
|||||||
start_date = None
|
start_date = None
|
||||||
if end_date == "":
|
if end_date == "":
|
||||||
end_date = None
|
end_date = None
|
||||||
|
if keyword == "":
|
||||||
|
keyword = None
|
||||||
offset = (page - 1) * page_size
|
offset = (page - 1) * page_size
|
||||||
total = await OperationLogModel.count_logs(
|
total = await OperationLogModel.count_logs(
|
||||||
operation_type, operator, start_date, end_date
|
operation_type, operator, start_date, end_date, keyword
|
||||||
)
|
)
|
||||||
logs = await OperationLogModel.get_logs(
|
logs = await OperationLogModel.get_logs(
|
||||||
operation_type, operator, start_date, end_date, page_size, offset
|
operation_type, operator, start_date, end_date, keyword, page_size, offset
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
"logs": logs,
|
"logs": logs,
|
||||||
|
|||||||
+38
-10
@@ -84,6 +84,17 @@
|
|||||||
1. 在历史记录列表中找到目标记录
|
1. 在历史记录列表中找到目标记录
|
||||||
2. 点击右侧"撤销"按钮
|
2. 点击右侧"撤销"按钮
|
||||||
3. 确认撤销操作
|
3. 确认撤销操作
|
||||||
|
4. 撤销后记录会移入"已撤销"(状态筛选选"已撤销"可查看并反撤销),学生分数自动恢复
|
||||||
|
|
||||||
|
#### 批量撤销 / 批量反撤销(批次合并视图)
|
||||||
|
1. 勾选"批次合并"后,同一批次的记录会合并为一行
|
||||||
|
2. 点击该行的"批量撤销"可一次撤销整批记录
|
||||||
|
3. 查看"已撤销"状态的批次时,点击"批量反撤销"可一次恢复整批记录
|
||||||
|
4. 撤销/反撤销操作均会写入操作日志(批量操作记录条数与记录ID)
|
||||||
|
|
||||||
|
#### 反撤销(恢复记录)
|
||||||
|
1. 状态筛选选择"已撤销",找到被撤销的记录
|
||||||
|
2. 点击"反撤销"按钮,确认后分数变动重新生效
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -151,29 +162,43 @@
|
|||||||
6. 点击"全选"可快速选中所有未记录的学生
|
6. 点击"全选"可快速选中所有未记录的学生
|
||||||
7. 点击"提交考勤"批量提交
|
7. 点击"提交考勤"批量提交
|
||||||
|
|
||||||
|
#### 请假(整天)
|
||||||
|
按学生**当天实际考勤时段**一键请假(不再固定 3 条):
|
||||||
|
|
||||||
|
1. 在学生方格中**点击选择**请假的学生
|
||||||
|
2. 点击工具栏"请假(整天)"按钮,系统按当天作息提交:
|
||||||
|
- 正常上课日(次日仍上课)→ **早/中/晚 3 条**
|
||||||
|
- 放假前一天(半天)→ **仅上午 1 条**
|
||||||
|
- 返校日晚修 → **晚修 1 条**
|
||||||
|
3. 每个时段按"请假"配置扣分(如 1 分/次:半天 1 分、正常日 3 分)
|
||||||
|
|
||||||
|
> 已有的对应时段记录会被更新为请假;如需只标记某个时段,仍用普通"请假"按钮 + 时段选择。
|
||||||
|
|
||||||
#### 查看考勤记录
|
#### 查看考勤记录
|
||||||
- 按日期筛选考勤记录
|
- 按日期筛选考勤记录
|
||||||
- 每条记录显示:学号、姓名、状态、原因、记录人、扣分情况
|
- 每条记录显示:学号、姓名、状态、原因、记录人、扣分金额(如"扣3分",已撤销的注明)
|
||||||
|
|
||||||
#### 默认出勤(批量补全)
|
#### 默认出勤(批量补全)
|
||||||
用于给一段时间内没有异常的学生批量补"出勤"记录,让统计报表的出勤率有意义。
|
用于给一段时间内没有异常的学生批量补"出勤"记录,让统计报表的出勤率有意义。
|
||||||
|
|
||||||
1. 点击工具栏"默认出勤"按钮
|
1. 点击工具栏"默认出勤"按钮
|
||||||
2. 选择**日期范围**(默认本月1日至今)与**时段**(默认全选早/中/晚)
|
2. 选择**日期范围**(默认本月1日至今)与**时段**(默认全选早/中/晚)
|
||||||
3. 点击"开始补全",完成后提示:上课日数量、新增条数、跳过已有条数
|
3. 点击"开始补全",完成后提示:上课日/节前半日/返校晚修数量、新增条数、跳过已有条数
|
||||||
|
|
||||||
规则说明:
|
作息规则(常规情况):
|
||||||
- **跳过周末与法定节假日**(节假日/调休补班来自在线接口)
|
- **返校日**(非上课日、次日上课,如周日)→ 仅生成**晚修**出勤
|
||||||
- **调休补班日照常**(接口中的补班日按上课处理)
|
- **上课日且次日仍上课** → 按所选时段生成(早/中/晚)
|
||||||
- **手动补课日照常**;手动放假日跳过
|
- **放假前一天**(上课日、次日不上课)→ 仅生成**上午**出勤(中午离校,无下午/晚修);少数需要下午上课的,按正常流程单独补录下午记录即可
|
||||||
|
- **跳过周末与法定节假日**(节假日/调休补班来自国内在线接口,失败时自动切换备用接口)
|
||||||
|
- **调休补班日照常**(接口中的补班日按上课处理);**手动补课日照常**、手动放假日跳过
|
||||||
- 已有的考勤记录(含缺勤/迟到/请假)**不会被覆盖**
|
- 已有的考勤记录(含缺勤/迟到/请假)**不会被覆盖**
|
||||||
- 单次最长支持 180 天;接口暂时不可用时会提示,本次仅按周末与手动设置判断
|
- 单次最长支持 180 天;接口暂时不可用时会提示,本次仅按周末与手动设置判断
|
||||||
|
|
||||||
#### 节假日 / 补课设置
|
#### 节假日 / 补课设置
|
||||||
点击工具栏"节假日/补课"按钮打开校历设置:
|
点击工具栏"节假日/补课"按钮打开校历设置:
|
||||||
|
|
||||||
- **查询范围**:查看范围内的法定节假日(放假)、调休补班(按上课)——来自在线接口,只读
|
- **查询范围**:查看范围内的法定节假日(放假)、调休补班(按上课)——来自国内在线接口(失败时自动切换备用接口),只读
|
||||||
- **手动添加**:添加学校自己的安排,可选择"补课(按上课)"或"放假(按休息)",可填写备注;手动设置**优先于接口**(例如把某天调休补班改回放假)
|
- **手动添加**:添加学校自己的安排,可选择「补课(按上课)」或「放假(按休息)」,可填写备注;手动设置**优先于接口**(例如把某天调休补班改回放假)
|
||||||
- 手动添加的记录可随时删除
|
- 手动添加的记录可随时删除
|
||||||
|
|
||||||
**默认扣分规则**:
|
**默认扣分规则**:
|
||||||
@@ -182,7 +207,7 @@
|
|||||||
|---------|---------|
|
|---------|---------|
|
||||||
| 缺勤 | 3分 |
|
| 缺勤 | 3分 |
|
||||||
| 迟到 | 1分 |
|
| 迟到 | 1分 |
|
||||||
| 请假 | 0分 |
|
| 请假 | 按系统配置(如配置为1分,整天请假=3分) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -258,6 +283,7 @@
|
|||||||
1. 点击"重置密码"按钮
|
1. 点击"重置密码"按钮
|
||||||
2. 输入新密码
|
2. 输入新密码
|
||||||
3. 点击"确认重置"
|
3. 点击"确认重置"
|
||||||
|
4. 重置后该账号**下次登录需重新设置密码**(弹窗设置,无需输入原密码)
|
||||||
|
|
||||||
#### 禁用/启用管理员
|
#### 禁用/启用管理员
|
||||||
- 点击"禁用/启用"切换账号状态,禁用后无法登录
|
- 点击"禁用/启用"切换账号状态,禁用后无法登录
|
||||||
@@ -373,6 +399,7 @@
|
|||||||
- 输入原密码和新密码
|
- 输入原密码和新密码
|
||||||
- 新密码需符合密码强度要求(密码策略可在「系统设置」中调整)
|
- 新密码需符合密码强度要求(密码策略可在「系统设置」中调整)
|
||||||
- 修改成功后需重新登录
|
- 修改成功后需重新登录
|
||||||
|
- **密码待修改时(首次使用或被管理员重置后)**:登录时会弹窗要求设置新密码(**无需输入原密码**);日常主动改密仍需原密码
|
||||||
- 页面下方可**绑定邮箱**(找回密码用):
|
- 页面下方可**绑定邮箱**(找回密码用):
|
||||||
1. 输入新邮箱,点击"发送验证码"(无需密码)
|
1. 输入新邮箱,点击"发送验证码"(无需密码)
|
||||||
2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效)
|
2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效)
|
||||||
@@ -399,8 +426,9 @@
|
|||||||
|
|
||||||
用于审计管理端所有关键操作。
|
用于审计管理端所有关键操作。
|
||||||
|
|
||||||
- 支持按**操作类型**、**操作人/角色关键词**、**日期范围**筛选
|
- 支持按**操作类型**、**操作人/角色关键词**、**详情关键词**(学生姓名/记录原因等)、**日期范围**筛选
|
||||||
- 分页展示:时间、操作人、角色、操作类型、对象、详情、IP
|
- 分页展示:时间、操作人、角色、操作类型、对象、详情、IP
|
||||||
|
- 操行分相关日志详情包含:学生姓名(学号)、分值变动、原因、原操作人;批量撤销/反撤销会记录条数与记录ID
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -223,8 +223,8 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { userId: <?php echo intval($_SESSION['user_id']); ?> };</script>
|
<script>window.PAGE_CONFIG = { 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/admin-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/admin-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/admins.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'; ?>
|
||||||
@@ -53,6 +53,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<?php if (has_perm('manage_calendar')): ?>
|
<?php if (has_perm('manage_calendar')): ?>
|
||||||
<button class="btn btn-ghost" onclick="openCalendarModal()">节假日/补课</button>
|
<button class="btn btn-ghost" onclick="openCalendarModal()">节假日/补课</button>
|
||||||
<?php endif; ?>
|
<?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">
|
||||||
@@ -71,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>
|
||||||
@@ -111,7 +112,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<span style="color:#999;">至</span>
|
<span style="color:#999;">至</span>
|
||||||
<input type="date" id="defaultEndDate" style="width:auto;">
|
<input type="date" id="defaultEndDate" style="width:auto;">
|
||||||
</div>
|
</div>
|
||||||
<small>跳过周末与法定节假日(在线接口获取),调休补班与手动补课日照常;已有的考勤记录(含异常)不会被覆盖</small>
|
<small>按学校常规作息生成:返校日晚修、放假前一天仅上午(中午离校)、其余上课日按所选时段;跳过周末与法定节假日(调休补课日照常),已有记录不覆盖</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>时段</label>
|
<label>时段</label>
|
||||||
@@ -164,7 +165,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/attendance-manage.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'; ?>
|
||||||
@@ -58,9 +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/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/conduct.js"></script>
|
<script src="<?php echo asset_url('/assets/js/conduct.js'); ?>"></script>
|
||||||
|
|
||||||
<!-- 批量加减分模态框 -->
|
<!-- 批量加减分模态框 -->
|
||||||
<div id="batchPointsModal" class="modal">
|
<div id="batchPointsModal" class="modal">
|
||||||
|
|||||||
@@ -88,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>
|
||||||
|
|||||||
@@ -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,9 @@ 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/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/history.js"></script>
|
<script src="<?php echo asset_url('/assets/js/history.js'); ?>"></script>
|
||||||
|
|
||||||
<!-- 导出历史记录模态框 -->
|
<!-- 导出历史记录模态框 -->
|
||||||
<div id="exportHistoryModal" class="modal">
|
<div id="exportHistoryModal" class="modal">
|
||||||
|
|||||||
@@ -159,7 +159,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>缺交学生与次数</label>
|
<label>缺交学生与次数</label>
|
||||||
<div id="hwRegStudentList" class="hw-reg-list"></div>
|
<div id="hwRegStudentList" class="hw-reg-list"></div>
|
||||||
<small>缺交次数不超过总提交次数,其他学生自动记为已交</small>
|
<small>默认全部学生按已交处理;在列表中为缺交学生填写缺交次数(0 或留空 = 已交),缺交次数不超过总提交次数</small>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>备注</label>
|
<label>备注</label>
|
||||||
@@ -289,8 +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/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/homework-manage.js"></script>
|
<script src="<?php echo asset_url('/assets/js/homework-manage.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -39,6 +39,10 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<label>操作人 / 角色</label>
|
<label>操作人 / 角色</label>
|
||||||
<input type="text" id="logOperatorFilter" placeholder="关键词">
|
<input type="text" id="logOperatorFilter" placeholder="关键词">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="filter-group">
|
||||||
|
<label>详情关键词</label>
|
||||||
|
<input type="text" id="logKeywordFilter" placeholder="学生 / 原因等">
|
||||||
|
</div>
|
||||||
<div class="filter-group">
|
<div class="filter-group">
|
||||||
<label>开始日期</label>
|
<label>开始日期</label>
|
||||||
<input type="date" id="logStartDate">
|
<input type="date" id="logStartDate">
|
||||||
@@ -72,6 +76,6 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/js/logs.js"></script>
|
<script src="<?php echo asset_url('/assets/js/logs.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -106,7 +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/record-query.js"></script>
|
<script src="<?php echo asset_url('/assets/js/record-query.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -99,6 +99,6 @@ 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/reports.js"></script>
|
<script src="<?php echo asset_url('/assets/js/reports.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -198,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'; ?>
|
||||||
@@ -51,6 +51,6 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/js/settings.js"></script>
|
<script src="<?php echo asset_url('/assets/js/settings.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -174,10 +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/student-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/student-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/modules/points-mgmt.js"></script>
|
<script src="<?php echo asset_url('/assets/js/modules/points-mgmt.js'); ?>"></script>
|
||||||
<script src="/assets/js/students-manage.js"></script>
|
<script src="<?php echo asset_url('/assets/js/students-manage.js'); ?>"></script>
|
||||||
|
|
||||||
<!-- 导出学生名单模态框 -->
|
<!-- 导出学生名单模态框 -->
|
||||||
<div id="exportStudentsModal" class="modal">
|
<div id="exportStudentsModal" class="modal">
|
||||||
|
|||||||
@@ -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) {
|
||||||
@@ -251,8 +260,10 @@ async function submitDefaultAttendance() {
|
|||||||
await loadExistingRecords();
|
await loadExistingRecords();
|
||||||
loadAttendanceRecords();
|
loadAttendanceRecords();
|
||||||
} else {
|
} else {
|
||||||
showToast((res && res.message) || '默认出勤失败', 'error');
|
showToast((res && (res.message || res.detail)) || '默认出勤失败', 'error');
|
||||||
}
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showToast('默认出勤失败:' + (err && err.message ? err.message : '未知错误'), 'error');
|
||||||
} finally {
|
} finally {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
btn.textContent = '开始补全';
|
btn.textContent = '开始补全';
|
||||||
@@ -373,6 +384,44 @@ async function deleteCalendarDay(day) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== 请假(整天) ==========
|
||||||
|
|
||||||
|
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();
|
||||||
@@ -387,6 +436,7 @@ window.submitAttendance = submitAttendance;
|
|||||||
window.loadAttendanceRecords = loadAttendanceRecords;
|
window.loadAttendanceRecords = loadAttendanceRecords;
|
||||||
window.openDefaultAttendanceModal = openDefaultAttendanceModal;
|
window.openDefaultAttendanceModal = openDefaultAttendanceModal;
|
||||||
window.submitDefaultAttendance = submitDefaultAttendance;
|
window.submitDefaultAttendance = submitDefaultAttendance;
|
||||||
|
window.submitFullDayLeave = submitFullDayLeave;
|
||||||
window.openCalendarModal = openCalendarModal;
|
window.openCalendarModal = openCalendarModal;
|
||||||
window.loadCalendar = loadCalendar;
|
window.loadCalendar = loadCalendar;
|
||||||
window.addCalendarDay = addCalendarDay;
|
window.addCalendarDay = addCalendarDay;
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ 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;
|
||||||
|
|
||||||
@@ -126,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>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -152,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 {
|
||||||
@@ -164,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 {
|
||||||
@@ -179,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) {
|
||||||
@@ -197,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>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -358,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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -370,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');
|
||||||
@@ -380,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);
|
||||||
@@ -396,6 +451,7 @@ window.loadStudentsForSelect = loadStudentsForSelect;
|
|||||||
window.showExportHistoryModal = showExportHistoryModal;
|
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);
|
||||||
@@ -43,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>
|
||||||
@@ -266,9 +269,8 @@ async function submitEditSubject() {
|
|||||||
// ========== 作业按次登记 ==========
|
// ========== 作业按次登记 ==========
|
||||||
|
|
||||||
async function showHomeworkRegisterModal() {
|
async function showHomeworkRegisterModal() {
|
||||||
const checked = Array.from(document.querySelectorAll('.student-checkbox:checked'));
|
if (!studentsData || studentsData.length === 0) {
|
||||||
if (checked.length === 0) {
|
showToast('学生列表尚未加载,请稍后重试', 'warning');
|
||||||
showToast('请先在学生列表中勾选缺交学生', 'warning');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,16 +285,13 @@ async function showHomeworkRegisterModal() {
|
|||||||
}
|
}
|
||||||
subjectSelect.innerHTML = options;
|
subjectSelect.innerHTML = options;
|
||||||
|
|
||||||
// 缺交学生列表(每人可填缺交次数)
|
// 默认列出全部学生,缺交次数默认 0(0 = 已交)
|
||||||
let html = '';
|
let html = '';
|
||||||
checked.forEach(cb => {
|
studentsData.forEach(student => {
|
||||||
const row = cb.closest('tr');
|
|
||||||
const no = row ? row.children[1].textContent.trim() : '';
|
|
||||||
const name = row ? row.children[2].textContent.trim() : '';
|
|
||||||
html += `<div class="hw-reg-item">
|
html += `<div class="hw-reg-item">
|
||||||
<span class="hw-reg-name">${escapeHtml(name)} <small>${escapeHtml(no)}</small></span>
|
<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>
|
<span class="hw-reg-miss-label" style="margin-left:auto;">缺交</span>
|
||||||
<input type="number" class="hw-reg-miss" data-id="${cb.dataset.id}" min="1" value="1" style="width:64px;">
|
<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>
|
<span class="hw-reg-miss-label">次</span>
|
||||||
</div>`;
|
</div>`;
|
||||||
});
|
});
|
||||||
@@ -325,19 +324,16 @@ async function submitHomeworkRegister() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const inputs = Array.from(document.querySelectorAll('.hw-reg-miss'));
|
const inputs = Array.from(document.querySelectorAll('.hw-reg-miss'));
|
||||||
if (inputs.length === 0) {
|
|
||||||
showToast('请先在学生列表中勾选缺交学生', 'warning');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const records = [];
|
const records = [];
|
||||||
for (const input of inputs) {
|
for (const input of inputs) {
|
||||||
const miss = parseInt(input.value);
|
const miss = parseInt(input.value) || 0;
|
||||||
if (!miss || miss < 1 || miss > totalTimes) {
|
if (miss < 0 || miss > totalTimes) {
|
||||||
showToast('缺交次数需在1~总提交次数之间', 'warning');
|
showToast('缺交次数需在0~总提交次数之间', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
records.push({ student_id: parseInt(input.dataset.id), miss_count: miss });
|
if (miss > 0) {
|
||||||
|
records.push({ student_id: parseInt(input.dataset.id), miss_count: miss });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -363,8 +359,10 @@ async function submitHomeworkRegister() {
|
|||||||
if (selectAll) selectAll.checked = false;
|
if (selectAll) selectAll.checked = false;
|
||||||
loadStudents();
|
loadStudents();
|
||||||
} else {
|
} else {
|
||||||
showToast((res && res.message) || '登记失败', 'error');
|
showToast((res && (res.message || res.detail)) || '登记失败', 'error');
|
||||||
}
|
}
|
||||||
|
} catch (err) {
|
||||||
|
showToast('登记失败:' + (err && err.message ? err.message : '未知错误'), 'error');
|
||||||
} finally {
|
} finally {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
btn.textContent = '确认登记';
|
btn.textContent = '确认登记';
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ const OPERATION_TYPES = {
|
|||||||
add_calendar_day: '添加校历设置',
|
add_calendar_day: '添加校历设置',
|
||||||
remove_calendar_day: '删除校历设置',
|
remove_calendar_day: '删除校历设置',
|
||||||
homework_register: '作业按次登记',
|
homework_register: '作业按次登记',
|
||||||
|
batch_revoke: '批量撤销记录',
|
||||||
|
batch_restore: '批量反撤销记录',
|
||||||
add_admin: '添加管理员',
|
add_admin: '添加管理员',
|
||||||
reactivate_admin: '重新激活管理员',
|
reactivate_admin: '重新激活管理员',
|
||||||
update_admin: '编辑管理员',
|
update_admin: '编辑管理员',
|
||||||
@@ -84,6 +86,7 @@ async function loadLogs(page) {
|
|||||||
page_size: 20,
|
page_size: 20,
|
||||||
operation_type: document.getElementById('logTypeFilter').value,
|
operation_type: document.getElementById('logTypeFilter').value,
|
||||||
operator: document.getElementById('logOperatorFilter').value.trim(),
|
operator: document.getElementById('logOperatorFilter').value.trim(),
|
||||||
|
keyword: document.getElementById('logKeywordFilter') ? document.getElementById('logKeywordFilter').value.trim() : '',
|
||||||
start_date: document.getElementById('logStartDate').value,
|
start_date: document.getElementById('logStartDate').value,
|
||||||
end_date: document.getElementById('logEndDate').value
|
end_date: document.getElementById('logEndDate').value
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -95,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');
|
||||||
@@ -108,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');
|
||||||
|
|||||||
@@ -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 = [];
|
||||||
@@ -153,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">
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -81,8 +81,8 @@ $page_title = $page_title ?? '首页';
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
</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
|
||||||
@@ -107,4 +107,72 @@ $page_title = $page_title ?? '首页';
|
|||||||
], JSON_UNESCAPED_UNICODE);
|
], JSON_UNESCAPED_UNICODE);
|
||||||
?>;
|
?>;
|
||||||
</script>
|
</script>
|
||||||
|
<?php endif; ?>
|
||||||
|
<?php if ($user_type === 'admin'): ?>
|
||||||
|
<!-- 密码待修改(初始密码/被重置后):设置新密码(无需原密码) -->
|
||||||
|
<div id="initPasswordModal" class="modal" style="display:none;">
|
||||||
|
<div class="modal-content" style="max-width:420px;">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>请设置新密码</h3>
|
||||||
|
</div>
|
||||||
|
<p style="font-size:13px;color:var(--color-text-muted);margin:0 0 12px;">首次使用或密码被管理员重置后,需要先设置新密码(无需输入原密码)</p>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>新密码</label>
|
||||||
|
<input type="password" id="initNewPassword" autocomplete="new-password">
|
||||||
|
<small>密码要求:<span class="pwd-policy"></span></small>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>确认新密码</label>
|
||||||
|
<input type="password" id="initConfirmPassword" autocomplete="new-password">
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-primary" id="initPasswordBtn" onclick="submitInitPassword()">确认修改</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
// 以服务端标记为准判断是否首次登录(避免本地旧标记误弹)
|
||||||
|
(async function() {
|
||||||
|
var user = (typeof getUserInfo === 'function') ? getUserInfo() : null;
|
||||||
|
var need = user && user.need_change_password;
|
||||||
|
try {
|
||||||
|
var res = await apiGet('/api/auth/me');
|
||||||
|
if (res && res.success && res.data) {
|
||||||
|
need = !!res.data.need_change_password;
|
||||||
|
}
|
||||||
|
} catch (e) { /* 接口异常时退回本地标记 */ }
|
||||||
|
if (!need) return;
|
||||||
|
document.getElementById('initPasswordModal').style.display = 'flex';
|
||||||
|
})();
|
||||||
|
|
||||||
|
window.submitInitPassword = async function() {
|
||||||
|
var p1 = document.getElementById('initNewPassword').value;
|
||||||
|
var p2 = document.getElementById('initConfirmPassword').value;
|
||||||
|
if (!p1) { showToast('请输入新密码', 'warning'); return; }
|
||||||
|
if (p1 !== p2) { showToast('两次输入的密码不一致', 'warning'); return; }
|
||||||
|
var err = (typeof validatePasswordByPolicy === 'function') ? validatePasswordByPolicy(p1) : '';
|
||||||
|
if (err) { showToast(err, 'warning'); return; }
|
||||||
|
|
||||||
|
var btn = document.getElementById('initPasswordBtn');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = '提交中...';
|
||||||
|
try {
|
||||||
|
var res = await apiPost('/api/auth/init-passwd', { new_password: p1 });
|
||||||
|
if (res && res.success) {
|
||||||
|
showToast(res.message || '密码设置成功,请重新登录');
|
||||||
|
setTimeout(function() { logout(); }, 1200);
|
||||||
|
} else {
|
||||||
|
showToast((res && (res.message || res.detail)) || '设置失败', 'error');
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '确认修改';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showToast('设置失败:' + (e && e.message ? e.message : '未知错误'), 'error');
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '确认修改';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
+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">
|
||||||
@@ -62,7 +62,7 @@ $token = isset($_GET['token']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['to
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/js/common.js"></script>
|
<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'); ?>';
|
||||||
|
|||||||
@@ -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'; ?>
|
||||||
@@ -214,12 +214,13 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 修改密码模态框(首次登录强制) -->
|
<!-- 密码待修改提示(初始密码/被重置后) -->
|
||||||
<div id="forceChangePasswordModal" class="modal" style="display: none;">
|
<div id="forceChangePasswordModal" class="modal" style="display: none;">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h3>首次登录,请修改密码</h3>
|
<h3>请设置新密码</h3>
|
||||||
</div>
|
</div>
|
||||||
|
<p style="font-size:13px;color:var(--color-text-muted);margin:0 0 12px;">首次使用或密码被管理员重置后,需要先设置新密码(无需输入原密码)</p>
|
||||||
<form id="forcePasswordForm">
|
<form id="forcePasswordForm">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>新密码</label>
|
<label>新密码</label>
|
||||||
@@ -485,10 +486,8 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await apiPost('/api/auth/change-password', {
|
const res = await apiPost('/api/auth/init-passwd', {
|
||||||
old_password: '',
|
new_password: newPassword
|
||||||
new_password: newPassword,
|
|
||||||
force: true
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res && res.success) {
|
if (res && res.success) {
|
||||||
@@ -499,9 +498,20 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 检查是否需要强制修改密码
|
// 检查是否需要强制修改密码(以服务端标记为准,避免本地旧标记误弹)
|
||||||
function checkForceChangePassword() {
|
async function checkForceChangePassword() {
|
||||||
const user = getUserInfo();
|
let user = getUserInfo();
|
||||||
|
try {
|
||||||
|
const res = await apiGet('/api/auth/me');
|
||||||
|
if (res && res.success && res.data) {
|
||||||
|
const stored = getUserInfo() || {};
|
||||||
|
stored.need_change_password = !!res.data.need_change_password;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(window.USER_STORAGE_KEY || 'class_system_user', JSON.stringify(stored));
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
user = stored;
|
||||||
|
}
|
||||||
|
} catch (e) { /* 接口异常时退回本地标记 */ }
|
||||||
if (user && user.need_change_password) {
|
if (user && user.need_change_password) {
|
||||||
document.getElementById('forceChangePasswordModal').style.display = 'flex';
|
document.getElementById('forceChangePasswordModal').style.display = 'flex';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>window.PAGE_CONFIG = { studentId: <?php echo $student_id; ?> };</script>
|
<script>window.PAGE_CONFIG = { studentId: <?php echo $student_id; ?> };</script>
|
||||||
<script src="/assets/js/student.js"></script>
|
<script src="<?php echo asset_url('/assets/js/student.js'); ?>"></script>
|
||||||
<script src="/assets/js/student-homework.js"></script>
|
<script src="<?php echo asset_url('/assets/js/student-homework.js'); ?>"></script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
@@ -82,6 +82,6 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
</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'; ?>
|
||||||
@@ -201,6 +201,6 @@ async function loadSemesterRecords() {
|
|||||||
|
|
||||||
loadSemesterRecords();
|
loadSemesterRecords();
|
||||||
</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'; ?>
|
||||||
+18
@@ -4,8 +4,26 @@
|
|||||||
*
|
*
|
||||||
* 读取 VERSION 文件确定目标版本,自动检测数据库当前版本,
|
* 读取 VERSION 文件确定目标版本,自动检测数据库当前版本,
|
||||||
* 依次执行增量 SQL 升级脚本。
|
* 依次执行增量 SQL 升级脚本。
|
||||||
|
*
|
||||||
|
* 仅限班主任(拥有系统升级权限 manage_upgrade)使用。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// 登录与权限校验:仅班主任(系统升级权限)可访问与执行
|
||||||
|
require_once __DIR__ . '/frontend/config.php';
|
||||||
|
|
||||||
|
if (!isset($_SESSION['user_id'])
|
||||||
|
|| ($_SESSION['user_type'] ?? '') !== 'admin'
|
||||||
|
|| !has_perm('manage_upgrade')) {
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['action'])) {
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode(['success' => false, 'error' => '未授权:仅班主任(系统升级权限)可执行升级操作']);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
header('Location: /index.php');
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
// ===========================================
|
// ===========================================
|
||||||
// 辅助函数
|
// 辅助函数
|
||||||
// ===========================================
|
// ===========================================
|
||||||
|
|||||||
Reference in new issue
Block a user