feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
export { AssessmentAttemptPage } from "./ui/assessment-attempt-page";
export { AssessmentPage } from "./ui/assessment-page";
@@ -0,0 +1,102 @@
.layout {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.resume,
.finalize,
.info,
.result,
.item {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.resume p,
.finalize p,
.info p,
.result p {
margin: 0;
}
.item {
gap: var(--space-4);
border-color: var(--color-border-strong);
}
.item-heading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: var(--space-2);
}
.item-heading h2,
.result h2 {
margin: 0;
font-size: var(--font-size-l);
}
.item-heading span {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.prompt {
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: var(--line-height-body);
}
.info {
color: var(--color-text-secondary);
}
.error {
margin: 0;
color: var(--color-danger);
}
.result {
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.demo-label {
font-weight: var(--font-weight-bold);
}
.result-error {
display: grid;
gap: var(--space-3);
}
.back-link {
display: flex;
flex-wrap: wrap;
}
@media (width < 42rem) {
.resume,
.finalize,
.info,
.result,
.item {
padding: var(--space-3);
}
}
@@ -0,0 +1,678 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import {
finalizeMyAssessmentAttempt,
startMyAssessmentAttemptSession,
} from "../../../shared/api/endpoints/assessment/assessment";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type {
AssessmentAttempt,
AssessmentFinalization,
Session,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
} from "../../../shared/ui";
import {
assessmentQueryKeys,
assessmentResultSummary,
assessmentSessionMatches,
gradeLabels,
isOutcomeAmbiguous,
isCurrentAssessmentSession,
methodLabel,
parseAssessmentAttemptResponse,
removeAssessmentQueries,
removeAssessmentQueriesForSessionChange,
useAssessmentAttempt,
useAssessmentResult,
} from "../../../entities/assessment";
import {
AnswerForm,
buildAnswerSubmission,
newIdempotencyKey,
submitPendingAnswerCommand,
} from "../../../features/answer-assessment";
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
import attemptStyles from "./assessment-attempt-page.module.css";
type PendingFinalize = { key: string; body: AssessmentFinalization };
function isAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
}
function isTerminal(attempt: AssessmentAttempt): boolean {
return ["completed", "expired", "insufficient_bank"].includes(attempt.state);
}
function attemptName(attempt: AssessmentAttempt): string {
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск";
return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
}
function answerErrorMessage(error: unknown): string {
if (error instanceof ApiRequestError && error.status === 0) {
return "Не удалось связаться с сервером. Повторите отправку того же ответа.";
}
if (error instanceof ApiRequestError && error.status >= 500) {
return "Сервер не подтвердил ответ. Повторите отправку того же ответа.";
}
if (error instanceof ApiRequestError && error.status === 429) {
return error.retryAfterSeconds
? `Слишком много запросов. Повторите через ${error.retryAfterSeconds} сек.`
: "Слишком много запросов. Повторите позже.";
}
if (error instanceof ApiRequestError && error.status === 412) {
return "Попытка изменилась в другом окне. Проверьте актуальное задание и отправьте ответ еще раз.";
}
if (error instanceof ApiRequestError && error.status === 400) {
return "Сервер не принял этот формат ответа. Проверьте введенные данные.";
}
return "Не удалось отправить ответ. Проверьте соединение и повторите попытку.";
}
export function AssessmentAttemptPage() {
const { attemptId = "" } = useParams();
return <AssessmentAttemptContent key={attemptId} attemptId={attemptId} />;
}
function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const actorReady = Boolean(
actor &&
actor.account.scenario === "candidate" &&
isCurrentAssessmentSession(queryClient, actor),
);
const attemptQuery = useAssessmentAttempt({ actor, attemptId, enabled: actorReady, queryClient });
const attempt = attemptQuery.data;
const resultQuery = useAssessmentResult({
actor,
attemptId,
enabled: actorReady && Boolean(attempt && isTerminal(attempt)),
queryClient,
});
const [workReady, setWorkReady] = useState(false);
const [resumeBusy, setResumeBusy] = useState(false);
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
const [answerBusy, setAnswerBusy] = useState(false);
const [answerError, setAnswerError] = useState<string | null>(null);
const [answerNeedsReview, setAnswerNeedsReview] = useState(false);
const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
const [finalizeBusy, setFinalizeBusy] = useState(false);
const [pageError, setPageError] = useState<string | null>(null);
const [accessDenied, setAccessDenied] = useState(false);
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
const requestInFlight = useRef(false);
useEffect(() => {
const next =
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
const previous = previousActor.current;
if (previous && (!next || previous.accountId !== next.accountId)) {
removeAssessmentQueriesForSessionChange(queryClient);
setPendingResume(null);
setPendingAnswer(null);
setPendingFinalize(null);
setWorkReady(false);
setPageError(null);
setAnswerError(null);
setAccessDenied(false);
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
removeAssessmentQueriesForSessionChange(queryClient);
setWorkReady(false);
setPageError("Проверка входа обновлена. Продолжите попытку еще раз.");
}
previousActor.current = next;
}, [actor, actorReady, queryClient]);
useEffect(() => {
if (attemptQuery.isError && isAccessLoss(attemptQuery.error)) {
removeAssessmentQueries(queryClient);
queueMicrotask(() => {
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
setAccessDenied(true);
setWorkReady(false);
});
}
if (resultQuery.isError && isAccessLoss(resultQuery.error)) {
removeAssessmentQueries(queryClient);
queueMicrotask(() => {
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
setAccessDenied(true);
setWorkReady(false);
});
}
}, [
actor,
attemptQuery.error,
attemptQuery.isError,
queryClient,
resultQuery.error,
resultQuery.isError,
]);
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
const key = getGetCurrentSessionQueryKey();
const captured = queryClient.getQueryData<Session>(key);
if (!assessmentSessionMatches(queryClient.getQueryState<Session>(key), currentActor))
return false;
const refreshed = await session.refetch();
const latest = queryClient.getQueryData<Session>(key);
const state = queryClient.getQueryState<Session>(key);
if (
!captured ||
refreshed.isError ||
!refreshed.data ||
state?.status !== "success" ||
latest?.account.id !== currentActor.account.id ||
latest.csrf_token !== refreshed.data.csrf_token
) {
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
}
return false;
}
if (captured.csrf_token !== currentActor.csrf_token) return false;
setAnswerError("Проверка входа обновлена. Черновик сохранен, повторите отправку.");
return true;
}
async function resumeWork() {
if (
!actor ||
!attempt ||
!isCurrentAssessmentSession(queryClient, actor) ||
requestInFlight.current
)
return;
const command = pendingResume ?? { key: newIdempotencyKey(), version: attempt.version };
if (!pendingResume) setPendingResume(command);
requestInFlight.current = true;
setResumeBusy(true);
setPageError(null);
try {
const resumedResponse = await startMyAssessmentAttemptSession(
attempt.id,
{ expected_version: command.version },
{ "Idempotency-Key": command.key },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const resumed = parseAssessmentAttemptResponse(resumedResponse);
if (!isCurrentAssessmentSession(queryClient, actor)) return;
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), resumed);
setPendingResume(null);
setWorkReady(true);
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, actor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
await refreshSessionForActor(actor);
} else if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
} else if (isOutcomeAmbiguous(error)) {
setPageError("Не удалось подтвердить продолжение. Повторите запрос с тем же ключом.");
} else {
setPendingResume(null);
setPageError("Не удалось продолжить попытку. Обновите состояние и повторите действие.");
await attemptQuery.refetch();
}
} finally {
requestInFlight.current = false;
setResumeBusy(false);
}
}
async function refetchAttempt(): Promise<AssessmentAttempt | null> {
const refreshed = await attemptQuery.refetch();
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || refreshed.isError) return null;
return refreshed.data ?? null;
}
async function sendAnswer(draft: AnswerDraft) {
if (!actor || !attempt || !attempt.current_item || !workReady || requestInFlight.current)
return;
const built = buildAnswerSubmission(attempt, attempt.current_item, draft);
if (!built.ok) {
setAnswerError(built.message);
return;
}
const command: PendingAnswerCommand = {
key: newIdempotencyKey(),
body: built.body,
itemId: attempt.current_item.id,
};
await sendPendingAnswer(command, actor, attempt.id);
}
async function retryAnswer() {
if (!actor || !attempt || !pendingAnswer || requestInFlight.current) return;
await sendPendingAnswer(pendingAnswer, actor, attempt.id);
}
async function sendPendingAnswer(
command: PendingAnswerCommand,
currentActor: Session,
currentAttemptId: string,
) {
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
setPendingAnswer(command);
requestInFlight.current = true;
setAnswerBusy(true);
setAnswerError(null);
setAnswerNeedsReview(false);
try {
const outcome = await submitPendingAnswerCommand(
command,
currentAttemptId,
currentActor.csrf_token,
);
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
if (outcome.kind === "retry") {
setPendingAnswer(outcome.command);
setAnswerError(answerErrorMessage(outcome.error));
return;
}
if (outcome.kind === "rejected") throw outcome.error;
const saved = outcome.attempt;
const key = assessmentQueryKeys.attempt(currentActor, currentAttemptId);
queryClient.setQueryData<AssessmentAttempt>(key, (current) =>
current && current.version > saved.version ? current : saved,
);
void queryClient.invalidateQueries({ queryKey: key });
setPendingAnswer(null);
setAnswerError(null);
setAnswerNeedsReview(false);
setWorkReady(true);
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
await refreshSessionForActor(currentActor);
return;
}
if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setPendingAnswer(null);
setAccessDenied(true);
setWorkReady(false);
return;
}
if (isOutcomeAmbiguous(error)) {
setAnswerError(answerErrorMessage(error));
return;
}
setPendingAnswer(null);
setAnswerError(answerErrorMessage(error));
if (error instanceof ApiRequestError && error.status === 412) {
const latest = await refetchAttempt();
setAnswerNeedsReview(Boolean(latest?.current_item?.id === command.itemId));
if (latest?.current_item?.id !== command.itemId) {
setAnswerError("Попытка изменилась в другом окне. Показано текущее задание с сервера.");
}
} else if (error instanceof ApiRequestError && error.status === 409) {
const latest = await refetchAttempt();
if (latest) {
queryClient.setQueryData(
assessmentQueryKeys.attempt(currentActor, currentAttemptId),
latest,
);
}
setWorkReady(false);
setPageError(
"Сеанс работы завершился или состояние попытки изменилось. Продолжите попытку заново.",
);
}
} finally {
requestInFlight.current = false;
setAnswerBusy(false);
}
}
async function finalizeAttempt() {
if (!actor || !attempt || !workReady || requestInFlight.current) return;
const body: AssessmentFinalization = { expected_version: attempt.version };
const command = pendingFinalize ?? { key: newIdempotencyKey(), body };
if (!pendingFinalize) setPendingFinalize(command);
requestInFlight.current = true;
setFinalizeBusy(true);
setPageError(null);
try {
const finalizedResponse = await finalizeMyAssessmentAttempt(
attempt.id,
command.body,
{ "Idempotency-Key": command.key },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const finalized = parseAssessmentAttemptResponse(finalizedResponse);
if (!isCurrentAssessmentSession(queryClient, actor)) return;
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), finalized);
setPendingFinalize(null);
await queryClient.invalidateQueries({
queryKey: assessmentQueryKeys.result(actor, attempt.id),
});
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, actor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
await refreshSessionForActor(actor);
} else if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
setWorkReady(false);
} else if (isOutcomeAmbiguous(error)) {
setPageError("Сервер не подтвердил завершение. Повторите запрос с тем же ключом.");
} else {
setPendingFinalize(null);
setPageError("Сервер пока не завершил попытку. Обновите состояние и повторите действие.");
const latest = await refetchAttempt();
if (latest)
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), latest);
}
} finally {
requestInFlight.current = false;
setFinalizeBusy(false);
}
}
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ForbiddenState
error={session.error}
title="Попытка недоступна"
description="Сервер не подтвердил доступ к этой попытке. Проверьте вход в кабинет кандидата."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
</Page>
);
}
if (session.isPending || !actor) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (!actorReady) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<LoadingState label="Подтверждаем текущий вход..." />
</Page>
);
}
if (!attemptId) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ErrorState
error={new Error("The attempt identifier is missing.")}
title="Не удалось открыть попытку"
/>
</Page>
);
}
if (attemptQuery.isPending && !attempt) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<LoadingState label="Загружаем сохраненную попытку..." />
</Page>
);
}
if (attemptQuery.isError || !attempt) {
if (isAccessLoss(attemptQuery.error)) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ForbiddenState
error={attemptQuery.error}
title="Попытка недоступна"
description="Сервер не подтвердил доступ к этой попытке."
action={<ButtonLink to={paths.candidate.assessment}>К списку проверок</ButtonLink>}
/>
</Page>
);
}
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ErrorState
error={attemptQuery.error}
isRetrying={attemptQuery.isRefetching}
onRetry={() => void attemptQuery.refetch()}
title="Не удалось загрузить попытку"
/>
</Page>
);
}
const currentItem = attempt.current_item;
const practicePending = attempt.practices.some((practice) => practice.status === "pending");
const pendingAnswerNeedsReplay = Boolean(
pendingAnswer && pendingAnswer.itemId !== currentItem?.id,
);
const canFinalize =
attempt.state === "ready_to_finalize" ||
(attempt.state === "additional_practice_pending" &&
!currentItem &&
attempt.practices.some(
(practice) =>
practice.kind === "additional" && ["not_started", "failed"].includes(practice.status),
));
const terminal = isTerminal(attempt);
return (
<Page
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
eyebrow="Кабинет кандидата"
lead={
attempt.kind === "demo_express"
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
: undefined
}
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>
{pageError ? (
<p className={attemptStyles.error} role="alert">
{pageError}
</p>
) : null}
{!workReady && !terminal ? (
<div className={attemptStyles.resume}>
<p>
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
меняются, а ответ не отправляется повторно автоматически.
</p>
<Button isBusy={resumeBusy} onClick={() => void resumeWork()}>
{resumeBusy
? "Проверяем попытку..."
: pendingResume
? "Повторить продолжение"
: "Начать или продолжить"}
</Button>
</div>
) : null}
{workReady && pendingAnswerNeedsReplay && !terminal ? (
<div className={attemptStyles.info} role="status">
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p>
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
</Button>
</div>
) : null}
{workReady &&
currentItem &&
!terminal &&
(!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}
</span>
</div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
<AnswerForm
key={currentItem.id}
item={currentItem}
isSaving={answerBusy}
retryable={Boolean(pendingAnswer && pendingAnswer.itemId === currentItem.id)}
errorMessage={answerError}
onSubmit={(draft) => void sendAnswer(draft)}
onRetry={() => void retryAnswer()}
/>
{answerNeedsReview ? (
<p className={attemptStyles.info} role="status">
Черновик остался в форме. Проверьте его и отправьте для актуальной версии попытки.
</p>
) : null}
</article>
) : null}
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
<p className={attemptStyles.info} role="status">
Решение передано на проверку. Результат появится после ответа сервера; страница
обновляет статус автоматически.
</p>
) : null}
{workReady &&
!currentItem &&
!practicePending &&
canFinalize &&
!terminal &&
!pendingAnswerNeedsReplay ? (
<div className={attemptStyles.finalize}>
<p>
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
</p>
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
{finalizeBusy
? "Запрашиваем решение..."
: pendingFinalize
? "Повторить завершение"
: "Завершить проверку"}
</Button>
</div>
) : null}
{workReady &&
!currentItem &&
!practicePending &&
!canFinalize &&
!terminal &&
!pendingAnswerNeedsReplay ? (
<div className={attemptStyles.info} role="status">
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p>
<Button
variant="secondary"
isBusy={attemptQuery.isRefetching}
onClick={() => void attemptQuery.refetch()}
>
Обновить попытку
</Button>
</div>
) : null}
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
</Section>
<div className={attemptStyles["back-link"]}>
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
К доступным проверкам
</ButtonLink>
</div>
</div>
</Page>
);
}
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
if (resultQuery.isPending && !resultQuery.data) {
return <LoadingState label="Загружаем сохраненный результат..." />;
}
if (resultQuery.isError || !resultQuery.data) {
return (
<div className={attemptStyles["result-error"]}>
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
<p role="status">Сервер еще завершает обработку результата. Повторите проверку позже.</p>
) : (
<ErrorState
error={resultQuery.error}
isRetrying={resultQuery.isRefetching}
onRetry={() => void resultQuery.refetch()}
title="Не удалось загрузить результат"
/>
)}
<Button
variant="secondary"
isBusy={resultQuery.isRefetching}
onClick={() => void resultQuery.refetch()}
>
Обновить результат
</Button>
</div>
);
}
const result = resultQuery.data;
const summary = assessmentResultSummary(result);
return (
<div className={attemptStyles.result} role="status" aria-live="polite">
<h2>Результат с сервера</h2>
<p>{summary.text}</p>
{summary.reason ? <p>{summary.reason}</p> : null}
{summary.isDemonstration ? (
<p className={attemptStyles["demo-label"]}>
Только демонстрация. Подтвержденный грейд не присваивается.
</p>
) : null}
</div>
);
}
@@ -0,0 +1,49 @@
import type {
AssessmentAttemptCreate,
GradeCode,
SpecializationCode,
TaskLanguage,
} from "../../../shared/api/schemas";
import { createMyAssessmentAttempt } from "../../../shared/api/endpoints/assessment/assessment";
import { parseAssessmentAttemptResponse } from "../../../entities/assessment";
export type PendingCreate = { key: string; body: AssessmentAttemptCreate };
export function buildRootAttemptCreate(
specialization: SpecializationCode,
grade: GradeCode,
savedLanguages: readonly TaskLanguage[],
selectedLanguage: TaskLanguage | "",
): AssessmentAttemptCreate | null {
let taskLanguage: TaskLanguage | null = null;
if (savedLanguages.length === 1) {
taskLanguage = savedLanguages[0] ?? null;
} else if (savedLanguages.length > 1) {
if (!selectedLanguage || !savedLanguages.includes(selectedLanguage)) return null;
taskLanguage = selectedLanguage;
}
return {
kind: "root",
specialization,
target_grade: grade,
task_language: taskLanguage,
};
}
export function preservePendingCreate(
pending: PendingCreate | null,
body: AssessmentAttemptCreate | null,
keyFactory: () => string,
): PendingCreate | null {
return pending ?? (body ? { key: keyFactory(), body } : null);
}
export function submitPendingAttempt(command: PendingCreate, csrfToken: string) {
return createMyAssessmentAttempt(
command.body,
{ "Idempotency-Key": command.key },
{ headers: { "X-CSRF-Token": csrfToken } },
).then((response) => parseAssessmentAttemptResponse(response, 201));
}
@@ -0,0 +1,141 @@
.layout {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.controls {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3);
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
font-weight: var(--font-weight-bold);
}
.field select {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.field select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.language-note,
.language-availability {
margin: 0;
color: var(--color-text-secondary);
}
.language-note {
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-divider);
}
.language-availability {
max-width: 72ch;
font-size: var(--font-size-s);
}
.availability,
.express,
.notice {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.availability p,
.express p,
.notice p {
margin: 0;
}
.status-row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: var(--space-2);
}
.status-row [data-state="available"] {
font-weight: var(--font-weight-bold);
}
.limits {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3);
margin: 0;
}
.limits div {
min-width: 0;
padding: var(--space-3);
background: var(--color-canvas);
border-radius: var(--radius-s);
}
.limits dt {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.limits dd {
margin: var(--space-1) 0 0;
font-weight: var(--font-weight-bold);
overflow-wrap: anywhere;
}
.notice {
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.notice h3 {
margin: 0;
font-size: var(--font-size-m);
}
.notice p,
.express p,
.pending {
color: var(--color-text-secondary);
}
.pending {
margin: 0;
}
.error {
margin: 0;
color: var(--color-danger);
}
@media (width < 42rem) {
.controls,
.limits {
grid-template-columns: minmax(0, 1fr);
}
.availability,
.express,
.notice {
padding: var(--space-3);
}
}
@@ -0,0 +1,190 @@
import { renderToStaticMarkup } from "react-dom/server";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { http, HttpResponse } from "msw";
import { AssessmentPolicyParameters, TaskLanguageControl } from "./assessment-page";
import {
buildRootAttemptCreate,
preservePendingCreate,
submitPendingAttempt,
} from "./assessment-page.model";
const server = setupServer();
beforeAll(() => server.listen());
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
describe("assessment task language selection", () => {
it("sends null when the saved questionnaire has no language", () => {
expect(buildRootAttemptCreate("backend", "junior", [], "")).toEqual({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: null,
});
});
it("uses the only saved language without an ambiguous default", () => {
expect(buildRootAttemptCreate("backend", "junior", ["python"], "")).toEqual({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "python",
});
});
it("requires an explicit choice when the questionnaire has multiple languages", () => {
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "")).toBeNull();
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "go")).toEqual({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
});
});
it("keeps the selected second language and idempotency key on an exact retry", () => {
const body = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
expect(body).not.toBeNull();
const keyFactory = vi.fn(() => "original-key");
const pending = preservePendingCreate(null, body, keyFactory);
const retryBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "python");
const retried = preservePendingCreate(pending, retryBody, () => "new-key");
expect(pending?.body).toMatchObject({ kind: "root", task_language: "go" });
expect(retried).toBe(pending);
expect(retried?.key).toBe("original-key");
expect(retried?.body).toEqual(body);
expect(keyFactory).toHaveBeenCalledOnce();
});
it("posts the selected second language and replays the same request after an ambiguous response", async () => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const requests: Array<{ body: unknown; key: string | null; csrf: string | null }> = [];
server.use(
http.post("http://localhost/api/v1/me/assessment-attempts", async ({ request }) => {
requests.push({
body: await request.json(),
key: request.headers.get("Idempotency-Key"),
csrf: request.headers.get("X-CSRF-Token"),
});
return HttpResponse.json(
{
type: "urn:lincodex:problem:internal",
title: "Internal error",
status: 500,
code: "internal",
},
{ status: 500, headers: { "Content-Type": "application/problem+json" } },
);
}),
);
const keyFactory = vi.fn(() => "retry-key");
const firstBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
const pending = preservePendingCreate(null, firstBody, keyFactory);
expect(pending).not.toBeNull();
await expect(submitPendingAttempt(pending!, "csrf-token")).rejects.toMatchObject({
status: 500,
});
const changedSelection = buildRootAttemptCreate(
"backend",
"junior",
["python", "go"],
"python",
);
const retry = preservePendingCreate(pending, changedSelection, keyFactory);
await expect(submitPendingAttempt(retry!, "csrf-token")).rejects.toMatchObject({
status: 500,
});
expect(requests).toEqual([
{
body: {
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
},
key: "retry-key",
csrf: "csrf-token",
},
{
body: {
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
},
key: "retry-key",
csrf: "csrf-token",
},
]);
expect(retry).toBe(pending);
expect(keyFactory).toHaveBeenCalledOnce();
});
});
describe("TaskLanguageControl", () => {
it("shows the single saved language without requiring another choice", () => {
const html = renderToStaticMarkup(
<TaskLanguageControl languages={["go"]} value="" disabled={false} onChange={() => {}} />,
);
expect(html).toContain("Язык задания из анкеты:");
expect(html).toContain("Go");
expect(html).not.toContain("<select");
});
it("requires a visible choice when both languages are saved", () => {
const html = renderToStaticMarkup(
<TaskLanguageControl
languages={["python", "go"]}
value="go"
disabled={false}
onChange={() => {}}
/>,
);
expect(html).toContain("Язык задания");
expect(html).toContain('value="python"');
expect(html).toContain('value="go" selected');
});
});
describe("AssessmentPolicyParameters", () => {
const grade = {
grade: "junior",
status: "active_attempt",
mode: "adaptive",
available_at: null,
time_limit_seconds: 900,
max_sessions: 1,
max_items: 12,
practice_required: true,
} as const;
it("does not present today's policy limits as settings for a pinned attempt", () => {
const html = renderToStaticMarkup(<AssessmentPolicyParameters grade={grade} />);
expect(html).toBe("");
});
it("shows current policy parameters before a new attempt", () => {
const html = renderToStaticMarkup(
<AssessmentPolicyParameters grade={{ ...grade, status: "available" }} />,
);
expect(html).toContain("Метод:");
expect(html).toContain("Лимит времени");
expect(html).toContain("Заданий");
});
});
@@ -0,0 +1,568 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
import type {
AssessmentAttemptCreate,
AssessmentGradeAvailability,
GradeCode,
Session,
SpecializationCode,
TaskLanguage,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
} from "../../../shared/ui";
import {
assessmentSessionMatches,
gradeLabels,
isOutcomeAmbiguous,
isCurrentAssessmentSession,
methodLabel,
removeAssessmentQueries,
removeAssessmentQueriesForSessionChange,
selectedSpecialization,
specializationLabels,
useAssessmentAvailability,
useAssessmentQuestionnaire,
} from "../../../entities/assessment";
import { newIdempotencyKey } from "../../../features/answer-assessment";
import {
buildRootAttemptCreate,
preservePendingCreate,
submitPendingAttempt,
type PendingCreate,
} from "./assessment-page.model";
import styles from "./assessment-page.module.css";
function isAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
}
function requiresC3(error: ApiRequestError): boolean {
return (
error.code === "state_conflict" &&
error.fieldErrors.some((field) => field.code === "consent_required")
);
}
function gradeStatusDescription(grade: AssessmentGradeAvailability): string {
switch (grade.status) {
case "available":
return "Уровень открыт для начала. Список доступности не разделяет варианты по языку; сервер проверит задания выбранного языка при создании попытки.";
case "active_attempt":
return "Продолжите сохраненную попытку по ссылке ниже. Ее язык и параметры закреплены и отображаются внутри попытки.";
case "cooldown":
return grade.available_at
? `Следующая попытка будет доступна ${formatDate(grade.available_at)}.`
: "Следующая попытка пока недоступна.";
case "insufficient_bank":
return "Набор заданий пока не подготовлен. Система не будет повторять уже пройденные задания.";
}
}
function formatDate(value: string): string {
return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
}).format(new Date(value));
}
function formatTimeLimit(seconds: number | null): string {
if (seconds === null) return "не задано";
const minutes = Math.ceil(seconds / 60);
return `${minutes} мин.`;
}
function taskLanguageLabel(language: TaskLanguage): string {
return language === "go" ? "Go" : "Python";
}
export function TaskLanguageControl({
languages,
value,
disabled,
onChange,
}: {
languages: readonly TaskLanguage[];
value: TaskLanguage | "";
disabled: boolean;
onChange: (language: TaskLanguage | "") => void;
}) {
if (languages.length === 0) {
return (
<p className={styles["language-note"]}>
В сохраненной анкете нет выбранного языка. Попытка отправится без языка, а сервер проверит
доступность заданий при создании.
</p>
);
}
if (languages.length === 1) {
return (
<p className={styles["language-note"]}>
Язык задания из анкеты: <strong>{taskLanguageLabel(languages[0]!)}</strong>.
</p>
);
}
return (
<label className={styles.field}>
<span>Язык задания</span>
<select
value={value}
disabled={disabled}
onChange={(event) => onChange(event.currentTarget.value as TaskLanguage | "")}
>
<option value="">Выберите язык</option>
{languages.map((language) => (
<option key={language} value={language}>
{taskLanguageLabel(language)}
</option>
))}
</select>
</label>
);
}
export function AssessmentPolicyParameters({ grade }: { grade: AssessmentGradeAvailability }) {
if (grade.status === "active_attempt") return null;
return (
<>
{grade.mode ? <p>Метод: {methodLabel(grade.mode)}.</p> : null}
<dl className={styles.limits}>
<div>
<dt>Лимит времени</dt>
<dd>{formatTimeLimit(grade.time_limit_seconds)}</dd>
</div>
<div>
<dt>Попыток работы</dt>
<dd>{grade.max_sessions ?? "не задано"}</dd>
</div>
<div>
<dt>Заданий</dt>
<dd>{grade.max_items ?? "не задано"}</dd>
</div>
<div>
<dt>Практика кода</dt>
<dd>
{grade.practice_required === null
? "не задано"
: grade.practice_required
? "включена"
: "не требуется"}
</dd>
</div>
</dl>
</>
);
}
function AssessmentSignalsNotice() {
return (
<aside className={styles.notice} aria-labelledby="assessment-signals-title">
<h3 id="assessment-signals-title">Какие данные фиксируются во время проверки</h3>
<p>
Сохраняются время ответов и технические события: смена вкладки, выход из полноэкранного
режима и размер операций копирования или вставки. Содержимое ответов и буфера не
отправляется как сигнал. Камера, микрофон и запись экрана не используются.
</p>
<p>Сигналы помогают назначить ручную перепроверку и сами по себе не меняют результат.</p>
</aside>
);
}
export function AssessmentPage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const actorReady = Boolean(
actor &&
actor.account.scenario === "candidate" &&
isCurrentAssessmentSession(queryClient, actor),
);
const availability = useAssessmentAvailability({ actor, enabled: actorReady, queryClient });
const questionnaire = useAssessmentQuestionnaire({ actor, enabled: actorReady, queryClient });
const [selection, setSelection] = useState<{
specialization: SpecializationCode | "";
grade: GradeCode | "";
}>({ specialization: "", grade: "" });
const [selectedTaskLanguage, setSelectedTaskLanguage] = useState<TaskLanguage | "">("");
const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
const [createBusy, setCreateBusy] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [c3Required, setC3Required] = useState(false);
const [accessDenied, setAccessDenied] = useState(false);
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
const requestInFlight = useRef(false);
useEffect(() => {
const next =
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
const previous = previousActor.current;
if (previous && (!next || previous.accountId !== next.accountId)) {
removeAssessmentQueriesForSessionChange(queryClient);
setPendingCreate(null);
setSelectedTaskLanguage("");
setFormError(null);
setC3Required(false);
setAccessDenied(false);
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
removeAssessmentQueriesForSessionChange(queryClient);
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
}
previousActor.current = next;
}, [actor, actorReady, queryClient]);
useEffect(() => {
if (
(availability.isError && isAccessLoss(availability.error)) ||
(questionnaire.isError && isAccessLoss(questionnaire.error))
) {
removeAssessmentQueries(queryClient);
queueMicrotask(() => {
if (isCurrentAssessmentSession(queryClient, actor)) setAccessDenied(true);
});
}
}, [
actor,
availability.error,
availability.isError,
queryClient,
questionnaire.error,
questionnaire.isError,
]);
const data = availability.data;
const firstSpecialization = data?.specializations[0]?.specialization ?? "";
const selectedCode = data?.specializations.some(
(item) => item.specialization === selection.specialization,
)
? selection.specialization
: firstSpecialization;
const specialization = data ? selectedSpecialization(data, selectedCode || undefined) : undefined;
const questionnaireSpecialization = questionnaire.data?.specializations.find(
(item) => item.specialization === selectedCode,
);
const selfGrade = questionnaireSpecialization?.self_assessed_grade ?? "";
const firstAvailableGrade =
specialization?.grades.find((grade) => grade.status === "available")?.grade ?? "";
const selectedGradeCode = specialization?.grades.some((grade) => grade.grade === selection.grade)
? selection.grade
: selfGrade || firstAvailableGrade || specialization?.grades[0]?.grade || "";
const grade = specialization?.grades.find((item) => item.grade === selectedGradeCode);
const activeAttemptId = specialization?.active_attempt_id;
const savedTaskLanguages = questionnaireSpecialization?.task_languages ?? [];
const selectedLanguageIsValid = savedTaskLanguages.includes(selectedTaskLanguage as TaskLanguage);
const taskLanguageReady = savedTaskLanguages.length < 2 || selectedLanguageIsValid;
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
const captured = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
if (
!assessmentSessionMatches(
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
currentActor,
)
) {
return false;
}
const refreshed = await session.refetch();
const latest = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const queryState = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
if (
!captured ||
refreshed.isError ||
!refreshed.data ||
!latest ||
latest.account.id !== currentActor.account.id ||
latest.csrf_token !== refreshed.data.csrf_token ||
queryState?.status !== "success"
) {
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
}
return false;
}
if (captured.csrf_token !== currentActor.csrf_token) return false;
return true;
}
async function startAttempt(body?: AssessmentAttemptCreate) {
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current)
return;
const command = preservePendingCreate(pendingCreate, body ?? null, newIdempotencyKey);
if (!command) return;
if (!pendingCreate) setPendingCreate(command);
requestInFlight.current = true;
setCreateBusy(true);
setFormError(null);
setC3Required(false);
try {
const created = await submitPendingAttempt(command, actor.csrf_token);
if (!isCurrentAssessmentSession(queryClient, actor)) return;
setPendingCreate(null);
navigate(paths.candidate.assessmentAttempt(created.id));
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, actor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
const refreshed = await refreshSessionForActor(actor);
if (refreshed) {
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
}
return;
}
if (error instanceof ApiRequestError && [401, 403, 404].includes(error.status)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
return;
}
if (error instanceof ApiRequestError && error.status === 409) {
setPendingCreate(null);
if (requiresC3(error)) {
setC3Required(true);
setFormError("Для полной проверки нужно активное согласие C3.");
return;
}
setFormError("Доступность изменилась. Обновите состояние перед началом новой попытки.");
await availability.refetch();
return;
}
if (isOutcomeAmbiguous(error)) {
setFormError(
"Не удалось подтвердить создание попытки. Повторная отправка использует тот же ключ.",
);
} else {
setPendingCreate(null);
setFormError(
"Сервер отклонил создание попытки. Проверьте доступность и повторите действие.",
);
}
} finally {
requestInFlight.current = false;
setCreateBusy(false);
}
}
const handleStartReal = () => {
if (!specialization || !grade || !questionnaireSpecialization) return;
const body = buildRootAttemptCreate(
specialization.specialization,
grade.grade,
questionnaireSpecialization.task_languages,
selectedTaskLanguage,
);
if (!body) {
setFormError("Выберите язык задания перед началом проверки.");
return;
}
void startAttempt(body);
};
const handleStartExpress = () => {
void startAttempt({ kind: "demo_express" });
};
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<ForbiddenState
error={session.error}
title="Проверка недоступна"
description="Войдите в кабинет кандидата и повторите проверку доступа."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
</Page>
);
}
if (session.isPending || !actor) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (!actorReady) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<LoadingState label="Подтверждаем текущий вход..." />
</Page>
);
}
return (
<Page
title="Проверка знаний"
eyebrow="Кабинет кандидата"
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
width="wide"
>
<div className={styles.layout}>
<Section
title="Доступность проверки"
description="Состояние и ограничения загружаются с сервера."
>
{(availability.isPending && !availability.data) ||
(questionnaire.isPending && !questionnaire.data) ? (
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
) : !data || !questionnaire.data ? (
<ErrorState
error={!data ? availability.error : questionnaire.error}
isRetrying={!data ? availability.isRefetching : questionnaire.isRefetching}
onRetry={() => void (!data ? availability.refetch() : questionnaire.refetch())}
title="Не удалось загрузить состояние проверки"
/>
) : data.specializations.length === 0 ? (
<EmptyState
title="Сначала выберите специализацию"
description="Сохраните специализацию в анкете кандидата, чтобы увидеть доступные проверки."
action={<ButtonLink to={paths.candidate.questionnaire}>Открыть анкету</ButtonLink>}
/>
) : (
<>
<div className={styles.controls}>
<label className={styles.field}>
<span>Специализация</span>
<select
value={selectedCode}
disabled={Boolean(pendingCreate)}
onChange={(event) => {
setSelection({
specialization: event.currentTarget.value as SpecializationCode,
grade: "",
});
setSelectedTaskLanguage("");
}}
>
{data.specializations.map((item) => (
<option key={item.specialization} value={item.specialization}>
{specializationLabels[item.specialization]}
</option>
))}
</select>
</label>
<label className={styles.field}>
<span>Целевой уровень</span>
<select
value={selectedGradeCode}
disabled={Boolean(pendingCreate)}
onChange={(event) =>
setSelection({
specialization: selectedCode,
grade: event.currentTarget.value as GradeCode,
})
}
>
{specialization?.grades.map((item) => (
<option key={item.grade} value={item.grade}>
{gradeLabels[item.grade]}
</option>
))}
</select>
</label>
</div>
{questionnaireSpecialization && grade?.status !== "active_attempt" ? (
<TaskLanguageControl
languages={savedTaskLanguages}
value={selectedLanguageIsValid ? selectedTaskLanguage : ""}
disabled={Boolean(pendingCreate) || createBusy}
onChange={setSelectedTaskLanguage}
/>
) : null}
{grade?.status !== "active_attempt" ? (
<p className={styles["language-availability"]}>
Доступность уровня не зависит от выбранного языка. При создании сервер проверит,
опубликованы ли подходящие задания.
</p>
) : null}
{specialization && grade ? (
<div className={styles.availability}>
<div className={styles["status-row"]}>
<strong>{gradeLabels[grade.grade]}</strong>
<span data-state={grade.status}>
{grade.status === "available"
? "Доступна"
: grade.status === "active_attempt"
? "Есть попытка"
: grade.status === "cooldown"
? "Пауза"
: "Банк не готов"}
</span>
</div>
<p>{gradeStatusDescription(grade)}</p>
<AssessmentPolicyParameters grade={grade} />
{activeAttemptId && grade.status === "active_attempt" ? (
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
Продолжить текущую попытку
</ButtonLink>
) : grade.status === "available" ? (
<Button
isBusy={createBusy}
disabled={!taskLanguageReady}
onClick={() => {
if (taskLanguageReady) handleStartReal();
}}
>
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
</Button>
) : null}
</div>
) : null}
{pendingCreate ? (
<p className={styles.pending} role="status">
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
ее с тем же ключом.
</p>
) : null}
{formError ? (
<p className={styles.error} role="alert">
{formError}{" "}
{c3Required ? (
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
) : null}
</p>
) : null}
</>
)}
<AssessmentSignalsNotice />
</Section>
<Section
title="Демонстрационный экспресс-запуск"
description="Отдельный учебный режим для знакомства с заданиями."
>
<div className={styles.express}>
<p>
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
и не влияет на доступность полной проверки.
</p>
<Button
isBusy={createBusy}
disabled={Boolean(pendingCreate)}
onClick={handleStartExpress}
>
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"}
</Button>
</div>
</Section>
</div>
</Page>
);
}