fix(frontend): исправлены дефекты P1 из аудита React (2.1-2.4)
2.1 Гонки запросов: общий механизм latest-request-wins - shared/latest-request.js (createLatestRequest) + use-latest-request.js - clientWithSignal в api-client.js: AbortSignal без правки сигнатур сервисов - ScheduleViewTab/ScheduleVersionsTab/ScheduleQualityTab/RequestDialog: устаревшие ответы не применяются, кнопки блокируются на время загрузки - смена семестра в анализе качества очищает зависимые данные 2.2 Пожелания преподавателя: semesterId=0 невозможен - resolveDefaultSemester: текущий -> ближайший будущий -> последний завершённый - явный пустой пункт «Выберите семестр», блокировка сетки/дат/переключателей - кнопка «Повторить» при ошибке метаданных 2.3 Dirty/hash-навигация: отмена возвращает URL через replaceState - confirmedHashRef + navigatingRef, hash-эффект с [role] deps 2.4 Диалог заявки: ошибка отправки показывается, диалог не закрывается - контракт onSubmitted true/false, защита от двойной отправки Тесты: latest-request.test.mjs (14 сценариев) + статические проверки в тематических тестах; всего 266 проверок, бюджеты бандлов в норме (teacher cold load 88648/90000 gzip).
This commit is contained in:
1 parent
28c3d12404
commit
9458a4a59d
19 files changed
+1261
-39
No files matched your search
@@ -11,7 +11,7 @@
|
||||
"build:react-tests": "node scripts/build-react-tests.mjs",
|
||||
"build:vendor": "node scripts/build-vendor.mjs",
|
||||
"test": "npm run build:react-tests && node --test tests/*.test.mjs",
|
||||
"check": "npm run build:react && node --check auth-session.js && node --check telemetry.js && node --check schedule-overview.js && node --check react/login/login-service.js && node --check react/shared/api-client.js && node --check react/shared/auth-client.js && node --check react/shared/session-policy.js && node --check react/student/student-service.js && node --check react/teacher/teacher-service.js && node --check react/settings/settings-service.js && node --check react/admin/admin-service.js && node --check react/admin/react-tabs.js && node --check react/admin/classrooms-service.js && node --check react/admin/subjects-service.js && node --check react/admin/dashboard-service.js && node --check react/admin/users-service.js && node --check react/admin/groups-service.js && node --check react/admin/university-structure-service.js && node --check react/admin/teacher-requests-service.js && node --check react/admin/department-workspace-service.js && node --check react/admin/auditorium-workload-service.js && node --check react/admin/academic-calendar-service.js && node --check react/admin/schedule-view-service.js && node --check react/admin/schedule-versions-service.js && node --check react/admin/schedule-service.js && node --check react/admin/schedule-override-service.js && node --check react/admin/schedule-quality-service.js && node --check react/admin/teacher-absences-service.js && node --check admin/js/api.js && node --check admin/js/academic-period.js && node --check admin/js/dialog.js && node --check admin/js/dirty-state.js && node --check admin/js/url-state.js && node --check admin/js/view-state.js && npm test",
|
||||
"check": "npm run build:react && node --check auth-session.js && node --check telemetry.js && node --check schedule-overview.js && node --check react/login/login-service.js && node --check react/shared/api-client.js && node --check react/shared/auth-client.js && node --check react/shared/latest-request.js && node --check react/shared/session-policy.js && node --check react/shared/use-latest-request.js && node --check react/student/student-service.js && node --check react/teacher/teacher-service.js && node --check react/settings/settings-service.js && node --check react/admin/admin-service.js && node --check react/admin/react-tabs.js && node --check react/admin/classrooms-service.js && node --check react/admin/subjects-service.js && node --check react/admin/dashboard-service.js && node --check react/admin/users-service.js && node --check react/admin/groups-service.js && node --check react/admin/university-structure-service.js && node --check react/admin/teacher-requests-service.js && node --check react/admin/department-workspace-service.js && node --check react/admin/auditorium-workload-service.js && node --check react/admin/academic-calendar-service.js && node --check react/admin/schedule-view-service.js && node --check react/admin/schedule-versions-service.js && node --check react/admin/schedule-service.js && node --check react/admin/schedule-override-service.js && node --check react/admin/schedule-quality-service.js && node --check react/admin/teacher-absences-service.js && node --check admin/js/api.js && node --check admin/js/academic-period.js && node --check admin/js/dialog.js && node --check admin/js/dirty-state.js && node --check admin/js/url-state.js && node --check admin/js/view-state.js && npm test",
|
||||
"check:browser": "node --test tests/browser/*.test.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -192,6 +192,16 @@ export function AdminWorkspace({ role }) {
|
||||
: tabFromHash(window.location.hash, role)
|
||||
));
|
||||
const activeTabRef = useRef(activeTab);
|
||||
// Последний подтверждённый hash: при отмене перехода с несохранёнными
|
||||
// изменениями URL возвращается к открытой вкладке без новой записи
|
||||
// history (replaceState не вызывает hashchange).
|
||||
const confirmedHashRef = useRef(null);
|
||||
if (confirmedHashRef.current === null) {
|
||||
confirmedHashRef.current = typeof window === 'undefined' ? '' : `#${activeTabRef.current}`;
|
||||
}
|
||||
// Пока открыт диалог подтверждения перехода, параллельные смены hash
|
||||
// (back/forward) блокируются — второй диалог не открывается.
|
||||
const navigatingRef = useRef(false);
|
||||
const { collapsed, mobileOpen, toggleSidebar, closeSidebar } = useSidebar();
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [pendingCount, setPendingCount] = useState(null);
|
||||
@@ -203,13 +213,19 @@ export function AdminWorkspace({ role }) {
|
||||
|
||||
useEffect(() => {
|
||||
function handleHashChange() {
|
||||
if (navigatingRef.current) {
|
||||
// Переход уже подтверждается: возвращаем URL к последнему
|
||||
// подтверждённому разделу, не открывая второй диалог.
|
||||
restoreConfirmedHash();
|
||||
return;
|
||||
}
|
||||
void requestTabSwitch(tabFromHash(window.location.hash, role));
|
||||
}
|
||||
window.addEventListener('hashchange', handleHashChange);
|
||||
return () => {
|
||||
window.removeEventListener('hashchange', handleHashChange);
|
||||
};
|
||||
});
|
||||
}, [role]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(event) {
|
||||
@@ -250,16 +266,43 @@ export function AdminWorkspace({ role }) {
|
||||
};
|
||||
}, [role]);
|
||||
|
||||
function restoreConfirmedHash() {
|
||||
if (typeof window === 'undefined') return;
|
||||
const confirmed = confirmedHashRef.current;
|
||||
if (confirmed && window.location.hash !== confirmed) {
|
||||
// replaceState не создаёт запись history и не вызывает
|
||||
// hashchange, поэтому отменённый переход не ломает навигацию.
|
||||
window.history.replaceState(null, '', confirmed);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestTabSwitch(tab) {
|
||||
if (tab === activeTabRef.current) {
|
||||
closeSidebar();
|
||||
return;
|
||||
}
|
||||
if (!allowedTabs.has(tab)) return;
|
||||
if (activeTabRef.current && !(await confirmAbandonDirtyChanges())) return;
|
||||
if (navigatingRef.current) return;
|
||||
if (activeTabRef.current) {
|
||||
navigatingRef.current = true;
|
||||
let confirmed = false;
|
||||
try {
|
||||
confirmed = await confirmAbandonDirtyChanges();
|
||||
} finally {
|
||||
navigatingRef.current = false;
|
||||
}
|
||||
if (!confirmed) {
|
||||
// Отмена перехода: URL уже указывает на новую вкладку
|
||||
// (back/forward меняют hash до подтверждения) — возвращаем
|
||||
// его к открытому разделу.
|
||||
restoreConfirmedHash();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
activeTabRef.current = tab;
|
||||
setActiveTab(tab);
|
||||
confirmedHashRef.current = `#${tab}`;
|
||||
closeSidebar();
|
||||
trackUxEvent('раздел_открыт', { tab, role });
|
||||
if (window.location.hash !== `#${tab}`) {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||||
import { apiClient, clientWithSignal } from '../../shared/api-client.js';
|
||||
import { useLatestRequest } from '../../shared/use-latest-request.js';
|
||||
|
||||
import {
|
||||
academicYearsFromSemesters,
|
||||
@@ -51,6 +53,11 @@ export function ScheduleQualityTab() {
|
||||
|
||||
const latestRef = useRef(null);
|
||||
latestRef.current = { academicYearId, semesterId, versionId };
|
||||
// Защита от гонок: быстрая смена года/семестра не позволяет ответу
|
||||
// предыдущего периода остаться в списке версий; смена периода также
|
||||
// делает неактуальным выполняющийся анализ.
|
||||
const versionsRequest = useLatestRequest();
|
||||
const analysisRequest = useLatestRequest();
|
||||
|
||||
const years = useMemo(() => academicYearsFromSemesters(semesters), [semesters]);
|
||||
const yearSemesters = useMemo(
|
||||
@@ -97,9 +104,20 @@ export function ScheduleQualityTab() {
|
||||
async function loadVersions(overrideSemesterId) {
|
||||
const nextSemesterId = overrideSemesterId ?? latestRef.current.semesterId;
|
||||
if (!nextSemesterId) return;
|
||||
const request = versionsRequest.begin();
|
||||
// Смена периода делает предыдущий анализ неактуальным: очищаем
|
||||
// зависимые данные до получения нового ответа.
|
||||
analysisRequest.dispose();
|
||||
setAnalysis(null);
|
||||
setResultsHidden(true);
|
||||
setSelectedProblemId(null);
|
||||
setVersionPhase('loading');
|
||||
try {
|
||||
const loadedVersions = await fetchScheduleVersions(nextSemesterId);
|
||||
const loadedVersions = await fetchScheduleVersions(
|
||||
nextSemesterId,
|
||||
clientWithSignal(apiClient, request.signal)
|
||||
);
|
||||
if (!versionsRequest.isCurrent(request.id)) return;
|
||||
setVersions(loadedVersions);
|
||||
if (!loadedVersions.length) {
|
||||
setVersionPhase('empty');
|
||||
@@ -113,6 +131,7 @@ export function ScheduleQualityTab() {
|
||||
window.localStorage.setItem(QUALITY_YEAR_STORAGE_KEY, latestRef.current.academicYearId);
|
||||
window.localStorage.setItem(QUALITY_SEMESTER_STORAGE_KEY, nextSemesterId);
|
||||
} catch (error) {
|
||||
if (!versionsRequest.isCurrent(request.id)) return;
|
||||
setVersionPhase('error');
|
||||
setStatus({ message: error.message || 'Не удалось загрузить версии расписания.', tone: 'error' });
|
||||
}
|
||||
@@ -149,11 +168,17 @@ export function ScheduleQualityTab() {
|
||||
}
|
||||
window.localStorage.setItem(QUALITY_SEMESTER_STORAGE_KEY, currentSemesterId);
|
||||
window.localStorage.setItem(QUALITY_VERSION_STORAGE_KEY, currentVersionId);
|
||||
const request = analysisRequest.begin();
|
||||
setAnalyzing(true);
|
||||
setResultsHidden(true);
|
||||
setStatus({ message: 'Строим фактическое расписание и рассчитываем показатели…', tone: 'loading' });
|
||||
try {
|
||||
const nextAnalysis = await fetchScheduleQualityAnalysis(currentSemesterId, currentVersionId);
|
||||
const nextAnalysis = await fetchScheduleQualityAnalysis(
|
||||
currentSemesterId,
|
||||
currentVersionId,
|
||||
clientWithSignal(apiClient, request.signal)
|
||||
);
|
||||
if (!analysisRequest.isCurrent(request.id)) return;
|
||||
setAnalysis(nextAnalysis);
|
||||
setSelectedProblemId(null);
|
||||
setResultsHidden(false);
|
||||
@@ -169,6 +194,7 @@ export function ScheduleQualityTab() {
|
||||
tone: 'success'
|
||||
});
|
||||
} catch (error) {
|
||||
if (!analysisRequest.isCurrent(request.id)) return;
|
||||
setStatus({ message: error.message || 'Не удалось выполнить анализ качества.', tone: 'error' });
|
||||
} finally {
|
||||
setAnalyzing(false);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||||
import { apiClient, clientWithSignal } from '../../shared/api-client.js';
|
||||
import { useLatestRequest } from '../../shared/use-latest-request.js';
|
||||
|
||||
import {
|
||||
academicYearsFromSemesters,
|
||||
@@ -49,7 +51,11 @@ export function ScheduleVersionsTab() {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const latestRef = useRef(null);
|
||||
latestRef.current = { academicYearId, semesterId, loading };
|
||||
latestRef.current = { academicYearId, semesterId };
|
||||
// Защита от гонок: смена семестра во время загрузки запускает новый
|
||||
// запрос, а ответ предыдущего не применяется — список версий всегда
|
||||
// соответствует выбранному семестру.
|
||||
const workspaceRequest = useLatestRequest();
|
||||
|
||||
const years = useMemo(() => academicYearsFromSemesters(semesters), [semesters]);
|
||||
const yearSemesters = useMemo(
|
||||
@@ -96,25 +102,29 @@ export function ScheduleVersionsTab() {
|
||||
|
||||
async function loadWorkspace(overrideSemesterId) {
|
||||
const nextSemesterId = overrideSemesterId ?? latestRef.current.semesterId;
|
||||
if (!nextSemesterId || latestRef.current.loading) return;
|
||||
if (!nextSemesterId) return;
|
||||
const request = workspaceRequest.begin();
|
||||
setLoading(true);
|
||||
window.localStorage.setItem(SCHEDULE_YEAR_STORAGE_KEY, latestRef.current.academicYearId);
|
||||
window.localStorage.setItem(SCHEDULE_SEMESTER_STORAGE_KEY, nextSemesterId);
|
||||
setStatus({ message: 'Собираем версии, правила и журнал публикаций…', tone: 'loading' });
|
||||
try {
|
||||
const client = clientWithSignal(apiClient, request.signal);
|
||||
const [nextVersions, nextHistory] = await Promise.all([
|
||||
fetchScheduleVersions(nextSemesterId),
|
||||
fetchScheduleVersionHistory(nextSemesterId)
|
||||
fetchScheduleVersions(nextSemesterId, client),
|
||||
fetchScheduleVersionHistory(nextSemesterId, client)
|
||||
]);
|
||||
if (!workspaceRequest.isCurrent(request.id)) return;
|
||||
setVersions(nextVersions);
|
||||
setHistory(nextHistory);
|
||||
setLoaded(true);
|
||||
trackUxEvent('версии_расписания_загружены', { semesterId: nextSemesterId, total: nextVersions.length });
|
||||
setStatus({ message: 'Контур версий синхронизирован.', tone: 'success' });
|
||||
} catch (error) {
|
||||
if (!workspaceRequest.isCurrent(request.id)) return;
|
||||
setStatus({ message: error.message || 'Не удалось загрузить версии расписания.', tone: 'error' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (workspaceRequest.isCurrent(request.id)) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
|
||||
import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||||
import { apiClient, clientWithSignal } from '../../shared/api-client.js';
|
||||
import { useLatestRequest } from '../../shared/use-latest-request.js';
|
||||
|
||||
import { getSession } from '../../../admin/js/api.js';
|
||||
import {
|
||||
@@ -165,6 +167,9 @@ export function ScheduleViewTab() {
|
||||
|
||||
const overrideDrawerRef = useRef(null);
|
||||
const rangeRef = useRef(null);
|
||||
// Защита от гонок: повторное нажатие «Показать» или смена фильтров
|
||||
// отменяет предыдущий запрос, устаревший ответ не применяется.
|
||||
const scheduleRequest = useLatestRequest();
|
||||
|
||||
// Загрузка и обработчики читают актуальные значения через этот ref:
|
||||
// боковая панель правок захватывает колбэки один раз при создании.
|
||||
@@ -285,6 +290,10 @@ export function ScheduleViewTab() {
|
||||
}
|
||||
|
||||
async function loadData(overrideDate) {
|
||||
// Любой новый запуск делает предыдущий запрос неактуальным:
|
||||
// устаревший ответ не может перезаписать состояние после
|
||||
// повторного нажатия «Показать» или смены фильтров.
|
||||
const request = scheduleRequest.begin();
|
||||
const current = latestRef.current;
|
||||
const effectiveDate = overrideDate || current.dateValue;
|
||||
setAlert(null);
|
||||
@@ -293,6 +302,9 @@ export function ScheduleViewTab() {
|
||||
const message = 'Выберите дату в периоде';
|
||||
setAlert({ message, type: 'error' });
|
||||
resetResults(message);
|
||||
// Прежний запрос только что стал неактуальным и не сбросит
|
||||
// индикатор сам — сбрасываем здесь.
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -300,6 +312,7 @@ export function ScheduleViewTab() {
|
||||
const message = 'Не удалось определить кафедру пользователя';
|
||||
setAlert({ message, type: 'error' });
|
||||
resetResults(message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -316,6 +329,7 @@ export function ScheduleViewTab() {
|
||||
departmentId: current.departmentId
|
||||
})) {
|
||||
resetResults('Выберите параметры и нажмите «Показать»');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -329,6 +343,7 @@ export function ScheduleViewTab() {
|
||||
setTableState({ message: 'Загрузка...', actionable: false });
|
||||
|
||||
try {
|
||||
const client = clientWithSignal(apiClient, request.signal);
|
||||
const [lessons, overrideList] = await Promise.all([
|
||||
fetchScheduleLessons({
|
||||
startDate: nextRange.startDate,
|
||||
@@ -343,22 +358,24 @@ export function ScheduleViewTab() {
|
||||
subjectId: current.subjectId,
|
||||
lessonTypeId: current.lessonTypeId,
|
||||
parity: current.parity
|
||||
}),
|
||||
}, client),
|
||||
canEditOverridesRef.current
|
||||
? fetchScheduleOverrides(nextRange)
|
||||
? fetchScheduleOverrides(nextRange, client)
|
||||
: Promise.resolve([])
|
||||
]);
|
||||
if (!scheduleRequest.isCurrent(request.id)) return;
|
||||
setOverrides(overrideList || []);
|
||||
setOverrideRegistryRange(nextRange);
|
||||
renderLessons(lessons, nextRange, loadTarget, previousKey, effectiveDate);
|
||||
persistFilters({ date: effectiveDate });
|
||||
trackUxEvent('расписание_найдено', { target: loadTarget, lessons: lessons.length });
|
||||
} catch (error) {
|
||||
if (!scheduleRequest.isCurrent(request.id)) return;
|
||||
const message = error.data?.message || error.message || 'Ошибка загрузки расписания';
|
||||
setAlert({ message, type: 'error' });
|
||||
resetResults(message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (scheduleRequest.isCurrent(request.id)) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -608,6 +625,7 @@ export function ScheduleViewTab() {
|
||||
type="button"
|
||||
className="btn btn-md btn-primary schedule-view-state-reload"
|
||||
data-schedule-view-reload=""
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
void loadData();
|
||||
}}
|
||||
@@ -700,6 +718,7 @@ export function ScheduleViewTab() {
|
||||
type="button"
|
||||
className="btn btn-md btn-secondary"
|
||||
id="schedule-view-load"
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
void loadData();
|
||||
}}
|
||||
|
||||
@@ -76,6 +76,23 @@ export const apiClient = Object.freeze({
|
||||
)
|
||||
});
|
||||
|
||||
/**
|
||||
* Привязка AbortSignal к клиенту: каждый запрос обёртки передаёт сигнал
|
||||
* в fetch, поэтому устаревший запрос прерывается защитой от гонок
|
||||
* (см. shared/latest-request.js). Без сигнала возвращается исходный
|
||||
* клиент без обёртки.
|
||||
*/
|
||||
export function clientWithSignal(client, signal) {
|
||||
if (!signal) return client;
|
||||
const withSignal = options => ({ ...(options || {}), signal });
|
||||
return {
|
||||
get: (endpoint, options, dependencies) => client.get(endpoint, withSignal(options), dependencies),
|
||||
post: (endpoint, json, options, dependencies) => client.post(endpoint, json, withSignal(options), dependencies),
|
||||
put: (endpoint, json, options, dependencies) => client.put(endpoint, json, withSignal(options), dependencies),
|
||||
delete: (endpoint, options, dependencies) => client.delete(endpoint, withSignal(options), dependencies)
|
||||
};
|
||||
}
|
||||
|
||||
async function readResponseData(response) {
|
||||
if (response.status === 204) {
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Защита от гонок запросов (latest-request-wins).
|
||||
*
|
||||
* `begin()` прерывает предыдущий запрос и возвращает дескриптор нового:
|
||||
* монотонный `id` для проверки актуальности и `AbortSignal` для передачи
|
||||
* в apiClient. Результат разрешено применять только пока `isCurrent(id)`
|
||||
* возвращает true: любой новый `begin()` или `dispose()` делает прежний
|
||||
* запрос неактуальным, поэтому устаревший ответ не может перезаписать
|
||||
* состояние после смены фильтров или размонтирования вкладки.
|
||||
*/
|
||||
export function createLatestRequest() {
|
||||
let latestId = 0;
|
||||
let latestController = null;
|
||||
|
||||
function abortCurrent() {
|
||||
if (latestController) {
|
||||
latestController.abort();
|
||||
latestController = null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
begin() {
|
||||
abortCurrent();
|
||||
latestController = typeof AbortController === 'undefined' ? null : new AbortController();
|
||||
latestId += 1;
|
||||
return { id: latestId, signal: latestController ? latestController.signal : undefined };
|
||||
},
|
||||
isCurrent(id) {
|
||||
return id === latestId;
|
||||
},
|
||||
dispose() {
|
||||
abortCurrent();
|
||||
latestId += 1;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
import { createLatestRequest } from './latest-request.js';
|
||||
|
||||
/**
|
||||
* Гонки запросов вкладки: `begin()` запускает новый запрос и прерывает
|
||||
* предыдущий, `isCurrent(id)` разрешает применять результат только
|
||||
* последнему запуску. При размонтировании вкладки запрос прерывается
|
||||
* через `dispose()`.
|
||||
*/
|
||||
export function useLatestRequest() {
|
||||
const guardRef = useRef(null);
|
||||
if (guardRef.current === null) guardRef.current = createLatestRequest();
|
||||
|
||||
useEffect(() => () => guardRef.current.dispose(), []);
|
||||
|
||||
return guardRef.current;
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
preferenceTypeClass,
|
||||
preferenceTypeLabel,
|
||||
preferenceTypeSymbol,
|
||||
resolveCurrentSemester,
|
||||
resolveDefaultSemester,
|
||||
resolveSelectedSemester,
|
||||
semesterLabel
|
||||
} from './teacher-service.js';
|
||||
@@ -25,6 +25,7 @@ const WEEK_DAY_LABELS = Object.freeze(['Пн', 'Вт', 'Ср', 'Чт', 'Пт', '
|
||||
export function PreferencesTab() {
|
||||
const [meta, setMeta] = useState({ semesters: [], timeSlots: [] });
|
||||
const [metaError, setMetaError] = useState(false);
|
||||
const [metaAttempt, setMetaAttempt] = useState(0);
|
||||
const [semesterId, setSemesterId] = useState('');
|
||||
const [preferences, setPreferences] = useState([]);
|
||||
const [brush, setBrush] = useState('SOFT_PREFERRED');
|
||||
@@ -33,6 +34,9 @@ export function PreferencesTab() {
|
||||
const [dateComment, setDateComment] = useState('');
|
||||
const [busyCell, setBusyCell] = useState('');
|
||||
|
||||
// Период по умолчанию: текущий семестр, в каникулы — ближайший
|
||||
// будущий, после завершения всех — последний завершившийся.
|
||||
// Повторные попытки загрузки метаданных перезапускают эффект.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
(async () => {
|
||||
@@ -40,9 +44,9 @@ export function PreferencesTab() {
|
||||
const loaded = await fetchPreferenceMeta();
|
||||
if (!active) return;
|
||||
setMeta(loaded);
|
||||
const semesters = loaded.semesters || [];
|
||||
const current = resolveCurrentSemester(semesters, toIsoDate(new Date()));
|
||||
if (current) setSemesterId(String(current.id));
|
||||
setMetaError(false);
|
||||
const fallback = resolveDefaultSemester(loaded.semesters || [], toIsoDate(new Date()));
|
||||
if (fallback) setSemesterId(String(fallback.id));
|
||||
} catch {
|
||||
if (active) setMetaError(true);
|
||||
}
|
||||
@@ -50,7 +54,7 @@ export function PreferencesTab() {
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
}, [metaAttempt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!semesterId) return undefined;
|
||||
@@ -71,6 +75,10 @@ export function PreferencesTab() {
|
||||
}, [semesterId]);
|
||||
|
||||
const semester = resolveSelectedSemester(meta.semesters, semesterId);
|
||||
// Запрос с semesterId = 0 невозможен: операции доступны только при
|
||||
// положительном целом ID выбранного семестра.
|
||||
const semesterIdNumber = Number(semesterId);
|
||||
const semesterSelected = Number.isInteger(semesterIdNumber) && semesterIdNumber > 0;
|
||||
|
||||
useEffect(() => {
|
||||
const min = semester?.startDate || '';
|
||||
@@ -93,6 +101,10 @@ export function PreferencesTab() {
|
||||
}
|
||||
|
||||
async function handleCell(dayOfWeek, timeSlotId) {
|
||||
if (!semesterSelected) {
|
||||
showMessage('Выберите семестр', true);
|
||||
return;
|
||||
}
|
||||
const existing = findWeekPreference(preferences, dayOfWeek, timeSlotId);
|
||||
if (existing) {
|
||||
if (existing.status === 'APPROVED') {
|
||||
@@ -114,7 +126,7 @@ export function PreferencesTab() {
|
||||
await createPreference({
|
||||
dayOfWeek,
|
||||
preferenceType: brush,
|
||||
semesterId: Number(semesterId),
|
||||
semesterId: semesterIdNumber,
|
||||
timeSlotId: Number(timeSlotId)
|
||||
});
|
||||
showMessage('Отметка отправлена на согласование', false);
|
||||
@@ -128,13 +140,17 @@ export function PreferencesTab() {
|
||||
|
||||
async function submitDate(event) {
|
||||
event.preventDefault();
|
||||
if (!semesterSelected) {
|
||||
showMessage('Выберите семестр', true);
|
||||
return;
|
||||
}
|
||||
if (!dateValue) return;
|
||||
try {
|
||||
await createPreference({
|
||||
comment: dateComment.trim() || null,
|
||||
preferenceDate: dateValue,
|
||||
preferenceType: 'HARD_UNAVAILABLE',
|
||||
semesterId: Number(semesterId)
|
||||
semesterId: semesterIdNumber
|
||||
});
|
||||
setDateComment('');
|
||||
showMessage('Дата недоступности отправлена на согласование', false);
|
||||
@@ -155,13 +171,17 @@ export function PreferencesTab() {
|
||||
}
|
||||
|
||||
async function toggleCompact(type, checked, existingId) {
|
||||
if (!semesterSelected) {
|
||||
showMessage('Выберите семестр', true);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!checked && existingId) {
|
||||
await deletePreference(existingId);
|
||||
} else if (checked) {
|
||||
await createPreference({
|
||||
preferenceType: type,
|
||||
semesterId: Number(semesterId)
|
||||
semesterId: semesterIdNumber
|
||||
});
|
||||
}
|
||||
await reloadPreferences();
|
||||
@@ -186,6 +206,7 @@ export function PreferencesTab() {
|
||||
<label className="preference-semester-field">
|
||||
<span>Семестр</span>
|
||||
<CustomSelect value={semesterId} onChange={event => setSemesterId(event.target.value)}>
|
||||
<option value="">Выберите семестр</option>
|
||||
{(meta.semesters || []).map(item => (
|
||||
<option key={item.id} value={item.id}>{semesterLabel(item)}</option>
|
||||
))}
|
||||
@@ -217,7 +238,16 @@ export function PreferencesTab() {
|
||||
<div className="preference-grid-wrap">
|
||||
<div className="preference-grid" aria-live="polite">
|
||||
{metaError ? (
|
||||
<div className="preference-empty">Не удалось загрузить параметры семестра</div>
|
||||
<div className="preference-empty">
|
||||
<span>Не удалось загрузить параметры семестра</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-secondary"
|
||||
onClick={() => setMetaAttempt(attempt => attempt + 1)}
|
||||
>
|
||||
Повторить
|
||||
</button>
|
||||
</div>
|
||||
) : slots.length === 0 ? (
|
||||
<div className="preference-empty">Базовая сетка времени не настроена</div>
|
||||
) : (
|
||||
@@ -242,7 +272,7 @@ export function PreferencesTab() {
|
||||
key={`cell-${slot.id}-${dayOfWeek}`}
|
||||
type="button"
|
||||
className={`preference-cell ${preferenceTypeClass(item?.preferenceType)}${item?.status === 'PENDING' ? ' is-pending' : ''}`}
|
||||
disabled={busyCell === `${dayOfWeek}:${slot.id}`}
|
||||
disabled={!semesterSelected || busyCell === `${dayOfWeek}:${slot.id}`}
|
||||
title={title}
|
||||
aria-label={title}
|
||||
onClick={() => void handleCell(dayOfWeek, slot.id)}
|
||||
@@ -273,6 +303,7 @@ export function PreferencesTab() {
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
disabled={!semesterSelected}
|
||||
min={semester?.startDate || ''}
|
||||
max={semester?.endDate || ''}
|
||||
value={dateValue}
|
||||
@@ -285,7 +316,7 @@ export function PreferencesTab() {
|
||||
value={dateComment}
|
||||
onChange={event => setDateComment(event.target.value)}
|
||||
/>
|
||||
<button className="btn btn-md btn-primary" type="submit">Добавить дату</button>
|
||||
<button className="btn btn-md btn-primary" type="submit" disabled={!semesterSelected}>Добавить дату</button>
|
||||
</form>
|
||||
<div className="preference-date-list">
|
||||
{dateItems.length === 0 ? (
|
||||
@@ -320,6 +351,7 @@ export function PreferencesTab() {
|
||||
title="Пары подряд"
|
||||
description="Собирать занятия последовательными блоками"
|
||||
preference={findCompactPreference(preferences, 'CONSECUTIVE')}
|
||||
disabled={!semesterSelected}
|
||||
onToggle={toggleCompact}
|
||||
/>
|
||||
<CompactToggle
|
||||
@@ -327,6 +359,7 @@ export function PreferencesTab() {
|
||||
title="Без окон"
|
||||
description="Не оставлять пустые интервалы между занятиями"
|
||||
preference={findCompactPreference(preferences, 'NO_GAPS')}
|
||||
disabled={!semesterSelected}
|
||||
onToggle={toggleCompact}
|
||||
/>
|
||||
</section>
|
||||
@@ -335,14 +368,14 @@ export function PreferencesTab() {
|
||||
);
|
||||
}
|
||||
|
||||
function CompactToggle({ type, title, description, preference, onToggle }) {
|
||||
function CompactToggle({ type, title, description, preference, onToggle, disabled = false }) {
|
||||
const approved = preference?.status === 'APPROVED';
|
||||
return (
|
||||
<label className={`preference-toggle-card${approved ? ' approved' : ''}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(preference)}
|
||||
disabled={approved}
|
||||
disabled={approved || disabled}
|
||||
onChange={event => void onToggle(type, event.target.checked, preference?.id)}
|
||||
/>
|
||||
<span><strong>{title}</strong><small>{description}</small></span>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { apiClient, clientWithSignal } from '../shared/api-client.js';
|
||||
import { formatIsoDate, trimTime } from '../shared/dates.js';
|
||||
import { useLatestRequest } from '../shared/use-latest-request.js';
|
||||
import { CustomSelect } from '../shared/ui/CustomSelect.jsx';
|
||||
import {
|
||||
buildChangeRequestPayload,
|
||||
@@ -8,6 +10,8 @@ import {
|
||||
fetchChangeRequestCandidates
|
||||
} from './teacher-service.js';
|
||||
|
||||
const SUBMIT_ERROR_MESSAGE = 'Не удалось отправить заявку. Попробуйте ещё раз.';
|
||||
|
||||
export function RequestDialog({ lesson, onClose, onSubmitted }) {
|
||||
const [candidates, setCandidates] = useState(null);
|
||||
const [candidatesError, setCandidatesError] = useState(false);
|
||||
@@ -18,6 +22,9 @@ export function RequestDialog({ lesson, onClose, onSubmitted }) {
|
||||
const [reason, setReason] = useState('');
|
||||
const [message, setMessage] = useState({ text: 'Проверяем допустимые варианты...', isError: false });
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
// Кандидаты всегда относятся к отображаемой дате: быстрая смена даты
|
||||
// отменяет предыдущую проверку, устаревший ответ не применяется.
|
||||
const candidatesRequest = useLatestRequest();
|
||||
|
||||
useEffect(() => {
|
||||
document.body.classList.add('dialog-open');
|
||||
@@ -27,57 +34,61 @@ export function RequestDialog({ lesson, onClose, onSubmitted }) {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const request = candidatesRequest.begin();
|
||||
(async () => {
|
||||
try {
|
||||
const loaded = await fetchChangeRequestCandidates({
|
||||
baseRuleSlotId: lesson.scheduleRuleSlotId,
|
||||
lessonDate: lesson.date
|
||||
});
|
||||
if (!active) return;
|
||||
}, clientWithSignal(apiClient, request.signal));
|
||||
if (!candidatesRequest.isCurrent(request.id)) return;
|
||||
setCandidates(loaded);
|
||||
setCandidatesError(false);
|
||||
setTargetDate(loaded.checkedDate || (loaded.availableDates || [])[0] || '');
|
||||
setMessage({ text: 'Доступны только варианты, прошедшие проверку конфликтов', isError: false });
|
||||
} catch {
|
||||
if (!active) return;
|
||||
if (!candidatesRequest.isCurrent(request.id)) return;
|
||||
setCandidatesError(true);
|
||||
setMessage({ text: 'Не удалось проверить допустимые варианты', isError: true });
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [lesson]);
|
||||
}, [lesson, candidatesRequest]);
|
||||
|
||||
async function reloadCandidates(nextDate) {
|
||||
if (!nextDate) return;
|
||||
const request = candidatesRequest.begin();
|
||||
setMessage({ text: 'Проверяем выбранную дату...', isError: false });
|
||||
try {
|
||||
const loaded = await fetchChangeRequestCandidates({
|
||||
baseRuleSlotId: lesson.scheduleRuleSlotId,
|
||||
lessonDate: lesson.date,
|
||||
targetDate: nextDate
|
||||
});
|
||||
}, clientWithSignal(apiClient, request.signal));
|
||||
if (!candidatesRequest.isCurrent(request.id)) return;
|
||||
setCandidates(loaded);
|
||||
setCandidatesError(false);
|
||||
setTimeSlotId('');
|
||||
setClassroomId('');
|
||||
setMessage({ text: 'Предварительная проверка завершена', isError: false });
|
||||
} catch {
|
||||
if (!candidatesRequest.isCurrent(request.id)) return;
|
||||
setMessage({ text: 'Не удалось проверить допустимые варианты', isError: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
if (submitting) return;
|
||||
if (!reason.trim()) {
|
||||
setMessage({ text: 'Укажите обоснование заявки', isError: true });
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await onSubmitted(buildChangeRequestPayload({
|
||||
// Контракт: onSubmitted возвращает true при успехе (родитель
|
||||
// закрывает диалог) и false при ошибке — диалог остаётся
|
||||
// открытым и показывает ошибку отправки.
|
||||
const sent = await onSubmitted(buildChangeRequestPayload({
|
||||
classroomId,
|
||||
lesson,
|
||||
reason,
|
||||
@@ -85,6 +96,11 @@ export function RequestDialog({ lesson, onClose, onSubmitted }) {
|
||||
targetDate,
|
||||
timeSlotId
|
||||
}));
|
||||
if (sent === false) {
|
||||
setMessage({ text: SUBMIT_ERROR_MESSAGE, isError: true });
|
||||
}
|
||||
} catch {
|
||||
setMessage({ text: SUBMIT_ERROR_MESSAGE, isError: true });
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -210,15 +210,20 @@ function TeacherWorkspace({ teacherId }) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправка заявки из диалога. Контракт: true — успех (диалог закрывает
|
||||
* родитель и переключает вкладку), false — ошибка отправки, диалог
|
||||
* остаётся открытым и показывает ошибку пользователю.
|
||||
*/
|
||||
async function handleSubmitRequest(payload) {
|
||||
try {
|
||||
await createChangeRequest(payload);
|
||||
setDialogLesson(null);
|
||||
await refreshRequests();
|
||||
switchTab('requests');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
setDialogLesson(null);
|
||||
await refreshRequests();
|
||||
switchTab('requests');
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -146,6 +146,23 @@ export function resolveCurrentSemester(semesters, todayIso) {
|
||||
return (semesters || []).find(semester => semester.startDate <= todayIso && semester.endDate >= todayIso) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Семестр по умолчанию для пожеланий: текущий; между семестрами
|
||||
* (каникулы) — ближайший будущий; если все завершены — последний
|
||||
* завершившийся. Возвращает null только при пустом справочнике.
|
||||
*/
|
||||
export function resolveDefaultSemester(semesters, todayIso) {
|
||||
const sorted = [...(semesters || [])].sort((left, right) => (
|
||||
left.startDate === right.startDate ? 0 : left.startDate < right.startDate ? -1 : 1
|
||||
));
|
||||
const current = sorted.find(semester => semester.startDate <= todayIso && semester.endDate >= todayIso);
|
||||
if (current) return current;
|
||||
const upcoming = sorted.find(semester => semester.startDate > todayIso);
|
||||
if (upcoming) return upcoming;
|
||||
const completed = sorted.filter(semester => semester.endDate < todayIso);
|
||||
return completed.length ? completed[completed.length - 1] : null;
|
||||
}
|
||||
|
||||
export function resolveSelectedSemester(semesters, semesterId) {
|
||||
return (semesters || []).find(semester => String(semester.id) === String(semesterId));
|
||||
}
|
||||
|
||||
@@ -753,6 +753,7 @@ body {
|
||||
.preference-date-mark.approved { background: #f43f5e; }
|
||||
.preference-status { color: var(--muted); font-size: 11px; font-weight: 800; }
|
||||
.preference-empty { padding: 14px; color: var(--muted); text-align: center; font-size: 13px; }
|
||||
.preference-empty .btn { margin-top: 10px; }
|
||||
|
||||
.preference-toggle-card {
|
||||
display: grid;
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { clientWithSignal, requestJson } from '../react/shared/api-client.js';
|
||||
import { createLatestRequest } from '../react/shared/latest-request.js';
|
||||
import { resolveDefaultSemester } from '../react/teacher/teacher-service.js';
|
||||
|
||||
test('latest-request: новый запрос делает предыдущий неактуальным и прерывает его', () => {
|
||||
const guard = createLatestRequest();
|
||||
|
||||
const first = guard.begin();
|
||||
assert.equal(first.id, 1);
|
||||
assert.ok(first.signal, 'begin возвращает AbortSignal для передачи в apiClient');
|
||||
assert.equal(guard.isCurrent(first.id), true);
|
||||
|
||||
const second = guard.begin();
|
||||
assert.equal(second.id, 2);
|
||||
assert.equal(first.signal.aborted, true, 'предыдущий запрос прерывается');
|
||||
assert.equal(guard.isCurrent(first.id), false, 'устаревший ответ не применяется');
|
||||
assert.equal(guard.isCurrent(second.id), true);
|
||||
});
|
||||
|
||||
test('latest-request: ответы в обратном порядке не перезаписывают состояние', () => {
|
||||
const guard = createLatestRequest();
|
||||
const first = guard.begin();
|
||||
const second = guard.begin();
|
||||
|
||||
// Первый запрос завершился позже второго — его результат отбрасывается.
|
||||
const appliedFromStale = guard.isCurrent(first.id);
|
||||
const appliedFromFresh = guard.isCurrent(second.id);
|
||||
|
||||
assert.equal(appliedFromStale, false);
|
||||
assert.equal(appliedFromFresh, true);
|
||||
});
|
||||
|
||||
test('latest-request: dispose прерывает текущий запрос и инвалидирует его', () => {
|
||||
const guard = createLatestRequest();
|
||||
const request = guard.begin();
|
||||
|
||||
guard.dispose();
|
||||
|
||||
assert.equal(request.signal.aborted, true);
|
||||
assert.equal(guard.isCurrent(request.id), false, 'ответ после размонтирования не применяется');
|
||||
});
|
||||
|
||||
test('latest-request: повторный dispose и begin после dispose безопасны', () => {
|
||||
const guard = createLatestRequest();
|
||||
guard.dispose();
|
||||
guard.dispose();
|
||||
|
||||
const request = guard.begin();
|
||||
assert.equal(guard.isCurrent(request.id), true);
|
||||
});
|
||||
|
||||
test('clientWithSignal передаёт сигнал во все методы клиента', async () => {
|
||||
const calls = [];
|
||||
const client = {
|
||||
get: async (endpoint, options) => (calls.push({ method: 'get', endpoint, options }), []),
|
||||
post: async (endpoint, json, options) => (calls.push({ method: 'post', endpoint, options }), {}),
|
||||
put: async (endpoint, json, options) => (calls.push({ method: 'put', endpoint, options }), {}),
|
||||
delete: async (endpoint, options) => (calls.push({ method: 'delete', endpoint, options }), null)
|
||||
};
|
||||
const controller = new AbortController();
|
||||
const wrapped = clientWithSignal(client, controller.signal);
|
||||
|
||||
assert.notEqual(wrapped, client, 'с сигналом возвращается обёртка');
|
||||
await wrapped.get('/api/a', { errorMessage: 'Ошибка' });
|
||||
await wrapped.post('/api/b', {}, { errorMessage: 'Ошибка' });
|
||||
await wrapped.put('/api/c', {}, { errorMessage: 'Ошибка' });
|
||||
await wrapped.delete('/api/d', { errorMessage: 'Ошибка' });
|
||||
|
||||
for (const call of calls) {
|
||||
assert.equal(call.options.signal, controller.signal, `${call.method} передаёт сигнал`);
|
||||
assert.equal(call.options.errorMessage, 'Ошибка', `${call.method} сохраняет options`);
|
||||
}
|
||||
|
||||
assert.equal(clientWithSignal(client, undefined), client, 'без сигнала клиент не оборачивается');
|
||||
});
|
||||
|
||||
test('requestJson передаёт AbortSignal в fetch', async () => {
|
||||
const controller = new AbortController();
|
||||
let seenSignal = null;
|
||||
await requestJson('/api/example', { signal: controller.signal }, {
|
||||
fetchImpl: async (endpoint, options) => {
|
||||
seenSignal = options.signal;
|
||||
return new Response('[]', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
assert.equal(seenSignal, controller.signal);
|
||||
});
|
||||
|
||||
test('выбор семестра пожеланий: текущий семестр', () => {
|
||||
const semesters = [
|
||||
{ id: 1, startDate: '2026-02-09', endDate: '2026-06-30' },
|
||||
{ id: 2, startDate: '2026-09-01', endDate: '2027-01-31' }
|
||||
];
|
||||
|
||||
assert.equal(resolveDefaultSemester(semesters, '2026-10-11').id, 2);
|
||||
assert.equal(resolveDefaultSemester(semesters, '2026-03-01').id, 1);
|
||||
});
|
||||
|
||||
test('выбор семестра пожеланий: летние каникулы дают ближайший будущий семестр', () => {
|
||||
const semesters = [
|
||||
{ id: 1, startDate: '2026-02-09', endDate: '2026-06-30' },
|
||||
{ id: 2, startDate: '2026-09-01', endDate: '2027-01-31' },
|
||||
{ id: 3, startDate: '2027-02-08', endDate: '2027-06-30' }
|
||||
];
|
||||
|
||||
// Сегодня между семестрами: выбирается ближайший будущий, а не первый.
|
||||
assert.equal(resolveDefaultSemester(semesters, '2026-07-15').id, 2);
|
||||
assert.equal(resolveDefaultSemester(semesters, '2027-02-01').id, 3);
|
||||
});
|
||||
|
||||
test('выбор семестра пожеланий: после завершения всех — последний завершившийся', () => {
|
||||
const semesters = [
|
||||
{ id: 1, startDate: '2024-09-01', endDate: '2025-01-25' },
|
||||
{ id: 2, startDate: '2025-02-10', endDate: '2025-06-30' }
|
||||
];
|
||||
|
||||
assert.equal(resolveDefaultSemester(semesters, '2026-10-11').id, 2);
|
||||
});
|
||||
|
||||
test('выбор семестра пожеланий: пустой справочник возвращает null', () => {
|
||||
assert.equal(resolveDefaultSemester([], '2026-10-11'), null);
|
||||
assert.equal(resolveDefaultSemester(null, '2026-10-11'), null);
|
||||
});
|
||||
@@ -214,3 +214,20 @@ test('оболочка админки не содержит бургер-мен
|
||||
assert.match(index, /id="admin-root"/);
|
||||
assert.match(index, /\/react\/admin\.js/);
|
||||
});
|
||||
|
||||
test('отмена перехода с несохранёнными изменениями возвращает URL без новой записи history', async () => {
|
||||
const workspace = await readFrontendFile('react/admin/AdminApp.jsx');
|
||||
|
||||
// Отмена: hash возвращается к последнему подтверждённому разделу через
|
||||
// replaceState (без записи history и без повторного hashchange).
|
||||
assert.match(workspace, /confirmedHashRef/);
|
||||
assert.match(workspace, /restoreConfirmedHash/);
|
||||
assert.match(workspace, /history\.replaceState\(null, '', confirmed\)/);
|
||||
|
||||
// Параллельные переходы сериализуются: второй диалог не открывается.
|
||||
assert.match(workspace, /navigatingRef\.current\) return/);
|
||||
assert.match(workspace, /navigatingRef\.current = true/);
|
||||
|
||||
// Подписка на hashchange не пересоздаётся каждый render.
|
||||
assert.match(workspace, /removeEventListener\('hashchange', handleHashChange\);\s*\};\s*\}, \[role\]\)/);
|
||||
});
|
||||
@@ -66,3 +66,32 @@ test('контур версий подключён к SPA, а профильны
|
||||
assert.match(scheduleViewTab, /id="schedule-view-year"/);
|
||||
assert.match(quality, /versionId=.*encodeURIComponent\(versionId\)/);
|
||||
});
|
||||
|
||||
test('смена периода во время загрузки не подменяет результат устаревшим ответом', async () => {
|
||||
const [versionsTab, qualityTab, scheduleViewTab] = await Promise.all([
|
||||
readFile(new URL('../react/admin/tabs/ScheduleVersionsTab.jsx', import.meta.url), 'utf8'),
|
||||
readFile(new URL('../react/admin/tabs/ScheduleQualityTab.jsx', import.meta.url), 'utf8'),
|
||||
readFile(new URL('../react/admin/tabs/ScheduleViewTab.jsx', import.meta.url), 'utf8')
|
||||
]);
|
||||
|
||||
// Контур версий: новый выбор семестра запускает новый запрос, а не
|
||||
// отбрасывается занятостью предыдущего.
|
||||
assert.match(versionsTab, /useLatestRequest\(\)/);
|
||||
assert.match(versionsTab, /workspaceRequest\.begin\(\)/);
|
||||
assert.match(versionsTab, /workspaceRequest\.isCurrent\(request\.id\)/);
|
||||
assert.doesNotMatch(versionsTab, /latestRef\.current\.loading/, 'загрузка больше не отбрасывает новый запрос');
|
||||
|
||||
// Качество: смена периода инвалидирует анализ и очищает зависимые данные.
|
||||
assert.match(qualityTab, /useLatestRequest\(\)/);
|
||||
assert.match(qualityTab, /analysisRequest\.dispose\(\)/);
|
||||
assert.match(qualityTab, /setAnalysis\(null\)/);
|
||||
assert.match(qualityTab, /versionsRequest\.isCurrent\(request\.id\)/);
|
||||
assert.match(qualityTab, /analysisRequest\.isCurrent\(request\.id\)/);
|
||||
|
||||
// Просмотр расписания: повторное нажатие «Показать» отменяет предыдущий
|
||||
// запрос, кнопка блокируется на время загрузки.
|
||||
assert.match(scheduleViewTab, /scheduleRequest\.begin\(\)/);
|
||||
assert.match(scheduleViewTab, /scheduleRequest\.isCurrent\(request\.id\)/);
|
||||
assert.match(scheduleViewTab, /clientWithSignal\(apiClient, request\.signal\)/);
|
||||
assert.match(scheduleViewTab, /id="schedule-view-load"[\s\S]{0,200}disabled=\{loading\}/);
|
||||
});
|
||||
@@ -47,3 +47,43 @@ test('конструктор правил показывает только со
|
||||
assert.match(service, /Строгая недоступность/);
|
||||
assert.match(styles, /\.schedule-preference-hint/);
|
||||
});
|
||||
|
||||
test('пожелания преподавателя переживают каникулы и не отправляют semesterId=0', async () => {
|
||||
const [preferences, service] = await Promise.all([
|
||||
readFile(new URL('../react/teacher/PreferencesTab.jsx', import.meta.url), 'utf8'),
|
||||
readFile(new URL('../react/teacher/teacher-service.js', import.meta.url), 'utf8')
|
||||
]);
|
||||
|
||||
// Резервный выбор периода: текущий семестр, в каникулы — ближайший
|
||||
// будущий, после завершения всех — последний завершившийся.
|
||||
assert.match(service, /export function resolveDefaultSemester/);
|
||||
assert.match(preferences, /resolveDefaultSemester\(loaded\.semesters \|\| \[\], toIsoDate\(new Date\(\)\)\)/);
|
||||
|
||||
// Явный пустой пункт и запрет операций без валидного ID семестра.
|
||||
assert.match(preferences, /<option value="">Выберите семестр<\/option>/);
|
||||
assert.match(preferences, /semesterIdNumber > 0/);
|
||||
assert.match(preferences, /semesterId: semesterIdNumber/);
|
||||
assert.doesNotMatch(preferences, /semesterId: Number\(semesterId\)/, 'число из пустой строки (0) больше не уходит в API');
|
||||
assert.match(preferences, /disabled=\{!semesterSelected/);
|
||||
|
||||
// Ошибка метаданных: кнопка повтора вместо мёртвой сетки.
|
||||
assert.match(preferences, /Повторить/);
|
||||
assert.match(preferences, /setMetaAttempt\(attempt => attempt \+ 1\)/);
|
||||
});
|
||||
|
||||
test('диалог заявки преподавателя показывает ошибку отправки и не закрывается при неудаче', async () => {
|
||||
const [dialog, app] = await Promise.all([
|
||||
readFile(new URL('../react/teacher/RequestDialog.jsx', import.meta.url), 'utf8'),
|
||||
readFile(new URL('../react/teacher/TeacherApp.jsx', import.meta.url), 'utf8')
|
||||
]);
|
||||
|
||||
// Контракт: false — ошибка, диалог остаётся открытым с сообщением.
|
||||
assert.match(app, /return false;\s*\}\s*setDialogLesson\(null\)/);
|
||||
assert.match(dialog, /sent === false/);
|
||||
assert.match(dialog, /SUBMIT_ERROR_MESSAGE/);
|
||||
|
||||
// Повторная отправка блокируется, кандидаты защищены от гонки по дате.
|
||||
assert.match(dialog, /if \(submitting\) return/);
|
||||
assert.match(dialog, /useLatestRequest\(\)/);
|
||||
assert.match(dialog, /candidatesRequest\.isCurrent\(request\.id\)/);
|
||||
});
|
||||
Reference in new issue
Block a user