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 { AssessmentResultPage } from "./ui/assessment-result-page";
export { AssessmentResultsPage } from "./ui/assessment-results-page";
@@ -0,0 +1,20 @@
.layout {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.back {
display: flex;
flex-wrap: wrap;
}
.pending {
display: grid;
gap: var(--space-3);
justify-items: start;
}
.pending p {
margin: 0;
}
@@ -0,0 +1,142 @@
import { useEffect } from "react";
import { useParams } from "react-router-dom";
import type { QueryClient } from "@tanstack/react-query";
import { ApiRequestError } from "../../../shared/api";
import type { Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Page,
} from "../../../shared/ui";
import {
AssessmentActorGate,
AssessmentResultView,
isAssessmentAccessLoss,
isAssessmentSessionEnded,
removeAssessmentQueries,
useAssessmentResult,
} from "../../../entities/assessment";
import styles from "./assessment-result-page.module.css";
const attemptIdPattern =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
/** One stored result, opened by a direct URL; only its owner can read it. */
export function AssessmentResultPage() {
const { attemptId = "" } = useParams();
return (
<Page title="Результат проверки" eyebrow="Кабинет кандидата" width="wide">
<AssessmentActorGate>
{({ actor, queryClient }) => (
<StoredResult
key={attemptId}
actor={actor}
queryClient={queryClient}
attemptId={attemptId}
/>
)}
</AssessmentActorGate>
</Page>
);
}
function StoredResult({
actor,
queryClient,
attemptId,
}: {
actor: Session;
queryClient: QueryClient;
attemptId: string;
}) {
const validId = attemptIdPattern.test(attemptId);
const result = useAssessmentResult({ actor, attemptId, enabled: validId, queryClient });
const accessLost = result.isError && isAssessmentAccessLoss(result.error);
const sessionEnded = result.isError && isAssessmentSessionEnded(result.error);
useEffect(() => {
if (sessionEnded) removeAssessmentQueries(queryClient);
}, [sessionEnded, queryClient]);
const back = (
<div className={styles.back}>
<ButtonLink variant="secondary" to={paths.candidate.results}>
К истории результатов
</ButtonLink>
</div>
);
if (!validId) {
return (
<>
<ErrorState
error={new Error("The attempt identifier is not valid.")}
title="Не удалось открыть результат"
/>
{back}
</>
);
}
if (accessLost) {
return (
<>
<ForbiddenState
error={result.error}
title="Результат недоступен"
description={
sessionEnded
? "Сеанс закончился. Войдите в кабинет кандидата и повторите."
: "Сервер не нашел этот результат среди ваших. Он мог принадлежать другому аккаунту."
}
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
{back}
</>
);
}
if (result.isPending) return <LoadingState label="Загружаем сохраненный результат..." />;
if (!result.data) {
return (
<>
{result.error instanceof ApiRequestError && result.error.status === 409 ? (
<div role="status" className={styles.pending}>
<p>Сервер еще завершает обработку результата. Повторите проверку позже.</p>
<Button
variant="secondary"
isBusy={result.isRefetching}
onClick={() => void result.refetch()}
>
Обновить результат
</Button>
</div>
) : (
<ErrorState
error={result.error}
isRetrying={result.isRefetching}
onRetry={() => void result.refetch()}
title="Не удалось загрузить результат"
/>
)}
{back}
</>
);
}
return (
<div className={styles.layout}>
{result.isError ? (
<ErrorState
error={result.error}
isRetrying={result.isRefetching}
onRetry={() => void result.refetch()}
title="Не удалось обновить результат. Показан ранее загруженный."
/>
) : null}
<AssessmentResultView result={result.data} />
{back}
</div>
);
}
@@ -0,0 +1,246 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { AssessmentResult, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { assessmentQueryKeys } from "../../../entities/assessment";
import { AssessmentResultPage } from "./assessment-result-page";
import { AssessmentResultsPage } from "./assessment-results-page";
const attemptId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff";
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;
const adaptive = {
attempt_id: attemptId,
specialization: "backend",
target_grade: "middle",
root_attempt_id: null,
chain_deadline: null,
task_language: "go",
kind: "root",
mode: "adaptive",
versions: { bank_version: "demo-1", algorithm_version: "adaptive-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: null,
source: null,
calibration_status: "uncalibrated",
},
strength: "medium",
calibration_status: "uncalibrated",
limitations: ["uncalibrated_thresholds"],
uncertainty: {
theta: 0.42,
standard_error: 0.21,
interval_95: { low: -0.19, high: 1.03 },
p_grade: 0.8,
},
basic_score: null,
practices: [],
gaps: [],
durations: { items_seconds: 900, practice_seconds: null },
next_steps: [{ action: "take_higher_grade", grade: "senior", available_at: null }],
decided_at: "2026-10-08T09:30:00Z",
} as unknown as AssessmentResult;
type Prepare = (queryClient: QueryClient) => void;
function signedIn(queryClient: QueryClient) {
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
}
function sessionRefused(queryClient: QueryClient) {
queryClient
.getQueryCache()
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
.setState({
status: "error",
error: new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }),
errorUpdateCount: 1,
fetchStatus: "idle",
});
}
function render(path: string, prepare: Prepare): 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 initialEntries={[path]}>
<Routes>
<Route path={paths.candidate.results} element={<AssessmentResultsPage />} />
<Route
path={`${paths.candidate.results}/:attemptId`}
element={<AssessmentResultPage />}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
}
describe("AssessmentResultPage", () => {
it("opens the stored result of the signed-in candidate by its URL", () => {
const html = render(paths.candidate.result(attemptId), (queryClient) => {
signedIn(queryClient);
queryClient.setQueryData(assessmentQueryKeys.result(session, attemptId), adaptive);
});
expect(html).toContain("Уровень подтвержден: Backend, Middle.");
expect(html).toContain("0,80");
expect(html).toContain("средняя");
expect(html).toContain(`href="${paths.candidate.results}"`);
});
it("shows no data by a direct URL when the session was refused", () => {
const html = render(paths.candidate.result(attemptId), (queryClient) => {
sessionRefused(queryClient);
queryClient.setQueryData(assessmentQueryKeys.result(session, attemptId), adaptive);
});
expect(html).toContain("Результаты недоступны");
expect(html).toContain(`href="${paths.login}"`);
expect(html).not.toContain("Backend");
expect(html).not.toContain("0,80");
});
it("shows no data for a result of another session key", () => {
const html = render(paths.candidate.result(attemptId), (queryClient) => {
signedIn(queryClient);
queryClient.setQueryData(
assessmentQueryKeys.result(
{
...session,
account: { ...session.account, id: "22222222-2222-4222-8222-222222222222" },
},
attemptId,
),
adaptive,
);
});
expect(html).not.toContain("Backend");
expect(html).toContain("Загружаем сохраненный результат...");
});
it("refuses to read a malformed identifier", () => {
const html = render(`${paths.candidate.results}/not-an-id`, signedIn);
expect(html).toContain("Не удалось открыть результат");
});
it("explains a result the server does not return for this candidate", () => {
const html = render(paths.candidate.result(attemptId), (queryClient) => {
signedIn(queryClient);
queryClient
.getQueryCache()
.build(queryClient, { queryKey: assessmentQueryKeys.result(session, attemptId) })
.setState({
status: "error",
error: new ApiRequestError({ status: 404, code: "not_found", title: "Not found" }),
errorUpdateCount: 1,
fetchStatus: "idle",
});
});
expect(html).toContain("Результат недоступен");
expect(html).not.toContain("Backend");
});
});
describe("AssessmentResultPage failures", () => {
function failWith(error: ApiRequestError, withData = false): Prepare {
return (queryClient) => {
signedIn(queryClient);
const key = assessmentQueryKeys.result(session, attemptId);
if (withData) queryClient.setQueryData(key, adaptive);
queryClient
.getQueryCache()
.build(queryClient, { queryKey: key })
.setState({ status: "error", error, errorUpdateCount: 1, fetchStatus: "idle" });
};
}
it("tells an ended session from a missing result", () => {
const ended = render(
paths.candidate.result(attemptId),
failWith(new ApiRequestError({ status: 401, code: "unauthenticated", title: "No session" })),
);
const missing = render(
paths.candidate.result(attemptId),
failWith(new ApiRequestError({ status: 404, code: "not_found", title: "Not found" })),
);
expect(ended).toContain("Сеанс закончился.");
expect(missing).toContain("Сервер не нашел этот результат среди ваших.");
expect(missing).not.toContain("Сеанс закончился.");
});
it("offers exactly one retry for a server error", () => {
const html = render(
paths.candidate.result(attemptId),
failWith(new ApiRequestError({ status: 500, code: "internal", title: "Internal error" })),
);
expect(html).toContain("Не удалось загрузить результат");
expect(html.match(/Повторить/g)).toHaveLength(1);
expect(html).not.toContain("Обновить результат");
});
it("keeps the loaded result when a refresh fails", () => {
const html = render(
paths.candidate.result(attemptId),
failWith(
new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }),
true,
),
);
expect(html).toContain("Уровень подтвержден: Backend, Middle.");
expect(html).toContain("Не удалось обновить результат. Показан ранее загруженный.");
});
it("offers a retry instead of claiming lost access when the session check fails", () => {
const html = render(paths.candidate.result(attemptId), (queryClient) => {
queryClient
.getQueryCache()
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
.setState({
status: "error",
error: new ApiRequestError({ status: 503, code: "internal", title: "Unavailable" }),
errorUpdateCount: 1,
fetchStatus: "idle",
});
});
expect(html).toContain("Не удалось проверить вход");
expect(html).toContain("Повторить");
expect(html).not.toContain("Результаты недоступны");
});
});
describe("AssessmentResultsPage", () => {
it("shows the history heading for the signed-in candidate", () => {
const html = render(paths.candidate.results, signedIn);
expect(html).toContain("Результаты проверок");
expect(html).toContain("Загружаем историю результатов...");
});
it("opens no history without a session", () => {
const html = render(paths.candidate.results, sessionRefused);
expect(html).toContain("Результаты недоступны");
expect(html).not.toContain("Загружаем историю результатов...");
});
});
@@ -0,0 +1,18 @@
import { Page } from "../../../shared/ui";
import { AssessmentActorGate } from "../../../entities/assessment";
import { AssessmentHistory } from "../../../widgets/assessment-history";
/** History of the signed-in candidate's real assessment results. */
export function AssessmentResultsPage() {
return (
<Page
title="Результаты проверок"
eyebrow="Кабинет кандидата"
lead="Решения сервера по завершенным проверкам. Неудачная попытка не понижает действующую категорию."
>
<AssessmentActorGate>
{({ actor, queryClient }) => <AssessmentHistory actor={actor} queryClient={queryClient} />}
</AssessmentActorGate>
</Page>
);
}
@@ -15,7 +15,6 @@
.resume,
.finalize,
.info,
.result,
.item {
display: grid;
gap: var(--space-3);
@@ -27,8 +26,7 @@
.resume p,
.finalize p,
.info p,
.result p {
.info p {
margin: 0;
}
@@ -73,12 +71,9 @@
}
.result {
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.demo-label {
font-weight: var(--font-weight-bold);
display: grid;
gap: var(--space-3);
min-width: 0;
}
.result-error {
@@ -95,8 +90,17 @@
.resume,
.finalize,
.info,
.result,
.item {
padding: var(--space-3);
}
}
.result-heading {
margin: 0;
font-size: var(--font-size-l);
}
.result-heading:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
@@ -13,6 +13,7 @@ import {
import type {
AssessmentAttempt,
AssessmentFinalization,
AssessmentResult,
Session,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
@@ -24,10 +25,11 @@ import {
LoadingState,
Page,
Section,
VisuallyHidden,
} from "../../../shared/ui";
import {
AssessmentResultView,
assessmentQueryKeys,
assessmentResultSummary,
assessmentSessionMatches,
gradeLabels,
isOutcomeAmbiguous,
@@ -679,11 +681,22 @@ function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessm
if (resultQuery.isPending && !resultQuery.data) {
return <LoadingState label="Загружаем сохраненный результат..." />;
}
if (resultQuery.isError || !resultQuery.data) {
if (!resultQuery.data) {
return (
<div className={attemptStyles["result-error"]}>
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
<p role="status">Сервер еще завершает обработку результата. Повторите проверку позже.</p>
<>
<p role="status">
Сервер еще завершает обработку результата. Повторите проверку позже.
</p>
<Button
variant="secondary"
isBusy={resultQuery.isRefetching}
onClick={() => void resultQuery.refetch()}
>
Обновить результат
</Button>
</>
) : (
<ErrorState
error={resultQuery.error}
@@ -692,28 +705,36 @@ function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessm
title="Не удалось загрузить результат"
/>
)}
<Button
variant="secondary"
isBusy={resultQuery.isRefetching}
onClick={() => void resultQuery.refetch()}
>
Обновить результат
</Button>
</div>
);
}
const result = resultQuery.data;
const summary = assessmentResultSummary(result);
return <ResultPanel result={resultQuery.data} />;
}
/**
* The result of a finished attempt. Only a short phrase is a live message;
* the full record is ordinary content, and the focus moves to its heading so
* a screen reader starts reading at the result.
*/
function ResultPanel({ result }: { result: AssessmentResult }) {
const headingRef = useRef<HTMLHeadingElement>(null);
useEffect(() => {
headingRef.current?.focus();
}, []);
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 className={attemptStyles.result}>
<p role="status">
<VisuallyHidden>Результат получен.</VisuallyHidden>
</p>
<h2 ref={headingRef} tabIndex={-1} className={attemptStyles["result-heading"]}>
Результат с сервера
</h2>
<AssessmentResultView result={result} headingLevel={3} />
<div className={attemptStyles["back-link"]}>
<ButtonLink variant="secondary" to={paths.candidate.result(result.attempt_id)}>
Открыть на странице результатов
</ButtonLink>
</div>
</div>
);
}
@@ -0,0 +1 @@
export { CandidateHomePage } from "./ui/candidate-home-page";
@@ -0,0 +1,53 @@
.columns {
display: grid;
gap: var(--space-6);
}
@media (width >= 64rem) {
.columns {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
}
.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(10rem, auto) minmax(0, 1fr);
}
}
.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;
}
.result-text {
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-snug);
}
.reason {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.links {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-5);
}
@@ -0,0 +1,256 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { candidateHomeQueryKeys } from "../../../entities/candidate";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
import { CandidateHomePage } from "./candidate-home-page";
const accountId = "11111111-1111-4111-8111-111111111111";
const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80";
const session = {
account: {
id: accountId,
email: "person@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "candidate_consents",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
} satisfies Session;
type Seed = {
step?: Session["account"]["onboarding_step"];
profileVersion?: number;
declared?: { specialization: string; grade: string } | null;
confirmed?: string | null;
activeAttempt?: string | null;
results?: unknown[];
privacy?: unknown;
};
const closedPrivacy = {
publication: {
state: "closed",
closed_reason: "never_published",
fields: [],
consent_id: null,
published_at: null,
version: 0,
},
search_status: {
value: "not_looking",
lapsed: false,
confirmed_at: null,
lapses_at: null,
version: 0,
},
hidden_organizations_total: 0,
};
function render(seed: Seed = {}): string {
const queryClient = new QueryClient();
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
...session,
account: { ...session.account, onboarding_step: seed.step ?? "candidate_consents" },
});
queryClient.setQueryData(candidateHomeQueryKeys.profile(accountId), {
version: seed.profileVersion ?? 0,
});
queryClient.setQueryData(candidateHomeQueryKeys.questionnaire(accountId), {
version: seed.declared ? 1 : 0,
specializations: seed.declared
? [
{
specialization: seed.declared.specialization,
self_assessed_grade: seed.declared.grade,
task_languages: [],
stack: [],
experience: null,
},
]
: [],
work_context: null,
updated_at: null,
});
queryClient.setQueryData(candidateHomeQueryKeys.availability(accountId), {
specializations: seed.declared
? [
{
specialization: seed.declared.specialization,
confirmed_grade: seed.confirmed ?? null,
active_attempt_id: seed.activeAttempt ?? null,
grades: [
{
grade: seed.declared.grade,
status: "available",
mode: null,
available_at: null,
time_limit_seconds: null,
max_sessions: null,
max_items: null,
practice_required: null,
},
],
},
]
: [],
});
queryClient.setQueryData(candidateHomeQueryKeys.latestResult(accountId), {
items: seed.results ?? [],
page: { has_more: false, next_cursor: null },
});
queryClient.setQueryData(
candidateHomeQueryKeys.privacy(accountId),
seed.privacy ?? closedPrivacy,
);
return renderToString(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<CandidateHomePage />
</MemoryRouter>
</QueryClientProvider>,
);
}
function linkTo(html: string, href: string, text: string): boolean {
return new RegExp(`<a[^>]*href="${href}"[^>]*>${text}</a>`).test(html);
}
describe("candidate home", () => {
it("leads an empty profile to the form without requiring any linking", () => {
const html = render();
expect(html).toMatch(/<h1[^>]*>Главная<\/h1>/);
expect(html).toContain("Заполните профиль");
expect(linkTo(html, "/candidate/profile", "Заполнить профиль")).toBe(true);
expect(html).toContain("Сохраненный шаг аккаунта: <strong>Согласия</strong>");
expect(html).toContain("Привязка ФСП ID необязательна");
// A missing FSP link or ML result is never an error.
expect(html).not.toContain('role="alert"');
});
it("leads a filled profile to the questionnaire", () => {
const html = render({ profileVersion: 2 });
expect(html).toContain("Заполните анкету");
expect(linkTo(html, "/candidate/questionnaire", "Заполнить анкету")).toBe(true);
});
it("leads a saved questionnaire to the test and shows no confirmed category", () => {
const html = render({
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "middle" },
});
expect(html).toContain("Подтвердите уровень тестом");
expect(linkTo(html, "/candidate/assessment", "Перейти к тесту")).toBe(true);
expect(html).toContain("Заявлено: Middle");
expect(html).toContain("Пока не подтверждена");
expect(html).not.toContain("Подтверждено тестом:");
expect(html).toContain("Завершенных попыток пока нет");
});
it("resumes an active attempt", () => {
const html = render({
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "junior" },
activeAttempt: attemptId,
});
expect(html).toContain("Продолжите тест");
expect(linkTo(html, `/candidate/assessment/${attemptId}`, "Продолжить попытку")).toBe(true);
});
it("shows the result, the privacy link, and the declared grade apart from the category", () => {
const html = render({
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "middle" },
confirmed: "junior",
});
expect(html).toContain("Категория получена");
expect(linkTo(html, "/candidate/results", "Открыть результат")).toBe(true);
expect(linkTo(html, "/candidate/privacy", "Настроить видимость")).toBe(true);
expect(html).toContain("Заявлено: Middle");
expect(html).toContain("Подтверждено тестом: Junior");
expect(html).toContain("Закрыта: компании ее не видят. Вы еще не публиковали карточку.");
});
it("restates a published card and an active search status from the API", () => {
const html = render({
profileVersion: 1,
declared: { specialization: "qa", grade: "junior" },
confirmed: "junior",
privacy: {
publication: {
state: "published",
closed_reason: null,
fields: ["categories"],
consent_id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81",
published_at: "2026-10-08T10:00:00Z",
version: 2,
},
search_status: {
value: "looking",
lapsed: false,
confirmed_at: "2026-10-08T10:00:00Z",
lapses_at: "2026-11-07T10:00:00Z",
version: 1,
},
hidden_organizations_total: 0,
},
});
expect(html).toContain("Открыта: компании видят выбранные поля");
expect(html).toContain("Показывается");
expect(html).toContain("Ищу работу, статус действует до");
});
it("describes a result that did not assign a category without presenting a grade", () => {
const html = render({
step: "candidate_assessment",
profileVersion: 1,
declared: { specialization: "backend", grade: "junior" },
results: [
{
attempt_id: attemptId,
specialization: "backend",
target_grade: "junior",
root_attempt_id: null,
chain_deadline: null,
task_language: null,
kind: "root",
mode: "demo_basic",
versions: {},
outcome: "not_confirmed",
not_determined_reason: null,
confirmed_grade: null,
previous_confirmed_grade: null,
strength: null,
calibration_status: "uncalibrated",
limitations: [],
uncertainty: null,
basic_score: null,
practices: [],
gaps: [],
durations: {},
next_steps: [],
decided_at: "2026-10-08T10:00:00Z",
},
],
});
expect(html).toContain("Уровень пока не подтвержден: Backend, Junior.");
expect(linkTo(html, `/candidate/results/${attemptId}`, "Открыть разбор результата")).toBe(true);
expect(html).not.toContain("Подтверждено тестом:");
expect(html).toContain("Пока не подтверждена");
});
});
@@ -0,0 +1,147 @@
import {
summarizeVisibility,
useCandidateLatestResultRead,
useCandidatePrivacyRead,
type VisibilitySummary,
} from "../../../entities/candidate";
import { assessmentResultSummary } from "../../../entities/assessment";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { ButtonLink, EmptyState, Page, QueryView, Section, TextLink } from "../../../shared/ui";
import { CandidateNextStep } from "../../../widgets/candidate-next-step";
import styles from "./candidate-home-page.module.css";
const closedReasonText: Readonly<Record<NonNullable<VisibilitySummary["closedReason"]>, string>> = {
never_published: "Вы еще не публиковали карточку.",
closed_by_candidate: "Вы закрыли карточку.",
consent_revoked: "Согласие C2 отозвано, поэтому карточка закрыта.",
};
function formatDate(value: string): string {
return new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium" }).format(new Date(value));
}
function searchStatusText(search: VisibilitySummary["searchStatus"]): string {
if (search.looking) {
return search.lapsesAt
? `Ищу работу, статус действует до ${formatDate(search.lapsesAt)}`
: "Ищу работу";
}
return search.lapsed
? "Статус «Ищу работу» истек, сейчас: не ищу. Подтвердите его на странице приватности."
: "Не ищу работу";
}
function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
const visibility = summarizeVisibility(settings);
return (
<>
<dl className={styles.facts}>
<dt>Карточка для компаний</dt>
<dd>
{visibility.published
? "Открыта: компании видят выбранные поля"
: `Закрыта: компании ее не видят. ${
visibility.closedReason ? closedReasonText[visibility.closedReason] : ""
}`.trim()}
</dd>
{visibility.published ? (
<>
<dt>Категория в карточке</dt>
<dd>{visibility.showsCategory ? "Показывается" : "Не показывается"}</dd>
</>
) : null}
<dt>Статус поиска</dt>
<dd>{searchStatusText(visibility.searchStatus)}</dd>
</dl>
<div>
<ButtonLink to={paths.candidate.privacy} variant="secondary">
Настроить видимость и согласия
</ButtonLink>
</div>
</>
);
}
function VisibilitySection() {
const session = useGetCurrentSession();
const privacy = useCandidatePrivacyRead(session.data);
return (
<Section
title="Видимость профиля"
description="Компании видят только то, что вы открыли. Контакты скрыты до вашего решения."
>
<QueryView query={privacy} loadingLabel="Загружаем настройки видимости...">
{(settings) => <VisibilityFacts settings={settings} />}
</QueryView>
</Section>
);
}
function LatestResult({ page }: { page: AssessmentResultHistoryPage }) {
const [latest] = page.items;
if (!latest) return null;
const summary = assessmentResultSummary(latest);
return (
<>
<p className={styles["result-text"]}>{summary.text}</p>
{summary.reason ? <p className={styles.reason}>{summary.reason}</p> : null}
<p className={styles.reason}>Решение сохранено: {formatDate(latest.decided_at)}</p>
<div className={styles.links}>
<TextLink to={paths.candidate.result(latest.attempt_id)}>
Открыть разбор результата
</TextLink>
<TextLink to={paths.candidate.results}>История результатов</TextLink>
</div>
</>
);
}
function LatestResultSection() {
const session = useGetCurrentSession();
const results = useCandidateLatestResultRead(session.data);
return (
<Section
title="Последний результат"
description="Результат показывает решение сервера по последней завершенной попытке."
>
<QueryView
query={results}
loadingLabel="Загружаем результаты..."
isEmpty={(page) => page.items.length === 0}
empty={
<EmptyState
title="Завершенных попыток пока нет"
description="Результат появится здесь после первой завершенной попытки теста."
/>
}
>
{(page) => <LatestResult page={page} />}
</QueryView>
</Section>
);
}
/**
* Candidate home: the next step and links to available actions, then the
* last assessment result and the current visibility of the profile. The
* independent blocks fail on their own, so one failed read never hides the
* next step.
*/
export function CandidateHomePage() {
return (
<Page
title="Главная"
eyebrow="Кабинет кандидата"
lead="Что сделать дальше, какой уровень вы заявили и какой подтвержден тестом."
width="wide"
>
<CandidateNextStep />
<div className={styles.columns}>
<LatestResultSection />
<VisibilitySection />
</div>
</Page>
);
}