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
+414 -31

No files matched your search

@@ -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) {
if (!departmentId) return { error: 'Выберите кафедру' };
const payload = (rows || [])
@@ -5,26 +5,31 @@ 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,
requestStatusClass,
requestStatusLabel,
saveSubjectComment,
subjectAttachmentGroups,
subjectCountLabel,
submitTeacherRequest,
teacherMetrics,
@@ -52,6 +57,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: '' });
@@ -133,7 +139,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 || 'Ошибка загрузки дисциплин' });
@@ -333,9 +339,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 (
<>
@@ -665,6 +672,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>
@@ -672,7 +693,7 @@ export function DepartmentWorkspaceTab() {
<tr>
<th>Код</th>
<th>Название</th>
<th>Описание</th>
<th>Календарный график</th>
<th>Комментарии</th>
</tr>
</thead>
@@ -689,28 +710,43 @@ 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);
return (
<tr key={subject.id}>
<td>{subject.code || '-'}</td>
<td>{subject.name || '-'}</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>
<button
type="button"
className="btn btn-sm btn-secondary department-comments-open"
onClick={() => void openComments(subject.id, subject.name || '')}
>
Открыть
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
+65 -6
View File
@@ -112,19 +112,25 @@ import {
import {
assignTeacher as assignTeacherToDepartment,
assignTeacherError,
attachmentGroupLabel,
availableTeachers,
departmentSubjectCalendarEndpoint,
departmentSubjectsEndpoint,
departmentTeacherRequestsEndpoint,
departmentTeachersEndpoint,
fetchDepartmentSubjectCalendar,
fetchDepartmentSubjects,
fetchDepartmentTeacherRequests,
fetchDepartmentTeachers,
fetchTeacherWorkload,
filterDepartmentSubjects,
formatDateTime,
importSubjects,
importSubjectsPayload,
requestStatusClass,
requestStatusLabel,
semesterNumbersLabel,
subjectAttachmentGroups,
subjectCountLabel,
submitTeacherRequest,
teacherMetrics,
@@ -1259,6 +1265,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 +1313,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 +1326,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 +1337,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 +1428,59 @@ 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.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('двухнедельный период загруженности считается по локальному времени', () => {
assert.deepEqual(twoWeekRange('2026-09-28'), { startDate: '2026-09-28', endDate: '2026-10-11' });
// среда 30.09 — период всё равно начинается с понедельника