feat(candidate): add the candidate home, results and result history screens

This commit is contained in:
shira committed 2026-10-09 01:24:45 +03:00
1 parent 8277133712
commit 4761508f13
52 files changed
+5334 -81

No files matched your search

@@ -0,0 +1,2 @@
export { AssessmentHistory } from "./ui/assessment-history";
export { AssessmentHistoryList } from "./ui/assessment-history-list";
@@ -0,0 +1,45 @@
import type { Ref } from "react";
import type { AssessmentResult } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import { TextLink } from "../../../shared/ui";
import { describeAssessmentResult } from "../../../entities/assessment";
import styles from "./assessment-history.module.css";
type AssessmentHistoryListProps = {
items: readonly AssessmentResult[];
/** IANA zone for dates; the browser zone when omitted. */
timeZone?: string;
listRef?: Ref<HTMLOListElement>;
};
/**
* Compact rows of stored results, newest first as the server ordered them.
* Each row restates the server decision; the full record is one link away.
*/
export function AssessmentHistoryList({ items, timeZone, listRef }: AssessmentHistoryListProps) {
return (
<ol className={styles.list} aria-label="История результатов" ref={listRef}>
{items.map((item) => {
const view = describeAssessmentResult(item, timeZone ? { timeZone } : {});
return (
<li key={item.attempt_id} className={styles.item}>
<p className={styles.kind}>{view.kindLabel}</p>
<h2 className={styles.title}>{view.title}</h2>
<p className={styles.summary}>{view.summary.text}</p>
<dl className={styles.facts}>
{view.facts.map((fact) => (
<div key={fact.label}>
<dt>{fact.label}</dt>
<dd>{fact.value}</dd>
</div>
))}
</dl>
<TextLink to={paths.candidate.result(view.attemptId)}>
Открыть результат: {view.title}, {view.decidedDay}
</TextLink>
</li>
);
})}
</ol>
);
}
@@ -0,0 +1,87 @@
.root {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.note {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.list {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.item {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.item p {
margin: 0;
overflow-wrap: anywhere;
}
.kind {
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.title {
margin: 0;
font-size: var(--font-size-l);
line-height: var(--line-height-snug);
overflow-wrap: anywhere;
}
.summary {
font-weight: var(--font-weight-bold);
}
.facts {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 12rem), 1fr));
gap: var(--space-3);
margin: 0;
}
.facts > div {
display: grid;
gap: var(--space-1);
min-width: 0;
}
.facts dt {
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
}
.facts dd {
margin: 0;
overflow-wrap: anywhere;
}
@media (width < 42rem) {
.item {
padding: var(--space-3);
}
}
.live {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
@@ -0,0 +1,217 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import type { AssessmentResult, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { assessmentQueryKeys } from "../../../entities/assessment";
import { AssessmentHistory } from "./assessment-history";
import { AssessmentHistoryList } from "./assessment-history-list";
const session = {
account: {
id: "11111111-1111-4111-8111-111111111111",
email: "person@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
} satisfies Session;
function stored(id: string, patch: Record<string, unknown> = {}): AssessmentResult {
return {
attempt_id: id,
specialization: "backend",
target_grade: "middle",
root_attempt_id: null,
chain_deadline: null,
task_language: "go",
kind: "root",
mode: "demo_basic",
versions: { bank_version: "demo-1", algorithm_version: "basic-1", policy_version: 1 },
outcome: "confirmed",
not_determined_reason: null,
confirmed_grade: "middle",
previous_confirmed_grade: null,
category_decision: {
status: "assigned",
previous_confirmed_grade: null,
current_confirmed_grade: "middle",
method: "demo_basic_pass_mark",
source: "synthetic_demo",
calibration_status: "uncalibrated",
},
strength: null,
calibration_status: "uncalibrated",
limitations: ["demo_bank"],
uncertainty: null,
basic_score: { points: 17, max_points: 20, pass_points: 14 },
practices: [],
gaps: [],
durations: { items_seconds: 600, practice_seconds: null },
next_steps: [],
decided_at: "2026-10-08T09:30:00Z",
...patch,
} as unknown as AssessmentResult;
}
function render(prepare: (queryClient: QueryClient) => void): string {
// Server rendering refetches an errored query on mount unless told not to.
const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } });
prepare(queryClient);
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<AssessmentHistory actor={session} queryClient={queryClient} />
</MemoryRouter>
</QueryClientProvider>,
);
}
function seedPages(queryClient: QueryClient, pages: unknown[]) {
queryClient.setQueryData(assessmentQueryKeys.resultHistory(session), {
pages,
pageParams: pages.map(() => null),
});
}
function seedError(queryClient: QueryClient, error: Error) {
queryClient
.getQueryCache()
.build(queryClient, { queryKey: assessmentQueryKeys.resultHistory(session) })
.setState({ status: "error", error, errorUpdateCount: 1, fetchStatus: "idle" });
}
const firstId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff";
const secondId = "0199b4f2-7c1e-7d3a-9f00-112233445566";
describe("AssessmentHistory", () => {
it("lists stored results with a link to each and says express runs are excluded", () => {
const html = render((queryClient) =>
seedPages(queryClient, [
{
items: [stored(firstId), stored(secondId, { outcome: "not_confirmed" })],
page: { has_more: false, next_cursor: null },
},
]),
);
expect(html).toContain("Backend, Middle");
expect(html).toContain(`href="${paths.candidate.result(firstId)}"`);
expect(html).toContain(`href="${paths.candidate.result(secondId)}"`);
expect(html).toContain("Демонстрационные запуски сюда не попадают");
expect(html).not.toContain("Показать еще");
});
it("offers the next page only while the server reports one", () => {
const html = render((queryClient) =>
seedPages(queryClient, [
{ items: [stored(firstId)], page: { has_more: true, next_cursor: "next_page" } },
]),
);
expect(html).toContain("Показать еще");
});
it("shows an empty state with a way to the checks", () => {
const html = render((queryClient) =>
seedPages(queryClient, [{ items: [], page: { has_more: false, next_cursor: null } }]),
);
expect(html).toContain("Результатов пока нет");
expect(html).toContain(`href="${paths.candidate.assessment}"`);
});
it("shows a load error with a retry and no stale rows", () => {
const html = render((queryClient) =>
seedError(
queryClient,
new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }),
),
);
expect(html).toContain("Не удалось загрузить историю результатов");
expect(html).toContain("Повторить");
expect(html).not.toContain("Backend");
});
it("shows no data once the server refuses access", () => {
const html = render((queryClient) =>
seedError(
queryClient,
new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }),
),
);
expect(html).toContain("История результатов недоступна");
expect(html).toContain(`href="${paths.login}"`);
expect(html).not.toContain("Backend");
});
it("names each link with the title and the decision date", () => {
const html = render((queryClient) =>
seedPages(queryClient, [
{ items: [stored(firstId)], page: { has_more: false, next_cursor: null } },
]),
);
expect(html).toMatch(/Открыть результат: Backend, Middle, \d{1,2} \S+ 2026 г\./);
});
it("separates an ended session from a refused one", () => {
const ended = render((queryClient) =>
seedError(
queryClient,
new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }),
),
);
const refused = render((queryClient) =>
seedError(
queryClient,
new ApiRequestError({ status: 404, code: "not_found", title: "Not found" }),
),
);
expect(ended).toContain("Сеанс закончился.");
expect(refused).not.toContain("Сеанс закончился.");
expect(refused).toContain("История результатов недоступна");
});
it("keeps the loaded rows and says so when a refresh fails", () => {
const html = render((queryClient) => {
seedPages(queryClient, [
{ items: [stored(firstId)], page: { has_more: false, next_cursor: null } },
]);
queryClient
.getQueryCache()
.build(queryClient, { queryKey: assessmentQueryKeys.resultHistory(session) })
.setState({
status: "error",
error: new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }),
errorUpdateCount: 1,
fetchStatus: "idle",
});
});
expect(html).toContain("Backend, Middle");
expect(html).toContain("Не удалось обновить историю. Показаны ранее загруженные результаты.");
});
it("shows the loading state before the first answer", () => {
const html = render(() => {});
expect(html).toContain("Загружаем историю результатов...");
});
});
describe("AssessmentHistoryList", () => {
it("keeps the order the server sent", () => {
const html = renderToStaticMarkup(
<MemoryRouter>
<AssessmentHistoryList
timeZone="UTC"
items={[
stored(firstId, { decided_at: "2026-10-09T09:30:00Z" }),
stored(secondId, { decided_at: "2026-10-01T09:30:00Z" }),
]}
/>
</MemoryRouter>,
);
expect(html.indexOf("9 октября 2026")).toBeGreaterThan(-1);
expect(html.indexOf("9 октября 2026")).toBeLessThan(html.indexOf("1 октября 2026"));
});
});
@@ -0,0 +1,141 @@
import { useEffect, useRef, useState } from "react";
import type { QueryClient } from "@tanstack/react-query";
import type { Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
} from "../../../shared/ui";
import {
isAssessmentAccessLoss,
isAssessmentSessionEnded,
removeAssessmentQueries,
useAssessmentResultHistory,
} from "../../../entities/assessment";
import { AssessmentHistoryList } from "./assessment-history-list";
import styles from "./assessment-history.module.css";
type AssessmentHistoryProps = {
actor: Session;
queryClient: QueryClient;
};
/**
* Immutable real results of the signed-in candidate. The list is read for
* the current session only. A lost session removes the cached rows; a 403 or
* 404 shows no data but leaves other cached answers alone. A failed
* background refresh keeps the rows that were already loaded. Express runs
* are not part of the history.
*/
export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps) {
const history = useAssessmentResultHistory({ actor, queryClient });
const accessLost = history.isError && isAssessmentAccessLoss(history.error);
const sessionEnded = history.isError && isAssessmentSessionEnded(history.error);
const listRef = useRef<HTMLOListElement>(null);
const focusFrom = useRef<number | null>(null);
const [announcement, setAnnouncement] = useState("");
const itemCount = history.data?.pages.reduce((total, page) => total + page.items.length, 0) ?? 0;
useEffect(() => {
if (sessionEnded) removeAssessmentQueries(queryClient);
}, [sessionEnded, queryClient]);
// After "Show more" the focus moves to the first new row, so the keyboard
// position is not lost when the button disappears or moves down.
useEffect(() => {
const from = focusFrom.current;
if (from === null || itemCount <= from) return;
focusFrom.current = null;
listRef.current?.querySelectorAll<HTMLAnchorElement>("li a")[from]?.focus();
}, [itemCount]);
async function loadMore() {
const before = itemCount;
focusFrom.current = before;
const result = await history.fetchNextPage();
if (result.isError || !result.data) {
focusFrom.current = null;
return;
}
const total = result.data.pages.reduce((sum, page) => sum + page.items.length, 0);
setAnnouncement(`Загружено еще результатов: ${total - before}. Всего: ${total}.`);
}
if (accessLost) {
return (
<ForbiddenState
error={history.error}
title="История результатов недоступна"
description={
sessionEnded
? "Сеанс закончился. Войдите в кабинет кандидата и повторите."
: "Сервер не подтвердил доступ к истории. Войдите в кабинет кандидата и повторите."
}
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
if (history.isPending) return <LoadingState label="Загружаем историю результатов..." />;
if (history.isError && !history.data) {
return (
<ErrorState
error={history.error}
isRetrying={history.isRefetching}
onRetry={() => void history.refetch()}
title="Не удалось загрузить историю результатов"
/>
);
}
const items = history.data?.pages.flatMap((page) => page.items) ?? [];
if (items.length === 0) {
return (
<EmptyState
title="Результатов пока нет"
description="Здесь появятся завершенные реальные проверки. Демонстрационные запуски в историю не входят."
action={<ButtonLink to={paths.candidate.assessment}>К проверкам</ButtonLink>}
/>
);
}
return (
<div className={styles.root}>
<p className={styles.note}>
В истории только завершенные реальные проверки. Демонстрационные запуски сюда не попадают и
категорию не меняют.
</p>
{history.isRefetchError && !history.isFetchNextPageError ? (
<ErrorState
error={history.error}
isRetrying={history.isRefetching}
onRetry={() => void history.refetch()}
title="Не удалось обновить историю. Показаны ранее загруженные результаты."
/>
) : null}
<AssessmentHistoryList items={items} listRef={listRef} />
<p className={styles.live} role="status">
{announcement}
</p>
{history.isFetchNextPageError ? (
<ErrorState
error={history.error}
title="Не удалось загрузить следующие результаты"
isRetrying={history.isFetchingNextPage}
onRetry={() => void loadMore()}
/>
) : history.hasNextPage ? (
<Button
variant="secondary"
isBusy={history.isFetchingNextPage}
onClick={() => void loadMore()}
>
{history.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
</Button>
) : null}
</div>
);
}
@@ -0,0 +1 @@
export { CandidateNextStep } from "./ui/candidate-next-step";
@@ -0,0 +1,126 @@
.root {
display: grid;
gap: var(--space-6);
}
/* The next step is the one dominant block of the home screen. */
.card {
display: grid;
gap: var(--space-3);
padding: var(--space-5);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-l);
background: var(--color-surface);
}
.card-eyebrow {
color: var(--color-accent);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.card-title {
font-size: var(--font-size-xl);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-snug);
}
.card-text {
max-width: 44rem;
font-size: var(--font-size-m);
line-height: var(--line-height-body);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
padding-top: var(--space-2);
}
.note {
max-width: 44rem;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.columns {
display: grid;
gap: var(--space-6);
}
@media (width >= 64rem) {
.columns {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
}
.standings,
.links {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.standing,
.link {
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.standing-title {
margin-bottom: var(--space-3);
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.facts {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--space-1) var(--space-4);
margin: 0;
}
@media (width >= 48rem) {
.facts {
grid-template-columns: minmax(9rem, auto) minmax(0, 1fr);
align-items: center;
}
}
.facts dt {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.facts dd {
min-width: 0;
margin: 0 0 var(--space-2);
overflow-wrap: anywhere;
}
.link {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: center;
justify-content: space-between;
}
.link-label {
font-weight: var(--font-weight-bold);
}
.link-status {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
@@ -0,0 +1,300 @@
import type { ReactNode } from "react";
import {
onboardingStepLabels,
useCandidateJourney,
type CandidateJourney,
type CandidateNextStep as NextStep,
type SpecializationStanding,
} from "../../../entities/candidate";
import { gradeLabels, specializationLabels } from "../../../entities/assessment";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { paths } from "../../../shared/config";
import {
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Section,
TextLink,
TrustLevel,
} from "../../../shared/ui";
import styles from "./candidate-next-step.module.css";
type StepView = {
title: string;
description: ReactNode;
action: { label: string; to: string };
secondary?: { label: string; to: string };
/** True while the optional FSP link is worth mentioning. */
mentionsOptionalFsp: boolean;
};
function standingLabel(standing: SpecializationStanding): string {
return `${specializationLabels[standing.specialization]}, ${
standing.declaredGrade ? gradeLabels[standing.declaredGrade] : "уровень не указан"
}`;
}
function describeNextStep(journey: CandidateJourney, step: NextStep): StepView {
switch (step.kind) {
case "profile":
return {
title: "Заполните профиль",
description:
"Профиль еще не сохранен. Его можно заполнить вручную, без резюме и без привязки аккаунта ФСП.",
action: { label: "Заполнить профиль", to: paths.candidate.profile },
mentionsOptionalFsp: true,
};
case "questionnaire":
return {
title: "Заполните анкету",
description:
"Укажите специализацию и уровень, на который вы претендуете. Это самооценка: подтвержденную категорию присваивает только тест.",
action: { label: "Заполнить анкету", to: paths.candidate.questionnaire },
mentionsOptionalFsp: true,
};
case "assessment": {
const declared = journey.standings.map(standingLabel).join("; ");
const canStart = journey.standings.some((standing) => standing.canStartAttempt);
return {
title: "Подтвердите уровень тестом",
description: (
<>
Заявлено: {declared}. Заявленный уровень не считается категорией, пока его не подтвердит
тест.{" "}
{canStart
? "Тест можно начать сейчас."
: "Сейчас ни один уровень не открыт для начала; на странице теста указано, что мешает и когда это изменится."}
</>
),
action: { label: "Перейти к тесту", to: paths.candidate.assessment },
mentionsOptionalFsp: true,
};
}
case "resume_attempt":
return {
title: "Продолжите тест",
description: `Есть незавершенная попытка: ${specializationLabels[step.specialization]}. Ответы хранятся на сервере.`,
action: {
label: "Продолжить попытку",
to: paths.candidate.assessmentAttempt(step.attemptId),
},
mentionsOptionalFsp: true,
};
case "result":
return {
title: "Категория получена",
description: `Подтверждено тестом: ${journey.confirmed
.flatMap((standing) =>
standing.confirmedGrade
? [
`${specializationLabels[standing.specialization]}, ${gradeLabels[standing.confirmedGrade]}`,
]
: [],
)
.join("; ")}. Посмотрите результат и решите, кому видна ваша карточка.`,
action: { label: "Открыть результат", to: paths.candidate.results },
secondary: { label: "Настроить видимость", to: paths.candidate.privacy },
mentionsOptionalFsp: false,
};
}
}
function NextStepCard({ journey }: { journey: CandidateJourney }) {
const view = describeNextStep(journey, journey.nextStep);
return (
<section className={styles.card} aria-labelledby="next-step-title">
<p className={styles["card-eyebrow"]}>Следующий шаг</p>
<h2 id="next-step-title" className={styles["card-title"]}>
{view.title}
</h2>
<p className={styles["card-text"]}>{view.description}</p>
<div className={styles.actions}>
<ButtonLink to={view.action.to}>{view.action.label}</ButtonLink>
{view.secondary ? (
<ButtonLink to={view.secondary.to} variant="secondary">
{view.secondary.label}
</ButtonLink>
) : null}
</div>
<p className={styles.note}>
Сохраненный шаг аккаунта: <strong>{onboardingStepLabels[journey.savedStep]}</strong>.
{view.mentionsOptionalFsp
? " Привязка ФСП ID необязательна: путь до категории проходит через анкету и тест."
: null}
</p>
</section>
);
}
function Standings({ journey }: { journey: CandidateJourney }) {
return (
<Section
title="Заявлено и подтверждено"
headingLevel={2}
description="Заявленный уровень - это ваша самооценка из анкеты. Подтвержденной бывает только категория, которую присвоил тест."
>
{journey.standings.length === 0 ? (
<EmptyState
title="Анкета еще не сохранена"
description="Заявленный уровень появится после анкеты."
action={<ButtonLink to={paths.candidate.questionnaire}>Заполнить анкету</ButtonLink>}
/>
) : (
<ul className={styles.standings}>
{journey.standings.map((standing) => (
<li key={standing.specialization} className={styles.standing}>
<h3 className={styles["standing-title"]}>
{specializationLabels[standing.specialization]}
</h3>
<dl className={styles.facts}>
<dt>Заявлено (самооценка)</dt>
<dd>
<TrustLevel
level="claimed"
label={
standing.declaredGrade
? `Заявлено: ${gradeLabels[standing.declaredGrade]}`
: "Уровень не указан"
}
/>
</dd>
<dt>Подтвержденная категория</dt>
<dd>
{standing.confirmedGrade ? (
<TrustLevel
level="confirmed"
label={`Подтверждено тестом: ${gradeLabels[standing.confirmedGrade]}`}
/>
) : (
<TrustLevel level="none" label="Пока не подтверждена" />
)}
</dd>
</dl>
</li>
))}
</ul>
)}
</Section>
);
}
type SectionLink = { label: string; status: string; to: string | null; linkLabel: string };
function sectionLinks(journey: CandidateJourney): SectionLink[] {
const hasConfirmed = journey.confirmed.length > 0;
const hasActiveAttempt = journey.standings.some((standing) => standing.activeAttemptId !== null);
const testStatus = !journey.questionnaireSaved
? "Откроется после анкеты"
: hasConfirmed
? "Есть подтвержденная категория"
: hasActiveAttempt
? "Есть незавершенная попытка"
: "Еще не пройден";
return [
{
label: "Профиль",
status: journey.profileSaved ? "Сохранен" : "Не заполнен",
to: paths.candidate.profile,
linkLabel: journey.profileSaved ? "Открыть профиль" : "Заполнить профиль",
},
{
label: "Анкета",
status: journey.questionnaireSaved ? "Сохранена" : "Не заполнена",
to: paths.candidate.questionnaire,
linkLabel: journey.questionnaireSaved ? "Открыть анкету" : "Заполнить анкету",
},
{
label: "Тест",
status: testStatus,
to: journey.questionnaireSaved ? paths.candidate.assessment : null,
linkLabel: "Перейти к тесту",
},
{
label: "Результаты",
status: hasConfirmed ? "Есть категория" : "Появятся после теста",
to: paths.candidate.results,
linkLabel: "Результаты и история",
},
{
label: "Приватность",
status: "Согласия, видимость карточки, статус поиска",
to: paths.candidate.privacy,
linkLabel: "Открыть настройки",
},
{
label: "Поддержка",
status: "Обращения и запрос ручной оценки",
to: paths.candidate.supportCases,
linkLabel: "Открыть обращения",
},
];
}
function AvailableActions({ journey }: { journey: CandidateJourney }) {
return (
<Section title="Доступные действия" headingLevel={2}>
<ul className={styles.links}>
{sectionLinks(journey).map((item) => (
<li key={item.label} className={styles.link}>
<div>
<p className={styles["link-label"]}>{item.label}</p>
<p className={styles["link-status"]}>{item.status}</p>
</div>
{item.to ? <TextLink to={item.to}>{item.linkLabel}</TextLink> : null}
</li>
))}
</ul>
</Section>
);
}
/**
* The main block of the candidate home: the next step, the declared and the
* confirmed level side by side, and links to the available actions. Everything
* comes from one read of the profile, the questionnaire, and the assessment
* availability; a failed read shows an error instead of a guessed step.
*/
export function CandidateNextStep() {
const session = useGetCurrentSession();
const state = useCandidateJourney(session.data);
if (session.isError) {
if (isAccessDenied(session.error)) return <ForbiddenState error={session.error} />;
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
);
}
if (state.status === "pending") {
return <LoadingState label="Определяем следующий шаг..." />;
}
if (state.status === "error") {
if (isAccessDenied(state.error)) return <ForbiddenState error={state.error} />;
return (
<ErrorState
error={state.error}
isRetrying={state.isRetrying}
onRetry={state.retry}
title="Не удалось определить следующий шаг"
/>
);
}
return (
<div className={styles.root}>
<NextStepCard journey={state.journey} />
<div className={styles.columns}>
<Standings journey={state.journey} />
<AvailableActions journey={state.journey} />
</div>
</div>
);
}