Files
ClassManager/backend/models/attendance.py
T
canglan a7304d151e 考勤记录扣分列显示实际扣分数
1. 新增/更新考勤扣分时记录关联的扣分记录ID(deduction_record_id)
2. 考勤记录查询关联扣分记录,返回扣分数与撤销状态;旧记录按考勤记录ID回查兜底
3. 前端扣分列显示"扣X分 / 扣X分(已撤销)",无扣分显示"-"
2026-11-26 09:56:21 +08:00

177 lines
6.4 KiB
Python

# ===========================================
# 班级操行分管理系统 - 后端服务
#
# 开发者: Canglan
# 联系方式: admin@sea-studio.top
# 版权归属: Sea Network Technology Studio
# 许可证: MIT License
#
# 版权所有 © Sea Network Technology Studio
# ===========================================
from typing import Dict, Any, List
from utils.database import execute_one, execute_query, execute_insert, execute_update
class AttendanceModel:
"""考勤数据模型"""
@staticmethod
async def get_student_records(student_id: int, month: str = None) -> List[Dict[str, Any]]:
sql = """
SELECT attendance_id, date, slot, status, reason, deduction_applied, created_at
FROM attendance_records
WHERE student_id = %s
"""
params = [student_id]
if month:
sql += " AND DATE_FORMAT(date, '%%Y-%%m') = %s"
params.append(month)
sql += " ORDER BY date DESC"
return await execute_query(sql, tuple(params))
@staticmethod
async def get_class_records(
date: str = None,
student_id: int = None,
slot: str = None
) -> List[Dict[str, Any]]:
sql = """
SELECT ar.*, s.name as student_name, s.student_no,
u.real_name as recorder_name,
COALESCE(cr.points_change, (
SELECT cr2.points_change FROM conduct_records cr2
WHERE cr2.related_type = 'attendance' AND cr2.related_id = ar.attendance_id
ORDER BY cr2.record_id DESC LIMIT 1
)) as deduction_points,
COALESCE(cr.is_revoked, (
SELECT cr3.is_revoked FROM conduct_records cr3
WHERE cr3.related_type = 'attendance' AND cr3.related_id = ar.attendance_id
ORDER BY cr3.record_id DESC LIMIT 1
)) as deduction_revoked
FROM attendance_records ar
JOIN students s ON ar.student_id = s.student_id
LEFT JOIN users u ON ar.recorder_id = u.user_id
LEFT JOIN conduct_records cr ON ar.deduction_record_id = cr.record_id
WHERE 1=1
"""
params = []
if date:
sql += " AND ar.date = %s"
params.append(date)
if student_id:
sql += " AND ar.student_id = %s"
params.append(student_id)
if slot:
sql += " AND ar.slot = %s"
params.append(slot)
sql += " ORDER BY ar.date DESC, s.student_no"
return await execute_query(sql, tuple(params))
@staticmethod
async def create_record(
student_id: int,
date: str,
status: str,
reason: str = None,
recorder_id: int = None,
slot: str = 'morning',
semester_id: int = None
) -> int:
# 检查是否已存在当天同时段记录
existing = await execute_one(
"SELECT attendance_id FROM attendance_records WHERE student_id = %s AND date = %s AND slot = %s",
(student_id, date, slot)
)
if existing:
# 更新已有记录
sql = """
UPDATE attendance_records
SET status = %s, reason = %s, recorder_id = %s, semester_id = %s
WHERE student_id = %s AND date = %s AND slot = %s
"""
await execute_update(sql, (status, reason, recorder_id, semester_id, student_id, date, slot))
return existing["attendance_id"]
else:
# 插入新记录
sql = """
INSERT INTO attendance_records (student_id, date, slot, status, reason, recorder_id, semester_id)
VALUES (%s, %s, %s, %s, %s, %s, %s)
"""
return await execute_insert(sql, (student_id, date, slot, status, reason, recorder_id, semester_id))
@staticmethod
async def mark_deduction_applied(attendance_id: int, deduction_record_id: int = None) -> bool:
"""标记考勤已扣分,并记录关联的扣分记录ID"""
if deduction_record_id:
sql = (
"UPDATE attendance_records "
"SET deduction_applied = 1, deduction_record_id = %s "
"WHERE attendance_id = %s"
)
result = await execute_update(sql, (deduction_record_id, attendance_id))
else:
sql = "UPDATE attendance_records SET deduction_applied = 1 WHERE attendance_id = %s"
result = await execute_update(sql, (attendance_id,))
return result > 0
@staticmethod
async def get_existing_keys(
start_date: str,
end_date: str,
slots: List[str]
) -> List[Dict[str, Any]]:
"""查询日期范围内已存在的考勤记录(学生+日期+时段)"""
placeholders = ", ".join(["%s"] * len(slots))
sql = f"""
SELECT student_id, date, slot
FROM attendance_records
WHERE date BETWEEN %s AND %s AND slot IN ({placeholders})
"""
rows = await execute_query(sql, (start_date, end_date, *slots))
result = []
for row in rows:
d = row['date']
result.append({
'student_id': row['student_id'],
'date': d.isoformat() if hasattr(d, 'isoformat') else str(d),
'slot': row['slot']
})
return result
@staticmethod
async def bulk_create_present(rows: List[tuple]) -> int:
"""批量插入出勤记录
rows: (student_id, date, slot, recorder_id, semester_id) 列表
"""
if not rows:
return 0
created = 0
chunk_size = 200
for i in range(0, len(rows), chunk_size):
chunk = rows[i:i + chunk_size]
values = ", ".join(["(%s, %s, 'present', '默认出勤', %s, %s, %s, 0)"] * len(chunk))
params = []
for student_id, day, slot, recorder_id, semester_id in chunk:
params.extend([student_id, day, slot, recorder_id, semester_id])
sql = f"""
INSERT INTO attendance_records
(student_id, date, status, reason, slot, recorder_id, semester_id, deduction_applied)
VALUES {values}
"""
created += await execute_update(sql, tuple(params))
return created