Files
ClassManager/backend/services/attendance_service.py
T
canglan 0ac933a3a5 考勤记录显示记录人,默认出勤写入原因;撤销"节前上课"特殊类型
1. 考勤记录查询关联 users 表返回记录人姓名(修复记录人为空)
2. 默认出勤生成的记录原因写为"默认出勤";整天请假未填原因时默认"请假(整天)"
3. "假前下午上课"属于偶发情况,默认不做:移除 pre_holiday 校历类型,需要时按正常考勤流程单独补录下午记录
4. 已确认:默认出勤记录可被异常考勤覆盖(覆盖时按异常状态正常扣分)
2026-11-26 09:53:51 +08:00

436 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ===========================================
# 班级操行分管理系统 - 后端服务
#
# 开发者: Canglan
# 联系方式: admin@sea-studio.top
# 版权归属: Sea Network Technology Studio
# 许可证: MIT License
#
# 版权所有 © Sea Network Technology Studio
# ===========================================
import json
from datetime import date, timedelta
from typing import Dict, Any, Optional
from models.attendance import AttendanceModel
from models.student import StudentModel
from models.conduct import ConductModel
from models.user import UserModel
from models.system_setting import SystemSettingModel
from services.holiday_service import get_range_data
from middleware.permission import PermissionChecker
from config import settings
from utils.logger import get_logger
logger = get_logger(__name__)
# 考勤状态中文映射
ATTENDANCE_STATUS_MAP = {
"absent": "缺勤",
"late": "迟到",
"leave": "请假"
}
# 手动校历设置的存储前缀与类型
CALENDAR_KEY_PREFIX = 'calendar_day:'
CALENDAR_TYPES = ('holiday', 'makeup')
VALID_SLOTS = ('morning', 'afternoon', 'evening')
MAX_DEFAULT_DAYS = 180
class AttendanceService:
"""考勤服务"""
@staticmethod
async def add_attendance(
student_id: int,
date: str,
status: str,
reason: Optional[str],
apply_deduction: bool,
recorder_id: int,
custom_deduction: Optional[int] = None,
slot: str = 'morning'
) -> Dict[str, Any]:
"""添加考勤记录"""
# 校验时段
if slot not in ('morning', 'afternoon', 'evening'):
return {"success": False, "message": "无效的考勤时段"}
# 校验状态
if status not in ('present', 'absent', 'late', 'leave'):
return {"success": False, "message": "无效的考勤状态"}
# 校验自定义扣分范围
if custom_deduction is not None and (custom_deduction < 1 or custom_deduction > 20):
return {"success": False, "message": "自定义扣分必须在1-20之间"}
# 检查权限
if not await PermissionChecker.check_permission(recorder_id, "manage_attendance"):
return {"success": False, "message": "无考勤管理权限"}
limits = await PermissionChecker.get_score_limits(recorder_id)
# 扣分权限与动态上限校验
if apply_deduction and status in ["absent", "late", "leave"]:
if not limits["can_subtract"]:
return {"success": False, "message": "当前权限组不允许扣分"}
if limits["max_subtract"] is not None:
if custom_deduction is not None and custom_deduction > limits["max_subtract"]:
return {"success": False, "message": f"单次扣分上限为{limits['max_subtract']}分"}
default_deduction = {
"absent": settings.DEDUCTION_ATTENDANCE_ABSENT,
"late": settings.DEDUCTION_ATTENDANCE_LATE,
"leave": settings.DEDUCTION_ATTENDANCE_LEAVE
}.get(status, 0)
if default_deduction > limits["max_subtract"]:
return {"success": False, "message": f"单次扣分上限为{limits['max_subtract']}分"}
# 获取当前活跃学期,用于记录归属
from models.semester import SemesterModel
active_semester = await SemesterModel.get_active()
semester_id = active_semester['semester_id'] if active_semester else None
# 添加考勤记录
attendance_id = await AttendanceModel.create_record(
student_id=student_id,
date=date,
status=status,
reason=reason,
recorder_id=recorder_id,
slot=slot,
semester_id=semester_id
)
if not attendance_id:
return {"success": False, "message": "添加考勤记录失败"}
# 应用扣分
if apply_deduction and status in ["absent", "late", "leave"]:
# 确定扣分数值(优先使用自定义扣分)
if custom_deduction is not None:
points_change = -custom_deduction
elif status == "absent":
points_change = -settings.DEDUCTION_ATTENDANCE_ABSENT
elif status == "late":
points_change = -settings.DEDUCTION_ATTENDANCE_LATE
else:
points_change = -settings.DEDUCTION_ATTENDANCE_LEAVE
# 扣分为0时跳过(如请假不扣分)
if points_change == 0:
logger.info(f"用户[{recorder_id}] 添加考勤记录[{attendance_id}] -> {status} (不扣分)")
return {"success": True, "message": "考勤记录添加成功(不扣分)"}
student = await StudentModel.get_by_id(student_id)
if student:
# 获取操作人姓名
user = await UserModel.get_by_user_id(recorder_id)
recorder_name = user.get("real_name", "班主任") if user else "班主任"
# 使用中文状态
status_text = ATTENDANCE_STATUS_MAP.get(status, status)
await ConductModel.create_record(
student_id=student_id,
points_change=points_change,
reason=f"考勤:{status_text}",
recorder_id=recorder_id,
recorder_name=recorder_name,
related_type="attendance",
related_id=attendance_id,
semester_id=semester_id
)
# 更新学生总分
await StudentModel.update_total_points(student_id, points_change)
# 标记已应用扣分
await AttendanceModel.mark_deduction_applied(attendance_id)
logger.info(f"用户[{recorder_id}] 添加考勤记录[{attendance_id}] -> {status}")
return {"success": True, "message": "考勤记录添加成功"}
@staticmethod
async def get_records(
user_id: int,
date: Optional[str] = None,
student_id: Optional[int] = None,
slot: Optional[str] = None
) -> Dict[str, Any]:
"""获取考勤记录"""
records = await AttendanceModel.get_class_records(
date=date,
student_id=student_id,
slot=slot
)
return {"records": records}
# ========== 校历(节假日/补课)==========
@staticmethod
async def get_calendar(start_date: str, end_date: str) -> Dict[str, Any]:
"""获取日期范围内的校历:法定节假日、调休补班、手动设置"""
start = date.fromisoformat(start_date)
end = date.fromisoformat(end_date)
api_data = await get_range_data(start, end)
manual_map: Dict[str, Dict[str, str]] = {}
manual_rows = await SystemSettingModel.get_by_prefix(CALENDAR_KEY_PREFIX)
for key, value in manual_rows.items():
day = key[len(CALENDAR_KEY_PREFIX):]
if not (start_date <= day <= end_date):
continue
try:
item = json.loads(value)
except (ValueError, TypeError):
item = {}
manual_map[day] = {
'type': item.get('type', 'makeup'),
'note': item.get('note', '')
}
return {
'holidays': api_data['holidays'],
'workdays': api_data['workdays'],
'manual': manual_map,
'api_ok': api_data['api_ok']
}
@staticmethod
async def add_calendar_day(
day: str,
day_type: str,
note: Optional[str],
operator_id: int
) -> Dict[str, Any]:
"""添加手动校历设置(放假/补课)"""
try:
date.fromisoformat(day)
except ValueError:
return {"success": False, "message": "日期格式不正确"}
if day_type not in CALENDAR_TYPES:
return {"success": False, "message": "无效的日期类型"}
value = json.dumps(
{'type': day_type, 'note': (note or '').strip()},
ensure_ascii=False
)
await SystemSettingModel.upsert(CALENDAR_KEY_PREFIX + day, value)
logger.info(f"用户[{operator_id}] 添加校历设置 {day} -> {day_type}")
return {"success": True, "message": "已保存"}
@staticmethod
async def remove_calendar_day(day: str, operator_id: int) -> Dict[str, Any]:
"""删除手动校历设置"""
deleted = await SystemSettingModel.delete(CALENDAR_KEY_PREFIX + day)
if not deleted:
return {"success": False, "message": "该日期没有手动设置"}
logger.info(f"用户[{operator_id}] 删除校历设置 {day}")
return {"success": True, "message": "已删除"}
@staticmethod
def _is_school_day(day: date, calendar_info: Dict[str, Any]) -> bool:
"""判断某天是否为上课日:手动设置优先于接口,接口优先于默认工作日"""
iso = day.isoformat()
manual = calendar_info['manual'].get(iso)
if manual:
return manual['type'] == 'makeup'
if iso in calendar_info['holidays']:
return False
if iso in calendar_info['workdays']:
return True
return day.weekday() < 5
@staticmethod
def _slots_for_date(
day: date,
calendar_info: Dict[str, Any],
selected_slots: Optional[list] = None
) -> list:
"""按学校常规作息返回某天实际考勤时段
- 上课日且次日仍上课:所选时段(早/中/晚)
- 放假前一天(次日不上课):仅上午
- 返校日(非上课日、次日上课):仅晚修
- 其他休息日:无
"""
selected = [s for s in (selected_slots or VALID_SLOTS) if s in VALID_SLOTS]
next_day = day + timedelta(days=1)
school_today = AttendanceService._is_school_day(day, calendar_info)
school_next = AttendanceService._is_school_day(next_day, calendar_info)
if school_today:
if school_next:
return list(selected)
return [s for s in selected if s == 'morning']
if school_next:
return [s for s in selected if s == 'evening']
return []
@staticmethod
async def full_day_leave(
date_str: str,
student_ids: list,
reason: Optional[str],
recorder_id: int
) -> Dict[str, Any]:
"""全天请假:按当天实际考勤时段为选中学生提交请假(每个时段按请假配置扣分)"""
try:
day = date.fromisoformat(date_str)
except ValueError:
return {"success": False, "message": "日期格式不正确"}
if not student_ids:
return {"success": False, "message": "请选择请假的学生"}
if len(student_ids) > 200:
return {"success": False, "message": "单次最多选择200名学生"}
calendar_info = await AttendanceService.get_calendar(
date_str, (day + timedelta(days=1)).isoformat()
)
slots = AttendanceService._slots_for_date(day, calendar_info)
if not slots:
return {"success": False, "message": "该日期没有考勤时段(休息日)"}
effective_reason = (reason or '').strip() or '请假(整天)'
created_count = 0
last_error = None
for student_id in student_ids:
for slot in slots:
result = await AttendanceService.add_attendance(
student_id=student_id,
date=date_str,
status='leave',
reason=effective_reason,
apply_deduction=True,
recorder_id=recorder_id,
custom_deduction=None,
slot=slot
)
if result.get("success"):
created_count += 1
else:
last_error = result.get("message", "未知错误")
if created_count == 0:
return {"success": False, "message": last_error or "提交失败"}
per_student = len(slots) * settings.DEDUCTION_ATTENDANCE_LEAVE
points_text = f",每人{per_student}分" if per_student > 0 else ""
logger.info(
f"用户[{recorder_id}] 全天请假 {date_str}: {len(student_ids)}人 × {len(slots)}时段"
f"({','.join(slots)}), 共{created_count}条"
)
return {
"success": True,
"message": f"整天请假提交成功:{len(student_ids)}人 × {len(slots)}个时段,共{created_count}条{points_text}",
"data": {
"slots": slots,
"created": created_count,
"students": len(student_ids),
"deduction_per_student": per_student
}
}
@staticmethod
async def batch_default_attendance(
start_date: str,
end_date: str,
slots: Optional[list],
recorder_id: int
) -> Dict[str, Any]:
"""批量默认出勤:给日期范围内所有上课日缺失的学生补出勤记录
跳过周末与节假日(接口+手动),调休补班与手动补课日照常;已有记录不覆盖。
"""
try:
start = date.fromisoformat(start_date)
end = date.fromisoformat(end_date)
except ValueError:
return {"success": False, "message": "日期格式不正确"}
if start > end:
return {"success": False, "message": "开始日期不能晚于结束日期"}
if (end - start).days > MAX_DEFAULT_DAYS:
return {"success": False, "message": f"日期范围过长(最长{MAX_DEFAULT_DAYS}天)"}
selected_slots = [s for s in (slots or VALID_SLOTS) if s in VALID_SLOTS]
if not selected_slots:
return {"success": False, "message": "请至少选择一个时段"}
students = await StudentModel.get_all()
if not students:
return {"success": False, "message": "暂无在读学生"}
# 校历多取一天,用于判断"次日是否上课"(决定节前半日/返校晚修)
calendar_info = await AttendanceService.get_calendar(
start_date, (end + timedelta(days=1)).isoformat()
)
# 常规作息:
# 返校日(非上课日、次日上课)→ 仅晚修
# 上课日且次日仍上课 → 按所选时段(早/中/晚)
# 上课日且次日不上课(放假前一天)→ 仅上午(中午走人,无下午/晚修)
day_slots = []
full_days = 0
half_days = 0
return_evenings = 0
rest_days = 0
cursor_day = start
while cursor_day <= end:
slots_today = AttendanceService._slots_for_date(cursor_day, calendar_info, selected_slots)
if slots_today:
school_today = AttendanceService._is_school_day(cursor_day, calendar_info)
school_next = AttendanceService._is_school_day(cursor_day + timedelta(days=1), calendar_info)
if school_today and school_next:
full_days += 1
elif school_today:
half_days += 1
elif school_next:
return_evenings += 1
day_slots.append((cursor_day, slots_today))
else:
rest_days += 1
cursor_day += timedelta(days=1)
if not day_slots:
return {"success": False, "message": "所选范围内没有需要默认出勤的时段(均为休息日或未选对应时段)"}
from models.semester import SemesterModel
active_semester = await SemesterModel.get_active()
semester_id = active_semester['semester_id'] if active_semester else None
student_ids = [s['student_id'] for s in students]
existing = await AttendanceModel.get_existing_keys(start_date, end_date, selected_slots)
existing_set = {(r['student_id'], r['date'], r['slot']) for r in existing}
rows = []
total_combos = 0
for day, slots_today in day_slots:
day_iso = day.isoformat()
for student_id in student_ids:
total_combos += len(slots_today)
for slot in slots_today:
if (student_id, day_iso, slot) not in existing_set:
rows.append((student_id, day_iso, slot, recorder_id, semester_id))
created = await AttendanceModel.bulk_create_present(rows)
skipped_existing = total_combos - len(rows)
summary = (
f"上课日{full_days + half_days}天(其中节前半日{half_days}天)、"
f"返校晚修{return_evenings}天,新增{created}条,跳过已有{skipped_existing}条"
)
logger.info(
f"用户[{recorder_id}] 批量默认出勤 {start_date}~{end_date} 时段{','.join(selected_slots)}: {summary}"
)
return {
"success": True,
"message": f"默认出勤完成:{summary}",
"data": {
"days": full_days + half_days,
"half_days": half_days,
"return_evenings": return_evenings,
"rest_days": rest_days,
"created": created,
"skipped_existing": skipped_existing,
"api_ok": calendar_info['api_ok']
}
}