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

@@ -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 "Не удалось отправить обращение. Попробуйте позже.";
}