Вид нагрузки в привязках преподавателей и повсеместный CustomSelect

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

Backend:
- teacher_subjects: колонка lesson_type_id NOT NULL FK, входит в
  UNIQUE (user_id, subject_id, academic_year_id, semester_number,
  lesson_type_id); таблица teacher_lesson_types удалена
- POST/DELETE /api/teacher-subjects требуют lessonTypeId (валидация
  «Вид нагрузки не найден»), ответ GET дополнен lessonTypeId/Name
- GET /api/users/teachers/options: параметр lessonTypeId сужает поиск
  до преподавателей, привязанных на вид нагрузки
- Подбор замещающих и реестр видов нагрузки дисциплины переписаны на
  teacher_subjects.lesson_type_id
- V2: привязки тестовых данных распределяются по кругу видов нагрузки

Frontend:
- Вкладка «Преподаватели дисциплин»: селект вида нагрузки в панели,
  метки «ФИО · вид», отвязка по виду, сужение поиска преподавателей
- Реестр дисциплин (ADMIN): селект вида в модалке, метки вида
- Конструктор правил: список преподавателя слота сужается по виду
  нагрузки слота
- Все нативные select заменены на CustomSelect (админка, преподаватель,
  студент, настройки, диалог заявок); общие стили меню для кабинетов
  преподавателя/студента в schedule-overview.css — тёмная тема без
  белых списков

Документация: API.md, DATABASE.md, BUSINESS_LOGIC.md, FRONTEND.md,
UI_COMPONENTS.md обновлены под новый контракт.
This commit is contained in:
dipatrik10 committed 2026-10-08 02:03:10 +03:00
1 parent 329a762d54
commit 28c3d12404
29 files changed
+676 -220

No files matched your search

