843 lines
32 KiB
TypeScript
843 lines
32 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
||
import { useQueryClient } from "@tanstack/react-query";
|
||
import { useLocation, 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,
|
||
AssessmentResult,
|
||
Session,
|
||
} from "../../../shared/api/schemas";
|
||
import { paths } from "../../../shared/config/paths";
|
||
import {
|
||
Button,
|
||
ButtonLink,
|
||
Card,
|
||
ErrorState,
|
||
ForbiddenState,
|
||
LoadingState,
|
||
Mono,
|
||
Notice,
|
||
Page,
|
||
Skeleton,
|
||
VisuallyHidden,
|
||
} from "../../../shared/ui";
|
||
import {
|
||
AssessmentResultView,
|
||
assessmentQueryKeys,
|
||
assessmentSessionMatches,
|
||
gradeLabels,
|
||
isOutcomeAmbiguous,
|
||
isCurrentAssessmentSession,
|
||
methodLabel,
|
||
parseAssessmentAttemptResponse,
|
||
removeAssessmentQueries,
|
||
removeAssessmentQueriesForSessionChange,
|
||
specializationLabels,
|
||
useAssessmentAttempt,
|
||
useAssessmentResult,
|
||
} from "../../../entities/assessment";
|
||
import {
|
||
AnswerForm,
|
||
buildAnswerSubmission,
|
||
clearAnswerDraft,
|
||
newIdempotencyKey,
|
||
submitPendingAnswerCommand,
|
||
} from "../../../features/answer-assessment";
|
||
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
|
||
import {
|
||
SignalNoticeDialog,
|
||
shouldCollectSignals,
|
||
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 };
|
||
|
||
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 ? 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 {
|
||
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 collectsSignals = Boolean(attempt && attempt.kind !== "demo_express");
|
||
const signalNotice = useSignalNoticeGate({
|
||
actor,
|
||
queryClient,
|
||
enabled: actorReady && collectsSignals,
|
||
});
|
||
// Signals are collected only while a real attempt is being worked on. The hook
|
||
// renders nothing and never waits for the network.
|
||
useAssessmentSignals({
|
||
attemptId,
|
||
itemId: attempt?.current_item?.id ?? null,
|
||
csrfToken: actor?.csrf_token ?? "",
|
||
enabled: Boolean(
|
||
attempt &&
|
||
shouldCollectSignals({
|
||
ready: actorReady,
|
||
kind: attempt.kind,
|
||
workReady,
|
||
terminal: isTerminal(attempt),
|
||
}),
|
||
),
|
||
});
|
||
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 [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);
|
||
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,
|
||
]);
|
||
|
||
// 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);
|
||
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);
|
||
setAnswerSaved(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;
|
||
clearAnswerDraft(currentAttemptId, command.itemId);
|
||
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);
|
||
setAnswerSaved(true);
|
||
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="Попытка проверки">
|
||
<ForbiddenState
|
||
error={session.error}
|
||
title="Попытка недоступна"
|
||
description="Сервер не подтвердил доступ к этой попытке. Проверьте вход в кабинет кандидата."
|
||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||
/>
|
||
</Page>
|
||
);
|
||
}
|
||
if (session.isPending || !actor) {
|
||
return (
|
||
<Page title="Попытка проверки">
|
||
<LoadingState label="Проверяем вход..." />
|
||
</Page>
|
||
);
|
||
}
|
||
if (!actorReady) {
|
||
return (
|
||
<Page title="Попытка проверки">
|
||
<LoadingState label="Подтверждаем текущий вход..." />
|
||
</Page>
|
||
);
|
||
}
|
||
if (!attemptId) {
|
||
return (
|
||
<Page title="Попытка проверки">
|
||
<ErrorState
|
||
error={new Error("The attempt identifier is missing.")}
|
||
title="Не удалось открыть попытку"
|
||
/>
|
||
</Page>
|
||
);
|
||
}
|
||
if (attemptQuery.isPending && !attempt) {
|
||
return (
|
||
<Page title="Попытка проверки">
|
||
<LoadingState label="Загружаем сохраненную попытку..." />
|
||
</Page>
|
||
);
|
||
}
|
||
if (attemptQuery.isError || !attempt) {
|
||
if (isAccessLoss(attemptQuery.error)) {
|
||
return (
|
||
<Page title="Попытка проверки">
|
||
<ForbiddenState
|
||
error={attemptQuery.error}
|
||
title="Попытка недоступна"
|
||
description="Сервер не подтвердил доступ к этой попытке."
|
||
action={<ButtonLink to={paths.candidate.assessment}>К списку проверок</ButtonLink>}
|
||
/>
|
||
</Page>
|
||
);
|
||
}
|
||
return (
|
||
<Page title="Попытка проверки">
|
||
<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);
|
||
|
||
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" ? "Демонстрационная проверка" : "Полная проверка"}
|
||
lead={
|
||
attempt.kind === "demo_express"
|
||
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
|
||
: undefined
|
||
}
|
||
width="wide"
|
||
>
|
||
<div className={attemptStyles.layout}>
|
||
<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 ? (
|
||
<div role="alert">
|
||
<Notice tone="danger">
|
||
<p className={attemptStyles["notice-text"]}>{pageError}</p>
|
||
</Notice>
|
||
</div>
|
||
) : null}
|
||
|
||
{!workReady && !terminal ? (
|
||
<Card tone="raised" className={attemptStyles.resume}>
|
||
<p>
|
||
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
|
||
меняются, а ответ не отправляется повторно автоматически.
|
||
</p>
|
||
{signalNotice.checkError ? (
|
||
<div role="alert">
|
||
<Notice tone="danger">
|
||
<p className={attemptStyles["notice-text"]}>{signalNotice.checkError}</p>
|
||
</Notice>
|
||
</div>
|
||
) : null}
|
||
<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 role="status">
|
||
<Notice
|
||
tone="neutral"
|
||
action={
|
||
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
|
||
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
|
||
</Button>
|
||
}
|
||
>
|
||
<p className={attemptStyles["notice-text"]}>
|
||
Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.
|
||
</p>
|
||
</Notice>
|
||
</div>
|
||
) : null}
|
||
|
||
{workReady &&
|
||
currentItem &&
|
||
!terminal &&
|
||
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
|
||
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
|
||
<div className={attemptStyles["item-heading"]}>
|
||
<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
|
||
key={currentItem.id}
|
||
attemptId={attempt.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 ? (
|
||
<div role="status">
|
||
<Notice tone="info">
|
||
<p className={attemptStyles["notice-text"]}>
|
||
Решение передано на проверку. Результат появится после ответа сервера; страница
|
||
обновляет статус автоматически.
|
||
</p>
|
||
</Notice>
|
||
</div>
|
||
) : null}
|
||
|
||
{workReady &&
|
||
!currentItem &&
|
||
!practicePending &&
|
||
canFinalize &&
|
||
!terminal &&
|
||
!pendingAnswerNeedsReplay ? (
|
||
<Card tone="raised" className={attemptStyles.finalize}>
|
||
<p>
|
||
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
|
||
</p>
|
||
<div className={attemptStyles.actions}>
|
||
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
|
||
{finalizeBusy
|
||
? "Запрашиваем решение..."
|
||
: pendingFinalize
|
||
? "Повторить завершение"
|
||
: "Завершить проверку"}
|
||
</Button>
|
||
</div>
|
||
</Card>
|
||
) : null}
|
||
|
||
{workReady &&
|
||
!currentItem &&
|
||
!practicePending &&
|
||
!canFinalize &&
|
||
!terminal &&
|
||
!pendingAnswerNeedsReplay ? (
|
||
<div role="status">
|
||
<Notice
|
||
tone="neutral"
|
||
action={
|
||
<Button
|
||
variant="secondary"
|
||
isBusy={attemptQuery.isRefetching}
|
||
onClick={() => void attemptQuery.refetch()}
|
||
>
|
||
Обновить попытку
|
||
</Button>
|
||
}
|
||
>
|
||
<p className={attemptStyles["notice-text"]}>
|
||
Сервер не вернул следующее задание. Обновите состояние попытки.
|
||
</p>
|
||
</Notice>
|
||
</div>
|
||
) : null}
|
||
|
||
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
|
||
</section>
|
||
<div className={attemptStyles["back-link"]}>
|
||
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
|
||
К доступным проверкам
|
||
</ButtonLink>
|
||
</div>
|
||
</div>
|
||
<SignalNoticeDialog {...signalNotice.dialog} />
|
||
</Page>
|
||
);
|
||
}
|
||
|
||
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
|
||
if (resultQuery.isPending && !resultQuery.data) {
|
||
return (
|
||
<div className={attemptStyles.result}>
|
||
<LoadingState label="Загружаем сохраненный результат..." />
|
||
<Skeleton shape="card" lines={4} />
|
||
</div>
|
||
);
|
||
}
|
||
if (!resultQuery.data) {
|
||
return (
|
||
<div className={attemptStyles["result-error"]}>
|
||
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
|
||
<>
|
||
<p role="status">
|
||
Сервер еще завершает обработку результата. Повторите проверку позже.
|
||
</p>
|
||
<Button
|
||
variant="secondary"
|
||
isBusy={resultQuery.isRefetching}
|
||
onClick={() => void resultQuery.refetch()}
|
||
>
|
||
Обновить результат
|
||
</Button>
|
||
</>
|
||
) : (
|
||
<ErrorState
|
||
error={resultQuery.error}
|
||
isRetrying={resultQuery.isRefetching}
|
||
onRetry={() => void resultQuery.refetch()}
|
||
title="Не удалось загрузить результат"
|
||
/>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
return <ResultPanel result={resultQuery.data} />;
|
||
}
|
||
|
||
/**
|
||
* The result of a finished attempt. Only a short phrase is a live message;
|
||
* the full record is ordinary content, and the focus moves to its heading so
|
||
* a screen reader starts reading at the result.
|
||
*/
|
||
function ResultPanel({ result }: { result: AssessmentResult }) {
|
||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||
useEffect(() => {
|
||
headingRef.current?.focus();
|
||
}, []);
|
||
return (
|
||
<div className={attemptStyles.result}>
|
||
<p role="status">
|
||
<VisuallyHidden>Результат получен.</VisuallyHidden>
|
||
</p>
|
||
<h2 ref={headingRef} tabIndex={-1} className={attemptStyles["result-heading"]}>
|
||
Результат с сервера
|
||
</h2>
|
||
<AssessmentResultView result={result} headingLevel={3} />
|
||
<div className={attemptStyles["back-link"]}>
|
||
<ButtonLink variant="secondary" to={paths.candidate.result(result.attempt_id)}>
|
||
Открыть на странице результатов
|
||
</ButtonLink>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|