Files
lincodex/frontend/src/pages/assessment/ui/assessment-page.tsx
T

680 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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,
Card,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Mono,
Notice,
Page,
Skeleton,
Tag,
type TagTone,
} 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 {
SignalNoticeDialog,
SignalNoticeSummary,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import {
buildRootAttemptCreate,
ExpressRunElsewhereError,
preservePendingCreate,
startExpressRun,
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 gradeStatusTag(grade: AssessmentGradeAvailability): { label: string; tone: TagTone } {
switch (grade.status) {
case "available":
return { label: "Доступна", tone: "success" };
case "active_attempt":
return { label: "Есть попытка", tone: "accent" };
case "cooldown":
return { label: "Пауза", tone: "neutral" };
case "insufficient_bank":
return { label: "Банк не готов", tone: "neutral" };
}
}
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>
</>
);
}
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 signalNotice = useSignalNoticeGate({ actor, queryClient, enabled: actorReady });
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 [expressNote, setExpressNote] = 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;
}
// A real attempt collects signals, so the disclosed list is confirmed first.
void signalNotice.guard(() => void startAttempt(body));
};
async function startExpress() {
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current)
return;
requestInFlight.current = true;
setCreateBusy(true);
setFormError(null);
setExpressNote(null);
setC3Required(false);
try {
const { attempt, resumed } = await startExpressRun({
accountId: actor.account.id,
csrfToken: actor.csrf_token,
pendingKey: pendingCreate?.body.kind === "demo_express" ? pendingCreate.key : null,
newKey: newIdempotencyKey,
onKey: (key) => setPendingCreate({ key, body: { kind: "demo_express" } }),
});
if (!isCurrentAssessmentSession(queryClient, actor)) return;
setPendingCreate(null);
navigate(paths.candidate.assessmentAttempt(attempt.id), {
state: resumed ? { expressResumed: true } : null,
});
} 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 ExpressRunElsewhereError) {
setPendingCreate(null);
setExpressNote(
"Незавершенный экспресс-тест открыт в другой вкладке или браузере. Продолжите его там или подождите: он закончится сам не позже чем через 5 минут после начала.",
);
return;
}
if (isOutcomeAmbiguous(error)) {
setExpressNote(
"Не удалось подтвердить начало экспресс-теста. Повторная отправка использует тот же ключ.",
);
return;
}
setPendingCreate(null);
setExpressNote("Сервер не начал экспресс-тест. Обновите страницу и повторите действие.");
} finally {
requestInFlight.current = false;
setCreateBusy(false);
}
}
const handleStartExpress = () => {
void startExpress();
};
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>
);
}
const statusTag = grade ? gradeStatusTag(grade) : null;
return (
<Page
title="Проверка знаний"
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
width="wide"
>
<div className={styles.layout}>
<Card as="section" tone="panel" labelledBy="assessment-full-title" className={styles.main}>
<header className={styles["block-header"]}>
<p className={styles.kicker}>Полная проверка</p>
<h2 id="assessment-full-title" className={styles["block-title"]}>
Доступность проверки
</h2>
<p className={styles["block-lead"]}>Состояние и ограничения загружаются с сервера.</p>
</header>
{(availability.isPending && !availability.data) ||
(questionnaire.isPending && !questionnaire.data) ? (
<div className={styles.loading}>
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
<Skeleton lines={4} />
</div>
) : !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 && statusTag ? (
<div className={styles.availability}>
<div className={styles["status-row"]}>
<Tag tone="grade">
{`${specializationLabels[specialization.specialization]} · ${gradeLabels[grade.grade]}`}
</Tag>
<Tag tone={statusTag.tone} dot>
{statusTag.label}
</Tag>
</div>
<p>{gradeStatusDescription(grade)}</p>
<AssessmentPolicyParameters grade={grade} />
<div className={styles.actions}>
{activeAttemptId && grade.status === "active_attempt" ? (
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
Продолжить текущую попытку
</ButtonLink>
) : grade.status === "available" ? (
<Button
isBusy={createBusy}
disabled={!taskLanguageReady || pendingCreate?.body.kind === "demo_express"}
onClick={() => {
if (taskLanguageReady) handleStartReal();
}}
>
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
</Button>
) : null}
</div>
</div>
) : null}
{pendingCreate && pendingCreate.body.kind !== "demo_express" ? (
<p className={styles.pending} role="status">
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
ее с тем же ключом.
</p>
) : null}
{formError ? (
<div role="alert">
<Notice
tone="danger"
action={
c3Required ? (
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
) : null
}
>
<p className={styles["notice-text"]}>{formError}</p>
</Notice>
</div>
) : null}
</>
)}
<SignalNoticeSummary />
{signalNotice.checkError ? (
<div role="alert">
<Notice tone="danger">
<p className={styles["notice-text"]}>{signalNotice.checkError}</p>
</Notice>
</div>
) : null}
</Card>
<aside className={styles.aside} aria-labelledby="assessment-express-title">
<Card tone="raised" className={styles.express}>
<p className={styles.kicker}>Учебный режим</p>
<h2 id="assessment-express-title" className={styles["block-title"]}>
Экспресс-тест
</h2>
<p className={styles.duration}>
<Mono strong>3-5</Mono> <span>минут</span>
</p>
<p className={styles["block-lead"]}>
Экспресс-тест не присваивает грейд и не влияет на доступность полной проверки.
</p>
<p className={styles["express-note"]}>
Незавершенный запуск этой вкладки продолжается той же кнопкой.
</p>
<Button
isBusy={createBusy}
disabled={Boolean(pendingCreate) && pendingCreate?.body.kind !== "demo_express"}
onClick={handleStartExpress}
>
{createBusy
? "Создаем запуск..."
: pendingCreate?.body.kind === "demo_express"
? "Повторить начало экспресс-теста"
: "Пройти экспресс-тест"}
</Button>
{expressNote ? (
<div role="status">
<Notice tone="neutral">
<p className={styles["notice-text"]}>{expressNote}</p>
</Notice>
</div>
) : null}
</Card>
</aside>
</div>
<SignalNoticeDialog {...signalNotice.dialog} />
</Page>
);
}