+10 -16
View File
@@ -698,28 +698,22 @@
/* ===== Кабинет кафедры: селект графиков и строка комментариев ===== */
/* Нативный селект (data-native-select="true" исключает его из кастомизации
dropdown.js): в узкой ячейке таблицы читается лучше кастомного дропдауна.
/* Селект календарных графиков дисциплины в узкой ячейке таблицы:
кастомный селект дизайн-системы (нативный select скрыт внутри
.react-custom-select и помечен классом для адресации обёртки).
Ширина — по самому длинному пункту: колонка растягивается под селект,
и он не короче текстовых ячеек. */
.department-subject-calendar-select {
.react-custom-select:has(.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);
.react-custom-select:has(.department-subject-calendar-select) .custom-select-trigger {
min-height: auto;
padding: 0.45rem 0.65rem;
font-size: 0.85rem;
line-height: 1.35;
white-space: nowrap;
}
.department-comments-row > td {
@@ -205,28 +205,31 @@ export async function fetchSubjectTeacherBindings(subjectIds, client = apiClient
}
// Привязка преподавателя к дисциплине на конкретный семестр
// (учебный год + номер семестра). Оба параметра null — привязка «без семестра»,
// действующая для всех семестров дисциплины.
export function bindSubjectTeacher(subjectId, userId, academicYearId, semesterNumber, client = apiClient) {
// (учебный год + номер семестр) и вид нагрузки (лекция, практика,
// лабораторная работа). Оба семестровых параметра null — привязка
// «без семестра», действующая для всех семестров дисциплины.
export function bindSubjectTeacher(subjectId, userId, academicYearId, semesterNumber, lessonTypeId, client = apiClient) {
return client.post(
'/api/teacher-subjects',
{
subjectId: Number(subjectId),
userId: Number(userId),
academicYearId: academicYearId == null || academicYearId === '' ? null : Number(academicYearId),
semesterNumber: semesterNumber == null || semesterNumber === '' ? null : Number(semesterNumber)
semesterNumber: semesterNumber == null || semesterNumber === '' ? null : Number(semesterNumber),
lessonTypeId: lessonTypeId == null || lessonTypeId === '' ? null : Number(lessonTypeId)
},
{ errorMessage: 'Ошибка привязки преподавателя' }
);
}
export function unbindSubjectTeacher(subjectId, userId, academicYearId, semesterNumber, client = apiClient) {
export function unbindSubjectTeacher(subjectId, userId, academicYearId, semesterNumber, lessonTypeId, client = apiClient) {
return client.delete('/api/teacher-subjects', {
json: {
subjectId: Number(subjectId),
userId: Number(userId),
academicYearId: academicYearId == null || academicYearId === '' ? null : Number(academicYearId),
semesterNumber: semesterNumber == null || semesterNumber === '' ? null : Number(semesterNumber)
semesterNumber: semesterNumber == null || semesterNumber === '' ? null : Number(semesterNumber),
lessonTypeId: lessonTypeId == null || lessonTypeId === '' ? null : Number(lessonTypeId)
},
errorMessage: 'Ошибка отвязки преподавателя'
});
@@ -300,6 +303,13 @@ export function bindingSemesterLabel(academicYearTitle, semesterNumber) {
return academicYearTitle ? `${academicYearTitle} · ${semesterPart}` : semesterPart;
}
// Метка привязанного преподавателя с видом нагрузки: «ФИО · Лекция».
// Вид нагрузки обязателен, поэтому показываем его всегда.
export function bindingTeacherLabel(binding) {
const name = binding.fullName || binding.username || `ID ${binding.userId}`;
return binding.lessonTypeName ? `${name} · ${binding.lessonTypeName}` : name;
}
export function fetchAllTeachers(client = apiClient) {
return client.get('/api/users/teachers', {
errorMessage: 'Ошибка загрузки преподавателей'
@@ -693,7 +693,7 @@ export function groupsOptionsEndpoint(query, selectedId, departmentId = '') {
// Семестровое сужение: semesterId — семестр версии расписания, semesterNumber —
// номер семестра группы из календарного графика. Вместе с subjectId сужают
// список преподавателя слота до привязок «дисциплина + учебный год + семестр».
export function teachersOptionsEndpoint(query, selectedId, subjectId, semesterId, semesterNumber) {
export function teachersOptionsEndpoint(query, selectedId, subjectId, semesterId, semesterNumber, lessonTypeId) {
const params = new URLSearchParams({ query, limit: '30' });
if (selectedId) params.set('selectedId', selectedId);
if (subjectId) params.set('subjectId', subjectId);
@@ -701,6 +701,9 @@ export function teachersOptionsEndpoint(query, selectedId, subjectId, semesterId
params.set('semesterId', semesterId);
params.set('semesterNumber', semesterNumber);
}
if (subjectId && lessonTypeId) {
params.set('lessonTypeId', lessonTypeId);
}
return `/api/users/teachers/options?${params}`;
}
@@ -714,9 +717,9 @@ export async function fetchGroupOptions(query, selectedId, departmentId, client
return client.get(groupsOptionsEndpoint(query, selectedId, departmentId), { errorMessage: 'Ошибка поиска групп' });
}
export async function fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber, client = apiClient) {
export async function fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber, lessonTypeId, client = apiClient) {
return client.get(
teachersOptionsEndpoint(query, selectedId, subjectId, semesterId, semesterNumber),
teachersOptionsEndpoint(query, selectedId, subjectId, semesterId, semesterNumber, lessonTypeId),
{ errorMessage: 'Ошибка поиска преподавателей' }
);
}
+17 -7
View File
@@ -96,24 +96,29 @@ export function archiveSubject(id, client = apiClient) {
return client.delete(`/api/subjects/${id}`, { errorMessage: 'Ошибка архивирования' });
}
export function assignTeacher({ userId, subjectId }, client = apiClient) {
export function assignTeacher({ userId, subjectId, lessonTypeId }, client = apiClient) {
return client.post(
'/api/teacher-subjects',
{ userId: Number(userId), subjectId: Number(subjectId) },
{
userId: Number(userId),
subjectId: Number(subjectId),
lessonTypeId: lessonTypeId == null || lessonTypeId === '' ? null : Number(lessonTypeId)
},
{ errorMessage: 'Ошибка привязки' }
);
}
// Удаление привязки: передаём семестровый контекст строки, чтобы удалить
// именно выбранную привязку (преподаватель может быть привязан к дисциплине
// на нескольких семестрах).
export function removeTeacherAssignment({ userId, subjectId, academicYearId, semesterNumber }, client = apiClient) {
// Удаление привязки: передаём семестровый контекст строки и вид нагрузки,
// чтобы удалить именно выбранную привязку (преподаватель может быть привязан
// к дисциплине на нескольких семестрах и видах нагрузки).
export function removeTeacherAssignment({ userId, subjectId, academicYearId, semesterNumber, lessonTypeId }, client = apiClient) {
return client.delete('/api/teacher-subjects', {
json: {
userId: Number(userId),
subjectId: Number(subjectId),
academicYearId: academicYearId == null || academicYearId === '' ? null : Number(academicYearId),
semesterNumber: semesterNumber == null || semesterNumber === '' ? null : Number(semesterNumber)
semesterNumber: semesterNumber == null || semesterNumber === '' ? null : Number(semesterNumber),
lessonTypeId: lessonTypeId == null || lessonTypeId === '' ? null : Number(lessonTypeId)
},
errorMessage: 'Ошибка удаления привязки'
});
@@ -130,6 +135,11 @@ export function assignmentSemesterLabel(assignment) {
return yearTitle ? `${yearTitle} · ${semesterPart}` : semesterPart;
}
// Читаемая метка вида нагрузки привязки в реестре дисциплин.
export function assignmentTypeLabel(assignment) {
return assignment?.lessonTypeName || '—';
}
export function teachersSearchEndpoint(query, selectedId) {
const params = new URLSearchParams({ query, limit: '30' });
if (selectedId) params.set('selectedId', selectedId);
@@ -23,6 +23,7 @@ import {
bindingRowsFromSubjects,
bindingRowKey,
bindingSemesterLabel,
bindingTeacherLabel,
defaultWorkloadPeriod,
departmentOptionLabel,
fetchAllTeachers,
@@ -54,6 +55,7 @@ import {
} from '../department-workspace-service.js';
import { consumeDepartmentNavigation, navigateDepartmentTab } from '../department-workspace-navigation.js';
import { fetchLessonTypes, orderedLessonTypes } from '../schedule-service.js';
const ROLE_DEPARTMENT = 'DEPARTMENT';
@@ -130,6 +132,8 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
const [subjectBindings, setSubjectBindings] = useState({ items: [], error: '' });
const [bindingPanel, setBindingPanel] = useState(null);
const [unbindConfirm, setUnbindConfirm] = useState(null);
// Справочник видов нагрузки для привязок (лекция, практика, лабораторная).
const [lessonTypes, setLessonTypes] = useState([]);
function currentDepartmentId() {
return isDepartmentRole ? userDepartmentId : departmentIdRef.current;
@@ -190,6 +194,19 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
return () => { active = false; };
}, [activeSection, allTeachersLoaded]);
// Виды нагрузки загружаются один раз для панели привязок.
useEffect(() => {
let active = true;
fetchLessonTypes().then(items => {
if (!active) return;
setLessonTypes(orderedLessonTypes(Array.isArray(items) ? items : []));
}).catch(() => {
// Панель привязок покажет предупреждение при отправке формы,
// если справочник видов нагрузки так и не загрузился.
});
return () => { active = false; };
}, []);
function openSection(section) {
setActiveSection(section);
requestAnimationFrame(() => document.getElementById(`department-pane-${section}`)?.scrollIntoView({ block: 'start' }));
@@ -285,6 +302,7 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
semesterNumber: row.semesterNumber == null ? null : Number(row.semesterNumber),
semesterLabel: bindingSemesterLabel(row.academicYearTitle, row.semesterNumber),
selectedTeacher: null,
selectedLessonTypeId: '',
alert: { text: '', isError: false }
}
));
@@ -292,8 +310,12 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
async function searchBindingTeachers(query, selectedId) {
const teachers = await fetchDepartmentTeacherOptions(query, selectedId, currentDepartmentId());
// Преподаватель может вести несколько видов нагрузки: скрываем только
// тех, кто уже привязан к строке на выбранном виде нагрузки.
const selectedType = bindingPanel?.selectedLessonTypeId;
const bound = new Set(
(bindingsByRow.get(bindingPanel?.rowKey) || [])
.filter(binding => !selectedType || String(binding.lessonTypeId) === String(selectedType))
.map(binding => String(binding.userId))
);
return (teachers || []).filter(teacher =>
@@ -308,8 +330,18 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
setBindingPanel({ ...panel, alert: { text: 'Выберите преподавателя', isError: true } });
return;
}
if (!panel.selectedLessonTypeId) {
setBindingPanel({ ...panel, alert: { text: 'Выберите вид нагрузки (лекция, практика или лабораторная работа)', isError: true } });
return;
}
try {
await bindSubjectTeacher(panel.subjectId, panel.selectedTeacher.id, panel.academicYearId, panel.semesterNumber);
await bindSubjectTeacher(
panel.subjectId,
panel.selectedTeacher.id,
panel.academicYearId,
panel.semesterNumber,
panel.selectedLessonTypeId
);
setBindingPanel(current => (
current
? { ...current, selectedTeacher: null, alert: { text: 'Преподаватель привязан к дисциплине', isError: false } }
@@ -329,14 +361,21 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
const panel = bindingPanel;
if (!panel) return;
const teacherName = binding.fullName || binding.username || `ID ${binding.userId}`;
const typePart = binding.lessonTypeName ? ` (вид нагрузки — ${binding.lessonTypeName})` : '';
setUnbindConfirm({
title: 'Отвязать преподавателя от дисциплины?',
message: `${teacherName} больше не будет доступен для дисциплины «${panel.subjectName || 'дисциплина'}» (${panel.semesterLabel}) в новых правилах.`,
message: `${teacherName} больше не будет доступен для дисциплины «${panel.subjectName || 'дисциплина'}» (${panel.semesterLabel})${typePart} в новых правилах.`,
confirmLabel: 'Отвязать',
danger: true,
action: async () => {
try {
await unbindSubjectTeacher(panel.subjectId, binding.userId, panel.academicYearId, panel.semesterNumber);
await unbindSubjectTeacher(
panel.subjectId,
binding.userId,
panel.academicYearId,
panel.semesterNumber,
binding.lessonTypeId
);
await loadSubjectBindings(subjects.items);
} catch (error) {
setBindingPanel(current => (
@@ -948,7 +987,7 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
<label className="schedule-section-label schedule-section-label--flush" htmlFor="department-subject-filter">
Показывать
</label>
<select
<CustomSelect
id="department-subject-filter"
value={subjectFilter}
onChange={event => { setSubjectFilter(event.target.value); setSubjectPage(0); }}
@@ -956,7 +995,7 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
{SUBJECT_CALENDAR_FILTER_OPTIONS.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</CustomSelect>
</div>
</div>
<div className="table-wrap">
@@ -1010,9 +1049,8 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
) : attachmentGroups.length === 1 ? (
<span>{attachmentGroupLabel(attachmentGroups[0])}</span>
) : (
<select
<CustomSelect
className="department-subject-calendar-select"
data-native-select="true"
aria-label="Календарные графики дисциплины"
defaultValue={String(attachmentGroups[0].calendarId)}
>
@@ -1021,7 +1059,7 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
{attachmentGroupLabel(group)}
</option>
))}
</select>
</CustomSelect>
)}
</td>
<td>
@@ -1112,7 +1150,9 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
<p className="muted" id="department-binding-hint">
Дисциплина, встречающаяся в разных семестрах графиков, показывается отдельными
строками — на каждый семестр можно привязать своих преподавателей. Строка
«Без семестра» действует для всех семестров дисциплины.
«Без семестра» действует для всех семестров дисциплины. Каждая привязка
указывает вид нагрузки — лекцию, практику или лабораторную работу: разные
виды могут вести разные преподаватели.
</p>
<div className="table-wrap">
<table id="department-binding-table">
@@ -1154,7 +1194,7 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
) : bound.length === 0 ? (
<span className="text-muted">Не привязаны</span>
) : (
<span>{bound.map(binding => binding.fullName || binding.username).join(', ')}</span>
<span>{bound.map(binding => bindingTeacherLabel(binding)).join(', ')}</span>
)}
</td>
<td>
@@ -1206,6 +1246,26 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
: ''}
/>
</div>
<div className="form-group">
<label htmlFor="department-binding-lesson-type">Вид нагрузки</label>
<CustomSelect
id="department-binding-lesson-type"
required
value={bindingPanel.selectedLessonTypeId}
onChange={event => setBindingPanel(current => (
current
? { ...current, selectedLessonTypeId: event.target.value }
: current
))}
>
<option value="">Выберите</option>
{lessonTypes.map(type => (
<option key={type.id} value={type.id}>
{type.name || type.lessonType || `ID ${type.id}`}
</option>
))}
</CustomSelect>
</div>
<button type="submit" className="btn btn-md btn-primary">Привязать</button>
</form>
<div
@@ -1221,8 +1281,8 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
) : bound.length === 0 ? (
<div className="loading-row">Привязанных преподавателей пока нет</div>
) : bound.map(binding => (
<div className="department-binding-item" key={`${binding.subjectId}-${binding.academicYearId ?? ''}-${binding.semesterNumber ?? ''}-${binding.userId}`}>
<span>{binding.fullName || binding.username || `ID ${binding.userId}`}</span>
<div className="department-binding-item" key={`${binding.subjectId}-${binding.academicYearId ?? ''}-${binding.semesterNumber ?? ''}-${binding.userId}-${binding.lessonTypeId ?? ''}`}>
<span>{bindingTeacherLabel(binding)}</span>
<button
type="button"
className="btn btn-sm btn-danger"
+2 -2
View File
@@ -2139,7 +2139,7 @@ function RuleSlotRow({
optionLabel={teacherOptionLabel}
optionDescription={teacherOptionDescription}
load={(query, selectedId) => (subjectId
? fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber)
? fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber, slot.lessonTypeId)
: Promise.resolve([]))}
selectedValue={slot.teacherId}
selectedLabel={slot.teacherName}
@@ -2333,7 +2333,7 @@ function ConflictSlotRow({ slot, index, conflictFields, timeSlotOptions, subject
optionLabel={teacherOptionLabel}
optionDescription={teacherOptionDescription}
load={(query, selectedId) => (subjectId
? fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber)
? fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber, original.lessonTypeId)
: fetchTeacherOptions(query, selectedId))}
selectedValue={slot.teacherId}
selectedLabel={slot.teacherName}
+54 -5
View File
@@ -12,6 +12,7 @@ import {
archiveSubject,
assignTeacher,
assignmentSemesterLabel,
assignmentTypeLabel,
createSubject,
departmentLabel,
departmentOptionLabel,
@@ -25,6 +26,7 @@ import {
subjectsUrlState,
teachersSearchEndpoint
} from '../subjects-service.js';
import { fetchLessonTypes, orderedLessonTypes } from '../schedule-service.js';
import { apiClient } from '../../shared/api-client.js';
const SEARCH_DEBOUNCE_MS = 320;
@@ -56,6 +58,8 @@ export function SubjectsTab() {
const [teachersModal, setTeachersModal] = useState(null);
const [confirmState, setConfirmState] = useState(null);
const [alertState, setAlertState] = useState(null);
// Справочник видов нагрузки для привязок (лекция, практика, лабораторная).
const [lessonTypes, setLessonTypes] = useState([]);
const searchTimer = useRef(null);
const requestNumber = useRef(0);
@@ -80,6 +84,19 @@ export function SubjectsTab() {
};
}, []);
// Виды нагрузки загружаются один раз для модального окна привязок.
useEffect(() => {
let active = true;
fetchLessonTypes().then(items => {
if (!active) return;
setLessonTypes(orderedLessonTypes(Array.isArray(items) ? items : []));
}).catch(() => {
// Форма привязки покажет предупреждение при отправке, если
// справочник видов нагрузки так и не загрузился.
});
return () => { active = false; };
}, []);
useEffect(() => () => {
window.clearTimeout(searchTimer.current);
}, []);
@@ -169,7 +186,8 @@ export function SubjectsTab() {
setTeachersModal({
subject,
alert: { text: '', isError: false },
selectedTeacher: null
selectedTeacher: null,
selectedLessonTypeId: ''
});
}
@@ -183,9 +201,13 @@ export function SubjectsTab() {
async function searchTeachers(query, selectedId) {
const teachers = await apiClient.get(teachersSearchEndpoint(query, selectedId));
const modalSubjectId = teachersModal?.subject?.id;
// Преподаватель может вести несколько видов нагрузки: скрываем только
// тех, кто уже привязан к дисциплине на выбранном виде нагрузки.
const selectedType = teachersModal?.selectedLessonTypeId;
const assigned = new Set(
(assignments || [])
.filter(item => String(item.subjectId) === String(modalSubjectId))
.filter(item => !selectedType || String(item.lessonTypeId) === String(selectedType))
.map(item => String(item.userId))
);
return (teachers || []).filter(teacher =>
@@ -199,8 +221,12 @@ export function SubjectsTab() {
setTeachersModal({ ...modal, alert: { text: 'Выберите преподавателя', isError: true } });
return;
}
if (!modal.selectedLessonTypeId) {
setTeachersModal({ ...modal, alert: { text: 'Выберите вид нагрузки (лекция, практика или лабораторная работа)', isError: true } });
return;
}
try {
await assignTeacher({ userId: modal.selectedTeacher.id, subjectId: modal.subject.id });
await assignTeacher({ userId: modal.selectedTeacher.id, subjectId: modal.subject.id, lessonTypeId: modal.selectedLessonTypeId });
setTeachersModal(current => (
current ? { ...current, alert: { text: 'Преподаватель успешно привязан', isError: false }, selectedTeacher: null } : current
));
@@ -222,7 +248,8 @@ export function SubjectsTab() {
userId: assignment.userId,
subjectId: assignment.subjectId,
academicYearId: assignment.academicYearId,
semesterNumber: assignment.semesterNumber
semesterNumber: assignment.semesterNumber,
lessonTypeId: assignment.lessonTypeId
});
await reloadAssignments();
} catch (error) {
@@ -474,6 +501,26 @@ export function SubjectsTab() {
: ''}
/>
</div>
<div className="form-group form-group--flush">
<label htmlFor="manage-ts-lesson-type">Вид нагрузки</label>
<CustomSelect
id="manage-ts-lesson-type"
required
value={teachersModal.selectedLessonTypeId}
onChange={event => setTeachersModal(current => (
current
? { ...current, selectedLessonTypeId: event.target.value }
: current
))}
>
<option value="">Выберите</option>
{lessonTypes.map(type => (
<option key={type.id} value={type.id}>
{type.name || type.lessonType || `ID ${type.id}`}
</option>
))}
</CustomSelect>
</div>
<button type="submit" className="btn btn-md btn-primary btn-inline">Привязать</button>
</div>
<div
@@ -490,19 +537,21 @@ export function SubjectsTab() {
<tr>
<th>Преподаватель</th>
<th>Семестр</th>
<th>Вид нагрузки</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
{(teachersBySubject.get(String(teachersModal.subject.id)) || []).length === 0 ? (
<tr><td colSpan="3" className="loading-row">Преподаватели не привязаны</td></tr>
<tr><td colSpan="4" className="loading-row">Преподаватели не привязаны</td></tr>
) : (teachersBySubject.get(String(teachersModal.subject.id)) || []).map(assignment => (
<tr key={`${assignment.userId}-${assignment.academicYearId ?? ''}-${assignment.semesterNumber ?? ''}`}>
<tr key={`${assignment.userId}-${assignment.academicYearId ?? ''}-${assignment.semesterNumber ?? ''}-${assignment.lessonTypeId ?? ''}`}>
<td>
<strong>{assignment.fullName || assignment.username}</strong>{' '}
<span className="text-muted">({assignment.username})</span>
</td>
<td>{assignmentSemesterLabel(assignment)}</td>
<td>{assignmentTypeLabel(assignment)}</td>
<td>
<button
type="button"
+3 -2
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { ConfirmDialog } from '../shared/ui/ConfirmDialog.jsx';
import { CustomSelect } from '../shared/ui/CustomSelect.jsx';
import {
buildSlotPayload,
createScope,
@@ -210,7 +211,7 @@ export function TimeSlotsTab() {
<div className="settings-form settings-form-single">
<label className="form-field" htmlFor="time-slot-scope-select">
<span>Область действия</span>
<select
<CustomSelect
id="time-slot-scope-select"
className="native-select-control"
value={activeScopeId === null ? '' : String(activeScopeId)}
@@ -224,7 +225,7 @@ export function TimeSlotsTab() {
{scopeOptionLabel(scope)}
</option>
))}
</select>
</CustomSelect>
</label>
</div>
+3 -2
View File
@@ -7,6 +7,7 @@ import { SESSION_PHASES } from '../shared/session-policy.js';
import { useAuthorizedSession } from '../shared/use-authorized-session.js';
import { AsyncCombobox } from '../shared/ui/AsyncCombobox.jsx';
import { AsyncState } from '../shared/ui/AsyncState.jsx';
import { CustomSelect } from '../shared/ui/CustomSelect.jsx';
import { buildScheduleOverviewModel } from '../../schedule-overview.js';
import { ScheduleOverview } from '../shared/ui/ScheduleOverview.jsx';
import { WeekGrid } from './WeekGrid.jsx';
@@ -235,9 +236,9 @@ function StudentWorkspace() {
selectedValue={groupId}
/>
) : (
<select className="select" aria-label="Группа" disabled>
<CustomSelect className="select" aria-label="Группа" disabled>
<option value="">{groupSelectPlaceholder(groupsState.kind)}</option>
</select>
</CustomSelect>
)}
<div className="week-nav">
<button className="btn btn-icon-md btn-secondary" type="button" aria-label="Предыдущая неделя" onClick={() => moveWeek(-1)}>
+5 -4
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { formatIsoDate, toIsoDate } from '../shared/dates.js';
import { CustomSelect } from '../shared/ui/CustomSelect.jsx';
import {
activeDatePreferences,
activeWeekPreferences,
@@ -184,11 +185,11 @@ export function PreferencesTab() {
</div>
<label className="preference-semester-field">
<span>Семестр</span>
<select value={semesterId} onChange={event => setSemesterId(event.target.value)}>
<CustomSelect value={semesterId} onChange={event => setSemesterId(event.target.value)}>
{(meta.semesters || []).map(item => (
<option key={item.id} value={item.id}>{semesterLabel(item)}</option>
))}
</select>
</CustomSelect>
</label>
</section>
@@ -200,11 +201,11 @@ export function PreferencesTab() {
</div>
<label>
<span>Режим отметки</span>
<select value={brush} onChange={event => setBrush(event.target.value)}>
<CustomSelect value={brush} onChange={event => setBrush(event.target.value)}>
<option value="SOFT_PREFERRED">Предпочтительно</option>
<option value="SOFT_UNWANTED">Нежелательно</option>
<option value="HARD_UNAVAILABLE">Строго недоступен</option>
</select>
</CustomSelect>
</label>
</header>
<div className="preference-legend" aria-label="Легенда">
+9 -8
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { formatIsoDate, trimTime } from '../shared/dates.js';
import { CustomSelect } from '../shared/ui/CustomSelect.jsx';
import {
buildChangeRequestPayload,
candidateOptions,
@@ -108,16 +109,16 @@ export function RequestDialog({ lesson, onClose, onSubmitted }) {
<form onSubmit={submit}>
<label>
<span>Что изменить</span>
<select value={requestType} onChange={event => setRequestType(event.target.value)}>
<CustomSelect value={requestType} onChange={event => setRequestType(event.target.value)}>
<option value="MOVE">Перенести дату или время</option>
<option value="CHANGE_CLASSROOM">Сменить аудиторию</option>
<option value="CANCEL">Отменить занятие</option>
</select>
</CustomSelect>
</label>
{requestType === 'MOVE' && (
<label>
<span>Новая дата</span>
<select
<CustomSelect
value={targetDate}
onChange={event => {
setTargetDate(event.target.value);
@@ -127,27 +128,27 @@ export function RequestDialog({ lesson, onClose, onSubmitted }) {
{(candidates?.availableDates || []).map(date => (
<option key={date} value={date}>{formatIsoDate(date)}</option>
))}
</select>
</CustomSelect>
</label>
)}
{requestType === 'MOVE' && (
<label>
<span>Новая пара</span>
<select value={timeSlotId} onChange={event => setTimeSlotId(event.target.value)}>
<CustomSelect value={timeSlotId} onChange={event => setTimeSlotId(event.target.value)}>
{timeOptions.map(option => (
<option key={option.id} value={option.id}>{option.label}</option>
))}
</select>
</CustomSelect>
</label>
)}
{requestType === 'CHANGE_CLASSROOM' && (
<label>
<span>Новая аудитория</span>
<select value={classroomId} onChange={event => setClassroomId(event.target.value)}>
<CustomSelect value={classroomId} onChange={event => setClassroomId(event.target.value)}>
{classroomOptions.map(option => (
<option key={option.id} value={option.id}>{option.label}</option>
))}
</select>
</CustomSelect>
</label>
)}
<label className="request-reason-field">
+150
View File
@@ -318,3 +318,153 @@
grid-template-columns: 1fr;
}
}
/* ===== Кастомный селект (общий для кабинетов преподавателя и студента) ===== */
.react-custom-select {
position: relative;
min-width: 0;
}
.react-custom-select select[hidden] {
display: none !important;
}
.select-layer-active {
position: relative !important;
z-index: 10001 !important;
}
.custom-select-wrapper {
position: relative;
width: 100%;
user-select: none;
}
.custom-select-wrapper.open {
z-index: 10002 !important;
}
.custom-select-trigger {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
width: 100%;
min-height: 42px;
padding: 0 12px;
border: 1px solid var(--panel-border, var(--border));
border-radius: 9px;
background: var(--panel, var(--card));
color: var(--text);
font: inherit;
text-align: left;
cursor: pointer;
}
.custom-select-trigger:hover {
border-color: var(--accent);
}
.custom-select-trigger:focus,
.custom-select-wrapper.open .custom-select-trigger {
border-color: var(--accent);
outline: 3px solid color-mix(in srgb, var(--accent) 16%, transparent);
}
.custom-select-trigger:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.custom-select-text {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.custom-select-trigger.placeholder-active .custom-select-text {
color: var(--muted);
}
.custom-select-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--muted);
transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}
.custom-select-wrapper.open .custom-select-icon {
transform: rotate(180deg);
}
.custom-select-menu {
position: absolute;
z-index: 40;
top: calc(100% + 6px);
left: 0;
right: 0;
max-height: 320px;
padding: 6px;
overflow-y: auto;
border: 1px solid var(--panel-border, var(--border));
border-radius: 10px;
background: var(--panel, var(--card));
box-shadow: var(--shadow);
}
.custom-select-search-input {
width: 100%;
min-height: 36px;
margin-bottom: 4px;
padding: 0 10px;
border: 1px solid var(--panel-border, var(--border));
border-radius: 7px;
background: transparent;
color: var(--text);
font: inherit;
}
.custom-select-search-input:focus {
border-color: var(--accent);
outline: 2px solid color-mix(in srgb, var(--accent) 14%, transparent);
}
.react-select-options {
margin: 0;
padding: 0;
list-style: none;
}
.custom-select-item {
display: block;
width: 100%;
padding: 9px 10px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--text);
font: inherit;
text-align: left;
cursor: pointer;
}
.custom-select-item:hover:not(.disabled),
.custom-select-item:focus-visible,
.custom-select-item.selected {
background: color-mix(in srgb, var(--accent) 10%, transparent);
outline: none;
}
.custom-select-item.selected {
color: var(--accent-strong, var(--accent));
font-weight: 600;
}
.custom-select-item.disabled {
cursor: not-allowed;
opacity: 0.45;
}
+10 -4
View File
@@ -62,8 +62,11 @@ test('селект графиков дисциплины кафедры не д
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"/);
// селект графиков переведён на CustomSelect: скрытый нативный select
// внутри .react-custom-select помечен data-native-select, поэтому
// dropdown.js не рисует рядом второй список
assert.match(tab.slice(selectIndex - 200, selectIndex + 200), /<CustomSelect/);
assert.match(tab.slice(selectIndex - 200, selectIndex + 200), /className="department-subject-calendar-select"/);
});
test('основная кнопка показа находится в заголовке блока параметров', async () => {
@@ -123,7 +126,7 @@ test('преподаватель слота формы правила сужае
// слот без дисциплины не ищет преподавателей, с дисциплиной — ищет по привязкам
assert.match(scheduleTab, /Сначала выберите дисциплину/);
assert.match(scheduleTab, /К дисциплине не привязаны преподаватели/);
assert.match(scheduleTab, /fetchTeacherOptions\(query, selectedId, subjectId, semesterId, semesterNumber\)/);
assert.match(scheduleTab, /fetchTeacherOptions\(query, selectedId, subjectId, semesterId, semesterNumber, slot\.lessonTypeId\)/);
// смена дисциплины сбрасывает преподавателей слотов
assert.match(
scheduleTab,
@@ -132,10 +135,13 @@ test('преподаватель слота формы правила сужае
assert.match(scheduleViewService, /params\.set\('subjectId', subjectId\)/);
assert.match(scheduleViewService, /params\.set\('semesterId', semesterId\)/);
assert.match(scheduleViewService, /params\.set\('semesterNumber', semesterNumber\)/);
// эндпоинт опций преподавателей принимает subjectId и семестр, ищет по привязкам
assert.match(scheduleViewService, /params\.set\('lessonTypeId', lessonTypeId\)/);
// эндпоинт опций преподавателей принимает subjectId, семестр и вид
// нагрузки, ищет по привязкам
assert.match(userController, /@RequestParam\(required = false\) Long subjectId/);
assert.match(userController, /@RequestParam\(required = false\) Long semesterId/);
assert.match(userController, /@RequestParam\(required = false\) Integer semesterNumber/);
assert.match(userController, /@RequestParam\(required = false\) Long lessonTypeId/);
assert.match(userController, /searchTeachersBySubjectBinding\(/);
assert.match(userController, /searchTeachersBySubjectSemesterBinding\(/);
});
+49 -16
View File
@@ -20,6 +20,7 @@ import {
import {
assignTeacher,
assignmentSemesterLabel,
assignmentTypeLabel,
createSubject,
departmentLabel,
departmentOptionLabel,
@@ -119,6 +120,7 @@ import {
bindingRowsFromSubjects,
bindingRowKey,
bindingSemesterLabel,
bindingTeacherLabel,
bindSubjectTeacher,
departmentSubjectCalendarEndpoint,
departmentSubjectsEndpoint,
@@ -545,27 +547,36 @@ test('контракты API дисциплин и привязок сохран
await createSubject({ name: 'Математика', code: 'MATH101', departmentId: '4' }, client);
assert.deepEqual(client.calls[1].json, { name: 'Математика', code: 'MATH101', departmentId: 4 });
await assignTeacher({ userId: '10', subjectId: '3' }, client);
assert.deepEqual(client.calls[2].json, { userId: 10, subjectId: 3 });
await assignTeacher({ userId: '10', subjectId: '3', lessonTypeId: '2' }, client);
assert.deepEqual(client.calls[2].json, { userId: 10, subjectId: 3, lessonTypeId: 2 });
await removeTeacherAssignment({ userId: '10', subjectId: '3', academicYearId: '2', semesterNumber: '6' }, client);
assert.deepEqual(client.calls[3], {
// привязка без вида нагрузки отправляет null
await assignTeacher({ userId: '10', subjectId: '3' }, client);
assert.deepEqual(client.calls[3].json, { userId: 10, subjectId: 3, lessonTypeId: null });
await removeTeacherAssignment({ userId: '10', subjectId: '3', academicYearId: '2', semesterNumber: '6', lessonTypeId: '2' }, client);
assert.deepEqual(client.calls[4], {
method: 'DELETE',
endpoint: '/api/teacher-subjects',
options: {
json: { userId: 10, subjectId: 3, academicYearId: 2, semesterNumber: 6 },
json: { userId: 10, subjectId: 3, academicYearId: 2, semesterNumber: 6, lessonTypeId: 2 },
errorMessage: 'Ошибка удаления привязки'
}
});
// удаление привязки «без семестра» отправляет null-параметры
await removeTeacherAssignment({ userId: '10', subjectId: '3' }, client);
assert.deepEqual(client.calls[4].options.json, { userId: 10, subjectId: 3, academicYearId: null, semesterNumber: null });
assert.deepEqual(client.calls[5].options.json, { userId: 10, subjectId: 3, academicYearId: null, semesterNumber: null, lessonTypeId: null });
// метки семестра привязки в реестре дисциплин
assert.equal(assignmentSemesterLabel({ academicYearTitle: '2025-2026', semesterNumber: 6 }), '2025-2026 · 6 семестр');
assert.equal(assignmentSemesterLabel({ academicYearTitle: null, semesterNumber: null }), 'Без семестра');
assert.equal(assignmentSemesterLabel(undefined), 'Без семестра');
// метка вида нагрузки привязки в реестре дисциплин
assert.equal(assignmentTypeLabel({ lessonTypeName: 'Лекция' }), 'Лекция');
assert.equal(assignmentTypeLabel({}), '—');
assert.equal(assignmentTypeLabel(undefined), '—');
});
test('метрики и слоты дашборда считаются по локальному времени', () => {
@@ -1528,12 +1539,29 @@ test('контракты привязки преподавателей к дис
teachersOptionsEndpoint('ivan', 7, null, 6, 8),
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7'
);
// вид нагрузки слота сужает опции до привязок этого вида
assert.equal(
teachersOptionsEndpoint('ivan', 7, 5, 6, 8, 2),
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5&semesterId=6&semesterNumber=8&lessonTypeId=2'
);
assert.equal(
teachersOptionsEndpoint('ivan', 7, 5, null, null, 2),
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5&lessonTypeId=2'
);
// вид нагрузки имеет смысл только вместе с дисциплиной
assert.equal(
teachersOptionsEndpoint('ivan', 7, null, null, null, 2),
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7'
);
const subjectTeachersClient = recordingClient(async () => [{ id: 7, fullName: 'Иванов И. И.' }]);
await fetchTeacherOptions('ivan', 7, 5, null, null, subjectTeachersClient);
await fetchTeacherOptions('ivan', 7, 5, null, null, null, subjectTeachersClient);
assert.equal(subjectTeachersClient.calls[0].endpoint, '/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5');
const semesterTeachersClient = recordingClient(async () => [{ id: 7, fullName: 'Иванов И. И.' }]);
await fetchTeacherOptions('ivan', 7, 5, 6, 8, semesterTeachersClient);
await fetchTeacherOptions('ivan', 7, 5, 6, 8, null, semesterTeachersClient);
assert.equal(semesterTeachersClient.calls[0].endpoint, '/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5&semesterId=6&semesterNumber=8');
const lessonTypeTeachersClient = recordingClient(async () => [{ id: 7, fullName: 'Иванов И. И.' }]);
await fetchTeacherOptions('ivan', 7, 5, 6, 8, 2, lessonTypeTeachersClient);
assert.equal(lessonTypeTeachersClient.calls[0].endpoint, '/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5&semesterId=6&semesterNumber=8&lessonTypeId=2');
// привязки: больше 100 дисциплин делятся на отдельные запросы
const subjectIds = Array.from({ length: 150 }, (_, index) => index + 1);
@@ -1549,23 +1577,23 @@ test('контракты привязки преподавателей к дис
assert.deepEqual(await fetchSubjectTeacherBindings([], emptyClient), []);
assert.equal(emptyClient.calls.length, 0);
// привязка и отвязка преподавателя на семестр
// привязка и отвязка преподавателя на семестр и вид нагрузки
const bindClient = recordingClient(async () => ({ message: 'Привязка создана' }));
await bindSubjectTeacher(5, 9, 3, 6, bindClient);
await bindSubjectTeacher(5, 9, 3, 6, 2, bindClient);
assert.equal(bindClient.calls[0].method, 'POST');
assert.equal(bindClient.calls[0].endpoint, '/api/teacher-subjects');
assert.deepEqual(bindClient.calls[0].json, { subjectId: 5, userId: 9, academicYearId: 3, semesterNumber: 6 });
assert.deepEqual(bindClient.calls[0].json, { subjectId: 5, userId: 9, academicYearId: 3, semesterNumber: 6, lessonTypeId: 2 });
// привязка «без семестра» отправляет null-параметры
const bindNoSemesterClient = recordingClient(async () => ({ message: 'Привязка создана' }));
await bindSubjectTeacher(5, 9, null, null, bindNoSemesterClient);
assert.deepEqual(bindNoSemesterClient.calls[0].json, { subjectId: 5, userId: 9, academicYearId: null, semesterNumber: null });
await bindSubjectTeacher(5, 9, null, null, 2, bindNoSemesterClient);
assert.deepEqual(bindNoSemesterClient.calls[0].json, { subjectId: 5, userId: 9, academicYearId: null, semesterNumber: null, lessonTypeId: 2 });
const unbindClient = recordingClient(async () => ({ message: 'Привязка удалена' }));
await unbindSubjectTeacher(5, 9, 3, 6, unbindClient);
await unbindSubjectTeacher(5, 9, 3, 6, 2, unbindClient);
assert.equal(unbindClient.calls[0].method, 'DELETE');
assert.equal(unbindClient.calls[0].endpoint, '/api/teacher-subjects');
assert.deepEqual(unbindClient.calls[0].options.json, { subjectId: 5, userId: 9, academicYearId: 3, semesterNumber: 6 });
assert.deepEqual(unbindClient.calls[0].options.json, { subjectId: 5, userId: 9, academicYearId: 3, semesterNumber: 6, lessonTypeId: 2 });
// группировка привязок по строкам «дисциплина + семестр»
const grouped = groupBindingsByRow([
@@ -1620,6 +1648,11 @@ test('контракты привязки преподавателей к дис
assert.equal(bindingSemesterLabel('', null), 'Без семестра');
assert.equal(bindingSemesterLabel('2025-2026', null), '2025-2026 · без семестра');
// метка привязанного преподавателя с видом нагрузки
assert.equal(bindingTeacherLabel({ fullName: 'А', lessonTypeName: 'Лекция' }), 'А · Лекция');
assert.equal(bindingTeacherLabel({ fullName: 'А', lessonTypeName: null }), 'А');
assert.equal(bindingTeacherLabel({ userId: 9 }), 'ID 9');
// склонение счётчика привязок
assert.equal(bindingCountLabel(1), '1 привязка');
assert.equal(bindingCountLabel(3), '3 привязки');
@@ -2356,7 +2389,7 @@ test('контракты API просмотра расписаний сохра
'/api/groups/options?query=%D0%BF%D0%BE%D0%B8%D1%81%D0%BA&limit=30&selectedId=15&departmentId=4'
);
await fetchTeacherOptions('иванов', '', null, null, null, client);
await fetchTeacherOptions('иванов', '', null, null, null, null, client);
assert.equal(
client.calls[9].endpoint,
'/api/users/teachers/options?query=%D0%B8%D0%B2%D0%B0%D0%BD%D0%BE%D0%B2&limit=30'