Files
ClassManager/backend/services/attendance_service.py
T
canglan d9dd7bf7e8 默认出勤按学校作息生成;新增"请假(整天)"按钮
1. 默认出勤:返校日仅生成晚修、放假前一天仅生成上午(中午离校,无下午/晚修)、其余上课日按所选时段;校历多取一天用于判断次日是否上课
2. 考勤页新增"请假(整天)":选中学生一键提交早/中/晚三条请假记录(各按请假扣分,配置1分时共3分/天)
3. 文档更新:请假(整天)用法与默认出勤作息规则
2026-11-26 09:39:57 +08:00

356 lines
14 KiB
Python

# ===========================================
# 班级操行分管理系统 - 后端服务
#
# 开发者: 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
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:
next_day = cursor_day + timedelta(days=1)
school_today = AttendanceService._is_school_day(cursor_day, calendar_info)
school_next = AttendanceService._is_school_day(next_day, calendar_info)
if school_today:
if school_next:
slots_today = list(selected_slots)
full_days += 1
else:
slots_today = [s for s in selected_slots if s == 'morning']
if slots_today:
half_days += 1
else:
rest_days += 1
if slots_today:
day_slots.append((cursor_day, slots_today))
else:
slots_today = [s for s in selected_slots if s == 'evening'] if school_next else []
if slots_today:
return_evenings += 1
day_slots.append((cursor_day, slots_today))
else:
rest_days += 1
cursor_day = next_day
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']
}
}