feat: дисциплины кафедры из календарных графиков

Дисциплины, прикреплённые к календарным графикам, автоматически
отображаются на странице кафедры — ручное ведение списка больше
не требуется (форма импорта сохранена).

- Backend: GET /api/department/subjects/calendar — дисциплины кафедры
  с прикреплениями к графикам (дисциплина попадает на страницу своей
  кафедры по subjects.department_id)
- Frontend: кабинет кафедры — колонка «Календарный график» с семестрами,
  фильтр «Все / В календарных графиках / Без графика»
- Тесты: backend (группировка, сортировка, пустая кафедра), frontend
  (контракт, фильтр, группировка семестров) — 239/239
- Документация: API.md, BUSINESS_LOGIC.md
This commit is contained in:
dipatrik10 committed 2026-10-04 18:52:24 +03:00
1 parent 97bf3cc50a
commit 91f44c85b4
11 files changed
+401 -18

No files matched your search

@@ -4,10 +4,12 @@ import com.magistr.app.config.auth.AuthContext;
import com.magistr.app.config.auth.RequireRoles; import com.magistr.app.config.auth.RequireRoles;
import com.magistr.app.dto.CreateTeacherCreationRequest; import com.magistr.app.dto.CreateTeacherCreationRequest;
import com.magistr.app.dto.CreateSubjectRequest; import com.magistr.app.dto.CreateSubjectRequest;
import com.magistr.app.dto.DepartmentCalendarSubjectDto;
import com.magistr.app.dto.SubjectCommentDto; import com.magistr.app.dto.SubjectCommentDto;
import com.magistr.app.dto.TeacherCreationRequestResponse; import com.magistr.app.dto.TeacherCreationRequestResponse;
import com.magistr.app.dto.UserResponse; import com.magistr.app.dto.UserResponse;
import com.magistr.app.model.*; import com.magistr.app.model.*;
import com.magistr.app.repository.AcademicCalendarSubjectRepository;
import com.magistr.app.repository.DepartmentRepository; import com.magistr.app.repository.DepartmentRepository;
import com.magistr.app.repository.SubjectCommentRepository; import com.magistr.app.repository.SubjectCommentRepository;
import com.magistr.app.repository.SubjectRepository; import com.magistr.app.repository.SubjectRepository;
@@ -29,6 +31,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
@RestController @RestController
@RequestMapping("/api/department") @RequestMapping("/api/department")
@@ -43,6 +46,7 @@ public class DepartmentWorkspaceController {
private final DepartmentRepository departmentRepository; private final DepartmentRepository departmentRepository;
private final TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository; private final TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository;
private final TeacherCreationRequestRepository teacherCreationRequestRepository; private final TeacherCreationRequestRepository teacherCreationRequestRepository;
private final AcademicCalendarSubjectRepository calendarSubjectRepository;
private final ScheduleQueryService scheduleQueryService; private final ScheduleQueryService scheduleQueryService;
private final TeacherDepartmentService teacherDepartmentService; private final TeacherDepartmentService teacherDepartmentService;
private final SubjectImportService subjectImportService; private final SubjectImportService subjectImportService;
@@ -54,12 +58,14 @@ public class DepartmentWorkspaceController {
DepartmentRepository departmentRepository, DepartmentRepository departmentRepository,
TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository, TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository,
TeacherCreationRequestRepository teacherCreationRequestRepository, TeacherCreationRequestRepository teacherCreationRequestRepository,
AcademicCalendarSubjectRepository calendarSubjectRepository,
ScheduleQueryService scheduleQueryService, ScheduleQueryService scheduleQueryService,
TeacherDepartmentService teacherDepartmentService, TeacherDepartmentService teacherDepartmentService,
SubjectImportService subjectImportService) { SubjectImportService subjectImportService) {
this(subjectRepository, subjectCommentRepository, userRepository, departmentRepository, this(subjectRepository, subjectCommentRepository, userRepository, departmentRepository,
teacherDepartmentAssignmentRepository, teacherCreationRequestRepository, teacherDepartmentAssignmentRepository, teacherCreationRequestRepository,
scheduleQueryService, teacherDepartmentService, subjectImportService, calendarSubjectRepository, scheduleQueryService, teacherDepartmentService,
subjectImportService,
BusinessTimeService.systemDefault()); BusinessTimeService.systemDefault());
} }
@@ -70,6 +76,7 @@ public class DepartmentWorkspaceController {
DepartmentRepository departmentRepository, DepartmentRepository departmentRepository,
TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository, TeacherDepartmentAssignmentRepository teacherDepartmentAssignmentRepository,
TeacherCreationRequestRepository teacherCreationRequestRepository, TeacherCreationRequestRepository teacherCreationRequestRepository,
AcademicCalendarSubjectRepository calendarSubjectRepository,
ScheduleQueryService scheduleQueryService, ScheduleQueryService scheduleQueryService,
TeacherDepartmentService teacherDepartmentService, TeacherDepartmentService teacherDepartmentService,
SubjectImportService subjectImportService, SubjectImportService subjectImportService,
@@ -80,6 +87,7 @@ public class DepartmentWorkspaceController {
this.departmentRepository = departmentRepository; this.departmentRepository = departmentRepository;
this.teacherDepartmentAssignmentRepository = teacherDepartmentAssignmentRepository; this.teacherDepartmentAssignmentRepository = teacherDepartmentAssignmentRepository;
this.teacherCreationRequestRepository = teacherCreationRequestRepository; this.teacherCreationRequestRepository = teacherCreationRequestRepository;
this.calendarSubjectRepository = calendarSubjectRepository;
this.scheduleQueryService = scheduleQueryService; this.scheduleQueryService = scheduleQueryService;
this.teacherDepartmentService = teacherDepartmentService; this.teacherDepartmentService = teacherDepartmentService;
this.subjectImportService = subjectImportService; this.subjectImportService = subjectImportService;
@@ -113,6 +121,66 @@ 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())
));
return subjects.stream()
.map(subject -> toDepartmentCalendarSubjectDto(subject, attachmentsBySubject))
.toList();
}
private DepartmentCalendarSubjectDto toDepartmentCalendarSubjectDto(
Subject subject,
Map<Long, List<DepartmentCalendarSubjectDto.CalendarAttachmentDto>> attachmentsBySubject) {
return new DepartmentCalendarSubjectDto(
subject.getId(),
subject.getCode(),
subject.getName(),
subject.getDepartmentId(),
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(),
academicYear == null ? null : academicYear.getId(),
academicYear == null ? null : academicYear.getTitle(),
calendarSubject.getSemesterNumber()
);
}
@GetMapping("/subjects/{subjectId}/comments") @GetMapping("/subjects/{subjectId}/comments")
public ResponseEntity<?> getComments(@PathVariable Long subjectId) { public ResponseEntity<?> getComments(@PathVariable Long subjectId) {
Subject subject = subjectRepository.findById(subjectId).orElse(null); Subject subject = subjectRepository.findById(subjectId).orElse(null);
@@ -0,0 +1,26 @@
package com.magistr.app.dto;
import java.util.List;
/**
* Дисциплина кафедры вместе с прикреплениями к календарным графикам.
* Прикрепления приходят из academic_calendar_subjects: дисциплина попадает
* на страницу той кафедры, за которой она закреплена в справочнике.
*/
public record DepartmentCalendarSubjectDto(
Long id,
String code,
String name,
Long departmentId,
List<CalendarAttachmentDto> attachments
) {
public record CalendarAttachmentDto(
Long calendarId,
String calendarTitle,
Long academicYearId,
String academicYearTitle,
Integer semesterNumber
) {
}
}
@@ -24,12 +24,27 @@ public interface AcademicCalendarSubjectRepository extends JpaRepository<Academi
select calendarSubject select calendarSubject
from AcademicCalendarSubject calendarSubject from AcademicCalendarSubject calendarSubject
join fetch calendarSubject.academicCalendar calendar join fetch calendarSubject.academicCalendar calendar
join fetch calendar.academicYear academicYear
join fetch calendarSubject.subject subject join fetch calendarSubject.subject subject
where calendar.id in :calendarIds where calendar.id in :calendarIds
order by calendar.id asc, calendarSubject.semesterNumber asc, lower(subject.name) asc order by calendar.id asc, calendarSubject.semesterNumber asc, lower(subject.name) asc
""") """)
List<AcademicCalendarSubject> findByCalendarIdInWithSubject(@Param("calendarIds") Collection<Long> calendarIds); List<AcademicCalendarSubject> findByCalendarIdInWithSubject(@Param("calendarIds") Collection<Long> calendarIds);
// Дисциплины кафедры, прикреплённые к календарным графикам: попадают
// на страницу кафедры через принадлежность самой дисциплины кафедре.
@Query("""
select calendarSubject
from AcademicCalendarSubject calendarSubject
join fetch calendarSubject.academicCalendar calendar
join fetch calendar.academicYear academicYear
join fetch calendarSubject.subject subject
where subject.departmentId = :departmentId
and subject.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); void deleteByAcademicCalendar_Id(Long calendarId);
boolean existsByAcademicCalendarIdAndSemesterNumberGreaterThan(Long calendarId, Integer semesterNumber); boolean existsByAcademicCalendarIdAndSemesterNumberGreaterThan(Long calendarId, Integer semesterNumber);
@@ -2,13 +2,18 @@ package com.magistr.app.controller;
import com.magistr.app.config.auth.AuthContext; import com.magistr.app.config.auth.AuthContext;
import com.magistr.app.config.auth.AuthenticatedUser; import com.magistr.app.config.auth.AuthenticatedUser;
import com.magistr.app.dto.DepartmentCalendarSubjectDto;
import com.magistr.app.dto.UserResponse; 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.Department;
import com.magistr.app.model.LifecycleEntity; import com.magistr.app.model.LifecycleEntity;
import com.magistr.app.model.Role; import com.magistr.app.model.Role;
import com.magistr.app.model.Subject; import com.magistr.app.model.Subject;
import com.magistr.app.model.TeacherDepartmentAssignment; import com.magistr.app.model.TeacherDepartmentAssignment;
import com.magistr.app.model.User; import com.magistr.app.model.User;
import com.magistr.app.repository.AcademicCalendarSubjectRepository;
import com.magistr.app.repository.SubjectCommentRepository; import com.magistr.app.repository.SubjectCommentRepository;
import com.magistr.app.repository.SubjectRepository; import com.magistr.app.repository.SubjectRepository;
import com.magistr.app.repository.DepartmentRepository; import com.magistr.app.repository.DepartmentRepository;
@@ -63,6 +68,7 @@ class DepartmentWorkspaceControllerTest {
mock(DepartmentRepository.class), mock(DepartmentRepository.class),
mock(TeacherDepartmentAssignmentRepository.class), mock(TeacherDepartmentAssignmentRepository.class),
mock(TeacherCreationRequestRepository.class), mock(TeacherCreationRequestRepository.class),
mock(AcademicCalendarSubjectRepository.class),
mock(ScheduleQueryService.class), mock(ScheduleQueryService.class),
mock(TeacherDepartmentService.class), mock(TeacherDepartmentService.class),
mock(SubjectImportService.class) mock(SubjectImportService.class)
@@ -90,6 +96,7 @@ class DepartmentWorkspaceControllerTest {
mock(DepartmentRepository.class), mock(DepartmentRepository.class),
assignmentRepository, assignmentRepository,
mock(TeacherCreationRequestRepository.class), mock(TeacherCreationRequestRepository.class),
mock(AcademicCalendarSubjectRepository.class),
mock(ScheduleQueryService.class), mock(ScheduleQueryService.class),
teacherDepartmentService, teacherDepartmentService,
mock(SubjectImportService.class), mock(SubjectImportService.class),
@@ -119,6 +126,7 @@ class DepartmentWorkspaceControllerTest {
departmentRepository, departmentRepository,
assignmentRepository, assignmentRepository,
mock(TeacherCreationRequestRepository.class), mock(TeacherCreationRequestRepository.class),
mock(AcademicCalendarSubjectRepository.class),
mock(ScheduleQueryService.class), mock(ScheduleQueryService.class),
mock(TeacherDepartmentService.class), mock(TeacherDepartmentService.class),
mock(SubjectImportService.class) mock(SubjectImportService.class)
@@ -137,6 +145,78 @@ class DepartmentWorkspaceControllerTest {
assertThat(saved.getCreatedBy()).isEqualTo(3L); assertThat(saved.getCreatedBy()).isEqualTo(3L);
} }
@Test
void subjectCalendarAttachmentsSortByNameAndGroupAttachments() {
SubjectRepository subjectRepository = mock(SubjectRepository.class);
AcademicCalendarSubjectRepository calendarSubjectRepository = mock(AcademicCalendarSubjectRepository.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));
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);
AcademicCalendarSubject link = new AcademicCalendarSubject();
link.setAcademicCalendar(calendar);
link.setSemesterNumber(3);
link.setSubject(databases);
when(calendarSubjectRepository.findBySubjectDepartmentId(1L)).thenReturn(List.of(link));
DepartmentWorkspaceController controller = new DepartmentWorkspaceController(
subjectRepository,
mock(SubjectCommentRepository.class),
mock(UserRepository.class),
mock(DepartmentRepository.class),
mock(TeacherDepartmentAssignmentRepository.class),
mock(TeacherCreationRequestRepository.class),
calendarSubjectRepository,
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.academicYearTitle()).isEqualTo("2026/2027");
assertThat(attachment.semesterNumber()).isEqualTo(3);
// дисциплина без прикреплений получает пустой список, а не null
assertThat(result.get(1).attachments()).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(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) { private TeacherDepartmentAssignment assignment(User teacher, Long departmentId) {
Department department = new Department(departmentId, "Кафедра", departmentId); Department department = new Department(departmentId, "Кафедра", departmentId);
TeacherDepartmentAssignment assignment = new TeacherDepartmentAssignment(); TeacherDepartmentAssignment assignment = new TeacherDepartmentAssignment();
+28
View File
@@ -1250,6 +1250,7 @@ GET /api/workload/teachers?departmentId=1&startDate=2026-05-20&endDate=2026-06-0
| Метод | URL | Назначение | | Метод | URL | Назначение |
|-------|-----|------------| |-------|-----|------------|
| `GET` | `/api/department/subjects` | Дисциплины текущей кафедры | | `GET` | `/api/department/subjects` | Дисциплины текущей кафедры |
| `GET` | `/api/department/subjects/calendar` | Дисциплины кафедры с прикреплениями к календарным графикам |
| `POST` | `/api/department/subjects/import` | Загрузка списка дисциплин | | `POST` | `/api/department/subjects/import` | Загрузка списка дисциплин |
| `GET` | `/api/department/subjects/{subjectId}/comments` | Комментарии дисциплины | | `GET` | `/api/department/subjects/{subjectId}/comments` | Комментарии дисциплины |
| `POST` | `/api/department/subjects/{subjectId}/comments` | Добавить комментарий | | `POST` | `/api/department/subjects/{subjectId}/comments` | Добавить комментарий |
@@ -1265,6 +1266,33 @@ GET /api/workload/teachers?departmentId=1&startDate=2026-05-20&endDate=2026-06-0
API возвращает `409 Conflict`; владелец записи не изменяется. Повторы одного названия внутри API возвращает `409 Conflict`; владелец записи не изменяется. Повторы одного названия внутри
payload обрабатываются один раз, используется последнее значение. payload обрабатываются один раз, используется последнее значение.
`GET /api/department/subjects/calendar` возвращает дисциплины кафедры (не архивные,
отсортированные по названию) вместе с прикреплениями к календарным графикам из
`academic_calendar_subjects`. Дисциплина попадает в список той кафедры, за которой она
закреплена в справочнике (`subjects.department_id`). Роль `DEPARTMENT` видит только свою
кафедру, `ADMIN` может передать `departmentId`. Элемент `attachments` может быть пустым —
такая дисциплина на странице кафедры помечается «Не прикреплена к графику».
```json
[
{
"id": 10,
"code": "DB201",
"name": "Базы данных",
"departmentId": 1,
"attachments": [
{
"calendarId": 2,
"calendarTitle": "2026/2027 · 10.03.01 Информационная безопасность · Очная",
"academicYearId": 1,
"academicYearTitle": "2026/2027",
"semesterNumber": 3
}
]
}
]
```
`GET /api/department/teachers` возвращает актуальных преподавателей кафедры только по `GET /api/department/teachers` возвращает актуальных преподавателей кафедры только по
`teacher_department_assignments`. Основные и дополнительные назначения учитываются на `teacher_department_assignments`. Основные и дополнительные назначения учитываются на
текущую дату; архивные и ещё не начавшиеся назначения исключаются. текущую дату; архивные и ещё не начавшиеся назначения исключаются.
+4
View File
@@ -96,6 +96,10 @@ Bearer-токен проверяется на backend. Frontend-скрытие
- Кафедра может добавлять комментарии к дисциплине и загружать список дисциплин через кабинет кафедры - Кафедра может добавлять комментарии к дисциплине и загружать список дисциплин через кабинет кафедры
- Повторный импорт собственной дисциплины обновляет ту же запись и восстанавливает её из архива - Повторный импорт собственной дисциплины обновляет ту же запись и восстанавливает её из архива
- Совпадение названия с дисциплиной другой кафедры даёт `409 Conflict` и никогда не меняет владельца - Совпадение названия с дисциплиной другой кафедры даёт `409 Conflict` и никогда не меняет владельца
- На странице кафедры дисциплины показываются вместе с прикреплениями к календарным графикам
(`GET /api/department/subjects/calendar`): дисциплина попадает в список той кафедры, за которой
она закреплена в справочнике; прикрепления группируются по графику с перечнем семестров.
Фильтр «В календарных графиках / Без графика» отделяет дисциплины, не входящие ни в один график.
### Жизненный цикл справочников ### Жизненный цикл справочников
+1 -1
View File
@@ -651,7 +651,7 @@ legacy-файл вкладки. Последними (волна 6) — `schedul
загрузка 84 857 байт gzip (лимит 90 000), общие chunk 79 217 байт gzip загрузка 84 857 байт gzip (лимит 90 000), общие chunk 79 217 байт gzip
(лимит 85 000), lazy-вкладки 128 571 байт gzip в 25 chunk'ах (лимит 150 000, (лимит 85 000), lazy-вкладки 128 571 байт gzip в 25 chunk'ах (лимит 150 000,
загружаются по одной) — лимиты не поднимались; загружаются по одной) — лимиты не поднимались;
- `npm run check`: 237 тестов пройдено (обновлены импорты тестов с legacy-модулей - `npm run check`: 239 тестов пройдено (обновлены импорты тестов с legacy-модулей
на React-сервисы, добавлены payload-валидация, DOM-рендер конструктора на React-сервисы, добавлены payload-валидация, DOM-рендер конструктора
и контроль разрешения lazy-вкладок; проверки `LegacyTabView`/`legacy-views` и контроль разрешения lazy-вкладок; проверки `LegacyTabView`/`legacy-views`
заменены на контроль отсутствия legacy-модулей). заменены на контроль отсутствия legacy-модулей).
+2 -2
View File
@@ -53,7 +53,7 @@
### Качество и надёжность ### Качество и надёжность
- **237 тестов** проходят (`npm run check`), против ~170 на момент начала этапа 5: - **239 тестов** проходят (`npm run check`), против ~170 на момент начала этапа 5:
контракты API, payload-валидация, DOM-рендер каждой вкладки, бюджеты bundle, CSP, контракты API, payload-валидация, DOM-рендер каждой вкладки, бюджеты bundle, CSP,
разрешение всех lazy-вкладок (регрессия на React error #306 поймана и закрыта тестом). разрешение всех lazy-вкладок (регрессия на React error #306 поймана и закрыта тестом).
- Логика вынесена в **чистые сервисы** (`*-service.js`) — тестируются в Node без браузера - Логика вынесена в **чистые сервисы** (`*-service.js`) — тестируются в Node без браузера
@@ -97,5 +97,5 @@
cd frontend cd frontend
npm ci npm ci
npm run build npm run build
npm run check # 237/237 тестов, бюджеты, CSP npm run check # 239/239 тестов, бюджеты, CSP
``` ```
@@ -42,6 +42,73 @@ 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 importSubjectsPayload(rows, departmentId) { export function importSubjectsPayload(rows, departmentId) {
if (!departmentId) return { error: 'Выберите кафедру' }; if (!departmentId) return { error: 'Выберите кафедру' };
const payload = (rows || []) const payload = (rows || [])
@@ -5,26 +5,31 @@ import { addDays, toIsoDate } from '../../shared/dates.js';
import { requestCountLabel } from '../admin-service.js'; import { requestCountLabel } from '../admin-service.js';
import { import {
DEPARTMENT_REQUEST_TABLE_COLUMNS, DEPARTMENT_REQUEST_TABLE_COLUMNS,
SUBJECT_CALENDAR_FILTER_ALL,
SUBJECT_CALENDAR_FILTER_OPTIONS,
SUBJECT_TABLE_COLUMNS, SUBJECT_TABLE_COLUMNS,
assignTeacher, assignTeacher,
assignTeacherError, assignTeacherError,
attachmentGroupLabel,
availableTeachers, availableTeachers,
defaultWorkloadPeriod, defaultWorkloadPeriod,
departmentOptionLabel, departmentOptionLabel,
fetchAllTeachers, fetchAllTeachers,
fetchDepartmentSubjects, fetchDepartmentSubjectCalendar,
fetchDepartmentTeacherRequests, fetchDepartmentTeacherRequests,
fetchDepartmentTeachers, fetchDepartmentTeachers,
fetchDepartments, fetchDepartments,
fetchSemesters, fetchSemesters,
fetchSubjectComments, fetchSubjectComments,
fetchTeacherWorkload, fetchTeacherWorkload,
filterDepartmentSubjects,
formatDateTime, formatDateTime,
importSubjects, importSubjects,
importSubjectsPayload, importSubjectsPayload,
requestStatusClass, requestStatusClass,
requestStatusLabel, requestStatusLabel,
saveSubjectComment, saveSubjectComment,
subjectAttachmentGroups,
subjectCountLabel, subjectCountLabel,
submitTeacherRequest, submitTeacherRequest,
teacherMetrics, teacherMetrics,
@@ -52,6 +57,7 @@ export function DepartmentWorkspaceTab() {
const [workspaceAlert, setWorkspaceAlert] = useState({ text: '', isError: false }); const [workspaceAlert, setWorkspaceAlert] = useState({ text: '', isError: false });
const [subjects, setSubjects] = useState({ loading: true, items: [], error: '' }); const [subjects, setSubjects] = useState({ loading: true, items: [], error: '' });
const [subjectFilter, setSubjectFilter] = useState(SUBJECT_CALENDAR_FILTER_ALL);
const [teachers, setTeachers] = useState({ items: null, error: '' }); const [teachers, setTeachers] = useState({ items: null, error: '' });
const [workload, setWorkload] = useState({ items: null, error: '' }); const [workload, setWorkload] = useState({ items: null, error: '' });
const [requests, setRequests] = useState({ items: null, error: '' }); const [requests, setRequests] = useState({ items: null, error: '' });
@@ -133,7 +139,7 @@ export function DepartmentWorkspaceTab() {
async function loadSubjects() { async function loadSubjects() {
setSubjects({ loading: true, items: [], error: '' }); setSubjects({ loading: true, items: [], error: '' });
try { try {
const items = await fetchDepartmentSubjects(currentDepartmentId()); const items = await fetchDepartmentSubjectCalendar(currentDepartmentId());
setSubjects({ loading: false, items: Array.isArray(items) ? items : [], error: '' }); setSubjects({ loading: false, items: Array.isArray(items) ? items : [], error: '' });
} catch (error) { } catch (error) {
setSubjects({ loading: false, items: [], error: error.message || 'Ошибка загрузки дисциплин' }); setSubjects({ loading: false, items: [], error: error.message || 'Ошибка загрузки дисциплин' });
@@ -333,9 +339,10 @@ export function DepartmentWorkspaceTab() {
const requestsCountLabel = requests.error const requestsCountLabel = requests.error
? '0 заявок' ? '0 заявок'
: (requests.items === null ? 'Загрузка...' : requestCountLabel(requests.items.length)); : (requests.items === null ? 'Загрузка...' : requestCountLabel(requests.items.length));
const visibleSubjects = subjects.error || subjects.loading ? [] : filterDepartmentSubjects(subjects.items, subjectFilter);
const subjectsCountLabel = subjects.error const subjectsCountLabel = subjects.error
? '0 дисциплин' ? '0 дисциплин'
: (subjects.loading ? 'Загрузка...' : subjectCountLabel(subjects.items.length)); : (subjects.loading ? 'Загрузка...' : subjectCountLabel(visibleSubjects.length));
return ( return (
<> <>
@@ -665,6 +672,20 @@ export function DepartmentWorkspaceTab() {
<div className="card-header-row"> <div className="card-header-row">
<h2>Дисциплины кафедры</h2> <h2>Дисциплины кафедры</h2>
<span className="muted" id="department-subject-count">{subjectsCountLabel}</span> <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>
<div className="table-wrap"> <div className="table-wrap">
<table> <table>
@@ -672,7 +693,7 @@ export function DepartmentWorkspaceTab() {
<tr> <tr>
<th>Код</th> <th>Код</th>
<th>Название</th> <th>Название</th>
<th>Описание</th> <th>Календарный график</th>
<th>Комментарии</th> <th>Комментарии</th>
</tr> </tr>
</thead> </thead>
@@ -689,17 +710,31 @@ export function DepartmentWorkspaceTab() {
{subjects.error} {subjects.error}
</td> </td>
</tr> </tr>
) : subjects.items.length === 0 ? ( ) : visibleSubjects.length === 0 ? (
<tr> <tr>
<td colSpan={SUBJECT_TABLE_COLUMNS} className="loading-row"> <td colSpan={SUBJECT_TABLE_COLUMNS} className="loading-row">
Дисциплины не найдены Дисциплины не найдены
</td> </td>
</tr> </tr>
) : subjects.items.map(subject => ( ) : visibleSubjects.map(subject => {
const attachmentGroups = subjectAttachmentGroups(subject.attachments);
return (
<tr key={subject.id}> <tr key={subject.id}>
<td>{subject.code || '-'}</td> <td>{subject.code || '-'}</td>
<td>{subject.name || '-'}</td> <td>{subject.name || '-'}</td>
<td>{subject.description || '-'}</td> <td>
{attachmentGroups.length ? (
<div className="assignment-subjects">
{attachmentGroups.map(group => (
<div className="assignment-subject-semester" key={group.calendarId}>
<span>{attachmentGroupLabel(group)}</span>
</div>
))}
</div>
) : (
<span className="text-muted">Не прикреплена к графику</span>
)}
</td>
<td> <td>
<button <button
type="button" type="button"
@@ -710,7 +745,8 @@ export function DepartmentWorkspaceTab() {
</button> </button>
</td> </td>
</tr> </tr>
))} );
})}
</tbody> </tbody>
</table> </table>
</div> </div>
+65 -6
View File
@@ -112,19 +112,25 @@ import {
import { import {
assignTeacher as assignTeacherToDepartment, assignTeacher as assignTeacherToDepartment,
assignTeacherError, assignTeacherError,
attachmentGroupLabel,
availableTeachers, availableTeachers,
departmentSubjectCalendarEndpoint,
departmentSubjectsEndpoint, departmentSubjectsEndpoint,
departmentTeacherRequestsEndpoint, departmentTeacherRequestsEndpoint,
departmentTeachersEndpoint, departmentTeachersEndpoint,
fetchDepartmentSubjectCalendar,
fetchDepartmentSubjects, fetchDepartmentSubjects,
fetchDepartmentTeacherRequests, fetchDepartmentTeacherRequests,
fetchDepartmentTeachers, fetchDepartmentTeachers,
fetchTeacherWorkload, fetchTeacherWorkload,
filterDepartmentSubjects,
formatDateTime, formatDateTime,
importSubjects, importSubjects,
importSubjectsPayload, importSubjectsPayload,
requestStatusClass, requestStatusClass,
requestStatusLabel, requestStatusLabel,
semesterNumbersLabel,
subjectAttachmentGroups,
subjectCountLabel, subjectCountLabel,
submitTeacherRequest, submitTeacherRequest,
teacherMetrics, teacherMetrics,
@@ -1259,6 +1265,8 @@ test('вкладка заявок рендерит реестр с фильтр
test('эндпоинты кабинета кафедры совпадают с legacy-контрактами', () => { test('эндпоинты кабинета кафедры совпадают с legacy-контрактами', () => {
assert.equal(departmentSubjectsEndpoint(4), '/api/department/subjects?departmentId=4'); assert.equal(departmentSubjectsEndpoint(4), '/api/department/subjects?departmentId=4');
assert.equal(departmentSubjectsEndpoint(''), '/api/department/subjects?departmentId='); 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(departmentTeachersEndpoint(4), '/api/department/teachers?departmentId=4');
assert.equal(departmentTeacherRequestsEndpoint(4), '/api/department/teacher-requests?departmentId=4'); assert.equal(departmentTeacherRequestsEndpoint(4), '/api/department/teacher-requests?departmentId=4');
assert.equal( assert.equal(
@@ -1305,8 +1313,12 @@ test('контракты API кабинета кафедры сохранены'
await fetchDepartmentSubjects(4, client); await fetchDepartmentSubjects(4, client);
assert.equal(client.calls[0].endpoint, '/api/department/subjects?departmentId=4'); 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); await importSubjects([{ code: 'DB201', name: 'Базы данных', departmentId: 4 }], client);
assert.deepEqual(client.calls[1], { assert.deepEqual(client.calls[2], {
method: 'POST', method: 'POST',
endpoint: '/api/department/subjects/import', endpoint: '/api/department/subjects/import',
json: [{ code: 'DB201', name: 'Базы данных', departmentId: 4 }], json: [{ code: 'DB201', name: 'Базы данных', departmentId: 4 }],
@@ -1314,10 +1326,10 @@ test('контракты API кабинета кафедры сохранены'
}); });
await fetchDepartmentTeachers(4, client); 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); await assignTeacherToDepartment(5, '4', '', client);
assert.deepEqual(client.calls[3], { assert.deepEqual(client.calls[4], {
method: 'POST', method: 'POST',
endpoint: '/api/department/teachers/5/assignments', endpoint: '/api/department/teachers/5/assignments',
json: { departmentId: 4, comment: null }, json: { departmentId: 4, comment: null },
@@ -1325,13 +1337,13 @@ test('контракты API кабинета кафедры сохранены'
}); });
await fetchTeacherWorkload({ startDate: '2026-09-01', endDate: '2026-09-14', departmentId: '4' }, client); 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); 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); await submitTeacherRequest({ departmentId: 4, username: 'ivanov', fullName: 'Иванов', jobTitle: '', comment: '' }, client);
assert.deepEqual(client.calls[6], { assert.deepEqual(client.calls[7], {
method: 'POST', method: 'POST',
endpoint: '/api/department/teacher-requests', endpoint: '/api/department/teacher-requests',
json: { departmentId: 4, username: 'ivanov', fullName: 'Иванов', jobTitle: '', comment: '' }, json: { departmentId: 4, username: 'ivanov', fullName: 'Иванов', jobTitle: '', comment: '' },
@@ -1416,12 +1428,59 @@ test('вкладка кабинета кафедры рендерит формы
assert.match(markup, /id="department-teacher-requests-tbody"/); assert.match(markup, /id="department-teacher-requests-tbody"/);
assert.match(markup, /Дисциплины кафедры/); assert.match(markup, /Дисциплины кафедры/);
assert.match(markup, /id="department-subjects-tbody"/); 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.doesNotMatch(markup, /style="/); assert.doesNotMatch(markup, /style="/);
// карточка комментариев скрыта до выбора дисциплины // карточка комментариев скрыта до выбора дисциплины
assert.doesNotMatch(markup, /department-comments-card/); 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('двухнедельный период загруженности считается по локальному времени', () => { test('двухнедельный период загруженности считается по локальному времени', () => {
assert.deepEqual(twoWeekRange('2026-09-28'), { startDate: '2026-09-28', endDate: '2026-10-11' }); assert.deepEqual(twoWeekRange('2026-09-28'), { startDate: '2026-09-28', endDate: '2026-10-11' });
// среда 30.09 — период всё равно начинается с понедельника // среда 30.09 — период всё равно начинается с понедельника