feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -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;
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -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 "Не удалось отправить обращение. Попробуйте позже.";
|
||||
}
|
||||
Reference in new issue
Block a user