feat(frontend): redesign the candidate cabinet with step-by-step profile and questionnaire forms

This commit is contained in:
shira committed 2026-10-10 09:50:27 +03:00
1 parent 15590d127c
commit c836d02ea3
77 files changed
+5409 -1618

No files matched your search

@@ -18,12 +18,17 @@ import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
Card,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Mono,
Notice,
Page,
Section,
Skeleton,
Tag,
type TagTone,
} from "../../../shared/ui";
import {
assessmentSessionMatches,
@@ -46,7 +51,9 @@ import {
} from "../../../features/assessment-signals";
import {
buildRootAttemptCreate,
ExpressRunElsewhereError,
preservePendingCreate,
startExpressRun,
submitPendingAttempt,
type PendingCreate,
} from "./assessment-page.model";
@@ -78,6 +85,19 @@ function gradeStatusDescription(grade: AssessmentGradeAvailability): string {
}
}
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",
@@ -197,6 +217,7 @@ export function AssessmentPage() {
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);
@@ -370,13 +391,73 @@ export function AssessmentPage() {
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 startAttempt({ kind: "demo_express" });
void startExpress();
};
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<Page title="Проверка знаний">
<ForbiddenState
error={session.error}
title="Проверка недоступна"
@@ -388,33 +469,41 @@ export function AssessmentPage() {
}
if (session.isPending || !actor) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<Page title="Проверка знаний">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (!actorReady) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<Page title="Проверка знаний">
<LoadingState label="Подтверждаем текущий вход..." />
</Page>
);
}
const statusTag = grade ? gradeStatusTag(grade) : null;
return (
<Page
title="Проверка знаний"
eyebrow="Кабинет кандидата"
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
width="wide"
>
<div className={styles.layout}>
<Section
title="Доступность проверки"
description="Состояние и ограничения загружаются с сервера."
>
<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) ? (
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
<div className={styles.loading}>
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
<Skeleton lines={4} />
</div>
) : !data || !questionnaire.data ? (
<ErrorState
error={!data ? availability.error : questionnaire.error}
@@ -485,81 +574,105 @@ export function AssessmentPage() {
опубликованы ли подходящие задания.
</p>
) : null}
{specialization && grade ? (
{specialization && grade && statusTag ? (
<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>
<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} />
{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 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 && pendingCreate.body.kind !== "demo_express" ? (
<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>
<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 ? (
<p className={styles.error} role="alert">
{signalNotice.checkError}
</p>
<div role="alert">
<Notice tone="danger">
<p className={styles["notice-text"]}>{signalNotice.checkError}</p>
</Notice>
</div>
) : null}
</Section>
</Card>
<Section
title="Демонстрационный экспресс-запуск"
description="Отдельный учебный режим для знакомства с заданиями."
>
<div className={styles.express}>
<p>
<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"]}>
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
и не влияет на доступность полной проверки.
</p>
<p className={styles["express-note"]}>
Незавершенный запуск этой вкладки продолжается той же кнопкой.
</p>
<Button
isBusy={createBusy}
disabled={Boolean(pendingCreate)}
disabled={Boolean(pendingCreate) && pendingCreate?.body.kind !== "demo_express"}
onClick={handleStartExpress}
>
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"}
{createBusy
? "Создаем запуск..."
: pendingCreate?.body.kind === "demo_express"
? "Повторить начало демонстрации"
: "Начать демонстрацию"}
</Button>
</div>
</Section>
{expressNote ? (
<div role="status">
<Notice tone="neutral">
<p className={styles["notice-text"]}>{expressNote}</p>
</Notice>
</div>
) : null}
</Card>
</aside>
</div>
<SignalNoticeDialog {...signalNotice.dialog} />
</Page>