feat: преподаватели дисциплин — привязки на странице кафедры и сужение в конструкторе правил

Кабинет кафедры: новая секция «Преподаватели дисциплин» — таблица дисциплин
кафедры с колонкой привязанных преподавателей, панель управления с поиском
по преподавателям кафедры (уже привязанные скрываются), отвязка с диалогом
подтверждения. Привязки грузятся пачками по 100 дисциплин.

Конструктор правил: список «Преподаватель» слота сужается до привязок
выбранной дисциплины через GET /api/users/teachers/options?subjectId=…
(новый параметр, запрос searchTeachersBySubjectBinding). До выбора
дисциплины — подсказка «Сначала выберите дисциплину», без привязок —
«К дисциплине не привязаны преподаватели». Смена дисциплины или группы
сбрасывает преподавателей слотов; текущий преподаватель редактируемого
правила остаётся в списке через selectedId. Тот же контракт в модалке
конфликта слота.
This commit is contained in:
dipatrik10 committed 2026-10-06 21:08:15 +03:00
1 parent deeee47cae
commit ddf1850155
13 files changed
+599 -26

No files matched your search

@@ -119,6 +119,7 @@ public class UserController {
public List<UserResponse> searchTeacherOptions(
@RequestParam(defaultValue = "") String query,
@RequestParam(required = false) Long departmentId,
@RequestParam(required = false) Long subjectId,
@RequestParam(required = false) Long selectedId,
@RequestParam(defaultValue = "20") int limit) {
var currentUser = AuthContext.getCurrentUser();
@@ -126,18 +127,34 @@ public class UserController {
? currentUser.departmentId()
: departmentId;
LocalDate today = businessTime.today();
List<UserResponse> options = new ArrayList<>(userRepository.searchTeacherOptions(
query == null ? "" : query.trim().toLowerCase(Locale.ROOT),
Role.TEACHER,
LifecycleEntity.STATUS_ARCHIVED,
effectiveDepartmentId,
today,
PageRequest.of(0, Math.min(normalizeSize(limit), 50), Sort.by("fullName").ascending())
).stream()
.map(user -> effectiveDepartmentId == null
? toUserResponse(user)
: toUserResponse(user, effectiveDepartmentId))
.toList());
List<UserResponse> options;
if (subjectId != null) {
// Конструктор правил: список преподавателя слота сужается до
// привязок выбранной дисциплины (teacher_subjects). Сортировка
// задана в самом запросе, поэтому Pageable идёт без Sort.
options = new ArrayList<>(userRepository.searchTeachersBySubjectBinding(
subjectId,
query == null ? "" : query.trim().toLowerCase(Locale.ROOT),
Role.TEACHER,
LifecycleEntity.STATUS_ARCHIVED,
PageRequest.of(0, Math.min(normalizeSize(limit), 50))
).stream()
.map(this::toUserResponse)
.toList());
} else {
options = new ArrayList<>(userRepository.searchTeacherOptions(
query == null ? "" : query.trim().toLowerCase(Locale.ROOT),
Role.TEACHER,
LifecycleEntity.STATUS_ARCHIVED,
effectiveDepartmentId,
today,
PageRequest.of(0, Math.min(normalizeSize(limit), 50), Sort.by("fullName").ascending())
).stream()
.map(user -> effectiveDepartmentId == null
? toUserResponse(user)
: toUserResponse(user, effectiveDepartmentId))
.toList());
}
if (selectedId != null && options.stream().noneMatch(item -> selectedId.equals(item.getId()))) {
userRepository.findById(selectedId)
.filter(user -> user.getRole() == Role.TEACHER)
@@ -72,6 +72,26 @@ public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificat
@Param("date") LocalDate date,
Pageable pageable);
// Преподаватели, привязанные к дисциплине (teacher_subjects): конструктор
// правил сужает список преподавателя слота до привязок выбранной дисциплины.
@Query("""
select teacherSubject.user
from TeacherSubject teacherSubject
where teacherSubject.subjectId = :subjectId
and teacherSubject.user.role = :role
and teacherSubject.user.status <> :archivedStatus
and (:query = ''
or lower(teacherSubject.user.username) like concat('%', :query, '%')
or lower(teacherSubject.user.fullName) like concat('%', :query, '%')
or lower(coalesce(teacherSubject.user.jobTitle, '')) like concat('%', :query, '%'))
order by teacherSubject.user.fullName asc
""")
List<User> searchTeachersBySubjectBinding(@Param("subjectId") Long subjectId,
@Param("query") String query,
@Param("role") Role role,
@Param("archivedStatus") String archivedStatus,
Pageable pageable);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select user from User user where user.id = :id")
Optional<User> findByIdForUpdate(@Param("id") Long id);
@@ -54,6 +54,49 @@ class UserControllerTest {
assertThat(body.get(0).getStatus()).isEqualTo(LifecycleEntity.STATUS_ACTIVE);
}
@Test
void teacherOptionsBySubjectReturnBoundTeachersAndInjectSelected() {
UserRepository userRepository = mock(UserRepository.class);
DepartmentRepository departmentRepository = mock(DepartmentRepository.class);
TeacherDepartmentAssignmentRepository assignmentRepository = mock(TeacherDepartmentAssignmentRepository.class);
TeacherDepartmentService teacherDepartmentService = mock(TeacherDepartmentService.class);
UserController controller = new UserController(
userRepository,
null,
departmentRepository,
assignmentRepository,
teacherDepartmentService
);
User bound = user(10L, "bound", Role.TEACHER, 2L);
User legacy = user(99L, "legacy", Role.TEACHER, 3L);
when(userRepository.searchTeachersBySubjectBinding(
org.mockito.ArgumentMatchers.eq(5L),
org.mockito.ArgumentMatchers.eq(""),
org.mockito.ArgumentMatchers.eq(Role.TEACHER),
org.mockito.ArgumentMatchers.eq(LifecycleEntity.STATUS_ARCHIVED),
org.mockito.ArgumentMatchers.any()
)).thenReturn(List.of(bound));
when(userRepository.findById(99L)).thenReturn(Optional.of(legacy));
when(teacherDepartmentService.findPrimaryDepartmentIdAtDate(
org.mockito.ArgumentMatchers.eq(10L),
org.mockito.ArgumentMatchers.any()
)).thenReturn(Optional.of(2L));
when(teacherDepartmentService.findPrimaryDepartmentIdAtDate(
org.mockito.ArgumentMatchers.eq(99L),
org.mockito.ArgumentMatchers.any()
)).thenReturn(Optional.of(3L));
when(departmentRepository.findById(2L))
.thenReturn(Optional.of(new Department(2L, "Кафедра ВТ", 2L)));
when(departmentRepository.findById(3L))
.thenReturn(Optional.of(new Department(3L, "Кафедра ИБ", 2L)));
List<UserResponse> options = controller.searchTeacherOptions("", null, 5L, 99L, 20);
assertThat(options).hasSize(2);
assertThat(options.get(0).getUsername()).isEqualTo("bound");
assertThat(options.get(1).getUsername()).isEqualTo("legacy");
}
private User user(Long id, String username, Role role, Long departmentId) {
User user = new User();
user.setId(id);