А. Учебный план (семестр, дисциплины, часы)
This commit is contained in:
1 parent
7d53e6ef60
commit
9b3c76de89
29 files changed
+2516
-78
No files matched your search
@@ -4705,3 +4705,28 @@ tbody tr:hover {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Учебные планы: компактный рабочий лист с отдельным итогом нагрузки. */
|
||||
.study-plans-workspace { display: grid; gap: 20px; }
|
||||
.study-plan-heading { display: flex; justify-content: space-between; align-items: center; gap: 20px; flex-wrap: wrap; margin-bottom: 18px; }
|
||||
.study-plan-heading h2, .study-plan-heading h3 { margin: 0 0 6px; }
|
||||
.study-plan-kicker { margin: 0 0 6px; color: var(--text-secondary); font-size: .78rem; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.study-plan-controls { display: flex; flex-wrap: wrap; gap: 16px; align-items: end; margin: 18px 0; }
|
||||
.study-plan-controls .form-group { flex: 1 1 230px; }
|
||||
.study-plan-fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||
.study-plan-totals { display: flex; gap: 24px; padding: 14px 20px; border-left: 3px solid var(--accent); background: var(--bg-hover); }
|
||||
.study-plan-totals span { display: grid; gap: 4px; font-size: .85rem; }
|
||||
.study-plan-totals strong { font-size: 1.45rem; font-variant-numeric: tabular-nums; }
|
||||
.study-plan-subject-editor { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--bg-card-border); }
|
||||
.study-plan-load-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin: 16px 0; }
|
||||
.study-plan-load-card { padding: 18px; background: var(--bg-hover); border: 1px solid var(--bg-card-border); border-radius: 8px; }
|
||||
.study-plan-load-card h4 { margin-top: 0; }
|
||||
.study-plan-load-total { font-variant-numeric: tabular-nums; }
|
||||
.study-plan-check { display: flex; gap: 8px; align-items: center; }
|
||||
.study-plan-row-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.study-plan-table .badge { display: block; width: fit-content; margin-top: 6px; }
|
||||
.study-plan-delete { margin-top: 18px; }
|
||||
@media (max-width: 900px) { .study-plan-load-grid { grid-template-columns: 1fr; } .study-plan-totals { width: 100%; } }
|
||||
|
||||
.study-plan-alert.success { color: var(--success); }
|
||||
.study-plan-alert.error { color: var(--error); }
|
||||
@@ -1,19 +1,19 @@
|
||||
const capabilities = {
|
||||
ADMIN: {
|
||||
defaultAdminTab: 'dashboard',
|
||||
adminTabs: ['dashboard', 'teacher-requests', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar', 'auditorium-workload', 'schedule-view', 'teacher-absences', 'classrooms', 'groups', 'university-structure', 'subjects', 'users'],
|
||||
adminTabs: ['dashboard', 'teacher-requests', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar', 'study-plans', 'auditorium-workload', 'schedule-view', 'teacher-absences', 'classrooms', 'groups', 'university-structure', 'subjects', 'users'],
|
||||
defaultSettingsTab: 'general',
|
||||
settingsTabs: ['general', 'time-slots', 'database', 'edu-forms']
|
||||
},
|
||||
EDUCATION_OFFICE: {
|
||||
defaultAdminTab: 'dashboard',
|
||||
adminTabs: ['dashboard', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar', 'auditorium-workload', 'schedule-view', 'teacher-absences', 'classrooms'],
|
||||
adminTabs: ['dashboard', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar', 'study-plans', 'auditorium-workload', 'schedule-view', 'teacher-absences', 'classrooms'],
|
||||
defaultSettingsTab: 'time-slots',
|
||||
settingsTabs: ['time-slots', 'edu-forms']
|
||||
},
|
||||
DEPARTMENT: {
|
||||
defaultAdminTab: 'department-workspace',
|
||||
adminTabs: ['department-workspace', 'department-requests', 'department-management', 'department-bindings', 'schedule-view', 'teacher-absences'],
|
||||
adminTabs: ['department-workspace', 'department-requests', 'department-management', 'department-bindings', 'study-plans', 'schedule-view', 'teacher-absences'],
|
||||
defaultSettingsTab: null,
|
||||
settingsTabs: []
|
||||
},
|
||||
|
||||
@@ -84,6 +84,12 @@ const ICONS = Object.freeze({
|
||||
<path d="M2 19h20" />
|
||||
</svg>
|
||||
),
|
||||
'study-plans': (
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M4 3h12a4 4 0 0 1 4 4v14H8a4 4 0 0 1-4-4z" />
|
||||
<path d="M4 17a4 4 0 0 1 4-4h12M8 6h8M8 9h6" />
|
||||
</svg>
|
||||
),
|
||||
'academic-calendar': (
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M3 3h18v18H3z" />
|
||||
|
||||
@@ -19,6 +19,7 @@ export const ADMIN_ROUTES = Object.freeze({
|
||||
schedule: { title: 'Конструктор правил' },
|
||||
'schedule-versions': { title: 'Версии расписания' },
|
||||
'schedule-quality': { title: 'Анализ качества расписания' },
|
||||
'study-plans': { title: 'Учебные планы' },
|
||||
'academic-calendar': { title: 'Календарный учебный график' },
|
||||
'auditorium-workload': { title: 'Загруженность' },
|
||||
'teacher-absences': { title: 'Запросы преподавателей' }
|
||||
@@ -34,6 +35,7 @@ const NAV_ITEMS = Object.freeze({
|
||||
schedule: { navLabel: 'Конструктор правил' },
|
||||
'schedule-versions': { navLabel: 'Версии расписания' },
|
||||
'schedule-quality': { navLabel: 'Качество расписания' },
|
||||
'study-plans': { navLabel: 'Учебные планы' },
|
||||
'academic-calendar': { navLabel: 'Календарный график' },
|
||||
'auditorium-workload': { navLabel: 'Загруженность' },
|
||||
'schedule-view': { navLabel: 'Просмотр расписаний' },
|
||||
@@ -54,6 +56,7 @@ const NAV_SECTIONS = Object.freeze([
|
||||
'schedule-versions',
|
||||
'schedule-quality',
|
||||
'academic-calendar',
|
||||
'study-plans',
|
||||
'auditorium-workload',
|
||||
'schedule-view',
|
||||
'teacher-absences'
|
||||
|
||||
Vendored
+1
@@ -9,6 +9,7 @@ import { lazy } from 'react';
|
||||
export const REACT_TABS = Object.freeze({
|
||||
dashboard: { Component: lazy(() => import('./tabs/DashboardTab.jsx').then(m => ({ default: m.DashboardTab }))) },
|
||||
classrooms: { Component: lazy(() => import('./tabs/ClassroomsTab.jsx').then(m => ({ default: m.ClassroomsTab }))) },
|
||||
'study-plans': { Component: lazy(() => import('./tabs/StudyPlansTab.jsx').then(m => ({ default: m.StudyPlansTab }))) },
|
||||
subjects: { Component: lazy(() => import('./tabs/SubjectsTab.jsx').then(m => ({ default: m.SubjectsTab }))) },
|
||||
users: { Component: lazy(() => import('./tabs/UsersTab.jsx').then(m => ({ default: m.UsersTab }))) },
|
||||
groups: { Component: lazy(() => import('./tabs/GroupsTab.jsx').then(m => ({ default: m.GroupsTab }))) },
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { apiClient } from '../shared/api-client.js';
|
||||
|
||||
export const LOAD_CATEGORIES = Object.freeze([
|
||||
{ key: 'LECTURE', label: 'Лекции' },
|
||||
{ key: 'PRACTICE', label: 'Практики' },
|
||||
{ key: 'LABORATORY', label: 'Лабораторные' },
|
||||
]);
|
||||
export function emptyPlanForm() {
|
||||
return {
|
||||
title: '',
|
||||
specialtyProfileId: '',
|
||||
educationFormId: '',
|
||||
semesterNumber: 1,
|
||||
};
|
||||
}
|
||||
export function loadDraft(subject) {
|
||||
return LOAD_CATEGORIES.map(({ key }) => {
|
||||
const existing = subject?.loads?.find((load) => load.category === key);
|
||||
return {
|
||||
category: key,
|
||||
academicHours: existing?.academicHours ?? 0,
|
||||
splitSubgroups: existing?.splitSubgroups ?? false,
|
||||
teacherId: existing?.teacherId ?? null,
|
||||
teacherName: existing?.teacherName ?? '',
|
||||
};
|
||||
});
|
||||
}
|
||||
export function workloadHours(load) {
|
||||
return (
|
||||
Number(load.academicHours || 0) *
|
||||
(load.category === 'LABORATORY' && load.splitSubgroups ? 2 : 1)
|
||||
);
|
||||
}
|
||||
export function subjectPayload(loads, expectedRevision) {
|
||||
const payload = loads.map((load) => ({
|
||||
category: load.category,
|
||||
academicHours: Number(load.academicHours),
|
||||
splitSubgroups:
|
||||
load.category === 'LABORATORY' && Boolean(load.splitSubgroups),
|
||||
teacherId: load.teacherId ? Number(load.teacherId) : null,
|
||||
}));
|
||||
if (
|
||||
payload.some(
|
||||
(load) =>
|
||||
!Number.isInteger(load.academicHours) ||
|
||||
load.academicHours < 0 ||
|
||||
load.academicHours > 100000 ||
|
||||
load.academicHours % 2,
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'Академические часы должны быть чётными, от 0 до 100000',
|
||||
);
|
||||
}
|
||||
if (!payload.some((load) => load.academicHours > 0))
|
||||
throw new Error('Укажите часы хотя бы одного вида нагрузки');
|
||||
if (
|
||||
payload.some(
|
||||
(load) =>
|
||||
!load.academicHours && (load.teacherId || load.splitSubgroups),
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'Для нулевой нагрузки снимите деление на подгруппы и назначение преподавателя',
|
||||
);
|
||||
}
|
||||
return { expectedRevision, loads: payload };
|
||||
}
|
||||
export function compatibleGroups(metadata, plan, semesterId) {
|
||||
const semester = metadata?.semesters.find(
|
||||
(item) => String(item.id) === String(semesterId),
|
||||
);
|
||||
if (!semester || !plan) return [];
|
||||
return metadata.groups.filter(
|
||||
(group) =>
|
||||
group.specialtyProfileId === plan.specialtyProfileId &&
|
||||
group.educationFormId === plan.educationFormId &&
|
||||
(semester.startYear - group.yearStartStudy) * 2 +
|
||||
(semester.semesterType === 'autumn' ? 1 : 2) ===
|
||||
plan.semesterNumber,
|
||||
);
|
||||
}
|
||||
export const fetchPlans = () =>
|
||||
apiClient.get('/api/study-plans', {
|
||||
errorMessage: 'Не удалось загрузить учебные планы',
|
||||
});
|
||||
export const fetchPlanMetadata = () =>
|
||||
apiClient.get('/api/study-plans/metadata', {
|
||||
errorMessage: 'Не удалось загрузить справочники учебных планов',
|
||||
});
|
||||
export const fetchPlan = (id) =>
|
||||
apiClient.get(`/api/study-plans/${id}`, {
|
||||
errorMessage: 'Не удалось загрузить учебный план',
|
||||
});
|
||||
export const savePlan = (id, form, revision) => {
|
||||
const payload = {
|
||||
title: form.title.trim(),
|
||||
specialtyProfileId: Number(form.specialtyProfileId),
|
||||
educationFormId: Number(form.educationFormId),
|
||||
semesterNumber: Number(form.semesterNumber),
|
||||
expectedRevision: revision,
|
||||
};
|
||||
return id
|
||||
? apiClient.put(`/api/study-plans/${id}`, payload)
|
||||
: apiClient.post('/api/study-plans', payload);
|
||||
};
|
||||
export const savePlanSubject = (id, subjectId, loads, revision) =>
|
||||
apiClient.put(
|
||||
`/api/study-plans/${id}/subjects/${subjectId}`,
|
||||
subjectPayload(loads, revision),
|
||||
);
|
||||
export const removePlanSubject = (id, subjectId, revision) =>
|
||||
apiClient.delete(
|
||||
`/api/study-plans/${id}/subjects/${subjectId}?expectedRevision=${revision}`,
|
||||
);
|
||||
export const assignPlan = (id, groupId, semesterId) =>
|
||||
apiClient.post(`/api/study-plans/${id}/assignments`, {
|
||||
groupId: Number(groupId),
|
||||
semesterId: Number(semesterId),
|
||||
});
|
||||
export const unassignPlan = (id, groupId, semesterId) =>
|
||||
apiClient.delete(
|
||||
`/api/study-plans/${id}/assignments?groupId=${groupId}&semesterId=${semesterId}`,
|
||||
);
|
||||
export const removePlan = (id, revision) =>
|
||||
apiClient.delete(`/api/study-plans/${id}?expectedRevision=${revision}`);
|
||||
export function planTeacherEndpoint(
|
||||
subjectId,
|
||||
query = '',
|
||||
groupIds = [],
|
||||
semesterId,
|
||||
lessonTypeId,
|
||||
) {
|
||||
const params = new URLSearchParams({ subjectId, query });
|
||||
groupIds.forEach((id) => params.append('groupId', id));
|
||||
if (semesterId) params.set('semesterId', semesterId);
|
||||
if (lessonTypeId) params.set('lessonTypeId', lessonTypeId);
|
||||
return `/api/study-plans/teacher-options?${params}`;
|
||||
}
|
||||
export const fetchPlanTeachers = (
|
||||
subjectId,
|
||||
query,
|
||||
groupIds,
|
||||
semesterId,
|
||||
lessonTypeId,
|
||||
) =>
|
||||
apiClient.get(
|
||||
planTeacherEndpoint(
|
||||
subjectId,
|
||||
query,
|
||||
groupIds,
|
||||
semesterId,
|
||||
lessonTypeId,
|
||||
),
|
||||
{
|
||||
errorMessage:
|
||||
'Не удалось загрузить преподавателей кафедры дисциплины',
|
||||
},
|
||||
);
|
||||
|
||||
// Состояние конструктора хранит часы внутри объектов видов занятий.
|
||||
export function plannedTypeLimits(loads, current) {
|
||||
return Object.fromEntries(
|
||||
[
|
||||
['lecture', 'LECTURE'],
|
||||
['practice', 'PRACTICE'],
|
||||
['laboratory', 'LABORATORY'],
|
||||
].map(([key, category]) => [
|
||||
key,
|
||||
{
|
||||
...current[key],
|
||||
hours: String(
|
||||
loads.find((load) => load.category === category)
|
||||
?.academicHours || 0,
|
||||
),
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
createScheduleDraftVersion,
|
||||
fetchScheduleVersions
|
||||
} from '../schedule-versions-service.js';
|
||||
import { fetchPlanTeachers, plannedTypeLimits } from '../study-plans-service.js';
|
||||
import { fetchClassroomOptions, fetchTeacherOptions } from '../schedule-view-service.js';
|
||||
import {
|
||||
CELL_PARITY_LAYOUT,
|
||||
@@ -792,6 +793,11 @@ export function ScheduleTab() {
|
||||
dirtyScopeRef.current?.mark();
|
||||
const value = event.target.value;
|
||||
setRuleSubjectId(value);
|
||||
const planned = ruleSubjectOptions?.studyPlanId
|
||||
? ruleSubjectOptions.subjects.find(subject => String(subject.id) === String(value)) : null;
|
||||
if (planned) {
|
||||
setTypeLimits(current => plannedTypeLimits(planned.loads, current));
|
||||
}
|
||||
// Преподаватели слотов зависят от привязок дисциплины — сбрасываем
|
||||
// выбранных преподавателей при смене дисциплины.
|
||||
setSlots(current => current.map(slot => ({ ...slot, teacherId: '', teacherName: '' })));
|
||||
@@ -1614,6 +1620,7 @@ export function ScheduleTab() {
|
||||
<option key={group.id} value={group.id}>{group.name}</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
{ruleSubjectOptions?.studyPlanTitle && <small className="muted">Учебный план: {ruleSubjectOptions.studyPlanTitle} · семестр {ruleSubjectOptions.semesterNumber}</small>}
|
||||
{ruleSubjectOptions && ruleSubjectOptions.calendarTitle && (
|
||||
<small className="muted" id="schedule-rule-calendar-hint">
|
||||
График: {ruleSubjectOptions.calendarTitle}
|
||||
@@ -2139,7 +2146,9 @@ function RuleSlotRow({
|
||||
optionLabel={teacherOptionLabel}
|
||||
optionDescription={teacherOptionDescription}
|
||||
load={(query, selectedId) => (subjectId
|
||||
? fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber, slot.lessonTypeId)
|
||||
? (selectedGroupIds.length && semesterId && slot.lessonTypeId
|
||||
? fetchPlanTeachers(subjectId, query, selectedGroupIds, semesterId, slot.lessonTypeId)
|
||||
: fetchTeacherOptions(query, selectedId, subjectId, semesterId, semesterNumber, slot.lessonTypeId))
|
||||
: Promise.resolve([]))}
|
||||
selectedValue={slot.teacherId}
|
||||
selectedLabel={slot.teacherName}
|
||||
|
||||
@@ -0,0 +1,926 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { getSession } from '../../../admin/js/api.js';
|
||||
import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||||
import { AsyncCombobox } from '../../shared/ui/AsyncCombobox.jsx';
|
||||
import { ConfirmDialog } from '../../shared/ui/ConfirmDialog.jsx';
|
||||
import {
|
||||
confirmAbandonDirtyChanges,
|
||||
createDirtyScope,
|
||||
} from '../../../admin/js/dirty-state.js';
|
||||
import {
|
||||
LOAD_CATEGORIES,
|
||||
emptyPlanForm,
|
||||
loadDraft,
|
||||
workloadHours,
|
||||
compatibleGroups,
|
||||
fetchPlans,
|
||||
fetchPlanMetadata,
|
||||
fetchPlan,
|
||||
savePlan,
|
||||
savePlanSubject,
|
||||
removePlanSubject,
|
||||
assignPlan,
|
||||
unassignPlan,
|
||||
removePlan,
|
||||
fetchPlanTeachers,
|
||||
} from '../study-plans-service.js';
|
||||
|
||||
export function StudyPlansTab() {
|
||||
const [session] = useState(() => getSession());
|
||||
const editable = ['ADMIN', 'EDUCATION_OFFICE'].includes(session?.role);
|
||||
const [plans, setPlans] = useState([]);
|
||||
const [metadata, setMetadata] = useState(null);
|
||||
const [details, setDetails] = useState(null);
|
||||
const [form, setForm] = useState(emptyPlanForm);
|
||||
const [phase, setPhase] = useState('loading');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [alert, setAlert] = useState(null);
|
||||
const [query, setQuery] = useState('');
|
||||
const [subjectId, setSubjectId] = useState('');
|
||||
const [loads, setLoads] = useState(() => loadDraft());
|
||||
const [editingSubjectId, setEditingSubjectId] = useState(null);
|
||||
const [semesterId, setSemesterId] = useState('');
|
||||
const [groupId, setGroupId] = useState('');
|
||||
const [confirm, setConfirm] = useState(null);
|
||||
const draftChanges = useRef({ header: false, subject: false });
|
||||
const request = useRef(0);
|
||||
const dirty = useRef(null);
|
||||
const mounted = useRef(false);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
dirty.current = createDirtyScope('study-plans');
|
||||
let active = true;
|
||||
Promise.all([fetchPlans(), fetchPlanMetadata()])
|
||||
.then(([list, refs]) => {
|
||||
if (!active) return;
|
||||
setPlans(list);
|
||||
setMetadata(refs);
|
||||
setPhase('ready');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!active) return;
|
||||
setPhase('error');
|
||||
setAlert({ error: true, text: error.message });
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
mounted.current = false;
|
||||
request.current++;
|
||||
dirty.current?.dispose();
|
||||
};
|
||||
}, []);
|
||||
function applyDetails(next) {
|
||||
setDetails(next);
|
||||
setForm(next ? { ...next.plan } : emptyPlanForm());
|
||||
setSubjectId('');
|
||||
setLoads(loadDraft());
|
||||
setEditingSubjectId(null);
|
||||
draftChanges.current = { header: false, subject: false };
|
||||
dirty.current?.clear();
|
||||
}
|
||||
async function selectPlan(id) {
|
||||
if (busy || !(await confirmAbandonDirtyChanges())) return;
|
||||
const token = ++request.current;
|
||||
setAlert(null);
|
||||
if (!id) {
|
||||
applyDetails(null);
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const next = await fetchPlan(id);
|
||||
if (token === request.current) applyDetails(next);
|
||||
} catch (error) {
|
||||
if (token === request.current)
|
||||
setAlert({ error: true, text: error.message });
|
||||
} finally {
|
||||
if (token === request.current) setBusy(false);
|
||||
}
|
||||
}
|
||||
async function run(action, success, resetSubject = false, part = null) {
|
||||
if (busy) return;
|
||||
if (!part && dirty.current?.isDirty()) {
|
||||
if (!(await confirmAbandonDirtyChanges())) return;
|
||||
applyDetails(details);
|
||||
}
|
||||
setBusy(true);
|
||||
setAlert(null);
|
||||
try {
|
||||
const next = await action();
|
||||
if (!mounted.current) return;
|
||||
if (next?.plan) {
|
||||
setDetails(next);
|
||||
if (part === 'header' || !draftChanges.current.header)
|
||||
setForm({ ...next.plan });
|
||||
if (part === 'header') draftChanges.current.header = false;
|
||||
if (resetSubject) draftChanges.current.subject = false;
|
||||
if (resetSubject) {
|
||||
setSubjectId('');
|
||||
setEditingSubjectId(null);
|
||||
setLoads(loadDraft());
|
||||
}
|
||||
}
|
||||
const list = await fetchPlans();
|
||||
if (!mounted.current) return;
|
||||
setPlans(list);
|
||||
setAlert({ text: success });
|
||||
if (!draftChanges.current.header && !draftChanges.current.subject)
|
||||
dirty.current?.clear();
|
||||
} catch (error) {
|
||||
if (mounted.current) setAlert({ error: true, text: error.message });
|
||||
} finally {
|
||||
if (mounted.current) setBusy(false);
|
||||
}
|
||||
}
|
||||
function changeForm(key, value) {
|
||||
draftChanges.current.header = true;
|
||||
dirty.current?.mark();
|
||||
setForm((current) => ({ ...current, [key]: value }));
|
||||
}
|
||||
function changeLoad(category, patch) {
|
||||
draftChanges.current.subject = true;
|
||||
dirty.current?.mark();
|
||||
setLoads((current) =>
|
||||
current.map((load) =>
|
||||
load.category === category ? { ...load, ...patch } : load,
|
||||
),
|
||||
);
|
||||
}
|
||||
async function editSubject(row) {
|
||||
if (!(await confirmAbandonDirtyChanges())) return;
|
||||
setForm({ ...details.plan });
|
||||
draftChanges.current = { header: false, subject: false };
|
||||
setSubjectId(String(row.subjectId));
|
||||
setEditingSubjectId(row.subjectId);
|
||||
setLoads(loadDraft(row));
|
||||
}
|
||||
const plan = details?.plan;
|
||||
const visiblePlans = plans.filter(
|
||||
(p) =>
|
||||
p.id === plan?.id ||
|
||||
`${p.title} ${p.specialtyCode} ${p.profileName}`
|
||||
.toLocaleLowerCase('ru')
|
||||
.includes(query.toLocaleLowerCase('ru')),
|
||||
);
|
||||
const groups = compatibleGroups(metadata, plan, semesterId);
|
||||
const totals = details?.subjects.reduce(
|
||||
(sum, row) => ({
|
||||
academic: sum.academic + row.academicHours,
|
||||
workload: sum.workload + row.workloadHours,
|
||||
}),
|
||||
{ academic: 0, workload: 0 },
|
||||
);
|
||||
const contextLocked = Boolean(details?.assignments.length);
|
||||
if (phase !== 'ready')
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>Учебные планы</h2>
|
||||
<p role="status">
|
||||
{phase === 'loading'
|
||||
? 'Загрузка учебных планов…'
|
||||
: alert?.text}
|
||||
</p>
|
||||
{phase === 'error' && (
|
||||
<button
|
||||
className="btn btn-md btn-secondary"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
Повторить загрузку
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<section className="study-plans-workspace" aria-label="Учебные планы">
|
||||
<div className="card study-plans-catalog">
|
||||
<div className="study-plan-heading">
|
||||
<div>
|
||||
<p className="study-plan-kicker">Учебный процесс</p>
|
||||
<h2>Учебные планы</h2>
|
||||
<p className="muted">
|
||||
Профиль → семестр → дисциплины и часы → группы
|
||||
</p>
|
||||
</div>
|
||||
<div className="study-plan-row-actions">
|
||||
{plan && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-md btn-secondary"
|
||||
disabled={busy}
|
||||
onClick={() => void selectPlan(plan.id)}
|
||||
>
|
||||
Обновить
|
||||
</button>
|
||||
)}
|
||||
{editable && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-md btn-primary"
|
||||
disabled={busy}
|
||||
onClick={() => void selectPlan(null)}
|
||||
>
|
||||
Новый план
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="study-plan-controls">
|
||||
<label className="form-group">
|
||||
Поиск по названию, шифру и профилю
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
type="search"
|
||||
placeholder="Название или шифр специальности"
|
||||
/>
|
||||
</label>
|
||||
<label className="form-group">
|
||||
Учебный план
|
||||
<CustomSelect
|
||||
disabled={busy}
|
||||
value={plan?.id || ''}
|
||||
onChange={(e) => void selectPlan(e.target.value)}
|
||||
>
|
||||
<option value="">Выберите план</option>
|
||||
{visiblePlans.map((p) => (
|
||||
<option value={p.id} key={p.id}>
|
||||
{p.title} · {p.specialtyCode} ·{' '}
|
||||
{p.profileName} · {p.semesterNumber} семестр
|
||||
</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
</label>
|
||||
</div>
|
||||
{alert && (
|
||||
<p
|
||||
role={alert.error ? 'alert' : 'status'}
|
||||
className={`form-alert study-plan-alert ${alert.error ? 'error' : 'success'}`}
|
||||
>
|
||||
{alert.text}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{(plan || editable) && (
|
||||
<div className="card">
|
||||
<div className="study-plan-heading">
|
||||
<h3>{plan ? plan.title : 'Новый учебный план'}</h3>
|
||||
{plan && (
|
||||
<span className="badge">
|
||||
{plan.specialtyCode} · {plan.profileName}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(
|
||||
() => savePlan(plan?.id, form, plan?.revision),
|
||||
'Учебный план сохранён',
|
||||
false,
|
||||
'header',
|
||||
);
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
disabled={!editable || busy}
|
||||
className="study-plan-fieldset"
|
||||
>
|
||||
<div className="study-plan-controls">
|
||||
<label className="form-group">
|
||||
Название
|
||||
<input
|
||||
required
|
||||
maxLength={255}
|
||||
value={form.title}
|
||||
onChange={(e) =>
|
||||
changeForm('title', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="form-group">
|
||||
Шифр и профиль
|
||||
<CustomSelect
|
||||
required
|
||||
disabled={contextLocked}
|
||||
value={form.specialtyProfileId}
|
||||
onChange={(e) =>
|
||||
changeForm(
|
||||
'specialtyProfileId',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Выберите профиль
|
||||
</option>
|
||||
{metadata.profiles.map((p) => (
|
||||
<option value={p.id} key={p.id}>
|
||||
{p.specialtyCode} · {p.name}
|
||||
</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
</label>
|
||||
<label className="form-group">
|
||||
Форма обучения
|
||||
<CustomSelect
|
||||
required
|
||||
disabled={contextLocked}
|
||||
value={form.educationFormId}
|
||||
onChange={(e) =>
|
||||
changeForm(
|
||||
'educationFormId',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Выберите форму</option>
|
||||
{metadata.educationForms.map((f) => (
|
||||
<option key={f.id} value={f.id}>
|
||||
{f.name}
|
||||
</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
</label>
|
||||
<label className="form-group">
|
||||
Номер семестра обучения
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
required
|
||||
disabled={contextLocked}
|
||||
value={form.semesterNumber}
|
||||
onChange={(e) =>
|
||||
changeForm(
|
||||
'semesterNumber',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{editable && (
|
||||
<button
|
||||
className="btn btn-md btn-primary"
|
||||
type="submit"
|
||||
>
|
||||
{plan ? 'Сохранить план' : 'Создать план'}
|
||||
</button>
|
||||
)}
|
||||
</fieldset>
|
||||
</form>
|
||||
{contextLocked && (
|
||||
<p className="muted">
|
||||
Профиль, форма и номер семестра закреплённого плана
|
||||
защищены от изменения.
|
||||
</p>
|
||||
)}
|
||||
{plan && editable && !contextLocked && (
|
||||
<button
|
||||
disabled={busy}
|
||||
type="button"
|
||||
className="btn btn-md btn-danger study-plan-delete"
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
text: `Удалить план «${plan.title}» вместе с дисциплинами?`,
|
||||
action: async () => {
|
||||
await removePlan(
|
||||
plan.id,
|
||||
plan.revision,
|
||||
);
|
||||
applyDetails(null);
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
Удалить план
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{plan && (
|
||||
<>
|
||||
<div className="card">
|
||||
<div className="study-plan-heading">
|
||||
<div>
|
||||
<h3>Дисциплины и часы</h3>
|
||||
<p className="muted">
|
||||
Академические часы. Одна пара — 2 часа. Для
|
||||
лабораторных в двух подгруппах нагрузка ×2.
|
||||
</p>
|
||||
</div>
|
||||
<div className="study-plan-totals">
|
||||
<span>
|
||||
<strong>{totals.academic}</strong> учебных
|
||||
часов
|
||||
</span>
|
||||
<span>
|
||||
<strong>{totals.workload}</strong> часов
|
||||
нагрузки
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-wrap">
|
||||
<table className="study-plan-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дисциплина</th>
|
||||
{LOAD_CATEGORIES.map((c) => (
|
||||
<th key={c.key}>{c.label}</th>
|
||||
))}
|
||||
<th>Учебные часы</th>
|
||||
<th>Нагрузка</th>
|
||||
{editable && <th>Действия</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{!details.subjects.length && (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={editable ? 7 : 6}
|
||||
className="loading-row"
|
||||
>
|
||||
Добавьте первую дисциплину в
|
||||
план
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{details.subjects.map((row) => (
|
||||
<tr key={row.subjectId}>
|
||||
<td>
|
||||
<strong>{row.name}</strong>
|
||||
<div className="muted">
|
||||
{row.code}
|
||||
</div>
|
||||
</td>
|
||||
{LOAD_CATEGORIES.map((c) => {
|
||||
const load = row.loads.find(
|
||||
(l) => l.category === c.key,
|
||||
);
|
||||
return (
|
||||
<td key={c.key}>
|
||||
{load?.academicHours ||
|
||||
'—'}
|
||||
{load?.splitSubgroups && (
|
||||
<span className="badge">
|
||||
2 подгруппы ·{' '}
|
||||
{
|
||||
load.workloadHours
|
||||
}{' '}
|
||||
ч нагрузки
|
||||
</span>
|
||||
)}
|
||||
<div className="muted">
|
||||
{load?.academicHours >
|
||||
0
|
||||
? load.teacherName ||
|
||||
'Преподаватель не назначен'
|
||||
: ''}
|
||||
</div>
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
<td>{row.academicHours}</td>
|
||||
<td>
|
||||
<strong>
|
||||
{row.workloadHours}
|
||||
</strong>
|
||||
</td>
|
||||
{editable && (
|
||||
<td>
|
||||
<div className="study-plan-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className="btn btn-sm btn-secondary"
|
||||
onClick={() =>
|
||||
void editSubject(
|
||||
row,
|
||||
)
|
||||
}
|
||||
>
|
||||
Изменить
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
text: `Удалить дисциплину «${row.name}» из плана?`,
|
||||
action: () =>
|
||||
removePlanSubject(
|
||||
plan.id,
|
||||
row.subjectId,
|
||||
plan.revision,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{editable && (
|
||||
<form
|
||||
className="study-plan-subject-editor"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(
|
||||
() =>
|
||||
savePlanSubject(
|
||||
plan.id,
|
||||
subjectId,
|
||||
loads,
|
||||
plan.revision,
|
||||
),
|
||||
'Дисциплина и нагрузка сохранены',
|
||||
true,
|
||||
'subject',
|
||||
);
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
className="study-plan-fieldset"
|
||||
disabled={busy}
|
||||
>
|
||||
<h4>
|
||||
{editingSubjectId
|
||||
? 'Изменение дисциплины'
|
||||
: 'Добавление дисциплины'}
|
||||
</h4>
|
||||
<label className="form-group">
|
||||
Дисциплина
|
||||
<CustomSelect
|
||||
required
|
||||
disabled={Boolean(editingSubjectId)}
|
||||
value={subjectId}
|
||||
onChange={(e) => {
|
||||
draftChanges.current.subject = true;
|
||||
dirty.current?.mark();
|
||||
setSubjectId(e.target.value);
|
||||
setLoads(loadDraft());
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Выберите дисциплину
|
||||
</option>
|
||||
{metadata.subjects
|
||||
.filter(
|
||||
(s) =>
|
||||
s.id ===
|
||||
editingSubjectId ||
|
||||
!details.subjects.some(
|
||||
(row) =>
|
||||
row.subjectId ===
|
||||
s.id,
|
||||
),
|
||||
)
|
||||
.map((s) => (
|
||||
<option
|
||||
value={s.id}
|
||||
key={s.id}
|
||||
>
|
||||
{s.code
|
||||
? `${s.code} · `
|
||||
: ''}
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
</label>
|
||||
<div className="study-plan-load-grid">
|
||||
{LOAD_CATEGORIES.map((c) => {
|
||||
const load = loads.find(
|
||||
(l) => l.category === c.key,
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className="study-plan-load-card"
|
||||
key={c.key}
|
||||
>
|
||||
<h4>{c.label}</h4>
|
||||
<label className="form-group">
|
||||
Учебные часы
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="100000"
|
||||
step="2"
|
||||
required
|
||||
value={
|
||||
load.academicHours
|
||||
}
|
||||
onChange={(e) =>
|
||||
changeLoad(
|
||||
c.key,
|
||||
{
|
||||
academicHours:
|
||||
e
|
||||
.target
|
||||
.value,
|
||||
...(Number(
|
||||
e
|
||||
.target
|
||||
.value,
|
||||
) === 0
|
||||
? {
|
||||
teacherId:
|
||||
null,
|
||||
teacherName:
|
||||
'',
|
||||
splitSubgroups: false,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{c.key === 'LABORATORY' && (
|
||||
<label className="study-plan-check checkbox-item">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={
|
||||
!Number(
|
||||
load.academicHours,
|
||||
)
|
||||
}
|
||||
checked={
|
||||
load.splitSubgroups
|
||||
}
|
||||
onChange={(e) =>
|
||||
changeLoad(
|
||||
c.key,
|
||||
{
|
||||
splitSubgroups:
|
||||
e
|
||||
.target
|
||||
.checked,
|
||||
},
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span
|
||||
className="checkmark"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>
|
||||
Делить на две
|
||||
подгруппы
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<p className="study-plan-load-total">
|
||||
Нагрузка:{' '}
|
||||
<strong>
|
||||
{workloadHours(
|
||||
load,
|
||||
)}{' '}
|
||||
ч
|
||||
</strong>
|
||||
</p>
|
||||
<fieldset
|
||||
disabled={
|
||||
!subjectId ||
|
||||
!Number(
|
||||
load.academicHours,
|
||||
) ||
|
||||
busy
|
||||
}
|
||||
className="study-plan-fieldset"
|
||||
>
|
||||
<label className="form-group">
|
||||
Преподаватель
|
||||
<AsyncCombobox
|
||||
key={`${plan.id}-${subjectId}-${c.key}`}
|
||||
ariaLabel={`Преподаватель: ${c.label}`}
|
||||
placeholder="Можно назначить позднее"
|
||||
optionLabel={(
|
||||
t,
|
||||
) =>
|
||||
t.fullName ||
|
||||
t.username
|
||||
}
|
||||
load={(q) =>
|
||||
subjectId
|
||||
? fetchPlanTeachers(
|
||||
subjectId,
|
||||
q,
|
||||
)
|
||||
: Promise.resolve(
|
||||
[],
|
||||
)
|
||||
}
|
||||
selectedValue={
|
||||
load.teacherId ||
|
||||
''
|
||||
}
|
||||
selectedLabel={
|
||||
load.teacherName
|
||||
}
|
||||
onSelect={(t) =>
|
||||
changeLoad(
|
||||
c.key,
|
||||
{
|
||||
teacherId:
|
||||
t?.id ||
|
||||
null,
|
||||
teacherName:
|
||||
t
|
||||
? t.fullName ||
|
||||
t.username
|
||||
: '',
|
||||
},
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="study-plan-row-actions">
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-md btn-primary"
|
||||
disabled={!subjectId}
|
||||
>
|
||||
Сохранить дисциплину
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-md btn-secondary"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmAbandonDirtyChanges()
|
||||
) {
|
||||
applyDetails(details);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Очистить форму
|
||||
</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
<div className="card">
|
||||
<h3>Закрепление за группами</h3>
|
||||
<p className="muted">
|
||||
На один календарный семестр группе назначается один
|
||||
план её профиля и формы обучения.
|
||||
</p>
|
||||
<div className="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Группа</th>
|
||||
<th>Календарный семестр</th>
|
||||
{editable && <th>Действия</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{!details.assignments.length && (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={editable ? 3 : 2}
|
||||
className="loading-row"
|
||||
>
|
||||
План пока не закреплён
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{details.assignments.map((a) => (
|
||||
<tr
|
||||
key={`${a.groupId}-${a.semesterId}`}
|
||||
>
|
||||
<td>{a.groupName}</td>
|
||||
<td>{a.semesterTitle}</td>
|
||||
{editable && (
|
||||
<td>
|
||||
<button
|
||||
disabled={busy}
|
||||
className="btn btn-sm btn-danger"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setConfirm({
|
||||
text: `Снять закрепление плана за группой ${a.groupName} (${a.semesterTitle})?`,
|
||||
action: () =>
|
||||
unassignPlan(
|
||||
plan.id,
|
||||
a.groupId,
|
||||
a.semesterId,
|
||||
),
|
||||
})
|
||||
}
|
||||
>
|
||||
Снять закрепление
|
||||
</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{editable && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void run(
|
||||
() =>
|
||||
assignPlan(
|
||||
plan.id,
|
||||
groupId,
|
||||
semesterId,
|
||||
),
|
||||
'План закреплён за группой',
|
||||
);
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
className="study-plan-fieldset study-plan-controls"
|
||||
disabled={busy}
|
||||
>
|
||||
<label className="form-group">
|
||||
Календарный семестр
|
||||
<CustomSelect
|
||||
required
|
||||
value={semesterId}
|
||||
onChange={(e) => {
|
||||
setSemesterId(e.target.value);
|
||||
setGroupId('');
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Выберите семестр
|
||||
</option>
|
||||
{metadata.semesters.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
</label>
|
||||
<label className="form-group">
|
||||
Совместимая группа
|
||||
<CustomSelect
|
||||
required
|
||||
value={groupId}
|
||||
onChange={(e) =>
|
||||
setGroupId(e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
{semesterId && !groups.length
|
||||
? 'Нет групп этого профиля и семестра'
|
||||
: 'Выберите группу'}
|
||||
</option>
|
||||
{groups.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</CustomSelect>
|
||||
</label>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-md btn-primary"
|
||||
disabled={
|
||||
!groupId || !details.subjects.length
|
||||
}
|
||||
>
|
||||
Закрепить план
|
||||
</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{confirm && (
|
||||
<ConfirmDialog
|
||||
title="Подтвердите действие"
|
||||
message={confirm.text}
|
||||
danger
|
||||
confirmLabel="Подтвердить"
|
||||
onClose={() => setConfirm(null)}
|
||||
onConfirm={() => {
|
||||
const action = confirm.action;
|
||||
setConfirm(null);
|
||||
void run(action, 'Изменения сохранены', true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -130,7 +130,7 @@ test('преподаватель слота формы правила сужае
|
||||
// смена дисциплины сбрасывает преподавателей слотов
|
||||
assert.match(
|
||||
scheduleTab,
|
||||
/setRuleSubjectId\(value\);\s*\n\s*\/\/ Преподаватели слотов зависят от привязок дисциплины/s
|
||||
/setRuleSubjectId\(value\);.*setSlots\(current => current\.map\(slot => \(\{ \.\.\.slot, teacherId: \'\', teacherName: \'\' \}\)\)\)/s
|
||||
);
|
||||
assert.match(scheduleViewService, /params\.set\('subjectId', subjectId\)/);
|
||||
assert.match(scheduleViewService, /params\.set\('semesterId', semesterId\)/);
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, test } from 'node:test';
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { build } from 'esbuild';
|
||||
import { chromium } from 'playwright';
|
||||
let browser, server, origin, bundle, styles;
|
||||
const metadata = {
|
||||
profiles: [
|
||||
{ id: 1, name: 'Программная инженерия', specialtyCode: '09.03.01' },
|
||||
],
|
||||
educationForms: [{ id: 1, name: 'Бакалавриат' }],
|
||||
semesters: [
|
||||
{
|
||||
id: 1,
|
||||
name: '2026–2027 · Осень',
|
||||
startYear: 2026,
|
||||
semesterType: 'autumn',
|
||||
},
|
||||
],
|
||||
groups: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'ИВТ-21-1',
|
||||
specialtyProfileId: 1,
|
||||
educationFormId: 1,
|
||||
yearStartStudy: 2025,
|
||||
},
|
||||
],
|
||||
subjects: [
|
||||
{ id: 1, name: 'Операционные системы', code: 'ОС', departmentId: 1 },
|
||||
],
|
||||
};
|
||||
function initialDetails() {
|
||||
return {
|
||||
plan: {
|
||||
id: 1,
|
||||
title: 'План третьего семестра',
|
||||
specialtyProfileId: 1,
|
||||
profileName: 'Программная инженерия',
|
||||
specialtyCode: '09.03.01',
|
||||
educationFormId: 1,
|
||||
educationFormName: 'Бакалавриат',
|
||||
semesterNumber: 3,
|
||||
revision: 0,
|
||||
},
|
||||
subjects: [
|
||||
{
|
||||
subjectId: 1,
|
||||
name: 'Операционные системы',
|
||||
code: 'ОС',
|
||||
departmentId: 1,
|
||||
loads: ['LECTURE', 'PRACTICE', 'LABORATORY'].map(
|
||||
(category, i) => ({
|
||||
category,
|
||||
academicHours: i === 2 ? 18 : 36,
|
||||
splitSubgroups: false,
|
||||
teacherId: 7,
|
||||
teacherName: 'Иванов И. И.',
|
||||
workloadHours: i === 2 ? 18 : 36,
|
||||
}),
|
||||
),
|
||||
academicHours: 90,
|
||||
workloadHours: 90,
|
||||
},
|
||||
],
|
||||
assignments: [],
|
||||
};
|
||||
}
|
||||
before(async () => {
|
||||
bundle = (
|
||||
await build({
|
||||
stdin: {
|
||||
contents: `import React from 'react'; import { createRoot } from 'react-dom/client'; import { storeAuthState } from './auth-session.js'; import { StudyPlansTab } from './react/admin/tabs/StudyPlansTab.jsx'; storeAuthState({ token: 'test-token', role: window.testRole || 'ADMIN', userId: 1, departmentId: 1 }); createRoot(document.getElementById('root')).render(<StudyPlansTab />);`,
|
||||
resolveDir: process.cwd(),
|
||||
loader: 'jsx',
|
||||
},
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: 'iife',
|
||||
jsx: 'automatic',
|
||||
define: { 'process.env.NODE_ENV': '"test"' },
|
||||
})
|
||||
).outputFiles[0].text;
|
||||
styles = (
|
||||
await Promise.all(
|
||||
['admin/css/main.css', 'admin/css/components.css'].map((p) =>
|
||||
readFile(p, 'utf8'),
|
||||
),
|
||||
)
|
||||
).join('\n');
|
||||
server = createServer((req, res) => {
|
||||
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
res.end('<div id="root"></div>');
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
origin = `http://127.0.0.1:${server.address().port}`;
|
||||
browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium',
|
||||
});
|
||||
});
|
||||
after(async () => {
|
||||
await browser?.close();
|
||||
if (server)
|
||||
await new Promise((resolve) => {
|
||||
server.closeAllConnections();
|
||||
server.close(resolve);
|
||||
});
|
||||
});
|
||||
async function fixture(t, role = 'ADMIN') {
|
||||
const page = await browser.newPage({
|
||||
viewport: { width: 1440, height: 1100 },
|
||||
});
|
||||
const errors = [],
|
||||
writes = [];
|
||||
let details = initialDetails();
|
||||
page.on('pageerror', (error) => errors.push(error.stack));
|
||||
await page.route(/\/api\/study-plans/, async (route) => {
|
||||
const request = route.request(),
|
||||
url = new URL(request.url());
|
||||
let response;
|
||||
if (url.pathname.endsWith('/metadata')) response = metadata;
|
||||
else if (url.pathname.endsWith('/teacher-options'))
|
||||
response = [{ id: 7, fullName: 'Иванов И. И.' }];
|
||||
else if (
|
||||
request.method() === 'PUT' &&
|
||||
url.pathname.endsWith('/subjects/1')
|
||||
) {
|
||||
const body = request.postDataJSON();
|
||||
writes.push(body);
|
||||
details.plan.revision++;
|
||||
details.subjects[0].loads = body.loads.map((l) => ({
|
||||
...l,
|
||||
teacherName: 'Иванов И. И.',
|
||||
workloadHours: l.academicHours * (l.splitSubgroups ? 2 : 1),
|
||||
}));
|
||||
details.subjects[0].workloadHours =
|
||||
details.subjects[0].loads.reduce(
|
||||
(sum, l) => sum + l.workloadHours,
|
||||
0,
|
||||
);
|
||||
response = details;
|
||||
} else if (
|
||||
request.method() === 'POST' &&
|
||||
url.pathname.endsWith('/assignments')
|
||||
) {
|
||||
writes.push(request.postDataJSON());
|
||||
details.assignments = [
|
||||
{
|
||||
groupId: 1,
|
||||
groupName: 'ИВТ-21-1',
|
||||
semesterId: 1,
|
||||
semesterTitle: metadata.semesters[0].name,
|
||||
},
|
||||
];
|
||||
response = details;
|
||||
} else
|
||||
response =
|
||||
url.pathname === '/api/study-plans' ? [details.plan] : details;
|
||||
await route.fulfill({ json: response });
|
||||
});
|
||||
await page.goto(origin);
|
||||
await page.addStyleTag({ content: styles });
|
||||
await page.evaluate((role) => {
|
||||
window.testRole = role;
|
||||
}, role);
|
||||
await page.addScriptTag({ content: bundle });
|
||||
await page
|
||||
.locator('select')
|
||||
.first()
|
||||
.selectOption('1', { force: true, timeout: 5000 });
|
||||
await page.getByRole('heading', { name: 'Дисциплины и часы' }).waitFor();
|
||||
t.after(async () => {
|
||||
await page.close();
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
return { page, writes };
|
||||
}
|
||||
test('редактор удваивает только лабораторную нагрузку, сохраняя учебные часы', async (t) => {
|
||||
const { page, writes } = await fixture(t);
|
||||
await page.getByRole('button', { name: 'Изменить', exact: true }).click();
|
||||
assert.equal(await page.getByRole('checkbox').count(), 1);
|
||||
await page.locator('label.checkbox-item').click();
|
||||
assert.ok(
|
||||
await page
|
||||
.getByRole('checkbox', { name: 'Делить на две подгруппы' })
|
||||
.isChecked(),
|
||||
);
|
||||
await page
|
||||
.locator('.study-plan-load-card')
|
||||
.last()
|
||||
.getByText('36 ч', { exact: true })
|
||||
.waitFor();
|
||||
await page.getByRole('button', { name: 'Сохранить дисциплину' }).click();
|
||||
await page
|
||||
.getByRole('status')
|
||||
.filter({ hasText: 'Дисциплина и нагрузка сохранены' })
|
||||
.waitFor();
|
||||
assert.equal(writes[0].loads[2].academicHours, 18);
|
||||
assert.equal(writes[0].loads[2].splitSubgroups, true);
|
||||
assert.equal(writes[0].loads[0].splitSubgroups, false);
|
||||
assert.equal(
|
||||
await page.locator('.study-plan-totals strong').last().textContent(),
|
||||
'108',
|
||||
);
|
||||
await page.waitForTimeout(400);
|
||||
await page.screenshot({
|
||||
path: '/tmp/magistr-study-plans.png',
|
||||
fullPage: true,
|
||||
});
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
assert.equal(
|
||||
await page
|
||||
.locator('.study-plan-load-grid')
|
||||
.evaluate(
|
||||
(el) =>
|
||||
getComputedStyle(el).gridTemplateColumns.split(' ').length,
|
||||
),
|
||||
1,
|
||||
);
|
||||
});
|
||||
test('совместимая группа закрепляется за календарным семестром', async (t) => {
|
||||
const { page, writes } = await fixture(t),
|
||||
form = page.locator('form').last();
|
||||
await form.locator('select').first().selectOption('1', { force: true });
|
||||
await form.locator('select').last().selectOption('1', { force: true });
|
||||
await form.getByRole('button', { name: 'Закрепить план' }).click();
|
||||
await page
|
||||
.getByRole('status')
|
||||
.filter({ hasText: 'План закреплён за группой' })
|
||||
.waitFor();
|
||||
assert.deepEqual(writes[0], { groupId: 1, semesterId: 1 });
|
||||
await page.getByRole('cell', { name: 'ИВТ-21-1', exact: true }).waitFor();
|
||||
});
|
||||
test('кафедра читает план без форм изменения', async (t) => {
|
||||
const { page } = await fixture(t, 'DEPARTMENT');
|
||||
assert.equal(
|
||||
await page
|
||||
.getByRole('button', { name: 'Сохранить дисциплину' })
|
||||
.count(),
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
await page.getByRole('button', { name: 'Закрепить план' }).count(),
|
||||
0,
|
||||
);
|
||||
assert.ok(
|
||||
(await page.getByText('Иванов И. И.', { exact: true }).count()) > 0,
|
||||
);
|
||||
});
|
||||
@@ -26,14 +26,14 @@ test('навигация админки фильтруется по единой
|
||||
assert.ok(adminTabs.includes('dashboard'));
|
||||
assert.ok(adminTabs.includes('users'));
|
||||
assert.ok(adminTabs.includes('schedule'));
|
||||
assert.equal(adminTabs.length, 14);
|
||||
assert.equal(adminTabs.length, 15);
|
||||
assert.ok(!adminTabs.includes('department-workspace'));
|
||||
|
||||
const officeSections = navSectionsForRole('EDUCATION_OFFICE');
|
||||
const officeTabs = officeSections.flatMap(section => section.items.map(item => item.id));
|
||||
assert.deepEqual(
|
||||
officeTabs,
|
||||
['dashboard', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar',
|
||||
['dashboard', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar', 'study-plans',
|
||||
'auditorium-workload', 'schedule-view', 'teacher-absences', 'classrooms']
|
||||
);
|
||||
assert.ok(!officeTabs.includes('teacher-requests'));
|
||||
@@ -42,7 +42,7 @@ test('навигация админки фильтруется по единой
|
||||
|
||||
const departmentTabs = navSectionsForRole('DEPARTMENT')
|
||||
.flatMap(section => section.items.map(item => item.id));
|
||||
assert.deepEqual(departmentTabs, ['department-workspace', 'department-requests', 'department-management', 'department-bindings', 'schedule-view', 'teacher-absences']);
|
||||
assert.deepEqual(departmentTabs, ['department-workspace', 'department-requests', 'department-management', 'department-bindings', 'study-plans', 'schedule-view', 'teacher-absences']);
|
||||
|
||||
const viewerTabs = navSectionsForRole('SCHEDULE_VIEWER')
|
||||
.flatMap(section => section.items.map(item => item.id));
|
||||
@@ -123,6 +123,7 @@ test('маршруты вкладок полностью перенесены н
|
||||
assert.deepEqual(reactTabs, [
|
||||
'dashboard',
|
||||
'classrooms',
|
||||
'study-plans',
|
||||
'subjects',
|
||||
'users',
|
||||
'groups',
|
||||
@@ -140,7 +141,7 @@ test('маршруты вкладок полностью перенесены н
|
||||
'schedule-quality',
|
||||
'teacher-absences'
|
||||
]);
|
||||
assert.equal(reactTabs.length, 18);
|
||||
assert.equal(reactTabs.length, 19);
|
||||
|
||||
for (const [tab, route] of Object.entries(ADMIN_ROUTES)) {
|
||||
assert.ok(route.title, tab);
|
||||
@@ -162,7 +163,7 @@ test('каждая lazy-вкладка разрешается в именова
|
||||
const entries = Array.from(source.matchAll(
|
||||
/'?\w+'?:\s*\{\s*Component:\s*lazy\(\(\)\s*=>\s*import\('([^']+)'\)\.then\(m\s*=>\s*\(\{\s*default:\s*m\.(\w+)\s*\}\)\)\)/g
|
||||
));
|
||||
assert.equal(entries.length, 18);
|
||||
assert.equal(entries.length, 19);
|
||||
|
||||
for (const [, modulePath, exportName] of entries) {
|
||||
const tabSource = await readFrontendFile(`react/admin/${modulePath.replace('./', '')}`);
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
loadDraft,
|
||||
workloadHours,
|
||||
subjectPayload,
|
||||
compatibleGroups,
|
||||
planTeacherEndpoint,
|
||||
} from '../react/admin/study-plans-service.js';
|
||||
import { allowedAdminTabs } from '../react/admin/admin-service.js';
|
||||
|
||||
test('лабораторные 18×2 увеличивают нагрузку до 108, учебные часы остаются 90', () => {
|
||||
const loads = loadDraft();
|
||||
loads[0].academicHours = 36;
|
||||
loads[1].academicHours = 36;
|
||||
loads[2].academicHours = 18;
|
||||
loads[2].splitSubgroups = true;
|
||||
const payload = subjectPayload(loads, 5);
|
||||
assert.equal(
|
||||
payload.loads.reduce((sum, l) => sum + l.academicHours, 0),
|
||||
90,
|
||||
);
|
||||
assert.equal(
|
||||
loads.reduce((sum, l) => sum + workloadHours(l), 0),
|
||||
108,
|
||||
);
|
||||
assert.equal(payload.expectedRevision, 5);
|
||||
loads[0].splitSubgroups = true;
|
||||
assert.equal(workloadHours(loads[0]), 36);
|
||||
assert.equal(subjectPayload(loads, 5).loads[0].splitSubgroups, false);
|
||||
});
|
||||
test('запрещены нечётные часы и нулевая нагрузка с преподавателем', () => {
|
||||
const loads = loadDraft();
|
||||
loads[0].academicHours = 17;
|
||||
assert.throws(() => subjectPayload(loads, 1), /чётными/);
|
||||
loads[0].academicHours = 18;
|
||||
loads[2].teacherId = 4;
|
||||
assert.throws(() => subjectPayload(loads, 1), /нулевой/);
|
||||
});
|
||||
test('назначение доступно только группам нужного профиля, формы и номера семестра', () => {
|
||||
const plan = {
|
||||
specialtyProfileId: 2,
|
||||
educationFormId: 1,
|
||||
semesterNumber: 3,
|
||||
};
|
||||
const metadata = {
|
||||
semesters: [{ id: 4, startYear: 2026, semesterType: 'autumn' }],
|
||||
groups: [
|
||||
{
|
||||
id: 1,
|
||||
specialtyProfileId: 2,
|
||||
educationFormId: 1,
|
||||
yearStartStudy: 2025,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
specialtyProfileId: 3,
|
||||
educationFormId: 1,
|
||||
yearStartStudy: 2025,
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
specialtyProfileId: 2,
|
||||
educationFormId: 1,
|
||||
yearStartStudy: 2026,
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
specialtyProfileId: 2,
|
||||
educationFormId: 2,
|
||||
yearStartStudy: 2025,
|
||||
},
|
||||
],
|
||||
};
|
||||
assert.deepEqual(
|
||||
compatibleGroups(metadata, plan, 4).map((g) => g.id),
|
||||
[1],
|
||||
);
|
||||
});
|
||||
test('выбор преподавателя в правиле передаёт все группы и вид нагрузки для пересечения профилей', () => {
|
||||
const url = new URL(
|
||||
planTeacherEndpoint(3, 'Иванов', [7, 8], 4, 2),
|
||||
'http://localhost',
|
||||
);
|
||||
assert.deepEqual(url.searchParams.getAll('groupId'), ['7', '8']);
|
||||
assert.equal(url.searchParams.get('subjectId'), '3');
|
||||
assert.equal(url.searchParams.get('lessonTypeId'), '2');
|
||||
});
|
||||
test('учебные планы доступны администратору, учебному отделу и кафедре', () => {
|
||||
for (const role of ['ADMIN', 'EDUCATION_OFFICE', 'DEPARTMENT'])
|
||||
assert.ok(allowedAdminTabs(role).has('study-plans'));
|
||||
assert.ok(!allowedAdminTabs('SCHEDULE_VIEWER').has('study-plans'));
|
||||
});
|
||||
|
||||
import { plannedTypeLimits } from '../react/admin/study-plans-service.js';
|
||||
test('часы плана подставляются в объекты видов нагрузки конструктора, сохраняя неделю начала', () => {
|
||||
const current = {
|
||||
lecture: { hours: '0', startWeek: '3' },
|
||||
practice: { hours: '0', startWeek: '1' },
|
||||
laboratory: { hours: '0', startWeek: '1' },
|
||||
};
|
||||
const next = plannedTypeLimits(
|
||||
[
|
||||
{ category: 'LECTURE', academicHours: 36 },
|
||||
{ category: 'LABORATORY', academicHours: 18 },
|
||||
],
|
||||
current,
|
||||
);
|
||||
assert.equal(next.lecture.hours, '36');
|
||||
assert.equal(next.lecture.startWeek, '3');
|
||||
assert.equal(next.laboratory.hours, '18');
|
||||
assert.equal(next.practice.hours, '0');
|
||||
});
|
||||
Reference in new issue
Block a user