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,128 @@
import { QueryClient } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { invalidResponseCode } from "../../../shared/api";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
import { demoBasicAssigned, notConfirmedAfterJunior } from "../model/result.fixtures";
import { assessmentResultHistoryOptions } from "./assessment-queries";
const server = setupServer();
const historyUrl = "http://localhost/api/v1/me/assessment-results";
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;
beforeAll(() => server.listen());
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
function signedInClient(): QueryClient {
const queryClient = new QueryClient();
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
return queryClient;
}
function stubRelativeFetch() {
const realFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
realFetch(new URL(input, "http://localhost"), init),
);
}
describe("assessmentResultHistoryOptions", () => {
it("reads pages with the server cursor and stops when the server says so", async () => {
stubRelativeFetch();
const requests: URL[] = [];
server.use(
http.get(historyUrl, ({ request }) => {
const url = new URL(request.url);
requests.push(url);
return url.searchParams.has("cursor")
? HttpResponse.json({
items: [notConfirmedAfterJunior()],
page: { has_more: false, next_cursor: null },
})
: HttpResponse.json({
items: [demoBasicAssigned()],
page: { has_more: true, next_cursor: "cursor_page_2" },
});
}),
);
const queryClient = signedInClient();
const data = await queryClient.fetchInfiniteQuery({
...assessmentResultHistoryOptions({ actor: session, queryClient }),
pages: 3,
});
expect(data.pages).toHaveLength(2);
expect(requests.map((url) => url.search)).toEqual([
"?limit=20",
"?limit=20&cursor=cursor_page_2",
]);
});
it("rejects a page that does not match the contract", async () => {
stubRelativeFetch();
server.use(
http.get(historyUrl, () =>
HttpResponse.json({
items: [{ attempt_id: "not-a-result" }],
page: { has_more: false, next_cursor: null },
}),
),
);
const queryClient = signedInClient();
await expect(
queryClient.fetchInfiniteQuery(
assessmentResultHistoryOptions({ actor: session, queryClient }),
),
).rejects.toMatchObject({ code: invalidResponseCode });
});
it("sends no request when the cached session is not the actor session", async () => {
stubRelativeFetch();
const requested = vi.fn();
server.use(
http.get(historyUrl, () => {
requested();
return HttpResponse.json({ items: [], page: { has_more: false, next_cursor: null } });
}),
);
const queryClient = new QueryClient();
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
...session,
account: { ...session.account, id: "22222222-2222-4222-8222-222222222222" },
});
await expect(
queryClient.fetchInfiniteQuery(
assessmentResultHistoryOptions({ actor: session, queryClient }),
),
).rejects.toThrow("candidate session changed");
expect(requested).not.toHaveBeenCalled();
});
it("keeps the history of different sessions under different keys", () => {
const queryClient = signedInClient();
const mine = assessmentResultHistoryOptions({ actor: session, queryClient }).queryKey;
const other = assessmentResultHistoryOptions({
actor: { ...session, csrf_token: "B".repeat(43) },
queryClient,
}).queryKey;
expect(mine).not.toEqual(other);
expect(mine).toContain(session.account.id);
});
});
@@ -1,9 +1,15 @@
import { useQuery, type QueryClient } from "@tanstack/react-query";
import {
infiniteQueryOptions,
useInfiniteQuery,
useQuery,
type QueryClient,
} from "@tanstack/react-query";
import {
acknowledgeMyAssessmentSignalNotice,
getMyAssessmentAvailability,
getMyAssessmentAttempt,
getMyAssessmentResult,
listMyAssessmentResults,
getMyAssessmentSignalNotice,
} from "../../../shared/api/endpoints/assessment/assessment";
import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate";
@@ -11,17 +17,23 @@ import type {
AssessmentAttempt,
AssessmentAvailability,
AssessmentResult,
AssessmentResultHistoryPage,
AssessmentSignalNotice,
Session,
} from "../../../shared/api/schemas";
import {
parseAssessmentAvailabilityResponse,
parseAssessmentAttemptResponse,
parseAssessmentResultHistoryResponse,
parseAssessmentResultResponse,
parseAssessmentSignalNoticeResponse,
parseCandidateQuestionnaireResponse,
} from "../model/contract-validation";
import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session";
import {
assessmentQueryKeys,
assessmentQueryPrefix,
assertCurrentAssessmentSession,
} from "../model/session";
type AssessmentQueryOptions = {
enabled?: boolean;
@@ -45,7 +57,7 @@ export function useAssessmentAvailability({
return useQuery<AssessmentAvailability, Error>({
queryKey: actor
? assessmentQueryKeys.availability(actor)
: [...assessmentQueryKeysPrefix, "availability"],
: [...assessmentQueryPrefix, "availability"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
@@ -65,7 +77,7 @@ export function useAssessmentQuestionnaire({
return useQuery({
queryKey: actor
? assessmentQueryKeys.questionnaire(actor)
: [...assessmentQueryKeysPrefix, "questionnaire"],
: [...assessmentQueryPrefix, "questionnaire"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
@@ -86,7 +98,7 @@ export function useAssessmentAttempt({
return useQuery<AssessmentAttempt, Error>({
queryKey: actor
? assessmentQueryKeys.attempt(actor, attemptId)
: [...assessmentQueryKeysPrefix, "attempt", attemptId],
: [...assessmentQueryPrefix, "attempt", attemptId],
enabled: Boolean(actor && attemptId && enabled),
...privateQueryOptions,
refetchInterval: (query) => {
@@ -111,7 +123,7 @@ export function useAssessmentResult({
return useQuery<AssessmentResult, Error>({
queryKey: actor
? assessmentQueryKeys.result(actor, attemptId)
: [...assessmentQueryKeysPrefix, "result", attemptId],
: [...assessmentQueryPrefix, "result", attemptId],
enabled: Boolean(actor && attemptId && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
@@ -123,6 +135,47 @@ export function useAssessmentResult({
});
}
/** Page size of the result history; the contract allows 1 to 50. */
export const assessmentHistoryPageSize = 20;
/**
* Options of the result history query. The cursor is opaque and comes from
* the server; it is never built or stored by the client. Express runs are
* not part of this list by contract.
*/
export function assessmentResultHistoryOptions({
actor,
enabled = true,
queryClient,
}: AssessmentQueryOptions) {
return infiniteQueryOptions({
queryKey: actor
? assessmentQueryKeys.resultHistory(actor)
: [...assessmentQueryPrefix, "result-history"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
initialPageParam: null as string | null,
getNextPageParam: (last: AssessmentResultHistoryPage) =>
last.page.has_more ? last.page.next_cursor : undefined,
queryFn: async ({ pageParam, signal }) => {
assertCurrentAssessmentSession(queryClient, actor);
const response = await listMyAssessmentResults(
pageParam
? { limit: assessmentHistoryPageSize, cursor: pageParam }
: { limit: assessmentHistoryPageSize },
{ signal },
);
assertCurrentAssessmentSession(queryClient, actor);
return parseAssessmentResultHistoryResponse(response);
},
});
}
/** Immutable real results of the current candidate, newest first. */
export function useAssessmentResultHistory(options: AssessmentQueryOptions) {
return useInfiniteQuery(assessmentResultHistoryOptions(options));
}
/**
* Server-owned state of the notice about the collected signals. It is read
* again on mount so an acknowledgement made in another window or browser is
@@ -136,7 +189,7 @@ export function useAssessmentSignalNotice({
return useQuery<AssessmentSignalNotice, Error>({
queryKey: actor
? assessmentQueryKeys.signalNotice(actor)
: [...assessmentQueryKeysPrefix, "signal-notice"],
: [...assessmentQueryPrefix, "signal-notice"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
@@ -168,5 +221,3 @@ export async function acknowledgeAssessmentSignalNotice(
queryClient.setQueryData(assessmentQueryKeys.signalNotice(actor), notice);
return notice;
}
const assessmentQueryKeysPrefix = ["candidate-assessment"] as const;
+22
View File
@@ -1,9 +1,12 @@
export {
acknowledgeAssessmentSignalNotice,
assessmentHistoryPageSize,
assessmentResultHistoryOptions,
useAssessmentAttempt,
useAssessmentAvailability,
useAssessmentQuestionnaire,
useAssessmentResult,
useAssessmentResultHistory,
useAssessmentSignalNotice,
} from "./api/assessment-queries";
export {
@@ -18,9 +21,28 @@ export {
export { isOutcomeAmbiguous } from "./model/idempotency";
export {
parseAssessmentAttemptResponse,
parseAssessmentResultHistoryResponse,
parseAssessmentResultResponse,
} from "./model/contract-validation";
export { assessmentResultSummary } from "./model/result-summary";
export {
describeAssessmentResult,
formatResultDate,
formatResultDay,
type AssessmentResultPresentation,
} from "./model/result-presentation";
export {
isAssessmentAccessLoss,
isAssessmentSessionEnded,
useAssessmentActor,
} from "./model/use-assessment-actor";
export {
actorIdentity,
shouldPurgeAssessmentCache,
trackActorIdentity,
} from "./model/actor-transition";
export { AssessmentActorGate } from "./ui/assessment-actor-gate";
export { AssessmentResultView } from "./ui/assessment-result-view";
export {
availabilityLabels,
gradeLabels,
@@ -0,0 +1,102 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
import { actorIdentity, shouldPurgeAssessmentCache, trackActorIdentity } from "./actor-transition";
import { demoBasicAssigned } from "./result.fixtures";
import { assessmentQueryKeys } from "./session";
function sessionFor(accountId: string, csrfToken: string): Session {
return {
account: {
id: accountId,
email: "person@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: csrfToken,
};
}
const first = sessionFor("11111111-1111-4111-8111-111111111111", "A".repeat(43));
const attemptId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff";
/** A client that holds the first account's cached assessment answers. */
function seededClient(): QueryClient {
const queryClient = new QueryClient();
queryClient.setQueryData(getGetCurrentSessionQueryKey(), first);
queryClient.setQueryData(assessmentQueryKeys.result(first, attemptId), demoBasicAssigned());
queryClient.setQueryData(assessmentQueryKeys.resultHistory(first), {
pages: [{ items: [demoBasicAssigned()], page: { has_more: false, next_cursor: null } }],
pageParams: [null],
});
queryClient.setQueryData(["unrelated"], "kept");
return queryClient;
}
function assessmentEntries(queryClient: QueryClient): number {
return queryClient.getQueryCache().findAll({ queryKey: ["candidate-assessment"] }).length;
}
describe("shouldPurgeAssessmentCache", () => {
const before = actorIdentity(first, true);
it("keeps the cache while the identity is the same", () => {
expect(shouldPurgeAssessmentCache(before, actorIdentity(first, true))).toBe(false);
});
it("purges when the account changes", () => {
const other = sessionFor("22222222-2222-4222-8222-222222222222", first.csrf_token);
expect(shouldPurgeAssessmentCache(before, actorIdentity(other, true))).toBe(true);
});
it("purges when the session token changes for the same account", () => {
const renewed = sessionFor(first.account.id, "B".repeat(43));
expect(shouldPurgeAssessmentCache(before, actorIdentity(renewed, true))).toBe(true);
});
it("purges when the session is lost and has nothing to purge before one exists", () => {
expect(shouldPurgeAssessmentCache(before, actorIdentity(first, false))).toBe(true);
expect(shouldPurgeAssessmentCache(null, actorIdentity(first, true))).toBe(false);
});
});
describe("trackActorIdentity on a real query client", () => {
it("removes only the assessment queries when the account changes", () => {
const queryClient = seededClient();
expect(assessmentEntries(queryClient)).toBe(2);
const other = sessionFor("22222222-2222-4222-8222-222222222222", "C".repeat(43));
const next = trackActorIdentity(
queryClient,
actorIdentity(first, true),
actorIdentity(other, true),
);
expect(next).toEqual({ accountId: other.account.id, csrfToken: other.csrf_token });
expect(assessmentEntries(queryClient)).toBe(0);
expect(queryClient.getQueryData(assessmentQueryKeys.result(first, attemptId))).toBeUndefined();
expect(queryClient.getQueryData(assessmentQueryKeys.resultHistory(first))).toBeUndefined();
expect(queryClient.getQueryData(["unrelated"])).toBe("kept");
expect(queryClient.getQueryData(getGetCurrentSessionQueryKey())).toEqual(first);
});
it("removes them when the session token changes", () => {
const queryClient = seededClient();
const renewed = sessionFor(first.account.id, "B".repeat(43));
trackActorIdentity(queryClient, actorIdentity(first, true), actorIdentity(renewed, true));
expect(assessmentEntries(queryClient)).toBe(0);
});
it("removes them when the session ends", () => {
const queryClient = seededClient();
trackActorIdentity(queryClient, actorIdentity(first, true), null);
expect(assessmentEntries(queryClient)).toBe(0);
});
it("keeps them while nothing changed", () => {
const queryClient = seededClient();
trackActorIdentity(queryClient, actorIdentity(first, true), actorIdentity(first, true));
expect(assessmentEntries(queryClient)).toBe(2);
});
});
@@ -0,0 +1,36 @@
import type { QueryClient } from "@tanstack/react-query";
import type { Session } from "../../../shared/api/schemas";
import { removeAssessmentQueries } from "./session";
export type ActorIdentity = {
readonly accountId: string;
readonly csrfToken: string;
};
/** The identity of a confirmed session, or null while there is none. */
export function actorIdentity(actor: Session | undefined, ready: boolean): ActorIdentity | null {
return actor && ready ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
}
/**
* Cached assessment data belongs to one session. It must go when the account
* changes, when the session token changes (a new sign-in), or when the
* session is lost.
*/
export function shouldPurgeAssessmentCache(
before: ActorIdentity | null,
next: ActorIdentity | null,
): boolean {
if (!before) return false;
return !next || before.accountId !== next.accountId || before.csrfToken !== next.csrfToken;
}
/** Removes the assessment queries when the identity moved; returns the new one. */
export function trackActorIdentity(
queryClient: QueryClient,
before: ActorIdentity | null,
next: ActorIdentity | null,
): ActorIdentity | null {
if (shouldPurgeAssessmentCache(before, next)) removeAssessmentQueries(queryClient);
return next;
}
@@ -3,11 +3,13 @@ import {
AssessmentAttempt as assessmentAttemptSchema,
AssessmentAvailability as assessmentAvailabilitySchema,
AssessmentResult as assessmentResultSchema,
AssessmentResultHistoryPage as assessmentResultHistoryPageSchema,
AssessmentSignalNotice as assessmentSignalNoticeSchema,
CandidateQuestionnaire as candidateQuestionnaireSchema,
type AssessmentAttempt,
type AssessmentAvailability,
type AssessmentResult,
type AssessmentResultHistoryPage,
type AssessmentSignalNotice,
type CandidateQuestionnaire,
} from "../../../shared/api/schemas";
@@ -50,6 +52,15 @@ export function parseAssessmentResultResponse(value: unknown, status = 200): Ass
return parsed.data;
}
export function parseAssessmentResultHistoryResponse(
value: unknown,
status = 200,
): AssessmentResultHistoryPage {
const parsed = assessmentResultHistoryPageSchema.safeParse(value);
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
export function parseAssessmentSignalNoticeResponse(
value: unknown,
status = 200,
@@ -0,0 +1,305 @@
import { describe, expect, it } from "vitest";
import { parseAssessmentResultResponse } from "./contract-validation";
import {
describeAssessmentResult,
formatDecimal,
formatDuration,
type AssessmentResultPresentation,
} from "./result-presentation";
import {
adaptiveConfirmed,
decisionFixture,
demoBasicAssigned,
expressFixture,
notConfirmedAfterJunior,
} from "./result.fixtures";
const options = { timeZone: "UTC" } as const;
const categoryLabel = "Категория после этого результата";
function fact(view: AssessmentResultPresentation, label: string): string | undefined {
return view.facts.find((item) => item.label === label)?.value;
}
describe("result fixtures", () => {
it("match the response contract", () => {
for (const result of [
demoBasicAssigned(),
adaptiveConfirmed(),
notConfirmedAfterJunior(),
expressFixture(),
]) {
expect(() => parseAssessmentResultResponse(result)).not.toThrow();
}
});
});
describe("describeAssessmentResult for a demo_basic result", () => {
const view = describeAssessmentResult(demoBasicAssigned(), options);
it("shows the category, date, method, and the provisional status", () => {
expect(fact(view, categoryLabel)).toBe("Backend, Middle (присвоена этим результатом)");
expect(fact(view, "Дата решения")).toBe("8 октября 2026 г. в 09:30 UTC");
expect(fact(view, "Метод")).toBe("Базовая проверка по фиксированному набору заданий");
expect(fact(view, "Статус")).toBe("предварительный, пороги не калибровались");
expect(fact(view, "Происхождение решения")).toBe("синтетическая демонстрация стенда");
expect(view.isProvisional).toBe(true);
});
it("states the method limitation and invents no percentile or estimate", () => {
expect(view.methodLimitation).toContain("Перцентиль");
expect(view.methodLimitation).toContain("не рассчитываются");
expect(view.uncertainty).toBeNull();
expect(view.uncertaintyNote).toBeNull();
expect(view.strength).toBeNull();
expect(view.score).toBe("17 из 20, проходной балл 14");
expect(view.limitations).toContain(
"Результат получен на небольшом проверенном демонстрационном банке заданий.",
);
});
});
describe("describeAssessmentResult for an adaptive result", () => {
it("shows the actual theta, SE, interval, P_G, strength, gap, and retry date", () => {
const view = describeAssessmentResult(adaptiveConfirmed(), options);
expect(view.uncertainty).toEqual({
theta: "0,42",
standardError: "0,21",
interval: "от −0,19 до 1,03",
pGrade: "0,80",
});
expect(view.strength).toBe("средняя");
expect(view.gaps).toEqual(["Базы данных"]);
expect(view.practices).toEqual(["Основная практика: 2 из 3"]);
expect(view.durations).toEqual(["Задания: 25 мин", "Практика: 12 мин"]);
expect(view.nextSteps).toEqual([
{
action: "take_higher_grade",
text: "Пройти проверку на более высокий уровень: Senior.",
availability: "Доступно с 12 ноября 2026 г. в 10:00 UTC.",
leadsToTest: true,
isOffer: false,
},
]);
});
it("never replaces missing uncertainty fields with zeros", () => {
const view = describeAssessmentResult(
adaptiveConfirmed({ uncertainty: null, strength: null, gaps: [], practices: [] }),
options,
);
expect(view.uncertainty).toBeNull();
expect(view.strength).toBeNull();
expect(view.uncertaintyNote).toBe(
"Сервер не вернул оценку способности и неопределенности для этой попытки.",
);
expect(view.gapsNote).toBe("Сервер не отметил областей со слабыми доказательствами.");
expect(JSON.stringify(view)).not.toContain("0,00");
});
it("keeps a real zero estimate as a value", () => {
const view = describeAssessmentResult(
adaptiveConfirmed({
uncertainty: {
theta: 0,
standard_error: 0.5,
interval_95: { low: -0.98, high: 0.98 },
p_grade: 0.5,
},
}),
options,
);
expect(view.uncertainty?.theta).toBe("0,00");
expect(view.uncertainty?.pGrade).toBe("0,50");
});
it("calls calibrated thresholds calibrated only when the server says so", () => {
const view = describeAssessmentResult(
adaptiveConfirmed({
calibration_status: "calibrated",
category_decision: decisionFixture("assigned", {
current_confirmed_grade: "middle",
calibration_status: "calibrated",
}),
}),
options,
);
expect(view.isProvisional).toBe(false);
expect(fact(view, "Статус")).toBe("пороги откалиброваны");
});
});
describe("describeAssessmentResult for a failed attempt", () => {
const view = describeAssessmentResult(notConfirmedAfterJunior(), options);
it("keeps the previous grade and shows the attempt result separately", () => {
expect(view.summary.text).toBe("Уровень пока не подтвержден: Backend, Middle.");
expect(view.summary.reason).toBe("Прежний подтвержденный уровень Junior сохраняется.");
expect(fact(view, categoryLabel)).toBe("Backend, Junior (прежняя, сохраняется)");
});
it("takes every next step from the server, in its order", () => {
expect(view.nextSteps.map((step) => step.action)).toEqual([
"retake_same_grade",
"take_lower_grade",
"accept_lower_grade",
]);
expect(view.nextSteps[0]?.availability).toBe("Доступно с 7 ноября 2026 г. в 09:30 UTC.");
expect(view.nextSteps[1]?.availability).toBe(
"Было доступно сразу на момент решения, без ожидания пересдачи.",
);
});
it("presents accepting a lower grade as an offer, not as a done change", () => {
const offer = view.nextSteps[2];
expect(offer?.isOffer).toBe(true);
expect(offer?.leadsToTest).toBe(false);
expect(offer?.text).toContain("предлагает");
expect(fact(view, categoryLabel)).not.toContain("Junior (присвоена");
});
it("says what stays true when there was no earlier grade", () => {
const first = describeAssessmentResult(
notConfirmedAfterJunior({
previous_confirmed_grade: null,
category_decision: decisionFixture("not_confirmed"),
}),
options,
);
expect(fact(first, categoryLabel)).toBe("не присвоена");
expect(first.categoryNote).toContain("ничего не понижает");
});
it("reports an empty list of next steps instead of inventing one", () => {
const none = describeAssessmentResult(notConfirmedAfterJunior({ next_steps: [] }), options);
expect(none.nextSteps).toEqual([]);
expect(none.nextStepsNote).toBe("Сервер не вернул следующих шагов для этого результата.");
});
});
describe("describeAssessmentResult for a result without a category", () => {
it("does not show a category when the threshold passed but none was assigned", () => {
const view = describeAssessmentResult(
demoBasicAssigned({
confirmed_grade: null,
category_decision: decisionFixture("not_eligible", {
method: null,
source: null,
calibration_status: null,
}),
}),
options,
);
expect(fact(view, categoryLabel)).toBe("не присвоена");
expect(view.summary.text).toContain("категория не присвоена");
});
it("keeps the higher category when a reviewed result is unchanged", () => {
const view = describeAssessmentResult(
demoBasicAssigned({
previous_confirmed_grade: "senior",
category_decision: decisionFixture("unchanged", {
previous_confirmed_grade: "senior",
current_confirmed_grade: "senior",
}),
}),
options,
);
expect(fact(view, categoryLabel)).toBe("Backend, Senior (без изменений)");
});
});
describe("describeAssessmentResult for old and unassigned results", () => {
it("says the decision was not stored for a result without category_decision", () => {
const view = describeAssessmentResult(
demoBasicAssigned({ confirmed_grade: null, category_decision: undefined }),
options,
);
expect(fact(view, categoryLabel)).toBe("решение о категории не сохранено");
});
it("shows the kept category when the threshold passed but nothing was assigned", () => {
const view = describeAssessmentResult(
demoBasicAssigned({
confirmed_grade: null,
previous_confirmed_grade: "junior",
category_decision: decisionFixture("not_eligible", {
previous_confirmed_grade: "junior",
current_confirmed_grade: "junior",
method: null,
source: null,
calibration_status: null,
}),
}),
options,
);
expect(fact(view, categoryLabel)).toBe("Backend, Junior (прежняя, сохраняется)");
});
it("marks next steps as computed at the decision time", () => {
const view = describeAssessmentResult(adaptiveConfirmed(), options);
expect(view.nextSteps[0]?.availability).toBe("Доступно с 12 ноября 2026 г. в 10:00 UTC.");
const immediate = describeAssessmentResult(demoBasicAssigned(), options);
expect(immediate.nextSteps[0]?.availability).toBe("Было доступно сразу на момент решения.");
});
it("does not round a near-certain probability up to one", () => {
const view = describeAssessmentResult(
adaptiveConfirmed({
uncertainty: {
theta: 1.2,
standard_error: 0.0004,
interval_95: { low: 1.19, high: 1.21 },
p_grade: 0.9996,
},
}),
options,
);
expect(view.uncertainty?.pGrade).toBe("больше 0,999");
expect(view.uncertainty?.standardError).toBe("меньше 0,001");
});
});
describe("describeAssessmentResult for an express result", () => {
const view = describeAssessmentResult(expressFixture(), options);
it("is a demonstration without a category, estimate, or next steps", () => {
expect(view.isExpress).toBe(true);
expect(fact(view, "Категория")).toBe("не присваивается");
expect(fact(view, "Статус")).toBe("демонстрация");
expect(view.expressSummary).toBe("Вы ответили на три учебных задания.");
expect(view.uncertainty).toBeNull();
expect(view.score).toBeNull();
expect(view.nextSteps).toEqual([]);
expect(view.nextStepsNote).toBeNull();
expect(view.limitations).toEqual([
"Запуск служит демонстрацией механики и не является квалификационной оценкой.",
]);
});
});
describe("number and duration formats", () => {
it("uses a comma with two to three fraction digits", () => {
expect(formatDecimal(0.8)).toBe("0,80");
expect(formatDecimal(0.853)).toBe("0,853");
expect(formatDecimal(-0.1999)).toBe("−0,20");
});
it("never shows a nonzero value as zero or a probability as one", () => {
expect(formatDecimal(0.0004, 1)).toBe("меньше 0,001");
expect(formatDecimal(0.0004)).toBe("меньше 0,001");
expect(formatDecimal(0.001)).toBe("0,001");
expect(formatDecimal(0)).toBe("0,00");
expect(formatDecimal(1, 1)).toBe("1,00");
expect(formatDecimal(0.9996, 1)).toBe("больше 0,999");
expect(formatDecimal(0.999, 1)).toBe("0,999");
expect(formatDecimal(-0.0004)).toBe("больше −0,001");
expect(formatDecimal(-0.19)).toBe("−0,19");
});
it("formats durations from seconds", () => {
expect(formatDuration(45)).toBe("45 сек");
expect(formatDuration(754)).toBe("12 мин 34 сек");
expect(formatDuration(3720)).toBe("1 ч 2 мин");
});
});
@@ -0,0 +1,368 @@
import type {
AssessmentLimitation,
AssessmentNextAction,
AssessmentResult,
GradeCode,
} from "../../../shared/api/schemas";
import { gradeLabels, methodLabel, specializationLabels } from "./labels";
import { assessmentResultSummary, type AssessmentResultSummary } from "./result-summary";
/** A result that can change the candidate category (root or corrective). */
type RealResult = Exclude<AssessmentResult, { kind: "demo_express" }>;
export type ResultFact = {
readonly label: string;
readonly value: string;
};
/** Ability estimate of an adaptive attempt, exactly as the server returned it. */
export type ResultUncertaintyView = {
readonly theta: string;
readonly standardError: string;
readonly interval: string;
readonly pGrade: string;
};
export type ResultNextStepView = {
readonly action: AssessmentNextAction;
/** What the server allows, in one sentence. */
readonly text: string;
/** When the step opens, or null when the server gave no extra note. */
readonly availability: string | null;
/** True when the step starts a test, so the screen may link to the checks. */
readonly leadsToTest: boolean;
/** True for an offer that changes the category only by a later command. */
readonly isOffer: boolean;
};
export type AssessmentResultPresentation = {
readonly isExpress: boolean;
readonly attemptId: string;
/** Specialization and target grade, or the express title. */
readonly title: string;
readonly kindLabel: string;
/** Decision date without the time, for short names. */
readonly decidedDay: string;
readonly summary: AssessmentResultSummary;
/** The server feedback text of an express run, otherwise null. */
readonly expressSummary: string | null;
/** Category, date, method, and the provisional status as label-value rows. */
readonly facts: readonly ResultFact[];
/** Extra sentence about the category, or null when the summary says it all. */
readonly categoryNote: string | null;
readonly isProvisional: boolean;
/** Plain statement about what the method does and does not measure. */
readonly methodLimitation: string;
readonly limitations: readonly string[];
/** Raw score of a demo_basic attempt, or null when none was recorded. */
readonly score: string | null;
readonly uncertainty: ResultUncertaintyView | null;
/** Why no uncertainty is shown, or null when it is shown or not expected. */
readonly uncertaintyNote: string | null;
readonly strength: string | null;
readonly gaps: readonly string[];
readonly gapsNote: string | null;
readonly practices: readonly string[];
readonly durations: readonly string[];
readonly nextSteps: readonly ResultNextStepView[];
/** Said when the server returned no next step for this result. */
readonly nextStepsNote: string | null;
};
export type ResultPresentationOptions = {
/** IANA zone for dates; the browser zone when omitted. Tests pin it. */
readonly timeZone?: string;
};
const limitationLabels: Readonly<Record<AssessmentLimitation | "demonstration_only", string>> = {
uncalibrated_thresholds: "Пороги пока не проверены на пилотной выборке.",
demo_bank: "Результат получен на небольшом проверенном демонстрационном банке заданий.",
practice_not_included: "В попытке не было кодовой практики: песочница не была включена.",
unproctored: "Проверка пройдена онлайн без наблюдения.",
demonstration_only:
"Запуск служит демонстрацией механики и не является квалификационной оценкой.",
};
const strengthLabels = {
high: "высокая",
medium: "средняя",
} as const;
const practiceKindLabels = {
main: "Основная практика",
additional: "Дополнительная практика",
} as const;
export function formatResultDate(value: string, timeZone?: string): string {
return new Intl.DateTimeFormat("ru-RU", {
day: "numeric",
month: "long",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
timeZoneName: "short",
...(timeZone ? { timeZone } : {}),
}).format(new Date(value));
}
/** Date without the time, for names that must stay short. */
export function formatResultDay(value: string, timeZone?: string): string {
return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "long",
...(timeZone ? { timeZone } : {}),
}).format(new Date(value));
}
const minusSign = "\u2212";
/**
* Decimal with a comma, the typographic minus, and two to three fraction
* digits. The value is only rounded for display and a nonzero value never
* shows as zero: a tiny positive value reads "меньше 0,001". With `upperBound`
* (a probability), a value just below it reads "больше 0,999" instead of
* rounding up to the bound.
*/
export function formatDecimal(value: number, upperBound?: number): string {
if (value > 0 && value < 0.001) return "меньше 0,001";
if (value < 0 && value > -0.001) return `больше ${minusSign}0,001`;
if (upperBound !== undefined && value < upperBound && value > upperBound - 0.001) {
return `больше ${formatDecimal(upperBound - 0.001)}`;
}
let text = Math.abs(value).toFixed(3);
if (text.endsWith("0")) text = text.slice(0, -1);
return `${value < 0 ? minusSign : ""}${text.replace(".", ",")}`;
}
export function formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const rest = seconds % 60;
if (hours > 0) return minutes > 0 ? `${hours} ч ${minutes} мин` : `${hours} ч`;
if (minutes === 0) return `${rest} сек`;
return rest > 0 ? `${minutes} мин ${rest} сек` : `${minutes} мин`;
}
function categoryName(result: RealResult, grade: GradeCode): string {
return `${specializationLabels[result.specialization]}, ${gradeLabels[grade]}`;
}
/**
* The category in force after this result, as the server recorded it. A
* grade is taken only from the decision or from the confirmed fields, never
* from the target grade.
*/
function categoryFact(result: RealResult): string {
const decision = result.category_decision;
if (decision?.status === "assigned" || decision?.status === "unchanged") {
const grade = decision.current_confirmed_grade ?? result.confirmed_grade;
if (grade) {
return decision.status === "assigned"
? `${categoryName(result, grade)} (присвоена этим результатом)`
: `${categoryName(result, grade)} (без изменений)`;
}
}
const kept = decision?.current_confirmed_grade ?? result.previous_confirmed_grade;
if (kept && (decision !== undefined || result.outcome !== "confirmed")) {
return `${categoryName(result, kept)} (прежняя, сохраняется)`;
}
// A result stored before category decisions cannot say what the category was.
return decision === undefined ? "решение о категории не сохранено" : "не присвоена";
}
/** A failed attempt with no earlier grade: say what stays true. */
function failedWithoutGradeNote(result: RealResult): string | null {
if (result.outcome === "confirmed") return null;
const kept = result.category_decision?.current_confirmed_grade ?? result.previous_confirmed_grade;
if (kept) return null;
return "По этой специализации еще нет подтвержденного уровня. Неудачная попытка ничего не понижает.";
}
function methodLimitationText(result: AssessmentResult): string {
if (result.kind === "demo_express") {
return "Экспресс-запуск показывает механику проверки. Он не создает категорию, перцентиль, оценку неопределенности и квалификационные доказательства.";
}
if (result.mode === "demo_basic") {
return "Базовая проверка считает только баллы по фиксированному набору заданий и сравнивает их с проходным баллом. Перцентиль, оценка способности, интервал, вероятность P_G и сила подтверждения не рассчитываются.";
}
return "Адаптивная проверка оценивает способность на шкале специализации. Оценка способности, интервал и вероятность P_G не являются баллом или перцентилем.";
}
function isProvisional(result: AssessmentResult): boolean {
if (result.kind === "demo_express") return true;
return (
result.calibration_status === "uncalibrated" ||
result.category_decision?.calibration_status === "uncalibrated"
);
}
function uncertaintyView(result: RealResult): ResultUncertaintyView | null {
const value = result.uncertainty;
if (!value) return null;
return {
theta: formatDecimal(value.theta),
standardError: formatDecimal(value.standard_error),
interval: `от ${formatDecimal(value.interval_95.low)} до ${formatDecimal(value.interval_95.high)}`,
pGrade: formatDecimal(value.p_grade, 1),
};
}
function nextStepView(
step: RealResult["next_steps"][number],
timeZone: string | undefined,
): ResultNextStepView {
const grade = gradeLabels[step.grade];
const date = step.available_at ? formatResultDate(step.available_at, timeZone) : null;
switch (step.action) {
case "retake_same_grade":
return {
action: step.action,
text: `Пересдать тот же уровень: ${grade}.`,
availability: date ? `Доступно с ${date}.` : "Было доступно сразу на момент решения.",
leadsToTest: true,
isOffer: false,
};
case "take_lower_grade":
return {
action: step.action,
text: `Пройти проверку на меньший уровень: ${grade}.`,
availability: date
? `Доступно с ${date}.`
: "Было доступно сразу на момент решения, без ожидания пересдачи.",
leadsToTest: true,
isOffer: false,
};
case "accept_lower_grade":
return {
action: step.action,
text: `Сервер предлагает принять меньший уровень ${grade} по данным этой попытки.`,
availability: date ? `Доступно с ${date}.` : null,
leadsToTest: false,
isOffer: true,
};
case "take_higher_grade":
return {
action: step.action,
text: `Пройти проверку на более высокий уровень: ${grade}.`,
availability: date ? `Доступно с ${date}.` : "Было доступно сразу на момент решения.",
leadsToTest: true,
isOffer: false,
};
}
}
function limitationList(result: AssessmentResult): string[] {
return result.limitations.map((code) => limitationLabels[code]);
}
function expressPresentation(
result: Extract<AssessmentResult, { kind: "demo_express" }>,
options: ResultPresentationOptions,
): AssessmentResultPresentation {
return {
isExpress: true,
attemptId: result.attempt_id,
title: methodLabel("demo_express"),
kindLabel: "Демонстрация без реального грейда",
decidedDay: formatResultDay(result.decided_at, options.timeZone),
summary: assessmentResultSummary(result),
expressSummary: result.summary,
facts: [
{ label: "Категория", value: "не присваивается" },
{ label: "Дата", value: formatResultDate(result.decided_at, options.timeZone) },
{ label: "Метод", value: methodLabel("demo_express") },
{ label: "Статус", value: "демонстрация" },
],
categoryNote: null,
isProvisional: true,
methodLimitation: methodLimitationText(result),
limitations: limitationList(result),
score: null,
uncertainty: null,
uncertaintyNote: null,
strength: null,
gaps: [],
gapsNote: null,
practices: [],
durations: durationList(result),
nextSteps: [],
nextStepsNote: null,
};
}
function durationList(result: AssessmentResult): string[] {
const durations: string[] = [`Задания: ${formatDuration(result.durations.items_seconds)}`];
if (result.durations.practice_seconds !== null) {
durations.push(`Практика: ${formatDuration(result.durations.practice_seconds)}`);
}
return durations;
}
/**
* Turns a stored result into display values. It restates server fields only:
* a field the server left null stays absent, no grade is derived, and an
* absent estimate is never shown as zero.
*/
export function describeAssessmentResult(
result: AssessmentResult,
options: ResultPresentationOptions = {},
): AssessmentResultPresentation {
if (result.kind === "demo_express") return expressPresentation(result, options);
const decision = result.category_decision;
const facts: ResultFact[] = [
{ label: "Категория после этого результата", value: categoryFact(result) },
{ label: "Дата решения", value: formatResultDate(result.decided_at, options.timeZone) },
{ label: "Метод", value: methodLabel(result.mode) },
{
label: "Статус",
value: isProvisional(result)
? "предварительный, пороги не калибровались"
: "пороги откалиброваны",
},
];
if (decision?.source === "synthetic_demo") {
facts.push({ label: "Происхождение решения", value: "синтетическая демонстрация стенда" });
}
const uncertainty = uncertaintyView(result);
const basic = result.basic_score;
return {
isExpress: false,
attemptId: result.attempt_id,
title: `${specializationLabels[result.specialization]}, ${gradeLabels[result.target_grade]}`,
decidedDay: formatResultDay(result.decided_at, options.timeZone),
kindLabel:
result.kind === "corrective" ? "Проверка меньшего уровня после неудачи" : "Основная проверка",
summary: assessmentResultSummary(result),
expressSummary: null,
facts,
categoryNote: failedWithoutGradeNote(result),
isProvisional: isProvisional(result),
methodLimitation: methodLimitationText(result),
limitations: limitationList(result),
score: basic
? `${basic.points} из ${basic.max_points}, проходной балл ${basic.pass_points}`
: null,
uncertainty,
uncertaintyNote:
uncertainty === null && result.mode === "adaptive"
? "Сервер не вернул оценку способности и неопределенности для этой попытки."
: null,
strength: result.strength ? strengthLabels[result.strength] : null,
gaps: result.gaps.map((gap) => gap.title),
gapsNote:
result.gaps.length === 0 && result.mode === "adaptive"
? "Сервер не отметил областей со слабыми доказательствами."
: null,
practices: result.practices.map(
(practice) =>
`${practiceKindLabels[practice.kind]}: ${practice.verdict.score} из ${practice.verdict.max_score}`,
),
durations: durationList(result),
nextSteps: result.next_steps.map((step) => nextStepView(step, options.timeZone)),
nextStepsNote:
result.next_steps.length === 0
? "Сервер не вернул следующих шагов для этого результата."
: null,
};
}
@@ -50,10 +50,22 @@ describe("assessmentResultSummary", () => {
}),
);
expect(summary.text).toBe("Уровень подтвержден: Backend, Middle.");
expect(summary.reason).toBe("Это демонстрационная категория: пороги не калибровались.");
expect(summary.isDemonstration).toBe(false);
});
it("names the demonstration bank only when the server lists it", () => {
const summary = assessmentResultSummary(
result({
outcome: "confirmed",
confirmed_grade: "middle",
limitations: ["demo_bank"],
category_decision: decision("assigned", { current_confirmed_grade: "middle" }),
}),
);
expect(summary.reason).toBe(
"Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный.",
);
expect(summary.isDemonstration).toBe(false);
});
it("keeps the higher grade when a reviewed result does not change the category", () => {
@@ -70,7 +82,7 @@ describe("assessmentResultSummary", () => {
);
expect(summary.text).toBe("Уровень подтвержден: Backend, Middle.");
expect(summary.reason).toBe(
"Прежний подтвержденный уровень Senior сохраняется. Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный.",
"Прежний подтвержденный уровень Senior сохраняется. Это демонстрационная категория: пороги не калибровались.",
);
});
@@ -90,6 +102,36 @@ describe("assessmentResultSummary", () => {
expect(summary.reason).toBeNull();
});
it("describes an adaptive result only by the flags the server set", () => {
const decision_ = decision("assigned", { current_confirmed_grade: "middle" });
const uncalibratedOnly = assessmentResultSummary(
result({
mode: "adaptive",
outcome: "confirmed",
confirmed_grade: "middle",
limitations: ["unproctored"],
category_decision: decision_,
}),
);
expect(uncalibratedOnly.reason).toBe("Результат предварительный: пороги не калибровались.");
expect(uncalibratedOnly.reason).not.toContain("демонстрационн");
const withBank = assessmentResultSummary(
result({
mode: "adaptive",
outcome: "confirmed",
confirmed_grade: "middle",
calibration_status: "calibrated",
limitations: ["demo_bank"],
category_decision: decision("assigned", {
current_confirmed_grade: "middle",
calibration_status: "calibrated",
}),
}),
);
expect(withBank.reason).toBe("Результат предварительный: банк заданий демонстрационный.");
});
it("says that the threshold was reached but no category was assigned", () => {
const summary = assessmentResultSummary(
result({
@@ -64,16 +64,20 @@ export function assessmentResultSummary(result: AssessmentResult): AssessmentRes
isDemonstration,
};
}
const demonstrational =
const flags = [
result.category_decision?.calibration_status === "uncalibrated" ||
result.calibration_status === "uncalibrated" ||
result.limitations.includes("demo_bank");
const reason = [
decisionStatus === "unchanged" ? keptGrade : null,
demonstrational
? "Это демонстрационная категория: пороги не калибровались, банк заданий демонстрационный."
result.calibration_status === "uncalibrated"
? "пороги не калибровались"
: null,
]
result.limitations.includes("demo_bank") ? "банк заданий демонстрационный" : null,
].filter(Boolean);
// Only the basic method yields a demonstration category; other methods
// are described by the flags the server actually set.
const caveat =
flags.length === 0
? null
: `${result.mode === "demo_basic" ? "Это демонстрационная категория" : "Результат предварительный"}: ${flags.join(", ")}.`;
const reason = [decisionStatus === "unchanged" ? keptGrade : null, caveat]
.filter(Boolean)
.join(" ");
return {
@@ -0,0 +1,150 @@
import type { AssessmentResult } from "../../../shared/api/schemas";
/*
* Contract-shaped results for tests. They are inputs, not evidence that the
* backend produces the same values.
*/
type Patch = Record<string, unknown>;
const realBase = {
attempt_id: "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff",
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: null,
previous_confirmed_grade: null,
strength: null,
calibration_status: "uncalibrated",
limitations: ["uncalibrated_thresholds", "demo_bank", "unproctored"],
uncertainty: null,
basic_score: null,
practices: [],
gaps: [],
durations: { items_seconds: 754, practice_seconds: null },
next_steps: [],
decided_at: "2026-10-08T09:30:00Z",
} as const;
function real(patch: Patch): AssessmentResult {
return { ...realBase, ...patch } as unknown as AssessmentResult;
}
export function decisionFixture(status: string, patch: Patch = {}): Patch {
return {
status,
previous_confirmed_grade: null,
current_confirmed_grade: null,
method: "demo_basic_pass_mark",
source: "synthetic_demo",
calibration_status: "uncalibrated",
...patch,
};
}
/** A passed demo_basic attempt that assigned a demonstration category. */
export function demoBasicAssigned(patch: Patch = {}): AssessmentResult {
return real({
confirmed_grade: "middle",
basic_score: { points: 17, max_points: 20, pass_points: 14 },
category_decision: decisionFixture("assigned", { current_confirmed_grade: "middle" }),
next_steps: [{ action: "take_higher_grade", grade: "senior", available_at: null }],
...patch,
});
}
/** An adaptive attempt: P_G = 0.80 with medium strength and full uncertainty. */
export function adaptiveConfirmed(patch: Patch = {}): AssessmentResult {
return real({
mode: "adaptive",
confirmed_grade: "middle",
strength: "medium",
calibration_status: "uncalibrated",
limitations: ["uncalibrated_thresholds", "unproctored"],
uncertainty: {
theta: 0.42,
standard_error: 0.21,
interval_95: { low: -0.19, high: 1.03 },
p_grade: 0.8,
},
gaps: [{ domain: "databases", title: "Базы данных" }],
practices: [
{
kind: "main",
verdict: {
score: 2,
max_score: 3,
groups: [
{ group: 1, passed: true },
{ group: 2, passed: true },
{ group: 3, passed: false },
],
},
},
],
durations: { items_seconds: 1500, practice_seconds: 720 },
category_decision: decisionFixture("assigned", {
current_confirmed_grade: "middle",
method: null,
source: null,
}),
next_steps: [
{ action: "take_higher_grade", grade: "senior", available_at: "2026-11-12T10:00:00Z" },
],
...patch,
});
}
/** A failed attempt after an earlier confirmed grade. */
export function notConfirmedAfterJunior(patch: Patch = {}): AssessmentResult {
return real({
outcome: "not_confirmed",
previous_confirmed_grade: "junior",
basic_score: { points: 8, max_points: 20, pass_points: 14 },
category_decision: decisionFixture("not_confirmed", {
previous_confirmed_grade: "junior",
current_confirmed_grade: "junior",
}),
next_steps: [
{ action: "retake_same_grade", grade: "middle", available_at: "2026-11-07T09:30:00Z" },
{ action: "take_lower_grade", grade: "junior", available_at: null },
{ action: "accept_lower_grade", grade: "junior", available_at: null },
],
...patch,
});
}
export function expressFixture(patch: Patch = {}): AssessmentResult {
return {
attempt_id: "0199b4f2-7c1e-7d3a-9f00-112233445566",
specialization: null,
target_grade: null,
task_language: null,
kind: "demo_express",
mode: "demo_express",
versions: { bank_version: "express-1", algorithm_version: "express-1", policy_version: 1 },
outcome: "demonstration",
not_determined_reason: null,
confirmed_grade: null,
previous_confirmed_grade: null,
strength: null,
calibration_status: "uncalibrated",
limitations: ["demonstration_only"],
uncertainty: null,
basic_score: null,
practices: [],
gaps: [],
durations: { items_seconds: 200, practice_seconds: null },
next_steps: [],
summary: "Вы ответили на три учебных задания.",
decided_at: "2026-10-08T10:00:00Z",
...patch,
} as unknown as AssessmentResult;
}
@@ -47,6 +47,8 @@ export const assessmentQueryKeys = {
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "attempt", attemptId] as const,
result: (actor: Session, attemptId: string) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result", attemptId] as const,
resultHistory: (actor: Session) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result-history"] as const,
signalNotice: (actor: Session) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "signal-notice"] as const,
};
@@ -0,0 +1,54 @@
import { useEffect, useRef } from "react";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import { ApiRequestError } from "../../../shared/api";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
import { actorIdentity, trackActorIdentity, type ActorIdentity } from "./actor-transition";
import { isCurrentAssessmentSession } from "./session";
export type AssessmentActor = {
readonly queryClient: QueryClient;
readonly session: ReturnType<typeof useGetCurrentSession>;
/** The signed-in session, or undefined until the server answers. */
readonly actor: Session | undefined;
/** True when the cached session is the successful candidate session. */
readonly actorReady: boolean;
};
/** Access loss as the API reports it: no session, no right, or not the owner. */
export function isAssessmentAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
}
/** The session itself is gone: only a 401 means that. */
export function isAssessmentSessionEnded(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && error.status === 401;
}
/**
* Current candidate session for the assessment screens. Cached assessment
* data is private to one session: when the account or its session token
* changes, or the session ends, every cached assessment query is dropped so
* the next account never sees it.
*/
export function useAssessmentActor(): AssessmentActor {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const actorReady = Boolean(
actor &&
actor.account.scenario === "candidate" &&
isCurrentAssessmentSession(queryClient, actor),
);
const previous = useRef<ActorIdentity | null>(null);
useEffect(() => {
previous.current = trackActorIdentity(
queryClient,
previous.current,
actorIdentity(actor, actorReady),
);
}, [actor, actorReady, queryClient]);
return { queryClient, session, actor, actorReady };
}
@@ -0,0 +1,50 @@
import type { ReactNode } from "react";
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 { ButtonLink, ErrorState, ForbiddenState, LoadingState } from "../../../shared/ui";
import { useAssessmentActor } from "../model/use-assessment-actor";
type AssessmentActorGateProps = {
/** Rendered only for a confirmed candidate session. */
children: (context: { actor: Session; queryClient: QueryClient }) => ReactNode;
};
function refusesAccess(error: unknown): boolean {
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
}
/**
* Shows the content of an assessment screen only for the current candidate
* session. A refused session or another scenario renders a state instead of
* data; a network or server failure offers a retry instead of claiming that
* access was lost.
*/
export function AssessmentActorGate({ children }: AssessmentActorGateProps) {
const { queryClient, session, actor, actorReady } = useAssessmentActor();
if (session.isError && !refusesAccess(session.error)) {
return (
<ErrorState
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
title="Не удалось проверить вход"
/>
);
}
if (session.isError || (actor && actor.account.scenario !== "candidate")) {
return (
<ForbiddenState
error={session.error}
title="Результаты недоступны"
description="Войдите в кабинет кандидата, чтобы открыть свои результаты."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
);
}
if (session.isPending || !actor) return <LoadingState label="Проверяем вход..." />;
if (!actorReady) return <LoadingState label="Подтверждаем текущий вход..." />;
return <>{children({ actor, queryClient })}</>;
}
@@ -0,0 +1,124 @@
.root {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-inline-start: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-m);
background: var(--color-canvas);
}
.root[data-express="true"] {
border-inline-start-style: dashed;
}
.root p {
margin: 0;
overflow-wrap: anywhere;
}
.header {
display: grid;
gap: var(--space-2);
}
.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-xl);
line-height: var(--line-height-snug);
overflow-wrap: anywhere;
}
.badges {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.badges:empty {
display: none;
}
.badge {
padding: var(--space-1) var(--space-3);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-pill);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-bold);
}
.summary {
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.demo {
font-weight: var(--font-weight-bold);
}
.facts {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
gap: var(--space-3) var(--space-4);
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;
}
.block {
display: grid;
gap: var(--space-3);
min-width: 0;
padding-block-start: var(--space-3);
border-block-start: var(--line-thin) solid var(--color-divider);
}
.block-title {
margin: 0;
font-size: var(--font-size-m);
}
.list,
.steps {
display: grid;
gap: var(--space-2);
margin: 0;
padding-inline-start: var(--space-5);
}
.steps {
gap: var(--space-3);
}
.note {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
@media (width < 42rem) {
.root {
padding: var(--space-3);
}
}
@@ -0,0 +1,113 @@
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import type { AssessmentResult } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
adaptiveConfirmed,
demoBasicAssigned,
expressFixture,
notConfirmedAfterJunior,
} from "../model/result.fixtures";
import { AssessmentResultView } from "./assessment-result-view";
function render(result: AssessmentResult): string {
return renderToStaticMarkup(
<MemoryRouter>
<AssessmentResultView result={result} timeZone="UTC" />
</MemoryRouter>,
);
}
describe("AssessmentResultView for demo_basic", () => {
const html = render(demoBasicAssigned());
it("shows the category, date, method, and provisional status", () => {
expect(html).toContain("Уровень подтвержден: Backend, Middle.");
expect(html).toContain("Backend, Middle (присвоена этим результатом)");
expect(html).toContain("8 октября 2026 г. в 09:30 UTC");
expect(html).toContain("Базовая проверка по фиксированному набору заданий");
expect(html).toContain("Предварительный результат");
expect(html).toContain("предварительный, пороги не калибровались");
});
it("names the method limitation and shows no estimate rows", () => {
expect(html).toContain("Перцентиль, оценка способности, интервал, вероятность P_G");
expect(html).not.toContain("Стандартная ошибка");
expect(html).not.toContain("95% интервал");
expect(html).not.toContain("Сила подтверждения");
expect(html).toContain("17 из 20, проходной балл 14");
});
});
describe("AssessmentResultView for an adaptive result", () => {
it("labels P_G, strength, SE, interval, and the retry date with the returned values", () => {
const html = render(adaptiveConfirmed());
expect(html).toContain("Вероятность достичь порога выбранного грейда (P_G)");
expect(html).toContain("0,80");
expect(html).toContain("Сила подтверждения");
expect(html).toContain("средняя");
expect(html).toContain("Стандартная ошибка (SE)");
expect(html).toContain("0,21");
expect(html).toContain("от −0,19 до 1,03");
expect(html).toContain("Базы данных");
expect(html).toContain("Доступно с 12 ноября 2026 г. в 10:00 UTC.");
expect(html).toContain("остается предварительной оценкой");
});
it("draws no estimate and no zeros once the fields are removed", () => {
const html = render(
adaptiveConfirmed({ uncertainty: null, strength: null, gaps: [], practices: [] }),
);
expect(html).not.toContain("P_G)");
expect(html).not.toContain("Стандартная ошибка");
expect(html).not.toContain("Сила подтверждения");
expect(html).not.toContain("0,00");
expect(html).toContain("Сервер не вернул оценку способности и неопределенности");
});
});
describe("AssessmentResultView for a failed attempt", () => {
const html = render(notConfirmedAfterJunior());
it("explains that the previous grade stays and shows the attempt result", () => {
expect(html).toContain("Уровень пока не подтвержден: Backend, Middle.");
expect(html).toContain("Прежний подтвержденный уровень Junior сохраняется.");
expect(html).toContain("Backend, Junior (прежняя, сохраняется)");
});
it("lists the server next steps and offers the lower grade only as text", () => {
expect(html).toContain("Следующие шаги на момент решения");
expect(html).toContain("Шаги рассчитаны сервером в момент решения.");
expect(html).toContain("Проверить актуальную доступность");
expect(html).toContain("Пересдать тот же уровень: Middle.");
expect(html).toContain("Доступно с 7 ноября 2026 г. в 09:30 UTC.");
expect(html).toContain("Пройти проверку на меньший уровень: Junior.");
expect(html).toContain("предлагает принять меньший уровень Junior");
expect(html).toContain("Категория не изменится, пока вы сами не подтвердите это действие.");
expect(html).not.toContain("<button");
expect(html.match(/<a /g)).toHaveLength(1);
expect(html).toContain(`href="${paths.candidate.assessment}"`);
});
});
describe("AssessmentResultView for an express result", () => {
const html = render(expressFixture());
it("is marked as a demonstration without a grade", () => {
expect(html).toContain("Демонстрация без реального грейда");
expect(html).toContain(
"Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.",
);
expect(html).toContain("Вы ответили на три учебных задания.");
expect(html).toContain("не присваивается");
expect(html).not.toContain("Подтвержденный уровень");
expect(html).not.toContain("Предварительный результат");
});
it("offers the full test and does not replace it", () => {
expect(html).toContain("Перейти к полной проверке");
expect(html).toContain(`href="${paths.candidate.assessment}"`);
expect(html).toContain("Категорию дает только полная проверка.");
});
});
@@ -0,0 +1,215 @@
import { useId, type ReactNode } from "react";
import type { AssessmentResult } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import { ButtonLink, Mono } from "../../../shared/ui";
import { describeAssessmentResult } from "../model/result-presentation";
import styles from "./assessment-result-view.module.css";
type AssessmentResultViewProps = {
result: AssessmentResult;
/** Level of the result heading; its blocks use the next level. */
headingLevel?: 2 | 3;
/** IANA zone for dates; the browser zone when omitted. */
timeZone?: string;
};
type BlockProps = {
title: string;
level: 3 | 4;
children: ReactNode;
};
function Block({ title, level, children }: BlockProps) {
const Heading = level === 3 ? "h3" : "h4";
return (
<section className={styles.block}>
<Heading className={styles["block-title"]}>{title}</Heading>
{children}
</section>
);
}
/**
* Stored result of one attempt. Every value is a restatement of a server
* field: an absent estimate is not drawn, a lower-grade offer is text and
* never a control that changes the category, and an express run is marked as
* a demonstration without a grade.
*/
export function AssessmentResultView({
result,
headingLevel = 2,
timeZone,
}: AssessmentResultViewProps) {
const titleId = useId();
const view = describeAssessmentResult(result, timeZone ? { timeZone } : {});
const Heading = headingLevel === 2 ? "h2" : "h3";
const blockLevel = headingLevel === 2 ? 3 : 4;
const testLinkVisible = view.nextSteps.some((step) => step.leadsToTest);
return (
<article className={styles.root} aria-labelledby={titleId} data-express={view.isExpress}>
<header className={styles.header}>
<p className={styles.kind}>{view.kindLabel}</p>
<Heading id={titleId} className={styles.title}>
{view.title}
</Heading>
<p className={styles.badges}>
{view.isExpress ? <span className={styles.badge}>Демонстрация</span> : null}
{!view.isExpress && view.isProvisional ? (
<span className={styles.badge}>Предварительный результат</span>
) : null}
</p>
</header>
<p className={styles.summary}>{view.summary.text}</p>
{view.summary.reason ? <p>{view.summary.reason}</p> : null}
{view.isExpress ? (
<>
<p className={styles.demo}>
Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.
</p>
{view.expressSummary ? <p>{view.expressSummary}</p> : null}
</>
) : null}
<dl className={styles.facts}>
{view.facts.map((fact) => (
<div key={fact.label}>
<dt>{fact.label}</dt>
<dd>{fact.value}</dd>
</div>
))}
</dl>
{view.categoryNote ? <p>{view.categoryNote}</p> : null}
<Block title="Метод и ограничения" level={blockLevel}>
<p>{view.methodLimitation}</p>
{view.limitations.length > 0 ? (
<ul className={styles.list}>
{view.limitations.map((limitation, index) => (
<li key={`${index}-${limitation}`}>{limitation}</li>
))}
</ul>
) : null}
{view.score ? (
<p>
Баллы за задания: <Mono strong>{view.score}</Mono>.
</p>
) : null}
</Block>
{view.uncertainty ? (
<Block title="Неопределенность оценки" level={blockLevel}>
<dl className={styles.facts}>
<div>
<dt>Оценка способности (θ)</dt>
<dd>
<Mono>{view.uncertainty.theta}</Mono>
</dd>
</div>
<div>
<dt>Стандартная ошибка (SE)</dt>
<dd>
<Mono>{view.uncertainty.standardError}</Mono>
</dd>
</div>
<div>
<dt>95% интервал способности</dt>
<dd>
<Mono>{view.uncertainty.interval}</Mono>
</dd>
</div>
<div>
<dt>Вероятность достичь порога выбранного грейда (P_G)</dt>
<dd>
<Mono strong>{view.uncertainty.pGrade}</Mono>
</dd>
</div>
{view.strength ? (
<div>
<dt>Сила подтверждения</dt>
<dd>{view.strength}</dd>
</div>
) : null}
</dl>
<p className={styles.note}>
Значения даны на шкале специализации.
{view.isProvisional
? " Пока пороги не откалиброваны, вероятность остается предварительной оценкой, а не измеренной долей."
: ""}
</p>
</Block>
) : null}
{!view.uncertainty && view.strength ? (
<p>
Сила подтверждения: <strong>{view.strength}</strong>.
</p>
) : null}
{view.uncertaintyNote ? <p className={styles.note}>{view.uncertaintyNote}</p> : null}
{view.gaps.length > 0 ? (
<Block title="Области со слабыми доказательствами" level={blockLevel}>
<ul className={styles.list}>
{view.gaps.map((gap, index) => (
<li key={`${index}-${gap}`}>{gap}</li>
))}
</ul>
</Block>
) : null}
{view.gapsNote ? <p className={styles.note}>{view.gapsNote}</p> : null}
{view.practices.length > 0 || view.durations.length > 0 ? (
<Block title="Практика и время" level={blockLevel}>
{view.practices.length > 0 ? (
<ul className={styles.list}>
{view.practices.map((practice, index) => (
<li key={`${index}-${practice}`}>{practice}</li>
))}
</ul>
) : null}
<p className={styles.note}>
{view.durations.join(". ")}. Время записано отдельной меткой и не влияет на решение.
</p>
</Block>
) : null}
{view.isExpress ? (
<Block title="Следующий шаг" level={blockLevel}>
<p>Категорию дает только полная проверка. Демонстрация ее не заменяет.</p>
<ButtonLink to={paths.candidate.assessment}>Перейти к полной проверке</ButtonLink>
</Block>
) : (
<Block title="Следующие шаги на момент решения" level={blockLevel}>
{view.nextSteps.length > 0 ? (
<ul className={styles.steps}>
{view.nextSteps.map((step) => (
<li key={`${step.action}-${step.text}`}>
<p>{step.text}</p>
{step.isOffer ? (
<p className={styles.note}>
Категория не изменится, пока вы сами не подтвердите это действие. Такой
команды в интерфейсе пока нет.
</p>
) : null}
{step.availability ? <p className={styles.note}>{step.availability}</p> : null}
</li>
))}
</ul>
) : null}
{view.nextStepsNote ? <p className={styles.note}>{view.nextStepsNote}</p> : null}
{view.nextSteps.length > 0 ? (
<p className={styles.note}>
Шаги рассчитаны сервером в момент решения. Сейчас доступность может быть другой: ее
показывает страница проверок.
</p>
) : null}
{testLinkVisible ? (
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
Проверить актуальную доступность
</ButtonLink>
) : null}
</Block>
)}
</article>
);
}
@@ -0,0 +1,104 @@
import { describe, expect, it, vi } from "vitest";
import { ApiRequestError, networkErrorCode } from "../../../shared/api";
import type {
AssessmentAvailability,
CandidateProfile,
CandidateQuestionnaire,
} from "../../../shared/api/schemas";
import { combineJourneyReads } from "./home-queries";
function read<T>(
status: "pending" | "error" | "success",
data?: T,
error: Error | null = null,
refetch: () => unknown = () => undefined,
) {
return { status, data, error, isRefetching: false, refetch };
}
const profile = { version: 1 } as CandidateProfile;
const questionnaire = {
version: 1,
specializations: [
{
specialization: "backend",
self_assessed_grade: "junior",
task_languages: [],
stack: [],
experience: null,
},
],
work_context: null,
updated_at: null,
} as CandidateQuestionnaire;
const availability = {
specializations: [
{ specialization: "backend", confirmed_grade: null, active_attempt_id: null, grades: [] },
],
} as AssessmentAvailability;
function apiError(status: number) {
return new ApiRequestError({ status, code: networkErrorCode, title: "Failed." });
}
describe("combineJourneyReads", () => {
it("stays pending until all three reads arrive", () => {
const state = combineJourneyReads(
"candidate_profile",
read("success", profile),
read("pending"),
read("success", availability),
);
expect(state).toEqual({ status: "pending" });
});
it("builds the journey from the three reads", () => {
const state = combineJourneyReads(
"candidate_assessment",
read("success", profile),
read("success", questionnaire),
read("success", availability),
);
expect(state.status).toBe("success");
if (state.status === "success") {
expect(state.journey.savedStep).toBe("candidate_assessment");
expect(state.journey.nextStep).toEqual({ kind: "assessment" });
}
});
it("fails as a whole instead of guessing a step from partial data", () => {
const failure = apiError(500);
const state = combineJourneyReads(
"candidate_profile",
read("error", undefined, failure),
read("success", questionnaire),
read("success", availability),
);
expect(state).toMatchObject({ status: "error", error: failure });
});
it("shows a denied read before other failures and retries only failed reads", () => {
const denied = apiError(403);
const failedProfile = vi.fn();
const failedAvailability = vi.fn();
const okQuestionnaire = vi.fn();
const state = combineJourneyReads(
"candidate_profile",
read("error", undefined, apiError(500), failedProfile),
read("success", questionnaire, null, okQuestionnaire),
read("error", undefined, denied, failedAvailability),
);
expect(state.status).toBe("error");
if (state.status === "error") {
expect(state.error).toBe(denied);
state.retry();
}
expect(failedProfile).toHaveBeenCalledOnce();
expect(failedAvailability).toHaveBeenCalledOnce();
expect(okQuestionnaire).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,202 @@
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
import type { z } from "zod";
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import {
getMyAssessmentAvailability,
listMyAssessmentResults,
} from "../../../shared/api/endpoints/assessment/assessment";
import {
getMyProfile,
getMyQuestionnaire,
} from "../../../shared/api/endpoints/candidate/candidate";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import { getMyPrivacySettings } from "../../../shared/api/endpoints/privacy/privacy";
import {
AssessmentAvailability,
AssessmentResultHistoryPage,
CandidateProfile,
CandidateQuestionnaire,
PrivacySettings,
type Session,
} from "../../../shared/api/schemas";
import { buildCandidateJourney, type CandidateJourney } from "../model/home";
// The home needs only the version of the profile: 0 means it was never saved.
// The profile form validates the rest of the document itself.
const profileVersionSchema = CandidateProfile.pick({ version: true });
type CandidateProfileVersion = Pick<CandidateProfile, "version">;
const homeQueryPrefix = ["candidate-home"] as const;
/** Account-scoped keys: a response for one account never fills another's cache. */
export const candidateHomeQueryKeys = {
root: homeQueryPrefix,
profile: (accountId: string) => [...homeQueryPrefix, accountId, "profile"] as const,
questionnaire: (accountId: string) => [...homeQueryPrefix, accountId, "questionnaire"] as const,
availability: (accountId: string) => [...homeQueryPrefix, accountId, "availability"] as const,
latestResult: (accountId: string) => [...homeQueryPrefix, accountId, "latest-result"] as const,
privacy: (accountId: string) => [...homeQueryPrefix, accountId, "privacy"] as const,
};
// Personal data is not kept after the screen closes, and every visit reads the
// current state: the home screen must match the API after a refresh.
const privateQueryOptions = {
gcTime: 0,
staleTime: 0,
retry: false,
refetchOnMount: "always" as const,
refetchOnWindowFocus: "always" as const,
};
function parseResponse(schema: z.ZodType, value: unknown): unknown {
const parsed = schema.safeParse(value);
if (!parsed.success) {
throw new ApiRequestError({
status: 200,
code: invalidResponseCode,
title: "The response does not match the API contract.",
});
}
return parsed.data;
}
function assertSameAccount(queryClient: QueryClient, accountId: string): void {
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
if (current?.account.id !== accountId) {
throw new Error("The candidate session changed during the home request.");
}
}
function useHomeQuery<T>(
session: Session | undefined,
key: (accountId: string) => readonly unknown[],
read: (signal: AbortSignal) => Promise<unknown>,
schema: z.ZodType,
) {
const queryClient = useQueryClient();
const accountId = session?.account.id;
const enabled = session?.account.scenario === "candidate";
return useQuery<T, Error>({
queryKey: key(accountId ?? "no-session"),
enabled,
...privateQueryOptions,
queryFn: async ({ signal }) => {
if (!accountId) throw new Error("A candidate session is required.");
assertSameAccount(queryClient, accountId);
const response = await read(signal);
assertSameAccount(queryClient, accountId);
return parseResponse(schema, response) as T;
},
});
}
export function useCandidateProfileRead(session: Session | undefined) {
return useHomeQuery<CandidateProfileVersion>(
session,
candidateHomeQueryKeys.profile,
(signal) => getMyProfile({ signal }),
profileVersionSchema,
);
}
export function useCandidateQuestionnaireRead(session: Session | undefined) {
return useHomeQuery<CandidateQuestionnaire>(
session,
candidateHomeQueryKeys.questionnaire,
(signal) => getMyQuestionnaire({ signal }),
CandidateQuestionnaire,
);
}
export function useCandidateAvailabilityRead(session: Session | undefined) {
return useHomeQuery<AssessmentAvailability>(
session,
candidateHomeQueryKeys.availability,
(signal) => getMyAssessmentAvailability({ signal }),
AssessmentAvailability,
);
}
/** Newest real result only: the home screen links to the full history. */
export function useCandidateLatestResultRead(session: Session | undefined) {
return useHomeQuery<AssessmentResultHistoryPage>(
session,
candidateHomeQueryKeys.latestResult,
(signal) => listMyAssessmentResults({ limit: 1 }, { signal }),
AssessmentResultHistoryPage,
);
}
export function useCandidatePrivacyRead(session: Session | undefined) {
return useHomeQuery<PrivacySettings>(
session,
candidateHomeQueryKeys.privacy,
(signal) => getMyPrivacySettings({ signal }),
PrivacySettings,
);
}
type ReadResult<T> = {
status: "pending" | "error" | "success";
data: T | undefined;
error: Error | null;
isRefetching: boolean;
refetch: () => unknown;
};
export type CandidateJourneyState =
| { status: "pending" }
| { status: "error"; error: unknown; isRetrying: boolean; retry: () => void }
| { status: "success"; journey: CandidateJourney };
function isAccessError(error: unknown): boolean {
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
}
/**
* Joins the three reads that the next step depends on. One failed read fails
* the whole state, because a step chosen from partial data could send the
* candidate to a form they already completed. A denied read wins over other
* failures so that the forbidden state is shown instead of a retry.
*/
export function combineJourneyReads(
savedStep: CandidateJourney["savedStep"],
profile: ReadResult<CandidateProfileVersion>,
questionnaire: ReadResult<CandidateQuestionnaire>,
availability: ReadResult<AssessmentAvailability>,
): CandidateJourneyState {
const reads = [profile, questionnaire, availability];
const failed = reads.filter((read) => read.status === "error");
if (failed.length > 0) {
const denied = failed.find((read) => isAccessError(read.error));
return {
status: "error",
error: (denied ?? failed[0])?.error,
isRetrying: failed.some((read) => read.isRefetching),
retry: () => {
for (const read of failed) void read.refetch();
},
};
}
if (profile.data === undefined || questionnaire.data === undefined || !availability.data) {
return { status: "pending" };
}
return {
status: "success",
journey: buildCandidateJourney({
savedStep,
profileVersion: profile.data.version,
questionnaire: questionnaire.data,
availability: availability.data,
}),
};
}
/** Next-step state of the signed-in candidate, read from the current API state. */
export function useCandidateJourney(session: Session | undefined): CandidateJourneyState {
const profile = useCandidateProfileRead(session);
const questionnaire = useCandidateQuestionnaireRead(session);
const availability = useCandidateAvailabilityRead(session);
if (!session) return { status: "pending" };
return combineJourneyReads(session.account.onboarding_step, profile, questionnaire, availability);
}
+18
View File
@@ -26,3 +26,21 @@ export {
type SoftSkillDraft,
type StackDraft,
} from "./model/profile-form";
export {
buildCandidateJourney,
onboardingStepLabels,
summarizeVisibility,
type CandidateJourney,
type CandidateJourneyInput,
type CandidateNextStep,
type SpecializationStanding,
type VisibilitySummary,
} from "./model/home";
export {
candidateHomeQueryKeys,
combineJourneyReads,
useCandidateJourney,
useCandidateLatestResultRead,
useCandidatePrivacyRead,
type CandidateJourneyState,
} from "./api/home-queries";
@@ -0,0 +1,277 @@
import { describe, expect, it } from "vitest";
import type {
AssessmentAvailability,
GradeCode,
PrivacySettings,
SpecializationCode,
} from "../../../shared/api/schemas";
import { buildCandidateJourney, summarizeVisibility, type CandidateJourneyInput } from "./home";
type Availability = AssessmentAvailability["specializations"][number];
function gradeRows(status: "available" | "cooldown"): Availability["grades"] {
return (["intern", "junior", "middle", "senior"] as const).map((grade) => ({
grade,
status,
mode: null,
available_at: null,
time_limit_seconds: null,
max_sessions: null,
max_items: null,
practice_required: null,
}));
}
function availabilityRow(
specialization: SpecializationCode,
options: {
confirmed?: GradeCode | null;
attemptId?: string | null;
status?: "available" | "cooldown";
} = {},
): Availability {
return {
specialization,
confirmed_grade: options.confirmed ?? null,
active_attempt_id: options.attemptId ?? null,
grades: gradeRows(options.status ?? "available"),
};
}
function questionnaire(
declared: [SpecializationCode, GradeCode][],
version = declared.length > 0 ? 1 : 0,
): CandidateJourneyInput["questionnaire"] {
return {
version,
specializations: declared.map(([specialization, grade]) => ({
specialization,
self_assessed_grade: grade,
task_languages: [],
stack: [],
experience: null,
})),
};
}
function input(overrides: Partial<CandidateJourneyInput> = {}): CandidateJourneyInput {
return {
savedStep: "candidate_consents",
profileVersion: 0,
questionnaire: questionnaire([]),
availability: { specializations: [] },
...overrides,
};
}
describe("buildCandidateJourney next step", () => {
it("leads an empty profile to the profile form", () => {
expect(buildCandidateJourney(input()).nextStep).toEqual({ kind: "profile" });
});
it("leads a saved profile without a questionnaire to the questionnaire", () => {
const journey = buildCandidateJourney(input({ profileVersion: 3 }));
expect(journey.profileSaved).toBe(true);
expect(journey.nextStep).toEqual({ kind: "questionnaire" });
});
it("does not wait for the stored step to advance past the consents step", () => {
// The server advances the stored step only from the matching step, so a
// saved profile can coexist with the stored consents step.
const journey = buildCandidateJourney(
input({ savedStep: "candidate_consents", profileVersion: 1 }),
);
expect(journey.savedStep).toBe("candidate_consents");
expect(journey.nextStep).toEqual({ kind: "questionnaire" });
});
it("leads a saved questionnaire to the test and keeps the declared grade", () => {
const journey = buildCandidateJourney(
input({
savedStep: "candidate_assessment",
profileVersion: 1,
questionnaire: questionnaire([["backend", "middle"]]),
availability: { specializations: [availabilityRow("backend")] },
}),
);
expect(journey.nextStep).toEqual({ kind: "assessment" });
expect(journey.confirmed).toEqual([]);
expect(journey.standings).toEqual([
{
specialization: "backend",
declaredGrade: "middle",
confirmedGrade: null,
activeAttemptId: null,
canStartAttempt: true,
},
]);
});
it("treats a questionnaire version without specializations as not saved", () => {
const journey = buildCandidateJourney(
input({ profileVersion: 1, questionnaire: questionnaire([], 2) }),
);
expect(journey.questionnaireSaved).toBe(false);
expect(journey.nextStep).toEqual({ kind: "questionnaire" });
});
it("resumes the active attempt instead of offering a new test", () => {
const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80";
const journey = buildCandidateJourney(
input({
profileVersion: 1,
questionnaire: questionnaire([["backend", "junior"]]),
availability: { specializations: [availabilityRow("backend", { attemptId })] },
}),
);
expect(journey.nextStep).toEqual({
kind: "resume_attempt",
attemptId,
specialization: "backend",
});
});
it("leads an obtained category to the result and keeps declared and confirmed apart", () => {
const journey = buildCandidateJourney(
input({
savedStep: "candidate_assessment",
profileVersion: 1,
questionnaire: questionnaire([["backend", "middle"]]),
availability: { specializations: [availabilityRow("backend", { confirmed: "junior" })] },
}),
);
expect(journey.nextStep).toEqual({ kind: "result" });
expect(journey.confirmed).toHaveLength(1);
expect(journey.standings[0]).toMatchObject({
declaredGrade: "middle",
confirmedGrade: "junior",
});
});
it("offers the result even when the profile is still empty", () => {
const journey = buildCandidateJourney(
input({
questionnaire: questionnaire([["qa", "junior"]]),
availability: { specializations: [availabilityRow("qa", { confirmed: "junior" })] },
}),
);
expect(journey.nextStep).toEqual({ kind: "result" });
});
it("reports that no test can start when every grade is blocked", () => {
const journey = buildCandidateJourney(
input({
profileVersion: 1,
questionnaire: questionnaire([["backend", "junior"]]),
availability: { specializations: [availabilityRow("backend", { status: "cooldown" })] },
}),
);
expect(journey.standings[0]?.canStartAttempt).toBe(false);
expect(journey.nextStep).toEqual({ kind: "assessment" });
});
it("never turns a declared grade into a confirmed one", () => {
const journey = buildCandidateJourney(
input({
savedStep: "completed",
profileVersion: 1,
questionnaire: questionnaire([["frontend", "senior"]]),
availability: { specializations: [] },
}),
);
expect(journey.confirmed).toEqual([]);
expect(journey.standings[0]).toMatchObject({
declaredGrade: "senior",
confirmedGrade: null,
});
expect(journey.nextStep).toEqual({ kind: "assessment" });
});
});
describe("summarizeVisibility", () => {
function settings(overrides: {
publication?: Partial<PrivacySettings["publication"]>;
search?: Partial<PrivacySettings["search_status"]>;
}): PrivacySettings {
return {
publication: {
state: "closed",
closed_reason: "never_published",
fields: [],
consent_id: null,
published_at: null,
version: 0,
...overrides.publication,
},
search_status: {
value: "not_looking",
lapsed: false,
confirmed_at: null,
lapses_at: null,
version: 0,
...overrides.search,
},
hidden_organizations_total: 0,
};
}
it("restates a closed card with its reason", () => {
expect(summarizeVisibility(settings({}))).toEqual({
published: false,
closedReason: "never_published",
showsCategory: false,
searchStatus: { looking: false, lapsed: false, lapsesAt: null },
});
});
it("reports whether a published card includes the category", () => {
const published = { state: "published", closed_reason: null } as const;
expect(
summarizeVisibility(
settings({ publication: { ...published, fields: ["categories", "stack"] } }),
),
).toMatchObject({ published: true, showsCategory: true });
expect(
summarizeVisibility(settings({ publication: { ...published, fields: ["stack"] } })),
).toMatchObject({ published: true, showsCategory: false });
});
it("keeps the lapse moment only for a status that holds now", () => {
expect(
summarizeVisibility(
settings({
search: {
value: "looking",
confirmed_at: "2026-10-01T10:00:00Z",
lapses_at: "2026-10-31T10:00:00Z",
},
}),
).searchStatus,
).toEqual({ looking: true, lapsed: false, lapsesAt: "2026-10-31T10:00:00Z" });
});
it("marks a lapsed search status", () => {
expect(
summarizeVisibility(
settings({
search: {
lapsed: true,
confirmed_at: "2026-09-01T10:00:00Z",
lapses_at: "2026-10-01T10:00:00Z",
version: 4,
},
}),
).searchStatus,
).toEqual({ looking: false, lapsed: true, lapsesAt: null });
});
});
@@ -0,0 +1,170 @@
import type {
Account,
AssessmentAvailability,
CandidateQuestionnaire,
GradeCode,
PrivacySettings,
SpecializationCode,
} from "../../../shared/api/schemas";
type OnboardingStep = Account["onboarding_step"];
/** Plain names of the stored onboarding steps, for the saved-step line. */
export const onboardingStepLabels: Readonly<Record<OnboardingStep, string>> = {
candidate_consents: "Согласия",
candidate_profile: "Профиль",
candidate_questionnaire: "Анкета",
candidate_assessment: "Тест",
employer_company: "Компания",
completed: "Онбординг завершен",
};
/**
* One questionnaire specialization with the two facts that must never be
* merged: what the candidate declared and what an assessment confirmed.
*/
export type SpecializationStanding = {
specialization: SpecializationCode;
/** Self-assessed grade from the questionnaire; a claim, not a category. */
declaredGrade: GradeCode | null;
/** Grade that an assessment result confirmed, or null. */
confirmedGrade: GradeCode | null;
/** Active attempt of this specialization that can be resumed. */
activeAttemptId: string | null;
/** True when at least one grade can start a new attempt now. */
canStartAttempt: boolean;
};
/** The single main action offered on the home screen. */
export type CandidateNextStep =
| { kind: "profile" }
| { kind: "questionnaire" }
| { kind: "assessment" }
| { kind: "resume_attempt"; attemptId: string; specialization: SpecializationCode }
| { kind: "result" };
export type CandidateJourneyInput = {
/** `onboarding_step` of the current session account. */
savedStep: OnboardingStep;
/** `version` of the profile read; 0 means it was never saved. */
profileVersion: number;
questionnaire: Pick<CandidateQuestionnaire, "version" | "specializations">;
availability: Pick<AssessmentAvailability, "specializations">;
};
export type CandidateJourney = {
savedStep: OnboardingStep;
profileSaved: boolean;
questionnaireSaved: boolean;
standings: readonly SpecializationStanding[];
/** Standings whose grade an assessment confirmed. */
confirmed: readonly SpecializationStanding[];
nextStep: CandidateNextStep;
};
function buildStandings(input: CandidateJourneyInput): SpecializationStanding[] {
const standings = new Map<SpecializationCode, SpecializationStanding>();
// The availability list is the server's view of the questionnaire
// specializations; the questionnaire adds the declared grade.
for (const item of input.availability.specializations) {
standings.set(item.specialization, {
specialization: item.specialization,
declaredGrade: null,
confirmedGrade: item.confirmed_grade,
activeAttemptId: item.active_attempt_id,
canStartAttempt: item.grades.some((grade) => grade.status === "available"),
});
}
for (const item of input.questionnaire.specializations) {
const existing = standings.get(item.specialization);
standings.set(item.specialization, {
specialization: item.specialization,
declaredGrade: item.self_assessed_grade,
confirmedGrade: existing?.confirmedGrade ?? null,
activeAttemptId: existing?.activeAttemptId ?? null,
canStartAttempt: existing?.canStartAttempt ?? false,
});
}
return [...standings.values()];
}
/**
* Chooses the main action from what the server returned. The stored
* onboarding step is kept for display and is never overridden; it is not the
* only input because the server advances it only when the profile or the
* questionnaire is saved from the matching step, so a saved profile can sit
* behind an earlier stored step. Presence of saved data therefore decides
* between the profile, the questionnaire, and the test.
*
* The client invents no category, grade, or threshold: a category exists only
* when the availability read returns a confirmed grade.
*/
export function buildCandidateJourney(input: CandidateJourneyInput): CandidateJourney {
const standings = buildStandings(input);
const confirmed = standings.filter((standing) => standing.confirmedGrade !== null);
const profileSaved = input.profileVersion > 0;
const questionnaireSaved =
input.questionnaire.version > 0 && input.questionnaire.specializations.length > 0;
return {
savedStep: input.savedStep,
profileSaved,
questionnaireSaved,
standings,
confirmed,
nextStep: chooseNextStep({ profileSaved, questionnaireSaved, standings, confirmed }),
};
}
function chooseNextStep(state: {
profileSaved: boolean;
questionnaireSaved: boolean;
standings: readonly SpecializationStanding[];
confirmed: readonly SpecializationStanding[];
}): CandidateNextStep {
if (state.confirmed.length > 0) return { kind: "result" };
if (!state.profileSaved) return { kind: "profile" };
if (!state.questionnaireSaved) return { kind: "questionnaire" };
const resumable = state.standings.find((standing) => standing.activeAttemptId !== null);
if (resumable?.activeAttemptId) {
return {
kind: "resume_attempt",
attemptId: resumable.activeAttemptId,
specialization: resumable.specialization,
};
}
return { kind: "assessment" };
}
export type VisibilitySummary = {
/** True while organizations can read the card. */
published: boolean;
/** Why the card is closed, or null while it is published. */
closedReason: PrivacySettings["publication"]["closed_reason"];
/** True only for a published card that includes the confirmed category. */
showsCategory: boolean;
searchStatus: {
looking: boolean;
/** True when "looking" ran out because it was not confirmed again. */
lapsed: boolean;
/** Moment the confirmed status lapses, for a status that holds now. */
lapsesAt: string | null;
};
};
/** Restates the privacy settings read without adding rules of its own. */
export function summarizeVisibility(settings: PrivacySettings): VisibilitySummary {
const published = settings.publication.state === "published";
return {
published,
closedReason: published ? null : settings.publication.closed_reason,
showsCategory: published && settings.publication.fields.includes("categories"),
searchStatus: {
looking: settings.search_status.value === "looking",
lapsed: settings.search_status.lapsed,
lapsesAt:
settings.search_status.value === "looking" ? settings.search_status.lapses_at : null,
},
};
}