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