# =========================================== # 班级操行分管理系统 - 后端服务 # # 开发者: 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 and deduction > limits["max_subtract"]: return { "success": False, "message": f"单次缺交扣分不能超过{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 } }