package com.xh.xunke.school; import com.xh.xunke.common.BizException; import com.xh.xunke.common.ErrorCode; import com.xh.xunke.course.Period; import com.xh.xunke.course.PeriodRepository; import com.xh.xunke.common.PagePayload; import com.xh.xunke.common.Pages; import com.xh.xunke.security.AccessGuard; import com.xh.xunke.security.UserPrincipal; import com.xh.xunke.user.RoleName; import com.xh.xunke.user.UserAccount; import com.xh.xunke.user.UserRepository; import com.xh.xunke.user.UserRoleRepository; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalTime; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Service public class SchoolService { private final SchoolRepository schools; private final GradeRepository grades; private final ClassRoomRepository classes; private final ClassTeacherRepository classTeachers; private final StudentRepository students; private final UserRepository users; private final UserRoleRepository roles; private final AccessGuard guard; private final PeriodRepository periods; public SchoolService(SchoolRepository schools, GradeRepository grades, ClassRoomRepository classes, ClassTeacherRepository classTeachers, StudentRepository students, UserRepository users, UserRoleRepository roles, AccessGuard guard, PeriodRepository periods) { this.schools = schools; this.grades = grades; this.classes = classes; this.classTeachers = classTeachers; this.students = students; this.users = users; this.roles = roles; this.guard = guard; this.periods = periods; } public record SchoolRequest(@NotBlank String name, @NotBlank String code, String logoUrl, String address, String contactName, String contactPhone, Boolean liveEnabled, Boolean recordEnabled, Boolean teacherPublic, Integer retentionDays) { } public record GradeRequest(@NotNull Long schoolId, @NotBlank String name, Integer sortOrder) { } public record ClassRequest(@NotNull Long schoolId, @NotNull Long gradeId, @NotBlank String name, Long headTeacherId) { } public record TeacherAssign(@NotNull Long teacherId, String subject, boolean head) { } public record StudentRequest(@NotNull Long classId, @NotBlank String name, @NotBlank String studentNo) { } public String className(Long classId) { return classes.findById(classId).map(ClassRoom::getName).orElse("班级 " + classId); } public String schoolName(Long schoolId) { return schools.findById(schoolId).map(School::getName).orElse(""); } public String studentName(Long classId, Long studentId) { return students.findByClassId(classId).stream() .filter(student -> student.getId().equals(studentId)) .map(Student::getName) .findFirst() .orElse(""); } /** 教师任教的班级 ID(用于直播/录像列表按教师范围过滤)。 */ public List teacherClassIds(Long teacherId) { return classTeachers.findByTeacherId(teacherId).stream() .map(ClassTeacher::getClassId) .distinct() .toList(); } public PagePayload listSchools(UserPrincipal me, String q, int page, int size) { if (!me.superAdmin()) { if (me.schoolId() == null) { return new PagePayload<>(List.of(), 0, 0, size); } School school = schools.findById(me.schoolId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在")); return new PagePayload<>(List.of(school), 1, 0, 1); } var result = schools.findByNameContainingIgnoreCase(q == null ? "" : q, Pages.of(page, size)); return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize()); } @Transactional public School createSchool(UserPrincipal me, SchoolRequest request) { if (!me.superAdmin()) { throw new BizException(ErrorCode.FORBIDDEN, "只有超级管理员可以创建学校"); } if (schools.existsByCode(request.code())) { throw new BizException(ErrorCode.CONFLICT, "学校编码已存在"); } School school = new School(); apply(school, request); schools.save(school); String[][] defaults = { {"第1节", "08:00", "08:40"}, {"第2节", "08:50", "09:30"}, {"第3节", "09:50", "10:30"}, {"第4节", "10:40", "11:20"}, {"第5节", "14:00", "14:40"}, {"第6节", "14:50", "15:30"}, {"第7节", "15:50", "16:30"}, {"第8节", "16:40", "17:20"} }; for (int i = 0; i < defaults.length; i++) { Period period = new Period(); period.setSchoolId(school.getId()); period.setName(defaults[i][0]); period.setStartTime(LocalTime.parse(defaults[i][1])); period.setEndTime(LocalTime.parse(defaults[i][2])); period.setSortOrder(i + 1); periods.save(period); } return school; } @Transactional public School updateSchool(UserPrincipal me, Long id, SchoolRequest request) { School school = schools.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在")); guard.checkSchool(me, school.getId()); if (!school.getCode().equals(request.code()) && schools.existsByCode(request.code())) { throw new BizException(ErrorCode.CONFLICT, "学校编码已存在"); } apply(school, request); return schools.save(school); } @Transactional public void updateSchoolStatus(UserPrincipal me, Long id, String status) { School school = schools.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在")); guard.checkSchool(me, school.getId()); if (!"ACTIVE".equals(status) && !"DISABLED".equals(status)) { throw new BizException(ErrorCode.VALIDATION, "状态不正确"); } school.setStatus(status); schools.save(school); } public List grades(UserPrincipal me, Long schoolId) { Long scoped = guard.requiredSchool(me, schoolId); return grades.findBySchoolIdOrderBySortOrderAsc(scoped); } @Transactional public Grade createGrade(UserPrincipal me, GradeRequest request) { Long schoolId = guard.requiredSchool(me, request.schoolId()); Grade grade = new Grade(); grade.setSchoolId(schoolId); grade.setName(request.name().trim()); grade.setSortOrder(request.sortOrder() == null ? 0 : request.sortOrder()); return grades.save(grade); } @Transactional public Grade updateGrade(UserPrincipal me, Long id, GradeRequest request) { Grade grade = grades.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "年级不存在")); guard.checkSchool(me, grade.getSchoolId()); grade.setName(request.name().trim()); grade.setSortOrder(request.sortOrder() == null ? grade.getSortOrder() : request.sortOrder()); return grades.save(grade); } @Transactional public void deleteGrade(UserPrincipal me, Long id) { Grade grade = grades.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "年级不存在")); guard.checkSchool(me, grade.getSchoolId()); if (!classes.findBySchoolIdAndGradeId(grade.getSchoolId(), id).isEmpty()) { throw new BizException(ErrorCode.CONFLICT, "年级下仍有班级"); } grades.delete(grade); } public List> directory() { Map schoolNames = new LinkedHashMap<>(); List> rows = new ArrayList<>(); for (ClassRoom room : classes.findAll()) { if (!"ACTIVE".equals(room.getStatus())) { continue; } String schoolName = schoolNames.computeIfAbsent(room.getSchoolId(), id -> schools.findById(id).map(School::getName).orElse("")); Map row = new LinkedHashMap<>(); row.put("id", room.getId()); row.put("name", room.getName()); row.put("schoolId", room.getSchoolId()); row.put("schoolName", schoolName); rows.add(row); } return rows; } public PagePayload classes(UserPrincipal me, Long schoolId, int page, int size) { Long scoped = me.superAdmin() ? schoolId : me.schoolId(); var result = scoped == null ? classes.findAll(Pages.of(page, size)) : classes.findBySchoolId(scoped, Pages.of(page, size)); return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize()); } @Transactional public ClassRoom createClass(UserPrincipal me, ClassRequest request) { Long schoolId = guard.requiredSchool(me, request.schoolId()); Grade grade = grades.findById(request.gradeId()).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "年级不存在")); if (!grade.getSchoolId().equals(schoolId)) { throw new BizException(ErrorCode.FORBIDDEN, "年级不属于该学校"); } ClassRoom room = new ClassRoom(); room.setSchoolId(schoolId); room.setGradeId(grade.getId()); room.setName(request.name().trim()); room.setHeadTeacherId(request.headTeacherId()); room.setStatus("ACTIVE"); return classes.save(room); } @Transactional public ClassRoom updateClass(UserPrincipal me, Long id, ClassRequest request) { ClassRoom room = requireClass(me, id); room.setName(request.name().trim()); room.setGradeId(request.gradeId()); room.setHeadTeacherId(request.headTeacherId()); return classes.save(room); } @Transactional public void deleteClass(UserPrincipal me, Long id) { ClassRoom room = requireClass(me, id); classes.delete(room); } public List teachersOf(UserPrincipal me, Long classId) { requireClass(me, classId); return classTeachers.findByClassId(classId); } @Transactional public ClassTeacher assignTeacher(UserPrincipal me, Long classId, TeacherAssign request) { ClassRoom room = requireClass(me, classId); UserAccount teacher = users.findById(request.teacherId()) .orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "教师不存在")); boolean isTeacher = roles.findByIdUserId(teacher.getId()).stream().anyMatch(role -> role.role() == RoleName.TEACHER); if (!isTeacher) { throw new BizException(ErrorCode.VALIDATION, "该账号不是教师"); } guard.checkSchool(me, teacher.getSchoolId()); ClassTeacher link = classTeachers.findByClassIdAndTeacherId(classId, teacher.getId()).orElseGet(ClassTeacher::new); link.setClassId(classId); link.setTeacherId(teacher.getId()); link.setSubject(request.subject()); link.setHead(request.head()); classTeachers.save(link); if (request.head()) { room.setHeadTeacherId(teacher.getId()); classes.save(room); } return link; } @Transactional public void removeTeacher(UserPrincipal me, Long classId, Long teacherId) { requireClass(me, classId); classTeachers.deleteByClassIdAndTeacherId(classId, teacherId); } public PagePayload students(UserPrincipal me, Long classId, int page, int size) { requireClass(me, classId); var result = students.findByClassId(classId, Pages.of(page, size)); return new PagePayload<>(result.getContent(), result.getTotalElements(), result.getNumber(), result.getSize()); } @Transactional public Student createStudent(UserPrincipal me, StudentRequest request) { ClassRoom room = requireClass(me, request.classId()); if (students.findBySchoolIdAndStudentNo(room.getSchoolId(), request.studentNo()).isPresent()) { throw new BizException(ErrorCode.CONFLICT, "学号已存在"); } Student student = new Student(); student.setSchoolId(room.getSchoolId()); student.setClassId(room.getId()); student.setName(request.name().trim()); student.setStudentNo(request.studentNo().trim()); return students.save(student); } @Transactional public void deleteStudent(UserPrincipal me, Long id) { Student student = students.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学生不存在")); guard.checkSchool(me, student.getSchoolId()); students.delete(student); } public ClassRoom requireClass(UserPrincipal me, Long classId) { ClassRoom room = classes.findById(classId).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "班级不存在")); guard.checkSchool(me, room.getSchoolId()); return room; } public School requireSchool(Long id) { return schools.findById(id).orElseThrow(() -> new BizException(ErrorCode.NOT_FOUND, "学校不存在")); } public boolean teaches(Long classId, Long teacherId) { return classTeachers.findByClassIdAndTeacherId(classId, teacherId).isPresent(); } public long countClasses(Long schoolId) { return schoolId == null ? classes.count() : classes.countBySchoolId(schoolId); } private void apply(School school, SchoolRequest request) { school.setName(request.name().trim()); school.setCode(request.code().trim()); school.setLogoUrl(request.logoUrl()); school.setAddress(request.address()); school.setContactName(request.contactName()); school.setContactPhone(request.contactPhone()); if (request.liveEnabled() != null) { school.setLiveEnabled(request.liveEnabled()); } if (request.recordEnabled() != null) { school.setRecordEnabled(request.recordEnabled()); } if (request.teacherPublic() != null) { school.setTeacherPublic(request.teacherPublic()); } if (request.retentionDays() != null) { school.setRetentionDays(Math.max(1, request.retentionDays())); } } }