feat: преподаватели дисциплин — привязки на странице кафедры и сужение в конструкторе правил
Кабинет кафедры: новая секция «Преподаватели дисциплин» — таблица дисциплин кафедры с колонкой привязанных преподавателей, панель управления с поиском по преподавателям кафедры (уже привязанные скрываются), отвязка с диалогом подтверждения. Привязки грузятся пачками по 100 дисциплин. Конструктор правил: список «Преподаватель» слота сужается до привязок выбранной дисциплины через GET /api/users/teachers/options?subjectId=… (новый параметр, запрос searchTeachersBySubjectBinding). До выбора дисциплины — подсказка «Сначала выберите дисциплину», без привязок — «К дисциплине не привязаны преподаватели». Смена дисциплины или группы сбрасывает преподавателей слотов; текущий преподаватель редактируемого правила остаётся в списке через selectedId. Тот же контракт в модалке конфликта слота.
This commit is contained in:
1 parent
deeee47cae
commit
ddf1850155
13 files changed
+599
-26
No files matched your search
@@ -679,6 +679,18 @@
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
/* Строка привязанного преподавателя: ФИО и кнопка «Отвязать» на одной линии */
|
||||
.department-binding-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.55rem 0.7rem;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--bg-card-border);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.department-comment-item p {
|
||||
margin-top: 0.5rem;
|
||||
color: var(--text-primary);
|
||||
|
||||
@@ -169,6 +169,66 @@ export function fetchDepartmentTeachers(departmentId, client = apiClient) {
|
||||
});
|
||||
}
|
||||
|
||||
// --- Привязки преподавателей к дисциплинам ---
|
||||
|
||||
// Опции преподавателей кафедры для привязки к дисциплине: поиск по кафедре,
|
||||
// выбранный преподаватель добавляется эндпоинтом через selectedId.
|
||||
export function departmentTeacherOptionsEndpoint(query, selectedId, departmentId) {
|
||||
const params = new URLSearchParams({ query: String(query || '').trim(), limit: '30' });
|
||||
if (selectedId) params.set('selectedId', selectedId);
|
||||
if (departmentId) params.set('departmentId', departmentId);
|
||||
return `/api/users/teachers/options?${params}`;
|
||||
}
|
||||
|
||||
export async function fetchDepartmentTeacherOptions(query, selectedId, departmentId, client = apiClient) {
|
||||
return client.get(departmentTeacherOptionsEndpoint(query, selectedId, departmentId), {
|
||||
errorMessage: 'Ошибка поиска преподавателей'
|
||||
});
|
||||
}
|
||||
|
||||
// Привязки преподавателей к дисциплинам кафедры: эндпоинт принимает не больше
|
||||
// 100 дисциплин за запрос, поэтому список делится на части.
|
||||
export async function fetchSubjectTeacherBindings(subjectIds, client = apiClient) {
|
||||
const ids = [...new Set((subjectIds || []).map(Number).filter(Boolean))];
|
||||
if (!ids.length) return [];
|
||||
const loaded = [];
|
||||
for (let index = 0; index < ids.length; index += 100) {
|
||||
const chunk = ids.slice(index, index + 100);
|
||||
const params = new URLSearchParams();
|
||||
chunk.forEach(subjectId => params.append('subjectId', String(subjectId)));
|
||||
const part = await client.get(`/api/teacher-subjects?${params}`, {
|
||||
errorMessage: 'Не удалось загрузить привязки преподавателей'
|
||||
});
|
||||
loaded.push(...(Array.isArray(part) ? part : []));
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
export function bindSubjectTeacher(subjectId, userId, client = apiClient) {
|
||||
return client.post(
|
||||
'/api/teacher-subjects',
|
||||
{ subjectId: Number(subjectId), userId: Number(userId) },
|
||||
{ errorMessage: 'Ошибка привязки преподавателя' }
|
||||
);
|
||||
}
|
||||
|
||||
export function unbindSubjectTeacher(subjectId, userId, client = apiClient) {
|
||||
return client.delete('/api/teacher-subjects', {
|
||||
json: { subjectId: Number(subjectId), userId: Number(userId) },
|
||||
errorMessage: 'Ошибка отвязки преподавателя'
|
||||
});
|
||||
}
|
||||
|
||||
export function groupBindingsBySubject(bindings) {
|
||||
const grouped = new Map();
|
||||
(bindings || []).forEach(binding => {
|
||||
const key = String(binding.subjectId);
|
||||
if (!grouped.has(key)) grouped.set(key, []);
|
||||
grouped.get(key).push(binding);
|
||||
});
|
||||
return grouped;
|
||||
}
|
||||
|
||||
export function fetchAllTeachers(client = apiClient) {
|
||||
return client.get('/api/users/teachers', {
|
||||
errorMessage: 'Ошибка загрузки преподавателей'
|
||||
@@ -257,6 +317,14 @@ export function subjectCountLabel(count) {
|
||||
return `${count} дисциплин`;
|
||||
}
|
||||
|
||||
export function bindingCountLabel(count) {
|
||||
const tail = count % 100;
|
||||
if (tail >= 11 && tail <= 14) return `${count} привязок`;
|
||||
if (count % 10 === 1) return `${count} привязка`;
|
||||
if ([2, 3, 4].includes(count % 10)) return `${count} привязки`;
|
||||
return `${count} привязок`;
|
||||
}
|
||||
|
||||
export function requestStatusLabel(status) {
|
||||
return {
|
||||
PENDING: 'На рассмотрении',
|
||||
|
||||
@@ -690,9 +690,10 @@ export function groupsOptionsEndpoint(query, selectedId, departmentId = '') {
|
||||
return `/api/groups/options?${params}`;
|
||||
}
|
||||
|
||||
export function teachersOptionsEndpoint(query, selectedId) {
|
||||
export function teachersOptionsEndpoint(query, selectedId, subjectId) {
|
||||
const params = new URLSearchParams({ query, limit: '30' });
|
||||
if (selectedId) params.set('selectedId', selectedId);
|
||||
if (subjectId) params.set('subjectId', subjectId);
|
||||
return `/api/users/teachers/options?${params}`;
|
||||
}
|
||||
|
||||
@@ -706,8 +707,8 @@ export async function fetchGroupOptions(query, selectedId, departmentId, client
|
||||
return client.get(groupsOptionsEndpoint(query, selectedId, departmentId), { errorMessage: 'Ошибка поиска групп' });
|
||||
}
|
||||
|
||||
export async function fetchTeacherOptions(query, selectedId, client = apiClient) {
|
||||
return client.get(teachersOptionsEndpoint(query, selectedId), { errorMessage: 'Ошибка поиска преподавателей' });
|
||||
export async function fetchTeacherOptions(query, selectedId, subjectId, client = apiClient) {
|
||||
return client.get(teachersOptionsEndpoint(query, selectedId, subjectId), { errorMessage: 'Ошибка поиска преподавателей' });
|
||||
}
|
||||
|
||||
export async function fetchClassroomOptions(query, selectedId, client = apiClient) {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||||
import { Pagination } from '../../shared/ui/Pagination.jsx';
|
||||
import { DepartmentDashboard, DepartmentTeacherList } from './DepartmentDashboard.jsx';
|
||||
import { departmentListPage, departmentWorkloadRows, departmentWorkloadSummary, filterDepartmentWorkload } from '../department-dashboard-service.js';
|
||||
import { AsyncCombobox } from '../../shared/ui/AsyncCombobox.jsx';
|
||||
import { ConfirmDialog } from '../../shared/ui/ConfirmDialog.jsx';
|
||||
|
||||
import { getSession } from '../../../admin/js/api.js';
|
||||
import { addDays, toIsoDate } from '../../shared/dates.js';
|
||||
@@ -16,18 +18,23 @@ import {
|
||||
assignTeacherError,
|
||||
attachmentGroupLabel,
|
||||
availableTeachers,
|
||||
bindSubjectTeacher,
|
||||
bindingCountLabel,
|
||||
defaultWorkloadPeriod,
|
||||
departmentOptionLabel,
|
||||
fetchAllTeachers,
|
||||
fetchDepartmentSubjectCalendar,
|
||||
fetchDepartmentTeacherOptions,
|
||||
fetchDepartmentTeacherRequests,
|
||||
fetchDepartmentTeachers,
|
||||
fetchDepartments,
|
||||
fetchSemesters,
|
||||
fetchSubjectComments,
|
||||
fetchSubjectTeacherBindings,
|
||||
fetchTeacherWorkload,
|
||||
filterDepartmentSubjects,
|
||||
formatDateTime,
|
||||
groupBindingsBySubject,
|
||||
importSubjects,
|
||||
importSubjectsPayload,
|
||||
listValuesLabel,
|
||||
@@ -39,6 +46,7 @@ import {
|
||||
submitTeacherRequest,
|
||||
teacherOptionLabel,
|
||||
teacherRequestPayload,
|
||||
unbindSubjectTeacher,
|
||||
uniqueAttachmentValues,
|
||||
} from '../department-workspace-service.js';
|
||||
|
||||
@@ -109,6 +117,11 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
|
||||
const [commentText, setCommentText] = useState('');
|
||||
const [commentAlert, setCommentAlert] = useState({ text: '', isError: false });
|
||||
|
||||
// Привязки преподавателей к дисциплинам кафедры.
|
||||
const [subjectBindings, setSubjectBindings] = useState({ items: [], error: '' });
|
||||
const [bindingPanel, setBindingPanel] = useState(null);
|
||||
const [unbindConfirm, setUnbindConfirm] = useState(null);
|
||||
|
||||
function currentDepartmentId() {
|
||||
return isDepartmentRole ? userDepartmentId : departmentIdRef.current;
|
||||
}
|
||||
@@ -219,16 +232,108 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
|
||||
const request = ++loadVersions.current.subjects;
|
||||
const department = currentDepartmentId();
|
||||
setSubjects({ loading: true, items: [], error: '' });
|
||||
setBindingPanel(null);
|
||||
setSubjectBindings({ items: [], error: '' });
|
||||
try {
|
||||
const items = await fetchDepartmentSubjectCalendar(department);
|
||||
if (request !== loadVersions.current.subjects || String(department) !== String(currentDepartmentId())) return;
|
||||
setSubjects({ loading: false, items: Array.isArray(items) ? items : [], error: '' });
|
||||
void loadSubjectBindings(items);
|
||||
} catch (error) {
|
||||
if (request !== loadVersions.current.subjects || String(department) !== String(currentDepartmentId())) return;
|
||||
setSubjects({ loading: false, items: [], error: error.message || 'Ошибка загрузки дисциплин' });
|
||||
}
|
||||
}
|
||||
|
||||
// --- Привязки преподавателей к дисциплинам ---
|
||||
|
||||
async function loadSubjectBindings(subjectItems) {
|
||||
const items = Array.isArray(subjectItems) ? subjectItems : [];
|
||||
if (!items.length) {
|
||||
setSubjectBindings({ items: [], error: '' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const loaded = await fetchSubjectTeacherBindings(items.map(subject => subject.id));
|
||||
setSubjectBindings({ items: loaded, error: '' });
|
||||
} catch (error) {
|
||||
setSubjectBindings({ items: [], error: error.message || 'Не удалось загрузить привязки преподавателей' });
|
||||
}
|
||||
}
|
||||
|
||||
function toggleBindingPanel(subject) {
|
||||
setBindingPanel(current => (
|
||||
current && String(current.subjectId) === String(subject.id)
|
||||
? null
|
||||
: { subjectId: subject.id, subjectName: subject.name || '', selectedTeacher: null, alert: { text: '', isError: false } }
|
||||
));
|
||||
}
|
||||
|
||||
async function searchBindingTeachers(query, selectedId) {
|
||||
const teachers = await fetchDepartmentTeacherOptions(query, selectedId, currentDepartmentId());
|
||||
const bound = new Set(
|
||||
(bindingsBySubject.get(String(bindingPanel?.subjectId)) || [])
|
||||
.map(binding => String(binding.userId))
|
||||
);
|
||||
return (teachers || []).filter(teacher =>
|
||||
!bound.has(String(teacher.id)) || String(teacher.id) === String(selectedId));
|
||||
}
|
||||
|
||||
async function submitBinding(event) {
|
||||
event.preventDefault();
|
||||
const panel = bindingPanel;
|
||||
if (!panel) return;
|
||||
if (!panel.selectedTeacher) {
|
||||
setBindingPanel({ ...panel, alert: { text: 'Выберите преподавателя', isError: true } });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await bindSubjectTeacher(panel.subjectId, panel.selectedTeacher.id);
|
||||
setBindingPanel(current => (
|
||||
current
|
||||
? { ...current, selectedTeacher: null, alert: { text: 'Преподаватель привязан к дисциплине', isError: false } }
|
||||
: current
|
||||
));
|
||||
await loadSubjectBindings(subjects.items);
|
||||
} catch (error) {
|
||||
setBindingPanel(current => (
|
||||
current
|
||||
? { ...current, alert: { text: error.message || 'Ошибка привязки преподавателя', isError: true } }
|
||||
: current
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
function confirmUnbind(binding) {
|
||||
const panel = bindingPanel;
|
||||
if (!panel) return;
|
||||
const teacherName = binding.fullName || binding.username || `ID ${binding.userId}`;
|
||||
setUnbindConfirm({
|
||||
title: 'Отвязать преподавателя от дисциплины?',
|
||||
message: `${teacherName} больше не будет доступен для дисциплины «${panel.subjectName || 'дисциплина'}» в новых правилах.`,
|
||||
confirmLabel: 'Отвязать',
|
||||
danger: true,
|
||||
action: async () => {
|
||||
try {
|
||||
await unbindSubjectTeacher(panel.subjectId, binding.userId);
|
||||
await loadSubjectBindings(subjects.items);
|
||||
} catch (error) {
|
||||
setBindingPanel(current => (
|
||||
current
|
||||
? { ...current, alert: { text: error.message || 'Ошибка отвязки преподавателя', isError: true } }
|
||||
: current
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function runUnbindConfirm() {
|
||||
const confirm = unbindConfirm;
|
||||
setUnbindConfirm(null);
|
||||
await confirm.action();
|
||||
}
|
||||
|
||||
async function loadTeachers() {
|
||||
const request = ++loadVersions.current.teachers;
|
||||
const department = currentDepartmentId();
|
||||
@@ -452,6 +557,10 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
|
||||
const subjectsCountLabel = subjects.error
|
||||
? 'Не удалось загрузить дисциплины'
|
||||
: (subjects.loading ? 'Загрузка...' : subjectCountLabel(visibleSubjects.length));
|
||||
const bindingsBySubject = groupBindingsBySubject(subjectBindings.items);
|
||||
const bindingsCountLabel = subjectBindings.error
|
||||
? '0 привязок'
|
||||
: bindingCountLabel(subjectBindings.items.length);
|
||||
|
||||
const pagedSubjects = departmentListPage(visibleSubjects, subjectPage, subjectSize);
|
||||
const withoutCalendarCount = subjects.loading || subjects.error ? null : filterDepartmentSubjects(subjects.items, 'manual').length;
|
||||
@@ -967,7 +1076,151 @@ export function DepartmentWorkspaceTab({ section = 'overview' } = {}) {
|
||||
</div>
|
||||
{!subjects.loading && !subjects.error && <Pagination id="department-subjects-pagination" {...pagedSubjects}
|
||||
label="дисциплин" onPage={setSubjectPage} onSize={value => { setSubjectSize(value); setSubjectPage(0); }} />}
|
||||
|
||||
<div className="card department-workspace-table-card" id="department-binding-card">
|
||||
<div className="card-header-row">
|
||||
<h2>Преподаватели дисциплин</h2>
|
||||
<span className="muted" id="department-binding-count">{bindingsCountLabel}</span>
|
||||
</div>
|
||||
<div className="table-wrap">
|
||||
<table id="department-binding-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Код</th>
|
||||
<th>Название</th>
|
||||
<th>Преподаватели</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="department-binding-tbody">
|
||||
{subjects.loading ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="loading-row">Загрузка...</td>
|
||||
</tr>
|
||||
) : subjects.error ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="loading-row">{subjects.error}</td>
|
||||
</tr>
|
||||
) : subjects.items.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="loading-row">Дисциплины не найдены</td>
|
||||
</tr>
|
||||
) : subjects.items.map(subject => {
|
||||
const bound = bindingsBySubject.get(String(subject.id)) || [];
|
||||
const panelOpen = bindingPanel && String(bindingPanel.subjectId) === String(subject.id);
|
||||
return (
|
||||
<Fragment key={subject.id}>
|
||||
<tr>
|
||||
<td>{subject.code || '-'}</td>
|
||||
<td>{subject.name || '-'}</td>
|
||||
<td>
|
||||
{subjectBindings.error ? (
|
||||
<span className="text-muted">{subjectBindings.error}</span>
|
||||
) : bound.length === 0 ? (
|
||||
<span className="text-muted">Не привязаны</span>
|
||||
) : (
|
||||
<span>{bound.map(binding => binding.fullName || binding.username).join(', ')}</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-secondary department-binding-open"
|
||||
aria-expanded={panelOpen ? 'true' : 'false'}
|
||||
onClick={() => toggleBindingPanel(subject)}
|
||||
>
|
||||
{panelOpen ? 'Скрыть' : 'Открыть'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{panelOpen && (
|
||||
<tr className="department-comments-row" id="department-binding-row">
|
||||
<td colSpan={4}>
|
||||
<div className="department-comments-card" id="department-binding-panel">
|
||||
<div className="card-header-row">
|
||||
<h3 id="department-binding-title">
|
||||
Преподаватели: {bindingPanel.subjectName || 'дисциплина'}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-ghost"
|
||||
id="department-binding-close"
|
||||
onClick={() => setBindingPanel(null)}
|
||||
>
|
||||
Скрыть
|
||||
</button>
|
||||
</div>
|
||||
<form id="department-binding-form" className="form-row" onSubmit={submitBinding}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="department-binding-teacher">Преподаватель кафедры</label>
|
||||
<AsyncCombobox
|
||||
ariaLabel="Поиск преподавателя для привязки"
|
||||
placeholder="Найдите преподавателя по ФИО"
|
||||
emptyLabel="Преподаватели не найдены"
|
||||
load={(query, selectedId) => searchBindingTeachers(query, selectedId)}
|
||||
optionLabel={teacher => teacher.fullName || teacher.username}
|
||||
optionDescription={teacher => [teacher.jobTitle, teacher.departmentName].filter(Boolean).join(' · ')}
|
||||
onSelect={teacher => setBindingPanel(current => (
|
||||
current ? { ...current, selectedTeacher: teacher } : current
|
||||
))}
|
||||
selectedLabel={bindingPanel.selectedTeacher
|
||||
? (bindingPanel.selectedTeacher.fullName || bindingPanel.selectedTeacher.username)
|
||||
: ''}
|
||||
selectedValue={bindingPanel.selectedTeacher
|
||||
? String(bindingPanel.selectedTeacher.id)
|
||||
: ''}
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="btn btn-md btn-primary">Привязать</button>
|
||||
</form>
|
||||
<div
|
||||
className={`form-alert${bindingPanel.alert.text ? (bindingPanel.alert.isError ? ' error' : ' success') : ''}`}
|
||||
id="department-binding-alert"
|
||||
role="alert"
|
||||
>
|
||||
{bindingPanel.alert.text}
|
||||
</div>
|
||||
<div className="department-comment-list" id="department-binding-list">
|
||||
{subjectBindings.error ? (
|
||||
<div className="loading-row">{subjectBindings.error}</div>
|
||||
) : bound.length === 0 ? (
|
||||
<div className="loading-row">Привязанных преподавателей пока нет</div>
|
||||
) : bound.map(binding => (
|
||||
<div className="department-binding-item" key={`${binding.subjectId}-${binding.userId}`}>
|
||||
<span>{binding.fullName || binding.username || `ID ${binding.userId}`}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => confirmUnbind(binding)}
|
||||
>
|
||||
Отвязать
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{unbindConfirm && (
|
||||
<ConfirmDialog
|
||||
title={unbindConfirm.title}
|
||||
message={unbindConfirm.message}
|
||||
confirmLabel={unbindConfirm.confirmLabel}
|
||||
danger={unbindConfirm.danger}
|
||||
onConfirm={() => void runUnbindConfirm()}
|
||||
onClose={() => setUnbindConfirm(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -790,7 +790,11 @@ export function ScheduleTab() {
|
||||
|
||||
function handleSubjectChange(event) {
|
||||
dirtyScopeRef.current?.mark();
|
||||
setRuleSubjectId(event.target.value);
|
||||
const value = event.target.value;
|
||||
setRuleSubjectId(value);
|
||||
// Преподаватели слотов зависят от привязок дисциплины — сбрасываем
|
||||
// выбранных преподавателей при смене дисциплины.
|
||||
setSlots(current => current.map(slot => ({ ...slot, teacherId: '', teacherName: '' })));
|
||||
}
|
||||
|
||||
// Группа в начале формы — фильтр дисциплин по календарному графику.
|
||||
@@ -801,6 +805,8 @@ export function ScheduleTab() {
|
||||
dirtyScopeRef.current?.mark();
|
||||
setRuleFilterGroupId(value);
|
||||
setRuleSubjectId('');
|
||||
// Вместе с дисциплиной сбрасываются и преподаватели слотов.
|
||||
setSlots(current => current.map(slot => ({ ...slot, teacherId: '', teacherName: '' })));
|
||||
if (!value) return;
|
||||
const groupId = Number(value);
|
||||
const previous = latestRef.current.selectedGroupIds;
|
||||
@@ -1745,6 +1751,7 @@ export function ScheduleTab() {
|
||||
subgroups={subgroups}
|
||||
selectedGroupIds={selectedGroupIds}
|
||||
semesterId={ruleSemesterId}
|
||||
subjectId={ruleSubjectId}
|
||||
preferences={approvedPreferences}
|
||||
subgroupMenuOpen={subgroupMenuOpenIndex === index}
|
||||
onToggleSubgroupMenu={handleSlotSubgroupToggle}
|
||||
@@ -1807,6 +1814,7 @@ export function ScheduleTab() {
|
||||
index={index}
|
||||
conflictFields={conflict.conflictFields}
|
||||
timeSlotOptions={timeSlotOptions}
|
||||
subjectId={conflict.conflictRule?.subjectId || ''}
|
||||
onSlotChange={handleConflictSlotChange}
|
||||
/>
|
||||
))}
|
||||
@@ -2063,7 +2071,7 @@ export function ScheduleTab() {
|
||||
function RuleSlotRow({
|
||||
slot, index, slotCount, disabled,
|
||||
timeSlotOptions, lessonTypeOptions, lessonTypes, subgroups, selectedGroupIds,
|
||||
semesterId, preferences,
|
||||
semesterId, subjectId, preferences,
|
||||
subgroupMenuOpen, onToggleSubgroupMenu, onChange, onRemove
|
||||
}) {
|
||||
const isSingle = slotCount === 1;
|
||||
@@ -2110,10 +2118,12 @@ function RuleSlotRow({
|
||||
ariaLabel={`Преподаватель слота ${index + 1}`}
|
||||
allowClear={false}
|
||||
placeholder="Найдите преподавателя"
|
||||
emptyLabel="Преподаватели не найдены"
|
||||
emptyLabel={subjectId ? 'К дисциплине не привязаны преподаватели' : 'Сначала выберите дисциплину'}
|
||||
optionLabel={teacherOptionLabel}
|
||||
optionDescription={teacherOptionDescription}
|
||||
load={(query, selectedId) => fetchTeacherOptions(query, selectedId)}
|
||||
load={(query, selectedId) => (subjectId
|
||||
? fetchTeacherOptions(query, selectedId, subjectId)
|
||||
: Promise.resolve([]))}
|
||||
selectedValue={slot.teacherId}
|
||||
selectedLabel={slot.teacherName}
|
||||
onSelect={teacher => onChange(index, teacher
|
||||
@@ -2260,7 +2270,7 @@ function RuleSlotRow({
|
||||
|
||||
// --- Строка слота конфликтующего правила ---
|
||||
|
||||
function ConflictSlotRow({ slot, index, conflictFields, timeSlotOptions, onSlotChange }) {
|
||||
function ConflictSlotRow({ slot, index, conflictFields, timeSlotOptions, subjectId, onSlotChange }) {
|
||||
const original = slot.original || {};
|
||||
const fixedParts = [
|
||||
original.lessonTypeName,
|
||||
@@ -2302,10 +2312,12 @@ function ConflictSlotRow({ slot, index, conflictFields, timeSlotOptions, onSlotC
|
||||
ariaLabel={`Преподаватель конфликтующего слота ${index + 1}`}
|
||||
allowClear={false}
|
||||
placeholder="Найдите преподавателя"
|
||||
emptyLabel="Преподаватели не найдены"
|
||||
emptyLabel={subjectId ? 'К дисциплине не привязаны преподаватели' : 'Преподаватели не найдены'}
|
||||
optionLabel={teacherOptionLabel}
|
||||
optionDescription={teacherOptionDescription}
|
||||
load={(query, selectedId) => fetchTeacherOptions(query, selectedId)}
|
||||
load={(query, selectedId) => (subjectId
|
||||
? fetchTeacherOptions(query, selectedId, subjectId)
|
||||
: fetchTeacherOptions(query, selectedId))}
|
||||
selectedValue={slot.teacherId}
|
||||
selectedLabel={slot.teacherName}
|
||||
onSelect={teacher => onSlotChange(index, teacher
|
||||
|
||||
@@ -12,6 +12,11 @@ const readFrontendFile = relativePath => readFile(
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const readBackendFile = relativePath => readFile(
|
||||
new URL(`../../backend/${relativePath}`, import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
test('одиночный слот очищается, а несколько слотов удаляются', () => {
|
||||
assert.equal(scheduleSlotActionLabel(1), 'Очистить');
|
||||
assert.equal(scheduleSlotActionLabel(2), 'Удалить');
|
||||
@@ -108,6 +113,28 @@ test('форма правила фильтрует дисциплины по г
|
||||
assert.match(scheduleService, /\/api\/admin\/schedule-rules\/subject-options\?/);
|
||||
});
|
||||
|
||||
test('преподаватель слота формы правила сужается до привязок выбранной дисциплины', async () => {
|
||||
const [scheduleTab, scheduleViewService, userController] = await Promise.all([
|
||||
readFrontendFile('react/admin/tabs/ScheduleTab.jsx'),
|
||||
readFrontendFile('react/admin/schedule-view-service.js'),
|
||||
readBackendFile('src/main/java/com/magistr/app/controller/UserController.java')
|
||||
]);
|
||||
|
||||
// слот без дисциплины не ищет преподавателей, с дисциплиной — ищет по привязкам
|
||||
assert.match(scheduleTab, /Сначала выберите дисциплину/);
|
||||
assert.match(scheduleTab, /К дисциплине не привязаны преподаватели/);
|
||||
assert.match(scheduleTab, /fetchTeacherOptions\(query, selectedId, subjectId\)/);
|
||||
// смена дисциплины сбрасывает преподавателей слотов
|
||||
assert.match(
|
||||
scheduleTab,
|
||||
/setRuleSubjectId\(value\);\s*\n\s*\/\/ Преподаватели слотов зависят от привязок дисциплины/s
|
||||
);
|
||||
assert.match(scheduleViewService, /params\.set\('subjectId', subjectId\)/);
|
||||
// эндпоинт опций преподавателей принимает subjectId и ищет по привязкам
|
||||
assert.match(userController, /@RequestParam\(required = false\) Long subjectId/);
|
||||
assert.match(userController, /searchTeachersBySubjectBinding\(/);
|
||||
});
|
||||
|
||||
test('все варианты системных кнопок имеют видимую обводку', async () => {
|
||||
const components = await readFrontendFile('admin/css/components.css');
|
||||
|
||||
|
||||
@@ -114,17 +114,23 @@ import {
|
||||
assignTeacherError,
|
||||
attachmentGroupLabel,
|
||||
availableTeachers,
|
||||
bindingCountLabel,
|
||||
bindSubjectTeacher,
|
||||
departmentSubjectCalendarEndpoint,
|
||||
departmentSubjectsEndpoint,
|
||||
departmentTeacherOptionsEndpoint,
|
||||
departmentTeacherRequestsEndpoint,
|
||||
departmentTeachersEndpoint,
|
||||
fetchDepartmentSubjectCalendar,
|
||||
fetchDepartmentSubjects,
|
||||
fetchDepartmentTeacherOptions,
|
||||
fetchDepartmentTeacherRequests,
|
||||
fetchDepartmentTeachers,
|
||||
fetchSubjectTeacherBindings,
|
||||
fetchTeacherWorkload,
|
||||
filterDepartmentSubjects,
|
||||
formatDateTime,
|
||||
groupBindingsBySubject,
|
||||
importSubjects,
|
||||
importSubjectsPayload,
|
||||
listValuesLabel,
|
||||
@@ -138,6 +144,7 @@ import {
|
||||
teacherOptionLabel,
|
||||
teacherRequestPayload,
|
||||
teacherWorkloadEndpoint,
|
||||
unbindSubjectTeacher,
|
||||
uniqueAttachmentValues,
|
||||
workloadLabel
|
||||
} from '../react/admin/department-workspace-service.js';
|
||||
@@ -1444,10 +1451,89 @@ test('вкладка кабинета кафедры рендерит формы
|
||||
assert.match(markup, /Профиль/);
|
||||
assert.match(markup, /Вид нагрузки/);
|
||||
assert.match(markup, /Календарный график/);
|
||||
assert.match(markup, /Преподаватели дисциплин/);
|
||||
assert.match(markup, /id="department-binding-card"/);
|
||||
assert.match(markup, /id="department-binding-table"/);
|
||||
assert.match(markup, /id="department-binding-tbody"/);
|
||||
assert.match(markup, /id="department-binding-count"/);
|
||||
assert.match(markup, /Загрузка\.\.\./);
|
||||
assert.doesNotMatch(markup, /style="/);
|
||||
// карточка комментариев скрыта до выбора дисциплины
|
||||
assert.doesNotMatch(markup, /department-comments-card/);
|
||||
// панель привязки преподавателей скрыта до выбора дисциплины
|
||||
assert.doesNotMatch(markup, /id="department-binding-panel"/);
|
||||
});
|
||||
|
||||
test('контракты привязки преподавателей к дисциплинам кафедры', async () => {
|
||||
// опции преподавателей кафедры для привязки
|
||||
assert.equal(
|
||||
departmentTeacherOptionsEndpoint('ivan', 7, 3),
|
||||
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7&departmentId=3'
|
||||
);
|
||||
assert.equal(
|
||||
departmentTeacherOptionsEndpoint(' ', null, null),
|
||||
'/api/users/teachers/options?query=&limit=30'
|
||||
);
|
||||
|
||||
const teachersClient = recordingClient(async () => [{ id: 7, fullName: 'Иванов И. И.' }]);
|
||||
const teachers = await fetchDepartmentTeacherOptions('ivan', 7, 3, teachersClient);
|
||||
assert.equal(teachers[0].fullName, 'Иванов И. И.');
|
||||
assert.equal(teachersClient.calls[0].endpoint, '/api/users/teachers/options?query=ivan&limit=30&selectedId=7&departmentId=3');
|
||||
|
||||
// опции преподавателей слота сужаются до привязок дисциплины
|
||||
assert.equal(
|
||||
teachersOptionsEndpoint('ivan', 7, 5),
|
||||
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5'
|
||||
);
|
||||
assert.equal(
|
||||
teachersOptionsEndpoint('ivan', 7, null),
|
||||
'/api/users/teachers/options?query=ivan&limit=30&selectedId=7'
|
||||
);
|
||||
const subjectTeachersClient = recordingClient(async () => [{ id: 7, fullName: 'Иванов И. И.' }]);
|
||||
await fetchTeacherOptions('ivan', 7, 5, subjectTeachersClient);
|
||||
assert.equal(subjectTeachersClient.calls[0].endpoint, '/api/users/teachers/options?query=ivan&limit=30&selectedId=7&subjectId=5');
|
||||
|
||||
// привязки: больше 100 дисциплин делятся на отдельные запросы
|
||||
const subjectIds = Array.from({ length: 150 }, (_, index) => index + 1);
|
||||
const bindingsClient = recordingClient(async () => []);
|
||||
await fetchSubjectTeacherBindings(subjectIds, bindingsClient);
|
||||
assert.equal(bindingsClient.calls.length, 2);
|
||||
assert.equal(bindingsClient.calls[0].endpoint.split('subjectId=').length - 1, 100);
|
||||
assert.equal(bindingsClient.calls[1].endpoint.split('subjectId=').length - 1, 50);
|
||||
assert.ok(bindingsClient.calls[0].endpoint.startsWith('/api/teacher-subjects?'));
|
||||
|
||||
// пустой список дисциплин не делает запросов
|
||||
const emptyClient = recordingClient(async () => []);
|
||||
assert.deepEqual(await fetchSubjectTeacherBindings([], emptyClient), []);
|
||||
assert.equal(emptyClient.calls.length, 0);
|
||||
|
||||
// привязка и отвязка преподавателя
|
||||
const bindClient = recordingClient(async () => ({ message: 'Привязка создана' }));
|
||||
await bindSubjectTeacher(5, 9, 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 });
|
||||
|
||||
const unbindClient = recordingClient(async () => ({ message: 'Привязка удалена' }));
|
||||
await unbindSubjectTeacher(5, 9, unbindClient);
|
||||
assert.equal(unbindClient.calls[0].method, 'DELETE');
|
||||
assert.equal(unbindClient.calls[0].endpoint, '/api/teacher-subjects');
|
||||
|
||||
// группировка привязок по дисциплинам
|
||||
const grouped = groupBindingsBySubject([
|
||||
{ subjectId: 5, userId: 1, fullName: 'А' },
|
||||
{ subjectId: 5, userId: 2, fullName: 'Б' },
|
||||
{ subjectId: 6, userId: 3, fullName: 'В' }
|
||||
]);
|
||||
assert.equal(grouped.get('5').length, 2);
|
||||
assert.equal(grouped.get('6').length, 1);
|
||||
assert.equal(grouped.get('7'), undefined);
|
||||
|
||||
// склонение счётчика привязок
|
||||
assert.equal(bindingCountLabel(1), '1 привязка');
|
||||
assert.equal(bindingCountLabel(3), '3 привязки');
|
||||
assert.equal(bindingCountLabel(11), '11 привязок');
|
||||
assert.equal(bindingCountLabel(25), '25 привязок');
|
||||
});
|
||||
|
||||
test('дисциплины кафедры фильтруются по прикреплению к графикам', () => {
|
||||
@@ -2179,7 +2265,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('иванов', '', client);
|
||||
await fetchTeacherOptions('иванов', '', 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'
|
||||
|
||||
Reference in new issue
Block a user