feat(frontend): redesign the candidate cabinet with step-by-step profile and questionnaire forms

This commit is contained in:
shira committed 2026-10-10 09:50:27 +03:00
1 parent 15590d127c
commit c836d02ea3
77 files changed
+5409 -1618

No files matched your search

@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import { useLocation, useParams } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import {
finalizeMyAssessmentAttempt,
@@ -20,11 +20,14 @@ import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
Card,
ErrorState,
ForbiddenState,
LoadingState,
Mono,
Notice,
Page,
Section,
Skeleton,
VisuallyHidden,
} from "../../../shared/ui";
import {
@@ -38,6 +41,7 @@ import {
parseAssessmentAttemptResponse,
removeAssessmentQueries,
removeAssessmentQueriesForSessionChange,
specializationLabels,
useAssessmentAttempt,
useAssessmentResult,
} from "../../../entities/assessment";
@@ -55,6 +59,8 @@ import {
useAssessmentSignals,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import { forgetExpressStart } from "../model/express-start";
import { AttemptFocusBar, type AnswerSaveState } from "./attempt-focus-bar";
import attemptStyles from "./assessment-attempt-page.module.css";
type PendingFinalize = { key: string; body: AssessmentFinalization };
@@ -69,7 +75,16 @@ function isTerminal(attempt: AssessmentAttempt): boolean {
function attemptName(attempt: AssessmentAttempt): string {
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск";
return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
return `${attempt.specialization ? specializationLabels[attempt.specialization] : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
}
function attemptTag(attempt: AssessmentAttempt): string {
if (attempt.kind === "demo_express") return "Демонстрация";
const parts = [
attempt.specialization ? specializationLabels[attempt.specialization] : "Проверка",
attempt.target_grade ? gradeLabels[attempt.target_grade] : null,
];
return parts.filter(Boolean).join(" · ");
}
function answerErrorMessage(error: unknown): string {
@@ -144,6 +159,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
const [answerBusy, setAnswerBusy] = useState(false);
const [answerError, setAnswerError] = useState<string | null>(null);
const [answerNeedsReview, setAnswerNeedsReview] = useState(false);
const [answerSaved, setAnswerSaved] = useState(false);
const location = useLocation();
const resumedExpress = Boolean(
(location.state as { expressResumed?: boolean } | null)?.expressResumed,
);
const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
const [finalizeBusy, setFinalizeBusy] = useState(false);
const [pageError, setPageError] = useState<string | null>(null);
@@ -198,6 +218,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
resultQuery.isError,
]);
// A finished or expired express run cannot be resumed; its start key goes.
const expressFinishedId =
attempt && attempt.kind === "demo_express" && isTerminal(attempt) ? attempt.id : null;
const actorId = actor?.account.id ?? null;
useEffect(() => {
if (expressFinishedId && actorId) forgetExpressStart(actorId, expressFinishedId);
}, [actorId, expressFinishedId]);
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
const key = getGetCurrentSessionQueryKey();
const captured = queryClient.getQueryData<Session>(key);
@@ -312,6 +340,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
setAnswerBusy(true);
setAnswerError(null);
setAnswerNeedsReview(false);
setAnswerSaved(false);
try {
const outcome = await submitPendingAnswerCommand(
command,
@@ -335,6 +364,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
setPendingAnswer(null);
setAnswerError(null);
setAnswerNeedsReview(false);
setAnswerSaved(true);
setWorkReady(true);
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
@@ -435,7 +465,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<ForbiddenState
error={session.error}
title="Попытка недоступна"
@@ -447,21 +477,21 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
}
if (session.isPending || !actor) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (!actorReady) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<LoadingState label="Подтверждаем текущий вход..." />
</Page>
);
}
if (!attemptId) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<ErrorState
error={new Error("The attempt identifier is missing.")}
title="Не удалось открыть попытку"
@@ -471,7 +501,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
}
if (attemptQuery.isPending && !attempt) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<LoadingState label="Загружаем сохраненную попытку..." />
</Page>
);
@@ -479,7 +509,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
if (attemptQuery.isError || !attempt) {
if (isAccessLoss(attemptQuery.error)) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<ForbiddenState
error={attemptQuery.error}
title="Попытка недоступна"
@@ -490,7 +520,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
);
}
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<Page title="Попытка проверки">
<ErrorState
error={attemptQuery.error}
isRetrying={attemptQuery.isRefetching}
@@ -516,10 +546,23 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
));
const terminal = isTerminal(attempt);
const saveState: AnswerSaveState = answerBusy
? "saving"
: pendingAnswer
? "unconfirmed"
: answerError
? "failed"
: answerSaved
? "saved"
: "idle";
const deadline = new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
}).format(new Date(attempt.expires_at));
return (
<Page
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
eyebrow="Кабинет кандидата"
lead={
attempt.kind === "demo_express"
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
@@ -528,67 +571,99 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
width="wide"
>
<div className={attemptStyles.layout}>
<Section
title={attemptName(attempt)}
description={`${methodLabel(attempt.mode)}. Сервер хранит состояние и результат попытки.`}
>
<div className={attemptStyles.meta}>
<span>
Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items}
</span>
<span>
Срок до:{" "}
{new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(
new Date(attempt.expires_at),
)}
</span>
{attempt.sessions ? (
<span>
Сеанс {attempt.sessions.used} из {attempt.sessions.max}
</span>
) : null}
</div>
<section className={attemptStyles.session} aria-labelledby="attempt-title">
<header className={attemptStyles["session-header"]}>
<h2 id="attempt-title" className={attemptStyles["session-title"]}>
{attemptName(attempt)}
</h2>
<p className={attemptStyles.meta}>
{methodLabel(attempt.mode) !== attemptName(attempt)
? `${methodLabel(attempt.mode)}. `
: ""}
Сервер хранит состояние и результат попытки. Срок до <Mono>{deadline}</Mono>
{attempt.sessions ? (
<>
, сеанс <Mono>{attempt.sessions.used}</Mono> из{" "}
<Mono>{attempt.sessions.max}</Mono>
</>
) : null}
.
</p>
</header>
{!terminal ? (
<AttemptFocusBar
label={attemptTag(attempt)}
answered={attempt.progress.answered_items}
total={attempt.progress.max_items}
expiresAt={attempt.expires_at}
saveState={saveState}
running={workReady}
/>
) : null}
{resumedExpress && attempt.kind === "demo_express" && !terminal ? (
<Notice tone="info" title="Незавершенная демонстрация продолжена">
<p>
Это тот же запуск: время идет с момента его начала, ответы сохранены на сервере.
</p>
</Notice>
) : null}
{pageError ? (
<p className={attemptStyles.error} role="alert">
{pageError}
</p>
<div role="alert">
<Notice tone="danger">
<p className={attemptStyles["notice-text"]}>{pageError}</p>
</Notice>
</div>
) : null}
{!workReady && !terminal ? (
<div className={attemptStyles.resume}>
<Card tone="raised" className={attemptStyles.resume}>
<p>
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
меняются, а ответ не отправляется повторно автоматически.
</p>
{signalNotice.checkError ? (
<p className={attemptStyles.error} role="alert">
{signalNotice.checkError}
</p>
<div role="alert">
<Notice tone="danger">
<p className={attemptStyles["notice-text"]}>{signalNotice.checkError}</p>
</Notice>
</div>
) : null}
<Button
isBusy={resumeBusy}
onClick={() =>
void (collectsSignals
? signalNotice.guard(() => void resumeWork())
: resumeWork())
}
>
{resumeBusy
? "Проверяем попытку..."
: pendingResume
? "Повторить продолжение"
: "Начать или продолжить"}
</Button>
</div>
<div className={attemptStyles.actions}>
<Button
isBusy={resumeBusy}
onClick={() =>
void (collectsSignals
? signalNotice.guard(() => void resumeWork())
: resumeWork())
}
>
{resumeBusy
? "Проверяем попытку..."
: pendingResume
? "Повторить продолжение"
: "Начать или продолжить"}
</Button>
</div>
</Card>
) : null}
{workReady && pendingAnswerNeedsReplay && !terminal ? (
<div className={attemptStyles.info} role="status">
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p>
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
</Button>
<div role="status">
<Notice
tone="neutral"
action={
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
</Button>
}
>
<p className={attemptStyles["notice-text"]}>
Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.
</p>
</Notice>
</div>
) : null}
@@ -598,10 +673,15 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
<div className={attemptStyles["item-heading"]}>
<h2 id="assessment-item-title">Задание {currentItem.sequence}</h2>
<span>
{currentItem.sequence} из {attempt.progress.max_items}
<h3 id="assessment-item-title">Задание {currentItem.sequence}</h3>
<span className={attemptStyles["item-counter"]} aria-hidden="true">
<Mono strong>{String(currentItem.sequence).padStart(2, "0")}</Mono>
<span>/</span>
<Mono>{String(attempt.progress.max_items).padStart(2, "0")}</Mono>
</span>
<VisuallyHidden>
{`${currentItem.sequence} из ${attempt.progress.max_items}`}
</VisuallyHidden>
</div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
<AnswerForm
@@ -623,10 +703,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
) : null}
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
<p className={attemptStyles.info} role="status">
Решение передано на проверку. Результат появится после ответа сервера; страница
обновляет статус автоматически.
</p>
<div role="status">
<Notice tone="info">
<p className={attemptStyles["notice-text"]}>
Решение передано на проверку. Результат появится после ответа сервера; страница
обновляет статус автоматически.
</p>
</Notice>
</div>
) : null}
{workReady &&
@@ -635,18 +719,20 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
canFinalize &&
!terminal &&
!pendingAnswerNeedsReplay ? (
<div className={attemptStyles.finalize}>
<Card tone="raised" className={attemptStyles.finalize}>
<p>
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
</p>
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
{finalizeBusy
? "Запрашиваем решение..."
: pendingFinalize
? "Повторить завершение"
: "Завершить проверку"}
</Button>
</div>
<div className={attemptStyles.actions}>
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
{finalizeBusy
? "Запрашиваем решение..."
: pendingFinalize
? "Повторить завершение"
: "Завершить проверку"}
</Button>
</div>
</Card>
) : null}
{workReady &&
@@ -655,20 +741,28 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
!canFinalize &&
!terminal &&
!pendingAnswerNeedsReplay ? (
<div className={attemptStyles.info} role="status">
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p>
<Button
variant="secondary"
isBusy={attemptQuery.isRefetching}
onClick={() => void attemptQuery.refetch()}
<div role="status">
<Notice
tone="neutral"
action={
<Button
variant="secondary"
isBusy={attemptQuery.isRefetching}
onClick={() => void attemptQuery.refetch()}
>
Обновить попытку
</Button>
}
>
Обновить попытку
</Button>
<p className={attemptStyles["notice-text"]}>
Сервер не вернул следующее задание. Обновите состояние попытки.
</p>
</Notice>
</div>
) : null}
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
</Section>
</section>
<div className={attemptStyles["back-link"]}>
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
К доступным проверкам
@@ -682,7 +776,12 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
if (resultQuery.isPending && !resultQuery.data) {
return <LoadingState label="Загружаем сохраненный результат..." />;
return (
<div className={attemptStyles.result}>
<LoadingState label="Загружаем сохраненный результат..." />
<Skeleton shape="card" lines={4} />
</div>
);
}
if (!resultQuery.data) {
return (