v4.5 考勤默认出勤/校历、作业按次登记与权限体系完善
1. 考勤默认出勤:按日期范围给缺失学生批量补"出勤"(跳过周末/法定节假日,调休补班与手动补课日照常,已有记录不覆盖) 2. 节假日/补课校历:法定节假日与调休补班来自在线接口(缓存+失败降级),支持手动添加放假/补课(存 system_settings,优先于接口) 3. 作业按次登记:一次登记覆盖多次作业,配置总提交次数,按每人缺交次数自动扣分(单次缺交扣分x次数),并写入作业提交数据供"数据报表-作业统计"使用 4. 权限体系:新增 homework_register/default_attendance/manage_calendar 权限项;数据报表/操作日志/系统设置拆分为 view_reports/view_logs/manage_settings,共20项功能权限可配置;预置组默认值与 init.sql 同步 5. 权限审计修复:学生端接口管理员越权修复(管理员查看需 view_all_records,学生仅本人);学生列表手机号仅向学生管理/导出名单权限下发;操行分管理页与导航补权限门控 6. v4.5.sql:为预置权限组补充新权限默认值(JSON_SET,幂等可重复执行)
This commit is contained in:
1 parent
4c57ba3a30
commit
4c1ca13a3f
34 files changed
+1438
-48
No files matched your search
@@ -9,12 +9,16 @@
|
||||
# 版权所有 © 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
|
||||
@@ -28,6 +32,12 @@ ATTENDANCE_STATUS_MAP = {
|
||||
"leave": "请假"
|
||||
}
|
||||
|
||||
# 手动校历设置的存储前缀与类型
|
||||
CALENDAR_KEY_PREFIX = 'calendar_day:'
|
||||
CALENDAR_TYPES = ('holiday', 'makeup')
|
||||
VALID_SLOTS = ('morning', 'afternoon', 'evening')
|
||||
MAX_DEFAULT_DAYS = 180
|
||||
|
||||
|
||||
class AttendanceService:
|
||||
"""考勤服务"""
|
||||
@@ -150,4 +160,162 @@ class AttendanceService:
|
||||
student_id=student_id,
|
||||
slot=slot
|
||||
)
|
||||
return {"records": records}
|
||||
return {"records": records}
|
||||
|
||||
# ========== 校历(节假日/补课)==========
|
||||
|
||||
@staticmethod
|
||||
async def get_calendar(start_date: str, end_date: str) -> Dict[str, Any]:
|
||||
"""获取日期范围内的校历:法定节假日、调休补班、手动设置"""
|
||||
start = date.fromisoformat(start_date)
|
||||
end = date.fromisoformat(end_date)
|
||||
|
||||
api_data = await get_range_data(start, end)
|
||||
|
||||
manual_map: Dict[str, Dict[str, str]] = {}
|
||||
manual_rows = await SystemSettingModel.get_by_prefix(CALENDAR_KEY_PREFIX)
|
||||
for key, value in manual_rows.items():
|
||||
day = key[len(CALENDAR_KEY_PREFIX):]
|
||||
if not (start_date <= day <= end_date):
|
||||
continue
|
||||
try:
|
||||
item = json.loads(value)
|
||||
except (ValueError, TypeError):
|
||||
item = {}
|
||||
manual_map[day] = {
|
||||
'type': item.get('type', 'makeup'),
|
||||
'note': item.get('note', '')
|
||||
}
|
||||
|
||||
return {
|
||||
'holidays': api_data['holidays'],
|
||||
'workdays': api_data['workdays'],
|
||||
'manual': manual_map,
|
||||
'api_ok': api_data['api_ok']
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def add_calendar_day(
|
||||
day: str,
|
||||
day_type: str,
|
||||
note: Optional[str],
|
||||
operator_id: int
|
||||
) -> Dict[str, Any]:
|
||||
"""添加手动校历设置(放假/补课)"""
|
||||
try:
|
||||
date.fromisoformat(day)
|
||||
except ValueError:
|
||||
return {"success": False, "message": "日期格式不正确"}
|
||||
if day_type not in CALENDAR_TYPES:
|
||||
return {"success": False, "message": "无效的日期类型"}
|
||||
|
||||
value = json.dumps(
|
||||
{'type': day_type, 'note': (note or '').strip()},
|
||||
ensure_ascii=False
|
||||
)
|
||||
await SystemSettingModel.upsert(CALENDAR_KEY_PREFIX + day, value)
|
||||
logger.info(f"用户[{operator_id}] 添加校历设置 {day} -> {day_type}")
|
||||
return {"success": True, "message": "已保存"}
|
||||
|
||||
@staticmethod
|
||||
async def remove_calendar_day(day: str, operator_id: int) -> Dict[str, Any]:
|
||||
"""删除手动校历设置"""
|
||||
deleted = await SystemSettingModel.delete(CALENDAR_KEY_PREFIX + day)
|
||||
if not deleted:
|
||||
return {"success": False, "message": "该日期没有手动设置"}
|
||||
logger.info(f"用户[{operator_id}] 删除校历设置 {day}")
|
||||
return {"success": True, "message": "已删除"}
|
||||
|
||||
@staticmethod
|
||||
def _is_school_day(day: date, calendar_info: Dict[str, Any]) -> bool:
|
||||
"""判断某天是否为上课日:手动设置优先于接口,接口优先于默认工作日"""
|
||||
iso = day.isoformat()
|
||||
manual = calendar_info['manual'].get(iso)
|
||||
if manual:
|
||||
return manual['type'] == 'makeup'
|
||||
if iso in calendar_info['holidays']:
|
||||
return False
|
||||
if iso in calendar_info['workdays']:
|
||||
return True
|
||||
return day.weekday() < 5
|
||||
|
||||
@staticmethod
|
||||
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_date)
|
||||
|
||||
school_days = []
|
||||
rest_days = 0
|
||||
cursor_day = start
|
||||
while cursor_day <= end:
|
||||
if AttendanceService._is_school_day(cursor_day, calendar_info):
|
||||
school_days.append(cursor_day)
|
||||
else:
|
||||
rest_days += 1
|
||||
cursor_day += timedelta(days=1)
|
||||
|
||||
if not school_days:
|
||||
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 = []
|
||||
for school_day in school_days:
|
||||
day_iso = school_day.isoformat()
|
||||
for student_id in student_ids:
|
||||
for slot in selected_slots:
|
||||
if (student_id, day_iso, slot) not in existing_set:
|
||||
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)
|
||||
skipped_existing = total_combos - len(rows)
|
||||
|
||||
logger.info(
|
||||
f"用户[{recorder_id}] 批量默认出勤 {start_date}~{end_date} 时段{','.join(selected_slots)}: "
|
||||
f"上课日{len(school_days)}天,新增{created}条,跳过已有{skipped_existing}条"
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"默认出勤完成:{len(school_days)}个上课日,新增{created}条,跳过已有{skipped_existing}条",
|
||||
"data": {
|
||||
"days": len(school_days),
|
||||
"rest_days": rest_days,
|
||||
"created": created,
|
||||
"skipped_existing": skipped_existing,
|
||||
"api_ok": calendar_info['api_ok']
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
"""节假日服务:在线获取法定节假日与调休补班数据(带缓存与失败降级)"""
|
||||
|
||||
import json
|
||||
import time
|
||||
import asyncio
|
||||
import urllib.request
|
||||
from datetime import date
|
||||
from typing import Dict, Any
|
||||
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
HOLIDAY_API = 'https://timor.tech/api/holiday/year/{year}'
|
||||
CACHE_TTL = 12 * 3600
|
||||
FAIL_CACHE_TTL = 600
|
||||
REQUEST_TIMEOUT = 6
|
||||
|
||||
_cache: Dict[int, Dict[str, Any]] = {}
|
||||
|
||||
|
||||
def _fetch_year_sync(year: int) -> Dict[str, Any]:
|
||||
"""同步请求节假日接口(在线程池中调用)"""
|
||||
request = urllib.request.Request(
|
||||
HOLIDAY_API.format(year=year),
|
||||
headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'}
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
||||
payload = json.loads(response.read().decode('utf-8'))
|
||||
|
||||
if payload.get('code') != 0:
|
||||
raise ValueError(f"接口返回错误码: {payload.get('code')}")
|
||||
|
||||
holidays: Dict[str, str] = {}
|
||||
workdays: Dict[str, str] = {}
|
||||
for day, info in (payload.get('holiday') or {}).items():
|
||||
d = str(info.get('date') or f'{year}-{day}')[:10]
|
||||
if info.get('holiday'):
|
||||
holidays[d] = info.get('name') or '节假日'
|
||||
else:
|
||||
workdays[d] = info.get('name') or '调休补班'
|
||||
|
||||
return {'holidays': holidays, 'workdays': workdays, 'api_ok': True}
|
||||
|
||||
|
||||
async def get_year_data(year: int) -> Dict[str, Any]:
|
||||
"""获取某年的节假日/调休数据(内存缓存,接口失败自动降级)"""
|
||||
now = time.time()
|
||||
cached = _cache.get(year)
|
||||
if cached:
|
||||
ttl = CACHE_TTL if cached.get('api_ok') else FAIL_CACHE_TTL
|
||||
if now - cached['fetched_at'] < ttl:
|
||||
return cached
|
||||
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
data = await loop.run_in_executor(None, _fetch_year_sync, year)
|
||||
data['fetched_at'] = now
|
||||
_cache[year] = data
|
||||
logger.info(
|
||||
f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天"
|
||||
)
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.warning(f"节假日接口获取失败({year}): {e}")
|
||||
failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now}
|
||||
_cache[year] = failed
|
||||
return failed
|
||||
|
||||
|
||||
async def get_range_data(start: date, end: date) -> Dict[str, Any]:
|
||||
"""获取日期范围内的节假日/调休数据"""
|
||||
holidays: Dict[str, str] = {}
|
||||
workdays: Dict[str, str] = {}
|
||||
api_ok = True
|
||||
|
||||
for year in range(start.year, end.year + 1):
|
||||
data = await get_year_data(year)
|
||||
holidays.update(data['holidays'])
|
||||
workdays.update(data['workdays'])
|
||||
api_ok = api_ok and data['api_ok']
|
||||
|
||||
start_iso = start.isoformat()
|
||||
end_iso = end.isoformat()
|
||||
return {
|
||||
'holidays': {d: n for d, n in holidays.items() if start_iso <= d <= end_iso},
|
||||
'workdays': {d: n for d, n in workdays.items() if start_iso <= d <= end_iso},
|
||||
'api_ok': api_ok
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
"""作业服务:按次登记(一次登记覆盖多次作业,按缺交次数扣分并写入提交统计)"""
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
from models.homework import HomeworkModel
|
||||
from models.student import StudentModel
|
||||
from models.subject import SubjectModel
|
||||
from models.conduct import ConductModel
|
||||
from models.semester import SemesterModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
MAX_TOTAL_TIMES = 99
|
||||
|
||||
|
||||
class HomeworkService:
|
||||
"""作业服务"""
|
||||
|
||||
@staticmethod
|
||||
async def register_batch(
|
||||
records: List[Dict[str, int]],
|
||||
deadline: str,
|
||||
total_times: int,
|
||||
per_deduction: Optional[int],
|
||||
title: Optional[str],
|
||||
subject_id: int,
|
||||
note: Optional[str],
|
||||
operator_id: int,
|
||||
operator_name: str
|
||||
) -> Dict[str, Any]:
|
||||
"""按次登记作业
|
||||
|
||||
一次登记覆盖 total_times 次作业:缺交学生前 miss_count 次记为未交,
|
||||
其余学生全部记为已交;按 缺交次数 × 单次扣分 生成扣分记录。
|
||||
"""
|
||||
if total_times < 1 or total_times > MAX_TOTAL_TIMES:
|
||||
return {"success": False, "message": f"总提交次数需在1-{MAX_TOTAL_TIMES}之间"}
|
||||
|
||||
# 学生去重与缺交次数校验
|
||||
miss_map: Dict[int, int] = {}
|
||||
for item in records:
|
||||
sid = item.get("student_id")
|
||||
miss = item.get("miss_count")
|
||||
if not sid or not isinstance(miss, int) or miss < 1 or miss > total_times:
|
||||
return {"success": False, "message": "缺交次数不合法(需在1~总提交次数之间)"}
|
||||
if sid in miss_map:
|
||||
return {"success": False, "message": "同一学生请勿重复提交"}
|
||||
miss_map[sid] = miss
|
||||
|
||||
# 科目校验(作业记录必须归属科目)
|
||||
subject = await SubjectModel.get_by_id(subject_id)
|
||||
if not subject:
|
||||
return {"success": False, "message": "科目不存在"}
|
||||
subject_name = subject["subject_name"]
|
||||
|
||||
# 权限与扣分上限校验
|
||||
limits = await PermissionChecker.get_score_limits(operator_id)
|
||||
if not limits["can_manage_conduct"]:
|
||||
return {"success": False, "message": "无权进行扣分操作"}
|
||||
if not limits["can_subtract"]:
|
||||
return {"success": False, "message": "当前权限组不允许扣分"}
|
||||
|
||||
deduction = per_deduction or settings.DEDUCTION_HOMEWORK_NOT_SUBMIT
|
||||
if deduction < 1 or deduction > 20:
|
||||
return {"success": False, "message": "单次缺交扣分需在1-20之间"}
|
||||
|
||||
students = await StudentModel.get_all()
|
||||
student_map = {s["student_id"]: s for s in students}
|
||||
for sid in miss_map:
|
||||
if sid not in student_map:
|
||||
return {"success": False, "message": "存在无效学生(不存在或已禁用)"}
|
||||
|
||||
if limits["max_subtract"] is not None:
|
||||
for sid, miss in miss_map.items():
|
||||
total_deduct = miss * deduction
|
||||
if total_deduct > limits["max_subtract"]:
|
||||
name = student_map[sid]["name"]
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"{name} 缺交{miss}次合计扣{total_deduct}分,超过单次扣分上限{limits['max_subtract']}分"
|
||||
}
|
||||
|
||||
# 创建作业记录(每次一条)
|
||||
base_title = (title or "作业登记").strip() or "作业登记"
|
||||
if total_times == 1:
|
||||
titles = [base_title]
|
||||
else:
|
||||
titles = [f"{base_title} #{i}" for i in range(1, total_times + 1)]
|
||||
assignment_ids = await HomeworkModel.create_assignments(
|
||||
subject_id=subject_id,
|
||||
titles=titles,
|
||||
deadline=deadline,
|
||||
created_by=operator_id
|
||||
)
|
||||
|
||||
# 写入提交数据:缺交学生前 k 次记为未交,其他学生全部记为已交
|
||||
rows = []
|
||||
for student in students:
|
||||
sid = student["student_id"]
|
||||
miss = miss_map.get(sid, 0)
|
||||
for index, assignment_id in enumerate(assignment_ids):
|
||||
status = "not_submitted" if index < miss else "submitted"
|
||||
rows.append((assignment_id, sid, status, operator_id))
|
||||
submission_count = await HomeworkModel.bulk_create_submissions(rows)
|
||||
|
||||
# 生成扣分记录并更新总分
|
||||
active_semester = await SemesterModel.get_active()
|
||||
semester_id = active_semester["semester_id"] if active_semester else None
|
||||
|
||||
total_deduction = 0
|
||||
deducted_students = 0
|
||||
for sid, miss in miss_map.items():
|
||||
points_change = -(miss * deduction)
|
||||
reason = f"[{subject_name}]{base_title} 缺交 {miss}/{total_times} 次"
|
||||
if note and note.strip():
|
||||
reason += f"({note.strip()})"
|
||||
reason = reason[:255]
|
||||
|
||||
await ConductModel.create_record(
|
||||
student_id=sid,
|
||||
points_change=points_change,
|
||||
reason=reason,
|
||||
recorder_id=operator_id,
|
||||
recorder_name=operator_name,
|
||||
related_type="homework",
|
||||
semester_id=semester_id
|
||||
)
|
||||
await StudentModel.update_total_points(sid, points_change)
|
||||
await HomeworkModel.mark_not_submitted_deducted(assignment_ids, sid)
|
||||
|
||||
total_deduction += -points_change
|
||||
deducted_students += 1
|
||||
|
||||
logger.info(
|
||||
f"用户[{operator_id}] 按次登记作业[{base_title}] 共{total_times}次,"
|
||||
f"缺交{deducted_students}人,合计扣{total_deduction}分"
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"登记完成:共{total_times}次作业,缺交{deducted_students}人,合计扣{total_deduction}分",
|
||||
"data": {
|
||||
"assignments": len(assignment_ids),
|
||||
"submissions": submission_count,
|
||||
"deducted_students": deducted_students,
|
||||
"total_deduction": total_deduction
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user