feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

+39 -3
View File
@@ -2,8 +2,10 @@ import { QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { assessmentQueryKeys } from "../../entities/assessment";
import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent";
import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity";
import type { Session } from "../../shared/api/schemas";
import { createQueryClient } from "../providers/query-client";
import { routes } from "./routes";
@@ -20,7 +22,7 @@ async function render(path: string): Promise<string | Response> {
const queryClient = createQueryClient();
const scenario = path.startsWith("/employer") ? "employer" : "candidate";
if (path.startsWith("/candidate") || path.startsWith("/employer")) {
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
const session = {
account: {
id: "11111111-1111-4111-8111-111111111111",
email: "person@example.test",
@@ -39,7 +41,17 @@ async function render(path: string): Promise<string | Response> {
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
});
} satisfies Session;
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
if (path === "/candidate/assessment") {
queryClient.setQueryData(assessmentQueryKeys.availability(session), { specializations: [] });
queryClient.setQueryData(assessmentQueryKeys.questionnaire(session), {
version: 0,
specializations: [],
work_context: null,
updated_at: null,
});
}
}
if (path.startsWith("/candidate/privacy")) {
const hasMore = path.includes("history=partial");
@@ -122,7 +134,23 @@ describe("route groups", () => {
["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"],
["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"],
["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"],
["/candidate/assessment", "Проверка знаний", "Разделы кабинета кандидата"],
[
"/candidate/assessment/01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80",
"Попытка проверки",
"Разделы кабинета кандидата",
],
["/employer/company", "Компания", "Разделы кабинета работодателя"],
["/employer/needs", "Потребности", "Разделы кабинета работодателя"],
["/candidate/support/cases", "Мои обращения", "Разделы кабинета кандидата"],
["/candidate/support/cases/new", "Обратиться в поддержку", "Разделы кабинета кандидата"],
[
"/candidate/support/cases/manual-assessment",
"Запросить ручную оценку",
"Разделы кабинета кандидата",
],
["/employer/support/cases", "Мои обращения", "Разделы кабинета работодателя"],
["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"],
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
const html = await renderHtml(path);
@@ -183,6 +211,14 @@ describe("route groups", () => {
});
describe("product readiness", () => {
it("keeps the training run available when no full-assessment category exists", async () => {
const html = await renderHtml("/candidate/assessment");
expect(html).toContain("Сначала выберите специализацию");
expect(html).toContain("Начать демонстрацию");
expect(html).not.toContain("Начать полную проверку");
});
it("presents the root page as a scaffold, not as a working product", async () => {
const html = await renderHtml("/");
@@ -226,7 +262,7 @@ describe("product readiness", () => {
});
it("labels the remaining cabinet scaffolds as placeholders", async () => {
for (const path of ["/candidate", "/employer/needs"]) {
for (const path of ["/candidate", "/employer/candidates"]) {
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
}
});
+32 -3
View File
@@ -1,14 +1,23 @@
import { redirect, type RouteObject } from "react-router-dom";
import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment";
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { CompanyPage } from "../../pages/company";
import { ConsentsPage } from "../../pages/consents";
import { SessionGate } from "../../entities/session";
import { NotFoundPage } from "../../pages/not-found";
import { NeedEditorPage } from "../../pages/need-editor";
import { NeedListPage } from "../../pages/needs";
import { PlaceholderPage } from "../../pages/placeholder";
import { ProfilePage } from "../../pages/profile";
import { QuestionnairePage } from "../../pages/questionnaire";
import { StatusPage } from "../../pages/status";
import {
CreateSupportCasePage,
ManualAssessmentPage,
SupportCaseDetailPage,
SupportCasesPage,
} from "../../pages/support-cases";
import { WelcomePage } from "../../pages/welcome";
import { paths } from "../../shared/config";
import { CandidateShell } from "../../widgets/candidate-shell";
@@ -17,6 +26,7 @@ import { PublicShell } from "../../widgets/public-shell";
import { RootLayout } from "../ui/root-layout";
import { RouteErrorPage } from "../ui/route-error-page";
import { CandidateHomeRoute } from "./candidate-home-route";
import { SupportRoute } from "./support-route";
/**
* Route tree with public pages and role-specific cabinets. Protected shells
@@ -34,7 +44,7 @@ export const routes: RouteObject[] = [
{ path: paths.login, element: <LoginPage /> },
{ path: paths.register, element: <RegisterPage /> },
{ path: paths.verifyEmail, element: <VerifyEmailPage /> },
{ path: paths.support, element: <PlaceholderPage screen="support" /> },
{ path: paths.support, element: <SupportRoute /> },
{ path: paths.status, element: <StatusPage /> },
{ path: "*", element: <NotFoundPage /> },
],
@@ -58,7 +68,11 @@ export const routes: RouteObject[] = [
},
{
path: paths.candidate.assessment,
element: <PlaceholderPage screen="candidateAssessment" />,
element: <AssessmentPage />,
},
{
path: `${paths.candidate.assessment}/:attemptId`,
element: <AssessmentAttemptPage />,
},
{
path: paths.candidate.results,
@@ -72,6 +86,13 @@ export const routes: RouteObject[] = [
path: paths.candidate.privacy,
element: <ConsentsPage />,
},
{ path: paths.candidate.supportCases, element: <SupportCasesPage /> },
{ path: paths.candidate.supportNew, element: <CreateSupportCasePage /> },
{ path: paths.candidate.supportManual, element: <ManualAssessmentPage /> },
{
path: `${paths.candidate.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{
path: "*",
element: (
@@ -94,7 +115,15 @@ export const routes: RouteObject[] = [
path: paths.employer.company,
element: <CompanyPage />,
},
{ path: paths.employer.needs, element: <PlaceholderPage screen="employerNeeds" /> },
{ path: paths.employer.needs, element: <NeedListPage /> },
{ path: `${paths.employer.needs}/new`, element: <NeedEditorPage /> },
{ path: `${paths.employer.needs}/:needId`, element: <NeedEditorPage /> },
{ path: paths.employer.supportCases, element: <SupportCasesPage /> },
{ path: paths.employer.supportNew, element: <CreateSupportCasePage /> },
{
path: `${paths.employer.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{
path: paths.employer.candidates,
element: <PlaceholderPage screen="employerCandidates" />,
+57
View File
@@ -0,0 +1,57 @@
import { Navigate, useLocation } from "react-router-dom";
import { parseSupportCaseContext } from "../../entities/support-case";
import { ApiRequestError } from "../../shared/api";
import { useGetCurrentSession } from "../../shared/api/endpoints/identity/identity";
import { paths } from "../../shared/config";
import { ButtonLink, ErrorState, LoadingState, Page, Section } from "../../shared/ui";
/** Support remains reachable before completing either onboarding flow. */
export function SupportRoute() {
const session = useGetCurrentSession();
const location = useLocation();
if (session.isPending) {
return (
<Page title="Поддержка">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (session.isError) {
if (session.error instanceof ApiRequestError && session.error.status === 401) {
return (
<Page title="Поддержка" lead="Войдите, чтобы отправить обращение и следить за ответом.">
<Section title="Ваши обращения">
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
Войти и открыть поддержку
</ButtonLink>
</Section>
</Page>
);
}
return (
<Page title="Поддержка">
<ErrorState
title="Не удалось открыть поддержку"
error={session.error}
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
/>
</Page>
);
}
const state: unknown = location.state;
const context =
state && typeof state === "object" && !Array.isArray(state)
? parseSupportCaseContext((state as Record<string, unknown>).supportContext)
: null;
const cabinet = session.data.account.scenario === "candidate" ? paths.candidate : paths.employer;
return (
<Navigate
to={context ? cabinet.supportNew : cabinet.supportCases}
state={context ? { supportContext: context } : undefined}
replace
/>
);
}
+3 -1
View File
@@ -1,5 +1,6 @@
import { useRouteError } from "react-router-dom";
import { ErrorState, Page } from "../../shared/ui";
import { paths } from "../../shared/config";
import { ErrorState, Page, TextLink } from "../../shared/ui";
/**
* Last-resort boundary for errors thrown while rendering a route. It has no
@@ -18,6 +19,7 @@ export function RouteErrorPage() {
window.location.reload();
}}
/>
<TextLink to={paths.support}>Обратиться в поддержку</TextLink>
</Page>
</main>
);
@@ -0,0 +1,122 @@
import { useQuery, type QueryClient } from "@tanstack/react-query";
import {
getMyAssessmentAvailability,
getMyAssessmentAttempt,
getMyAssessmentResult,
} from "../../../shared/api/endpoints/assessment/assessment";
import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate";
import type {
AssessmentAttempt,
AssessmentAvailability,
AssessmentResult,
Session,
} from "../../../shared/api/schemas";
import {
parseAssessmentAvailabilityResponse,
parseAssessmentAttemptResponse,
parseAssessmentResultResponse,
parseCandidateQuestionnaireResponse,
} from "../model/contract-validation";
import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session";
type AssessmentQueryOptions = {
enabled?: boolean;
queryClient: QueryClient;
actor: Session | undefined;
};
const privateQueryOptions = {
gcTime: 0,
staleTime: 0,
refetchOnMount: "always" as const,
refetchOnWindowFocus: "always" as const,
retry: false,
};
export function useAssessmentAvailability({
actor,
enabled = true,
queryClient,
}: AssessmentQueryOptions) {
return useQuery<AssessmentAvailability, Error>({
queryKey: actor
? assessmentQueryKeys.availability(actor)
: [...assessmentQueryKeysPrefix, "availability"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
assertCurrentAssessmentSession(queryClient, actor);
const availability = await getMyAssessmentAvailability({ signal });
assertCurrentAssessmentSession(queryClient, actor);
return parseAssessmentAvailabilityResponse(availability);
},
});
}
export function useAssessmentQuestionnaire({
actor,
enabled = true,
queryClient,
}: AssessmentQueryOptions) {
return useQuery({
queryKey: actor
? assessmentQueryKeys.questionnaire(actor)
: [...assessmentQueryKeysPrefix, "questionnaire"],
enabled: Boolean(actor && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
assertCurrentAssessmentSession(queryClient, actor);
const questionnaire = await getMyQuestionnaire({ signal });
assertCurrentAssessmentSession(queryClient, actor);
return parseCandidateQuestionnaireResponse(questionnaire);
},
});
}
export function useAssessmentAttempt({
actor,
attemptId,
enabled = true,
queryClient,
}: AssessmentQueryOptions & { attemptId: string }) {
return useQuery<AssessmentAttempt, Error>({
queryKey: actor
? assessmentQueryKeys.attempt(actor, attemptId)
: [...assessmentQueryKeysPrefix, "attempt", attemptId],
enabled: Boolean(actor && attemptId && enabled),
...privateQueryOptions,
refetchInterval: (query) => {
const attempt = query.state.data;
return attempt?.practices.some((practice) => practice.status === "pending") ? 2500 : false;
},
queryFn: async ({ signal }) => {
assertCurrentAssessmentSession(queryClient, actor);
const response = await getMyAssessmentAttempt(attemptId, { signal });
assertCurrentAssessmentSession(queryClient, actor);
return parseAssessmentAttemptResponse(response);
},
});
}
export function useAssessmentResult({
actor,
attemptId,
enabled = true,
queryClient,
}: AssessmentQueryOptions & { attemptId: string }) {
return useQuery<AssessmentResult, Error>({
queryKey: actor
? assessmentQueryKeys.result(actor, attemptId)
: [...assessmentQueryKeysPrefix, "result", attemptId],
enabled: Boolean(actor && attemptId && enabled),
...privateQueryOptions,
queryFn: async ({ signal }) => {
assertCurrentAssessmentSession(queryClient, actor);
const response = await getMyAssessmentResult(attemptId, { signal });
assertCurrentAssessmentSession(queryClient, actor);
return parseAssessmentResultResponse(response);
},
});
}
const assessmentQueryKeysPrefix = ["candidate-assessment"] as const;
+29
View File
@@ -0,0 +1,29 @@
export {
useAssessmentAttempt,
useAssessmentAvailability,
useAssessmentQuestionnaire,
useAssessmentResult,
} from "./api/assessment-queries";
export {
assessmentQueryKeys,
assessmentQueryPrefix,
assessmentSessionMatches,
assertCurrentAssessmentSession,
isCurrentAssessmentSession,
removeAssessmentQueries,
removeAssessmentQueriesForSessionChange,
} from "./model/session";
export { isOutcomeAmbiguous } from "./model/idempotency";
export {
parseAssessmentAttemptResponse,
parseAssessmentResultResponse,
} from "./model/contract-validation";
export { assessmentResultSummary } from "./model/result-summary";
export {
availabilityLabels,
gradeLabels,
methodLabel,
outcomeLabels,
selectedSpecialization,
specializationLabels,
} from "./model/labels";
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import type { AssessmentAttempt } from "../../../shared/api/schemas";
import {
parseAssessmentAvailabilityResponse,
parseAssessmentAttemptResponse,
parseAssessmentResultResponse,
parseCandidateQuestionnaireResponse,
} from "./contract-validation";
const validAttempt: AssessmentAttempt = {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01",
version: 2,
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "python",
root_attempt_id: null,
chain_deadline: null,
mode: "demo_basic",
state: "in_progress",
versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" },
started_at: "2026-10-08T10:00:00Z",
expires_at: "2026-10-08T11:00:00Z",
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
finished_at: null,
progress: { answered_items: 1, max_items: 2 },
current_item: {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
sequence: 2,
prompt: "Сколько?",
content: { format: "number", unit: null },
},
practices: [],
};
function captureError(operation: () => unknown): unknown {
try {
operation();
} catch (error: unknown) {
return error;
}
return undefined;
}
describe("assessment response contract validation", () => {
it("accepts an empty availability and an unsaved questionnaire", () => {
expect(parseAssessmentAvailabilityResponse({ specializations: [] })).toEqual({
specializations: [],
});
expect(
parseCandidateQuestionnaireResponse({
version: 0,
specializations: [],
work_context: null,
updated_at: null,
}),
).toEqual({
version: 0,
specializations: [],
work_context: null,
updated_at: null,
});
});
it.each([
["availability", parseAssessmentAvailabilityResponse],
["questionnaire", parseCandidateQuestionnaireResponse],
] as const)("rejects an invalid %s response", (_name, parse) => {
const error = captureError(() => parse({}));
expect(error).toBeInstanceOf(ApiRequestError);
expect(error).toMatchObject({ status: 200, code: invalidResponseCode });
});
it("accepts a complete attempt payload", () => {
expect(parseAssessmentAttemptResponse(validAttempt)).toEqual(validAttempt);
});
it.each([{}, { id: validAttempt.id, version: validAttempt.version }])(
"rejects an incomplete successful attempt payload",
(value) => {
const error = captureError(() => parseAssessmentAttemptResponse(value, 201));
expect(error).toBeInstanceOf(ApiRequestError);
expect(error).toMatchObject({ status: 201, code: invalidResponseCode });
},
);
it("rejects an incomplete successful result payload", () => {
expect(() => parseAssessmentResultResponse({})).toThrowError(
expect.objectContaining({ status: 200, code: invalidResponseCode }),
);
});
});
@@ -0,0 +1,49 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import {
AssessmentAttempt as assessmentAttemptSchema,
AssessmentAvailability as assessmentAvailabilitySchema,
AssessmentResult as assessmentResultSchema,
CandidateQuestionnaire as candidateQuestionnaireSchema,
type AssessmentAttempt,
type AssessmentAvailability,
type AssessmentResult,
type CandidateQuestionnaire,
} from "../../../shared/api/schemas";
function invalidAssessmentResponse(status: number): ApiRequestError {
return new ApiRequestError({
status,
code: invalidResponseCode,
title: "The response does not match the API contract.",
});
}
export function parseAssessmentAttemptResponse(value: unknown, status = 200): AssessmentAttempt {
const parsed = assessmentAttemptSchema.safeParse(value);
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
export function parseAssessmentAvailabilityResponse(
value: unknown,
status = 200,
): AssessmentAvailability {
const parsed = assessmentAvailabilitySchema.safeParse(value);
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
export function parseCandidateQuestionnaireResponse(
value: unknown,
status = 200,
): CandidateQuestionnaire {
const parsed = candidateQuestionnaireSchema.safeParse(value);
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
export function parseAssessmentResultResponse(value: unknown, status = 200): AssessmentResult {
const parsed = assessmentResultSchema.safeParse(value);
if (!parsed.success) throw invalidAssessmentResponse(status);
return parsed.data;
}
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import {
ApiRequestError,
invalidResponseCode,
networkErrorCode,
type ApiErrorCode,
} from "../../../shared/api";
import { isOutcomeAmbiguous } from "./idempotency";
const ambiguousOutcomes: ReadonlyArray<readonly [number, ApiErrorCode]> = [
[0, networkErrorCode],
[200, invalidResponseCode],
[429, "rate_limited"],
[500, "internal"],
];
describe("assessment command retry safety", () => {
it.each(ambiguousOutcomes)(
"keeps the idempotency key when outcome status is %s",
(status, code) => {
expect(
isOutcomeAmbiguous(new ApiRequestError({ status, code, title: "Request failed." })),
).toBe(true);
},
);
it.each([400, 401, 403, 404, 409, 412, 422])(
"does not classify deterministic HTTP %s as an ambiguous outcome",
(status) => {
expect(
isOutcomeAmbiguous(
new ApiRequestError({ status, code: "validation_failed", title: "Rejected." }),
),
).toBe(false);
},
);
it("does not treat local validation errors as a request outcome", () => {
expect(isOutcomeAmbiguous(new Error("Invalid form state."))).toBe(false);
});
});
@@ -0,0 +1,11 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
export function isOutcomeAmbiguous(error: unknown): boolean {
return (
error instanceof ApiRequestError &&
(error.status === 0 ||
error.status >= 500 ||
error.status === 429 ||
error.code === invalidResponseCode)
);
}
@@ -0,0 +1,59 @@
import type {
AssessmentAvailability,
AssessmentGradeAvailabilityStatus,
AssessmentMode,
AssessmentOutcome,
AssessmentSpecializationAvailability,
GradeCode,
SpecializationCode,
} from "../../../shared/api/schemas";
export const specializationLabels: Readonly<Record<SpecializationCode, string>> = {
backend: "Backend",
frontend: "Frontend",
mobile: "Мобильная разработка",
network_engineer: "Сетевые технологии",
devops_sre: "DevOps и SRE",
data_analyst: "Аналитика данных",
ds_ml: "Data Science и ML",
information_security: "Информационная безопасность",
qa: "Тестирование",
};
export const gradeLabels: Readonly<Record<GradeCode, string>> = {
intern: "Стажер",
junior: "Junior",
middle: "Middle",
senior: "Senior",
};
export const availabilityLabels: Readonly<Record<AssessmentGradeAvailabilityStatus, string>> = {
available: "Можно начать",
active_attempt: "Есть незавершенная попытка",
cooldown: "Пока недоступно",
insufficient_bank: "Проверка еще не подготовлена",
};
export const outcomeLabels: Readonly<Record<AssessmentOutcome, string>> = {
confirmed: "Уровень подтвержден",
not_confirmed: "Уровень пока не подтвержден",
not_determined: "Результат не определен",
};
export function methodLabel(mode: AssessmentMode): string {
switch (mode) {
case "adaptive":
return "Адаптивная проверка";
case "demo_basic":
return "Базовая проверка по фиксированному набору заданий";
case "demo_express":
return "Демонстрационный экспресс-запуск";
}
}
export function selectedSpecialization(
availability: AssessmentAvailability,
code: SpecializationCode | undefined,
): AssessmentSpecializationAvailability | undefined {
return availability.specializations.find((item) => item.specialization === code);
}
@@ -0,0 +1,65 @@
import type { QueryClient, QueryKey, QueryState } from "@tanstack/react-query";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
type SessionSnapshot = Pick<QueryState<Session, Error>, "data" | "status">;
export function assessmentSessionMatches(
snapshot: SessionSnapshot | undefined,
actor: Session | undefined,
): boolean {
return Boolean(
snapshot?.status === "success" &&
actor &&
snapshot.data?.account.id === actor.account.id &&
snapshot.data.csrf_token === actor.csrf_token &&
actor.account.scenario === "candidate",
);
}
export function isCurrentAssessmentSession(
queryClient: QueryClient,
actor: Session | undefined,
): boolean {
return assessmentSessionMatches(
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
actor,
);
}
export function assertCurrentAssessmentSession(
queryClient: QueryClient,
actor: Session | undefined,
): asserts actor is Session {
if (!isCurrentAssessmentSession(queryClient, actor)) {
throw new Error("The candidate session changed during the assessment request.");
}
}
export const assessmentQueryPrefix = ["candidate-assessment"] as const;
export const assessmentQueryKeys = {
availability: (actor: Session) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "availability"] as const,
questionnaire: (actor: Session) =>
[...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "questionnaire"] as const,
attempt: (actor: Session, attemptId: string) =>
[...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,
};
export function removeAssessmentQueries(queryClient: QueryClient): void {
queryClient.removeQueries({ queryKey: assessmentQueryPrefix });
}
export function removeAssessmentQueriesForSessionChange(
queryClient: QueryClient,
previousKey?: QueryKey,
): void {
if (previousKey) {
queryClient.removeQueries({ queryKey: previousKey });
return;
}
removeAssessmentQueries(queryClient);
}
@@ -0,0 +1,64 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { getListMyOrganizationsQueryKey } from "../../../shared/api/endpoints/organization/organization";
import { needQueryKeys } from "../model/query-keys";
import {
removeAllNeedQueries,
removeNeedQueriesForOrganization,
removeNeedQueriesForSessionChange,
} from "./cache";
const accountId = "22b209a8-8715-4ad5-a9b0-d93a18fc70a4";
const organizationId = "f4866808-70dc-4cbe-b98e-05009c8171d4";
const otherOrganizationId = "e0102126-0c16-49f8-8e81-a82949710454";
const needId = "2ec5ba38-46f8-4e03-b5a5-8f10e0fbad91";
describe("need query cache cleanup", () => {
it("removes every list and detail for a denied organization only", () => {
const client = new QueryClient();
const deniedListKey = needQueryKeys.list(accountId, organizationId);
const deniedDetailKey = needQueryKeys.detail(accountId, organizationId, needId);
const otherListKey = needQueryKeys.list(accountId, otherOrganizationId);
client.setQueryData(deniedListKey, { items: [] });
client.setQueryData(deniedDetailKey, { id: needId });
client.setQueryData(otherListKey, { items: [] });
removeNeedQueriesForOrganization(client, organizationId);
expect(client.getQueryData(deniedListKey)).toBeUndefined();
expect(client.getQueryData(deniedDetailKey)).toBeUndefined();
expect(client.getQueryData(otherListKey)).toEqual({ items: [] });
});
it("clears need and owner-directory caches when the session changes", () => {
const client = new QueryClient();
const directoryKey = getListMyOrganizationsQueryKey({ limit: 100 });
const listKey = needQueryKeys.list(accountId, organizationId);
const detailKey = needQueryKeys.detail(accountId, organizationId, needId);
client.setQueryData(directoryKey, { items: [] });
client.setQueryData(listKey, { items: [] });
client.setQueryData(detailKey, { id: needId });
removeNeedQueriesForSessionChange(client);
expect(client.getQueryData(directoryKey)).toBeUndefined();
expect(client.getQueryData(listKey)).toBeUndefined();
expect(client.getQueryData(detailKey)).toBeUndefined();
});
it("clears private need data if the owner directory loses authorization", () => {
const client = new QueryClient();
const firstNeedKey = needQueryKeys.list(accountId, organizationId);
const secondNeedKey = needQueryKeys.detail(accountId, otherOrganizationId, needId);
client.setQueryData(firstNeedKey, { items: [] });
client.setQueryData(secondNeedKey, { id: needId });
removeAllNeedQueries(client);
expect(client.getQueryData(firstNeedKey)).toBeUndefined();
expect(client.getQueryData(secondNeedKey)).toBeUndefined();
});
});
+40
View File
@@ -0,0 +1,40 @@
import type { QueryClient } from "@tanstack/react-query";
/** Removes every private need list/detail cache for one organization. */
export function removeNeedQueriesForOrganization(
queryClient: QueryClient,
organizationId: string,
): void {
const prefix = `/api/v1/organizations/${organizationId}/needs`;
void queryClient.removeQueries({
predicate: (query) => {
const key = query.queryKey[0];
return typeof key === "string" && (key === prefix || key.startsWith(`${prefix}/`));
},
});
}
/** Removes every private need query when the owner directory cannot be trusted. */
export function removeAllNeedQueries(queryClient: QueryClient): void {
void queryClient.removeQueries({
predicate: (query) => {
const key = query.queryKey[0];
return (
typeof key === "string" &&
key.startsWith("/api/v1/organizations/") &&
key.includes("/needs")
);
},
});
}
/** Clears need and owner-directory caches when a session identity changes. */
export function removeNeedQueriesForSessionChange(queryClient: QueryClient): void {
void queryClient.removeQueries({
predicate: (query) => {
const key = query.queryKey[0];
return typeof key === "string" && key === "/api/v1/me/organizations";
},
});
removeAllNeedQueries(queryClient);
}
@@ -0,0 +1,37 @@
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { listMyOrganizations } from "../../../shared/api/endpoints/organization/organization";
import type { Session } from "../../../shared/api/schemas";
import { needDirectoryPageSize, needQueryKeys } from "../model/query-keys";
import { isNeedSessionCurrent } from "./session";
/** Reads the signed-in account's organization directory for need context checks. */
export function useNeedOrganizationDirectory(session: Session | undefined, enabled: boolean) {
const queryClient = useQueryClient();
const accountId = session?.account.id;
const scopedAccountId = accountId ?? "no-session";
const csrfToken = session?.csrf_token;
return useInfiniteQuery({
queryKey: needQueryKeys.directory(scopedAccountId),
initialPageParam: undefined as string | undefined,
queryFn: async ({ pageParam, signal }) => {
if (!isNeedSessionCurrent(queryClient, session))
throw new Error("The session changed before the directory request.");
const result = await listMyOrganizations(
{ limit: needDirectoryPageSize, ...(pageParam ? { cursor: pageParam } : {}) },
{ signal },
);
if (!isNeedSessionCurrent(queryClient, session))
throw new Error("The session changed during the directory request.");
return result;
},
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
enabled: enabled && accountId !== undefined && csrfToken !== undefined,
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
retry: false,
});
}
@@ -0,0 +1,34 @@
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 { isNeedSessionCurrent } from "./session";
const session: Session = {
account: {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
email: "owner@example.test",
email_verified: true,
scenario: "employer",
onboarding_step: "completed",
created_at: "2026-10-06T09:00:00Z",
},
csrf_token: "abcdefghijklmnopqrstuvwxyz123456",
};
describe("isNeedSessionCurrent", () => {
it("matches both the account and current CSRF token", () => {
const client = new QueryClient();
client.setQueryData(getGetCurrentSessionQueryKey(), session);
expect(isNeedSessionCurrent(client, session)).toBe(true);
expect(isNeedSessionCurrent(client, { ...session, csrf_token: "another-token" })).toBe(false);
expect(
isNeedSessionCurrent(client, {
...session,
account: { ...session.account, id: "36acbba3-d786-4c3a-95b2-4c374ab3206e" },
}),
).toBe(false);
expect(isNeedSessionCurrent(client, undefined)).toBe(false);
});
});
+17
View File
@@ -0,0 +1,17 @@
import type { QueryClient } from "@tanstack/react-query";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
/** Checks that a response still belongs to the active account and CSRF session. */
export function isNeedSessionCurrent(
queryClient: QueryClient,
session: Session | undefined,
): boolean {
if (!session?.csrf_token) return false;
const state = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
return Boolean(
state?.status === "success" &&
state.data?.account.id === session.account.id &&
state.data.csrf_token === session.csrf_token,
);
}
+10
View File
@@ -5,6 +5,13 @@
// toUpdateBody with the generated mutations. After a successful update the
// returned Need is the new baseline of the draft.
export { useNeedOrganizationDirectory } from "./api/organization-directory";
export {
removeAllNeedQueries,
removeNeedQueriesForOrganization,
removeNeedQueriesForSessionChange,
} from "./api/cache";
export { isNeedSessionCurrent } from "./api/session";
export {
addSkill,
addTask,
@@ -23,6 +30,9 @@ export {
setFieldValue,
} from "./model/edit";
export { fromTransport, NeedTransportError } from "./model/from-transport";
export { rebaseNeedDraft } from "./model/rebase";
export { activeNeedOrganizations, type NeedOrganization } from "./model/owner-organizations";
export { needDirectoryPageSize, needListPageSize, needQueryKeys } from "./model/query-keys";
export {
changedNeedFields,
isNeedFormDirty,
@@ -29,6 +29,7 @@ import {
setFieldValue,
} from "./edit";
import { fromTransport, NeedTransportError } from "./from-transport";
import { rebaseNeedDraft } from "./rebase";
import {
changedNeedFields,
isNeedFormDirty,
@@ -410,6 +411,45 @@ describe("toUpdateBody", () => {
});
});
describe("rebaseNeedDraft", () => {
it("keeps local edits and adopts untouched fields from the latest version", () => {
const baseline = fromTransport(extractedNeed);
let draft = setFieldValue(baseline, "grade", "middle");
draft = removeSkill(draft, "requiredSkills", skillIndex(draft, "requiredSkills", "PostgreSQL"));
const latest = Need.parse({
...extractedNeed,
version: 2,
title: "Backend for the payments team, updated",
requirements: {
...extractedNeed.requirements,
domain: {
status: "confirmed",
value: "payments",
source: {
origin: "manual",
quote: null,
extracted_in_version: null,
extraction_version: null,
},
},
},
});
const rebased = rebaseNeedDraft(extractedNeed, draft, latest);
const body = toUpdateBody(latest, rebased);
expect(rebased.title).toBe(latest.title);
expect(rebased.domain).toMatchObject({ status: "confirmed", value: "payments" });
expect(rebased.grade).toEqual({ status: "confirmed", value: "middle", source: null });
expect(rebased.requiredSkills.map((skill) => skill.name)).not.toContain("PostgreSQL");
expect(body.expected_version).toBe(2);
expect(body.title).toBeUndefined();
expect(body.domain).toBeUndefined();
expect(body.grade).toEqual({ value: "middle", status: "confirmed" });
expect(body.required_skills?.map((skill) => skill.name)).not.toContain("PostgreSQL");
});
});
describe("toCreateBody", () => {
function manualDraft(): NeedFormValues {
let form: NeedFormValues = { ...emptyNeedForm(), title: createManual.title };
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import type { MyOrganizationList } from "../../../shared/api/schemas";
import { activeNeedOrganizations } from "./owner-organizations";
function organization(role: "owner" | "recruiter", state: "active" | "removed", id: string) {
return {
organization: { id, name: `Company ${id}`, verification_level: "e0" },
membership: {
organization_id: id,
role,
state,
joined_at: "2026-09-01T00:00:00Z",
},
} satisfies MyOrganizationList["items"][number];
}
describe("activeNeedOrganizations", () => {
it("keeps only active owner memberships across loaded pages", () => {
const pages: MyOrganizationList[] = [
{
items: [
organization("owner", "active", "00000000-0000-4000-8000-000000000001"),
organization("recruiter", "active", "00000000-0000-4000-8000-000000000002"),
],
page: { has_more: true, next_cursor: "next" },
},
{
items: [organization("owner", "removed", "00000000-0000-4000-8000-000000000003")],
page: { has_more: false, next_cursor: null },
},
];
expect(activeNeedOrganizations(pages).map((item) => item.organization.id)).toEqual([
"00000000-0000-4000-8000-000000000001",
]);
});
});
@@ -0,0 +1,12 @@
import type { MyOrganizationList } from "../../../shared/api/schemas";
export type NeedOrganization = MyOrganizationList["items"][number];
/** Returns only active owner contexts; other active roles grant no need access. */
export function activeNeedOrganizations(pages: readonly MyOrganizationList[]): NeedOrganization[] {
return pages.flatMap((page) =>
page.items.filter(
(item) => item.membership.role === "owner" && item.membership.state === "active",
),
);
}
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { needQueryKeys } from "./query-keys";
const firstAccount = "22b209a8-8715-4ad5-a9b0-d93a18fc70a4";
const secondAccount = "36acbba3-d786-4c3a-95b2-4c374ab3206e";
const firstOrganization = "f4866808-70dc-4cbe-b98e-05009c8171d4";
const secondOrganization = "e0102126-0c16-49f8-8e81-a82949710454";
const firstNeed = "2ec5ba38-46f8-4e03-b5a5-8f10e0fbad91";
const secondNeed = "ae85244a-a0c9-432d-a863-c99f63bb2677";
describe("need query keys", () => {
it("separates directory and need data by the active account", () => {
expect(needQueryKeys.directory(firstAccount)).not.toEqual(
needQueryKeys.directory(secondAccount),
);
expect(needQueryKeys.list(firstAccount, firstOrganization)).not.toEqual(
needQueryKeys.list(secondAccount, firstOrganization),
);
});
it("separates organization list and need detail contexts", () => {
expect(needQueryKeys.list(firstAccount, firstOrganization)).not.toEqual(
needQueryKeys.list(firstAccount, secondOrganization),
);
expect(needQueryKeys.detail(firstAccount, firstOrganization, firstNeed)).not.toEqual(
needQueryKeys.detail(firstAccount, firstOrganization, secondNeed),
);
expect(needQueryKeys.detail(firstAccount, firstOrganization, firstNeed)).not.toEqual(
needQueryKeys.detail(firstAccount, secondOrganization, firstNeed),
);
});
});
@@ -0,0 +1,22 @@
import {
getGetOrganizationNeedQueryKey,
getListOrganizationNeedsQueryKey,
} from "../../../shared/api/endpoints/need/need";
import { getListMyOrganizationsQueryKey } from "../../../shared/api/endpoints/organization/organization";
export const needDirectoryPageSize = 100;
export const needListPageSize = 20;
/** Need data stays separate for each signed-in account and organization. */
export const needQueryKeys = {
directory: (accountId: string) =>
[...getListMyOrganizationsQueryKey({ limit: needDirectoryPageSize }), accountId] as const,
list: (accountId: string, organizationId: string) =>
[
...getListOrganizationNeedsQueryKey(organizationId, { limit: needListPageSize }),
accountId,
organizationId,
] as const,
detail: (accountId: string, organizationId: string, needId: string) =>
[...getGetOrganizationNeedQueryKey(organizationId, needId), accountId, organizationId] as const,
};
@@ -0,0 +1,25 @@
import type { Need } from "../../../shared/api/schemas";
import { changedNeedFields } from "./to-transport";
import { fromTransport } from "./from-transport";
import type { NeedFormField, NeedFormValues } from "./types";
function carryDraftField<K extends NeedFormField>(
target: NeedFormValues,
source: NeedFormValues,
field: K,
): NeedFormValues {
return { ...target, [field]: source[field] };
}
/** Reapplies only locally changed fields over a newly loaded server version. */
export function rebaseNeedDraft(
original: Need,
draft: NeedFormValues,
latest: Need,
): NeedFormValues {
const changedFields = new Set(changedNeedFields(original, draft));
return (Object.keys(draft) as NeedFormField[]).reduce((rebased, field) => {
if (!changedFields.has(field)) return rebased;
return carryDraftField(rebased, draft, field);
}, fromTransport(latest));
}
@@ -0,0 +1,18 @@
export { createSupportCaseIdempotencyKey, getSupportCaseIdempotencyKey } from "./model/idempotency";
export type { SupportCaseKeyBinding } from "./model/idempotency";
export { parseSupportCaseContext, supportCaseContextLabel } from "./model/context";
export { supportCaseDetailQueryKey, supportCaseListQueryKey } from "./model/query-keys";
export { queryClientHasSupportActor, supportSessionMatches } from "./model/session-guard";
export {
isSupportSessionAccessError,
supportCaseCreateFailureMessage,
supportCasePathFor,
} from "./model/submission";
export {
formatSupportDate,
supportCaseActorLabels,
supportCaseEventKindLabels,
supportCaseStatusLabels,
supportCaseTypeLabels,
supportTargetDescription,
} from "./model/presentation";
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { parseSupportCaseContext, supportCaseContextLabel } from "./context";
const attempt = { type: "assessment_attempt", id: "4c0ce905-a668-4f5d-961b-dc90fc4b684d" };
describe("support case context", () => {
it("accepts only the allowlisted object kind and UUID from router state", () => {
expect(parseSupportCaseContext(attempt)).toEqual(attempt);
expect(parseSupportCaseContext({ ...attempt, extra: "ignored" })).toEqual(attempt);
expect(parseSupportCaseContext({ type: "profile", id: attempt.id })).toBeNull();
expect(parseSupportCaseContext({ ...attempt, id: "not-a-uuid" })).toBeNull();
expect(parseSupportCaseContext(null)).toBeNull();
});
it("uses a descriptive label without showing the reference identifier", () => {
const context = parseSupportCaseContext(attempt);
if (!context) throw new Error("Expected a valid context");
expect(supportCaseContextLabel(context)).toBe("попыткой оценки");
});
});
@@ -0,0 +1,37 @@
import type { SupportCaseObjectReference } from "../../../shared/api/schemas";
const allowedObjectTypes = new Set<SupportCaseObjectReference["type"]>([
"assessment_attempt",
"organization",
"invitation",
"support_case",
]);
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function parseSupportCaseContext(value: unknown): SupportCaseObjectReference | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
if (
typeof record.type !== "string" ||
!allowedObjectTypes.has(record.type as SupportCaseObjectReference["type"]) ||
typeof record.id !== "string" ||
!uuidPattern.test(record.id)
) {
return null;
}
return { type: record.type as SupportCaseObjectReference["type"], id: record.id };
}
export function supportCaseContextLabel(context: SupportCaseObjectReference): string {
switch (context.type) {
case "assessment_attempt":
return "попыткой оценки";
case "organization":
return "компанией";
case "invitation":
return "приглашением";
case "support_case":
return "другим обращением";
}
}
@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from "vitest";
import type { SupportCaseCreate } from "../../../shared/api/schemas";
import { getSupportCaseIdempotencyKey } from "./idempotency";
const body: SupportCaseCreate = { type: "support", description: "Нужна помощь" };
describe("support case idempotency key", () => {
it("keeps a key for an identical retry", () => {
const createKey = vi.fn(() => "case-key-1");
const first = getSupportCaseIdempotencyKey(body, null, createKey);
const retry = getSupportCaseIdempotencyKey({ ...body }, first, createKey);
expect(retry).toBe(first);
expect(retry.key).toBe("case-key-1");
expect(createKey).toHaveBeenCalledOnce();
});
it("rotates the key when the request body changes", () => {
const createKey = vi.fn().mockReturnValueOnce("case-key-1").mockReturnValueOnce("case-key-2");
const first = getSupportCaseIdempotencyKey(body, null, createKey);
const changed = getSupportCaseIdempotencyKey(
{ ...body, description: "Нужна другая помощь" },
first,
createKey,
);
expect(changed.key).toBe("case-key-2");
});
});
@@ -0,0 +1,20 @@
import type { SupportCaseCreate } from "../../../shared/api/schemas";
export type SupportCaseKeyBinding = { body: string; key: string };
export function getSupportCaseIdempotencyKey(
body: SupportCaseCreate,
previous: SupportCaseKeyBinding | null,
createKey: () => string,
): SupportCaseKeyBinding {
const serialized = JSON.stringify(body);
if (previous?.body === serialized) return previous;
return { body: serialized, key: createKey() };
}
export function createSupportCaseIdempotencyKey(): string {
if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") {
throw new Error("Secure random key generation is unavailable.");
}
return crypto.randomUUID();
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { supportCaseStatusLabels, supportTargetDescription } from "./presentation";
describe("support case presentation", () => {
it("describes operational goals without presenting them as legal deadlines", () => {
expect(
supportTargetDescription({
kind: "operational_goal",
business_days: 5,
due_at: "2026-10-13T09:00:00Z",
answered_at: null,
late: false,
policy_version: 2,
}),
).toMatch(/операционная цель, не юридический срок/);
});
it("labels manual assessment as waiting for an expert", () => {
expect(supportCaseStatusLabels.waiting_expert).toBe("Ожидает эксперта");
});
});
@@ -0,0 +1,68 @@
import type {
SupportCaseActorKind,
SupportCaseEventKind,
SupportCaseStatus,
SupportCaseType,
SupportResponseTarget,
} from "../../../shared/api/schemas";
export const supportCaseTypeLabels: Readonly<Record<SupportCaseType, string>> = {
support: "Вопрос в поддержку",
complaint: "Жалоба",
grade_appeal: "Апелляция по оценке",
anticheat_appeal: "Апелляция по проверке безопасности",
manual_assessment: "Ручная оценка",
};
export const supportCaseStatusLabels: Readonly<Record<SupportCaseStatus, string>> = {
submitted: "Принято",
in_review: "Рассматривается",
waiting_for_user: "Нужен ваш ответ",
waiting_expert: "Ожидает эксперта",
resolved: "Решено",
closed: "Закрыто",
};
export const supportCaseEventKindLabels: Readonly<Record<SupportCaseEventKind, string>> = {
created: "Обращение создано",
status_changed: "Статус изменен",
reply: "Ответ поддержки",
decision: "Решение",
};
export const supportCaseActorLabels: Readonly<Record<SupportCaseActorKind, string>> = {
user: "Вы",
support: "Поддержка или эксперт",
system: "Система",
};
export function formatSupportDate(value: string): string {
const date = new Date(value);
if (Number.isNaN(date.valueOf())) return value;
return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
}).format(date);
}
export function supportTargetDescription(target: SupportResponseTarget): string {
const targetDate = formatSupportDate(target.due_at);
const period = `${target.business_days} ${businessDayLabel(target.business_days)}`;
if (target.answered_at) {
return `Первый ответ получен ${formatSupportDate(target.answered_at)}. Целевой период был ${period}.`;
}
if (target.late) {
return `Ориентир команды - до ${targetDate}; целевой период ${period} уже прошел.`;
}
return `Ориентир команды - до ${targetDate}, в течение ${period}. Это операционная цель, не юридический срок.`;
}
function businessDayLabel(value: number): string {
const remainder = value % 10;
const hundredRemainder = value % 100;
if (remainder === 1 && hundredRemainder !== 11) return "рабочий день";
if (remainder >= 2 && remainder <= 4 && (hundredRemainder < 12 || hundredRemainder > 14)) {
return "рабочих дня";
}
return "рабочих дней";
}
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { supportCaseDetailQueryKey, supportCaseListQueryKey } from "./query-keys";
describe("support case query keys", () => {
it("separates private lists and details by account", () => {
expect(supportCaseListQueryKey("account-a")).not.toEqual(supportCaseListQueryKey("account-b"));
expect(supportCaseDetailQueryKey("account-a", "case-1")).not.toEqual(
supportCaseDetailQueryKey("account-b", "case-1"),
);
});
it("separates case details within the same account", () => {
expect(supportCaseDetailQueryKey("account-a", "case-1")).not.toEqual(
supportCaseDetailQueryKey("account-a", "case-2"),
);
});
});
@@ -0,0 +1,7 @@
export function supportCaseListQueryKey(accountId: string) {
return ["account", accountId, "support-cases", "list"] as const;
}
export function supportCaseDetailQueryKey(accountId: string, caseId: string) {
return ["account", accountId, "support-cases", "detail", caseId] as const;
}
@@ -0,0 +1,63 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import type { Session } from "../../../shared/api/schemas";
import { queryClientHasSupportActor, supportSessionMatches } from "./session-guard";
const session: Session = {
account: {
id: "22b209a8-8715-4ad5-a9b0-d93a18fc70a4",
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "a".repeat(32),
};
const otherSession: Session = {
...session,
account: {
...session.account,
id: "36acbba3-d786-4c3a-95b2-4c374ab3206e",
},
csrf_token: "b".repeat(32),
};
describe("support session guard", () => {
it("accepts the same account during a background refresh", () => {
const state = {
data: session,
status: "success",
fetchStatus: "fetching",
isInvalidated: true,
} as const;
expect(supportSessionMatches(state, session)).toBe(true);
});
it("rejects cached session data once the session query errors", () => {
expect(supportSessionMatches({ data: session, status: "error" }, session)).toBe(false);
});
it("rejects another account and a rotated CSRF token", () => {
expect(supportSessionMatches({ data: otherSession, status: "success" }, session)).toBe(false);
expect(
supportSessionMatches(
{ data: { ...session, csrf_token: "c".repeat(32) }, status: "success" },
session,
),
).toBe(false);
});
it("reads the live session query state before allowing a callback to write", () => {
const queryClient = new QueryClient();
const sessionKey = ["/api/v1/identity/sessions/current"];
queryClient.setQueryData(sessionKey, session);
expect(queryClientHasSupportActor(queryClient, sessionKey, session)).toBe(true);
queryClient.setQueryData(sessionKey, otherSession);
expect(queryClientHasSupportActor(queryClient, sessionKey, session)).toBe(false);
});
});
@@ -0,0 +1,25 @@
import type { QueryClient, QueryState } from "@tanstack/react-query";
import type { Session } from "../../../shared/api/schemas";
type SessionSnapshot = Pick<QueryState<Session, Error>, "data" | "status">;
export function supportSessionMatches(
snapshot: SessionSnapshot | undefined,
actor: Session,
): boolean {
return Boolean(
snapshot &&
snapshot.status === "success" &&
snapshot.data &&
snapshot.data.account.id === actor.account.id &&
snapshot.data.csrf_token === actor.csrf_token,
);
}
export function queryClientHasSupportActor(
queryClient: QueryClient,
sessionQueryKey: readonly unknown[],
actor: Session,
): boolean {
return supportSessionMatches(queryClient.getQueryState<Session>(sessionQueryKey), actor);
}
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import { supportCaseCreateFailureMessage } from "./submission";
describe("support case submission feedback", () => {
it("shows the server retry interval without retrying automatically", () => {
const message = supportCaseCreateFailureMessage(
new ApiRequestError({
status: 429,
code: "rate_limited",
title: "Rate limited",
retryAfterSeconds: 15,
}),
);
expect(message).toContain("Повторите вручную через 15 сек.");
});
it("handles missing retry intervals and idempotency conflicts", () => {
expect(
supportCaseCreateFailureMessage(
new ApiRequestError({ status: 429, code: "rate_limited", title: "Rate limited" }),
),
).toContain("Попробуйте отправить обращение позже.");
expect(
supportCaseCreateFailureMessage(
new ApiRequestError({
status: 422,
code: "idempotency_key_reused",
title: "Key reused",
}),
),
).toContain("Отправьте форму еще раз.");
});
});
@@ -0,0 +1,41 @@
import { ApiRequestError } from "../../../shared/api";
import type { Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
export function isSupportSessionAccessError(error: unknown): boolean {
return error instanceof ApiRequestError && (error.status === 401 || error.status === 403);
}
export function supportCasePathFor(session: Session, caseId: string): string {
return session.account.scenario === "candidate"
? paths.candidate.supportCase(caseId)
: paths.employer.supportCase(caseId);
}
export function supportCaseCreateFailureMessage(error: unknown): string {
if (!(error instanceof ApiRequestError)) {
return "Не удалось отправить обращение. Проверьте соединение и повторите попытку.";
}
if (error.status === 429) {
const delay = error.retryAfterSeconds;
return delay === undefined
? "Слишком много запросов. Попробуйте отправить обращение позже."
: `Слишком много запросов. Повторите вручную через ${delay} сек.`;
}
if (error.code === "idempotency_key_reused") {
return "Запрос уже связан с другой отправкой. Отправьте форму еще раз.";
}
if (error.code === "not_found") {
return "Не удалось подтвердить связанный объект. Проверьте его доступность и повторите отправку.";
}
if (error.code === "state_conflict") {
return "Действие конфликтует с текущим состоянием объекта. Обновите страницу и проверьте данные.";
}
if (error.code === "validation_failed") {
return "Проверьте текст обращения и выбранный контекст.";
}
if (error.status === 401 || error.status === 403) {
return "Сервер не подтвердил право отправить обращение. Обновите вход и повторите попытку.";
}
return "Не удалось отправить обращение. Попробуйте позже.";
}
@@ -0,0 +1,5 @@
export { AnswerForm } from "./ui/answer-form";
export { buildAnswerSubmission, emptyAnswerDraft, newIdempotencyKey } from "./model/answer-draft";
export { submitPendingAnswerCommand } from "./model/answer-command";
export type { AnswerDraft, AnswerBuildResult } from "./model/answer-draft";
export type { AnswerCommandOutcome, PendingAnswerCommand } from "./model/answer-command";
@@ -0,0 +1,156 @@
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import { AssessmentAttempt } from "../../../shared/api/schemas";
import { submitPendingAnswerCommand, type PendingAnswerCommand } from "./answer-command";
const attemptId = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01";
const server = setupServer();
beforeAll(() => server.listen());
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
const validAttempt: AssessmentAttempt = {
id: attemptId,
version: 2,
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "python",
root_attempt_id: null,
chain_deadline: null,
mode: "demo_basic",
state: "in_progress",
versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" },
started_at: "2026-10-08T10:00:00Z",
expires_at: "2026-10-08T11:00:00Z",
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
finished_at: null,
progress: { answered_items: 1, max_items: 2 },
current_item: {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
sequence: 2,
prompt: "Сколько?",
content: { format: "number", unit: null },
},
practices: [],
};
describe("assessment answer response validation", () => {
it.each([{}, { id: attemptId, version: 2 }])(
"keeps the exact command retryable when a successful response is incomplete",
async (body) => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const requests: Array<{ body: string | null; key: string | null; csrf: string | null }> = [];
server.use(
http.post(
`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`,
async ({ request }) => {
requests.push({
body: await request.text(),
key: request.headers.get("Idempotency-Key"),
csrf: request.headers.get("X-CSRF-Token"),
});
return HttpResponse.json(body, { status: 200 });
},
),
);
const command: PendingAnswerCommand = {
key: "answer-command-key",
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
itemId: "item-1",
};
const outcome = await submitPendingAnswerCommand(command, attemptId, "csrf-token");
expect(outcome.kind).toBe("retry");
if (outcome.kind !== "retry") return;
expect(outcome.command).toBe(command);
expect(outcome.command).toEqual({
key: "answer-command-key",
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
itemId: "item-1",
});
expect(outcome.error).toMatchObject({
status: 200,
code: invalidResponseCode,
} satisfies Partial<ApiRequestError>);
expect(requests).toEqual([
{
body: command.body,
key: command.key,
csrf: "csrf-token",
},
]);
},
);
it("accepts a complete server attempt response", async () => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
server.use(
http.post(`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`, () =>
HttpResponse.json(validAttempt, { status: 200 }),
),
);
const outcome = await submitPendingAnswerCommand(
{
key: "answer-command-key",
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
itemId: "item-1",
},
attemptId,
"csrf-token",
);
expect(outcome).toEqual({ kind: "accepted", attempt: validAttempt });
});
it("replays the original key and body after a malformed success response", async () => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const requests: Array<{ body: string; key: string | null }> = [];
let responseCount = 0;
server.use(
http.post(
`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`,
async ({ request }) => {
requests.push({
body: await request.text(),
key: request.headers.get("Idempotency-Key"),
});
responseCount += 1;
return HttpResponse.json(responseCount === 1 ? {} : validAttempt, { status: 200 });
},
),
);
const original: PendingAnswerCommand = {
key: "same-answer-key",
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
itemId: "item-1",
};
const first = await submitPendingAnswerCommand(original, attemptId, "csrf-token");
expect(first.kind).toBe("retry");
if (first.kind !== "retry") return;
const second = await submitPendingAnswerCommand(first.command, attemptId, "csrf-token");
expect(second).toEqual({ kind: "accepted", attempt: validAttempt });
expect(requests).toEqual([
{ body: original.body, key: original.key },
{ body: original.body, key: original.key },
]);
});
});
@@ -0,0 +1,41 @@
import { apiRequest } from "../../../shared/api";
import { isOutcomeAmbiguous } from "../../../entities/assessment";
import { getSubmitMyAssessmentAnswerUrl } from "../../../shared/api/endpoints/assessment/assessment";
import {
AssessmentAttempt as assessmentAttemptSchema,
type AssessmentAttempt,
} from "../../../shared/api/schemas";
export type PendingAnswerCommand = { key: string; body: string; itemId: string };
export type AnswerCommandOutcome =
| { kind: "accepted"; attempt: AssessmentAttempt }
| { kind: "retry"; command: PendingAnswerCommand; error: unknown }
| { kind: "rejected"; error: unknown };
export async function submitPendingAnswerCommand(
command: PendingAnswerCommand,
attemptId: string,
csrfToken: string,
): Promise<AnswerCommandOutcome> {
try {
const attempt = await apiRequest<AssessmentAttempt>(
getSubmitMyAssessmentAnswerUrl(attemptId),
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": command.key,
"X-CSRF-Token": csrfToken,
},
body: command.body,
},
assessmentAttemptSchema,
);
return { kind: "accepted", attempt };
} catch (error: unknown) {
return isOutcomeAmbiguous(error)
? { kind: "retry", command, error }
: { kind: "rejected", error };
}
}
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import type { AssessmentAttempt, AssessmentItem } from "../../../shared/api/schemas";
import { buildAnswerSubmission, emptyAnswerDraft } from "./answer-draft";
const attempt = {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01",
version: 4,
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
root_attempt_id: null,
chain_deadline: null,
mode: "demo_basic",
state: "in_progress",
versions: { policy_version: 1, bank_version: "bank.1", algorithm_version: "algo.1" },
started_at: "2026-10-07T10:00:00Z",
expires_at: "2026-10-07T11:00:00Z",
sessions: { used: 1, max: 2, idle_timeout_seconds: 1800 },
finished_at: null,
progress: { answered_items: 0, max_items: 10 },
current_item: null,
practices: [],
} satisfies AssessmentAttempt;
const numberItem = {
id: "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02",
sequence: 1,
prompt: "Сколько?",
content: { format: "number", unit: null },
} satisfies AssessmentItem;
describe("assessment answer submission", () => {
it("preserves a decimal JSON token without converting it through JavaScript number", () => {
const token = "254.00000000000000000000000000000000000001";
const result = buildAnswerSubmission(attempt, numberItem, { format: "number", value: token });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.submission).toBeNull();
expect(result.body).toContain(`"number":${token}`);
expect(JSON.parse(result.body)).toMatchObject({
expected_version: attempt.version,
item_id: numberItem.id,
});
});
it.each([" 2", "2,5", "+2", "01", "Infinity", "2 "])(
"rejects a number token that is not valid JSON: %s",
(value) => {
const result = buildAnswerSubmission(attempt, numberItem, { format: "number", value });
expect(result).toMatchObject({ ok: false });
},
);
it("keeps the initial order as a draft and requires a complete permutation", () => {
const item = {
id: numberItem.id,
sequence: 1,
prompt: "Упорядочите",
content: {
format: "order",
elements: [
{ id: "one", text: "Первый" },
{ id: "two", text: "Второй" },
],
},
} satisfies AssessmentItem;
const draft = emptyAnswerDraft(item);
expect(draft).toEqual({ format: "order", elementIds: ["one", "two"] });
expect(buildAnswerSubmission(attempt, item, draft).ok).toBe(true);
expect(
buildAnswerSubmission(attempt, item, { format: "order", elementIds: ["one", "one"] }),
).toMatchObject({ ok: false });
});
});
@@ -0,0 +1,145 @@
import { AssessmentAnswerSubmission } from "../../../shared/api/schemas";
import type {
AssessmentAttempt,
AssessmentItem,
AssessmentAnswerSubmission as AnswerSubmission,
} from "../../../shared/api/schemas";
export type AnswerDraft =
| { format: "choice"; optionIds: string[] }
| { format: "number"; value: string }
| { format: "string"; value: string }
| { format: "order"; elementIds: string[] }
| { format: "find_error"; lineNumbers: number[] }
| { format: "configuration"; value: string }
| { format: "practice"; language: "python" | "go" | null; sourceCode: string };
export type AnswerBuildResult =
{ ok: true; body: string; submission: AnswerSubmission | null } | { ok: false; message: string };
const jsonNumberToken = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
const maxNumberTokenLength = 64;
export function emptyAnswerDraft(item: AssessmentItem): AnswerDraft {
switch (item.content.format) {
case "choice":
return { format: "choice", optionIds: [] };
case "number":
return { format: "number", value: "" };
case "string":
return { format: "string", value: "" };
case "order":
return { format: "order", elementIds: item.content.elements.map(({ id }) => id) };
case "find_error":
return { format: "find_error", lineNumbers: [] };
case "configuration":
return { format: "configuration", value: item.content.initial_config };
case "practice":
return { format: "practice", language: item.content.languages[0] ?? null, sourceCode: "" };
}
}
export function buildAnswerSubmission(
attempt: AssessmentAttempt,
item: AssessmentItem,
draft: AnswerDraft,
): AnswerBuildResult {
if (draft.format !== item.content.format) {
return { ok: false, message: "Формат ответа не совпадает с заданием. Перезагрузите попытку." };
}
if (draft.format === "number" && item.content.format === "number") {
const token = draft.value;
if (token.length === 0) return { ok: false, message: "Введите числовой ответ." };
if (token.length > maxNumberTokenLength || !jsonNumberToken.test(token)) {
return {
ok: false,
message: "Введите число без пробелов и разделителей тысяч. Десятичный разделитель - точка.",
};
}
const body = `{"expected_version":${attempt.version},"item_id":${JSON.stringify(item.id)},"answer":{"format":"number","number":${token}}}`;
return { ok: true, body, submission: null };
}
let answer: AnswerSubmission["answer"] | null = null;
switch (draft.format) {
case "choice":
if (draft.optionIds.length === 0) {
return { ok: false, message: "Выберите ответ." };
}
if (
item.content.format === "choice" &&
!item.content.multiple &&
draft.optionIds.length !== 1
) {
return { ok: false, message: "Выберите один вариант." };
}
answer = { format: "choice", option_ids: [...draft.optionIds] };
break;
case "string":
if (draft.value.length === 0) return { ok: false, message: "Введите ответ." };
if (item.content.format !== "string" || draft.value.length > item.content.max_length) {
return { ok: false, message: "Проверьте длину ответа." };
}
answer = { format: "string", text: draft.value };
break;
case "order":
if (
item.content.format !== "order" ||
draft.elementIds.length !== item.content.elements.length ||
new Set(draft.elementIds).size !== item.content.elements.length ||
item.content.elements.some(({ id }) => !draft.elementIds.includes(id))
) {
return { ok: false, message: "Расположите все элементы в нужном порядке." };
}
answer = { format: "order", element_ids: [...draft.elementIds] };
break;
case "find_error":
if (
item.content.format !== "find_error" ||
draft.lineNumbers.length === 0 ||
draft.lineNumbers.length > item.content.max_selections
) {
return { ok: false, message: "Выберите строки с ошибкой в пределах лимита." };
}
answer = { format: "find_error", line_numbers: [...draft.lineNumbers] };
break;
case "configuration":
if (
item.content.format !== "configuration" ||
draft.value.length === 0 ||
draft.value.length > item.content.max_length
) {
return { ok: false, message: "Введите конфигурацию в пределах указанного лимита." };
}
answer = { format: "configuration", config: draft.value };
break;
case "practice":
if (
item.content.format !== "practice" ||
draft.sourceCode.length === 0 ||
draft.sourceCode.length > item.content.max_source_length ||
(draft.language !== null && !item.content.languages.includes(draft.language))
) {
return { ok: false, message: "Добавьте решение в разрешенном формате." };
}
answer = { format: "practice", language: draft.language, source_code: draft.sourceCode };
break;
}
if (!answer) return { ok: false, message: "Проверьте ответ и повторите отправку." };
const parsed = AssessmentAnswerSubmission.safeParse({
expected_version: attempt.version,
item_id: item.id,
answer,
});
if (!parsed.success) {
return { ok: false, message: "Проверьте ответ и повторите отправку." };
}
return { ok: true, body: JSON.stringify(parsed.data), submission: parsed.data };
}
export function newIdempotencyKey(): string {
return crypto.randomUUID();
}
@@ -0,0 +1,181 @@
.form {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.fields,
.code-lines {
display: grid;
gap: var(--space-3);
min-width: 0;
margin: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.legend,
.code-lines legend {
padding: 0 var(--space-2);
font-weight: var(--font-weight-bold);
}
.options,
.practice {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.option,
.code-line {
display: flex;
align-items: flex-start;
gap: var(--space-3);
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
cursor: pointer;
}
.option input,
.code-line input {
flex: 0 0 auto;
width: 1.2rem;
height: 1.2rem;
margin-block-start: 0.15rem;
accent-color: var(--color-accent);
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
font-weight: var(--font-weight-bold);
}
.field input,
.field select,
.field textarea {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
font-weight: var(--font-weight-regular);
}
.field textarea {
resize: vertical;
font-family: var(--font-mono);
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.field :is(input, select, textarea):focus-visible,
.option input:focus-visible,
.code-line input:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
font-weight: var(--font-weight-regular);
}
.order {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.order-item {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: var(--space-3);
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
}
.order-actions,
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
}
.code-lines {
padding-inline: var(--space-3);
}
.code-line {
align-items: baseline;
font-family: var(--font-mono);
overflow-wrap: anywhere;
}
.line-number {
flex: 0 0 2.5rem;
color: var(--color-text-secondary);
text-align: end;
user-select: none;
}
.code-line code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.examples {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-3);
background: var(--color-canvas);
border-radius: var(--radius-s);
}
.examples h3,
.examples p {
margin: 0;
}
.examples pre {
max-width: 100%;
margin: var(--space-1) 0 var(--space-3);
padding: var(--space-2);
overflow-x: auto;
background: var(--color-surface);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.error {
margin: 0;
color: var(--color-danger);
}
@media (width < 42rem) {
.fields {
padding: var(--space-3);
}
.order-item {
align-items: flex-start;
}
}
@@ -0,0 +1,281 @@
import { useState, type FormEvent } from "react";
import type { AssessmentItem } from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui";
import { emptyAnswerDraft, type AnswerDraft } from "../model/answer-draft";
import styles from "./answer-form.module.css";
type AnswerFormProps = {
item: AssessmentItem;
isSaving: boolean;
retryable: boolean;
errorMessage: string | null;
onSubmit: (draft: AnswerDraft) => void;
onRetry: () => void;
};
export function AnswerForm({
item,
isSaving,
retryable,
errorMessage,
onSubmit,
onRetry,
}: AnswerFormProps) {
const [draft, setDraft] = useState<AnswerDraft>(() => emptyAnswerDraft(item));
const frozen = isSaving || retryable;
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (frozen) return;
onSubmit(draft);
}
return (
<form className={styles.form} onSubmit={submit}>
<fieldset className={styles.fields} disabled={frozen}>
<legend className={styles.legend}>Ваш ответ</legend>
<AnswerFields item={item} draft={draft} setDraft={setDraft} />
</fieldset>
{errorMessage ? (
<p className={styles.error} role="alert">
{errorMessage}
</p>
) : null}
<div className={styles.actions}>
{retryable ? (
<Button isBusy={isSaving} onClick={onRetry}>
Повторить отправку того же ответа
</Button>
) : (
<Button type="submit" isBusy={isSaving}>
{isSaving ? "Сохраняем ответ..." : "Отправить ответ"}
</Button>
)}
</div>
</form>
);
}
type AnswerFieldsProps = {
item: AssessmentItem;
draft: AnswerDraft;
setDraft: (draft: AnswerDraft) => void;
};
function AnswerFields({ item, draft, setDraft }: AnswerFieldsProps) {
const content = item.content;
switch (content.format) {
case "choice": {
const selected = draft.format === "choice" ? draft.optionIds : [];
return (
<div className={styles.options}>
{content.options.map((option) => {
const checked = selected.includes(option.id);
return (
<label className={styles.option} key={option.id}>
<input
type={content.multiple ? "checkbox" : "radio"}
name={`answer-${item.id}`}
value={option.id}
checked={checked}
onChange={() => {
const optionIds = content.multiple
? checked
? selected.filter((id) => id !== option.id)
: [...selected, option.id]
: [option.id];
setDraft({ format: "choice", optionIds });
}}
/>
<span>{option.text}</span>
</label>
);
})}
</div>
);
}
case "number":
return (
<label className={styles.field}>
<span>Числовой ответ{content.unit ? `, ${content.unit}` : ""}</span>
<input
autoComplete="off"
inputMode="decimal"
maxLength={64}
name="number-answer"
type="text"
value={draft.format === "number" ? draft.value : ""}
onChange={(event) => setDraft({ format: "number", value: event.currentTarget.value })}
/>
<span className={styles.hint}>
Десятичный разделитель - точка. Введенное число отправляется без округления.
</span>
</label>
);
case "string":
return (
<label className={styles.field}>
<span>Краткий ответ</span>
<input
autoComplete="off"
maxLength={content.max_length}
name="text-answer"
type="text"
value={draft.format === "string" ? draft.value : ""}
onChange={(event) => setDraft({ format: "string", value: event.currentTarget.value })}
/>
<span className={styles.hint}>Не более {content.max_length} символов.</span>
</label>
);
case "order": {
const ids =
draft.format === "order" ? draft.elementIds : content.elements.map(({ id }) => id);
const options = new Map(content.elements.map((element) => [element.id, element.text]));
function move(index: number, offset: -1 | 1) {
const nextIndex = index + offset;
if (nextIndex < 0 || nextIndex >= ids.length) return;
const next = [...ids];
[next[index], next[nextIndex]] = [next[nextIndex] as string, next[index] as string];
setDraft({ format: "order", elementIds: next });
}
return (
<ol className={styles.order} aria-label="Порядок элементов">
{ids.map((id, index) => (
<li className={styles["order-item"]} key={id}>
<span>{options.get(id)}</span>
<div className={styles["order-actions"]}>
<Button
variant="secondary"
disabled={index === 0}
aria-label={`Переместить ${options.get(id)} выше`}
onClick={() => move(index, -1)}
>
Выше
</Button>
<Button
variant="secondary"
disabled={index === ids.length - 1}
aria-label={`Переместить ${options.get(id)} ниже`}
onClick={() => move(index, 1)}
>
Ниже
</Button>
</div>
</li>
))}
</ol>
);
}
case "find_error": {
const selected = draft.format === "find_error" ? draft.lineNumbers : [];
return (
<fieldset className={styles["code-lines"]}>
<legend>Отметьте строки с ошибкой</legend>
{content.lines.map((line) => (
<label className={styles["code-line"]} key={line.number}>
<input
type="checkbox"
checked={selected.includes(line.number)}
onChange={(event) => {
const lineNumbers = event.currentTarget.checked
? [...selected, line.number]
: selected.filter((number) => number !== line.number);
setDraft({ format: "find_error", lineNumbers });
}}
/>
<span className={styles["line-number"]}>{line.number}</span>
<code>{line.text}</code>
</label>
))}
<p className={styles.hint}>Можно отметить не более {content.max_selections} строк.</p>
</fieldset>
);
}
case "configuration":
return (
<label className={styles.field}>
<span>Конфигурация ({content.syntax})</span>
<textarea
autoComplete="off"
maxLength={content.max_length}
name="configuration-answer"
rows={12}
spellCheck={false}
value={draft.format === "configuration" ? draft.value : content.initial_config}
onChange={(event) =>
setDraft({ format: "configuration", value: event.currentTarget.value })
}
/>
<span className={styles.hint}>Не более {content.max_length} символов.</span>
</label>
);
case "practice":
return (
<div className={styles.practice}>
{content.languages.length > 1 ? (
<label className={styles.field}>
<span>Язык решения</span>
<select
value={draft.format === "practice" ? (draft.language ?? "") : ""}
onChange={(event) =>
setDraft({
format: "practice",
language:
event.currentTarget.value === ""
? null
: (event.currentTarget.value as "go" | "python"),
sourceCode: draft.format === "practice" ? draft.sourceCode : "",
})
}
>
<option value="">Выберите язык</option>
{content.languages.map((language) => (
<option key={language} value={language}>
{language === "go" ? "Go" : "Python"}
</option>
))}
</select>
</label>
) : content.languages[0] ? (
<p className={styles.hint}>
Язык решения: {content.languages[0] === "go" ? "Go" : "Python"}.
</p>
) : null}
{content.public_examples.length > 0 ? (
<div className={styles.examples}>
<h3>Примеры</h3>
{content.public_examples.map((example, index) => (
<div key={`${index}-${example.input}`}>
<p>Входные данные</p>
<pre>{example.input}</pre>
<p>Ожидаемый вывод</p>
<pre>{example.expected_output}</pre>
</div>
))}
</div>
) : null}
<label className={styles.field}>
<span>Код решения</span>
<textarea
autoComplete="off"
maxLength={content.max_source_length}
name="practice-answer"
rows={16}
spellCheck={false}
value={draft.format === "practice" ? draft.sourceCode : ""}
onChange={(event) =>
setDraft({
format: "practice",
language:
draft.format === "practice" ? draft.language : (content.languages[0] ?? null),
sourceCode: event.currentTarget.value,
})
}
/>
<span className={styles.hint}>Не более {content.max_source_length} символов.</span>
</label>
</div>
);
}
}
@@ -0,0 +1 @@
export { CreateSupportCase } from "./ui/create-support-case";
@@ -0,0 +1,117 @@
.root {
display: grid;
gap: 1.5rem;
}
.intro {
max-width: 68ch;
margin: 0 0 1.25rem;
color: var(--color-text-muted);
line-height: 1.65;
}
.form {
display: grid;
gap: 1.25rem;
max-width: 52rem;
}
.context {
min-width: 0;
padding: 1rem;
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.context legend {
padding: 0 0.35rem;
color: var(--color-text-strong);
font-weight: 650;
}
.checkbox {
display: flex;
align-items: flex-start;
gap: 0.7rem;
line-height: 1.5;
}
.checkbox input {
width: 1.1rem;
height: 1.1rem;
margin: 0.15rem 0 0;
flex: 0 0 auto;
}
.field {
display: grid;
gap: 0.45rem;
}
.field label {
color: var(--color-text-strong);
font-weight: 650;
}
.field textarea {
box-sizing: border-box;
width: 100%;
min-width: 0;
max-width: 100%;
min-height: 12rem;
padding: 0.85rem;
resize: vertical;
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
line-height: 1.55;
}
.field textarea:focus-visible,
.checkbox input:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.field textarea[aria-invalid="true"] {
border-color: var(--color-danger);
}
.hint {
margin: 0;
color: var(--color-text-muted);
font-size: 0.92rem;
line-height: 1.5;
}
.error {
padding: 0.85rem 1rem;
border-inline-start: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
}
.error:focus {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 1rem;
}
@media (width <= 40rem) {
.actions > * {
max-width: 100%;
}
.actions button {
width: 100%;
}
}
@@ -0,0 +1,239 @@
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useLocation, useNavigate } from "react-router-dom";
import {
createSupportCaseIdempotencyKey,
getSupportCaseIdempotencyKey,
isSupportSessionAccessError,
parseSupportCaseContext,
queryClientHasSupportActor,
supportCaseCreateFailureMessage,
supportCaseContextLabel,
supportCaseDetailQueryKey,
supportCaseListQueryKey,
supportCasePathFor,
supportSessionMatches,
type SupportCaseKeyBinding,
} from "../../../entities/support-case";
import { ApiRequestError } from "../../../shared/api";
import { createMySupportCase } from "../../../shared/api/endpoints/support/support";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type {
Session,
SupportCase,
SupportCaseCreate,
SupportCaseObjectReference,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Section,
TextLink,
} from "../../../shared/ui";
import styles from "./create-support-case.module.css";
function locationSupportContext(state: unknown): SupportCaseObjectReference | null {
if (typeof state !== "object" || state === null || Array.isArray(state)) return null;
return parseSupportCaseContext((state as Record<string, unknown>).supportContext);
}
export function CreateSupportCase() {
const queryClient = useQueryClient();
const location = useLocation();
const navigate = useNavigate();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.isSuccess ? session.data : null;
const knownActor =
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const formId = useId();
const errorRef = useRef<HTMLDivElement>(null);
const idempotencyBinding = useRef<SupportCaseKeyBinding | null>(null);
const [description, setDescription] = useState("");
const [context] = useState(() => locationSupportContext(location.state));
const [includeContext, setIncludeContext] = useState(Boolean(context));
const [actionError, setActionError] = useState<string | null>(null);
const create = useMutation({
mutationFn: ({ data, key }: { data: SupportCaseCreate; key: string }) => {
const csrfToken = actor?.csrf_token;
if (!actor || !csrfToken || !session.isSuccess) {
throw new Error("An active account session is required.");
}
return createMySupportCase(
data,
{ "Idempotency-Key": key },
{ headers: { "X-CSRF-Token": csrfToken } },
);
},
gcTime: 0,
});
useEffect(() => {
if (actionError) errorRef.current?.focus();
}, [actionError]);
useEffect(() => {
const accountId = actor?.account.id ?? knownActor?.account.id;
if (!accountId || !isSupportSessionAccessError(session.error)) return;
queryClient.removeQueries({
predicate: (query) =>
query.queryKey[0] === "account" &&
query.queryKey[1] === accountId &&
query.queryKey[2] === "support-cases",
});
}, [actor, knownActor, queryClient, session.error]);
if (session.isPending && !session.data) return <LoadingState label="Проверяем вход..." />;
if (session.isError && isSupportSessionAccessError(session.error)) {
return (
<ForbiddenState
error={session.error}
title="Войдите, чтобы отправить обращение"
description="После входа вы вернетесь в раздел поддержки. Чужая история обращений не будет открыта."
action={
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
Войти и продолжить
</ButtonLink>
}
/>
);
}
if (session.isError) {
return (
<ErrorState
error={session.error}
title="Не удалось проверить вход"
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
/>
);
}
if (!actor || (actor.account.scenario !== "candidate" && actor.account.scenario !== "employer")) {
return <ForbiddenState title="Поддержка недоступна" />;
}
const contextLabel = context ? supportCaseContextLabel(context) : null;
const isSubmitting = create.isPending;
const canSubmit = description.trim().length > 0 && !isSubmitting && !session.isError;
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (
!canSubmit ||
!actor ||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
) {
return;
}
setActionError(null);
const data: SupportCaseCreate = {
type: "support",
description,
...(includeContext && context ? { object: context } : {}),
};
const binding = getSupportCaseIdempotencyKey(
data,
idempotencyBinding.current,
createSupportCaseIdempotencyKey,
);
idempotencyBinding.current = binding;
let created: SupportCase;
try {
created = await create.mutateAsync({ data, key: binding.key });
} catch (error: unknown) {
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
if (error instanceof ApiRequestError && error.code === "idempotency_key_reused") {
idempotencyBinding.current = null;
}
setActionError(supportCaseCreateFailureMessage(error));
return;
}
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
queryClient.setQueryData(supportCaseDetailQueryKey(actor.account.id, created.id), created);
void queryClient.invalidateQueries({ queryKey: supportCaseListQueryKey(actor.account.id) });
navigate(supportCasePathFor(actor, created.id), { replace: true });
}
return (
<div className={styles.root}>
<Section title="Новое обращение">
<p className={styles.intro}>
Опишите вопрос своими словами. Не добавляйте пароль или контактные данные других людей.
Обращение сохранится в вашем кабинете, а ответ появится в его истории.
</p>
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
{context && contextLabel ? (
<fieldset className={styles.context} disabled={isSubmitting}>
<legend>Контекст страницы</legend>
<label className={styles.checkbox}>
<input
type="checkbox"
checked={includeContext}
onChange={(event) => setIncludeContext(event.currentTarget.checked)}
aria-describedby={`${formId}-context-hint`}
/>
<span>Связать обращение с {contextLabel}</span>
</label>
<p id={`${formId}-context-hint`} className={styles.hint}>
Передается только вид объекта и его идентификатор. Пароли и параметры адресной
строки не передаются.
</p>
</fieldset>
) : null}
<div className={styles.field}>
<label htmlFor={`${formId}-description`}>Что произошло или какая помощь нужна</label>
<textarea
id={`${formId}-description`}
name="description"
value={description}
onChange={(event) => setDescription(event.currentTarget.value)}
rows={7}
maxLength={4000}
required
disabled={isSubmitting}
aria-invalid={actionError ? true : undefined}
aria-describedby={`${formId}-hint${actionError ? ` ${formId}-error` : ""}`}
/>
<p id={`${formId}-hint`} className={styles.hint}>
До 4000 символов. Текст будет показан как обычный текст.
</p>
</div>
{actionError ? (
<div
className={styles.error}
id={`${formId}-error`}
role="alert"
tabIndex={-1}
ref={errorRef}
>
{actionError}
</div>
) : null}
<div className={styles.actions}>
<Button type="submit" isBusy={isSubmitting} aria-disabled={!canSubmit}>
{isSubmitting ? "Отправляем..." : "Отправить обращение"}
</Button>
<TextLink
to={
actor.account.scenario === "candidate"
? paths.candidate.supportCases
: paths.employer.supportCases
}
>
Мои обращения
</TextLink>
</div>
</form>
</Section>
</div>
);
}
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vitest";
import type { Session } from "../../../shared/api/schemas";
import { isCurrentSessionSnapshot } from "./session-refresh";
const initialSession: Session = {
account: {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
email: "owner@example.test",
email_verified: true,
scenario: "employer",
onboarding_step: "completed",
created_at: "2026-10-06T09:00:00Z",
},
csrf_token: "abcdefghijklmnopqrstuvwxyz123456",
};
describe("isCurrentSessionSnapshot", () => {
it("accepts the same account and CSRF snapshot only while its cache generation is unchanged", () => {
expect(isCurrentSessionSnapshot(initialSession, "success", 100, initialSession, 100)).toBe(
true,
);
expect(isCurrentSessionSnapshot(initialSession, "success", 101, initialSession, 100)).toBe(
false,
);
});
it("rejects a changed account or CSRF token before applying a delayed refresh", () => {
const rotatedToken = { ...initialSession, csrf_token: "zyxwvutsrqponmlkjihgfedcba654321" };
const anotherAccount = {
...initialSession,
account: { ...initialSession.account, id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e02" },
};
expect(isCurrentSessionSnapshot(rotatedToken, "success", 100, initialSession, 100)).toBe(false);
expect(isCurrentSessionSnapshot(anotherAccount, "success", 100, initialSession, 100)).toBe(
false,
);
});
});
@@ -0,0 +1,19 @@
import type { Session } from "../../../shared/api/schemas";
type SessionQueryStatus = "error" | "pending" | "success";
export function isCurrentSessionSnapshot(
current: Session | undefined,
status: SessionQueryStatus | undefined,
dataUpdatedAt: number | undefined,
expected: Session,
expectedDataUpdatedAt: number,
): boolean {
return Boolean(
current &&
status === "success" &&
current.account.id === expected.account.id &&
current.csrf_token === expected.csrf_token &&
dataUpdatedAt === expectedDataUpdatedAt,
);
}
@@ -7,6 +7,7 @@ import {
} from "../../../shared/api/endpoints/organization/organization";
import {
getGetCurrentSessionQueryKey,
getCurrentSession,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
@@ -20,6 +21,7 @@ import {
rebaseCompanyDraft,
type CompanyDraft,
} from "../../../entities/company";
import { isCurrentSessionSnapshot } from "../model/session-refresh";
import styles from "./company-editor.module.css";
type CompanyEditorProps = {
@@ -150,23 +152,64 @@ export function CompanyEditor({ organization, onSaved, onAccessLost }: CompanyEd
);
}
function isSubmittingAccountCurrent(expected: Session): boolean {
const current = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
return current?.account.id === expected.account.id;
}
async function refreshAfterCsrfFailure(expected: Session): Promise<void> {
if (!isSubmittingAccountCurrent(expected)) return;
const sessionQueryKey = getGetCurrentSessionQueryKey();
const initialQueryState = queryClient.getQueryState<Session>(sessionQueryKey);
if (!isSubmittingSessionCurrent(expected) || !initialQueryState) return;
const initialDataUpdatedAt = initialQueryState.dataUpdatedAt;
setActionError(null);
setCsrfRetryMessage("Проверяем текущий вход...");
setStatus("failed");
const refreshed = await session.refetch();
if (refreshed.data?.account.id !== expected.account.id) return;
setCsrfRetryMessage(
refreshed.isError
? "Не удалось проверить вход. Данные формы сохранены; повторите проверку и отправьте их снова."
: "Проверка входа обновлена. Данные формы сохранены, повторите сохранение.",
);
try {
const refreshed = await getCurrentSession();
const currentQueryState = queryClient.getQueryState<Session>(sessionQueryKey);
const current = queryClient.getQueryData<Session>(sessionQueryKey);
if (
!isCurrentSessionSnapshot(
current,
currentQueryState?.status,
currentQueryState?.dataUpdatedAt,
expected,
initialDataUpdatedAt,
)
) {
if (
current?.account.id === expected.account.id &&
currentQueryState?.status === "success" &&
currentQueryState.dataUpdatedAt !== initialDataUpdatedAt
) {
setCsrfRetryMessage("Вход уже обновлен. Данные формы сохранены; повторите сохранение.");
}
return;
}
queryClient.setQueryData(sessionQueryKey, refreshed);
if (refreshed.account.id !== expected.account.id) return;
setCsrfRetryMessage(
"Проверка входа обновлена. Данные формы сохранены, повторите сохранение.",
);
} catch (error: unknown) {
const currentQueryState = queryClient.getQueryState<Session>(sessionQueryKey);
const current = queryClient.getQueryData<Session>(sessionQueryKey);
if (
!isCurrentSessionSnapshot(
current,
currentQueryState?.status,
currentQueryState?.dataUpdatedAt,
expected,
initialDataUpdatedAt,
)
) {
return;
}
if (error instanceof ApiRequestError && (error.status === 401 || error.status === 403)) {
onAccessLost(error);
void queryClient.invalidateQueries({ queryKey: sessionQueryKey });
return;
}
setCsrfRetryMessage(
"Не удалось проверить вход. Данные формы сохранены; повторите проверку и отправьте их снова.",
);
}
}
async function saveCreate(): Promise<void> {
+1
View File
@@ -0,0 +1 @@
export { NeedEditor, type NeedEditorProps } from "./ui/need-editor";
@@ -0,0 +1,202 @@
.form {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.intro,
.hint,
.meta,
.provenance,
.question {
color: var(--color-text-secondary);
}
.hint,
.provenance,
.question,
.field-error,
.action-error,
.meta {
margin: 0;
}
.group,
.salary,
.conflict,
.recommendations,
.list {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.group legend,
.work-formats legend {
padding: 0 var(--space-2);
font-weight: var(--font-weight-bold);
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.field label,
.add-row label,
.skill-label {
font-weight: var(--font-weight-bold);
}
.field input,
.field select,
.field textarea,
.item input,
.add-row input {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.add-row input {
flex: 1 1 14rem;
}
.field textarea {
resize: vertical;
}
.field :is(input, select, textarea):focus-visible,
.item input:focus-visible,
.add-row input:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.field [aria-invalid="true"] {
border-color: var(--color-danger);
}
.provenance {
display: grid;
gap: var(--space-1);
font-size: var(--font-size-s);
}
.provenance p,
.provenance blockquote,
.item blockquote {
margin: 0;
}
.provenance blockquote,
.item blockquote {
padding-inline-start: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-divider);
color: var(--color-text-secondary);
overflow-wrap: anywhere;
}
.question {
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.field-error,
.action-error {
color: var(--color-danger);
}
.work-formats {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
}
.work-formats label {
display: inline-flex;
gap: var(--space-2);
align-items: center;
}
.work-formats .provenance,
.work-formats .question {
flex-basis: 100%;
}
.salary-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: var(--space-3);
}
.actions,
.add-row {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
}
.list ul {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.item {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
}
.badge {
width: fit-content;
padding: var(--space-1) var(--space-2);
border-radius: var(--radius-s);
color: var(--color-text-secondary);
background: var(--color-canvas);
font-size: var(--font-size-s);
}
.conflict {
border-color: var(--color-accent);
background: var(--color-canvas);
}
.meta {
font-size: var(--font-size-s);
}
@media (width < 42rem) {
.salary-grid {
grid-template-columns: minmax(0, 1fr);
}
.group,
.salary,
.conflict,
.recommendations,
.list {
padding: var(--space-3);
}
}
@@ -0,0 +1,90 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { parse as parseYaml } from "yaml";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Need, Session } from "../../../shared/api/schemas";
import { Need as NeedSchema } from "../../../shared/api/schemas";
import { NeedEditor } from "./need-editor";
type ExampleMap = Record<string, { value?: unknown } | undefined>;
const bundlePath = fileURLToPath(
new URL("../../../../../api/core/openapi.bundle.yml", import.meta.url),
);
const examples = (
parseYaml(readFileSync(bundlePath, "utf8")) as { components: { examples: ExampleMap } }
).components.examples;
function contractExample(name: string): unknown {
const value = examples[name]?.value;
if (value === undefined) throw new Error(`Missing contract example ${name}.`);
return value;
}
const need = NeedSchema.parse(contractExample("NeedExtractedWithUnknownSkill")) as Need;
const session: Session = {
account: {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
email: "owner@example.test",
email_verified: true,
scenario: "employer",
onboarding_step: "completed",
created_at: "2026-10-06T09:00:00Z",
},
csrf_token: "abcdefghijklmnopqrstuvwxyz123456",
};
function renderEditor(value: Need): string {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<NeedEditor
accountId={session.account.id}
organizationId={value.organization_id}
session={session}
need={value}
onCreated={() => undefined}
onSaved={() => undefined}
onAccessLost={() => undefined}
/>
</QueryClientProvider>,
);
}
describe("NeedEditor", () => {
it("keeps parser suggestions reviewable and asks about unknown critical fields", () => {
const markup = renderEditor(need);
expect(markup).toContain("Предложено из текста");
expect(markup).toContain("Подтвердить предложение");
expect(markup).toContain("Какой грейд нужен");
expect(markup).toContain("в какой базе");
expect(markup).toContain("Вакансия для сохранения потребности не требуется.");
expect(markup).toMatch(
/<select id="[^"]+-grade" aria-invalid="false"><option value="" selected="">Не указано/,
);
});
it("shows pending recommendation status without fabricating categories", () => {
const pending: Need = {
...need,
recommendations: {
status: "pending",
requirements_version: need.requirements_version,
policy_version: null,
algorithm_version: null,
computed_at: null,
categories: [],
},
};
const markup = renderEditor(pending);
expect(markup).toContain("Рекомендации пока не рассчитаны.");
expect(markup).not.toContain("Категории рассчитаны по подтвержденным требованиям.");
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
export { RequestManualAssessment } from "./ui/request-manual-assessment";
@@ -0,0 +1,11 @@
import type { CatalogSpecializationOption } from "../../../entities/specialization";
export function manualAvailabilityMessage(option: CatalogSpecializationOption | null): string {
if (!option) return "Выберите специальность, чтобы увидеть ее доступность.";
if (option.test_availability.status === "in_development") {
return option.test_availability.note
? `${option.test_availability.note} Запрос ручной оценки остается доступен.`
: "Автоматическая проверка пока не опубликована. Запрос ручной оценки остается доступен.";
}
return "Автоматическая проверка опубликована отдельно. Этот запрос направляется эксперту и не запускает тест.";
}
@@ -0,0 +1,90 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.intro,
.privacy,
.hint {
max-width: 72ch;
margin: 0;
color: var(--color-text-secondary);
line-height: var(--line-height-body);
}
.privacy {
color: var(--color-text);
}
.form {
display: grid;
gap: var(--space-5);
max-width: 52rem;
min-width: 0;
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.field label {
font-weight: var(--font-weight-bold);
}
.field select,
.field textarea {
box-sizing: border-box;
width: 100%;
min-width: 0;
max-width: 100%;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
line-height: var(--line-height-body);
}
.field textarea {
min-height: 10rem;
resize: vertical;
}
.field select:focus-visible,
.field textarea:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.hint {
font-size: var(--font-size-s);
}
.error {
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-danger);
background: var(--color-surface);
}
.error:focus {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-4);
}
@media (width <= 40rem) {
.actions > :first-child {
width: 100%;
}
}
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vitest";
import type { CatalogSpecializationOption } from "../../../entities/specialization";
import { manualAvailabilityMessage } from "../model/availability-message";
const unavailableOption: CatalogSpecializationOption = {
code: "ds_ml",
title: "DS/ML",
directionCode: "data",
directionTitle: "Данные",
test_availability: {
status: "in_development",
grades: [],
task_languages: [],
note: "Банк заданий готовится.",
},
};
describe("manual assessment availability copy", () => {
it("keeps the manual request available when the automated bank is unavailable", () => {
const copy = manualAvailabilityMessage(unavailableOption);
expect(copy).toContain("Банк заданий готовится.");
expect(copy).toContain("Запрос ручной оценки остается доступен.");
});
it("states that a manual request does not start an available automated test", () => {
const copy = manualAvailabilityMessage({
...unavailableOption,
test_availability: {
status: "available",
grades: ["junior"],
task_languages: ["go"],
note: null,
},
});
expect(copy).toContain("не запускает тест");
});
});
@@ -0,0 +1,294 @@
import { useEffect, useId, useMemo, useRef, useState, type FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
createSupportCaseIdempotencyKey,
getSupportCaseIdempotencyKey,
isSupportSessionAccessError,
queryClientHasSupportActor,
supportCaseCreateFailureMessage,
supportCaseDetailQueryKey,
supportCaseListQueryKey,
supportCasePathFor,
supportSessionMatches,
type SupportCaseKeyBinding,
} from "../../../entities/support-case";
import { listSpecializationOptions } from "../../../entities/specialization";
import { ApiRequestError } from "../../../shared/api";
import { useGetSpecializationCatalog } from "../../../shared/api/endpoints/catalog/catalog";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import { createMySupportCase } from "../../../shared/api/endpoints/support/support";
import { manualAvailabilityMessage } from "../model/availability-message";
import type {
CatalogGrade,
Session,
SpecializationCode,
SupportCase,
SupportCaseCreate,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Section,
TextLink,
} from "../../../shared/ui";
import styles from "./request-manual-assessment.module.css";
export function RequestManualAssessment() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.isSuccess ? session.data : null;
const knownActor =
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const catalog = useGetSpecializationCatalog({ query: { retry: false, staleTime: 0 } });
const formId = useId();
const errorRef = useRef<HTMLDivElement>(null);
const idempotencyBinding = useRef<SupportCaseKeyBinding | null>(null);
const [specializationCode, setSpecializationCode] = useState<SpecializationCode | "">("");
const [gradeCode, setGradeCode] = useState<CatalogGrade["code"] | "">("");
const [description, setDescription] = useState("");
const [actionError, setActionError] = useState<string | null>(null);
const options = useMemo(
() => (catalog.data ? listSpecializationOptions(catalog.data) : []),
[catalog.data],
);
const specialization = useMemo(
() => options.find((option) => option.code === specializationCode) ?? null,
[options, specializationCode],
);
const create = useMutation({
mutationFn: ({ data, key }: { data: SupportCaseCreate; key: string }) => {
const csrfToken = actor?.csrf_token;
if (!actor || !csrfToken || !session.isSuccess) {
throw new Error("An active account session is required.");
}
return createMySupportCase(
data,
{ "Idempotency-Key": key },
{ headers: { "X-CSRF-Token": csrfToken } },
);
},
gcTime: 0,
});
useEffect(() => {
if (actionError) errorRef.current?.focus();
}, [actionError]);
useEffect(() => {
const accountId = actor?.account.id ?? knownActor?.account.id;
if (!accountId || !isSupportSessionAccessError(session.error)) return;
queryClient.removeQueries({
predicate: (query) =>
query.queryKey[0] === "account" &&
query.queryKey[1] === accountId &&
query.queryKey[2] === "support-cases",
});
}, [actor, knownActor, queryClient, session.error]);
if (session.isPending && !session.data) return <LoadingState label="Проверяем вход..." />;
if (session.isError && isSupportSessionAccessError(session.error)) {
return (
<ForbiddenState
error={session.error}
title="Войдите, чтобы отправить запрос эксперту"
description="После входа вы вернетесь в раздел поддержки. Запрос не включает согласие C3."
action={
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
Войти и продолжить
</ButtonLink>
}
/>
);
}
if (session.isError) {
return (
<ErrorState
error={session.error}
title="Не удалось проверить вход"
isRetrying={session.isRefetching}
onRetry={() => void session.refetch()}
/>
);
}
if (!actor || actor.account.scenario !== "candidate") {
return (
<ForbiddenState
title="Ручная оценка доступна кандидатам"
description="Откройте кабинет кандидата, чтобы выбрать специальность и желаемый грейд."
/>
);
}
if (catalog.isPending && !catalog.data)
return <LoadingState label="Загружаем каталог специальностей..." />;
if (catalog.isError && !catalog.data) {
return (
<ErrorState
error={catalog.error}
title="Не удалось загрузить специальности"
isRetrying={catalog.isRefetching}
onRetry={() => void catalog.refetch()}
/>
);
}
if (catalog.isError) {
return (
<ErrorState
error={catalog.error}
title="Не удалось подтвердить каталог"
isRetrying={catalog.isRefetching}
onRetry={() => void catalog.refetch()}
/>
);
}
const isSubmitting = create.isPending;
const grades = catalog.data?.grades ?? [];
const canSubmit = Boolean(specializationCode && gradeCode && description.trim()) && !isSubmitting;
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (
!canSubmit ||
!actor ||
!specialization ||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
) {
return;
}
setActionError(null);
const data: SupportCaseCreate = {
type: "manual_assessment",
description,
assessment_target: {
specialization: specialization.code,
grade: gradeCode as CatalogGrade["code"],
},
};
const binding = getSupportCaseIdempotencyKey(
data,
idempotencyBinding.current,
createSupportCaseIdempotencyKey,
);
idempotencyBinding.current = binding;
let created: SupportCase;
try {
created = await create.mutateAsync({ data, key: binding.key });
} catch (error: unknown) {
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
if (error instanceof ApiRequestError && error.code === "idempotency_key_reused") {
idempotencyBinding.current = null;
}
setActionError(supportCaseCreateFailureMessage(error));
return;
}
if (!queryClientHasSupportActor(queryClient, getGetCurrentSessionQueryKey(), actor)) return;
queryClient.setQueryData(supportCaseDetailQueryKey(actor.account.id, created.id), created);
void queryClient.invalidateQueries({ queryKey: supportCaseListQueryKey(actor.account.id) });
navigate(supportCasePathFor(actor, created.id), { replace: true });
}
return (
<div className={styles.root}>
<Section title="Запрос ручной оценки">
<p className={styles.intro}>
Вы выбираете специальность и желаемый грейд. Эксперт рассмотрит запрос по рубрике этой
категории, если она опубликована. Запрос доступен до первой попытки и не требует C3.
</p>
<p className={styles.privacy}>
Отправка не включает и не меняет C3, не создает попытку и не меняет подтвержденный грейд.{" "}
<TextLink to={paths.candidate.privacy}>Проверить состояние согласия C3</TextLink>.
</p>
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
<div className={styles.field}>
<label htmlFor={`${formId}-specialization`}>Специальность</label>
<select
id={`${formId}-specialization`}
value={specializationCode}
onChange={(event) =>
setSpecializationCode(event.currentTarget.value as SpecializationCode | "")
}
disabled={isSubmitting || catalog.isFetching}
aria-describedby={`${formId}-availability`}
required
>
<option value="">Выберите специальность</option>
{options.map((option) => (
<option key={option.code} value={option.code}>
{option.title}
</option>
))}
</select>
<p id={`${formId}-availability`} className={styles.hint}>
{manualAvailabilityMessage(specialization)}
</p>
</div>
<div className={styles.field}>
<label htmlFor={`${formId}-grade`}>Желаемый грейд</label>
<select
id={`${formId}-grade`}
value={gradeCode}
onChange={(event) =>
setGradeCode(event.currentTarget.value as CatalogGrade["code"] | "")
}
disabled={isSubmitting}
required
>
<option value="">Выберите грейд</option>
{grades.map((grade) => (
<option key={grade.code} value={grade.code}>
{grade.title}
</option>
))}
</select>
<p className={styles.hint}>Это желаемая цель оценки, а не подтвержденный результат.</p>
</div>
<div className={styles.field}>
<label htmlFor={`${formId}-description`}>Почему вы просите ручную оценку</label>
<textarea
id={`${formId}-description`}
value={description}
onChange={(event) => setDescription(event.currentTarget.value)}
rows={6}
maxLength={4000}
required
disabled={isSubmitting}
aria-describedby={`${formId}-description-hint${actionError ? ` ${formId}-error` : ""}`}
/>
<p id={`${formId}-description-hint`} className={styles.hint}>
Можно отправить запрос без предыдущей попытки. До 4000 символов.
</p>
</div>
{actionError ? (
<div
id={`${formId}-error`}
className={styles.error}
role="alert"
tabIndex={-1}
ref={errorRef}
>
{actionError}
</div>
) : null}
<div className={styles.actions}>
<Button type="submit" isBusy={isSubmitting} aria-disabled={!canSubmit}>
{isSubmitting ? "Отправляем запрос..." : "Отправить запрос эксперту"}
</Button>
<TextLink to={paths.candidate.supportCases}>Мои обращения</TextLink>
</div>
</form>
</Section>
</div>
);
}
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { paths } from "../../../shared/config";
import { getSignInDestination } from "./sign-in-destination";
describe("getSignInDestination", () => {
it.each(["candidate", "employer"] as const)(
"returns %s to its own support area before onboarding is complete",
(scenario) => {
expect(
getSignInDestination(
{ scenario, onboarding_step: "candidate_consents" },
{ returnTo: "support", pathname: "https://example.test/", scenario: "other" },
),
).toBe(paths[scenario].supportCases);
},
);
it.each([
null,
undefined,
"support",
[],
{ returnTo: "/support" },
{ returnTo: "https://example.test/" },
{ returnTo: "//example.test/" },
{ pathname: "/support" },
{ returnTo: { pathname: "/support" } },
])("ignores an unrecognized return intent: %j", (state) => {
expect(
getSignInDestination({ scenario: "candidate", onboarding_step: "candidate_profile" }, state),
).toBe(paths.candidate.profile);
});
});
@@ -0,0 +1,22 @@
import { getOnboardingDestination } from "../../../entities/session";
import type { Account } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
/** Only a fixed support intent can override the saved onboarding step. */
export function getSignInDestination(
account: Pick<Account, "scenario" | "onboarding_step">,
state: unknown,
): string {
if (
typeof state === "object" &&
state !== null &&
!Array.isArray(state) &&
"returnTo" in state &&
state.returnTo === "support"
) {
return account.scenario === "candidate"
? paths.candidate.supportCases
: paths.employer.supportCases;
}
return getOnboardingDestination(account);
}
@@ -1,13 +1,13 @@
import { useQueryClient } from "@tanstack/react-query";
import { useId, useState, type FormEvent } from "react";
import { useNavigate } from "react-router-dom";
import { useLocation, useNavigate } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import { useLogin } from "../../../shared/api/endpoints/identity/identity";
import { EmailAddress } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { getOnboardingDestination } from "../../../entities/session";
import { Button, TextLink } from "../../../shared/ui";
import { establishSession } from "../model/establish-session";
import { getSignInDestination } from "../model/sign-in-destination";
import styles from "./sign-in-form.module.css";
type SignInFormProps = {
@@ -19,6 +19,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
const id = useId();
const queryClient = useQueryClient();
const navigate = useNavigate();
const location = useLocation();
const login = useLogin({ mutation: { gcTime: 0 } });
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
@@ -46,7 +47,7 @@ export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
establishSession(queryClient, session);
setPassword("");
onSignedIn();
await navigate(getOnboardingDestination(session.account), { replace: true });
await navigate(getSignInDestination(session.account, location.state), { replace: true });
} catch (error: unknown) {
if (error instanceof ApiRequestError && error.code === "email_not_verified") {
onUnverified(email);
+2
View File
@@ -0,0 +1,2 @@
export { AssessmentAttemptPage } from "./ui/assessment-attempt-page";
export { AssessmentPage } from "./ui/assessment-page";
@@ -0,0 +1,102 @@
.layout {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.resume,
.finalize,
.info,
.result,
.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);
}
.resume p,
.finalize p,
.info p,
.result p {
margin: 0;
}
.item {
gap: var(--space-4);
border-color: var(--color-border-strong);
}
.item-heading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: var(--space-2);
}
.item-heading h2,
.result h2 {
margin: 0;
font-size: var(--font-size-l);
}
.item-heading span {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.prompt {
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: var(--line-height-body);
}
.info {
color: var(--color-text-secondary);
}
.error {
margin: 0;
color: var(--color-danger);
}
.result {
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.demo-label {
font-weight: var(--font-weight-bold);
}
.result-error {
display: grid;
gap: var(--space-3);
}
.back-link {
display: flex;
flex-wrap: wrap;
}
@media (width < 42rem) {
.resume,
.finalize,
.info,
.result,
.item {
padding: var(--space-3);
}
}
@@ -0,0 +1,678 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import {
finalizeMyAssessmentAttempt,
startMyAssessmentAttemptSession,
} from "../../../shared/api/endpoints/assessment/assessment";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type {
AssessmentAttempt,
AssessmentFinalization,
Session,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
} from "../../../shared/ui";
import {
assessmentQueryKeys,
assessmentResultSummary,
assessmentSessionMatches,
gradeLabels,
isOutcomeAmbiguous,
isCurrentAssessmentSession,
methodLabel,
parseAssessmentAttemptResponse,
removeAssessmentQueries,
removeAssessmentQueriesForSessionChange,
useAssessmentAttempt,
useAssessmentResult,
} from "../../../entities/assessment";
import {
AnswerForm,
buildAnswerSubmission,
newIdempotencyKey,
submitPendingAnswerCommand,
} from "../../../features/answer-assessment";
import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment";
import attemptStyles from "./assessment-attempt-page.module.css";
type PendingFinalize = { key: string; body: AssessmentFinalization };
function isAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
}
function isTerminal(attempt: AssessmentAttempt): boolean {
return ["completed", "expired", "insufficient_bank"].includes(attempt.state);
}
function attemptName(attempt: AssessmentAttempt): string {
if (attempt.kind === "demo_express") return "Демонстрационный экспресс-запуск";
return `${attempt.specialization ? attempt.specialization : "Проверка"} - ${attempt.target_grade ? gradeLabels[attempt.target_grade] : ""}`;
}
function answerErrorMessage(error: unknown): string {
if (error instanceof ApiRequestError && error.status === 0) {
return "Не удалось связаться с сервером. Повторите отправку того же ответа.";
}
if (error instanceof ApiRequestError && error.status >= 500) {
return "Сервер не подтвердил ответ. Повторите отправку того же ответа.";
}
if (error instanceof ApiRequestError && error.status === 429) {
return error.retryAfterSeconds
? `Слишком много запросов. Повторите через ${error.retryAfterSeconds} сек.`
: "Слишком много запросов. Повторите позже.";
}
if (error instanceof ApiRequestError && error.status === 412) {
return "Попытка изменилась в другом окне. Проверьте актуальное задание и отправьте ответ еще раз.";
}
if (error instanceof ApiRequestError && error.status === 400) {
return "Сервер не принял этот формат ответа. Проверьте введенные данные.";
}
return "Не удалось отправить ответ. Проверьте соединение и повторите попытку.";
}
export function AssessmentAttemptPage() {
const { attemptId = "" } = useParams();
return <AssessmentAttemptContent key={attemptId} attemptId={attemptId} />;
}
function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
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 attemptQuery = useAssessmentAttempt({ actor, attemptId, enabled: actorReady, queryClient });
const attempt = attemptQuery.data;
const resultQuery = useAssessmentResult({
actor,
attemptId,
enabled: actorReady && Boolean(attempt && isTerminal(attempt)),
queryClient,
});
const [workReady, setWorkReady] = useState(false);
const [resumeBusy, setResumeBusy] = useState(false);
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
const [answerBusy, setAnswerBusy] = useState(false);
const [answerError, setAnswerError] = useState<string | null>(null);
const [answerNeedsReview, setAnswerNeedsReview] = useState(false);
const [pendingFinalize, setPendingFinalize] = useState<PendingFinalize | null>(null);
const [finalizeBusy, setFinalizeBusy] = useState(false);
const [pageError, setPageError] = useState<string | null>(null);
const [accessDenied, setAccessDenied] = useState(false);
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
const requestInFlight = useRef(false);
useEffect(() => {
const next =
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
const previous = previousActor.current;
if (previous && (!next || previous.accountId !== next.accountId)) {
removeAssessmentQueriesForSessionChange(queryClient);
setPendingResume(null);
setPendingAnswer(null);
setPendingFinalize(null);
setWorkReady(false);
setPageError(null);
setAnswerError(null);
setAccessDenied(false);
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
removeAssessmentQueriesForSessionChange(queryClient);
setWorkReady(false);
setPageError("Проверка входа обновлена. Продолжите попытку еще раз.");
}
previousActor.current = next;
}, [actor, actorReady, queryClient]);
useEffect(() => {
if (attemptQuery.isError && isAccessLoss(attemptQuery.error)) {
removeAssessmentQueries(queryClient);
queueMicrotask(() => {
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
setAccessDenied(true);
setWorkReady(false);
});
}
if (resultQuery.isError && isAccessLoss(resultQuery.error)) {
removeAssessmentQueries(queryClient);
queueMicrotask(() => {
if (!actor || !isCurrentAssessmentSession(queryClient, actor)) return;
setAccessDenied(true);
setWorkReady(false);
});
}
}, [
actor,
attemptQuery.error,
attemptQuery.isError,
queryClient,
resultQuery.error,
resultQuery.isError,
]);
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
const key = getGetCurrentSessionQueryKey();
const captured = queryClient.getQueryData<Session>(key);
if (!assessmentSessionMatches(queryClient.getQueryState<Session>(key), currentActor))
return false;
const refreshed = await session.refetch();
const latest = queryClient.getQueryData<Session>(key);
const state = queryClient.getQueryState<Session>(key);
if (
!captured ||
refreshed.isError ||
!refreshed.data ||
state?.status !== "success" ||
latest?.account.id !== currentActor.account.id ||
latest.csrf_token !== refreshed.data.csrf_token
) {
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
}
return false;
}
if (captured.csrf_token !== currentActor.csrf_token) return false;
setAnswerError("Проверка входа обновлена. Черновик сохранен, повторите отправку.");
return true;
}
async function resumeWork() {
if (
!actor ||
!attempt ||
!isCurrentAssessmentSession(queryClient, actor) ||
requestInFlight.current
)
return;
const command = pendingResume ?? { key: newIdempotencyKey(), version: attempt.version };
if (!pendingResume) setPendingResume(command);
requestInFlight.current = true;
setResumeBusy(true);
setPageError(null);
try {
const resumedResponse = await startMyAssessmentAttemptSession(
attempt.id,
{ expected_version: command.version },
{ "Idempotency-Key": command.key },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const resumed = parseAssessmentAttemptResponse(resumedResponse);
if (!isCurrentAssessmentSession(queryClient, actor)) return;
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), resumed);
setPendingResume(null);
setWorkReady(true);
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, actor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
await refreshSessionForActor(actor);
} else if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
} else if (isOutcomeAmbiguous(error)) {
setPageError("Не удалось подтвердить продолжение. Повторите запрос с тем же ключом.");
} else {
setPendingResume(null);
setPageError("Не удалось продолжить попытку. Обновите состояние и повторите действие.");
await attemptQuery.refetch();
}
} finally {
requestInFlight.current = false;
setResumeBusy(false);
}
}
async function refetchAttempt(): Promise<AssessmentAttempt | null> {
const refreshed = await attemptQuery.refetch();
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || refreshed.isError) return null;
return refreshed.data ?? null;
}
async function sendAnswer(draft: AnswerDraft) {
if (!actor || !attempt || !attempt.current_item || !workReady || requestInFlight.current)
return;
const built = buildAnswerSubmission(attempt, attempt.current_item, draft);
if (!built.ok) {
setAnswerError(built.message);
return;
}
const command: PendingAnswerCommand = {
key: newIdempotencyKey(),
body: built.body,
itemId: attempt.current_item.id,
};
await sendPendingAnswer(command, actor, attempt.id);
}
async function retryAnswer() {
if (!actor || !attempt || !pendingAnswer || requestInFlight.current) return;
await sendPendingAnswer(pendingAnswer, actor, attempt.id);
}
async function sendPendingAnswer(
command: PendingAnswerCommand,
currentActor: Session,
currentAttemptId: string,
) {
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
setPendingAnswer(command);
requestInFlight.current = true;
setAnswerBusy(true);
setAnswerError(null);
setAnswerNeedsReview(false);
try {
const outcome = await submitPendingAnswerCommand(
command,
currentAttemptId,
currentActor.csrf_token,
);
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
if (outcome.kind === "retry") {
setPendingAnswer(outcome.command);
setAnswerError(answerErrorMessage(outcome.error));
return;
}
if (outcome.kind === "rejected") throw outcome.error;
const saved = outcome.attempt;
const key = assessmentQueryKeys.attempt(currentActor, currentAttemptId);
queryClient.setQueryData<AssessmentAttempt>(key, (current) =>
current && current.version > saved.version ? current : saved,
);
void queryClient.invalidateQueries({ queryKey: key });
setPendingAnswer(null);
setAnswerError(null);
setAnswerNeedsReview(false);
setWorkReady(true);
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
await refreshSessionForActor(currentActor);
return;
}
if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setPendingAnswer(null);
setAccessDenied(true);
setWorkReady(false);
return;
}
if (isOutcomeAmbiguous(error)) {
setAnswerError(answerErrorMessage(error));
return;
}
setPendingAnswer(null);
setAnswerError(answerErrorMessage(error));
if (error instanceof ApiRequestError && error.status === 412) {
const latest = await refetchAttempt();
setAnswerNeedsReview(Boolean(latest?.current_item?.id === command.itemId));
if (latest?.current_item?.id !== command.itemId) {
setAnswerError("Попытка изменилась в другом окне. Показано текущее задание с сервера.");
}
} else if (error instanceof ApiRequestError && error.status === 409) {
const latest = await refetchAttempt();
if (latest) {
queryClient.setQueryData(
assessmentQueryKeys.attempt(currentActor, currentAttemptId),
latest,
);
}
setWorkReady(false);
setPageError(
"Сеанс работы завершился или состояние попытки изменилось. Продолжите попытку заново.",
);
}
} finally {
requestInFlight.current = false;
setAnswerBusy(false);
}
}
async function finalizeAttempt() {
if (!actor || !attempt || !workReady || requestInFlight.current) return;
const body: AssessmentFinalization = { expected_version: attempt.version };
const command = pendingFinalize ?? { key: newIdempotencyKey(), body };
if (!pendingFinalize) setPendingFinalize(command);
requestInFlight.current = true;
setFinalizeBusy(true);
setPageError(null);
try {
const finalizedResponse = await finalizeMyAssessmentAttempt(
attempt.id,
command.body,
{ "Idempotency-Key": command.key },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const finalized = parseAssessmentAttemptResponse(finalizedResponse);
if (!isCurrentAssessmentSession(queryClient, actor)) return;
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), finalized);
setPendingFinalize(null);
await queryClient.invalidateQueries({
queryKey: assessmentQueryKeys.result(actor, attempt.id),
});
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, actor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
await refreshSessionForActor(actor);
} else if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
setWorkReady(false);
} else if (isOutcomeAmbiguous(error)) {
setPageError("Сервер не подтвердил завершение. Повторите запрос с тем же ключом.");
} else {
setPendingFinalize(null);
setPageError("Сервер пока не завершил попытку. Обновите состояние и повторите действие.");
const latest = await refetchAttempt();
if (latest)
queryClient.setQueryData(assessmentQueryKeys.attempt(actor, attempt.id), latest);
}
} finally {
requestInFlight.current = false;
setFinalizeBusy(false);
}
}
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ForbiddenState
error={session.error}
title="Попытка недоступна"
description="Сервер не подтвердил доступ к этой попытке. Проверьте вход в кабинет кандидата."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
</Page>
);
}
if (session.isPending || !actor) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (!actorReady) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<LoadingState label="Подтверждаем текущий вход..." />
</Page>
);
}
if (!attemptId) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ErrorState
error={new Error("The attempt identifier is missing.")}
title="Не удалось открыть попытку"
/>
</Page>
);
}
if (attemptQuery.isPending && !attempt) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<LoadingState label="Загружаем сохраненную попытку..." />
</Page>
);
}
if (attemptQuery.isError || !attempt) {
if (isAccessLoss(attemptQuery.error)) {
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ForbiddenState
error={attemptQuery.error}
title="Попытка недоступна"
description="Сервер не подтвердил доступ к этой попытке."
action={<ButtonLink to={paths.candidate.assessment}>К списку проверок</ButtonLink>}
/>
</Page>
);
}
return (
<Page title="Попытка проверки" eyebrow="Кабинет кандидата">
<ErrorState
error={attemptQuery.error}
isRetrying={attemptQuery.isRefetching}
onRetry={() => void attemptQuery.refetch()}
title="Не удалось загрузить попытку"
/>
</Page>
);
}
const currentItem = attempt.current_item;
const practicePending = attempt.practices.some((practice) => practice.status === "pending");
const pendingAnswerNeedsReplay = Boolean(
pendingAnswer && pendingAnswer.itemId !== currentItem?.id,
);
const canFinalize =
attempt.state === "ready_to_finalize" ||
(attempt.state === "additional_practice_pending" &&
!currentItem &&
attempt.practices.some(
(practice) =>
practice.kind === "additional" && ["not_started", "failed"].includes(practice.status),
));
const terminal = isTerminal(attempt);
return (
<Page
title={attempt.kind === "demo_express" ? "Демонстрационная проверка" : "Полная проверка"}
eyebrow="Кабинет кандидата"
lead={
attempt.kind === "demo_express"
? "Учебный режим на 3-5 минут. Он не подтверждает квалификацию и не присваивает грейд."
: undefined
}
width="wide"
>
<div className={attemptStyles.layout}>
<Section
title={attemptName(attempt)}
description={`${methodLabel(attempt.mode)}. Сервер хранит состояние и результат попытки.`}
>
<div className={attemptStyles.meta}>
<span>
Заданий: {attempt.progress.answered_items} из {attempt.progress.max_items}
</span>
<span>
Срок до:{" "}
{new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(
new Date(attempt.expires_at),
)}
</span>
{attempt.sessions ? (
<span>
Сеанс {attempt.sessions.used} из {attempt.sessions.max}
</span>
) : null}
</div>
{pageError ? (
<p className={attemptStyles.error} role="alert">
{pageError}
</p>
) : null}
{!workReady && !terminal ? (
<div className={attemptStyles.resume}>
<p>
Продолжение сверит актуальную версию с сервером. При перезагрузке задания не
меняются, а ответ не отправляется повторно автоматически.
</p>
<Button isBusy={resumeBusy} onClick={() => void resumeWork()}>
{resumeBusy
? "Проверяем попытку..."
: pendingResume
? "Повторить продолжение"
: "Начать или продолжить"}
</Button>
</div>
) : null}
{workReady && pendingAnswerNeedsReplay && !terminal ? (
<div className={attemptStyles.info} role="status">
<p>Предыдущий ответ еще не подтвержден. Сначала повторите отправку того же ответа.</p>
<Button isBusy={answerBusy} onClick={() => void retryAnswer()}>
{answerBusy ? "Повторяем отправку..." : "Повторить отправку того же ответа"}
</Button>
</div>
) : null}
{workReady &&
currentItem &&
!terminal &&
(!pendingAnswer || pendingAnswer.itemId === currentItem.id) ? (
<article className={attemptStyles.item} aria-labelledby="assessment-item-title">
<div className={attemptStyles["item-heading"]}>
<h2 id="assessment-item-title">Задание {currentItem.sequence}</h2>
<span>
{currentItem.sequence} из {attempt.progress.max_items}
</span>
</div>
<p className={attemptStyles.prompt}>{currentItem.prompt}</p>
<AnswerForm
key={currentItem.id}
item={currentItem}
isSaving={answerBusy}
retryable={Boolean(pendingAnswer && pendingAnswer.itemId === currentItem.id)}
errorMessage={answerError}
onSubmit={(draft) => void sendAnswer(draft)}
onRetry={() => void retryAnswer()}
/>
{answerNeedsReview ? (
<p className={attemptStyles.info} role="status">
Черновик остался в форме. Проверьте его и отправьте для актуальной версии попытки.
</p>
) : null}
</article>
) : null}
{workReady && practicePending && !currentItem && !pendingAnswerNeedsReplay ? (
<p className={attemptStyles.info} role="status">
Решение передано на проверку. Результат появится после ответа сервера; страница
обновляет статус автоматически.
</p>
) : null}
{workReady &&
!currentItem &&
!practicePending &&
canFinalize &&
!terminal &&
!pendingAnswerNeedsReplay ? (
<div className={attemptStyles.finalize}>
<p>
Обязательные задания завершены. Решение по уровню примет сервер после подтверждения.
</p>
<Button isBusy={finalizeBusy} onClick={() => void finalizeAttempt()}>
{finalizeBusy
? "Запрашиваем решение..."
: pendingFinalize
? "Повторить завершение"
: "Завершить проверку"}
</Button>
</div>
) : null}
{workReady &&
!currentItem &&
!practicePending &&
!canFinalize &&
!terminal &&
!pendingAnswerNeedsReplay ? (
<div className={attemptStyles.info} role="status">
<p>Сервер не вернул следующее задание. Обновите состояние попытки.</p>
<Button
variant="secondary"
isBusy={attemptQuery.isRefetching}
onClick={() => void attemptQuery.refetch()}
>
Обновить попытку
</Button>
</div>
) : null}
{terminal ? <ResultView resultQuery={resultQuery} /> : null}
</Section>
<div className={attemptStyles["back-link"]}>
<ButtonLink variant="secondary" to={paths.candidate.assessment}>
К доступным проверкам
</ButtonLink>
</div>
</div>
</Page>
);
}
function ResultView({ resultQuery }: { resultQuery: ReturnType<typeof useAssessmentResult> }) {
if (resultQuery.isPending && !resultQuery.data) {
return <LoadingState label="Загружаем сохраненный результат..." />;
}
if (resultQuery.isError || !resultQuery.data) {
return (
<div className={attemptStyles["result-error"]}>
{resultQuery.error instanceof ApiRequestError && resultQuery.error.status === 409 ? (
<p role="status">Сервер еще завершает обработку результата. Повторите проверку позже.</p>
) : (
<ErrorState
error={resultQuery.error}
isRetrying={resultQuery.isRefetching}
onRetry={() => void resultQuery.refetch()}
title="Не удалось загрузить результат"
/>
)}
<Button
variant="secondary"
isBusy={resultQuery.isRefetching}
onClick={() => void resultQuery.refetch()}
>
Обновить результат
</Button>
</div>
);
}
const result = resultQuery.data;
const summary = assessmentResultSummary(result);
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>
);
}
@@ -0,0 +1,49 @@
import type {
AssessmentAttemptCreate,
GradeCode,
SpecializationCode,
TaskLanguage,
} from "../../../shared/api/schemas";
import { createMyAssessmentAttempt } from "../../../shared/api/endpoints/assessment/assessment";
import { parseAssessmentAttemptResponse } from "../../../entities/assessment";
export type PendingCreate = { key: string; body: AssessmentAttemptCreate };
export function buildRootAttemptCreate(
specialization: SpecializationCode,
grade: GradeCode,
savedLanguages: readonly TaskLanguage[],
selectedLanguage: TaskLanguage | "",
): AssessmentAttemptCreate | null {
let taskLanguage: TaskLanguage | null = null;
if (savedLanguages.length === 1) {
taskLanguage = savedLanguages[0] ?? null;
} else if (savedLanguages.length > 1) {
if (!selectedLanguage || !savedLanguages.includes(selectedLanguage)) return null;
taskLanguage = selectedLanguage;
}
return {
kind: "root",
specialization,
target_grade: grade,
task_language: taskLanguage,
};
}
export function preservePendingCreate(
pending: PendingCreate | null,
body: AssessmentAttemptCreate | null,
keyFactory: () => string,
): PendingCreate | null {
return pending ?? (body ? { key: keyFactory(), body } : null);
}
export function submitPendingAttempt(command: PendingCreate, csrfToken: string) {
return createMyAssessmentAttempt(
command.body,
{ "Idempotency-Key": command.key },
{ headers: { "X-CSRF-Token": csrfToken } },
).then((response) => parseAssessmentAttemptResponse(response, 201));
}
@@ -0,0 +1,141 @@
.layout {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.controls {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3);
}
.field {
display: grid;
gap: var(--space-2);
min-width: 0;
font-weight: var(--font-weight-bold);
}
.field select {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.field select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.language-note,
.language-availability {
margin: 0;
color: var(--color-text-secondary);
}
.language-note {
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-divider);
}
.language-availability {
max-width: 72ch;
font-size: var(--font-size-s);
}
.availability,
.express,
.notice {
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);
}
.availability p,
.express p,
.notice p {
margin: 0;
}
.status-row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: var(--space-2);
}
.status-row [data-state="available"] {
font-weight: var(--font-weight-bold);
}
.limits {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3);
margin: 0;
}
.limits div {
min-width: 0;
padding: var(--space-3);
background: var(--color-canvas);
border-radius: var(--radius-s);
}
.limits dt {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.limits dd {
margin: var(--space-1) 0 0;
font-weight: var(--font-weight-bold);
overflow-wrap: anywhere;
}
.notice {
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.notice h3 {
margin: 0;
font-size: var(--font-size-m);
}
.notice p,
.express p,
.pending {
color: var(--color-text-secondary);
}
.pending {
margin: 0;
}
.error {
margin: 0;
color: var(--color-danger);
}
@media (width < 42rem) {
.controls,
.limits {
grid-template-columns: minmax(0, 1fr);
}
.availability,
.express,
.notice {
padding: var(--space-3);
}
}
@@ -0,0 +1,190 @@
import { renderToStaticMarkup } from "react-dom/server";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { http, HttpResponse } from "msw";
import { AssessmentPolicyParameters, TaskLanguageControl } from "./assessment-page";
import {
buildRootAttemptCreate,
preservePendingCreate,
submitPendingAttempt,
} from "./assessment-page.model";
const server = setupServer();
beforeAll(() => server.listen());
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
describe("assessment task language selection", () => {
it("sends null when the saved questionnaire has no language", () => {
expect(buildRootAttemptCreate("backend", "junior", [], "")).toEqual({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: null,
});
});
it("uses the only saved language without an ambiguous default", () => {
expect(buildRootAttemptCreate("backend", "junior", ["python"], "")).toEqual({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "python",
});
});
it("requires an explicit choice when the questionnaire has multiple languages", () => {
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "")).toBeNull();
expect(buildRootAttemptCreate("backend", "junior", ["python", "go"], "go")).toEqual({
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
});
});
it("keeps the selected second language and idempotency key on an exact retry", () => {
const body = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
expect(body).not.toBeNull();
const keyFactory = vi.fn(() => "original-key");
const pending = preservePendingCreate(null, body, keyFactory);
const retryBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "python");
const retried = preservePendingCreate(pending, retryBody, () => "new-key");
expect(pending?.body).toMatchObject({ kind: "root", task_language: "go" });
expect(retried).toBe(pending);
expect(retried?.key).toBe("original-key");
expect(retried?.body).toEqual(body);
expect(keyFactory).toHaveBeenCalledOnce();
});
it("posts the selected second language and replays the same request after an ambiguous response", async () => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const requests: Array<{ body: unknown; key: string | null; csrf: string | null }> = [];
server.use(
http.post("http://localhost/api/v1/me/assessment-attempts", async ({ request }) => {
requests.push({
body: await request.json(),
key: request.headers.get("Idempotency-Key"),
csrf: request.headers.get("X-CSRF-Token"),
});
return HttpResponse.json(
{
type: "urn:lincodex:problem:internal",
title: "Internal error",
status: 500,
code: "internal",
},
{ status: 500, headers: { "Content-Type": "application/problem+json" } },
);
}),
);
const keyFactory = vi.fn(() => "retry-key");
const firstBody = buildRootAttemptCreate("backend", "junior", ["python", "go"], "go");
const pending = preservePendingCreate(null, firstBody, keyFactory);
expect(pending).not.toBeNull();
await expect(submitPendingAttempt(pending!, "csrf-token")).rejects.toMatchObject({
status: 500,
});
const changedSelection = buildRootAttemptCreate(
"backend",
"junior",
["python", "go"],
"python",
);
const retry = preservePendingCreate(pending, changedSelection, keyFactory);
await expect(submitPendingAttempt(retry!, "csrf-token")).rejects.toMatchObject({
status: 500,
});
expect(requests).toEqual([
{
body: {
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
},
key: "retry-key",
csrf: "csrf-token",
},
{
body: {
kind: "root",
specialization: "backend",
target_grade: "junior",
task_language: "go",
},
key: "retry-key",
csrf: "csrf-token",
},
]);
expect(retry).toBe(pending);
expect(keyFactory).toHaveBeenCalledOnce();
});
});
describe("TaskLanguageControl", () => {
it("shows the single saved language without requiring another choice", () => {
const html = renderToStaticMarkup(
<TaskLanguageControl languages={["go"]} value="" disabled={false} onChange={() => {}} />,
);
expect(html).toContain("Язык задания из анкеты:");
expect(html).toContain("Go");
expect(html).not.toContain("<select");
});
it("requires a visible choice when both languages are saved", () => {
const html = renderToStaticMarkup(
<TaskLanguageControl
languages={["python", "go"]}
value="go"
disabled={false}
onChange={() => {}}
/>,
);
expect(html).toContain("Язык задания");
expect(html).toContain('value="python"');
expect(html).toContain('value="go" selected');
});
});
describe("AssessmentPolicyParameters", () => {
const grade = {
grade: "junior",
status: "active_attempt",
mode: "adaptive",
available_at: null,
time_limit_seconds: 900,
max_sessions: 1,
max_items: 12,
practice_required: true,
} as const;
it("does not present today's policy limits as settings for a pinned attempt", () => {
const html = renderToStaticMarkup(<AssessmentPolicyParameters grade={grade} />);
expect(html).toBe("");
});
it("shows current policy parameters before a new attempt", () => {
const html = renderToStaticMarkup(
<AssessmentPolicyParameters grade={{ ...grade, status: "available" }} />,
);
expect(html).toContain("Метод:");
expect(html).toContain("Лимит времени");
expect(html).toContain("Заданий");
});
});
@@ -0,0 +1,568 @@
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
import type {
AssessmentAttemptCreate,
AssessmentGradeAvailability,
GradeCode,
Session,
SpecializationCode,
TaskLanguage,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
} from "../../../shared/ui";
import {
assessmentSessionMatches,
gradeLabels,
isOutcomeAmbiguous,
isCurrentAssessmentSession,
methodLabel,
removeAssessmentQueries,
removeAssessmentQueriesForSessionChange,
selectedSpecialization,
specializationLabels,
useAssessmentAvailability,
useAssessmentQuestionnaire,
} from "../../../entities/assessment";
import { newIdempotencyKey } from "../../../features/answer-assessment";
import {
buildRootAttemptCreate,
preservePendingCreate,
submitPendingAttempt,
type PendingCreate,
} from "./assessment-page.model";
import styles from "./assessment-page.module.css";
function isAccessLoss(error: unknown): error is ApiRequestError {
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
}
function requiresC3(error: ApiRequestError): boolean {
return (
error.code === "state_conflict" &&
error.fieldErrors.some((field) => field.code === "consent_required")
);
}
function gradeStatusDescription(grade: AssessmentGradeAvailability): string {
switch (grade.status) {
case "available":
return "Уровень открыт для начала. Список доступности не разделяет варианты по языку; сервер проверит задания выбранного языка при создании попытки.";
case "active_attempt":
return "Продолжите сохраненную попытку по ссылке ниже. Ее язык и параметры закреплены и отображаются внутри попытки.";
case "cooldown":
return grade.available_at
? `Следующая попытка будет доступна ${formatDate(grade.available_at)}.`
: "Следующая попытка пока недоступна.";
case "insufficient_bank":
return "Набор заданий пока не подготовлен. Система не будет повторять уже пройденные задания.";
}
}
function formatDate(value: string): string {
return new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
}).format(new Date(value));
}
function formatTimeLimit(seconds: number | null): string {
if (seconds === null) return "не задано";
const minutes = Math.ceil(seconds / 60);
return `${minutes} мин.`;
}
function taskLanguageLabel(language: TaskLanguage): string {
return language === "go" ? "Go" : "Python";
}
export function TaskLanguageControl({
languages,
value,
disabled,
onChange,
}: {
languages: readonly TaskLanguage[];
value: TaskLanguage | "";
disabled: boolean;
onChange: (language: TaskLanguage | "") => void;
}) {
if (languages.length === 0) {
return (
<p className={styles["language-note"]}>
В сохраненной анкете нет выбранного языка. Попытка отправится без языка, а сервер проверит
доступность заданий при создании.
</p>
);
}
if (languages.length === 1) {
return (
<p className={styles["language-note"]}>
Язык задания из анкеты: <strong>{taskLanguageLabel(languages[0]!)}</strong>.
</p>
);
}
return (
<label className={styles.field}>
<span>Язык задания</span>
<select
value={value}
disabled={disabled}
onChange={(event) => onChange(event.currentTarget.value as TaskLanguage | "")}
>
<option value="">Выберите язык</option>
{languages.map((language) => (
<option key={language} value={language}>
{taskLanguageLabel(language)}
</option>
))}
</select>
</label>
);
}
export function AssessmentPolicyParameters({ grade }: { grade: AssessmentGradeAvailability }) {
if (grade.status === "active_attempt") return null;
return (
<>
{grade.mode ? <p>Метод: {methodLabel(grade.mode)}.</p> : null}
<dl className={styles.limits}>
<div>
<dt>Лимит времени</dt>
<dd>{formatTimeLimit(grade.time_limit_seconds)}</dd>
</div>
<div>
<dt>Попыток работы</dt>
<dd>{grade.max_sessions ?? "не задано"}</dd>
</div>
<div>
<dt>Заданий</dt>
<dd>{grade.max_items ?? "не задано"}</dd>
</div>
<div>
<dt>Практика кода</dt>
<dd>
{grade.practice_required === null
? "не задано"
: grade.practice_required
? "включена"
: "не требуется"}
</dd>
</div>
</dl>
</>
);
}
function AssessmentSignalsNotice() {
return (
<aside className={styles.notice} aria-labelledby="assessment-signals-title">
<h3 id="assessment-signals-title">Какие данные фиксируются во время проверки</h3>
<p>
Сохраняются время ответов и технические события: смена вкладки, выход из полноэкранного
режима и размер операций копирования или вставки. Содержимое ответов и буфера не
отправляется как сигнал. Камера, микрофон и запись экрана не используются.
</p>
<p>Сигналы помогают назначить ручную перепроверку и сами по себе не меняют результат.</p>
</aside>
);
}
export function AssessmentPage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.data;
const actorReady = Boolean(
actor &&
actor.account.scenario === "candidate" &&
isCurrentAssessmentSession(queryClient, actor),
);
const availability = useAssessmentAvailability({ actor, enabled: actorReady, queryClient });
const questionnaire = useAssessmentQuestionnaire({ actor, enabled: actorReady, queryClient });
const [selection, setSelection] = useState<{
specialization: SpecializationCode | "";
grade: GradeCode | "";
}>({ specialization: "", grade: "" });
const [selectedTaskLanguage, setSelectedTaskLanguage] = useState<TaskLanguage | "">("");
const [pendingCreate, setPendingCreate] = useState<PendingCreate | null>(null);
const [createBusy, setCreateBusy] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [c3Required, setC3Required] = useState(false);
const [accessDenied, setAccessDenied] = useState(false);
const previousActor = useRef<{ accountId: string; csrfToken: string } | null>(null);
const requestInFlight = useRef(false);
useEffect(() => {
const next =
actor && actorReady ? { accountId: actor.account.id, csrfToken: actor.csrf_token } : null;
const previous = previousActor.current;
if (previous && (!next || previous.accountId !== next.accountId)) {
removeAssessmentQueriesForSessionChange(queryClient);
setPendingCreate(null);
setSelectedTaskLanguage("");
setFormError(null);
setC3Required(false);
setAccessDenied(false);
} else if (previous && next && previous.csrfToken !== next.csrfToken) {
removeAssessmentQueriesForSessionChange(queryClient);
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
}
previousActor.current = next;
}, [actor, actorReady, queryClient]);
useEffect(() => {
if (
(availability.isError && isAccessLoss(availability.error)) ||
(questionnaire.isError && isAccessLoss(questionnaire.error))
) {
removeAssessmentQueries(queryClient);
queueMicrotask(() => {
if (isCurrentAssessmentSession(queryClient, actor)) setAccessDenied(true);
});
}
}, [
actor,
availability.error,
availability.isError,
queryClient,
questionnaire.error,
questionnaire.isError,
]);
const data = availability.data;
const firstSpecialization = data?.specializations[0]?.specialization ?? "";
const selectedCode = data?.specializations.some(
(item) => item.specialization === selection.specialization,
)
? selection.specialization
: firstSpecialization;
const specialization = data ? selectedSpecialization(data, selectedCode || undefined) : undefined;
const questionnaireSpecialization = questionnaire.data?.specializations.find(
(item) => item.specialization === selectedCode,
);
const selfGrade = questionnaireSpecialization?.self_assessed_grade ?? "";
const firstAvailableGrade =
specialization?.grades.find((grade) => grade.status === "available")?.grade ?? "";
const selectedGradeCode = specialization?.grades.some((grade) => grade.grade === selection.grade)
? selection.grade
: selfGrade || firstAvailableGrade || specialization?.grades[0]?.grade || "";
const grade = specialization?.grades.find((item) => item.grade === selectedGradeCode);
const activeAttemptId = specialization?.active_attempt_id;
const savedTaskLanguages = questionnaireSpecialization?.task_languages ?? [];
const selectedLanguageIsValid = savedTaskLanguages.includes(selectedTaskLanguage as TaskLanguage);
const taskLanguageReady = savedTaskLanguages.length < 2 || selectedLanguageIsValid;
async function refreshSessionForActor(currentActor: Session): Promise<boolean> {
const captured = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
if (
!assessmentSessionMatches(
queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey()),
currentActor,
)
) {
return false;
}
const refreshed = await session.refetch();
const latest = queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const queryState = queryClient.getQueryState<Session>(getGetCurrentSessionQueryKey());
if (
!captured ||
refreshed.isError ||
!refreshed.data ||
!latest ||
latest.account.id !== currentActor.account.id ||
latest.csrf_token !== refreshed.data.csrf_token ||
queryState?.status !== "success"
) {
if (refreshed.isError || refreshed.data?.account.id !== currentActor.account.id) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
}
return false;
}
if (captured.csrf_token !== currentActor.csrf_token) return false;
return true;
}
async function startAttempt(body?: AssessmentAttemptCreate) {
if (!actor || !isCurrentAssessmentSession(queryClient, actor) || requestInFlight.current)
return;
const command = preservePendingCreate(pendingCreate, body ?? null, newIdempotencyKey);
if (!command) return;
if (!pendingCreate) setPendingCreate(command);
requestInFlight.current = true;
setCreateBusy(true);
setFormError(null);
setC3Required(false);
try {
const created = await submitPendingAttempt(command, actor.csrf_token);
if (!isCurrentAssessmentSession(queryClient, actor)) return;
setPendingCreate(null);
navigate(paths.candidate.assessmentAttempt(created.id));
} catch (error: unknown) {
if (!isCurrentAssessmentSession(queryClient, actor)) return;
if (
error instanceof ApiRequestError &&
error.status === 403 &&
error.code === "csrf_check_failed"
) {
const refreshed = await refreshSessionForActor(actor);
if (refreshed) {
setFormError("Проверка входа обновлена. Повторите отправку теми же данными.");
}
return;
}
if (error instanceof ApiRequestError && [401, 403, 404].includes(error.status)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
return;
}
if (error instanceof ApiRequestError && error.status === 409) {
setPendingCreate(null);
if (requiresC3(error)) {
setC3Required(true);
setFormError("Для полной проверки нужно активное согласие C3.");
return;
}
setFormError("Доступность изменилась. Обновите состояние перед началом новой попытки.");
await availability.refetch();
return;
}
if (isOutcomeAmbiguous(error)) {
setFormError(
"Не удалось подтвердить создание попытки. Повторная отправка использует тот же ключ.",
);
} else {
setPendingCreate(null);
setFormError(
"Сервер отклонил создание попытки. Проверьте доступность и повторите действие.",
);
}
} finally {
requestInFlight.current = false;
setCreateBusy(false);
}
}
const handleStartReal = () => {
if (!specialization || !grade || !questionnaireSpecialization) return;
const body = buildRootAttemptCreate(
specialization.specialization,
grade.grade,
questionnaireSpecialization.task_languages,
selectedTaskLanguage,
);
if (!body) {
setFormError("Выберите язык задания перед началом проверки.");
return;
}
void startAttempt(body);
};
const handleStartExpress = () => {
void startAttempt({ kind: "demo_express" });
};
if (session.isError || accessDenied || (actor && actor.account.scenario !== "candidate")) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<ForbiddenState
error={session.error}
title="Проверка недоступна"
description="Войдите в кабинет кандидата и повторите проверку доступа."
action={<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>}
/>
</Page>
);
}
if (session.isPending || !actor) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (!actorReady) {
return (
<Page title="Проверка знаний" eyebrow="Кабинет кандидата">
<LoadingState label="Подтверждаем текущий вход..." />
</Page>
);
}
return (
<Page
title="Проверка знаний"
eyebrow="Кабинет кандидата"
lead="Выберите доступную проверку. Уровень из анкеты - это ваша самооценка; результат определяет только сервер после прохождения."
width="wide"
>
<div className={styles.layout}>
<Section
title="Доступность проверки"
description="Состояние и ограничения загружаются с сервера."
>
{(availability.isPending && !availability.data) ||
(questionnaire.isPending && !questionnaire.data) ? (
<LoadingState label="Загружаем доступность и сохраненные ответы..." />
) : !data || !questionnaire.data ? (
<ErrorState
error={!data ? availability.error : questionnaire.error}
isRetrying={!data ? availability.isRefetching : questionnaire.isRefetching}
onRetry={() => void (!data ? availability.refetch() : questionnaire.refetch())}
title="Не удалось загрузить состояние проверки"
/>
) : data.specializations.length === 0 ? (
<EmptyState
title="Сначала выберите специализацию"
description="Сохраните специализацию в анкете кандидата, чтобы увидеть доступные проверки."
action={<ButtonLink to={paths.candidate.questionnaire}>Открыть анкету</ButtonLink>}
/>
) : (
<>
<div className={styles.controls}>
<label className={styles.field}>
<span>Специализация</span>
<select
value={selectedCode}
disabled={Boolean(pendingCreate)}
onChange={(event) => {
setSelection({
specialization: event.currentTarget.value as SpecializationCode,
grade: "",
});
setSelectedTaskLanguage("");
}}
>
{data.specializations.map((item) => (
<option key={item.specialization} value={item.specialization}>
{specializationLabels[item.specialization]}
</option>
))}
</select>
</label>
<label className={styles.field}>
<span>Целевой уровень</span>
<select
value={selectedGradeCode}
disabled={Boolean(pendingCreate)}
onChange={(event) =>
setSelection({
specialization: selectedCode,
grade: event.currentTarget.value as GradeCode,
})
}
>
{specialization?.grades.map((item) => (
<option key={item.grade} value={item.grade}>
{gradeLabels[item.grade]}
</option>
))}
</select>
</label>
</div>
{questionnaireSpecialization && grade?.status !== "active_attempt" ? (
<TaskLanguageControl
languages={savedTaskLanguages}
value={selectedLanguageIsValid ? selectedTaskLanguage : ""}
disabled={Boolean(pendingCreate) || createBusy}
onChange={setSelectedTaskLanguage}
/>
) : null}
{grade?.status !== "active_attempt" ? (
<p className={styles["language-availability"]}>
Доступность уровня не зависит от выбранного языка. При создании сервер проверит,
опубликованы ли подходящие задания.
</p>
) : null}
{specialization && grade ? (
<div className={styles.availability}>
<div className={styles["status-row"]}>
<strong>{gradeLabels[grade.grade]}</strong>
<span data-state={grade.status}>
{grade.status === "available"
? "Доступна"
: grade.status === "active_attempt"
? "Есть попытка"
: grade.status === "cooldown"
? "Пауза"
: "Банк не готов"}
</span>
</div>
<p>{gradeStatusDescription(grade)}</p>
<AssessmentPolicyParameters grade={grade} />
{activeAttemptId && grade.status === "active_attempt" ? (
<ButtonLink to={paths.candidate.assessmentAttempt(activeAttemptId)}>
Продолжить текущую попытку
</ButtonLink>
) : grade.status === "available" ? (
<Button
isBusy={createBusy}
disabled={!taskLanguageReady}
onClick={() => {
if (taskLanguageReady) handleStartReal();
}}
>
{createBusy ? "Создаем попытку..." : "Начать полную проверку"}
</Button>
) : null}
</div>
) : null}
{pendingCreate ? (
<p className={styles.pending} role="status">
Данные отправки зафиксированы до подтверждения. Если связь прервалась, повторите
ее с тем же ключом.
</p>
) : null}
{formError ? (
<p className={styles.error} role="alert">
{formError}{" "}
{c3Required ? (
<ButtonLink to={paths.candidate.privacy}>Открыть согласие C3</ButtonLink>
) : null}
</p>
) : null}
</>
)}
<AssessmentSignalsNotice />
</Section>
<Section
title="Демонстрационный экспресс-запуск"
description="Отдельный учебный режим для знакомства с заданиями."
>
<div className={styles.express}>
<p>
Это демонстрация на 3-5 минут. Она не подтверждает квалификацию, не присваивает грейд
и не влияет на доступность полной проверки.
</p>
<Button
isBusy={createBusy}
disabled={Boolean(pendingCreate)}
onClick={handleStartExpress}
>
{createBusy ? "Создаем запуск..." : "Начать демонстрацию"}
</Button>
</div>
</Section>
</div>
</Page>
);
}
@@ -1,5 +1,6 @@
import { ConsentManagement } from "../../../features/consent-management";
import { Page } from "../../../shared/ui";
import { paths } from "../../../shared/config";
import { ButtonLink, Page, Section } from "../../../shared/ui";
export function ConsentsPage() {
return (
@@ -10,6 +11,15 @@ export function ConsentsPage() {
width="wide"
>
<ConsentManagement />
<Section title="Ручная оценка">
<p>
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
автоматическую оценку. Запрос не включает согласие обратно.
</p>
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
Запросить ручную оценку
</ButtonLink>
</Section>
</Page>
);
}
+1
View File
@@ -0,0 +1 @@
export { NeedEditorPage } from "./ui/need-editor-page";
@@ -0,0 +1,41 @@
.content {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.content [hidden] {
display: none;
}
.selector {
display: grid;
gap: var(--space-2);
max-width: 38rem;
}
.selector label {
font-weight: var(--font-weight-bold);
}
.selector select {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.selector select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
@@ -0,0 +1,398 @@
import { useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import {
getOrganizationNeed,
useGetOrganizationNeed,
} from "../../../shared/api/endpoints/need/need";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
import type { MyOrganizationList, Need, Session } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
} from "../../../shared/ui";
import {
activeNeedOrganizations,
isNeedSessionCurrent,
needQueryKeys,
removeAllNeedQueries,
removeNeedQueriesForOrganization,
removeNeedQueriesForSessionChange,
useNeedOrganizationDirectory,
} from "../../../entities/need";
import { NeedEditor } from "../../../features/edit-need";
import styles from "./need-editor-page.module.css";
const emptyDirectoryPages: readonly MyOrganizationList[] = [];
function isAccessLoss(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || error.status === 403 || error.status === 404)
);
}
function isOwnerContext(
queryClient: ReturnType<typeof useQueryClient>,
session: Session | undefined,
pages: readonly MyOrganizationList[],
organizationId: string,
): boolean {
if (!isNeedSessionCurrent(queryClient, session)) return false;
return activeNeedOrganizations(pages).some((item) => item.organization.id === organizationId);
}
export function NeedEditorPage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const { needId } = useParams();
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
const session = sessionQuery.data;
const accountId = session?.account.id;
const sessionReady =
Boolean(session && session.account.scenario === "employer") &&
isNeedSessionCurrent(queryClient, session);
const directory = useNeedOrganizationDirectory(session, sessionReady);
const directoryData = directory.data;
const directoryIsError = directory.isError;
const directoryIsFetching = directory.isFetching;
const directoryIsFetchingNextPage = directory.isFetchingNextPage;
const directoryIsLoading = directory.isLoading;
const hasMoreOwnerPages = directory.hasNextPage;
const fetchNextOwnerPage = directory.fetchNextPage;
const refetchDirectory = directory.refetch;
const [searchParams, setSearchParams] = useSearchParams();
const organizationId = searchParams.get("organization_id");
const [deniedOrganizationId, setDeniedOrganizationId] = useState<string | null>(null);
const reportedAccessError = useRef(false);
const previousSessionRef = useRef<{ accountId: string; csrfToken: string } | null>(null);
const pages = directoryData?.pages ?? emptyDirectoryPages;
const organizations = useMemo(() => activeNeedOrganizations(pages), [pages]);
const owner = organizations.find((item) => item.organization.id === organizationId);
const directoryRefreshing = directoryIsFetching && !directoryIsFetchingNextPage;
const directoryFresh =
sessionReady && Boolean(directoryData) && !directoryIsError && !directoryRefreshing;
const deniedKey = accountId && organizationId ? `${accountId}:${organizationId}` : null;
const denied = deniedOrganizationId !== null && deniedOrganizationId === deniedKey;
const membershipDenied =
Boolean(organizationId) && !owner && directoryFresh && !hasMoreOwnerPages;
const canReadNeed =
needId !== undefined &&
organizationId !== null &&
directoryFresh &&
owner !== undefined &&
!denied;
const needQuery = useGetOrganizationNeed(organizationId ?? "", needId ?? "", {
query: {
queryKey: needQueryKeys.detail(
accountId ?? "no-session",
organizationId ?? "no-organization",
needId ?? "new",
),
queryFn: async ({ signal }) => {
if (!isNeedSessionCurrent(queryClient, session)) {
throw new Error("The session changed before the need request.");
}
const result = await getOrganizationNeed(organizationId ?? "", needId ?? "", { signal });
if (!isNeedSessionCurrent(queryClient, session)) {
throw new Error("The session changed during the need request.");
}
return result;
},
enabled: canReadNeed,
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
retry: false,
},
});
useEffect(() => {
const next =
session && sessionReady
? { accountId: session.account.id, csrfToken: session.csrf_token }
: null;
const previous = previousSessionRef.current;
if (
previous &&
(!next || previous.accountId !== next.accountId || previous.csrfToken !== next.csrfToken)
) {
removeNeedQueriesForSessionChange(queryClient);
}
previousSessionRef.current = next;
}, [queryClient, session, sessionReady]);
useEffect(() => {
if (directoryIsError && isAccessLoss(directory.error)) {
removeAllNeedQueries(queryClient);
}
}, [directory.error, directoryIsError, queryClient]);
useEffect(() => {
if (!sessionReady || !directoryData || directoryIsError || directoryIsFetchingNextPage) return;
if (organizationId) {
if (!owner && hasMoreOwnerPages) void fetchNextOwnerPage();
return;
}
if (organizations[0]) {
const next = new URLSearchParams(searchParams);
next.set("organization_id", organizations[0].organization.id);
setSearchParams(next, { replace: true });
} else if (hasMoreOwnerPages) {
void fetchNextOwnerPage();
}
}, [
directoryData,
directoryIsError,
directoryIsFetchingNextPage,
fetchNextOwnerPage,
hasMoreOwnerPages,
organizations,
organizationId,
owner,
searchParams,
sessionReady,
setSearchParams,
]);
const markAccessLost = useCallback(
async (error: ApiRequestError, deniedOrganizationId: string | null) => {
if (
!isAccessLoss(error) ||
!deniedOrganizationId ||
!isNeedSessionCurrent(queryClient, session) ||
!accountId
)
return;
setDeniedOrganizationId(`${accountId}:${deniedOrganizationId}`);
removeNeedQueriesForOrganization(queryClient, deniedOrganizationId);
await refetchDirectory();
},
[accountId, queryClient, refetchDirectory, session, setDeniedOrganizationId],
);
useEffect(() => {
if (!needQuery.isError || !isAccessLoss(needQuery.error)) {
if (!needQuery.isError) reportedAccessError.current = false;
return;
}
if (reportedAccessError.current) return;
reportedAccessError.current = true;
void markAccessLost(needQuery.error, organizationId);
}, [markAccessLost, needQuery.error, needQuery.isError, organizationId]);
useEffect(() => {
if (!membershipDenied || !organizationId) return;
removeNeedQueriesForOrganization(queryClient, organizationId);
}, [membershipDenied, organizationId, queryClient]);
const isCurrentActor = useCallback(
() => isNeedSessionCurrent(queryClient, session),
[queryClient, session],
);
const persistCreated = useCallback(
async (saved: Need) => {
const refreshed = await refetchDirectory();
if (refreshed.isError) throw new Error("Could not confirm company access after saving.");
const refreshedPages = refreshed.data?.pages ?? [];
if (!isCurrentActor()) return;
if (!isOwnerContext(queryClient, session, refreshedPages, organizationId ?? "")) {
if (organizationId && accountId) setDeniedOrganizationId(`${accountId}:${organizationId}`);
if (organizationId) removeNeedQueriesForOrganization(queryClient, organizationId);
throw new Error("Owner access changed while saving the need.");
}
const key = needQueryKeys.detail(accountId ?? "no-session", organizationId ?? "", saved.id);
queryClient.setQueryData(key, saved);
navigate(paths.employer.need(saved.id, organizationId ?? ""), { replace: true });
},
[
accountId,
isCurrentActor,
navigate,
organizationId,
queryClient,
refetchDirectory,
session,
setDeniedOrganizationId,
],
);
const persistSaved = useCallback(
async (saved: Need) => {
const refreshed = await refetchDirectory();
if (refreshed.isError) throw new Error("Could not confirm company access after saving.");
const refreshedPages = refreshed.data?.pages ?? [];
if (!isCurrentActor()) return;
if (!isOwnerContext(queryClient, session, refreshedPages, organizationId ?? "")) {
if (organizationId && accountId) setDeniedOrganizationId(`${accountId}:${organizationId}`);
if (organizationId) removeNeedQueriesForOrganization(queryClient, organizationId);
throw new Error("Owner access changed while saving the need.");
}
queryClient.setQueryData(
needQueryKeys.detail(accountId ?? "no-session", organizationId ?? "", saved.id),
saved,
);
},
[
accountId,
isCurrentActor,
organizationId,
queryClient,
refetchDirectory,
session,
setDeniedOrganizationId,
],
);
const selectedOrganizationDenied = denied || membershipDenied;
const sessionFailure = sessionQuery.isError;
const directoryAccessFailure = directory.isError && isAccessLoss(directory.error);
const loading =
!sessionFailure &&
(!sessionReady ||
directoryIsLoading ||
directoryRefreshing ||
!directoryData ||
(!owner && hasMoreOwnerPages));
const title = needId ? "Потребность" : "Новая потребность";
return (
<Page
title={title}
eyebrow="Кабинет работодателя"
lead={
needId
? "Подтверждайте требования и следите за полнотой данных."
: "Опишите потребность команды без создания вакансии."
}
width="wide"
>
<div className={styles.content}>
{sessionFailure ? (
isAccessLoss(sessionQuery.error) ? (
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
) : (
<ErrorState
error={sessionQuery.error}
isRetrying={sessionQuery.isFetching}
onRetry={() => void sessionQuery.refetch()}
/>
)
) : null}
{directory.isError ? (
directoryAccessFailure ? (
<ForbiddenState error={directory.error} />
) : (
<ErrorState
error={directory.error}
isRetrying={directory.isFetching}
onRetry={() => void directory.refetch()}
/>
)
) : null}
{loading ? <LoadingState label="Проверяем компанию и загружаем потребность..." /> : null}
{!sessionFailure && !directory.isError && directory.data ? (
<>
{directoryRefreshing ? (
<LoadingState label="Повторно проверяем права владельца..." />
) : null}
{organizations.length > 1 ? (
<div className={styles.selector} hidden={!directoryFresh}>
<label htmlFor="need-editor-organization">Компания</label>
<select
id="need-editor-organization"
value={owner?.organization.id ?? ""}
onChange={(event) => {
const next = new URLSearchParams(searchParams);
next.set("organization_id", event.currentTarget.value);
reportedAccessError.current = false;
setDeniedOrganizationId(null);
setSearchParams(next);
}}
>
{!owner ? <option value="">Выберите компанию</option> : null}
{organizations.map((item) => (
<option key={item.organization.id} value={item.organization.id}>
{item.organization.name}
</option>
))}
</select>
</div>
) : null}
{selectedOrganizationDenied ? (
<ForbiddenState
title="Потребность недоступна"
description="Доступ владельца не подтвержден. Выберите компанию с активным членством владельца."
action={
<div className={styles.actions}>
{needId ? (
<ButtonLink to={paths.employer.needs}>К списку потребностей</ButtonLink>
) : null}
<Button variant="secondary" onClick={() => void directory.refetch()}>
Проверить доступ снова
</Button>
</div>
}
/>
) : null}
{!organizationId && organizations.length === 0 && !directory.hasNextPage ? (
<ForbiddenState
title="Нужны права владельца компании"
description="Потребностями в этой версии может управлять только владелец компании."
action={
<ButtonLink to={paths.employer.company}>Открыть профиль компании</ButtonLink>
}
/>
) : null}
{owner && !selectedOrganizationDenied ? (
<Section title={needId ? "Редактирование" : "Создание потребности"}>
{needId && needQuery.isError && isAccessLoss(needQuery.error) ? (
<ForbiddenState
title="Потребность недоступна"
description="Проверьте права владельца и выбранную компанию."
/>
) : null}
{needId && needQuery.isError && !isAccessLoss(needQuery.error) ? (
<ErrorState
error={needQuery.error}
isRetrying={needQuery.isFetching}
onRetry={() => void needQuery.refetch()}
/>
) : null}
{needId && needQuery.isLoading ? (
<LoadingState label="Загружаем данные потребности..." />
) : null}
{needId && needQuery.data && needQuery.isFetching ? (
<LoadingState label="Проверяем, что доступ владельца действует..." />
) : null}
<div hidden={!directoryFresh || needQuery.isFetching || needQuery.isError}>
{(!needId || needQuery.data) && !needQuery.isError ? (
<NeedEditor
key={`${accountId ?? "no-session"}:${organizationId}:${needId ?? "new"}`}
accountId={accountId ?? "no-session"}
organizationId={organizationId ?? ""}
session={session!}
need={needQuery.data}
onCreated={persistCreated}
onSaved={persistSaved}
onAccessLost={(error) => void markAccessLost(error, organizationId)}
/>
) : null}
</div>
</Section>
) : null}
</>
) : null}
</div>
</Page>
);
}
+1
View File
@@ -0,0 +1 @@
export { NeedListPage } from "./ui/need-list-page";
@@ -0,0 +1,139 @@
.content {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: end;
justify-content: space-between;
margin-block-end: var(--space-5);
}
.selector {
display: grid;
gap: var(--space-2);
min-width: min(100%, 20rem);
}
.selector label {
font-weight: var(--font-weight-bold);
}
.selector select {
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.selector select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.list {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.card {
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);
}
.card-heading {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: baseline;
justify-content: space-between;
}
.card-heading h3 {
margin: 0;
overflow-wrap: anywhere;
font-size: var(--font-size-l);
}
.complete,
.incomplete {
max-width: 100%;
overflow-wrap: anywhere;
font-size: var(--font-size-s);
font-weight: var(--font-weight-bold);
}
.complete {
color: var(--color-text-secondary);
}
.incomplete {
color: var(--color-text);
}
.facts {
display: grid;
grid-template-columns: minmax(8rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
}
.facts dt {
color: var(--color-text-secondary);
}
.facts dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.missing {
display: grid;
gap: var(--space-2);
margin: 0;
padding-inline-start: var(--space-5);
}
.load-more {
display: flex;
justify-content: center;
margin-block-start: var(--space-4);
}
@media (width < 30rem) {
.toolbar {
align-items: stretch;
flex-direction: column;
}
.toolbar > a {
width: fit-content;
}
.facts {
grid-template-columns: minmax(0, 1fr);
}
.facts dd + dt {
padding-block-start: var(--space-2);
}
.card {
padding: var(--space-3);
}
}
@@ -0,0 +1,407 @@
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { listOrganizationNeeds } from "../../../shared/api/endpoints/need/need";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { ApiRequestError } from "../../../shared/api";
import type { MyOrganizationList, NeedList } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config/paths";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
} from "../../../shared/ui";
import {
activeNeedOrganizations,
isNeedSessionCurrent,
needListPageSize,
needQueryKeys,
removeAllNeedQueries,
removeNeedQueriesForOrganization,
removeNeedQueriesForSessionChange,
useNeedOrganizationDirectory,
} from "../../../entities/need";
import styles from "./need-list-page.module.css";
type NeedSummary = NeedList["items"][number];
const emptyDirectoryPages: readonly MyOrganizationList[] = [];
const specializationLabels: Readonly<Record<string, string>> = {
backend: "Backend",
frontend: "Frontend",
mobile: "Мобильная разработка",
network_engineer: "Сетевые технологии",
devops_sre: "DevOps/SRE",
data_analyst: "Аналитика данных",
ds_ml: "DS/ML",
information_security: "Информационная безопасность",
qa: "QA",
};
const gradeLabels: Readonly<Record<string, string>> = {
intern: "Стажер",
junior: "Junior",
middle: "Middle",
senior: "Senior",
};
function isAccessLoss(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || error.status === 403 || error.status === 404)
);
}
function displayDecision<T extends string>(
state: { status: "confirmed" | "extracted" | "unknown"; value: T | null },
labels: Readonly<Record<string, string>>,
): string {
if (state.status === "unknown" || state.value === null) return "Не указано";
const label = labels[state.value] ?? state.value;
return state.status === "extracted" ? `Предложено: ${label}` : label;
}
function NeedCard({ item, organizationId }: { item: NeedSummary; organizationId: string }) {
const missingCount = item.readiness.missing_fields.length;
return (
<article className={styles.card}>
<div className={styles["card-heading"]}>
<h3>{item.title}</h3>
<span
className={item.readiness.status === "complete" ? styles.complete : styles.incomplete}
>
{item.readiness.status === "complete"
? "Данные заполнены"
: `Не хватает данных: ${missingCount}`}
</span>
</div>
<dl className={styles.facts}>
<dt>Специализация</dt>
<dd>{displayDecision(item.specialization, specializationLabels)}</dd>
<dt>Грейд</dt>
<dd>{displayDecision(item.grade, gradeLabels)}</dd>
<dt>Версия</dt>
<dd>{item.version}</dd>
</dl>
{missingCount > 0 ? (
<ul className={styles.missing}>
{item.readiness.missing_fields.map((field) => (
<li key={field.field}>{field.question}</li>
))}
</ul>
) : null}
<ButtonLink to={paths.employer.need(item.id, organizationId)} variant="secondary">
Открыть потребность
</ButtonLink>
</article>
);
}
export function NeedListPage() {
const queryClient = useQueryClient();
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
const session = sessionQuery.data;
const accountId = session?.account.id;
const sessionReady =
Boolean(session && session.account.scenario === "employer") &&
isNeedSessionCurrent(queryClient, session);
const directory = useNeedOrganizationDirectory(session, sessionReady);
const directoryData = directory.data;
const directoryIsError = directory.isError;
const directoryError = directory.error;
const directoryIsFetching = directory.isFetching;
const directoryIsFetchingNextPage = directory.isFetchingNextPage;
const directoryIsLoading = directory.isLoading;
const hasMoreOrganizations = directory.hasNextPage;
const fetchNextOrganizationPage = directory.fetchNextPage;
const refetchDirectory = directory.refetch;
const [searchParams, setSearchParams] = useSearchParams();
const selectedOrganizationId = searchParams.get("organization_id");
const [deniedContext, setDeniedContext] = useState<string | null>(null);
const reportedAccessError = useRef(false);
const previousSessionRef = useRef<{ accountId: string; csrfToken: string } | null>(null);
const pages = directoryData?.pages ?? emptyDirectoryPages;
const organizations = useMemo(() => activeNeedOrganizations(pages), [pages]);
const selectedOrganization = organizations.find(
(item) => item.organization.id === selectedOrganizationId,
);
const directoryRefreshing = directoryIsFetching && !directoryIsFetchingNextPage;
const directoryFresh =
sessionReady && Boolean(directoryData) && !directoryIsError && !directoryRefreshing;
const deniedKey =
accountId && selectedOrganizationId ? `${accountId}:${selectedOrganizationId}` : null;
const denied = deniedContext !== null && deniedContext === deniedKey;
const membershipDenied =
Boolean(selectedOrganizationId) &&
!selectedOrganization &&
directoryFresh &&
!hasMoreOrganizations;
useEffect(() => {
const next =
session && sessionReady
? { accountId: session.account.id, csrfToken: session.csrf_token }
: null;
const previous = previousSessionRef.current;
if (
previous &&
(!next || previous.accountId !== next.accountId || previous.csrfToken !== next.csrfToken)
) {
removeNeedQueriesForSessionChange(queryClient);
}
previousSessionRef.current = next;
}, [queryClient, session, sessionReady]);
useEffect(() => {
if (directoryIsError && isAccessLoss(directoryError)) {
removeAllNeedQueries(queryClient);
}
}, [directoryError, directoryIsError, queryClient]);
useEffect(() => {
if (!sessionReady || !directoryData || directoryIsError || directoryIsFetchingNextPage) return;
if (selectedOrganizationId) {
if (!selectedOrganization && hasMoreOrganizations) void fetchNextOrganizationPage();
return;
}
if (organizations[0]) {
setSearchParams({ organization_id: organizations[0].organization.id }, { replace: true });
} else if (hasMoreOrganizations) {
void fetchNextOrganizationPage();
}
}, [
directoryData,
directoryIsError,
directoryIsFetchingNextPage,
fetchNextOrganizationPage,
hasMoreOrganizations,
organizations,
selectedOrganization,
selectedOrganizationId,
sessionReady,
setSearchParams,
]);
const needs = useInfiniteQuery({
queryKey: needQueryKeys.list(
accountId ?? "no-session",
selectedOrganizationId ?? "no-organization",
),
initialPageParam: undefined as string | undefined,
queryFn: async ({ pageParam, signal }) => {
if (!isNeedSessionCurrent(queryClient, session))
throw new Error("The session changed before the need-list request.");
const result = await listOrganizationNeeds(
selectedOrganizationId ?? "",
{ limit: needListPageSize, ...(pageParam ? { cursor: pageParam } : {}) },
{ signal },
);
if (!isNeedSessionCurrent(queryClient, session))
throw new Error("The session changed during the need-list request.");
return result;
},
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
enabled: directoryFresh && selectedOrganization !== undefined && !denied && !membershipDenied,
gcTime: 0,
staleTime: 0,
refetchOnMount: "always",
refetchOnWindowFocus: "always",
retry: false,
});
const handleAccessLoss = useCallback(
async (error: ApiRequestError, deniedOrganizationId: string | null) => {
if (
!isAccessLoss(error) ||
!deniedOrganizationId ||
!isNeedSessionCurrent(queryClient, session)
)
return;
if (!accountId) return;
setDeniedContext(`${accountId}:${deniedOrganizationId}`);
removeNeedQueriesForOrganization(queryClient, deniedOrganizationId);
await refetchDirectory();
},
[accountId, queryClient, refetchDirectory, session, setDeniedContext],
);
useEffect(() => {
if (!needs.isError || !isAccessLoss(needs.error)) {
if (!needs.isError) reportedAccessError.current = false;
return;
}
if (reportedAccessError.current) return;
reportedAccessError.current = true;
void handleAccessLoss(needs.error, selectedOrganizationId);
}, [handleAccessLoss, needs.error, needs.isError, selectedOrganizationId]);
useEffect(() => {
if (!membershipDenied || !selectedOrganizationId) return;
removeNeedQueriesForOrganization(queryClient, selectedOrganizationId);
}, [membershipDenied, queryClient, selectedOrganizationId]);
const listItems = needs.data?.pages.flatMap((page) => page.items) ?? [];
const hasAccessError = sessionQuery.isError || directoryIsError;
const loading =
!sessionQuery.isError &&
(!sessionReady ||
directoryIsLoading ||
directoryRefreshing ||
!directoryData ||
(!selectedOrganization && hasMoreOrganizations));
return (
<Page
title="Потребности"
eyebrow="Кабинет работодателя"
lead="Описывайте потребности команды, подтверждайте предложения из текста и проверяйте готовность данных."
width="wide"
>
{sessionQuery.isError ? (
isAccessLoss(sessionQuery.error) ? (
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
) : (
<ErrorState
error={sessionQuery.error}
isRetrying={sessionQuery.isFetching}
onRetry={() => void sessionQuery.refetch()}
/>
)
) : null}
{directoryIsError ? (
isAccessLoss(directoryError) ? (
<ForbiddenState error={directoryError} />
) : (
<ErrorState
error={directoryError}
isRetrying={directoryIsFetching}
onRetry={() => void refetchDirectory()}
/>
)
) : null}
{loading ? <LoadingState label="Проверяем компанию и загружаем потребности..." /> : null}
{!hasAccessError && directoryData && directoryFresh ? (
<div className={styles.content}>
{organizations.length > 0 ? (
<Section title="Список потребностей">
<div className={styles.toolbar}>
<div className={styles.selector}>
<label htmlFor="need-organization">Компания</label>
<select
id="need-organization"
value={selectedOrganization?.organization.id ?? ""}
onChange={(event) => {
const next = new URLSearchParams(searchParams);
next.set("organization_id", event.currentTarget.value);
setDeniedContext(null);
reportedAccessError.current = false;
setSearchParams(next);
}}
>
{!selectedOrganization ? <option value="">Выберите компанию</option> : null}
{organizations.map((item) => (
<option key={item.organization.id} value={item.organization.id}>
{item.organization.name}
</option>
))}
</select>
</div>
{selectedOrganization ? (
<ButtonLink to={paths.employer.needNew(selectedOrganization.organization.id)}>
Создать потребность
</ButtonLink>
) : null}
</div>
{denied || membershipDenied ? (
<ForbiddenState
title="Потребности компании недоступны"
description="Доступ владельца не подтвержден. Выберите компанию с активным членством владельца."
action={
<Button
variant="secondary"
onClick={() => {
setDeniedContext(null);
reportedAccessError.current = false;
void refetchDirectory();
}}
>
Проверить доступ снова
</Button>
}
/>
) : null}
{needs.isError && !isAccessLoss(needs.error) ? (
<ErrorState
error={needs.error}
isRetrying={needs.isFetching}
onRetry={() => void needs.refetch()}
/>
) : null}
{needs.isLoading ? <LoadingState label="Загружаем потребности..." /> : null}
{needs.data && !needs.isError && !denied && !membershipDenied ? (
listItems.length === 0 ? (
<EmptyState
title="Потребностей пока нет"
description="Создайте первую потребность. Связанная вакансия для этого не нужна."
action={
selectedOrganization ? (
<ButtonLink
to={paths.employer.needNew(selectedOrganization.organization.id)}
>
Создать потребность
</ButtonLink>
) : null
}
/>
) : (
<div className={styles.list}>
{listItems.map((item) => (
<NeedCard
key={item.id}
item={item}
organizationId={selectedOrganizationId ?? ""}
/>
))}
</div>
)
) : null}
{needs.hasNextPage && !denied && !membershipDenied ? (
<div className={styles["load-more"]}>
<Button
variant="secondary"
isBusy={needs.isFetchingNextPage}
onClick={() => void needs.fetchNextPage()}
>
{needs.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
</Button>
</div>
) : null}
</Section>
) : (
<ForbiddenState
title="Нужны права владельца компании"
description="Потребностями в этой версии может управлять только владелец."
/>
)}
{hasMoreOrganizations ? (
<div className={styles["load-more"]}>
<Button
variant="secondary"
isBusy={directoryIsFetchingNextPage}
onClick={() => void fetchNextOrganizationPage()}
>
{directoryIsFetchingNextPage ? "Загружаем компании..." : "Показать еще компании"}
</Button>
</div>
) : null}
</div>
) : null}
</Page>
);
}
@@ -0,0 +1,6 @@
export {
CreateSupportCasePage,
ManualAssessmentPage,
SupportCaseDetailPage,
SupportCasesPage,
} from "./ui/support-cases-pages";
@@ -0,0 +1,119 @@
.root {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-4);
}
.case-list {
display: grid;
gap: var(--space-4);
}
.case-card,
.event,
.decision {
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.card-heading,
.event-heading {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: var(--space-2) var(--space-4);
}
.card-heading h3,
.event-heading h3,
.decision h3 {
margin: 0;
font-size: var(--font-size-l);
}
.card-heading > span {
padding: var(--space-1) var(--space-2);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-pill);
font-size: var(--font-size-s);
font-weight: var(--font-weight-bold);
}
.case-card p,
.event p,
.decision p {
margin: var(--space-3) 0 0;
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.target,
.date,
.event-heading time {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.more {
margin-top: var(--space-4);
}
.facts {
display: grid;
grid-template-columns: minmax(9rem, 0.45fr) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
}
.facts dt {
color: var(--color-text-secondary);
}
.facts dd {
margin: 0;
overflow-wrap: anywhere;
}
.description,
.message {
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.history {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.event-heading time {
white-space: normal;
}
@media (width <= 40rem) {
.actions > * {
width: 100%;
}
.facts {
grid-template-columns: minmax(0, 1fr);
gap: var(--space-1);
}
.facts dd + dt {
margin-top: var(--space-3);
}
}
@@ -0,0 +1,548 @@
import { useEffect } from "react";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import {
formatSupportDate,
isSupportSessionAccessError,
supportCaseActorLabels,
supportCaseDetailQueryKey,
supportCaseEventKindLabels,
supportCaseListQueryKey,
supportCasePathFor,
supportCaseStatusLabels,
supportCaseTypeLabels,
supportSessionMatches,
supportTargetDescription,
} from "../../../entities/support-case";
import { CreateSupportCase } from "../../../features/create-support-case";
import { RequestManualAssessment } from "../../../features/request-manual-assessment";
import { ApiRequestError } from "../../../shared/api";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import {
getMySupportCase,
listMySupportCases,
} from "../../../shared/api/endpoints/support/support";
import type { Session, SupportCase } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
Button,
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
LoadingState,
Page,
Section,
TextLink,
} from "../../../shared/ui";
import styles from "./support-cases-pages.module.css";
const supportCasePageSize = 20;
const caseIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function isCaseAccessError(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || error.status === 403 || error.status === 404)
);
}
function sessionErrorState(error: unknown, onRetry: () => void, isRetrying: boolean) {
if (isSupportSessionAccessError(error)) {
return (
<ForbiddenState
error={error}
title="Войдите, чтобы открыть обращения"
description="После входа поддержка откроется для вашего аккаунта."
action={
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
Войти в поддержку
</ButtonLink>
}
/>
);
}
return (
<ErrorState
error={error}
title="Не удалось проверить вход"
isRetrying={isRetrying}
onRetry={onRetry}
/>
);
}
function removeSupportAccountCache(
queryClient: ReturnType<typeof useQueryClient>,
accountId: string,
) {
queryClient.removeQueries({
predicate: (query) =>
query.queryKey[0] === "account" &&
query.queryKey[1] === accountId &&
query.queryKey[2] === "support-cases",
});
}
function supportLandingPath(session: Session): string {
return session.account.scenario === "candidate"
? paths.candidate.supportCases
: paths.employer.supportCases;
}
export function SupportCasesPage() {
const queryClient = useQueryClient();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.isSuccess ? session.data : null;
const knownActor =
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const list = useInfiniteQuery({
queryKey: actor
? supportCaseListQueryKey(actor.account.id)
: ["account", "anonymous", "support-cases", "list"],
queryFn: async ({ pageParam, signal }) => {
if (
!actor ||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
) {
throw new Error("The active account changed before support history was loaded.");
}
const result = await listMySupportCases(
pageParam
? { limit: supportCasePageSize, cursor: pageParam }
: { limit: supportCasePageSize },
{ signal },
);
if (
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
) {
throw new Error("The active account changed while support history was loading.");
}
return result;
},
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
enabled: Boolean(actor),
staleTime: 0,
gcTime: 0,
refetchOnMount: "always",
retry: false,
});
const listAccessError = list.isError && isCaseAccessError(list.error) ? list.error : null;
useEffect(() => {
const accountId = actor?.account.id ?? knownActor?.account.id;
if (!accountId || (!isSupportSessionAccessError(session.error) && !listAccessError)) {
return;
}
removeSupportAccountCache(queryClient, accountId);
}, [actor, knownActor, listAccessError, queryClient, session.error]);
if (session.isPending && !session.data) {
return (
<Page title="Мои обращения">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (session.isError) {
return (
<Page title="Мои обращения">
{sessionErrorState(session.error, () => void session.refetch(), session.isRefetching)}
</Page>
);
}
if (!actor || (actor.account.scenario !== "candidate" && actor.account.scenario !== "employer")) {
return (
<Page title="Мои обращения">
<ForbiddenState title="Поддержка недоступна" />
</Page>
);
}
if (listAccessError) {
return (
<Page title="Мои обращения">
<ForbiddenState
error={listAccessError}
title="Обращения недоступны"
description="Сервер не подтвердил доступ к истории этого аккаунта."
action={
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
Обновить вход
</ButtonLink>
}
/>
</Page>
);
}
if (list.isPending && !list.data) {
return (
<Page title="Мои обращения">
<LoadingState label="Загружаем историю обращений..." />
</Page>
);
}
if (list.isError && !list.data) {
return (
<Page title="Мои обращения">
<ErrorState
error={list.error}
title="Не удалось загрузить обращения"
isRetrying={list.isRefetching}
onRetry={() => void list.refetch()}
/>
</Page>
);
}
const cases = list.data?.pages.flatMap((page) => page.items) ?? [];
return (
<Page
title="Мои обращения"
eyebrow={
actor.account.scenario === "candidate" ? "Кабинет кандидата" : "Кабинет работодателя"
}
lead="Здесь хранятся обращения этого аккаунта и ответы поддержки."
width="wide"
>
<div className={styles.root}>
<Section title="Новый запрос">
<div className={styles.actions}>
<ButtonLink
to={
actor.account.scenario === "candidate"
? paths.candidate.supportNew
: paths.employer.supportNew
}
>
Написать в поддержку
</ButtonLink>
{actor.account.scenario === "candidate" ? (
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
Запросить ручную оценку
</ButtonLink>
) : null}
</div>
</Section>
<Section title="История">
{list.isError ? (
<ErrorState
error={list.error}
title="Не удалось обновить историю"
isRetrying={list.isRefetching}
onRetry={() => void list.refetch()}
/>
) : null}
{cases.length === 0 ? (
<EmptyState
title="Обращений пока нет"
description="После отправки новое дело появится здесь и останется доступным после повторного входа."
action={
<ButtonLink
to={
actor.account.scenario === "candidate"
? paths.candidate.supportNew
: paths.employer.supportNew
}
>
Создать обращение
</ButtonLink>
}
/>
) : (
<div className={styles["case-list"]}>
{cases.map((supportCase) => (
<SupportCaseSummaryCard
key={supportCase.id}
supportCase={supportCase}
href={supportCasePathFor(actor, supportCase.id)}
/>
))}
</div>
)}
{list.hasNextPage ? (
<div className={styles.more}>
<Button
variant="secondary"
isBusy={list.isFetchingNextPage}
onClick={() => void list.fetchNextPage()}
>
{list.isFetchingNextPage ? "Загружаем..." : "Показать более ранние обращения"}
</Button>
</div>
) : null}
</Section>
</div>
</Page>
);
}
function SupportCaseSummaryCard({
supportCase,
href,
}: {
supportCase: {
id: string;
number: string;
type: SupportCase["type"];
status: SupportCase["status"];
response_target: SupportCase["response_target"];
created_at: string;
};
href: string;
}) {
return (
<article className={styles["case-card"]}>
<div className={styles["card-heading"]}>
<h3>
<TextLink to={href}>{supportCase.number}</TextLink>
</h3>
<span>{supportCaseStatusLabels[supportCase.status]}</span>
</div>
<p>{supportCaseTypeLabels[supportCase.type]}</p>
<p className={styles.target}>{supportTargetDescription(supportCase.response_target)}</p>
<p className={styles.date}>Создано {formatSupportDate(supportCase.created_at)}</p>
</article>
);
}
export function CreateSupportCasePage() {
return (
<Page
title="Обратиться в поддержку"
eyebrow="Мои обращения"
lead="Отправьте вопрос или сообщите о проблеме."
width="wide"
>
<CreateSupportCase />
</Page>
);
}
export function ManualAssessmentPage() {
return (
<Page
title="Запросить ручную оценку"
eyebrow="Поддержка"
lead="Выберите категорию и расскажите, что важно учесть эксперту."
width="wide"
>
<RequestManualAssessment />
</Page>
);
}
export function SupportCaseDetailPage() {
const queryClient = useQueryClient();
const { caseId = "" } = useParams();
const session = useGetCurrentSession({ query: { retry: false } });
const actor = session.isSuccess ? session.data : null;
const knownActor =
session.data ?? queryClient.getQueryData<Session>(getGetCurrentSessionQueryKey());
const validId = caseIdPattern.test(caseId);
const details = useQuery({
queryKey:
actor && validId
? supportCaseDetailQueryKey(actor.account.id, caseId)
: ["account", "anonymous", "support-cases", "detail", caseId],
queryFn: async ({ signal }) => {
if (
!actor ||
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
) {
throw new Error("The active account changed before the support request was loaded.");
}
const result = await getMySupportCase(caseId, { signal });
if (
!supportSessionMatches(queryClient.getQueryState(getGetCurrentSessionQueryKey()), actor)
) {
throw new Error("The active account changed while the support request was loading.");
}
return result;
},
enabled: Boolean(actor && validId),
staleTime: 0,
gcTime: 0,
refetchOnMount: "always",
retry: false,
});
const detailsAccessError =
details.isError && isCaseAccessError(details.error) ? details.error : null;
useEffect(() => {
const accountId = actor?.account.id ?? knownActor?.account.id;
if (!accountId || (!isSupportSessionAccessError(session.error) && !detailsAccessError)) {
return;
}
removeSupportAccountCache(queryClient, accountId);
}, [actor, detailsAccessError, knownActor, queryClient, session.error]);
if (session.isPending && !session.data) {
return (
<Page title="Обращение">
<LoadingState label="Проверяем вход..." />
</Page>
);
}
if (session.isError) {
return (
<Page title="Обращение">
{sessionErrorState(session.error, () => void session.refetch(), session.isRefetching)}
</Page>
);
}
if (!actor)
return (
<Page title="Обращение">
<ForbiddenState title="Войдите, чтобы открыть обращение" />
</Page>
);
if (!validId) {
return (
<Page title="Обращение не найдено">
<EmptyState
title="Обращение не найдено или недоступно"
description="Проверьте ссылку или вернитесь к истории своего аккаунта."
action={<ButtonLink to={supportLandingPath(actor)}>Мои обращения</ButtonLink>}
/>
</Page>
);
}
if (detailsAccessError) {
if (detailsAccessError.status === 404) {
return (
<Page title="Обращение не найдено">
<EmptyState
title="Обращение не найдено или недоступно"
description="Ссылка не дает доступ к истории другого аккаунта."
action={<ButtonLink to={supportLandingPath(actor)}>Мои обращения</ButtonLink>}
/>
</Page>
);
}
return (
<Page title="Обращение недоступно">
<ForbiddenState
error={detailsAccessError}
title="Обращение недоступно"
description="Сервер не подтвердил доступ к этой истории."
action={
<ButtonLink to={paths.login} state={{ returnTo: "support" }}>
Обновить вход
</ButtonLink>
}
/>
</Page>
);
}
if (details.isPending && !details.data) {
return (
<Page title="Обращение">
<LoadingState label="Загружаем обращение..." />
</Page>
);
}
if (details.isError && !details.data) {
return (
<Page title="Не удалось открыть обращение">
<ErrorState
error={details.error}
title="Не удалось загрузить обращение"
isRetrying={details.isRefetching}
onRetry={() => void details.refetch()}
/>
</Page>
);
}
if (!details.data)
return (
<Page title="Обращение">
<LoadingState label="Загружаем обращение..." />
</Page>
);
return (
<Page
title={details.data.number}
eyebrow="Мои обращения"
lead={supportCaseTypeLabels[details.data.type]}
width="wide"
>
<SupportCaseDetails supportCase={details.data} session={actor} />
</Page>
);
}
function SupportCaseDetails({
supportCase,
session,
}: {
supportCase: SupportCase;
session: Session;
}) {
return (
<div className={styles.root}>
<Section title="Состояние">
<dl className={styles.facts}>
<dt>Номер</dt>
<dd>{supportCase.number}</dd>
<dt>Статус</dt>
<dd>{supportCaseStatusLabels[supportCase.status]}</dd>
<dt>Создано</dt>
<dd>{formatSupportDate(supportCase.created_at)}</dd>
<dt>Операционная цель</dt>
<dd>{supportTargetDescription(supportCase.response_target)}</dd>
{supportCase.assessment_target ? (
<>
<dt>Специальность</dt>
<dd>{supportCase.assessment_target.specialization}</dd>
<dt>Желаемый грейд</dt>
<dd>{supportCase.assessment_target.grade}</dd>
</>
) : null}
{supportCase.type === "manual_assessment" ? (
<>
<dt>Рубрика</dt>
<dd>
{supportCase.rubric_version === null
? "Опубликованной рубрики для этой категории пока нет. Запрос ожидает эксперта; автоматическая оценка не выполнялась."
: `Зафиксирована версия ${supportCase.rubric_version}. Запрос ожидает эксперта.`}
</dd>
</>
) : null}
</dl>
<p className={styles.description}>{supportCase.description}</p>
{supportCase.decision ? (
<div className={styles.decision}>
<h3>Решение</h3>
<p>{supportCase.decision.reason}</p>
</div>
) : null}
</Section>
<Section title="История">
<ol className={styles.history}>
{supportCase.history.map((event) => (
<li key={event.sequence} className={styles.event}>
<div className={styles["event-heading"]}>
<h3>{supportCaseEventKindLabels[event.kind]}</h3>
<time dateTime={event.occurred_at}>{formatSupportDate(event.occurred_at)}</time>
</div>
<p>{supportCaseActorLabels[event.actor]}</p>
{event.status ? <p>Статус: {supportCaseStatusLabels[event.status]}</p> : null}
{event.message ? <p className={styles.message}>{event.message}</p> : null}
</li>
))}
</ol>
</Section>
<div className={styles.actions}>
<ButtonLink to={supportLandingPath(session)} variant="secondary">
Мои обращения
</ButtonLink>
</div>
</div>
);
}
+44
View File
@@ -138,6 +138,50 @@ describe("apiRequest", () => {
});
});
it("retains a valid Retry-After integer without retaining response headers", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ code: "rate_limited" }), {
status: 429,
headers: {
"content-type": "application/problem+json",
"retry-after": "17",
},
}),
),
);
const caught: unknown = await apiRequest("/healthz").catch((error: unknown) => error);
expect(caught).toBeInstanceOf(ApiRequestError);
expect(caught).toMatchObject({ status: 429, retryAfterSeconds: 17 });
expect(caught).not.toHaveProperty("headers");
});
it.each([undefined, "", "1.5", "-1", "Wed, 21 Oct 2015 07:28:00 GMT", "9007199254740992"])(
"omits invalid or missing Retry-After value %s",
async (retryAfter) => {
const headers: Record<string, string> = { "content-type": "application/problem+json" };
if (retryAfter !== undefined) {
headers["retry-after"] = retryAfter;
}
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ code: "rate_limited" }), { status: 429, headers }),
),
);
await expect(apiRequest("/healthz")).rejects.toMatchObject({
status: 429,
retryAfterSeconds: undefined,
});
},
);
it.each([
{
name: "a JSON body that is not a problem",
+15
View File
@@ -27,6 +27,7 @@ type ApiRequestErrorInit = {
detail?: string | undefined;
traceId?: string | undefined;
fieldErrors?: readonly ProblemFieldError[] | undefined;
retryAfterSeconds?: number | undefined;
};
/**
@@ -40,6 +41,7 @@ export class ApiRequestError extends Error {
readonly detail: string | undefined;
readonly traceId: string | undefined;
readonly fieldErrors: readonly ProblemFieldError[];
readonly retryAfterSeconds: number | undefined;
constructor(init: ApiRequestErrorInit) {
super(init.detail ?? init.title);
@@ -50,6 +52,7 @@ export class ApiRequestError extends Error {
this.detail = init.detail;
this.traceId = init.traceId;
this.fieldErrors = init.fieldErrors ?? [];
this.retryAfterSeconds = init.retryAfterSeconds;
}
}
@@ -94,8 +97,18 @@ function isProblemResponse(response: Response): boolean {
return mediaType === problemMediaType;
}
function retryAfterSeconds(response: Response): number | undefined {
const value = response.headers.get("retry-after");
if (value === null || !/^\d+$/.test(value)) {
return undefined;
}
const seconds = Number(value);
return Number.isSafeInteger(seconds) ? seconds : undefined;
}
async function toApiError(response: Response): Promise<ApiRequestError> {
const headerTraceId = response.headers.get(requestIdHeader) ?? undefined;
const retryAfter = retryAfterSeconds(response);
if (isProblemResponse(response)) {
const body: unknown = await response.json().catch(() => undefined);
@@ -109,6 +122,7 @@ async function toApiError(response: Response): Promise<ApiRequestError> {
detail: problem.detail,
traceId: problem.trace_id ?? headerTraceId,
fieldErrors: problem.errors,
retryAfterSeconds: retryAfter,
});
}
}
@@ -118,6 +132,7 @@ async function toApiError(response: Response): Promise<ApiRequestError> {
code: unknownErrorCode,
title: `Request failed with status ${response.status}.`,
traceId: headerTraceId,
retryAfterSeconds: retryAfter,
});
}
@@ -32,6 +32,7 @@ import type {
AssessmentQualifiedResult,
AssessmentResult,
AssessmentSessions,
AssessmentSignalReceipt,
AssessmentUncertainty,
BasicScore,
ChoiceItemContent,
@@ -131,6 +132,8 @@ export const getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptM
export const getStartMyAssessmentAttemptSessionResponseMock = (): AssessmentAttempt => (faker.helpers.arrayElement([{...getStartMyAssessmentAttemptSessionResponseAssessmentQualifiedAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentCorrectiveAttemptMock()},{...getStartMyAssessmentAttemptSessionResponseAssessmentExpressAttemptMock()},]))
export const getRecordMyAssessmentAttemptSignalsResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalReceipt, object>> = {}): AssessmentSignalReceipt => ({status: faker.helpers.arrayElement(['accepted','saturated'] as const), accepted_events: faker.number.int({min: 0, max: 50}), received_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
@@ -248,6 +251,18 @@ export const getStartMyAssessmentAttemptSessionMockHandler = (overrideResponse?:
}, options)
}
export const getRecordMyAssessmentAttemptSignalsMockHandler = (overrideResponse?: AssessmentSignalReceipt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentSignalReceipt> | AssessmentSignalReceipt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts/:attemptId/signals', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getRecordMyAssessmentAttemptSignalsResponseMock(),
{ status: 200
})
}, options)
}
export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
@@ -288,6 +303,7 @@ export const getAssessmentMock = () => [
getCreateMyAssessmentAttemptMockHandler(),
getGetMyAssessmentAttemptMockHandler(),
getStartMyAssessmentAttemptSessionMockHandler(),
getRecordMyAssessmentAttemptSignalsMockHandler(),
getSubmitMyAssessmentAnswerMockHandler(),
getFinalizeMyAssessmentAttemptMockHandler(),
getGetMyAssessmentResultMockHandler()
@@ -30,10 +30,14 @@ import type {
AssessmentAttemptSessionStart,
AssessmentAvailability,
AssessmentFinalization,
AssessmentFinalizeConflictProblem,
AssessmentResult,
AssessmentSignalBatch,
AssessmentSignalReceipt,
CreateMyAssessmentAttemptHeaders,
FinalizeMyAssessmentAttemptHeaders,
Problem,
RecordMyAssessmentAttemptSignalsHeaders,
StartMyAssessmentAttemptSessionHeaders,
SubmitMyAssessmentAnswerHeaders
} from '../../schemas';
@@ -464,6 +468,100 @@ export const useStartMyAssessmentAttemptSession = <TError = ErrorType<Problem>,
> => {
return useMutation(getStartMyAssessmentAttemptSessionMutationOptions(options), queryClient);
}
export const getRecordMyAssessmentAttemptSignalsUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/signals`
}
/**
* Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt, remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks every item_instance_id against that attempt, and commits the receipt and any events in one transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express remains a separate training mode and receives no signal storage or grade effect.
*
* The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents, arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers. Client timestamps must be within five minutes before attempt creation and five minutes after the database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed with the assessment attempt or account; this release does not promise an independent expiry schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
*
* A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt without storing another batch; using that key with another body answers 422.
* @summary Store a bounded batch of client-reported assessment signals.
*/
export const recordMyAssessmentAttemptSignals = async (attemptId: string,
assessmentSignalBatch: AssessmentSignalBatch,
headers: RecordMyAssessmentAttemptSignalsHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentSignalReceipt> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentSignalReceipt>(getRecordMyAssessmentAttemptSignalsUrl(attemptId),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(assessmentSignalBatch)
}
);}
export const getRecordMyAssessmentAttemptSignalsMutationKey = () => ['recordMyAssessmentAttemptSignals'] as const;
export const getRecordMyAssessmentAttemptSignalsMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, TError,RecordMyAssessmentAttemptSignalsMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, TError,RecordMyAssessmentAttemptSignalsMutationVariables, TContext> => {
const mutationKey = getRecordMyAssessmentAttemptSignalsMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, RecordMyAssessmentAttemptSignalsMutationVariables> = (props) => {
const {attemptId,data,headers} = props ?? {};
return recordMyAssessmentAttemptSignals(attemptId,data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type RecordMyAssessmentAttemptSignalsMutationResult = NonNullable<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>>
export type RecordMyAssessmentAttemptSignalsMutationBody = AssessmentSignalBatch
export type RecordMyAssessmentAttemptSignalsMutationError = ErrorType<Problem>
export type RecordMyAssessmentAttemptSignalsMutationVariables = {attemptId: string;data: AssessmentSignalBatch;headers: RecordMyAssessmentAttemptSignalsHeaders}
/**
* @summary Store a bounded batch of client-reported assessment signals.
*/
export const useRecordMyAssessmentAttemptSignals = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>, TError,RecordMyAssessmentAttemptSignalsMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof recordMyAssessmentAttemptSignals>>,
TError,
RecordMyAssessmentAttemptSignalsMutationVariables,
TContext
> => {
return useMutation(getRecordMyAssessmentAttemptSignalsMutationOptions(options), queryClient);
}
export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => {
@@ -590,7 +688,7 @@ export const useSubmitMyAssessmentAnswer = <TError = ErrorType<Problem>,
*
* A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it.
*
* An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
* An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not.
* @summary Ask for the grade decision of an assessment attempt.
@@ -628,7 +726,7 @@ return apiRequest<AssessmentAttempt>(getFinalizeMyAssessmentAttemptUrl(attemptId
export const getFinalizeMyAssessmentAttemptMutationKey = () => ['finalizeMyAssessmentAttempt'] as const;
export const getFinalizeMyAssessmentAttemptMutationOptions = <TError = ErrorType<Problem>,
export const getFinalizeMyAssessmentAttemptMutationOptions = <TError = ErrorType<Problem | AssessmentFinalizeConflictProblem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext> => {
@@ -657,13 +755,13 @@ const {mutation: mutationOptions, request: requestOptions} = options ?
export type FinalizeMyAssessmentAttemptMutationResult = NonNullable<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>>
export type FinalizeMyAssessmentAttemptMutationBody = AssessmentFinalization
export type FinalizeMyAssessmentAttemptMutationError = ErrorType<Problem>
export type FinalizeMyAssessmentAttemptMutationError = ErrorType<Problem | AssessmentFinalizeConflictProblem>
export type FinalizeMyAssessmentAttemptMutationVariables = {attemptId: string;data: AssessmentFinalization;headers: FinalizeMyAssessmentAttemptHeaders}
/**
* @summary Ask for the grade decision of an assessment attempt.
*/
export const useFinalizeMyAssessmentAttempt = <TError = ErrorType<Problem>,
export const useFinalizeMyAssessmentAttempt = <TError = ErrorType<Problem | AssessmentFinalizeConflictProblem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>, TError,FinalizeMyAssessmentAttemptMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof finalizeMyAssessmentAttempt>>,
@@ -37,7 +37,7 @@ import type {
export const getListOrganizationInvitationsResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
export const getListOrganizationInvitationsResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitationList, object>> = {}): OrganizationInvitationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getListOrganizationInvitationsResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getListOrganizationInvitationsResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitationList, object>> = {}): OrganizationInvitationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getListOrganizationInvitationsResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getCreateOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
@@ -45,7 +45,7 @@ export const getCreateOrganizationInvitationResponseInvitationPackageItemProvide
export const getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getCreateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getCreateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getCreateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getCreateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getGetOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
@@ -53,7 +53,7 @@ export const getGetOrganizationInvitationResponseInvitationPackageItemProvidedMo
export const getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getGetOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getGetOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getGetOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getGetOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
@@ -61,7 +61,7 @@ export const getUpdateOrganizationInvitationResponseInvitationPackageItemProvide
export const getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getUpdateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getUpdateOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getUpdateOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getUpdateOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getSendOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
@@ -69,7 +69,7 @@ export const getSendOrganizationInvitationResponseInvitationPackageItemProvidedM
export const getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getSendOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getSendOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getSendOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getSendOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
@@ -77,7 +77,7 @@ export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemPr
export const getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getRaiseOrganizationInvitationSalaryResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getRaiseOrganizationInvitationSalaryResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemProvidedMock()},{...getRaiseOrganizationInvitationSalaryResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock = (overrideResponse: Partial<InvitationNeedReference> = {}): InvitationNeedReference => ({...{need_id: faker.string.uuid(), requirements_version: faker.number.int({min: 1})}, ...overrideResponse});
@@ -85,7 +85,7 @@ export const getWithdrawOrganizationInvitationResponseInvitationPackageItemProvi
export const getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock = (overrideResponse: Partial<InvitationPackageItemNotProvided> = {}): InvitationPackageItemNotProvided => ({...{status: faker.helpers.arrayElement(['not_provided'] as const)}, ...overrideResponse});
export const getWithdrawOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 128}), need: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getWithdrawOrganizationInvitationResponseMock = (overrideResponse: Partial<Extract<OrganizationInvitation, object>> = {}): OrganizationInvitation => ({id: faker.string.uuid(), organization_id: faker.string.uuid(), candidate_handle: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), need: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationNeedReferenceMock()},null,]), state: faker.helpers.arrayElement(['draft','delivered','viewed','counter','accepted','interview_scheduled','interviewed','negotiation','terms_agreed','no_deal','declined','expired','withdrawn','cancelled_by_candidate'] as const), expiry_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['invitation_timeout','negotiation_timeout'] as const),null,]), version: faker.number.int({min: 1}), terms_version: faker.number.int({min: 1}), terms: {role_title: fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}), specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), offer_type: faker.helpers.arrayElement(['full_time','part_time','contract','internship'] as const), tasks: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}))), team: fakeFromPattern("\\S", {minLength: 1, maxLength: 1000}), tech_stack: Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}))), work_formats: faker.helpers.arrayElements(['remote','office','hybrid'] as const), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}),null,]), communication_method: {channel: faker.helpers.arrayElement(['email','phone','telegram','video_call'] as const), details: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 300}),null,])}, salary: {salary_from: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), salary_to: faker.number.int({min: 1000, max: 100000000, multipleOf: 1000}), currency: faker.helpers.arrayElement(['RUB'] as const), period: faker.helpers.arrayElement(['month'] as const), tax_basis: faker.helpers.arrayElement(['net','gross'] as const)}, package: {bonus: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), equipment: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), training: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},]), health_insurance: faker.helpers.arrayElement([{...getWithdrawOrganizationInvitationResponseInvitationPackageItemProvidedMock()},{...getWithdrawOrganizationInvitationResponseInvitationPackageItemNotProvidedMock()},])}}, response_period_days: faker.helpers.arrayElement([3,7,14] as const), response_deadline_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), salary_raise_used: faker.datatype.boolean(), salary_fit: faker.helpers.arrayElement(['within_range','up_to_10_percent_above','above','withheld','not_available'] as const), contact_access: {status: faker.helpers.arrayElement(['not_granted','available','closed'] as const), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const)}, created_at: faker.date.past().toISOString().slice(0, 19) + 'Z', updated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', delivered_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), viewed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), responded_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), ...overrideResponse})
export const getGetOrganizationInvitationContactsResponseMock = (overrideResponse: Partial<Extract<ContactDisclosure, object>> = {}): ContactDisclosure => ({invitation_id: faker.string.uuid(), grant_id: faker.string.uuid(), fields: faker.helpers.arrayElements(['full_name','email','phone','telegram'] as const), granted_at: faker.date.past().toISOString().slice(0, 19) + 'Z', full_name: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 200}),null,]), email: faker.helpers.arrayElement([faker.internet.email(),null,]), phone: faker.helpers.arrayElement([fakeFromPattern("^\\+[1-9][0-9]{6,14}$", {minLength: 8, maxLength: 16}),null,]), telegram: faker.helpers.arrayElement([fakeFromPattern("^@[A-Za-z0-9_]{5,32}$", {minLength: 6, maxLength: 33}),null,]), ...overrideResponse})
@@ -34,13 +34,15 @@ import type {
} from '../../schemas';
export const getGetMyPrivacySettingsResponseMock = (overrideResponse: Partial<Extract<PrivacySettings, object>> = {}): PrivacySettings => ({publication: {state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, search_status: {value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, hidden_organizations_total: faker.number.int({min: 0, max: 1000}), ...overrideResponse})
export const getGetOrganizationCandidateCardResponseMock = (overrideResponse: Partial<Extract<AnonymousCardContent, object>> = {}): AnonymousCardContent => ({pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,]), ...overrideResponse})
export const getSetMyPublicationResponseMock = (overrideResponse: Partial<Extract<Publication, object>> = {}): Publication => ({state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
export const getGetMyPrivacySettingsResponseMock = (overrideResponse: Partial<Extract<PrivacySettings, object>> = {}): PrivacySettings => ({publication: {state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, search_status: {value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, hidden_organizations_total: faker.number.int({min: 0, max: 1000}), ...overrideResponse})
export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial<AnonymousCardContent> = {}): AnonymousCardContent => ({...{categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)})), null]), stack: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), null]), experience_months: faker.helpers.arrayElement([faker.number.int({min: 0, max: 1200}), null]), soft_skills: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), null]), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), null]), relocation: faker.helpers.arrayElement([faker.datatype.boolean(), null])}, ...overrideResponse});
export const getSetMyPublicationResponseMock = (overrideResponse: Partial<Extract<Publication, object>> = {}): Publication => ({state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial<Extract<CardPreview, object>> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial<AnonymousCardContent> = {}): AnonymousCardContent => ({...{pseudonym: fakeFromPattern("^cv1_[A-Za-z0-9_-]{43}$", {minLength: 47, maxLength: 47}), categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const), strength: faker.helpers.arrayElement(['standard','strong'] as const)})), null]), stack: faker.helpers.arrayElement([faker.helpers.arrayElements(['go','postgresql','kafka','docker'] as const), null]), self_assessment: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), confirmation_status: faker.helpers.arrayElement(['confirmed','unconfirmed'] as const), declared_grade: faker.helpers.arrayElement([faker.helpers.arrayElement(['intern','junior','middle','senior'] as const),null,])})), null]), experience_band: faker.helpers.arrayElement([faker.helpers.arrayElement(['0_1','1_3','3_6','6_plus','0_3','3_plus'] as const),null,]), work_formats: faker.helpers.arrayElement([faker.helpers.arrayElements(['remote','office','hybrid'] as const), null]), salary_compatibility: faker.helpers.arrayElement([faker.helpers.arrayElement(['compatible','not_compatible'] as const),null,])}, ...overrideResponse});
export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial<Extract<CardPreview, object>> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getSetMySearchStatusResponseMock = (overrideResponse: Partial<Extract<SearchStatus, object>> = {}): SearchStatus => ({value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse})
@@ -50,13 +52,25 @@ export const getHideOrganizationResponseMock = (overrideResponse: Partial<Extrac
export const getListMyPrivacyHistoryResponsePrivacyOrganizationMock = (overrideResponse: Partial<PrivacyOrganization> = {}): PrivacyOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse});
export const getListMyPrivacyHistoryResponseMock = (overrideResponse: Partial<Extract<PrivacyEventList, object>> = {}): PrivacyEventList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['publication_opened','publication_changed','publication_closed','search_status_confirmed','search_status_cleared','organization_hidden','organization_unhidden'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const),null,]), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), organization: faker.helpers.arrayElement([{...getListMyPrivacyHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getListMyPrivacyHistoryResponseMock = (overrideResponse: Partial<Extract<PrivacyEventList, object>> = {}): PrivacyEventList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['publication_opened','publication_changed','publication_closed','search_status_confirmed','search_status_cleared','organization_hidden','organization_unhidden'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['categories','salary_compatibility','self_assessment','stack','experience','soft_skills','location','relocation','work_formats'] as const),null,]), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), organization: faker.helpers.arrayElement([{...getListMyPrivacyHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getListMyCardAccessHistoryResponsePrivacyOrganizationMock = (overrideResponse: Partial<PrivacyOrganization> = {}): PrivacyOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse});
export const getListMyCardAccessHistoryResponseMock = (overrideResponse: Partial<Extract<CardAccessList, object>> = {}): CardAccessList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['card_viewed','contact_read'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', organization: faker.helpers.arrayElement([{...getListMyCardAccessHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse})
export const getGetOrganizationCandidateCardMockHandler = (overrideResponse?: AnonymousCardContent | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<AnonymousCardContent> | AnonymousCardContent), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/organizations/:orgId/candidate-cards/:candidateHandle', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getGetOrganizationCandidateCardResponseMock(),
{ status: 200
})
}, options)
}
export const getGetMyPrivacySettingsMockHandler = (overrideResponse?: PrivacySettings | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<PrivacySettings> | PrivacySettings), options?: RequestHandlerOptions) => {
return http.get('*/api/v1/me/privacy', async (info: Parameters<Parameters<typeof http.get>[1]>[0]) => {
@@ -163,6 +177,7 @@ export const getListMyCardAccessHistoryMockHandler = (overrideResponse?: CardAcc
}, options)
}
export const getPrivacyMock = () => [
getGetOrganizationCandidateCardMockHandler(),
getGetMyPrivacySettingsMockHandler(),
getSetMyPublicationMockHandler(),
getGetMyCardPreviewMockHandler(),
@@ -24,6 +24,7 @@ import type {
} from '@tanstack/react-query';
import type {
AnonymousCardContent,
CardAccessList,
CardPreview,
HiddenOrganization,
@@ -63,6 +64,123 @@ const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKe
return result;
};
export const getGetOrganizationCandidateCardUrl = (orgId: string,
candidateHandle: string,) => {
return `/api/v1/organizations/${orgId}/candidate-cards/${candidateHandle}`
}
/**
* Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data.
*
* `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server resolves it against the current visible cohort, rechecks active membership, effective C2 publication, and the candidate's hiding settings on every request, and applies the cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle, a handle from another organization, a closed or revoked publication, a profile hidden from this organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
*
* The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever available, are a separate operation and require the current explicit C4 grant and contact-access policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks this read immediately. Republishing does not reopen an earlier contact grant.
*
* Every allowed employer card read is recorded in the access history and consumes the organization's current product-policy card-view quota. A repeated view within the quota window is allowed by the existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed.
* @summary Read one currently visible anonymous candidate card.
*/
export const getOrganizationCandidateCard = async (orgId: string,
candidateHandle: string, options?: Parameters<typeof apiRequest>[1]): Promise<AnonymousCardContent> => {
return apiRequest<AnonymousCardContent>(getGetOrganizationCandidateCardUrl(orgId,candidateHandle),
{
...options,
method: 'GET'
}
);}
export const getGetOrganizationCandidateCardQueryKey = (orgId: string,
candidateHandle: string,) => {
return [
`/api/v1/organizations/${orgId}/candidate-cards/${candidateHandle}`
] as const;
}
export const getGetOrganizationCandidateCardQueryOptions = <TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(orgId: string,
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetOrganizationCandidateCardQueryKey(orgId,candidateHandle);
const queryFn: QueryFunction<Awaited<ReturnType<typeof getOrganizationCandidateCard>>> = ({ signal }) => getOrganizationCandidateCard(orgId,candidateHandle, { signal, ...requestOptions });
return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined && candidateHandle !== null && candidateHandle !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetOrganizationCandidateCardQueryResult = NonNullable<Awaited<ReturnType<typeof getOrganizationCandidateCard>>>
export type GetOrganizationCandidateCardQueryError = ErrorType<Problem>
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
orgId: string,
candidateHandle: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getOrganizationCandidateCard>>,
TError,
Awaited<ReturnType<typeof getOrganizationCandidateCard>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
orgId: string,
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getOrganizationCandidateCard>>,
TError,
Awaited<ReturnType<typeof getOrganizationCandidateCard>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
orgId: string,
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read one currently visible anonymous candidate card.
*/
export function useGetOrganizationCandidateCard<TData = Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError = ErrorType<Problem>>(
orgId: string,
candidateHandle: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganizationCandidateCard>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetOrganizationCandidateCardQueryOptions(orgId,candidateHandle,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getGetMyPrivacySettingsUrl = () => {
@@ -273,9 +391,11 @@ export const useSetMyPublication = <TError = ErrorType<Problem>,
}
/**
* Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`.
* Requires the session cookie of a candidate account. Returns a private preview of the permitted anonymous-card fields from the current profile, publication, and consent ledger. The response is `Cache-Control: no-store`.
*
* The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results.
* The preview creates no view or access record and is never shown to an organization. While the profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an organization's pseudonym. Organization-specific visibility filters and cohort checks can further generalize or suppress the card when an organization reads it.
*
* `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden.
* @summary Preview the anonymous card that organizations would read.
@@ -590,7 +710,7 @@ export const getHideOrganizationUrl = (orgId: string,) => {
*
* The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization.
*
* Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
* Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate may name an organization in their own card-access history or an existing hidden-organization record. Invitation visibility will be added with the invitation workflow, and a candidate lookup remains planned. The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it.
*
* A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit.
*
@@ -869,9 +989,9 @@ export const getListMyCardAccessHistoryUrl = (params?: ListMyCardAccessHistoryPa
/**
* Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
*
* An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card.
* An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A retained access record permits the candidate to see the organization's identifier and current name and to hide their profile from it. The nullable organization field is preserved for records whose organization cannot be presented. The entries carry no employee identity, search query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does not erase earlier permitted accesses from the history.
*
* The storage of accesses is planned with the card and contact operations of the organization side (anonymous card reads and contact reads under the invitation contract); until then the operation answers 501 not_implemented after the session and request checks.
* Successful organization card reads are recorded transactionally with the visibility and quota checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an accepted workflow status alone never authorizes contact access.
*
* A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
* @summary List the accesses of organizations to the card of the current candidate.
@@ -62,7 +62,7 @@ const terms = {
} as const;
const draft = {
candidate_handle: "cand_7Qm2xVb9Lr4Kp0Zt",
candidate_handle: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
need: { need_id: "01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12", requirements_version: 3 },
response_period_days: 7,
terms,
@@ -294,7 +294,7 @@ it("parses an accepted invitation of the organization without contact values", (
const parsed = OrganizationInvitation.parse({
id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f",
organization_id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
candidate_handle: "cand_7Qm2xVb9Lr4Kp0Zt",
candidate_handle: "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
need: null,
state: "accepted",
expiry_reason: null,
@@ -135,7 +135,15 @@ describe("generated PublicationUpdate", () => {
expected_version: number;
state: "closed" | "published";
fields: Array<
"categories" | "stack" | "experience" | "soft_skills" | "location" | "relocation"
| "categories"
| "stack"
| "experience"
| "soft_skills"
| "location"
| "relocation"
| "self_assessment"
| "work_formats"
| "salary_compatibility"
>;
}>();
});
@@ -205,23 +213,31 @@ describe("generated HiddenOrganization", () => {
describe("generated AnonymousCardContent", () => {
const card = {
categories: [{ specialization: "backend", grade: "middle" }],
stack: ["PostgreSQL", "Kafka"],
experience_months: null,
soft_skills: null,
location: null,
relocation: null,
pseudonym: `cv1_${"a".repeat(43)}`,
categories: [{ specialization: "backend", grade: "middle", strength: "standard" }],
stack: ["postgresql", "kafka"],
self_assessment: [
{
specialization: "network_engineer",
confirmation_status: "unconfirmed",
declared_grade: "junior",
},
],
experience_band: "1_3",
work_formats: null,
salary_compatibility: null,
};
it("holds only the closed set of card properties and reads an unpublished one as null", () => {
expect(AnonymousCardContent.parse(card)).toEqual(card);
expect(Object.keys(AnonymousCardContent.shape).sort()).toEqual([
"categories",
"experience_months",
"location",
"relocation",
"soft_skills",
"experience_band",
"pseudonym",
"salary_compatibility",
"self_assessment",
"stack",
"work_formats",
]);
});
@@ -251,7 +267,7 @@ describe("generated AnonymousCardContent", () => {
expect(
CardPreview.parse({ ...closed, state: "published", fields: ["stack"], card }),
).toMatchObject({
card: { stack: ["PostgreSQL", "Kafka"] },
card: { stack: ["postgresql", "kafka"] },
});
});
});
@@ -0,0 +1,21 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentClipboardSignalSizeBytesMin = 0;
export const assessmentClipboardSignalSizeBytesMax = 2147483647;
export const AssessmentClipboardSignal = zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(assessmentClipboardSignalSizeBytesMin).max(assessmentClipboardSignalSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
})
export type AssessmentClipboardSignal = zod.input<typeof AssessmentClipboardSignal>;
export type AssessmentClipboardSignalOutput = zod.output<typeof AssessmentClipboardSignal>;
@@ -0,0 +1,54 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentFinalizeConflictProblemTypeMax = 256;
export const assessmentFinalizeConflictProblemTitleMax = 200;
export const assessmentFinalizeConflictProblemDetailMax = 1000;
export const assessmentFinalizeConflictProblemInstanceMax = 2048;
export const assessmentFinalizeConflictProblemTraceIdMax = 128;
export const assessmentFinalizeConflictProblemTraceIdRegExp = new RegExp('^[A-Za-z0-9._-]+$');
export const assessmentFinalizeConflictProblemErrorsItemPointerMax = 1024;
export const assessmentFinalizeConflictProblemErrorsItemPointerRegExp = new RegExp('^(/([^~/]|~[01])*)*$');
export const assessmentFinalizeConflictProblemErrorsItemCodeMax = 64;
export const assessmentFinalizeConflictProblemErrorsItemCodeRegExp = new RegExp('^[a-z][a-z0-9_]*$');
export const assessmentFinalizeConflictProblemErrorsItemMessageMax = 500;
export const assessmentFinalizeConflictProblemErrorsMax = 100;
export const assessmentFinalizeConflictProblemPendingItemIdsMax = 220;
export const AssessmentFinalizeConflictProblem = zod.object({
"type": zod.string().max(assessmentFinalizeConflictProblemTypeMax),
"title": zod.string().min(1).max(assessmentFinalizeConflictProblemTitleMax),
"status": zod.literal(409),
"code": zod.enum(['state_conflict', 'idempotency_in_progress']),
"detail": zod.string().max(assessmentFinalizeConflictProblemDetailMax).exactOptional(),
"instance": zod.string().max(assessmentFinalizeConflictProblemInstanceMax).exactOptional(),
"trace_id": zod.string().min(1).max(assessmentFinalizeConflictProblemTraceIdMax).regex(assessmentFinalizeConflictProblemTraceIdRegExp).exactOptional(),
"errors": zod.array(zod.object({
"in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'),
"pointer": zod.string().max(assessmentFinalizeConflictProblemErrorsItemPointerMax).regex(assessmentFinalizeConflictProblemErrorsItemPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'),
"code": zod.string().min(1).max(assessmentFinalizeConflictProblemErrorsItemCodeMax).regex(assessmentFinalizeConflictProblemErrorsItemCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values.'),
"message": zod.string().min(1).max(assessmentFinalizeConflictProblemErrorsItemMessageMax).describe('Fixed English message that never echoes the submitted value.')
}).describe('One reason why a request field or parameter is invalid.')).max(assessmentFinalizeConflictProblemErrorsMax).exactOptional(),
"pending_item_ids": zod.array(zod.uuid()).max(assessmentFinalizeConflictProblemPendingItemIdsMax).exactOptional().describe('Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items.')
}).describe('A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts.')
export type AssessmentFinalizeConflictProblem = zod.input<typeof AssessmentFinalizeConflictProblem>;
export type AssessmentFinalizeConflictProblemOutput = zod.output<typeof AssessmentFinalizeConflictProblem>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentFocusLossSignalDurationMsMax = 259200000;
export const AssessmentFocusLossSignal = zod.object({
"kind": zod.enum(['focus_loss']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"duration_ms": zod.int().min(1).max(assessmentFocusLossSignalDurationMsMax).describe('Client-measured duration away from the assessment tab or window, in milliseconds.')
})
export type AssessmentFocusLossSignal = zod.input<typeof AssessmentFocusLossSignal>;
export type AssessmentFocusLossSignalOutput = zod.output<typeof AssessmentFocusLossSignal>;
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const AssessmentFullscreenExitSignal = zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})
export type AssessmentFullscreenExitSignal = zod.input<typeof AssessmentFullscreenExitSignal>;
export type AssessmentFullscreenExitSignalOutput = zod.output<typeof AssessmentFullscreenExitSignal>;
@@ -0,0 +1,36 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSignalBatchEventsItemOneDurationMsMax = 259200000;
export const assessmentSignalBatchEventsItemTwoSizeBytesMin = 0;
export const assessmentSignalBatchEventsItemTwoSizeBytesMax = 2147483647;
export const assessmentSignalBatchEventsMax = 50;
export const AssessmentSignalBatch = zod.object({
"events": zod.array(zod.union([zod.object({
"kind": zod.enum(['focus_loss']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"duration_ms": zod.int().min(1).max(assessmentSignalBatchEventsItemOneDurationMsMax).describe('Client-measured duration away from the assessment tab or window, in milliseconds.')
}),zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(assessmentSignalBatchEventsItemTwoSizeBytesMin).max(assessmentSignalBatchEventsItemTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
}),zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(assessmentSignalBatchEventsMax)
}).describe('A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.')
export type AssessmentSignalBatch = zod.input<typeof AssessmentSignalBatch>;
export type AssessmentSignalBatchOutput = zod.output<typeof AssessmentSignalBatch>;
@@ -0,0 +1,32 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSignalEventOneDurationMsMax = 259200000;
export const assessmentSignalEventTwoSizeBytesMin = 0;
export const assessmentSignalEventTwoSizeBytesMax = 2147483647;
export const AssessmentSignalEvent = zod.union([zod.object({
"kind": zod.enum(['focus_loss']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"duration_ms": zod.int().min(1).max(assessmentSignalEventOneDurationMsMax).describe('Client-measured duration away from the assessment tab or window, in milliseconds.')
}),zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(assessmentSignalEventTwoSizeBytesMin).max(assessmentSignalEventTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
}),zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')
export type AssessmentSignalEvent = zod.input<typeof AssessmentSignalEvent>;
export type AssessmentSignalEventOutput = zod.output<typeof AssessmentSignalEvent>;
@@ -0,0 +1,20 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const assessmentSignalReceiptAcceptedEventsMin = 0;
export const assessmentSignalReceiptAcceptedEventsMax = 50;
export const AssessmentSignalReceipt = zod.object({
"status": zod.enum(['accepted', 'saturated']).describe('`saturated` means no event from this batch was stored because the attempt\'s bounded evidence storage is full.'),
"accepted_events": zod.int().min(assessmentSignalReceiptAcceptedEventsMin).max(assessmentSignalReceiptAcceptedEventsMax).describe('Number of events stored from this batch; zero when saturated.'),
"received_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band.')
export type AssessmentSignalReceipt = zod.input<typeof AssessmentSignalReceipt>;
export type AssessmentSignalReceiptOutput = zod.output<typeof AssessmentSignalReceipt>;
@@ -15,6 +15,7 @@ export * from './assessmentAttemptSessionStart.zod';
export * from './assessmentAttemptState.zod';
export * from './assessmentAttemptVersion.zod';
export * from './assessmentAvailability.zod';
export * from './assessmentClipboardSignal.zod';
export * from './assessmentCorrectiveAttempt.zod';
export * from './assessmentCorrectiveAttemptCreate.zod';
export * from './assessmentCorrectiveResult.zod';
@@ -23,6 +24,9 @@ export * from './assessmentExpressAttempt.zod';
export * from './assessmentExpressAttemptCreate.zod';
export * from './assessmentExpressResult.zod';
export * from './assessmentFinalization.zod';
export * from './assessmentFinalizeConflictProblem.zod';
export * from './assessmentFocusLossSignal.zod';
export * from './assessmentFullscreenExitSignal.zod';
export * from './assessmentGap.zod';
export * from './assessmentGradeAvailability.zod';
export * from './assessmentGradeAvailabilityStatus.zod';
@@ -47,6 +51,9 @@ export * from './assessmentRealMode.zod';
export * from './assessmentRealResultCommon.zod';
export * from './assessmentResult.zod';
export * from './assessmentSessions.zod';
export * from './assessmentSignalBatch.zod';
export * from './assessmentSignalEvent.zod';
export * from './assessmentSignalReceipt.zod';
export * from './assessmentSpecializationAvailability.zod';
export * from './assessmentStrength.zod';
export * from './assessmentUncertainty.zod';
@@ -78,6 +85,8 @@ export * from './practiceItemContent.zod';
export * from './practiceKind.zod';
export * from './practiceStatus.zod';
export * from './practiceVerdict.zod';
export * from './recordMyAssessmentAttemptSignalsBody.zod';
export * from './recordMyAssessmentAttemptSignalsHeaders.zod';
export * from './startMyAssessmentAttemptSessionBody.zod';
export * from './startMyAssessmentAttemptSessionHeaders.zod';
export * from './stringAnswer.zod';
@@ -0,0 +1,36 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const recordMyAssessmentAttemptSignalsBodyEventsItemOneDurationMsMax = 259200000;
export const recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMin = 0;
export const recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMax = 2147483647;
export const recordMyAssessmentAttemptSignalsBodyEventsMax = 50;
export const RecordMyAssessmentAttemptSignalsBody = zod.object({
"events": zod.array(zod.union([zod.object({
"kind": zod.enum(['focus_loss']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"duration_ms": zod.int().min(1).max(recordMyAssessmentAttemptSignalsBodyEventsItemOneDurationMsMax).describe('Client-measured duration away from the assessment tab or window, in milliseconds.')
}),zod.object({
"kind": zod.enum(['copy', 'paste', 'cut']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),
"size_bytes": zod.int().min(recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMin).max(recordMyAssessmentAttemptSignalsBodyEventsItemTwoSizeBytesMax).describe('Byte count only. Clipboard or selection contents are not transmitted or retained.')
}),zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(recordMyAssessmentAttemptSignalsBodyEventsMax)
}).describe('A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.')
export type RecordMyAssessmentAttemptSignalsBody = zod.input<typeof RecordMyAssessmentAttemptSignalsBody>;
export type RecordMyAssessmentAttemptSignalsBodyOutput = zod.output<typeof RecordMyAssessmentAttemptSignalsBody>;
@@ -0,0 +1,19 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const recordMyAssessmentAttemptSignalsHeadersIdempotencyKeyMax = 255;
export const recordMyAssessmentAttemptSignalsHeadersIdempotencyKeyRegExp = new RegExp('^[A-Za-z0-9._:-]+$');
export const RecordMyAssessmentAttemptSignalsHeaders = zod.object({
"Idempotency-Key": zod.string().min(1).max(recordMyAssessmentAttemptSignalsHeadersIdempotencyKeyMax).regex(recordMyAssessmentAttemptSignalsHeadersIdempotencyKeyRegExp)
})
export type RecordMyAssessmentAttemptSignalsHeaders = zod.input<typeof RecordMyAssessmentAttemptSignalsHeaders>;
export type RecordMyAssessmentAttemptSignalsHeadersOutput = zod.output<typeof RecordMyAssessmentAttemptSignalsHeaders>;
@@ -58,4 +58,5 @@ export * from './questionnaireSpecialization.zod';
export * from './questionnaireVersion.zod';
export * from './saveMyProfileBody.zod';
export * from './saveMyQuestionnaireBody.zod';
export * from './stackTag.zod';
export * from './workContext.zod';
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more