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,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 };
}