feat(candidate): add the candidate home, results and result history screens
This commit is contained in:
1 parent
8277133712
commit
4761508f13
52 files changed
+5334
-81
No files matched your search
@@ -0,0 +1,44 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../shared/api/schemas";
|
||||
import { CandidateHomeRoute } from "./candidate-home-route";
|
||||
|
||||
function render(step: Session["account"]["onboarding_step"]): string {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
|
||||
account: {
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
email: "person@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: step,
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session);
|
||||
return renderToString(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<CandidateHomeRoute />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("CandidateHomeRoute", () => {
|
||||
it.each([
|
||||
"candidate_consents",
|
||||
"candidate_profile",
|
||||
"candidate_questionnaire",
|
||||
"candidate_assessment",
|
||||
"completed",
|
||||
] as const)("shows the home at the saved step %s instead of redirecting", (step) => {
|
||||
const html = render(step);
|
||||
|
||||
expect(html).toMatch(/<h1[^>]*>Главная<\/h1>/);
|
||||
expect(html).toContain("Определяем следующий шаг...");
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,9 @@
|
||||
import { Navigate } from "react-router-dom";
|
||||
import { getOnboardingDestination } from "../../entities/session";
|
||||
import { PlaceholderPage } from "../../pages/placeholder";
|
||||
import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity";
|
||||
import { CandidateHomePage } from "../../pages/candidate-home";
|
||||
|
||||
/**
|
||||
* The candidate home opens at every saved onboarding step: it shows the saved
|
||||
* step and leads to the next action itself instead of redirecting away.
|
||||
*/
|
||||
export function CandidateHomeRoute() {
|
||||
const session = useGetCurrentSession();
|
||||
if (!session.data) return <PlaceholderPage screen="candidateHome" />;
|
||||
if (session.data.account.onboarding_step !== "completed") {
|
||||
return <Navigate to={getOnboardingDestination(session.data.account)} replace />;
|
||||
}
|
||||
return <PlaceholderPage screen="candidateHome" />;
|
||||
return <CandidateHomePage />;
|
||||
}
|
||||
@@ -283,7 +283,7 @@ describe("product readiness", () => {
|
||||
});
|
||||
|
||||
it("labels the remaining cabinet scaffolds as placeholders", async () => {
|
||||
for (const path of ["/candidate", "/employer/candidates"]) {
|
||||
for (const path of ["/candidate/invitations", "/employer/candidates"]) {
|
||||
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { redirect, type RouteObject } from "react-router-dom";
|
||||
import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment";
|
||||
import { AssessmentResultPage, AssessmentResultsPage } from "../../pages/assessment-result";
|
||||
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
|
||||
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
|
||||
import { CompanyPage } from "../../pages/company";
|
||||
@@ -74,10 +75,8 @@ export const routes: RouteObject[] = [
|
||||
path: `${paths.candidate.assessment}/:attemptId`,
|
||||
element: <AssessmentAttemptPage />,
|
||||
},
|
||||
{
|
||||
path: paths.candidate.results,
|
||||
element: <PlaceholderPage screen="candidateResults" />,
|
||||
},
|
||||
{ path: paths.candidate.results, element: <AssessmentResultsPage /> },
|
||||
{ path: `${paths.candidate.results}/:attemptId`, element: <AssessmentResultPage /> },
|
||||
{
|
||||
path: paths.candidate.invitations,
|
||||
element: <PlaceholderPage screen="candidateInvitations" />,
|
||||
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { AssessmentResultPage } from "./ui/assessment-result-page";
|
||||
export { AssessmentResultsPage } from "./ui/assessment-results-page";
|
||||
@@ -0,0 +1,20 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.back {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.pending {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
justify-items: start;
|
||||
}
|
||||
|
||||
.pending p {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { useEffect } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
Page,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
AssessmentActorGate,
|
||||
AssessmentResultView,
|
||||
isAssessmentAccessLoss,
|
||||
isAssessmentSessionEnded,
|
||||
removeAssessmentQueries,
|
||||
useAssessmentResult,
|
||||
} from "../../../entities/assessment";
|
||||
import styles from "./assessment-result-page.module.css";
|
||||
|
||||
const attemptIdPattern =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
/** One stored result, opened by a direct URL; only its owner can read it. */
|
||||
export function AssessmentResultPage() {
|
||||
const { attemptId = "" } = useParams();
|
||||
return (
|
||||
<Page title="Результат проверки" eyebrow="Кабинет кандидата" width="wide">
|
||||
<AssessmentActorGate>
|
||||
{({ actor, queryClient }) => (
|
||||
<StoredResult
|
||||
key={attemptId}
|
||||
actor={actor}
|
||||
queryClient={queryClient}
|
||||
attemptId={attemptId}
|
||||
/>
|
||||
)}
|
||||
</AssessmentActorGate>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
function StoredResult({
|
||||
actor,
|
||||
queryClient,
|
||||
attemptId,
|
||||
}: {
|
||||
actor: Session;
|
||||
queryClient: QueryClient;
|
||||
attemptId: string;
|
||||
}) {
|
||||
const validId = attemptIdPattern.test(attemptId);
|
||||
const result = useAssessmentResult({ actor, attemptId, enabled: validId, queryClient });
|
||||
const accessLost = result.isError && isAssessmentAccessLoss(result.error);
|
||||
const sessionEnded = result.isError && isAssessmentSessionEnded(result.error);
|
||||
|
||||
useEffect(() => {
|
||||
if (sessionEnded) removeAssessmentQueries(queryClient);
|
||||
}, [sessionEnded, queryClient]);
|
||||
|
||||
const back = (
|
||||
<div className={styles.back}>
|
||||
<ButtonLink variant="secondary" to={paths.candidate.results}>
|
||||
К истории результатов
|
||||
</ButtonLink>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!validId) {
|
||||
return (
|
||||
<>
|
||||
<ErrorState
|
||||
error={new Error("The attempt identifier is not valid.")}
|
||||
title="Не удалось открыть результат"
|
||||
/>
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (accessLost) {
|
||||
return (
|
||||
<>
|
||||
<ForbiddenState
|
||||
error={result.error}
|
||||
title="Результат недоступен"
|
||||
description={
|
||||
sessionEnded
|
||||
? "Сеанс закончился. Войдите в кабинет кандидата и повторите."
|
||||
: "Сервер не нашел этот результат среди ваших. Он мог принадлежать другому аккаунту."
|
||||
}
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (result.isPending) return <LoadingState label="Загружаем сохраненный результат..." />;
|
||||
if (!result.data) {
|
||||
return (
|
||||
<>
|
||||
{result.error instanceof ApiRequestError && result.error.status === 409 ? (
|
||||
<div role="status" className={styles.pending}>
|
||||
<p>Сервер еще завершает обработку результата. Повторите проверку позже.</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={result.isRefetching}
|
||||
onClick={() => void result.refetch()}
|
||||
>
|
||||
Обновить результат
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<ErrorState
|
||||
error={result.error}
|
||||
isRetrying={result.isRefetching}
|
||||
onRetry={() => void result.refetch()}
|
||||
title="Не удалось загрузить результат"
|
||||
/>
|
||||
)}
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={styles.layout}>
|
||||
{result.isError ? (
|
||||
<ErrorState
|
||||
error={result.error}
|
||||
isRetrying={result.isRefetching}
|
||||
onRetry={() => void result.refetch()}
|
||||
title="Не удалось обновить результат. Показан ранее загруженный."
|
||||
/>
|
||||
) : null}
|
||||
<AssessmentResultView result={result.data} />
|
||||
{back}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter, Route, Routes } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { AssessmentResult, Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { assessmentQueryKeys } from "../../../entities/assessment";
|
||||
import { AssessmentResultPage } from "./assessment-result-page";
|
||||
import { AssessmentResultsPage } from "./assessment-results-page";
|
||||
|
||||
const attemptId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff";
|
||||
|
||||
const session = {
|
||||
account: {
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
email: "person@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
const adaptive = {
|
||||
attempt_id: attemptId,
|
||||
specialization: "backend",
|
||||
target_grade: "middle",
|
||||
root_attempt_id: null,
|
||||
chain_deadline: null,
|
||||
task_language: "go",
|
||||
kind: "root",
|
||||
mode: "adaptive",
|
||||
versions: { bank_version: "demo-1", algorithm_version: "adaptive-1", policy_version: 1 },
|
||||
outcome: "confirmed",
|
||||
not_determined_reason: null,
|
||||
confirmed_grade: "middle",
|
||||
previous_confirmed_grade: null,
|
||||
category_decision: {
|
||||
status: "assigned",
|
||||
previous_confirmed_grade: null,
|
||||
current_confirmed_grade: "middle",
|
||||
method: null,
|
||||
source: null,
|
||||
calibration_status: "uncalibrated",
|
||||
},
|
||||
strength: "medium",
|
||||
calibration_status: "uncalibrated",
|
||||
limitations: ["uncalibrated_thresholds"],
|
||||
uncertainty: {
|
||||
theta: 0.42,
|
||||
standard_error: 0.21,
|
||||
interval_95: { low: -0.19, high: 1.03 },
|
||||
p_grade: 0.8,
|
||||
},
|
||||
basic_score: null,
|
||||
practices: [],
|
||||
gaps: [],
|
||||
durations: { items_seconds: 900, practice_seconds: null },
|
||||
next_steps: [{ action: "take_higher_grade", grade: "senior", available_at: null }],
|
||||
decided_at: "2026-10-08T09:30:00Z",
|
||||
} as unknown as AssessmentResult;
|
||||
|
||||
type Prepare = (queryClient: QueryClient) => void;
|
||||
|
||||
function signedIn(queryClient: QueryClient) {
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
}
|
||||
|
||||
function sessionRefused(queryClient: QueryClient) {
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
|
||||
.setState({
|
||||
status: "error",
|
||||
error: new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }),
|
||||
errorUpdateCount: 1,
|
||||
fetchStatus: "idle",
|
||||
});
|
||||
}
|
||||
|
||||
function render(path: string, prepare: Prepare): string {
|
||||
// Server rendering refetches an errored query on mount unless told not to.
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } });
|
||||
prepare(queryClient);
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Routes>
|
||||
<Route path={paths.candidate.results} element={<AssessmentResultsPage />} />
|
||||
<Route
|
||||
path={`${paths.candidate.results}/:attemptId`}
|
||||
element={<AssessmentResultPage />}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("AssessmentResultPage", () => {
|
||||
it("opens the stored result of the signed-in candidate by its URL", () => {
|
||||
const html = render(paths.candidate.result(attemptId), (queryClient) => {
|
||||
signedIn(queryClient);
|
||||
queryClient.setQueryData(assessmentQueryKeys.result(session, attemptId), adaptive);
|
||||
});
|
||||
expect(html).toContain("Уровень подтвержден: Backend, Middle.");
|
||||
expect(html).toContain("0,80");
|
||||
expect(html).toContain("средняя");
|
||||
expect(html).toContain(`href="${paths.candidate.results}"`);
|
||||
});
|
||||
|
||||
it("shows no data by a direct URL when the session was refused", () => {
|
||||
const html = render(paths.candidate.result(attemptId), (queryClient) => {
|
||||
sessionRefused(queryClient);
|
||||
queryClient.setQueryData(assessmentQueryKeys.result(session, attemptId), adaptive);
|
||||
});
|
||||
expect(html).toContain("Результаты недоступны");
|
||||
expect(html).toContain(`href="${paths.login}"`);
|
||||
expect(html).not.toContain("Backend");
|
||||
expect(html).not.toContain("0,80");
|
||||
});
|
||||
|
||||
it("shows no data for a result of another session key", () => {
|
||||
const html = render(paths.candidate.result(attemptId), (queryClient) => {
|
||||
signedIn(queryClient);
|
||||
queryClient.setQueryData(
|
||||
assessmentQueryKeys.result(
|
||||
{
|
||||
...session,
|
||||
account: { ...session.account, id: "22222222-2222-4222-8222-222222222222" },
|
||||
},
|
||||
attemptId,
|
||||
),
|
||||
adaptive,
|
||||
);
|
||||
});
|
||||
expect(html).not.toContain("Backend");
|
||||
expect(html).toContain("Загружаем сохраненный результат...");
|
||||
});
|
||||
|
||||
it("refuses to read a malformed identifier", () => {
|
||||
const html = render(`${paths.candidate.results}/not-an-id`, signedIn);
|
||||
expect(html).toContain("Не удалось открыть результат");
|
||||
});
|
||||
|
||||
it("explains a result the server does not return for this candidate", () => {
|
||||
const html = render(paths.candidate.result(attemptId), (queryClient) => {
|
||||
signedIn(queryClient);
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.build(queryClient, { queryKey: assessmentQueryKeys.result(session, attemptId) })
|
||||
.setState({
|
||||
status: "error",
|
||||
error: new ApiRequestError({ status: 404, code: "not_found", title: "Not found" }),
|
||||
errorUpdateCount: 1,
|
||||
fetchStatus: "idle",
|
||||
});
|
||||
});
|
||||
expect(html).toContain("Результат недоступен");
|
||||
expect(html).not.toContain("Backend");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AssessmentResultPage failures", () => {
|
||||
function failWith(error: ApiRequestError, withData = false): Prepare {
|
||||
return (queryClient) => {
|
||||
signedIn(queryClient);
|
||||
const key = assessmentQueryKeys.result(session, attemptId);
|
||||
if (withData) queryClient.setQueryData(key, adaptive);
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.build(queryClient, { queryKey: key })
|
||||
.setState({ status: "error", error, errorUpdateCount: 1, fetchStatus: "idle" });
|
||||
};
|
||||
}
|
||||
|
||||
it("tells an ended session from a missing result", () => {
|
||||
const ended = render(
|
||||
paths.candidate.result(attemptId),
|
||||
failWith(new ApiRequestError({ status: 401, code: "unauthenticated", title: "No session" })),
|
||||
);
|
||||
const missing = render(
|
||||
paths.candidate.result(attemptId),
|
||||
failWith(new ApiRequestError({ status: 404, code: "not_found", title: "Not found" })),
|
||||
);
|
||||
expect(ended).toContain("Сеанс закончился.");
|
||||
expect(missing).toContain("Сервер не нашел этот результат среди ваших.");
|
||||
expect(missing).not.toContain("Сеанс закончился.");
|
||||
});
|
||||
|
||||
it("offers exactly one retry for a server error", () => {
|
||||
const html = render(
|
||||
paths.candidate.result(attemptId),
|
||||
failWith(new ApiRequestError({ status: 500, code: "internal", title: "Internal error" })),
|
||||
);
|
||||
expect(html).toContain("Не удалось загрузить результат");
|
||||
expect(html.match(/Повторить/g)).toHaveLength(1);
|
||||
expect(html).not.toContain("Обновить результат");
|
||||
});
|
||||
|
||||
it("keeps the loaded result when a refresh fails", () => {
|
||||
const html = render(
|
||||
paths.candidate.result(attemptId),
|
||||
failWith(
|
||||
new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }),
|
||||
true,
|
||||
),
|
||||
);
|
||||
expect(html).toContain("Уровень подтвержден: Backend, Middle.");
|
||||
expect(html).toContain("Не удалось обновить результат. Показан ранее загруженный.");
|
||||
});
|
||||
|
||||
it("offers a retry instead of claiming lost access when the session check fails", () => {
|
||||
const html = render(paths.candidate.result(attemptId), (queryClient) => {
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.build(queryClient, { queryKey: getGetCurrentSessionQueryKey() })
|
||||
.setState({
|
||||
status: "error",
|
||||
error: new ApiRequestError({ status: 503, code: "internal", title: "Unavailable" }),
|
||||
errorUpdateCount: 1,
|
||||
fetchStatus: "idle",
|
||||
});
|
||||
});
|
||||
expect(html).toContain("Не удалось проверить вход");
|
||||
expect(html).toContain("Повторить");
|
||||
expect(html).not.toContain("Результаты недоступны");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AssessmentResultsPage", () => {
|
||||
it("shows the history heading for the signed-in candidate", () => {
|
||||
const html = render(paths.candidate.results, signedIn);
|
||||
expect(html).toContain("Результаты проверок");
|
||||
expect(html).toContain("Загружаем историю результатов...");
|
||||
});
|
||||
|
||||
it("opens no history without a session", () => {
|
||||
const html = render(paths.candidate.results, sessionRefused);
|
||||
expect(html).toContain("Результаты недоступны");
|
||||
expect(html).not.toContain("Загружаем историю результатов...");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Page } from "../../../shared/ui";
|
||||
import { AssessmentActorGate } from "../../../entities/assessment";
|
||||
import { AssessmentHistory } from "../../../widgets/assessment-history";
|
||||
|
||||
/** History of the signed-in candidate's real assessment results. */
|
||||
export function AssessmentResultsPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Результаты проверок"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Решения сервера по завершенным проверкам. Неудачная попытка не понижает действующую категорию."
|
||||
>
|
||||
<AssessmentActorGate>
|
||||
{({ actor, queryClient }) => <AssessmentHistory actor={actor} queryClient={queryClient} />}
|
||||
</AssessmentActorGate>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,6 @@
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.result,
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
@@ -27,8 +26,7 @@
|
||||
|
||||
.resume p,
|
||||
.finalize p,
|
||||
.info p,
|
||||
.result p {
|
||||
.info p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@@ -73,12 +71,9 @@
|
||||
}
|
||||
|
||||
.result {
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.demo-label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.result-error {
|
||||
@@ -95,8 +90,17 @@
|
||||
.resume,
|
||||
.finalize,
|
||||
.info,
|
||||
.result,
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
.result-heading {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.result-heading:focus-visible {
|
||||
outline: var(--focus-ring-width) solid var(--color-focus-ring);
|
||||
outline-offset: var(--focus-ring-offset);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import type {
|
||||
AssessmentAttempt,
|
||||
AssessmentFinalization,
|
||||
AssessmentResult,
|
||||
Session,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
@@ -24,10 +25,11 @@ import {
|
||||
LoadingState,
|
||||
Page,
|
||||
Section,
|
||||
VisuallyHidden,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
AssessmentResultView,
|
||||
assessmentQueryKeys,
|
||||
assessmentResultSummary,
|
||||
assessmentSessionMatches,
|
||||
gradeLabels,
|
||||
isOutcomeAmbiguous,
|
||||
@@ -679,11 +681,22 @@ function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessm
|
||||
if (resultQuery.isPending && !resultQuery.data) {
|
||||
return <LoadingState label="Загружаем сохраненный результат..." />;
|
||||
}
|
||||
if (resultQuery.isError || !resultQuery.data) {
|
||||
if (!resultQuery.data) {
|
||||
return (
|
||||
<div className={attemptStyles["result-error"]}>
|
||||
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
|
||||
<p role="status">Сервер еще завершает обработку результата. Повторите проверку позже.</p>
|
||||
<>
|
||||
<p role="status">
|
||||
Сервер еще завершает обработку результата. Повторите проверку позже.
|
||||
</p>
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={resultQuery.isRefetching}
|
||||
onClick={() => void resultQuery.refetch()}
|
||||
>
|
||||
Обновить результат
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<ErrorState
|
||||
error={resultQuery.error}
|
||||
@@ -692,28 +705,36 @@ function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessm
|
||||
title="Не удалось загрузить результат"
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={resultQuery.isRefetching}
|
||||
onClick={() => void resultQuery.refetch()}
|
||||
>
|
||||
Обновить результат
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const result = resultQuery.data;
|
||||
const summary = assessmentResultSummary(result);
|
||||
return <ResultPanel result={resultQuery.data} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The result of a finished attempt. Only a short phrase is a live message;
|
||||
* the full record is ordinary content, and the focus moves to its heading so
|
||||
* a screen reader starts reading at the result.
|
||||
*/
|
||||
function ResultPanel({ result }: { result: AssessmentResult }) {
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
useEffect(() => {
|
||||
headingRef.current?.focus();
|
||||
}, []);
|
||||
return (
|
||||
<div className={attemptStyles.result} role="status" aria-live="polite">
|
||||
<h2>Результат с сервера</h2>
|
||||
<p>{summary.text}</p>
|
||||
{summary.reason ? <p>{summary.reason}</p> : null}
|
||||
{summary.isDemonstration ? (
|
||||
<p className={attemptStyles["demo-label"]}>
|
||||
Только демонстрация. Подтвержденный грейд не присваивается.
|
||||
</p>
|
||||
) : null}
|
||||
<div className={attemptStyles.result}>
|
||||
<p role="status">
|
||||
<VisuallyHidden>Результат получен.</VisuallyHidden>
|
||||
</p>
|
||||
<h2 ref={headingRef} tabIndex={-1} className={attemptStyles["result-heading"]}>
|
||||
Результат с сервера
|
||||
</h2>
|
||||
<AssessmentResultView result={result} headingLevel={3} />
|
||||
<div className={attemptStyles["back-link"]}>
|
||||
<ButtonLink variant="secondary" to={paths.candidate.result(result.attempt_id)}>
|
||||
Открыть на странице результатов
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { CandidateHomePage } from "./ui/candidate-home-page";
|
||||
@@ -0,0 +1,53 @@
|
||||
.columns {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
}
|
||||
|
||||
@media (width >= 64rem) {
|
||||
.columns {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: start;
|
||||
}
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.facts {
|
||||
grid-template-columns: minmax(10rem, auto) minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
min-width: 0;
|
||||
margin: 0 0 var(--space-2);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.result-text {
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-snug);
|
||||
}
|
||||
|
||||
.reason {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-5);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { candidateHomeQueryKeys } from "../../../entities/candidate";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { CandidateHomePage } from "./candidate-home-page";
|
||||
|
||||
const accountId = "11111111-1111-4111-8111-111111111111";
|
||||
const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80";
|
||||
|
||||
const session = {
|
||||
account: {
|
||||
id: accountId,
|
||||
email: "person@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "candidate_consents",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
type Seed = {
|
||||
step?: Session["account"]["onboarding_step"];
|
||||
profileVersion?: number;
|
||||
declared?: { specialization: string; grade: string } | null;
|
||||
confirmed?: string | null;
|
||||
activeAttempt?: string | null;
|
||||
results?: unknown[];
|
||||
privacy?: unknown;
|
||||
};
|
||||
|
||||
const closedPrivacy = {
|
||||
publication: {
|
||||
state: "closed",
|
||||
closed_reason: "never_published",
|
||||
fields: [],
|
||||
consent_id: null,
|
||||
published_at: null,
|
||||
version: 0,
|
||||
},
|
||||
search_status: {
|
||||
value: "not_looking",
|
||||
lapsed: false,
|
||||
confirmed_at: null,
|
||||
lapses_at: null,
|
||||
version: 0,
|
||||
},
|
||||
hidden_organizations_total: 0,
|
||||
};
|
||||
|
||||
function render(seed: Seed = {}): string {
|
||||
const queryClient = new QueryClient();
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
|
||||
...session,
|
||||
account: { ...session.account, onboarding_step: seed.step ?? "candidate_consents" },
|
||||
});
|
||||
queryClient.setQueryData(candidateHomeQueryKeys.profile(accountId), {
|
||||
version: seed.profileVersion ?? 0,
|
||||
});
|
||||
queryClient.setQueryData(candidateHomeQueryKeys.questionnaire(accountId), {
|
||||
version: seed.declared ? 1 : 0,
|
||||
specializations: seed.declared
|
||||
? [
|
||||
{
|
||||
specialization: seed.declared.specialization,
|
||||
self_assessed_grade: seed.declared.grade,
|
||||
task_languages: [],
|
||||
stack: [],
|
||||
experience: null,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
work_context: null,
|
||||
updated_at: null,
|
||||
});
|
||||
queryClient.setQueryData(candidateHomeQueryKeys.availability(accountId), {
|
||||
specializations: seed.declared
|
||||
? [
|
||||
{
|
||||
specialization: seed.declared.specialization,
|
||||
confirmed_grade: seed.confirmed ?? null,
|
||||
active_attempt_id: seed.activeAttempt ?? null,
|
||||
grades: [
|
||||
{
|
||||
grade: seed.declared.grade,
|
||||
status: "available",
|
||||
mode: null,
|
||||
available_at: null,
|
||||
time_limit_seconds: null,
|
||||
max_sessions: null,
|
||||
max_items: null,
|
||||
practice_required: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
});
|
||||
queryClient.setQueryData(candidateHomeQueryKeys.latestResult(accountId), {
|
||||
items: seed.results ?? [],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
});
|
||||
queryClient.setQueryData(
|
||||
candidateHomeQueryKeys.privacy(accountId),
|
||||
seed.privacy ?? closedPrivacy,
|
||||
);
|
||||
|
||||
return renderToString(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<CandidateHomePage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function linkTo(html: string, href: string, text: string): boolean {
|
||||
return new RegExp(`<a[^>]*href="${href}"[^>]*>${text}</a>`).test(html);
|
||||
}
|
||||
|
||||
describe("candidate home", () => {
|
||||
it("leads an empty profile to the form without requiring any linking", () => {
|
||||
const html = render();
|
||||
|
||||
expect(html).toMatch(/<h1[^>]*>Главная<\/h1>/);
|
||||
expect(html).toContain("Заполните профиль");
|
||||
expect(linkTo(html, "/candidate/profile", "Заполнить профиль")).toBe(true);
|
||||
expect(html).toContain("Сохраненный шаг аккаунта: <strong>Согласия</strong>");
|
||||
expect(html).toContain("Привязка ФСП ID необязательна");
|
||||
// A missing FSP link or ML result is never an error.
|
||||
expect(html).not.toContain('role="alert"');
|
||||
});
|
||||
|
||||
it("leads a filled profile to the questionnaire", () => {
|
||||
const html = render({ profileVersion: 2 });
|
||||
|
||||
expect(html).toContain("Заполните анкету");
|
||||
expect(linkTo(html, "/candidate/questionnaire", "Заполнить анкету")).toBe(true);
|
||||
});
|
||||
|
||||
it("leads a saved questionnaire to the test and shows no confirmed category", () => {
|
||||
const html = render({
|
||||
step: "candidate_assessment",
|
||||
profileVersion: 2,
|
||||
declared: { specialization: "backend", grade: "middle" },
|
||||
});
|
||||
|
||||
expect(html).toContain("Подтвердите уровень тестом");
|
||||
expect(linkTo(html, "/candidate/assessment", "Перейти к тесту")).toBe(true);
|
||||
expect(html).toContain("Заявлено: Middle");
|
||||
expect(html).toContain("Пока не подтверждена");
|
||||
expect(html).not.toContain("Подтверждено тестом:");
|
||||
expect(html).toContain("Завершенных попыток пока нет");
|
||||
});
|
||||
|
||||
it("resumes an active attempt", () => {
|
||||
const html = render({
|
||||
step: "candidate_assessment",
|
||||
profileVersion: 2,
|
||||
declared: { specialization: "backend", grade: "junior" },
|
||||
activeAttempt: attemptId,
|
||||
});
|
||||
|
||||
expect(html).toContain("Продолжите тест");
|
||||
expect(linkTo(html, `/candidate/assessment/${attemptId}`, "Продолжить попытку")).toBe(true);
|
||||
});
|
||||
|
||||
it("shows the result, the privacy link, and the declared grade apart from the category", () => {
|
||||
const html = render({
|
||||
step: "candidate_assessment",
|
||||
profileVersion: 2,
|
||||
declared: { specialization: "backend", grade: "middle" },
|
||||
confirmed: "junior",
|
||||
});
|
||||
|
||||
expect(html).toContain("Категория получена");
|
||||
expect(linkTo(html, "/candidate/results", "Открыть результат")).toBe(true);
|
||||
expect(linkTo(html, "/candidate/privacy", "Настроить видимость")).toBe(true);
|
||||
expect(html).toContain("Заявлено: Middle");
|
||||
expect(html).toContain("Подтверждено тестом: Junior");
|
||||
expect(html).toContain("Закрыта: компании ее не видят. Вы еще не публиковали карточку.");
|
||||
});
|
||||
|
||||
it("restates a published card and an active search status from the API", () => {
|
||||
const html = render({
|
||||
profileVersion: 1,
|
||||
declared: { specialization: "qa", grade: "junior" },
|
||||
confirmed: "junior",
|
||||
privacy: {
|
||||
publication: {
|
||||
state: "published",
|
||||
closed_reason: null,
|
||||
fields: ["categories"],
|
||||
consent_id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81",
|
||||
published_at: "2026-10-08T10:00:00Z",
|
||||
version: 2,
|
||||
},
|
||||
search_status: {
|
||||
value: "looking",
|
||||
lapsed: false,
|
||||
confirmed_at: "2026-10-08T10:00:00Z",
|
||||
lapses_at: "2026-11-07T10:00:00Z",
|
||||
version: 1,
|
||||
},
|
||||
hidden_organizations_total: 0,
|
||||
},
|
||||
});
|
||||
|
||||
expect(html).toContain("Открыта: компании видят выбранные поля");
|
||||
expect(html).toContain("Показывается");
|
||||
expect(html).toContain("Ищу работу, статус действует до");
|
||||
});
|
||||
|
||||
it("describes a result that did not assign a category without presenting a grade", () => {
|
||||
const html = render({
|
||||
step: "candidate_assessment",
|
||||
profileVersion: 1,
|
||||
declared: { specialization: "backend", grade: "junior" },
|
||||
results: [
|
||||
{
|
||||
attempt_id: attemptId,
|
||||
specialization: "backend",
|
||||
target_grade: "junior",
|
||||
root_attempt_id: null,
|
||||
chain_deadline: null,
|
||||
task_language: null,
|
||||
kind: "root",
|
||||
mode: "demo_basic",
|
||||
versions: {},
|
||||
outcome: "not_confirmed",
|
||||
not_determined_reason: null,
|
||||
confirmed_grade: null,
|
||||
previous_confirmed_grade: null,
|
||||
strength: null,
|
||||
calibration_status: "uncalibrated",
|
||||
limitations: [],
|
||||
uncertainty: null,
|
||||
basic_score: null,
|
||||
practices: [],
|
||||
gaps: [],
|
||||
durations: {},
|
||||
next_steps: [],
|
||||
decided_at: "2026-10-08T10:00:00Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(html).toContain("Уровень пока не подтвержден: Backend, Junior.");
|
||||
expect(linkTo(html, `/candidate/results/${attemptId}`, "Открыть разбор результата")).toBe(true);
|
||||
expect(html).not.toContain("Подтверждено тестом:");
|
||||
expect(html).toContain("Пока не подтверждена");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
summarizeVisibility,
|
||||
useCandidateLatestResultRead,
|
||||
useCandidatePrivacyRead,
|
||||
type VisibilitySummary,
|
||||
} from "../../../entities/candidate";
|
||||
import { assessmentResultSummary } from "../../../entities/assessment";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { AssessmentResultHistoryPage, PrivacySettings } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { ButtonLink, EmptyState, Page, QueryView, Section, TextLink } from "../../../shared/ui";
|
||||
import { CandidateNextStep } from "../../../widgets/candidate-next-step";
|
||||
import styles from "./candidate-home-page.module.css";
|
||||
|
||||
const closedReasonText: Readonly<Record<NonNullable<VisibilitySummary["closedReason"]>, string>> = {
|
||||
never_published: "Вы еще не публиковали карточку.",
|
||||
closed_by_candidate: "Вы закрыли карточку.",
|
||||
consent_revoked: "Согласие C2 отозвано, поэтому карточка закрыта.",
|
||||
};
|
||||
|
||||
function formatDate(value: string): string {
|
||||
return new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium" }).format(new Date(value));
|
||||
}
|
||||
|
||||
function searchStatusText(search: VisibilitySummary["searchStatus"]): string {
|
||||
if (search.looking) {
|
||||
return search.lapsesAt
|
||||
? `Ищу работу, статус действует до ${formatDate(search.lapsesAt)}`
|
||||
: "Ищу работу";
|
||||
}
|
||||
return search.lapsed
|
||||
? "Статус «Ищу работу» истек, сейчас: не ищу. Подтвердите его на странице приватности."
|
||||
: "Не ищу работу";
|
||||
}
|
||||
|
||||
function VisibilityFacts({ settings }: { settings: PrivacySettings }) {
|
||||
const visibility = summarizeVisibility(settings);
|
||||
return (
|
||||
<>
|
||||
<dl className={styles.facts}>
|
||||
<dt>Карточка для компаний</dt>
|
||||
<dd>
|
||||
{visibility.published
|
||||
? "Открыта: компании видят выбранные поля"
|
||||
: `Закрыта: компании ее не видят. ${
|
||||
visibility.closedReason ? closedReasonText[visibility.closedReason] : ""
|
||||
}`.trim()}
|
||||
</dd>
|
||||
{visibility.published ? (
|
||||
<>
|
||||
<dt>Категория в карточке</dt>
|
||||
<dd>{visibility.showsCategory ? "Показывается" : "Не показывается"}</dd>
|
||||
</>
|
||||
) : null}
|
||||
<dt>Статус поиска</dt>
|
||||
<dd>{searchStatusText(visibility.searchStatus)}</dd>
|
||||
</dl>
|
||||
<div>
|
||||
<ButtonLink to={paths.candidate.privacy} variant="secondary">
|
||||
Настроить видимость и согласия
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function VisibilitySection() {
|
||||
const session = useGetCurrentSession();
|
||||
const privacy = useCandidatePrivacyRead(session.data);
|
||||
return (
|
||||
<Section
|
||||
title="Видимость профиля"
|
||||
description="Компании видят только то, что вы открыли. Контакты скрыты до вашего решения."
|
||||
>
|
||||
<QueryView query={privacy} loadingLabel="Загружаем настройки видимости...">
|
||||
{(settings) => <VisibilityFacts settings={settings} />}
|
||||
</QueryView>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function LatestResult({ page }: { page: AssessmentResultHistoryPage }) {
|
||||
const [latest] = page.items;
|
||||
if (!latest) return null;
|
||||
const summary = assessmentResultSummary(latest);
|
||||
return (
|
||||
<>
|
||||
<p className={styles["result-text"]}>{summary.text}</p>
|
||||
{summary.reason ? <p className={styles.reason}>{summary.reason}</p> : null}
|
||||
<p className={styles.reason}>Решение сохранено: {formatDate(latest.decided_at)}</p>
|
||||
<div className={styles.links}>
|
||||
<TextLink to={paths.candidate.result(latest.attempt_id)}>
|
||||
Открыть разбор результата
|
||||
</TextLink>
|
||||
<TextLink to={paths.candidate.results}>История результатов</TextLink>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LatestResultSection() {
|
||||
const session = useGetCurrentSession();
|
||||
const results = useCandidateLatestResultRead(session.data);
|
||||
return (
|
||||
<Section
|
||||
title="Последний результат"
|
||||
description="Результат показывает решение сервера по последней завершенной попытке."
|
||||
>
|
||||
<QueryView
|
||||
query={results}
|
||||
loadingLabel="Загружаем результаты..."
|
||||
isEmpty={(page) => page.items.length === 0}
|
||||
empty={
|
||||
<EmptyState
|
||||
title="Завершенных попыток пока нет"
|
||||
description="Результат появится здесь после первой завершенной попытки теста."
|
||||
/>
|
||||
}
|
||||
>
|
||||
{(page) => <LatestResult page={page} />}
|
||||
</QueryView>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Candidate home: the next step and links to available actions, then the
|
||||
* last assessment result and the current visibility of the profile. The
|
||||
* independent blocks fail on their own, so one failed read never hides the
|
||||
* next step.
|
||||
*/
|
||||
export function CandidateHomePage() {
|
||||
return (
|
||||
<Page
|
||||
title="Главная"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Что сделать дальше, какой уровень вы заявили и какой подтвержден тестом."
|
||||
width="wide"
|
||||
>
|
||||
<CandidateNextStep />
|
||||
<div className={styles.columns}>
|
||||
<LatestResultSection />
|
||||
<VisibilitySection />
|
||||
</div>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export const paths = {
|
||||
assessmentAttempt: (attemptId: string) =>
|
||||
`/candidate/assessment/${encodeURIComponent(attemptId)}`,
|
||||
results: "/candidate/results",
|
||||
result: (attemptId: string) => `/candidate/results/${encodeURIComponent(attemptId)}`,
|
||||
invitations: "/candidate/invitations",
|
||||
privacy: "/candidate/privacy",
|
||||
supportCases: "/candidate/support/cases",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export { AssessmentHistory } from "./ui/assessment-history";
|
||||
export { AssessmentHistoryList } from "./ui/assessment-history-list";
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Ref } from "react";
|
||||
import type { AssessmentResult } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import { TextLink } from "../../../shared/ui";
|
||||
import { describeAssessmentResult } from "../../../entities/assessment";
|
||||
import styles from "./assessment-history.module.css";
|
||||
|
||||
type AssessmentHistoryListProps = {
|
||||
items: readonly AssessmentResult[];
|
||||
/** IANA zone for dates; the browser zone when omitted. */
|
||||
timeZone?: string;
|
||||
listRef?: Ref<HTMLOListElement>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compact rows of stored results, newest first as the server ordered them.
|
||||
* Each row restates the server decision; the full record is one link away.
|
||||
*/
|
||||
export function AssessmentHistoryList({ items, timeZone, listRef }: AssessmentHistoryListProps) {
|
||||
return (
|
||||
<ol className={styles.list} aria-label="История результатов" ref={listRef}>
|
||||
{items.map((item) => {
|
||||
const view = describeAssessmentResult(item, timeZone ? { timeZone } : {});
|
||||
return (
|
||||
<li key={item.attempt_id} className={styles.item}>
|
||||
<p className={styles.kind}>{view.kindLabel}</p>
|
||||
<h2 className={styles.title}>{view.title}</h2>
|
||||
<p className={styles.summary}>{view.summary.text}</p>
|
||||
<dl className={styles.facts}>
|
||||
{view.facts.map((fact) => (
|
||||
<div key={fact.label}>
|
||||
<dt>{fact.label}</dt>
|
||||
<dd>{fact.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<TextLink to={paths.candidate.result(view.attemptId)}>
|
||||
Открыть результат: {view.title}, {view.decidedDay}
|
||||
</TextLink>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.note {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.item {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.item p {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.kind {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
line-height: var(--line-height-snug);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.summary {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 12rem), 1fr));
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.facts > div {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.item {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
.live {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type { AssessmentResult, Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { assessmentQueryKeys } from "../../../entities/assessment";
|
||||
import { AssessmentHistory } from "./assessment-history";
|
||||
import { AssessmentHistoryList } from "./assessment-history-list";
|
||||
|
||||
const session = {
|
||||
account: {
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
email: "person@example.test",
|
||||
email_verified: true,
|
||||
scenario: "candidate",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
function stored(id: string, patch: Record<string, unknown> = {}): AssessmentResult {
|
||||
return {
|
||||
attempt_id: id,
|
||||
specialization: "backend",
|
||||
target_grade: "middle",
|
||||
root_attempt_id: null,
|
||||
chain_deadline: null,
|
||||
task_language: "go",
|
||||
kind: "root",
|
||||
mode: "demo_basic",
|
||||
versions: { bank_version: "demo-1", algorithm_version: "basic-1", policy_version: 1 },
|
||||
outcome: "confirmed",
|
||||
not_determined_reason: null,
|
||||
confirmed_grade: "middle",
|
||||
previous_confirmed_grade: null,
|
||||
category_decision: {
|
||||
status: "assigned",
|
||||
previous_confirmed_grade: null,
|
||||
current_confirmed_grade: "middle",
|
||||
method: "demo_basic_pass_mark",
|
||||
source: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
},
|
||||
strength: null,
|
||||
calibration_status: "uncalibrated",
|
||||
limitations: ["demo_bank"],
|
||||
uncertainty: null,
|
||||
basic_score: { points: 17, max_points: 20, pass_points: 14 },
|
||||
practices: [],
|
||||
gaps: [],
|
||||
durations: { items_seconds: 600, practice_seconds: null },
|
||||
next_steps: [],
|
||||
decided_at: "2026-10-08T09:30:00Z",
|
||||
...patch,
|
||||
} as unknown as AssessmentResult;
|
||||
}
|
||||
|
||||
function render(prepare: (queryClient: QueryClient) => void): string {
|
||||
// Server rendering refetches an errored query on mount unless told not to.
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } });
|
||||
prepare(queryClient);
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter>
|
||||
<AssessmentHistory actor={session} queryClient={queryClient} />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function seedPages(queryClient: QueryClient, pages: unknown[]) {
|
||||
queryClient.setQueryData(assessmentQueryKeys.resultHistory(session), {
|
||||
pages,
|
||||
pageParams: pages.map(() => null),
|
||||
});
|
||||
}
|
||||
|
||||
function seedError(queryClient: QueryClient, error: Error) {
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.build(queryClient, { queryKey: assessmentQueryKeys.resultHistory(session) })
|
||||
.setState({ status: "error", error, errorUpdateCount: 1, fetchStatus: "idle" });
|
||||
}
|
||||
|
||||
const firstId = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff";
|
||||
const secondId = "0199b4f2-7c1e-7d3a-9f00-112233445566";
|
||||
|
||||
describe("AssessmentHistory", () => {
|
||||
it("lists stored results with a link to each and says express runs are excluded", () => {
|
||||
const html = render((queryClient) =>
|
||||
seedPages(queryClient, [
|
||||
{
|
||||
items: [stored(firstId), stored(secondId, { outcome: "not_confirmed" })],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(html).toContain("Backend, Middle");
|
||||
expect(html).toContain(`href="${paths.candidate.result(firstId)}"`);
|
||||
expect(html).toContain(`href="${paths.candidate.result(secondId)}"`);
|
||||
expect(html).toContain("Демонстрационные запуски сюда не попадают");
|
||||
expect(html).not.toContain("Показать еще");
|
||||
});
|
||||
|
||||
it("offers the next page only while the server reports one", () => {
|
||||
const html = render((queryClient) =>
|
||||
seedPages(queryClient, [
|
||||
{ items: [stored(firstId)], page: { has_more: true, next_cursor: "next_page" } },
|
||||
]),
|
||||
);
|
||||
expect(html).toContain("Показать еще");
|
||||
});
|
||||
|
||||
it("shows an empty state with a way to the checks", () => {
|
||||
const html = render((queryClient) =>
|
||||
seedPages(queryClient, [{ items: [], page: { has_more: false, next_cursor: null } }]),
|
||||
);
|
||||
expect(html).toContain("Результатов пока нет");
|
||||
expect(html).toContain(`href="${paths.candidate.assessment}"`);
|
||||
});
|
||||
|
||||
it("shows a load error with a retry and no stale rows", () => {
|
||||
const html = render((queryClient) =>
|
||||
seedError(
|
||||
queryClient,
|
||||
new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }),
|
||||
),
|
||||
);
|
||||
expect(html).toContain("Не удалось загрузить историю результатов");
|
||||
expect(html).toContain("Повторить");
|
||||
expect(html).not.toContain("Backend");
|
||||
});
|
||||
|
||||
it("shows no data once the server refuses access", () => {
|
||||
const html = render((queryClient) =>
|
||||
seedError(
|
||||
queryClient,
|
||||
new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }),
|
||||
),
|
||||
);
|
||||
expect(html).toContain("История результатов недоступна");
|
||||
expect(html).toContain(`href="${paths.login}"`);
|
||||
expect(html).not.toContain("Backend");
|
||||
});
|
||||
|
||||
it("names each link with the title and the decision date", () => {
|
||||
const html = render((queryClient) =>
|
||||
seedPages(queryClient, [
|
||||
{ items: [stored(firstId)], page: { has_more: false, next_cursor: null } },
|
||||
]),
|
||||
);
|
||||
expect(html).toMatch(/Открыть результат: Backend, Middle, \d{1,2} \S+ 2026 г\./);
|
||||
});
|
||||
|
||||
it("separates an ended session from a refused one", () => {
|
||||
const ended = render((queryClient) =>
|
||||
seedError(
|
||||
queryClient,
|
||||
new ApiRequestError({ status: 401, code: "unauthenticated", title: "Unauthorized" }),
|
||||
),
|
||||
);
|
||||
const refused = render((queryClient) =>
|
||||
seedError(
|
||||
queryClient,
|
||||
new ApiRequestError({ status: 404, code: "not_found", title: "Not found" }),
|
||||
),
|
||||
);
|
||||
expect(ended).toContain("Сеанс закончился.");
|
||||
expect(refused).not.toContain("Сеанс закончился.");
|
||||
expect(refused).toContain("История результатов недоступна");
|
||||
});
|
||||
|
||||
it("keeps the loaded rows and says so when a refresh fails", () => {
|
||||
const html = render((queryClient) => {
|
||||
seedPages(queryClient, [
|
||||
{ items: [stored(firstId)], page: { has_more: false, next_cursor: null } },
|
||||
]);
|
||||
queryClient
|
||||
.getQueryCache()
|
||||
.build(queryClient, { queryKey: assessmentQueryKeys.resultHistory(session) })
|
||||
.setState({
|
||||
status: "error",
|
||||
error: new ApiRequestError({ status: 500, code: "internal", title: "Internal error" }),
|
||||
errorUpdateCount: 1,
|
||||
fetchStatus: "idle",
|
||||
});
|
||||
});
|
||||
expect(html).toContain("Backend, Middle");
|
||||
expect(html).toContain("Не удалось обновить историю. Показаны ранее загруженные результаты.");
|
||||
});
|
||||
|
||||
it("shows the loading state before the first answer", () => {
|
||||
const html = render(() => {});
|
||||
expect(html).toContain("Загружаем историю результатов...");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AssessmentHistoryList", () => {
|
||||
it("keeps the order the server sent", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<MemoryRouter>
|
||||
<AssessmentHistoryList
|
||||
timeZone="UTC"
|
||||
items={[
|
||||
stored(firstId, { decided_at: "2026-10-09T09:30:00Z" }),
|
||||
stored(secondId, { decided_at: "2026-10-01T09:30:00Z" }),
|
||||
]}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
expect(html.indexOf("9 октября 2026")).toBeGreaterThan(-1);
|
||||
expect(html.indexOf("9 октября 2026")).toBeLessThan(html.indexOf("1 октября 2026"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config/paths";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
LoadingState,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
isAssessmentAccessLoss,
|
||||
isAssessmentSessionEnded,
|
||||
removeAssessmentQueries,
|
||||
useAssessmentResultHistory,
|
||||
} from "../../../entities/assessment";
|
||||
import { AssessmentHistoryList } from "./assessment-history-list";
|
||||
import styles from "./assessment-history.module.css";
|
||||
|
||||
type AssessmentHistoryProps = {
|
||||
actor: Session;
|
||||
queryClient: QueryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Immutable real results of the signed-in candidate. The list is read for
|
||||
* the current session only. A lost session removes the cached rows; a 403 or
|
||||
* 404 shows no data but leaves other cached answers alone. A failed
|
||||
* background refresh keeps the rows that were already loaded. Express runs
|
||||
* are not part of the history.
|
||||
*/
|
||||
export function AssessmentHistory({ actor, queryClient }: AssessmentHistoryProps) {
|
||||
const history = useAssessmentResultHistory({ actor, queryClient });
|
||||
const accessLost = history.isError && isAssessmentAccessLoss(history.error);
|
||||
const sessionEnded = history.isError && isAssessmentSessionEnded(history.error);
|
||||
const listRef = useRef<HTMLOListElement>(null);
|
||||
const focusFrom = useRef<number | null>(null);
|
||||
const [announcement, setAnnouncement] = useState("");
|
||||
const itemCount = history.data?.pages.reduce((total, page) => total + page.items.length, 0) ?? 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (sessionEnded) removeAssessmentQueries(queryClient);
|
||||
}, [sessionEnded, queryClient]);
|
||||
|
||||
// After "Show more" the focus moves to the first new row, so the keyboard
|
||||
// position is not lost when the button disappears or moves down.
|
||||
useEffect(() => {
|
||||
const from = focusFrom.current;
|
||||
if (from === null || itemCount <= from) return;
|
||||
focusFrom.current = null;
|
||||
listRef.current?.querySelectorAll<HTMLAnchorElement>("li a")[from]?.focus();
|
||||
}, [itemCount]);
|
||||
|
||||
async function loadMore() {
|
||||
const before = itemCount;
|
||||
focusFrom.current = before;
|
||||
const result = await history.fetchNextPage();
|
||||
if (result.isError || !result.data) {
|
||||
focusFrom.current = null;
|
||||
return;
|
||||
}
|
||||
const total = result.data.pages.reduce((sum, page) => sum + page.items.length, 0);
|
||||
setAnnouncement(`Загружено еще результатов: ${total - before}. Всего: ${total}.`);
|
||||
}
|
||||
|
||||
if (accessLost) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
error={history.error}
|
||||
title="История результатов недоступна"
|
||||
description={
|
||||
sessionEnded
|
||||
? "Сеанс закончился. Войдите в кабинет кандидата и повторите."
|
||||
: "Сервер не подтвердил доступ к истории. Войдите в кабинет кандидата и повторите."
|
||||
}
|
||||
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (history.isPending) return <LoadingState label="Загружаем историю результатов..." />;
|
||||
if (history.isError && !history.data) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={history.error}
|
||||
isRetrying={history.isRefetching}
|
||||
onRetry={() => void history.refetch()}
|
||||
title="Не удалось загрузить историю результатов"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const items = history.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<EmptyState
|
||||
title="Результатов пока нет"
|
||||
description="Здесь появятся завершенные реальные проверки. Демонстрационные запуски в историю не входят."
|
||||
action={<ButtonLink to={paths.candidate.assessment}>К проверкам</ButtonLink>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<p className={styles.note}>
|
||||
В истории только завершенные реальные проверки. Демонстрационные запуски сюда не попадают и
|
||||
категорию не меняют.
|
||||
</p>
|
||||
{history.isRefetchError && !history.isFetchNextPageError ? (
|
||||
<ErrorState
|
||||
error={history.error}
|
||||
isRetrying={history.isRefetching}
|
||||
onRetry={() => void history.refetch()}
|
||||
title="Не удалось обновить историю. Показаны ранее загруженные результаты."
|
||||
/>
|
||||
) : null}
|
||||
<AssessmentHistoryList items={items} listRef={listRef} />
|
||||
<p className={styles.live} role="status">
|
||||
{announcement}
|
||||
</p>
|
||||
{history.isFetchNextPageError ? (
|
||||
<ErrorState
|
||||
error={history.error}
|
||||
title="Не удалось загрузить следующие результаты"
|
||||
isRetrying={history.isFetchingNextPage}
|
||||
onRetry={() => void loadMore()}
|
||||
/>
|
||||
) : history.hasNextPage ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={history.isFetchingNextPage}
|
||||
onClick={() => void loadMore()}
|
||||
>
|
||||
{history.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { CandidateNextStep } from "./ui/candidate-next-step";
|
||||
@@ -0,0 +1,126 @@
|
||||
.root {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
}
|
||||
|
||||
/* The next step is the one dominant block of the home screen. */
|
||||
.card {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-5);
|
||||
border: var(--line-strong) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-l);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.card-eyebrow {
|
||||
color: var(--color-accent);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-bold);
|
||||
letter-spacing: var(--letter-spacing-label);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: var(--font-size-xl);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-snug);
|
||||
}
|
||||
|
||||
.card-text {
|
||||
max-width: 44rem;
|
||||
font-size: var(--font-size-m);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
padding-top: var(--space-2);
|
||||
}
|
||||
|
||||
.note {
|
||||
max-width: 44rem;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.columns {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
}
|
||||
|
||||
@media (width >= 64rem) {
|
||||
.columns {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
align-items: start;
|
||||
}
|
||||
}
|
||||
|
||||
.standings,
|
||||
.links {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.standing,
|
||||
.link {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.standing-title {
|
||||
margin-bottom: var(--space-3);
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.facts {
|
||||
grid-template-columns: minmax(9rem, auto) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.facts dd {
|
||||
min-width: 0;
|
||||
margin: 0 0 var(--space-2);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.link {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.link-label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.link-status {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import type { ReactNode } from "react";
|
||||
import {
|
||||
onboardingStepLabels,
|
||||
useCandidateJourney,
|
||||
type CandidateJourney,
|
||||
type CandidateNextStep as NextStep,
|
||||
type SpecializationStanding,
|
||||
} from "../../../entities/candidate";
|
||||
import { gradeLabels, specializationLabels } from "../../../entities/assessment";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Section,
|
||||
TextLink,
|
||||
TrustLevel,
|
||||
} from "../../../shared/ui";
|
||||
import styles from "./candidate-next-step.module.css";
|
||||
|
||||
type StepView = {
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
action: { label: string; to: string };
|
||||
secondary?: { label: string; to: string };
|
||||
/** True while the optional FSP link is worth mentioning. */
|
||||
mentionsOptionalFsp: boolean;
|
||||
};
|
||||
|
||||
function standingLabel(standing: SpecializationStanding): string {
|
||||
return `${specializationLabels[standing.specialization]}, ${
|
||||
standing.declaredGrade ? gradeLabels[standing.declaredGrade] : "уровень не указан"
|
||||
}`;
|
||||
}
|
||||
|
||||
function describeNextStep(journey: CandidateJourney, step: NextStep): StepView {
|
||||
switch (step.kind) {
|
||||
case "profile":
|
||||
return {
|
||||
title: "Заполните профиль",
|
||||
description:
|
||||
"Профиль еще не сохранен. Его можно заполнить вручную, без резюме и без привязки аккаунта ФСП.",
|
||||
action: { label: "Заполнить профиль", to: paths.candidate.profile },
|
||||
mentionsOptionalFsp: true,
|
||||
};
|
||||
case "questionnaire":
|
||||
return {
|
||||
title: "Заполните анкету",
|
||||
description:
|
||||
"Укажите специализацию и уровень, на который вы претендуете. Это самооценка: подтвержденную категорию присваивает только тест.",
|
||||
action: { label: "Заполнить анкету", to: paths.candidate.questionnaire },
|
||||
mentionsOptionalFsp: true,
|
||||
};
|
||||
case "assessment": {
|
||||
const declared = journey.standings.map(standingLabel).join("; ");
|
||||
const canStart = journey.standings.some((standing) => standing.canStartAttempt);
|
||||
return {
|
||||
title: "Подтвердите уровень тестом",
|
||||
description: (
|
||||
<>
|
||||
Заявлено: {declared}. Заявленный уровень не считается категорией, пока его не подтвердит
|
||||
тест.{" "}
|
||||
{canStart
|
||||
? "Тест можно начать сейчас."
|
||||
: "Сейчас ни один уровень не открыт для начала; на странице теста указано, что мешает и когда это изменится."}
|
||||
</>
|
||||
),
|
||||
action: { label: "Перейти к тесту", to: paths.candidate.assessment },
|
||||
mentionsOptionalFsp: true,
|
||||
};
|
||||
}
|
||||
case "resume_attempt":
|
||||
return {
|
||||
title: "Продолжите тест",
|
||||
description: `Есть незавершенная попытка: ${specializationLabels[step.specialization]}. Ответы хранятся на сервере.`,
|
||||
action: {
|
||||
label: "Продолжить попытку",
|
||||
to: paths.candidate.assessmentAttempt(step.attemptId),
|
||||
},
|
||||
mentionsOptionalFsp: true,
|
||||
};
|
||||
case "result":
|
||||
return {
|
||||
title: "Категория получена",
|
||||
description: `Подтверждено тестом: ${journey.confirmed
|
||||
.flatMap((standing) =>
|
||||
standing.confirmedGrade
|
||||
? [
|
||||
`${specializationLabels[standing.specialization]}, ${gradeLabels[standing.confirmedGrade]}`,
|
||||
]
|
||||
: [],
|
||||
)
|
||||
.join("; ")}. Посмотрите результат и решите, кому видна ваша карточка.`,
|
||||
action: { label: "Открыть результат", to: paths.candidate.results },
|
||||
secondary: { label: "Настроить видимость", to: paths.candidate.privacy },
|
||||
mentionsOptionalFsp: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function NextStepCard({ journey }: { journey: CandidateJourney }) {
|
||||
const view = describeNextStep(journey, journey.nextStep);
|
||||
return (
|
||||
<section className={styles.card} aria-labelledby="next-step-title">
|
||||
<p className={styles["card-eyebrow"]}>Следующий шаг</p>
|
||||
<h2 id="next-step-title" className={styles["card-title"]}>
|
||||
{view.title}
|
||||
</h2>
|
||||
<p className={styles["card-text"]}>{view.description}</p>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink to={view.action.to}>{view.action.label}</ButtonLink>
|
||||
{view.secondary ? (
|
||||
<ButtonLink to={view.secondary.to} variant="secondary">
|
||||
{view.secondary.label}
|
||||
</ButtonLink>
|
||||
) : null}
|
||||
</div>
|
||||
<p className={styles.note}>
|
||||
Сохраненный шаг аккаунта: <strong>{onboardingStepLabels[journey.savedStep]}</strong>.
|
||||
{view.mentionsOptionalFsp
|
||||
? " Привязка ФСП ID необязательна: путь до категории проходит через анкету и тест."
|
||||
: null}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Standings({ journey }: { journey: CandidateJourney }) {
|
||||
return (
|
||||
<Section
|
||||
title="Заявлено и подтверждено"
|
||||
headingLevel={2}
|
||||
description="Заявленный уровень - это ваша самооценка из анкеты. Подтвержденной бывает только категория, которую присвоил тест."
|
||||
>
|
||||
{journey.standings.length === 0 ? (
|
||||
<EmptyState
|
||||
title="Анкета еще не сохранена"
|
||||
description="Заявленный уровень появится после анкеты."
|
||||
action={<ButtonLink to={paths.candidate.questionnaire}>Заполнить анкету</ButtonLink>}
|
||||
/>
|
||||
) : (
|
||||
<ul className={styles.standings}>
|
||||
{journey.standings.map((standing) => (
|
||||
<li key={standing.specialization} className={styles.standing}>
|
||||
<h3 className={styles["standing-title"]}>
|
||||
{specializationLabels[standing.specialization]}
|
||||
</h3>
|
||||
<dl className={styles.facts}>
|
||||
<dt>Заявлено (самооценка)</dt>
|
||||
<dd>
|
||||
<TrustLevel
|
||||
level="claimed"
|
||||
label={
|
||||
standing.declaredGrade
|
||||
? `Заявлено: ${gradeLabels[standing.declaredGrade]}`
|
||||
: "Уровень не указан"
|
||||
}
|
||||
/>
|
||||
</dd>
|
||||
<dt>Подтвержденная категория</dt>
|
||||
<dd>
|
||||
{standing.confirmedGrade ? (
|
||||
<TrustLevel
|
||||
level="confirmed"
|
||||
label={`Подтверждено тестом: ${gradeLabels[standing.confirmedGrade]}`}
|
||||
/>
|
||||
) : (
|
||||
<TrustLevel level="none" label="Пока не подтверждена" />
|
||||
)}
|
||||
</dd>
|
||||
</dl>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
type SectionLink = { label: string; status: string; to: string | null; linkLabel: string };
|
||||
|
||||
function sectionLinks(journey: CandidateJourney): SectionLink[] {
|
||||
const hasConfirmed = journey.confirmed.length > 0;
|
||||
const hasActiveAttempt = journey.standings.some((standing) => standing.activeAttemptId !== null);
|
||||
const testStatus = !journey.questionnaireSaved
|
||||
? "Откроется после анкеты"
|
||||
: hasConfirmed
|
||||
? "Есть подтвержденная категория"
|
||||
: hasActiveAttempt
|
||||
? "Есть незавершенная попытка"
|
||||
: "Еще не пройден";
|
||||
|
||||
return [
|
||||
{
|
||||
label: "Профиль",
|
||||
status: journey.profileSaved ? "Сохранен" : "Не заполнен",
|
||||
to: paths.candidate.profile,
|
||||
linkLabel: journey.profileSaved ? "Открыть профиль" : "Заполнить профиль",
|
||||
},
|
||||
{
|
||||
label: "Анкета",
|
||||
status: journey.questionnaireSaved ? "Сохранена" : "Не заполнена",
|
||||
to: paths.candidate.questionnaire,
|
||||
linkLabel: journey.questionnaireSaved ? "Открыть анкету" : "Заполнить анкету",
|
||||
},
|
||||
{
|
||||
label: "Тест",
|
||||
status: testStatus,
|
||||
to: journey.questionnaireSaved ? paths.candidate.assessment : null,
|
||||
linkLabel: "Перейти к тесту",
|
||||
},
|
||||
{
|
||||
label: "Результаты",
|
||||
status: hasConfirmed ? "Есть категория" : "Появятся после теста",
|
||||
to: paths.candidate.results,
|
||||
linkLabel: "Результаты и история",
|
||||
},
|
||||
{
|
||||
label: "Приватность",
|
||||
status: "Согласия, видимость карточки, статус поиска",
|
||||
to: paths.candidate.privacy,
|
||||
linkLabel: "Открыть настройки",
|
||||
},
|
||||
{
|
||||
label: "Поддержка",
|
||||
status: "Обращения и запрос ручной оценки",
|
||||
to: paths.candidate.supportCases,
|
||||
linkLabel: "Открыть обращения",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function AvailableActions({ journey }: { journey: CandidateJourney }) {
|
||||
return (
|
||||
<Section title="Доступные действия" headingLevel={2}>
|
||||
<ul className={styles.links}>
|
||||
{sectionLinks(journey).map((item) => (
|
||||
<li key={item.label} className={styles.link}>
|
||||
<div>
|
||||
<p className={styles["link-label"]}>{item.label}</p>
|
||||
<p className={styles["link-status"]}>{item.status}</p>
|
||||
</div>
|
||||
{item.to ? <TextLink to={item.to}>{item.linkLabel}</TextLink> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The main block of the candidate home: the next step, the declared and the
|
||||
* confirmed level side by side, and links to the available actions. Everything
|
||||
* comes from one read of the profile, the questionnaire, and the assessment
|
||||
* availability; a failed read shows an error instead of a guessed step.
|
||||
*/
|
||||
export function CandidateNextStep() {
|
||||
const session = useGetCurrentSession();
|
||||
const state = useCandidateJourney(session.data);
|
||||
|
||||
if (session.isError) {
|
||||
if (isAccessDenied(session.error)) return <ForbiddenState error={session.error} />;
|
||||
return (
|
||||
<ErrorState
|
||||
error={session.error}
|
||||
isRetrying={session.isRefetching}
|
||||
onRetry={() => void session.refetch()}
|
||||
title="Не удалось проверить вход"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (state.status === "pending") {
|
||||
return <LoadingState label="Определяем следующий шаг..." />;
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (isAccessDenied(state.error)) return <ForbiddenState error={state.error} />;
|
||||
return (
|
||||
<ErrorState
|
||||
error={state.error}
|
||||
isRetrying={state.isRetrying}
|
||||
onRetry={state.retry}
|
||||
title="Не удалось определить следующий шаг"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<NextStepCard journey={state.journey} />
|
||||
<div className={styles.columns}>
|
||||
<Standings journey={state.journey} />
|
||||
<AvailableActions journey={state.journey} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user