Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df59e1a924 | ||
|
|
59818bc78c | ||
|
|
4eafeb7a3b | ||
|
|
37665f1aae | ||
|
|
efacac1c59 | ||
|
|
91f44c85b4 |
No files matched your search
+102
-1
@@ -4,15 +4,18 @@ import com.magistr.app.config.auth.AuthContext;
|
||||
import com.magistr.app.config.auth.RequireRoles;
|
||||
import com.magistr.app.dto.CreateTeacherCreationRequest;
|
||||
import com.magistr.app.dto.CreateSubjectRequest;
|
||||
import com.magistr.app.dto.DepartmentCalendarSubjectDto;
|
||||
import com.magistr.app.dto.SubjectCommentDto;
|
||||
import com.magistr.app.dto.TeacherCreationRequestResponse;
|
||||
import com.magistr.app.dto.UserResponse;
|
||||
import com.magistr.app.model.*;
|
||||
import com.magistr.app.repository.AcademicCalendarSubjectRepository;
|
||||
import com.magistr.app.repository.DepartmentRepository;
|
||||
import com.magistr.app.repository.SubjectCommentRepository;
|
||||
import com.magistr.app.repository.SubjectRepository;
|
||||
import com.magistr.app.repository.TeacherCreationRequestRepository;
|
||||
import com.magistr.app.repository.TeacherDepartmentAssignmentRepository;
|
||||
import com.magistr.app.repository.TeacherSubjectRepository;
|
||||
import com.magistr.app.repository.UserRepository;
|
||||
import com.magistr.app.service.ScheduleQueryService;
|
||||
import com.magistr.app.service.SubjectImportService;
|
||||
@@ -25,10 +28,12 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/department")
|
||||
@@ -43,6 +48,8 @@ public class DepartmentWorkspaceController {
|
||||
private final DepartmentRepository departmentRepository;
|
||||
private final TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository;
|
||||
private final TeacherCreationRequestRepository teacherCreationRequestRepository;
|
||||
private final AcademicCalendarSubjectRepository calendarSubjectRepository;
|
||||
private final TeacherSubjectRepository teacherSubjectRepository;
|
||||
private final ScheduleQueryService scheduleQueryService;
|
||||
private final TeacherDepartmentService teacherDepartmentService;
|
||||
private final SubjectImportService subjectImportService;
|
||||
@@ -54,12 +61,15 @@ public class DepartmentWorkspaceController {
|
||||
DepartmentRepository departmentRepository,
|
||||
TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository,
|
||||
TeacherCreationRequestRepository teacherCreationRequestRepository,
|
||||
AcademicCalendarSubjectRepository calendarSubjectRepository,
|
||||
TeacherSubjectRepository teacherSubjectRepository,
|
||||
ScheduleQueryService scheduleQueryService,
|
||||
TeacherDepartmentService teacherDepartmentService,
|
||||
SubjectImportService subjectImportService) {
|
||||
this(subjectRepository, subjectCommentRepository, userRepository, departmentRepository,
|
||||
teacherDepartmentAssignmentRepository, teacherCreationRequestRepository,
|
||||
scheduleQueryService, teacherDepartmentService, subjectImportService,
|
||||
calendarSubjectRepository, teacherSubjectRepository, scheduleQueryService,
|
||||
teacherDepartmentService, subjectImportService,
|
||||
BusinessTimeService.systemDefault());
|
||||
}
|
||||
|
||||
@@ -70,6 +80,8 @@ public class DepartmentWorkspaceController {
|
||||
DepartmentRepository departmentRepository,
|
||||
TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository,
|
||||
TeacherCreationRequestRepository teacherCreationRequestRepository,
|
||||
AcademicCalendarSubjectRepository calendarSubjectRepository,
|
||||
TeacherSubjectRepository teacherSubjectRepository,
|
||||
ScheduleQueryService scheduleQueryService,
|
||||
TeacherDepartmentService teacherDepartmentService,
|
||||
SubjectImportService subjectImportService,
|
||||
@@ -80,6 +92,8 @@ public class DepartmentWorkspaceController {
|
||||
this.departmentRepository = departmentRepository;
|
||||
this.teacherDepartmentAssignmentRepository = teacherDepartmentAssignmentRepository;
|
||||
this.teacherCreationRequestRepository = teacherCreationRequestRepository;
|
||||
this.calendarSubjectRepository = calendarSubjectRepository;
|
||||
this.teacherSubjectRepository = teacherSubjectRepository;
|
||||
this.scheduleQueryService = scheduleQueryService;
|
||||
this.teacherDepartmentService = teacherDepartmentService;
|
||||
this.subjectImportService = subjectImportService;
|
||||
@@ -113,6 +127,93 @@ public class DepartmentWorkspaceController {
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Дисциплины кафедры вместе с прикреплениями к календарным графикам.
|
||||
* Дисциплина попадает в список той кафедры, за которой она закреплена
|
||||
* в справочнике (subjects.department_id); прикрепления берутся из
|
||||
* academic_calendar_subjects по всем графикам и семестрам.
|
||||
*/
|
||||
@GetMapping("/subjects/calendar")
|
||||
public List<DepartmentCalendarSubjectDto> getSubjectCalendarAttachments(
|
||||
@RequestParam(required = false) Long departmentId) {
|
||||
Long effectiveDepartmentId = effectiveDepartmentId(departmentId);
|
||||
if (effectiveDepartmentId == null || effectiveDepartmentId == NO_DEPARTMENT_ID) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Subject> subjects = subjectRepository
|
||||
.findByDepartmentIdAndStatusNot(effectiveDepartmentId, LifecycleEntity.STATUS_ARCHIVED)
|
||||
.stream()
|
||||
.sorted((left, right) -> String.CASE_INSENSITIVE_ORDER.compare(
|
||||
left.getName() == null ? "" : left.getName(),
|
||||
right.getName() == null ? "" : right.getName()))
|
||||
.toList();
|
||||
|
||||
Map<Long, List<DepartmentCalendarSubjectDto.CalendarAttachmentDto>> attachmentsBySubject =
|
||||
calendarSubjectRepository.findBySubjectDepartmentId(effectiveDepartmentId).stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
calendarSubject -> calendarSubject.getSubject().getId(),
|
||||
LinkedHashMap::new,
|
||||
Collectors.mapping(this::toCalendarAttachmentDto, Collectors.toList())
|
||||
));
|
||||
|
||||
Map<Long, List<String>> lessonTypesBySubject = lessonTypesBySubjectId(
|
||||
subjects.stream().map(Subject::getId).toList());
|
||||
|
||||
return subjects.stream()
|
||||
.map(subject -> toDepartmentCalendarSubjectDto(subject, attachmentsBySubject, lessonTypesBySubject))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Виды нагрузки дисциплин: уникальные типы занятий из привязок
|
||||
* преподавателей (teacher_lesson_types), без повторов от разных педагогов.
|
||||
*/
|
||||
private Map<Long, List<String>> lessonTypesBySubjectId(List<Long> subjectIds) {
|
||||
if (subjectIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, List<String>> lessonTypesBySubject = new LinkedHashMap<>();
|
||||
for (Object[] row : teacherSubjectRepository.findLessonTypeNamesBySubjectIds(subjectIds)) {
|
||||
Long subjectId = ((Number) row[0]).longValue();
|
||||
String lessonTypeName = String.valueOf(row[1]);
|
||||
List<String> lessonTypes = lessonTypesBySubject.computeIfAbsent(subjectId, key -> new ArrayList<>());
|
||||
if (!lessonTypes.contains(lessonTypeName)) {
|
||||
lessonTypes.add(lessonTypeName);
|
||||
}
|
||||
}
|
||||
return lessonTypesBySubject;
|
||||
}
|
||||
|
||||
private DepartmentCalendarSubjectDto toDepartmentCalendarSubjectDto(
|
||||
Subject subject,
|
||||
Map<Long, List<DepartmentCalendarSubjectDto.CalendarAttachmentDto>> attachmentsBySubject,
|
||||
Map<Long, List<String>> lessonTypesBySubject) {
|
||||
return new DepartmentCalendarSubjectDto(
|
||||
subject.getId(),
|
||||
subject.getCode(),
|
||||
subject.getName(),
|
||||
subject.getDepartmentId(),
|
||||
lessonTypesBySubject.getOrDefault(subject.getId(), List.of()),
|
||||
attachmentsBySubject.getOrDefault(subject.getId(), List.of())
|
||||
);
|
||||
}
|
||||
|
||||
private DepartmentCalendarSubjectDto.CalendarAttachmentDto toCalendarAttachmentDto(
|
||||
AcademicCalendarSubject calendarSubject) {
|
||||
AcademicCalendar calendar = calendarSubject.getAcademicCalendar();
|
||||
AcademicYear academicYear = calendar.getAcademicYear();
|
||||
return new DepartmentCalendarSubjectDto.CalendarAttachmentDto(
|
||||
calendar.getId(),
|
||||
calendar.getTitle(),
|
||||
calendar.getSpeciality() == null ? null : calendar.getSpeciality().getSpecialityCode(),
|
||||
calendar.getSpecialtyProfile() == null ? null : calendar.getSpecialtyProfile().getName(),
|
||||
academicYear == null ? null : academicYear.getId(),
|
||||
academicYear == null ? null : academicYear.getTitle(),
|
||||
calendarSubject.getSemesterNumber()
|
||||
);
|
||||
}
|
||||
|
||||
@GetMapping("/subjects/{subjectId}/comments")
|
||||
public ResponseEntity<?> getComments(@PathVariable Long subjectId) {
|
||||
Subject subject = subjectRepository.findById(subjectId).orElse(null);
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.magistr.app.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Дисциплина кафедры вместе с прикреплениями к календарным графикам.
|
||||
* Прикрепления приходят из academic_calendar_subjects: дисциплина попадает
|
||||
* на страницу той кафедры, за которой она закреплена в справочнике.
|
||||
* lessonTypes — виды нагрузки (типы занятий) из привязок преподавателей.
|
||||
*/
|
||||
public record DepartmentCalendarSubjectDto(
|
||||
Long id,
|
||||
String code,
|
||||
String name,
|
||||
Long departmentId,
|
||||
List<String> lessonTypes,
|
||||
List<CalendarAttachmentDto> attachments
|
||||
) {
|
||||
|
||||
public record CalendarAttachmentDto(
|
||||
Long calendarId,
|
||||
String calendarTitle,
|
||||
String specialtyCode,
|
||||
String specialtyProfileName,
|
||||
Long academicYearId,
|
||||
String academicYearTitle,
|
||||
Integer semesterNumber
|
||||
) {
|
||||
}
|
||||
}
|
||||
+25
@@ -24,12 +24,37 @@ public interface AcademicCalendarSubjectRepository extends JpaRepository<Academi
|
||||
select calendarSubject
|
||||
from AcademicCalendarSubject calendarSubject
|
||||
join fetch calendarSubject.academicCalendar calendar
|
||||
join fetch calendar.academicYear academicYear
|
||||
join fetch calendarSubject.subject subject
|
||||
where calendar.id in :calendarIds
|
||||
order by calendar.id asc, calendarSubject.semesterNumber asc, lower(subject.name) asc
|
||||
""")
|
||||
List<AcademicCalendarSubject> findByCalendarIdInWithSubject(@Param("calendarIds") Collection<Long> calendarIds);
|
||||
|
||||
// Дисциплины кафедры, прикреплённые к календарным графикам: попадают
|
||||
// на страницу кафедры через принадлежность самой дисциплины кафедре.
|
||||
// График относится к кафедре, только если его специальность используется
|
||||
// активными группами этой кафедры (кафедра ИБ — 10.03.01, но не 08.03.01).
|
||||
@Query("""
|
||||
select calendarSubject
|
||||
from AcademicCalendarSubject calendarSubject
|
||||
join fetch calendarSubject.academicCalendar calendar
|
||||
join fetch calendar.academicYear academicYear
|
||||
join fetch calendar.speciality speciality
|
||||
join fetch calendar.specialtyProfile specialtyProfile
|
||||
join fetch calendarSubject.subject subject
|
||||
where subject.departmentId = :departmentId
|
||||
and subject.status <> 'ARCHIVED'
|
||||
and speciality.id in (
|
||||
select studentGroup.speciality.id
|
||||
from StudentGroup studentGroup
|
||||
where studentGroup.departmentId = :departmentId
|
||||
and studentGroup.status <> 'ARCHIVED'
|
||||
)
|
||||
order by academicYear.startDate desc, calendarSubject.semesterNumber asc, lower(subject.name) asc
|
||||
""")
|
||||
List<AcademicCalendarSubject> findBySubjectDepartmentId(@Param("departmentId") Long departmentId);
|
||||
|
||||
void deleteByAcademicCalendar_Id(Long calendarId);
|
||||
|
||||
boolean existsByAcademicCalendarIdAndSemesterNumberGreaterThan(Long calendarId, Integer semesterNumber);
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public interface TeacherSubjectRepository extends JpaRepository<TeacherSubject, TeacherSubjectId> {
|
||||
@@ -47,4 +48,18 @@ public interface TeacherSubjectRepository extends JpaRepository<TeacherSubject,
|
||||
@Param("subjectId") Long subjectId,
|
||||
@Param("lessonTypeId") Long lessonTypeId
|
||||
);
|
||||
|
||||
/**
|
||||
* Виды нагрузки дисциплин (типы занятий из привязок преподавателей)
|
||||
* для сводной колонки на странице кафедры. Один тип от разных
|
||||
* преподавателей не дублируется — уникальность собирает контроллер.
|
||||
*/
|
||||
@Query(value = """
|
||||
select link.subject_id, type.name
|
||||
from teacher_lesson_types link
|
||||
join lesson_types type on type.id = link.lesson_type_id
|
||||
where link.subject_id in (:subjectIds)
|
||||
order by link.subject_id, type.name
|
||||
""", nativeQuery = true)
|
||||
List<Object[]> findLessonTypeNamesBySubjectIds(@Param("subjectIds") Collection<Long> subjectIds);
|
||||
}
|
||||
+111
@@ -2,18 +2,26 @@ package com.magistr.app.controller;
|
||||
|
||||
import com.magistr.app.config.auth.AuthContext;
|
||||
import com.magistr.app.config.auth.AuthenticatedUser;
|
||||
import com.magistr.app.dto.DepartmentCalendarSubjectDto;
|
||||
import com.magistr.app.dto.UserResponse;
|
||||
import com.magistr.app.model.AcademicCalendar;
|
||||
import com.magistr.app.model.AcademicCalendarSubject;
|
||||
import com.magistr.app.model.AcademicYear;
|
||||
import com.magistr.app.model.Department;
|
||||
import com.magistr.app.model.LifecycleEntity;
|
||||
import com.magistr.app.model.Role;
|
||||
import com.magistr.app.model.Speciality;
|
||||
import com.magistr.app.model.SpecialtyProfile;
|
||||
import com.magistr.app.model.Subject;
|
||||
import com.magistr.app.model.TeacherDepartmentAssignment;
|
||||
import com.magistr.app.model.User;
|
||||
import com.magistr.app.repository.AcademicCalendarSubjectRepository;
|
||||
import com.magistr.app.repository.SubjectCommentRepository;
|
||||
import com.magistr.app.repository.SubjectRepository;
|
||||
import com.magistr.app.repository.DepartmentRepository;
|
||||
import com.magistr.app.repository.TeacherCreationRequestRepository;
|
||||
import com.magistr.app.repository.TeacherDepartmentAssignmentRepository;
|
||||
import com.magistr.app.repository.TeacherSubjectRepository;
|
||||
import com.magistr.app.repository.UserRepository;
|
||||
import com.magistr.app.service.BusinessTimeService;
|
||||
import com.magistr.app.service.ScheduleQueryService;
|
||||
@@ -63,6 +71,8 @@ class DepartmentWorkspaceControllerTest {
|
||||
mock(DepartmentRepository.class),
|
||||
mock(TeacherDepartmentAssignmentRepository.class),
|
||||
mock(TeacherCreationRequestRepository.class),
|
||||
mock(AcademicCalendarSubjectRepository.class),
|
||||
mock(TeacherSubjectRepository.class),
|
||||
mock(ScheduleQueryService.class),
|
||||
mock(TeacherDepartmentService.class),
|
||||
mock(SubjectImportService.class)
|
||||
@@ -90,6 +100,8 @@ class DepartmentWorkspaceControllerTest {
|
||||
mock(DepartmentRepository.class),
|
||||
assignmentRepository,
|
||||
mock(TeacherCreationRequestRepository.class),
|
||||
mock(AcademicCalendarSubjectRepository.class),
|
||||
mock(TeacherSubjectRepository.class),
|
||||
mock(ScheduleQueryService.class),
|
||||
teacherDepartmentService,
|
||||
mock(SubjectImportService.class),
|
||||
@@ -119,6 +131,8 @@ class DepartmentWorkspaceControllerTest {
|
||||
departmentRepository,
|
||||
assignmentRepository,
|
||||
mock(TeacherCreationRequestRepository.class),
|
||||
mock(AcademicCalendarSubjectRepository.class),
|
||||
mock(TeacherSubjectRepository.class),
|
||||
mock(ScheduleQueryService.class),
|
||||
mock(TeacherDepartmentService.class),
|
||||
mock(SubjectImportService.class)
|
||||
@@ -137,6 +151,103 @@ class DepartmentWorkspaceControllerTest {
|
||||
assertThat(saved.getCreatedBy()).isEqualTo(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void subjectCalendarAttachmentsSortByNameAndGroupAttachments() {
|
||||
SubjectRepository subjectRepository = mock(SubjectRepository.class);
|
||||
AcademicCalendarSubjectRepository calendarSubjectRepository = mock(AcademicCalendarSubjectRepository.class);
|
||||
TeacherSubjectRepository teacherSubjectRepository = mock(TeacherSubjectRepository.class);
|
||||
Subject databases = new Subject(10L, "Базы данных", "DB201", 1L);
|
||||
Subject crypto = new Subject(11L, "Криптография", "KR101", 1L);
|
||||
// порядок из репозитория намеренно не по алфавиту — контроллер сортирует
|
||||
when(subjectRepository.findByDepartmentIdAndStatusNot(1L, LifecycleEntity.STATUS_ARCHIVED))
|
||||
.thenReturn(List.of(crypto, databases));
|
||||
|
||||
Speciality speciality = new Speciality();
|
||||
speciality.setId(3L);
|
||||
speciality.setSpecialityName("Информационная безопасность");
|
||||
speciality.setSpecialityCode("10.03.01");
|
||||
SpecialtyProfile specialtyProfile = new SpecialtyProfile();
|
||||
specialtyProfile.setId(4L);
|
||||
specialtyProfile.setName("Без профиля");
|
||||
AcademicYear year = new AcademicYear();
|
||||
year.setId(1L);
|
||||
year.setTitle("2026/2027");
|
||||
year.setStartDate(LocalDate.of(2026, 9, 1));
|
||||
year.setEndDate(LocalDate.of(2027, 8, 31));
|
||||
AcademicCalendar calendar = new AcademicCalendar();
|
||||
calendar.setId(2L);
|
||||
calendar.setTitle("2026/2027 · 10.03.01 Информационная безопасность");
|
||||
calendar.setAcademicYear(year);
|
||||
calendar.setSpeciality(speciality);
|
||||
calendar.setSpecialtyProfile(specialtyProfile);
|
||||
AcademicCalendarSubject link = new AcademicCalendarSubject();
|
||||
link.setAcademicCalendar(calendar);
|
||||
link.setSemesterNumber(3);
|
||||
link.setSubject(databases);
|
||||
when(calendarSubjectRepository.findBySubjectDepartmentId(1L)).thenReturn(List.of(link));
|
||||
// один и тот же тип занятия от двух преподавателей не дублируется
|
||||
when(teacherSubjectRepository.findLessonTypeNamesBySubjectIds(List.of(10L, 11L)))
|
||||
.thenReturn(List.of(
|
||||
new Object[]{10L, "Лабораторные занятия"},
|
||||
new Object[]{10L, "Лекции"},
|
||||
new Object[]{10L, "Лекции"}
|
||||
));
|
||||
|
||||
DepartmentWorkspaceController controller = new DepartmentWorkspaceController(
|
||||
subjectRepository,
|
||||
mock(SubjectCommentRepository.class),
|
||||
mock(UserRepository.class),
|
||||
mock(DepartmentRepository.class),
|
||||
mock(TeacherDepartmentAssignmentRepository.class),
|
||||
mock(TeacherCreationRequestRepository.class),
|
||||
calendarSubjectRepository,
|
||||
teacherSubjectRepository,
|
||||
mock(ScheduleQueryService.class),
|
||||
mock(TeacherDepartmentService.class),
|
||||
mock(SubjectImportService.class)
|
||||
);
|
||||
AuthContext.setCurrentUser(new AuthenticatedUser(5L, "admin", Role.ADMIN, null));
|
||||
|
||||
List<DepartmentCalendarSubjectDto> result = controller.getSubjectCalendarAttachments(1L);
|
||||
|
||||
assertThat(result).extracting(DepartmentCalendarSubjectDto::name)
|
||||
.containsExactly("Базы данных", "Криптография");
|
||||
assertThat(result.get(0).attachments()).hasSize(1);
|
||||
DepartmentCalendarSubjectDto.CalendarAttachmentDto attachment = result.get(0).attachments().get(0);
|
||||
assertThat(attachment.calendarId()).isEqualTo(2L);
|
||||
assertThat(attachment.calendarTitle()).isEqualTo("2026/2027 · 10.03.01 Информационная безопасность");
|
||||
assertThat(attachment.specialtyCode()).isEqualTo("10.03.01");
|
||||
assertThat(attachment.specialtyProfileName()).isEqualTo("Без профиля");
|
||||
assertThat(attachment.academicYearTitle()).isEqualTo("2026/2027");
|
||||
assertThat(attachment.semesterNumber()).isEqualTo(3);
|
||||
// виды нагрузки дисциплины: уникальные типы занятий по алфавиту
|
||||
assertThat(result.get(0).lessonTypes())
|
||||
.containsExactly("Лабораторные занятия", "Лекции");
|
||||
// дисциплина без прикреплений и без типов получает пустые списки, а не null
|
||||
assertThat(result.get(1).attachments()).isEmpty();
|
||||
assertThat(result.get(1).lessonTypes()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void subjectCalendarAttachmentsEmptyForDepartmentUserWithoutDepartment() {
|
||||
DepartmentWorkspaceController controller = new DepartmentWorkspaceController(
|
||||
mock(SubjectRepository.class),
|
||||
mock(SubjectCommentRepository.class),
|
||||
mock(UserRepository.class),
|
||||
mock(DepartmentRepository.class),
|
||||
mock(TeacherDepartmentAssignmentRepository.class),
|
||||
mock(TeacherCreationRequestRepository.class),
|
||||
mock(AcademicCalendarSubjectRepository.class),
|
||||
mock(TeacherSubjectRepository.class),
|
||||
mock(ScheduleQueryService.class),
|
||||
mock(TeacherDepartmentService.class),
|
||||
mock(SubjectImportService.class)
|
||||
);
|
||||
AuthContext.setCurrentUser(new AuthenticatedUser(6L, "кафедра", Role.DEPARTMENT, null));
|
||||
|
||||
assertThat(controller.getSubjectCalendarAttachments(null)).isEmpty();
|
||||
}
|
||||
|
||||
private TeacherDepartmentAssignment assignment(User teacher, Long departmentId) {
|
||||
Department department = new Department(departmentId, "Кафедра", departmentId);
|
||||
TeacherDepartmentAssignment assignment = new TeacherDepartmentAssignment();
|
||||
|
||||
+36
@@ -1250,6 +1250,7 @@ GET /api/workload/teachers?departmentId=1&startDate=2026-05-20&endDate=2026-06-0
|
||||
| Метод | URL | Назначение |
|
||||
|-------|-----|------------|
|
||||
| `GET` | `/api/department/subjects` | Дисциплины текущей кафедры |
|
||||
| `GET` | `/api/department/subjects/calendar` | Дисциплины кафедры с прикреплениями к календарным графикам |
|
||||
| `POST` | `/api/department/subjects/import` | Загрузка списка дисциплин |
|
||||
| `GET` | `/api/department/subjects/{subjectId}/comments` | Комментарии дисциплины |
|
||||
| `POST` | `/api/department/subjects/{subjectId}/comments` | Добавить комментарий |
|
||||
@@ -1265,6 +1266,41 @@ GET /api/workload/teachers?departmentId=1&startDate=2026-05-20&endDate=2026-06-0
|
||||
API возвращает `409 Conflict`; владелец записи не изменяется. Повторы одного названия внутри
|
||||
payload обрабатываются один раз, используется последнее значение.
|
||||
|
||||
`GET /api/department/subjects/calendar` возвращает дисциплины кафедры (не архивные,
|
||||
отсортированные по названию) вместе с прикреплениями к календарным графикам из
|
||||
`academic_calendar_subjects`. Дисциплина попадает в список той кафедры, за которой она
|
||||
закреплена в справочнике (`subjects.department_id`). График относится к кафедре, только
|
||||
если его специальность используется активными группами этой кафедры: графики чужих
|
||||
специальностей в прикрепления не попадают. Роль `DEPARTMENT` видит только свою
|
||||
кафедру, `ADMIN` может передать `departmentId`. Элемент `attachments` может быть пустым —
|
||||
такая дисциплина на странице кафедры помечается «Не прикреплена к графику».
|
||||
`lessonTypes` — уникальные виды нагрузки дисциплины (типы занятий из привязок
|
||||
преподавателей `teacher_lesson_types`); у прикрепления `specialtyCode` и
|
||||
`specialtyProfileName` — шифр и профиль специальности графика.
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 10,
|
||||
"code": "DB201",
|
||||
"name": "Базы данных",
|
||||
"departmentId": 1,
|
||||
"lessonTypes": ["Лекции", "Лабораторные занятия"],
|
||||
"attachments": [
|
||||
{
|
||||
"calendarId": 2,
|
||||
"calendarTitle": "2026/2027 · 10.03.01 Информационная безопасность · Очная",
|
||||
"specialtyCode": "10.03.01",
|
||||
"specialtyProfileName": "Без профиля",
|
||||
"academicYearId": 1,
|
||||
"academicYearTitle": "2026/2027",
|
||||
"semesterNumber": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
`GET /api/department/teachers` возвращает актуальных преподавателей кафедры только по
|
||||
`teacher_department_assignments`. Основные и дополнительные назначения учитываются на
|
||||
текущую дату; архивные и ещё не начавшиеся назначения исключаются.
|
||||
|
||||
@@ -96,6 +96,14 @@ Bearer-токен проверяется на backend. Frontend-скрытие
|
||||
- Кафедра может добавлять комментарии к дисциплине и загружать список дисциплин через кабинет кафедры
|
||||
- Повторный импорт собственной дисциплины обновляет ту же запись и восстанавливает её из архива
|
||||
- Совпадение названия с дисциплиной другой кафедры даёт `409 Conflict` и никогда не меняет владельца
|
||||
- На странице кафедры дисциплины показываются вместе с прикреплениями к календарным графикам
|
||||
(`GET /api/department/subjects/calendar`): дисциплина попадает в список той кафедры, за которой
|
||||
она закреплена в справочнике; график относится к кафедре, только если его специальность
|
||||
используется активными группами этой кафедры. В таблице — колонки «Шифр» и «Профиль»
|
||||
(специальность графика), «Вид нагрузки» (уникальные типы занятий дисциплины из привязок
|
||||
преподавателей). Прикрепления группируются по графику с перечнем семестров; при нескольких
|
||||
графиках показывается выпадающий список. Комментарии открываются строкой под дисциплиной.
|
||||
Фильтр «В календарных графиках / Без графика» отделяет дисциплины, не входящие ни в один график.
|
||||
|
||||
### Жизненный цикл справочников
|
||||
|
||||
|
||||
@@ -651,7 +651,7 @@ legacy-файл вкладки. Последними (волна 6) — `schedul
|
||||
загрузка 84 857 байт gzip (лимит 90 000), общие chunk 79 217 байт gzip
|
||||
(лимит 85 000), lazy-вкладки 128 571 байт gzip в 25 chunk'ах (лимит 150 000,
|
||||
загружаются по одной) — лимиты не поднимались;
|
||||
- `npm run check`: 237 тестов пройдено (обновлены импорты тестов с legacy-модулей
|
||||
- `npm run check`: 241 тест пройден (обновлены импорты тестов с legacy-модулей
|
||||
на React-сервисы, добавлены payload-валидация, DOM-рендер конструктора
|
||||
и контроль разрешения lazy-вкладок; проверки `LegacyTabView`/`legacy-views`
|
||||
заменены на контроль отсутствия legacy-модулей).
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
|
||||
### Качество и надёжность
|
||||
|
||||
- **237 тестов** проходят (`npm run check`), против ~170 на момент начала этапа 5:
|
||||
- **241 тест** проходит (`npm run check`), против ~170 на момент начала этапа 5:
|
||||
контракты API, payload-валидация, DOM-рендер каждой вкладки, бюджеты bundle, CSP,
|
||||
разрешение всех lazy-вкладок (регрессия на React error #306 поймана и закрыта тестом).
|
||||
- Логика вынесена в **чистые сервисы** (`*-service.js`) — тестируются в Node без браузера
|
||||
@@ -97,5 +97,5 @@
|
||||
cd frontend
|
||||
npm ci
|
||||
npm run build
|
||||
npm run check # 237/237 тестов, бюджеты, CSP
|
||||
npm run check # 241/241 тестов, бюджеты, CSP
|
||||
```
|
||||
@@ -684,6 +684,60 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* ===== Кабинет кафедры: селект графиков и строка комментариев ===== */
|
||||
|
||||
/* Нативный селект (data-native-select="true" исключает его из кастомизации
|
||||
dropdown.js): в узкой ячейке таблицы читается лучше кастомного дропдауна.
|
||||
Ширина — по самому длинному пункту: колонка растягивается под селект,
|
||||
и он не короче текстовых ячеек. */
|
||||
.department-subject-calendar-select {
|
||||
width: auto;
|
||||
max-width: 100%;
|
||||
padding: 0.45rem 0.65rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--bg-card-border);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-primary);
|
||||
font-family: inherit;
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.department-subject-calendar-select:focus {
|
||||
outline: none;
|
||||
background: var(--bg-input-focus);
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px var(--accent-glow);
|
||||
}
|
||||
|
||||
.department-comments-row > td {
|
||||
padding: 0.9rem 0.8rem 1rem;
|
||||
background: var(--bg-input);
|
||||
border-bottom: 1px solid var(--bg-card-border);
|
||||
}
|
||||
|
||||
.department-comments-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.75rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.department-comments-card .card-header-row {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.department-comments-card .card-header-row h3 {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.department-comments-card .department-comment-list {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.schedule-section-label {
|
||||
display: block;
|
||||
font-size: 0.78rem;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { apiClient } from '../shared/api-client.js';
|
||||
import { defaultSchedulePeriod } from '../../admin/js/schedule-period.js';
|
||||
import { toIsoDate } from '../shared/dates.js';
|
||||
|
||||
export const SUBJECT_TABLE_COLUMNS = 4;
|
||||
export const SUBJECT_TABLE_COLUMNS = 7;
|
||||
export const DEPARTMENT_REQUEST_TABLE_COLUMNS = 6;
|
||||
|
||||
// --- Справочники и период ---
|
||||
@@ -42,6 +42,86 @@ export function fetchDepartmentSubjects(departmentId, client = apiClient) {
|
||||
});
|
||||
}
|
||||
|
||||
// --- Дисциплины кафедры с прикреплениями к календарным графикам ---
|
||||
|
||||
export function departmentSubjectCalendarEndpoint(departmentId) {
|
||||
return `/api/department/subjects/calendar?departmentId=${encodeURIComponent(departmentId || '')}`;
|
||||
}
|
||||
|
||||
export function fetchDepartmentSubjectCalendar(departmentId, client = apiClient) {
|
||||
return client.get(departmentSubjectCalendarEndpoint(departmentId), {
|
||||
errorMessage: 'Ошибка загрузки дисциплин'
|
||||
});
|
||||
}
|
||||
|
||||
export const SUBJECT_CALENDAR_FILTER_ALL = 'all';
|
||||
export const SUBJECT_CALENDAR_FILTER_IN_CALENDAR = 'calendar';
|
||||
export const SUBJECT_CALENDAR_FILTER_WITHOUT_CALENDAR = 'manual';
|
||||
|
||||
export const SUBJECT_CALENDAR_FILTER_OPTIONS = [
|
||||
{ value: SUBJECT_CALENDAR_FILTER_ALL, label: 'Все дисциплины' },
|
||||
{ value: SUBJECT_CALENDAR_FILTER_IN_CALENDAR, label: 'В календарных графиках' },
|
||||
{ value: SUBJECT_CALENDAR_FILTER_WITHOUT_CALENDAR, label: 'Без графика' }
|
||||
];
|
||||
|
||||
export function filterDepartmentSubjects(items, filter) {
|
||||
const list = items || [];
|
||||
if (filter === SUBJECT_CALENDAR_FILTER_IN_CALENDAR) {
|
||||
return list.filter(item => (item.attachments || []).length > 0);
|
||||
}
|
||||
if (filter === SUBJECT_CALENDAR_FILTER_WITHOUT_CALENDAR) {
|
||||
return list.filter(item => !(item.attachments || []).length);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
// Прикрепления дисциплины группируются по графику: один график — одна строка
|
||||
// с перечнем семестров («2026/2027 · 10.03.01 ИБ — 1, 3 семестр»).
|
||||
export function subjectAttachmentGroups(attachments) {
|
||||
const groups = new Map();
|
||||
(attachments || []).forEach(attachment => {
|
||||
if (!attachment) return;
|
||||
const key = String(attachment.calendarId);
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, {
|
||||
calendarId: attachment.calendarId,
|
||||
calendarTitle: attachment.calendarTitle || '',
|
||||
academicYearTitle: attachment.academicYearTitle || '',
|
||||
semesterNumbers: []
|
||||
});
|
||||
}
|
||||
groups.get(key).semesterNumbers.push(attachment.semesterNumber);
|
||||
});
|
||||
return Array.from(groups.values()).map(group => ({
|
||||
...group,
|
||||
semesterNumbers: [...new Set(group.semesterNumbers)].sort((a, b) => a - b)
|
||||
}));
|
||||
}
|
||||
|
||||
export function semesterNumbersLabel(numbers) {
|
||||
const sorted = [...(numbers || [])].sort((a, b) => a - b);
|
||||
return sorted.map(number => `${number} семестр`).join(', ');
|
||||
}
|
||||
|
||||
export function attachmentGroupLabel(group) {
|
||||
if (!group) return '';
|
||||
const title = group.calendarTitle || group.academicYearTitle || 'График';
|
||||
return `${title} — ${semesterNumbersLabel(group.semesterNumbers)}`;
|
||||
}
|
||||
|
||||
// Уникальные значения поля прикреплений для сводных колонок (шифр, профиль).
|
||||
export function uniqueAttachmentValues(attachments, field) {
|
||||
const values = new Set();
|
||||
(attachments || []).forEach(attachment => {
|
||||
if (attachment && attachment[field]) values.add(attachment[field]);
|
||||
});
|
||||
return Array.from(values).sort((left, right) => left.localeCompare(right, 'ru'));
|
||||
}
|
||||
|
||||
export function listValuesLabel(values) {
|
||||
return (values || []).join(', ');
|
||||
}
|
||||
|
||||
export function importSubjectsPayload(rows, departmentId) {
|
||||
if (!departmentId) return { error: 'Выберите кафедру' };
|
||||
const payload = (rows || [])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Fragment, useEffect, useRef, useState } from 'react';
|
||||
import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||||
|
||||
import { getSession } from '../../../admin/js/api.js';
|
||||
@@ -6,31 +6,38 @@ import { addDays, toIsoDate } from '../../shared/dates.js';
|
||||
import { requestCountLabel } from '../admin-service.js';
|
||||
import {
|
||||
DEPARTMENT_REQUEST_TABLE_COLUMNS,
|
||||
SUBJECT_CALENDAR_FILTER_ALL,
|
||||
SUBJECT_CALENDAR_FILTER_OPTIONS,
|
||||
SUBJECT_TABLE_COLUMNS,
|
||||
assignTeacher,
|
||||
assignTeacherError,
|
||||
attachmentGroupLabel,
|
||||
availableTeachers,
|
||||
defaultWorkloadPeriod,
|
||||
departmentOptionLabel,
|
||||
fetchAllTeachers,
|
||||
fetchDepartmentSubjects,
|
||||
fetchDepartmentSubjectCalendar,
|
||||
fetchDepartmentTeacherRequests,
|
||||
fetchDepartmentTeachers,
|
||||
fetchDepartments,
|
||||
fetchSemesters,
|
||||
fetchSubjectComments,
|
||||
fetchTeacherWorkload,
|
||||
filterDepartmentSubjects,
|
||||
formatDateTime,
|
||||
importSubjects,
|
||||
importSubjectsPayload,
|
||||
listValuesLabel,
|
||||
requestStatusClass,
|
||||
requestStatusLabel,
|
||||
saveSubjectComment,
|
||||
subjectAttachmentGroups,
|
||||
subjectCountLabel,
|
||||
submitTeacherRequest,
|
||||
teacherMetrics,
|
||||
teacherOptionLabel,
|
||||
teacherRequestPayload,
|
||||
uniqueAttachmentValues,
|
||||
workloadLabel
|
||||
} from '../department-workspace-service.js';
|
||||
|
||||
@@ -53,6 +60,7 @@ export function DepartmentWorkspaceTab() {
|
||||
const [workspaceAlert, setWorkspaceAlert] = useState({ text: '', isError: false });
|
||||
|
||||
const [subjects, setSubjects] = useState({ loading: true, items: [], error: '' });
|
||||
const [subjectFilter, setSubjectFilter] = useState(SUBJECT_CALENDAR_FILTER_ALL);
|
||||
const [teachers, setTeachers] = useState({ items: null, error: '' });
|
||||
const [workload, setWorkload] = useState({ items: null, error: '' });
|
||||
const [requests, setRequests] = useState({ items: null, error: '' });
|
||||
@@ -134,7 +142,7 @@ export function DepartmentWorkspaceTab() {
|
||||
async function loadSubjects() {
|
||||
setSubjects({ loading: true, items: [], error: '' });
|
||||
try {
|
||||
const items = await fetchDepartmentSubjects(currentDepartmentId());
|
||||
const items = await fetchDepartmentSubjectCalendar(currentDepartmentId());
|
||||
setSubjects({ loading: false, items: Array.isArray(items) ? items : [], error: '' });
|
||||
} catch (error) {
|
||||
setSubjects({ loading: false, items: [], error: error.message || 'Ошибка загрузки дисциплин' });
|
||||
@@ -334,9 +342,10 @@ export function DepartmentWorkspaceTab() {
|
||||
const requestsCountLabel = requests.error
|
||||
? '0 заявок'
|
||||
: (requests.items === null ? 'Загрузка...' : requestCountLabel(requests.items.length));
|
||||
const visibleSubjects = subjects.error || subjects.loading ? [] : filterDepartmentSubjects(subjects.items, subjectFilter);
|
||||
const subjectsCountLabel = subjects.error
|
||||
? '0 дисциплин'
|
||||
: (subjects.loading ? 'Загрузка...' : subjectCountLabel(subjects.items.length));
|
||||
: (subjects.loading ? 'Загрузка...' : subjectCountLabel(visibleSubjects.length));
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -666,6 +675,20 @@ export function DepartmentWorkspaceTab() {
|
||||
<div className="card-header-row">
|
||||
<h2>Дисциплины кафедры</h2>
|
||||
<span className="muted" id="department-subject-count">{subjectsCountLabel}</span>
|
||||
<div className="form-group form-group--flush" id="department-subject-filter-field">
|
||||
<label className="schedule-section-label schedule-section-label--flush" htmlFor="department-subject-filter">
|
||||
Показывать
|
||||
</label>
|
||||
<select
|
||||
id="department-subject-filter"
|
||||
value={subjectFilter}
|
||||
onChange={event => setSubjectFilter(event.target.value)}
|
||||
>
|
||||
{SUBJECT_CALENDAR_FILTER_OPTIONS.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
@@ -673,7 +696,10 @@ export function DepartmentWorkspaceTab() {
|
||||
<tr>
|
||||
<th>Код</th>
|
||||
<th>Название</th>
|
||||
<th>Описание</th>
|
||||
<th>Шифр</th>
|
||||
<th>Профиль</th>
|
||||
<th>Вид нагрузки</th>
|
||||
<th>Календарный график</th>
|
||||
<th>Комментарии</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -690,86 +716,119 @@ export function DepartmentWorkspaceTab() {
|
||||
{subjects.error}
|
||||
</td>
|
||||
</tr>
|
||||
) : subjects.items.length === 0 ? (
|
||||
) : visibleSubjects.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={SUBJECT_TABLE_COLUMNS} className="loading-row">
|
||||
Дисциплины не найдены
|
||||
</td>
|
||||
</tr>
|
||||
) : subjects.items.map(subject => (
|
||||
<tr key={subject.id}>
|
||||
<td>{subject.code || '-'}</td>
|
||||
<td>{subject.name || '-'}</td>
|
||||
<td>{subject.description || '-'}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-secondary department-comments-open"
|
||||
onClick={() => void openComments(subject.id, subject.name || '')}
|
||||
>
|
||||
Открыть
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
) : visibleSubjects.map(subject => {
|
||||
const attachmentGroups = subjectAttachmentGroups(subject.attachments);
|
||||
const specialtyCode = listValuesLabel(uniqueAttachmentValues(subject.attachments, 'specialtyCode'));
|
||||
const specialtyProfile = listValuesLabel(uniqueAttachmentValues(subject.attachments, 'specialtyProfileName'));
|
||||
const lessonTypes = listValuesLabel(subject.lessonTypes);
|
||||
return (
|
||||
<Fragment key={subject.id}>
|
||||
<tr>
|
||||
<td>{subject.code || '-'}</td>
|
||||
<td>{subject.name || '-'}</td>
|
||||
<td>{specialtyCode || '-'}</td>
|
||||
<td>{specialtyProfile || '-'}</td>
|
||||
<td>{lessonTypes || '-'}</td>
|
||||
<td>
|
||||
{attachmentGroups.length === 0 ? (
|
||||
<span className="text-muted">Не прикреплена к графику</span>
|
||||
) : attachmentGroups.length === 1 ? (
|
||||
<span>{attachmentGroupLabel(attachmentGroups[0])}</span>
|
||||
) : (
|
||||
<select
|
||||
className="department-subject-calendar-select"
|
||||
data-native-select="true"
|
||||
aria-label="Календарные графики дисциплины"
|
||||
defaultValue={String(attachmentGroups[0].calendarId)}
|
||||
>
|
||||
{attachmentGroups.map(group => (
|
||||
<option key={group.calendarId} value={String(group.calendarId)}>
|
||||
{attachmentGroupLabel(group)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-secondary department-comments-open"
|
||||
onClick={() => void openComments(subject.id, subject.name || '')}
|
||||
>
|
||||
Открыть
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{comments && comments.subjectId === subject.id && (
|
||||
<tr className="department-comments-row" id="department-comments-row">
|
||||
<td colSpan={SUBJECT_TABLE_COLUMNS}>
|
||||
<div className="department-comments-card" id="department-comments-card">
|
||||
<div className="card-header-row">
|
||||
<h3 id="department-comments-title">
|
||||
Комментарии: {comments.subjectName || 'дисциплина'}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
id="department-comments-close"
|
||||
onClick={() => setComments(null)}
|
||||
>
|
||||
Скрыть
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form id="department-comment-form" className="form-row" onSubmit={submitComment}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="department-comment-text">Новый комментарий</label>
|
||||
<input
|
||||
type="text"
|
||||
id="department-comment-text"
|
||||
placeholder="Добавьте примечание по дисциплине"
|
||||
value={commentText}
|
||||
onChange={event => setCommentText(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="btn btn-md btn-primary">Сохранить</button>
|
||||
</form>
|
||||
<div
|
||||
className={`form-alert${commentAlert.text ? (commentAlert.isError ? ' error' : ' success') : ''}`}
|
||||
id="department-comment-alert"
|
||||
role="alert"
|
||||
>
|
||||
{commentAlert.text}
|
||||
</div>
|
||||
<div className="department-comment-list" id="department-comment-list">
|
||||
{comments.items === null ? (
|
||||
'Загрузка...'
|
||||
) : comments.error ? (
|
||||
<div className="loading-row">{comments.error}</div>
|
||||
) : comments.items.length === 0 ? (
|
||||
<div className="loading-row">Комментариев пока нет</div>
|
||||
) : comments.items.map((comment, index) => (
|
||||
<article className="department-comment-item" key={index}>
|
||||
<strong>{comment.authorName || 'Автор не указан'}</strong>
|
||||
<span>{formatDateTime(comment.createdAt)}</span>
|
||||
<p>{comment.comment}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{comments && (
|
||||
<div className="card department-workspace-table-card" id="department-comments-card">
|
||||
<div className="card-header-row">
|
||||
<h2 id="department-comments-title">
|
||||
Комментарии: {comments.subjectName || 'дисциплина'}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
id="department-comments-close"
|
||||
onClick={() => setComments(null)}
|
||||
>
|
||||
Скрыть
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form id="department-comment-form" className="form-row" onSubmit={submitComment}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="department-comment-text">Новый комментарий</label>
|
||||
<input
|
||||
type="text"
|
||||
id="department-comment-text"
|
||||
placeholder="Добавьте примечание по дисциплине"
|
||||
value={commentText}
|
||||
onChange={event => setCommentText(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="btn btn-md btn-primary">Сохранить</button>
|
||||
</form>
|
||||
<div
|
||||
className={`form-alert${commentAlert.text ? (commentAlert.isError ? ' error' : ' success') : ''}`}
|
||||
id="department-comment-alert"
|
||||
role="alert"
|
||||
>
|
||||
{commentAlert.text}
|
||||
</div>
|
||||
<div className="department-comment-list" id="department-comment-list">
|
||||
{comments.items === null ? (
|
||||
'Загрузка...'
|
||||
) : comments.error ? (
|
||||
<div className="loading-row">{comments.error}</div>
|
||||
) : comments.items.length === 0 ? (
|
||||
<div className="loading-row">Комментариев пока нет</div>
|
||||
) : comments.items.map((comment, index) => (
|
||||
<article className="department-comment-item" key={index}>
|
||||
<strong>{comment.authorName || 'Автор не указан'}</strong>
|
||||
<span>{formatDateTime(comment.createdAt)}</span>
|
||||
<p>{comment.comment}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -53,6 +53,14 @@ test('заголовок вкладки соответствует констр
|
||||
assert.match(adminService, /schedule:\s*\{\s*title:\s*'Конструктор правил'/);
|
||||
});
|
||||
|
||||
test('селект графиков дисциплины кафедры не дублируется кастомным дропдауном', async () => {
|
||||
const tab = await readFrontendFile('react/admin/tabs/DepartmentWorkspaceTab.jsx');
|
||||
const selectIndex = tab.indexOf('department-subject-calendar-select');
|
||||
assert.ok(selectIndex > -1, 'селект графиков должен быть в таблице дисциплин');
|
||||
// без data-native-select="true" dropdown.js рисует рядом второй список
|
||||
assert.match(tab.slice(selectIndex, selectIndex + 200), /data-native-select="true"/);
|
||||
});
|
||||
|
||||
test('основная кнопка показа находится в заголовке блока параметров', async () => {
|
||||
const scheduleViewTab = await readFrontendFile('react/admin/tabs/ScheduleViewTab.jsx');
|
||||
const controlHeaderIndex = scheduleViewTab.indexOf('schedule-view-control-header');
|
||||
|
||||
@@ -112,25 +112,33 @@ import {
|
||||
import {
|
||||
assignTeacher as assignTeacherToDepartment,
|
||||
assignTeacherError,
|
||||
attachmentGroupLabel,
|
||||
availableTeachers,
|
||||
departmentSubjectCalendarEndpoint,
|
||||
departmentSubjectsEndpoint,
|
||||
departmentTeacherRequestsEndpoint,
|
||||
departmentTeachersEndpoint,
|
||||
fetchDepartmentSubjectCalendar,
|
||||
fetchDepartmentSubjects,
|
||||
fetchDepartmentTeacherRequests,
|
||||
fetchDepartmentTeachers,
|
||||
fetchTeacherWorkload,
|
||||
filterDepartmentSubjects,
|
||||
formatDateTime,
|
||||
importSubjects,
|
||||
importSubjectsPayload,
|
||||
listValuesLabel,
|
||||
requestStatusClass,
|
||||
requestStatusLabel,
|
||||
semesterNumbersLabel,
|
||||
subjectAttachmentGroups,
|
||||
subjectCountLabel,
|
||||
submitTeacherRequest,
|
||||
teacherMetrics,
|
||||
teacherOptionLabel,
|
||||
teacherRequestPayload,
|
||||
teacherWorkloadEndpoint,
|
||||
uniqueAttachmentValues,
|
||||
workloadLabel
|
||||
} from '../react/admin/department-workspace-service.js';
|
||||
import {
|
||||
@@ -1259,6 +1267,8 @@ test('вкладка заявок рендерит реестр с фильтр
|
||||
test('эндпоинты кабинета кафедры совпадают с legacy-контрактами', () => {
|
||||
assert.equal(departmentSubjectsEndpoint(4), '/api/department/subjects?departmentId=4');
|
||||
assert.equal(departmentSubjectsEndpoint(''), '/api/department/subjects?departmentId=');
|
||||
assert.equal(departmentSubjectCalendarEndpoint(4), '/api/department/subjects/calendar?departmentId=4');
|
||||
assert.equal(departmentSubjectCalendarEndpoint(''), '/api/department/subjects/calendar?departmentId=');
|
||||
assert.equal(departmentTeachersEndpoint(4), '/api/department/teachers?departmentId=4');
|
||||
assert.equal(departmentTeacherRequestsEndpoint(4), '/api/department/teacher-requests?departmentId=4');
|
||||
assert.equal(
|
||||
@@ -1305,8 +1315,12 @@ test('контракты API кабинета кафедры сохранены'
|
||||
await fetchDepartmentSubjects(4, client);
|
||||
assert.equal(client.calls[0].endpoint, '/api/department/subjects?departmentId=4');
|
||||
|
||||
await fetchDepartmentSubjectCalendar(4, client);
|
||||
assert.equal(client.calls[1].endpoint, '/api/department/subjects/calendar?departmentId=4');
|
||||
assert.ok(client.calls[1].options.errorMessage);
|
||||
|
||||
await importSubjects([{ code: 'DB201', name: 'Базы данных', departmentId: 4 }], client);
|
||||
assert.deepEqual(client.calls[1], {
|
||||
assert.deepEqual(client.calls[2], {
|
||||
method: 'POST',
|
||||
endpoint: '/api/department/subjects/import',
|
||||
json: [{ code: 'DB201', name: 'Базы данных', departmentId: 4 }],
|
||||
@@ -1314,10 +1328,10 @@ test('контракты API кабинета кафедры сохранены'
|
||||
});
|
||||
|
||||
await fetchDepartmentTeachers(4, client);
|
||||
assert.equal(client.calls[2].endpoint, '/api/department/teachers?departmentId=4');
|
||||
assert.equal(client.calls[3].endpoint, '/api/department/teachers?departmentId=4');
|
||||
|
||||
await assignTeacherToDepartment(5, '4', '', client);
|
||||
assert.deepEqual(client.calls[3], {
|
||||
assert.deepEqual(client.calls[4], {
|
||||
method: 'POST',
|
||||
endpoint: '/api/department/teachers/5/assignments',
|
||||
json: { departmentId: 4, comment: null },
|
||||
@@ -1325,13 +1339,13 @@ test('контракты API кабинета кафедры сохранены'
|
||||
});
|
||||
|
||||
await fetchTeacherWorkload({ startDate: '2026-09-01', endDate: '2026-09-14', departmentId: '4' }, client);
|
||||
assert.equal(client.calls[4].endpoint, '/api/workload/teachers?startDate=2026-09-01&endDate=2026-09-14&departmentId=4');
|
||||
assert.equal(client.calls[5].endpoint, '/api/workload/teachers?startDate=2026-09-01&endDate=2026-09-14&departmentId=4');
|
||||
|
||||
await fetchDepartmentTeacherRequests(4, client);
|
||||
assert.equal(client.calls[5].endpoint, '/api/department/teacher-requests?departmentId=4');
|
||||
assert.equal(client.calls[6].endpoint, '/api/department/teacher-requests?departmentId=4');
|
||||
|
||||
await submitTeacherRequest({ departmentId: 4, username: 'ivanov', fullName: 'Иванов', jobTitle: '', comment: '' }, client);
|
||||
assert.deepEqual(client.calls[6], {
|
||||
assert.deepEqual(client.calls[7], {
|
||||
method: 'POST',
|
||||
endpoint: '/api/department/teacher-requests',
|
||||
json: { departmentId: 4, username: 'ivanov', fullName: 'Иванов', jobTitle: '', comment: '' },
|
||||
@@ -1416,12 +1430,88 @@ test('вкладка кабинета кафедры рендерит формы
|
||||
assert.match(markup, /id="department-teacher-requests-tbody"/);
|
||||
assert.match(markup, /Дисциплины кафедры/);
|
||||
assert.match(markup, /id="department-subjects-tbody"/);
|
||||
assert.match(markup, /id="department-subject-filter"/);
|
||||
assert.match(markup, /Все дисциплины/);
|
||||
assert.match(markup, /В календарных графиках/);
|
||||
assert.match(markup, /Без графика/);
|
||||
assert.match(markup, /Шифр/);
|
||||
assert.match(markup, /Профиль/);
|
||||
assert.match(markup, /Вид нагрузки/);
|
||||
assert.match(markup, /Календарный график/);
|
||||
assert.match(markup, /Загрузка\.\.\./);
|
||||
assert.doesNotMatch(markup, /style="/);
|
||||
// карточка комментариев скрыта до выбора дисциплины
|
||||
assert.doesNotMatch(markup, /department-comments-card/);
|
||||
});
|
||||
|
||||
test('дисциплины кафедры фильтруются по прикреплению к графикам', () => {
|
||||
const items = [
|
||||
{ id: 1, name: 'Базы данных', attachments: [{ calendarId: 2, semesterNumber: 3 }] },
|
||||
{ id: 2, name: 'Криптография', attachments: [] },
|
||||
{ id: 3, name: 'Математика', attachments: [{ calendarId: 2, semesterNumber: 1 }, { calendarId: 5, semesterNumber: 5 }] }
|
||||
];
|
||||
|
||||
assert.equal(filterDepartmentSubjects(items, 'all').length, 3);
|
||||
assert.equal(filterDepartmentSubjects(items, 'calendar').length, 2);
|
||||
assert.deepEqual(
|
||||
filterDepartmentSubjects(items, 'manual').map(item => item.name),
|
||||
['Криптография']
|
||||
);
|
||||
// неизвестный фильтр показывает всё
|
||||
assert.equal(filterDepartmentSubjects(items, 'unknown').length, 3);
|
||||
assert.deepEqual(filterDepartmentSubjects(null, 'calendar'), []);
|
||||
});
|
||||
|
||||
test('прикрепления дисциплины группируются по графику с перечнем семестров', () => {
|
||||
const attachments = [
|
||||
{ calendarId: 2, calendarTitle: '2026/2027 · 10.03.01 ИБ', academicYearTitle: '2026/2027', semesterNumber: 3 },
|
||||
{ calendarId: 2, calendarTitle: '2026/2027 · 10.03.01 ИБ', academicYearTitle: '2026/2027', semesterNumber: 1 },
|
||||
{ calendarId: 5, calendarTitle: '2027/2028 · 10.03.01 ИБ', academicYearTitle: '2027/2028', semesterNumber: 5 },
|
||||
{ calendarId: 2, calendarTitle: '2026/2027 · 10.03.01 ИБ', academicYearTitle: '2026/2027', semesterNumber: 3 }
|
||||
];
|
||||
|
||||
const groups = subjectAttachmentGroups(attachments);
|
||||
assert.equal(groups.length, 2);
|
||||
assert.deepEqual(groups[0].semesterNumbers, [1, 3]);
|
||||
assert.equal(groups[0].calendarTitle, '2026/2027 · 10.03.01 ИБ');
|
||||
assert.deepEqual(groups[1].semesterNumbers, [5]);
|
||||
|
||||
assert.equal(semesterNumbersLabel([3, 1]), '1 семестр, 3 семестр');
|
||||
assert.equal(semesterNumbersLabel([]), '');
|
||||
assert.equal(
|
||||
attachmentGroupLabel(groups[0]),
|
||||
'2026/2027 · 10.03.01 ИБ — 1 семестр, 3 семестр'
|
||||
);
|
||||
assert.deepEqual(subjectAttachmentGroups(null), []);
|
||||
assert.deepEqual(subjectAttachmentGroups([]), []);
|
||||
});
|
||||
|
||||
test('сводные колонки дисциплин собирают уникальные шифры и профили', () => {
|
||||
const attachments = [
|
||||
{ calendarId: 2, specialtyCode: '10.03.01', specialtyProfileName: 'Без профиля' },
|
||||
{ calendarId: 5, specialtyCode: '09.03.01', specialtyProfileName: 'Без профиля' },
|
||||
{ calendarId: 2, specialtyCode: '10.03.01', specialtyProfileName: 'Без профиля' }
|
||||
];
|
||||
|
||||
assert.deepEqual(
|
||||
uniqueAttachmentValues(attachments, 'specialtyCode'),
|
||||
['09.03.01', '10.03.01']
|
||||
);
|
||||
assert.deepEqual(
|
||||
uniqueAttachmentValues(attachments, 'specialtyProfileName'),
|
||||
['Без профиля']
|
||||
);
|
||||
assert.equal(listValuesLabel(uniqueAttachmentValues(attachments, 'specialtyCode')), '09.03.01, 10.03.01');
|
||||
assert.equal(listValuesLabel(uniqueAttachmentValues(attachments, 'specialtyProfileName')), 'Без профиля');
|
||||
// без прикреплений колонки пустые
|
||||
assert.deepEqual(uniqueAttachmentValues([], 'specialtyCode'), []);
|
||||
assert.deepEqual(uniqueAttachmentValues(null, 'specialtyCode'), []);
|
||||
assert.equal(listValuesLabel([]), '');
|
||||
assert.equal(listValuesLabel(null), '');
|
||||
// виды нагрузки дисциплины выводятся списком через запятую
|
||||
assert.equal(listValuesLabel(['Лекции', 'Лабораторные занятия']), 'Лекции, Лабораторные занятия');
|
||||
});
|
||||
|
||||
test('двухнедельный период загруженности считается по локальному времени', () => {
|
||||
assert.deepEqual(twoWeekRange('2026-09-28'), { startDate: '2026-09-28', endDate: '2026-10-11' });
|
||||
// среда 30.09 — период всё равно начинается с понедельника
|
||||
|
||||
Reference in new issue
Block a user