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

@@ -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>
);
}