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