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
@@ -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();
|
||||
}}
|
||||
|
||||
Reference in new issue
Block a user