всё по Созвону 14.10.2026

This commit is contained in:
Zuev committed 2026-10-21 03:06:12 +03:00
1 parent ac228ae0c3
commit 0bb2911353
54 files changed
+2837 -738

No files matched your search

@@ -0,0 +1,360 @@
import assert from 'node:assert/strict';
import { before, after, test } from 'node:test';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { build } from 'esbuild';
import { chromium } from 'playwright';
let bundle, styles, server, origin, browser;
before(async () => {
bundle = (
await build({
stdin: {
contents: `import React from 'react'; import { createRoot } from 'react-dom/client'; import { storeAuthState } from './auth-session.js'; import { CalendarLoadsWorkspace } from './react/admin/tabs/CalendarLoadsWorkspace.jsx'; import { GroupScheduleMatrix } from './react/admin/tabs/GroupScheduleMatrix.jsx'; storeAuthState({ token: 'test-token', role: 'EDUCATION_OFFICE', userId: 1 }); createRoot(document.getElementById('root')).render(window.testMatrix ? <GroupScheduleMatrix /> : <CalendarLoadsWorkspace editHours={window.testHours} />);`,
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(
['main.css', 'components.css'].map((name) =>
readFile(`admin/css/${name}`, 'utf8'),
),
)
).join('\n');
server = createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(
'<html data-theme="light"><body style="padding:24px"><div id="root"></div></body></html>',
);
});
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,
{ hours = false, conflict = false, matrix = false } = {},
) {
const page = await browser.newPage({
viewport: { width: 1440, height: 1200 },
});
const errors = [],
writes = [];
const details = [1, 2].map((id) => ({
context: {
assignmentId: id,
calendarId: 1,
calendarTitle: 'График профиля',
groupId: id,
groupName: `ИВТ-${id}`,
groupDepartmentId: id,
semesterId: 3,
semesterNumber: 3,
revision: 5,
},
subjects: [
{
subjectId: 20,
name: 'Операционные системы',
departmentId: 4,
academicHours: 54,
workloadHours: 72,
loads: [
{
category: 'LECTURE',
academicHours: 36,
workloadHours: 36,
teacherId: 7,
teacherName: 'Иванов И. И.',
},
{
category: 'PRACTICE',
academicHours: 0,
workloadHours: 0,
teacherId: null,
},
{
category: 'LABORATORY',
academicHours: 18,
workloadHours: 36,
splitSubgroups: true,
teacherId: null,
},
],
},
],
}));
page.on('pageerror', (error) => errors.push(error.message));
await page.route('**/api/**', async (route) => {
const req = route.request(),
url = new URL(req.url());
let response;
if (url.pathname === '/api/departments')
response = [
{ id: 1, departmentName: 'Кафедра А' },
{ id: 2, departmentName: 'Кафедра Б' },
{ id: 4, departmentName: 'Кафедра ВТ' },
];
else if (url.pathname === '/api/schedule/semesters')
response = [
{
id: 3,
academicYearTitle: '2026–2027',
semesterType: 'autumn',
startDate: '2026-09-01',
endDate: '2026-12-31',
},
];
else if (url.pathname === '/api/groups')
response = details.map((d) => ({
id: d.context.groupId,
name: d.context.groupName,
departmentId: d.context.groupDepartmentId,
}));
else if (url.pathname.endsWith('/teacher-options'))
response = [{ id: 8, fullName: 'Петров П. П.' }];
else if (url.pathname === '/api/calendar-loads') response = details;
else if (req.method() === 'PUT') {
const body = req.postDataJSON();
writes.push({ path: url.pathname, body });
if (conflict) {
await route.fulfill({
status: 409,
json: {
message:
'Нагрузка группы изменена другим пользователем. Обновите данные',
},
});
return;
}
const d = details.find((d) =>
url.pathname.includes(`/groups/${d.context.groupId}/`),
);
if (body.loads)
d.subjects[0].loads = body.loads.map((load) => ({
...load,
workloadHours:
load.academicHours * (load.splitSubgroups ? 2 : 1),
}));
else {
const load = d.subjects[0].loads.find((load) =>
url.pathname.includes(`/${load.category}/`),
);
load.teacherId = body.teacherId;
load.teacherName =
body.teacherId == null ? null : 'Петров П. П.';
}
d.subjects[0].academicHours = d.subjects[0].loads.reduce(
(sum, l) => sum + l.academicHours,
0,
);
d.subjects[0].workloadHours = d.subjects[0].loads.reduce(
(sum, l) => sum + l.workloadHours,
0,
);
d.context.revision++;
response = d;
} else if (url.pathname.includes('/time-slots/effective'))
response = [
{ id: 1, orderNumber: 1, startTime: '09:00', endTime: '10:30' },
];
else if (url.pathname === '/api/schedule') {
response = [
{
date: url.searchParams.get('startDate'),
timeSlotOrder: 1,
timeSlotId: 1,
subjectName: 'Потоковая лекция',
teacherName: 'Иванов И. И.',
startTime: '09:00',
endTime: '10:30',
lessonTypeName: 'Лекция',
classroomName: '101',
scheduleRuleSlotId: 50,
},
];
} else if (url.pathname.includes('/workload/')) response = [];
else throw new Error(`Неожиданный запрос ${url.pathname}`);
await route.fulfill({ json: response });
});
await page.goto(origin);
await page.addStyleTag({ content: styles });
await page.evaluate(
({ hours, matrix }) => {
window.testHours = hours;
window.testMatrix = matrix;
},
{ hours, matrix },
);
await page.addScriptTag({ content: bundle });
if (!matrix)
await page.locator('.materials-table tbody tr').first().waitFor();
t.after(async () => {
await page.close();
assert.deepEqual(errors, []);
});
return { page, writes };
}
async function chooseTeacher(page) {
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-1' })
.filter({ hasText: 'Лабораторные' })
.getByRole('button', { name: 'Назначить', exact: true })
.click();
await page
.getByRole('combobox', { name: 'Преподаватель нагрузки группы' })
.fill('Петров');
await page.getByRole('option', { name: 'Петров П. П.' }).click();
}
test('материалы сохраняют преподавателя одной группы, другая группа не меняется', async (t) => {
const { page, writes } = await fixture(t);
assert.deepEqual(
await page.locator('.materials-totals strong').allTextContents(),
['108', '144', '72'],
);
await chooseTeacher(page);
await page.getByRole('button', { name: 'Сохранить назначение' }).click();
await page
.getByRole('status')
.filter({ hasText: 'Преподаватель группы назначен' })
.waitFor();
assert.deepEqual(writes[0], {
path: '/api/calendar-loads/groups/1/semesters/3/subjects/20/loads/LABORATORY/teacher',
body: { teacherId: 8, expectedRevision: 5 },
});
await page.getByRole('button', { name: 'Обновить', exact: true }).click();
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-1' })
.getByText('Петров П. П.')
.waitFor();
assert.equal(
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-2' })
.filter({ hasText: 'Лабораторные' })
.getByText('Не назначен')
.count(),
1,
);
await page.locator('select').nth(1).selectOption('2', { force: true });
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-2' })
.first()
.waitFor();
assert.equal(await page.locator('.materials-table tbody tr').count(), 2);
});
test('редактор часов календарного графика сохраняет часы группы и лабораторное деление', async (t) => {
const { page, writes } = await fixture(t, { hours: true });
await page
.locator('.materials-table tbody tr')
.filter({ hasText: 'ИВТ-1' })
.getByRole('button', { name: 'Изменить часы' })
.click();
await page
.locator('.study-plan-load-card')
.first()
.getByRole('spinbutton')
.fill('20');
await page.getByRole('button', { name: 'Сохранить часы группы' }).click();
await page
.getByRole('status')
.filter({ hasText: 'Часы группы сохранены' })
.waitFor();
assert.equal(writes[0].body.loads[0].academicHours, 20);
assert.equal(writes[0].body.loads[2].splitSubgroups, true);
assert.equal(writes[0].body.loads[2].academicHours, 18);
await page.locator('.materials-workspace').evaluate(async (el) => {
await Promise.all(
el
.getAnimations({ subtree: true })
.filter((a) => a.effect.getTiming().iterations !== Infinity)
.map((a) => a.finished.catch(() => {})),
);
});
await page.screenshot({
path: '/tmp/magistr14-calendar-hours.png',
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth,
),
);
});
test('устаревшее распределение группы не перезаписывается', async (t) => {
const { page } = await fixture(t, { conflict: true });
await chooseTeacher(page);
await page.getByRole('button', { name: 'Сохранить назначение' }).click();
await page
.getByRole('alert')
.filter({ hasText: 'другим пользователем' })
.waitFor();
assert.deepEqual(
await page.locator('.materials-totals strong').allTextContents(),
['108', '144', '72'],
);
});
test('матрица показывает группы под кафедрами и общую лекцию в каждой колонке', async (t) => {
const { page } = await fixture(t, { matrix: true });
await page.getByText('ИВТ-1', { exact: true }).click();
await page.getByText('ИВТ-2', { exact: true }).click();
await page.getByRole('button', { name: 'Показать матрицу' }).click();
await page.locator('.group-schedule-matrix').waitFor();
assert.equal(
await page.locator('.group-schedule-matrix thead tr').count(),
2,
);
assert.deepEqual(
await page
.locator('.group-schedule-matrix thead tr')
.first()
.locator('th')
.allTextContents(),
['День / пара', 'Кафедра А', 'Кафедра Б'],
);
assert.equal(
await page
.locator('.group-schedule-matrix')
.getByText('Потоковая лекция', { exact: true })
.count(),
2,
);
await page.locator('.materials-workspace').evaluate(async (el) => {
await Promise.all(
el
.getAnimations({ subtree: true })
.filter((a) => a.effect.getTiming().iterations !== Infinity)
.map((a) => a.finished.catch(() => {})),
);
});
await page.screenshot({
path: '/tmp/magistr14-group-matrix.png',
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth,
),
);
});
+8 -47
View File
@@ -165,59 +165,20 @@ async function fixture(t, role = 'ADMIN') {
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();
try { await page.locator('select').first().selectOption('1', { force: true, timeout: 5000 }); } catch (error) { throw new Error(`${error.message}\n${errors.join('\n')}`); }
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);
test('учебный план содержит дисциплины, часы редактируются в календарном графике', async (t) => {
const { page } = 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,
);
assert.equal(await page.getByRole('checkbox').count(), 0);
assert.equal(await page.getByRole('combobox', { name: /Преподаватель/ }).count(), 0);
await page.getByRole('link', { name: 'календарном графике' }).waitFor();
});
test('совместимая группа закрепляется за календарным семестром', async (t) => {
const { page, writes } = await fixture(t),
@@ -245,6 +206,6 @@ test('кафедра читает план без форм изменения',
0,
);
assert.ok(
(await page.getByText('Иванов И. И.', { exact: true }).count()) > 0,
(await page.getByText('Операционные системы', { exact: true }).count()) > 0,
);
});
+5 -4
View File
@@ -26,14 +26,14 @@ test('навигация админки фильтруется по единой
assert.ok(adminTabs.includes('dashboard'));
assert.ok(adminTabs.includes('users'));
assert.ok(adminTabs.includes('schedule'));
assert.equal(adminTabs.length, 15);
assert.equal(adminTabs.length, 16);
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', 'study-plans',
['dashboard', 'schedule', 'schedule-versions', 'schedule-quality', 'academic-calendar', 'study-plans', 'schedule-materials',
'auditorium-workload', 'schedule-view', 'teacher-absences', 'classrooms']
);
assert.ok(!officeTabs.includes('teacher-requests'));
@@ -123,6 +123,7 @@ test('маршруты вкладок полностью перенесены н
assert.deepEqual(reactTabs, [
'dashboard',
'classrooms',
'schedule-materials',
'study-plans',
'subjects',
'users',
@@ -141,7 +142,7 @@ test('маршруты вкладок полностью перенесены н
'schedule-quality',
'teacher-absences'
]);
assert.equal(reactTabs.length, 19);
assert.equal(reactTabs.length, 20);
for (const [tab, route] of Object.entries(ADMIN_ROUTES)) {
assert.ok(route.title, tab);
@@ -163,7 +164,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, 19);
assert.equal(entries.length, 20);
for (const [, modulePath, exportName] of entries) {
const tabSource = await readFrontendFile(`react/admin/${modulePath.replace('./', '')}`);
+119
View File
@@ -0,0 +1,119 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { materialTotals } from '../react/admin/schedule-materials-service.js';
import { calendarMaterialRows } from '../react/admin/calendar-loads-service.js';
import { teachersSearchEndpoint } from '../react/admin/subjects-service.js';
import { allowedAdminTabs } from '../react/admin/admin-service.js';
import {
groupMatrixColumns,
groupMatrixRows,
groupMatrixDates,
} from '../react/admin/group-schedule-matrix-service.js';
const details = [1, 2].map((id) => ({
context: { groupId: id, groupName: `Группа ${id}` },
subjects: [
{
subjectId: 1,
name: 'Операционные системы',
departmentId: 2,
loads: [
{
category: 'LECTURE',
academicHours: id === 1 ? 36 : 20,
workloadHours: id === 1 ? 36 : 20,
teacherId: id + 6,
},
{
category: 'PRACTICE',
academicHours: 0,
workloadHours: 0,
teacherId: null,
},
{
category: 'LABORATORY',
academicHours: 18,
workloadHours: 36,
splitSubgroups: true,
teacherId: null,
},
],
},
],
}));
test('нагрузка одной дисциплины отличается по группам, подгруппы удваивают только нагрузку', () => {
const rows = calendarMaterialRows(details);
assert.equal(rows.length, 4);
assert.deepEqual(materialTotals(rows), {
academic: 92,
workload: 128,
unassigned: 72,
});
assert.equal(
calendarMaterialRows(details, { groupId: '2' })[0].academicHours,
20,
);
assert.equal(
calendarMaterialRows(details, { groupId: '1', unassigned: true })[0]
.workloadHours,
36,
);
assert.equal(
calendarMaterialRows(details, { query: 'Группа 2' }).length,
2,
);
assert.equal(
calendarMaterialRows(details, { includeZero: true }).length,
6,
);
});
test('поиск преподавателей дисциплины передаёт кафедру и выбранного преподавателя', () => {
const url = new URL(
teachersSearchEndpoint('Иванов', 7, 2),
'http://localhost',
);
assert.equal(url.searchParams.get('departmentId'), '2');
assert.equal(url.searchParams.get('selectedId'), '7');
});
test('распределять материалы могут администратор и учебный отдел', () => {
for (const role of ['ADMIN', 'EDUCATION_OFFICE'])
assert.ok(allowedAdminTabs(role).has('schedule-materials'));
for (const role of ['DEPARTMENT', 'SCHEDULE_VIEWER'])
assert.ok(!allowedAdminTabs(role).has('schedule-materials'));
});
test('матрица группирует столбцы по кафедре, строки по дням и парам, не теряет занятия вне сетки', () => {
const groups = [
{ id: 1, name: 'Группа 1', departmentId: 2 },
{ id: 2, name: 'Группа 2', departmentId: 1 },
];
const { columns, sections } = groupMatrixColumns(groups, [
{ id: 1, name: 'А' },
{ id: 2, name: 'Б' },
]);
assert.deepEqual(
columns.map((g) => g.id),
[2, 1],
);
assert.deepEqual(
sections.map((s) => s.name),
['А', 'Б'],
);
const dates = groupMatrixDates('2026-10-21');
assert.equal(dates[0], '2026-10-19');
assert.equal(dates.at(-1), '2026-10-25');
const lesson = { date: dates[0], timeSlotOrder: 2, subjectName: 'Лекция' };
const rows = groupMatrixRows(
dates,
columns,
new Map([[dates[0], [{ orderNumber: 1 }]]]),
new Map([
['1', [lesson]],
['2', [lesson]],
]),
);
assert.deepEqual(
rows.map((r) => r.order),
[1, 2],
);
assert.equal(rows[1].cells[0][0].subjectName, 'Лекция');
assert.equal(rows[1].cells[1][0].subjectName, 'Лекция');
});