feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user