feat(consent): add privacy settings and scoped revocation flow

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:46:49 +03:00
1 parent b2322bc178
commit 3ab6bd91a3
19 files changed
+1868 -8

No files matched your search

+281
View File
@@ -0,0 +1,281 @@
import { expect, test, type Locator, type Page, type Response } from "@playwright/test";
type ConsentRecord = {
id: string;
purpose: "c1" | "c2" | "c3" | "c4" | "c5";
state: "active" | "superseded" | "revoked";
text_version: string;
organization: { id: string; name: string } | null;
fields: ("full_name" | "email" | "phone" | "telegram")[] | null;
};
type ConsentList = {
items: ConsentRecord[];
page: { has_more: boolean; next_cursor: string | null };
};
const fixtureEnabled = process.env.E2E_CONSENT_FIXTURE === "1";
const fixtureEmail = "consent-browser@example.test";
const fixturePassword = "browser consent fixture 2026";
test.use({ trace: "off", screenshot: "off", video: "off" });
function consentListResponse(response: {
url(): string;
request(): { method(): string };
}): boolean {
return (
new URL(response.url()).pathname === "/api/v1/me/consents" &&
response.request().method() === "GET"
);
}
async function checkResponsiveKeyboardFlow(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
await page.keyboard.press("Tab");
const hasVisibleKeyboardFocus = await page.evaluate(() => {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false;
const style = getComputedStyle(active);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasVisibleKeyboardFocus).toBe(true);
expect(hasHorizontalOverflow).toBe(false);
}
}
async function focusByTab(page: Page, target: Locator): Promise<void> {
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let attempt = 0; attempt < 80; attempt += 1) {
await page.keyboard.press("Tab");
if (await target.evaluate((element) => element === document.activeElement)) {
const hasVisibleFocus = await target.evaluate((element) => {
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
const style = getComputedStyle(element);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasVisibleFocus).toBe(true);
return;
}
}
throw new Error("Keyboard navigation did not reach the requested consent action.");
}
async function readConsentList(
responseOrPromise: Response | Promise<Response>,
): Promise<ConsentList> {
const response = await responseOrPromise;
expect(response.status()).toBe(200);
return (await response.json()) as ConsentList;
}
test("candidate can review, revoke, and retain independent consent scopes", async ({ page }) => {
test.skip(!fixtureEnabled, "Requires the isolated synthetic consent fixture.");
await page.goto("/login");
await page.getByLabel("Электронная почта").fill(fixtureEmail);
await page.getByLabel("Пароль", { exact: true }).fill(fixturePassword);
const loginResponse = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.request().method() === "POST",
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
const firstListResponsePromise = page.waitForResponse(consentListResponse);
await page.goto("/candidate/privacy");
const firstListResponse = await firstListResponsePromise;
const initial = await readConsentList(firstListResponse);
const activeC2 = initial.items.find(
(record) => record.purpose === "c2" && record.state === "active",
);
const activeC4 = initial.items.filter(
(record) => record.purpose === "c4" && record.state === "active",
);
expect(activeC2).toBeDefined();
expect(activeC4).toHaveLength(2);
if (!activeC2) throw new Error("The consent fixture is missing active C2.");
expect(activeC4.map((record) => record.organization?.name).sort()).toEqual(
["Вторая тестовая компания", "Первая тестовая компания"].sort(),
);
await expect(
page.getByRole("heading", { name: "Согласия и настройки приватности" }),
).toBeVisible();
await expect(page.getByText(`Версия ${activeC2.text_version}`)).toBeVisible();
await expect(page.getByText("Первая тестовая компания").first()).toBeVisible();
await expect(page.getByText("Вторая тестовая компания").first()).toBeVisible();
await expect(page.getByText("Электронная почта", { exact: true })).toBeVisible();
await expect(page.getByText("Телефон", { exact: true })).toBeVisible();
await checkResponsiveKeyboardFlow(page);
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
await page.setViewportSize({ width: 1280, height: 900 });
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
await page.screenshot({
path: `${artifactsDirectory}/consent-history-candidate.png`,
animations: "disabled",
});
const c3TextResponse = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consent-texts/c3" &&
response.request().method() === "GET",
);
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
expect((await c3TextResponse).status()).toBe(200);
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
const c3Grant = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consents/c3" &&
response.request().method() === "PUT",
);
const c3Refresh = page.waitForResponse(consentListResponse);
await page.getByRole("button", { name: "Дать согласие C3" }).click();
expect((await c3Grant).status()).toBe(200);
const afterC3 = await readConsentList(c3Refresh);
expect(afterC3.items.some((record) => record.purpose === "c3" && record.state === "active")).toBe(
true,
);
expect(
afterC3.items.find((record) => record.purpose === "c1" && record.state === "active"),
).toBeDefined();
expect(
afterC3.items.find((record) => record.purpose === "c2" && record.state === "active"),
).toBeDefined();
expect(
afterC3.items.filter((record) => record.purpose === "c4" && record.state === "active"),
).toHaveLength(2);
const c2Delete = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/consents/c2" &&
response.request().method() === "DELETE",
);
const c2Refresh = page.waitForResponse(consentListResponse);
await page.setViewportSize({ width: 360, height: 900 });
const c2RevokeButton = page.getByRole("button", { name: "Отозвать C2", exact: true });
await focusByTab(page, c2RevokeButton);
await page.keyboard.press("Enter");
const c2Acknowledgment = page.getByLabel("Я понимаю последствия отзыва C2.");
await expect(c2Acknowledgment).toBeVisible();
await focusByTab(page, c2Acknowledgment);
await page.keyboard.press("Space");
await expect(c2Acknowledgment).toBeChecked();
const c2ConfirmButton = page.getByRole("button", { name: "Подтвердить отзыв" });
await page.keyboard.press("Tab");
await expect(c2ConfirmButton).toBeFocused();
const c2ConfirmHasVisibleFocus = await c2ConfirmButton.evaluate((element) => {
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
const style = getComputedStyle(element);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(c2ConfirmHasVisibleFocus).toBe(true);
await page.keyboard.press("Enter");
expect((await c2Delete).status()).toBe(204);
const afterC2 = await readConsentList(c2Refresh);
expect(afterC2.items.find((record) => record.id === activeC2?.id)?.state).toBe("revoked");
const c2Record = page
.getByRole("heading", { name: `Версия ${activeC2.text_version}` })
.locator("xpath=..");
await expect(c2Record.getByText("Отозвано", { exact: true }).first()).toBeVisible();
const target = activeC4.find(
(record) => record.organization?.name === "Первая тестовая компания",
);
const other = activeC4.find((record) => record.organization?.name === "Вторая тестовая компания");
expect(target?.organization?.id).toBeTruthy();
expect(other?.organization?.id).toBeTruthy();
if (!target?.organization || !other?.organization) {
throw new Error("The consent fixture is missing the two organization scopes.");
}
const targetOrganizationId = target.organization.id;
const targetOrganizationName = target.organization.name;
const otherRecordId = other.id;
const deniedUrl = `**/api/v1/me/consents/c4/organizations/${targetOrganizationId}`;
await page.route(deniedUrl, (route) =>
route.fulfill({
status: 403,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:forbidden",
title: "Forbidden",
status: 403,
code: "forbidden",
}),
}),
);
const c4RejectedRefresh = page.waitForResponse(consentListResponse);
const targetCompany = page
.getByRole("heading", { name: targetOrganizationName })
.locator("xpath=..");
await targetCompany.getByRole("button", { name: "Отозвать C4 для этой компании" }).click();
await page
.getByLabel("Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.")
.check();
await page.getByRole("button", { name: "Подтвердить отзыв" }).click();
const afterRejectedC4 = await readConsentList(c4RejectedRefresh);
expect(afterRejectedC4.items.find((record) => record.id === target.id)?.state).toBe("active");
expect(afterRejectedC4.items.find((record) => record.id === otherRecordId)?.state).toBe("active");
await expect(page.getByRole("alert")).toContainText("Сервер отклонил действие");
await expect(page.getByRole("alert")).toBeFocused();
await expect(targetCompany.getByText("Действует", { exact: true })).toBeVisible();
await page.unroute(deniedUrl);
const c4Delete = page.waitForResponse(
(response) =>
new URL(response.url()).pathname ===
`/api/v1/me/consents/c4/organizations/${targetOrganizationId}` &&
response.request().method() === "DELETE",
);
const c4Refresh = page.waitForResponse(consentListResponse);
await targetCompany.getByRole("button", { name: "Подтвердить отзыв" }).click();
expect((await c4Delete).status()).toBe(204);
const afterC4 = await readConsentList(c4Refresh);
expect(afterC4.items.find((record) => record.id === target.id)?.state).toBe("revoked");
expect(afterC4.items.find((record) => record.id === otherRecordId)?.state).toBe("active");
const reloadList = page.waitForResponse(consentListResponse);
await page.reload();
const afterReload = await readConsentList(reloadList);
expect(afterReload.items.find((record) => record.id === activeC2?.id)?.state).toBe("revoked");
expect(afterReload.items.find((record) => record.id === target.id)?.state).toBe("revoked");
expect(afterReload.items.find((record) => record.id === otherRecordId)?.state).toBe("active");
await expect(
page.getByRole("heading", { name: "Согласия и настройки приватности" }),
).toBeVisible();
await checkResponsiveKeyboardFlow(page);
const deletionResponsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname === "/api/v1/me/account-deletion-requests" &&
response.request().method() === "POST",
);
const deletionRefresh = page.waitForResponse(consentListResponse);
await page.getByRole("button", { name: "Отозвать C1 и запросить удаление" }).click();
await page
.getByLabel(
"Я понимаю, что этот запрос запустит удаление аккаунта и не будет отменен повторным согласием.",
)
.check();
await page.getByRole("button", { name: "Запросить удаление" }).click();
const deletionResponse = await deletionResponsePromise;
expect(deletionResponse.status()).toBe(202);
const deletionRequest = (await deletionResponse.json()) as {
status: "requested" | "processing";
};
const afterDeletionRequest = await readConsentList(deletionRefresh);
expect(afterDeletionRequest.items.find((record) => record.purpose === "c1")?.state).toBe(
"revoked",
);
await expect(page.getByRole("status").filter({ hasText: "Запрос на удаление" })).toContainText(
deletionRequest.status === "processing" ? "передан в обработку" : "ожидает обработки",
);
});
+75 -2
View File
@@ -2,6 +2,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent";
import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity";
import { createQueryClient } from "../providers/query-client";
import { routes } from "./routes";
@@ -40,6 +41,50 @@ async function render(path: string): Promise<string | Response> {
csrf_token: "A".repeat(43),
});
}
if (path.startsWith("/candidate/privacy")) {
const hasMore = path.includes("history=partial");
queryClient.setQueryData(getListMyConsentsQueryKey({ limit: 100 }), {
pages: [
{
items: [
{
id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80",
purpose: "c2",
state: "active",
text_version: "c2-2026-10-01",
source: "consent_settings",
granted_at: "2026-10-02T09:00:00Z",
revoked_at: null,
revocation_source: null,
organization: null,
fields: null,
invitation_id: null,
invitation_terms_version: null,
},
{
id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81",
purpose: "c4",
state: "active",
text_version: "c4-2026-10-01",
source: "invitation_acceptance",
granted_at: "2026-10-03T09:00:00Z",
revoked_at: null,
revocation_source: null,
organization: {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
name: "Первая тестовая компания",
},
fields: ["email"],
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60",
invitation_terms_version: 1,
},
],
page: { has_more: hasMore, next_cursor: hasMore ? "next-page" : null },
},
],
pageParams: [undefined],
});
}
return renderToString(
<QueryClientProvider client={queryClient}>
<StaticRouterProvider router={router} context={context} hydrate={false} />
@@ -75,6 +120,7 @@ describe("route groups", () => {
["/candidate", "Главная", "Разделы кабинета кандидата"],
["/candidate/profile", "Профиль", "Разделы кабинета кандидата"],
["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"],
["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"],
["/employer/company", "Компания и команда", "Разделы кабинета работодателя"],
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
@@ -101,6 +147,7 @@ describe("route groups", () => {
it("marks the active cabinet section with aria-current", async () => {
expect(currentLinkText(await renderHtml("/candidate"))).toEqual(["Главная"]);
expect(currentLinkText(await renderHtml("/candidate/results"))).toEqual(["Результаты"]);
expect(currentLinkText(await renderHtml("/candidate/privacy"))).toEqual(["Приватность"]);
expect(currentLinkText(await renderHtml("/employer/invitations"))).toEqual(["Приглашения"]);
});
@@ -151,8 +198,34 @@ describe("product readiness", () => {
expect(html).toContain("Это не показатель готовности продукта");
});
it("labels every cabinet screen as a placeholder", async () => {
for (const path of ["/candidate", "/candidate/privacy", "/employer/needs"]) {
it("renders the consent settings route with server-backed history", async () => {
const html = await renderHtml("/candidate/privacy");
expect(html).toContain("Публикация карточки кандидата");
expect(html).toContain("c2-2026-10-01");
expect(html).toContain("Первая тестовая компания");
expect(html).toContain("Электронная почта");
});
it("does not call a purpose empty while older history pages remain", async () => {
const html = await renderHtml("/candidate/privacy?history=partial");
expect(html).toContain("В загруженной части истории записей C3 пока нет");
expect(html).toContain("Показать более ранние записи");
expect(html).not.toContain("Записей C3 пока нет.");
});
it("links the saved candidate consent step to the same settings screen", async () => {
const html = await renderHtml("/candidate/onboarding");
expect(html).toContain("Состояние шага хранится на сервере");
expect(html).toMatch(
/<a[^>]*href="\/candidate\/privacy"[^>]*>Открыть согласия и настройки приватности<\/a>/,
);
});
it("labels the remaining cabinet scaffolds as placeholders", async () => {
for (const path of ["/candidate", "/employer/needs"]) {
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
}
});
+2 -1
View File
@@ -1,6 +1,7 @@
import { redirect, type RouteObject } from "react-router-dom";
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { ConsentsPage } from "../../pages/consents";
import { SessionGate } from "../../entities/session";
import { NotFoundPage } from "../../pages/not-found";
import { PlaceholderPage } from "../../pages/placeholder";
@@ -62,7 +63,7 @@ export const routes: RouteObject[] = [
},
{
path: paths.candidate.privacy,
element: <PlaceholderPage screen="candidatePrivacy" />,
element: <ConsentsPage />,
},
{
path: "*",
+14
View File
@@ -0,0 +1,14 @@
export {
consentPurposeDetails,
consentPurposeOrder,
consentSourceLabels,
consentStateLabels,
contactFieldLabels,
deletionRequestStatusMessage,
emptyPurposeHistoryMessage,
formatConsentDate,
groupConsentHistory,
groupOrganizationConsents,
type ConsentPurposeGroup,
type OrganizationConsentGroup,
} from "./model/consent-presentation";
@@ -0,0 +1,129 @@
import { describe, expect, it } from "vitest";
import type { ConsentRecord } from "../../../shared/api/schemas";
import {
consentPurposeDetails,
consentPurposeOrder,
consentStateLabels,
deletionRequestStatusMessage,
emptyPurposeHistoryMessage,
formatConsentDate,
groupConsentHistory,
groupOrganizationConsents,
} from "./consent-presentation";
const record = (overrides: Partial<ConsentRecord> = {}): ConsentRecord => ({
id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80",
purpose: "c2",
state: "active",
text_version: "c2-2026-10-01",
source: "consent_settings",
granted_at: "2026-10-02T09:00:00Z",
revoked_at: null,
revocation_source: null,
organization: null,
fields: null,
invitation_id: null,
invitation_terms_version: null,
...overrides,
});
describe("consent presentation", () => {
it("keeps every purpose independent and gives empty purposes their own groups", () => {
const groups = groupConsentHistory([
record({ id: "c2-old", state: "superseded" }),
record({ id: "c1", purpose: "c1", text_version: "c1-2026-10-01" }),
record({ id: "c2-new", text_version: "c2-2026-10-02" }),
]);
expect(groups.map(({ purpose }) => purpose)).toEqual(consentPurposeOrder);
expect(groups.find(({ purpose }) => purpose === "c1")?.records.map(({ id }) => id)).toEqual([
"c1",
]);
expect(groups.find(({ purpose }) => purpose === "c2")?.records.map(({ id }) => id)).toEqual([
"c2-old",
"c2-new",
]);
expect(groups.find(({ purpose }) => purpose === "c3")?.records).toEqual([]);
});
it("groups C4 actions by organization while preserving each invitation record", () => {
const firstOrganization = {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
name: "Первая тестовая компания",
};
const secondOrganization = {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e02",
name: "Вторая тестовая компания",
};
const groups = groupOrganizationConsents([
record({
id: "first-invitation-new",
purpose: "c4",
organization: firstOrganization,
fields: ["email"],
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e61",
invitation_terms_version: 2,
}),
record({
id: "second-company",
purpose: "c4",
organization: secondOrganization,
fields: ["phone"],
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e62",
invitation_terms_version: 1,
}),
record({
id: "first-invitation-old",
purpose: "c4",
state: "superseded",
organization: { ...firstOrganization, name: "Первая компания до переименования" },
fields: ["phone"],
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e63",
invitation_terms_version: 1,
}),
]);
expect(groups).toHaveLength(2);
expect(groups[0]?.displayName).toBe("Первая тестовая компания");
expect(groups[0]?.records.map(({ id }) => id)).toEqual([
"first-invitation-new",
"first-invitation-old",
]);
expect(groups[1]?.records.map(({ id }) => id)).toEqual(["second-company"]);
expect(groups[0]?.records[1]?.organization?.name).toBe("Первая компания до переименования");
});
it("provides distinct state labels and consequence copy for C1-C5", () => {
expect(consentStateLabels).toEqual({
active: "Действует",
superseded: "Заменено новой версией",
revoked: "Отозвано",
});
expect(Object.keys(consentPurposeDetails)).toEqual(consentPurposeOrder);
expect(consentPurposeDetails.c1.consequence).toContain("удаление аккаунта");
expect(consentPurposeDetails.c2.consequence).toContain("карточку");
expect(consentPurposeDetails.c3.consequence).toContain("ручную оценку");
expect(consentPurposeDetails.c4.consequence).toContain("компании");
expect(consentPurposeDetails.c5.consequence).toContain("синхронизацию");
});
it("formats server timestamps in UTC", () => {
expect(formatConsentDate("2026-10-02T09:00:00Z")).toContain("UTC");
});
it("does not claim that an unloaded history has no records", () => {
expect(emptyPurposeHistoryMessage("c2", true)).toContain("В загруженной части истории");
expect(emptyPurposeHistoryMessage("c2", true)).toContain("Загрузите более ранние записи");
expect(emptyPurposeHistoryMessage("c2", false)).toBe("Записей C2 пока нет.");
});
it("describes the server-reported account-deletion state without claiming completion", () => {
const requested = deletionRequestStatusMessage("requested");
const processing = deletionRequestStatusMessage("processing");
expect(requested).toContain("ожидает обработки");
expect(processing).toContain("передан в обработку");
expect(requested).toContain("не удаляются сразу");
expect(processing).toContain("еще не завершено");
});
});
@@ -0,0 +1,137 @@
import type {
ConsentDeletionRequest,
ConsentRecord,
ConsentPurposeCode,
} from "../../../shared/api/schemas";
export const consentPurposeOrder = [
"c1",
"c2",
"c3",
"c4",
"c5",
] as const satisfies readonly ConsentPurposeCode[];
export const consentPurposeDetails: Readonly<
Record<ConsentPurposeCode, { title: string; consequence: string }>
> = {
c1: {
title: "Обработка персональных данных",
consequence:
"Отзыв запускает запрос на удаление аккаунта и данных. Запрос обрабатывается отдельно и не удаляет данные сразу.",
},
c2: {
title: "Публикация карточки кандидата",
consequence:
"Отзыв закроет карточку для будущих просмотров и связанные доступы. Новая публикация потребует нового согласия.",
},
c3: {
title: "Автоматическая категоризация",
consequence:
"Отзыв остановит автоматическую категоризацию. Можно запросить ручную оценку по той же рубрике.",
},
c4: {
title: "Передача выбранных данных компании",
consequence:
"Отзыв закроет будущий доступ указанной компании к выбранным полям и запустит уведомление интеграции.",
},
c5: {
title: "Импорт результатов ФСП",
consequence:
"Отзыв остановит синхронизацию и закроет новые чтения импортированных результатов. Обработка сохраненных данных следует принятой политике.",
},
};
export const consentStateLabels = {
active: "Действует",
superseded: "Заменено новой версией",
revoked: "Отозвано",
} as const satisfies Record<ConsentRecord["state"], string>;
export const consentSourceLabels = {
registration: "При регистрации",
consent_settings: "В настройках согласий",
invitation_acceptance: "При принятии приглашения",
} as const satisfies Record<ConsentRecord["source"], string>;
export const contactFieldLabels = {
full_name: "ФИО",
email: "Электронная почта",
phone: "Телефон",
telegram: "Telegram",
} as const satisfies Record<NonNullable<ConsentRecord["fields"]>[number], string>;
export type ConsentPurposeGroup = {
purpose: ConsentPurposeCode;
records: ConsentRecord[];
};
export type OrganizationConsentGroup = {
organizationId: string;
displayName: string;
records: ConsentRecord[];
};
export function groupConsentHistory(records: readonly ConsentRecord[]): ConsentPurposeGroup[] {
const grouped = new Map<ConsentPurposeCode, ConsentRecord[]>(
consentPurposeOrder.map((purpose) => [purpose, []]),
);
for (const record of records) {
grouped.get(record.purpose)?.push(record);
}
return consentPurposeOrder.map((purpose) => ({
purpose,
records: grouped.get(purpose) ?? [],
}));
}
export function groupOrganizationConsents(
records: readonly ConsentRecord[],
): OrganizationConsentGroup[] {
const grouped = new Map<string, OrganizationConsentGroup>();
for (const record of records) {
if (record.purpose !== "c4" || !record.organization) continue;
const current = grouped.get(record.organization.id);
if (current) {
current.records.push(record);
continue;
}
grouped.set(record.organization.id, {
organizationId: record.organization.id,
displayName: record.organization.name,
records: [record],
});
}
return [...grouped.values()];
}
export function formatConsentDate(value: string): string {
return `${new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "UTC",
}).format(new Date(value))} UTC`;
}
export function emptyPurposeHistoryMessage(purpose: ConsentPurposeCode, hasMore: boolean): string {
if (hasMore) {
return `В загруженной части истории записей C${purpose.slice(1)} пока нет. Загрузите более ранние записи, чтобы проверить историю.`;
}
if (purpose === "c4") {
return "Записей C4 пока нет. Такое согласие появляется при принятии приглашения с показом компании и выбранных полей.";
}
return `Записей C${purpose.slice(1)} пока нет.`;
}
export function deletionRequestStatusMessage(status: ConsentDeletionRequest["status"]): string {
if (status === "processing") {
return "Запрос на удаление передан в обработку. Удаление еще не завершено; данные не удаляются сразу.";
}
return "Запрос на удаление зарегистрирован. Он ожидает обработки; данные не удаляются сразу.";
}
@@ -0,0 +1 @@
export { ConsentManagement } from "./ui/consent-management";
@@ -0,0 +1,178 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.purpose-list {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.record-list,
.organization-list {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.record,
.organization-group,
.grant-panel,
.confirmation {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.record-title {
overflow-wrap: anywhere;
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.organization-snapshot {
overflow-wrap: anywhere;
color: var(--color-text-secondary);
}
.facts {
display: grid;
grid-template-columns: minmax(0, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
min-width: 0;
}
.facts dt {
color: var(--color-text-secondary);
}
.facts dd {
min-width: 0;
overflow-wrap: anywhere;
}
.empty-purpose,
.notice,
.status-message,
.action-error {
overflow-wrap: anywhere;
}
.notice {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.status-message {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.action-error {
padding: var(--space-3);
border-left: var(--line-strong) solid var(--color-danger);
background: var(--color-canvas);
}
.action-error button {
margin-left: var(--space-2);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
}
.checkbox {
display: flex;
gap: var(--space-3);
align-items: flex-start;
width: fit-content;
max-width: 100%;
line-height: var(--line-height-body);
}
.checkbox input {
flex: none;
width: 1.15rem;
height: 1.15rem;
margin-top: 0.2em;
accent-color: var(--color-accent);
}
.grant-actions {
display: grid;
gap: var(--space-3);
justify-items: start;
min-width: 0;
}
.grant-panel {
width: 100%;
max-width: 50rem;
}
.text-metadata {
color: var(--color-text-secondary);
}
.consent-text {
max-height: 24rem;
min-width: 0;
overflow: auto;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-canvas);
font: inherit;
line-height: var(--line-height-body);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.grant-form {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.load-more {
display: flex;
justify-content: center;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
white-space: nowrap;
clip-path: inset(50%);
}
@media (width < 30rem) {
.facts {
grid-template-columns: minmax(0, 1fr);
}
.facts dd + dt {
padding-top: var(--space-2);
}
.record,
.organization-group,
.grant-panel,
.confirmation {
padding: var(--space-3);
}
}
@@ -0,0 +1,708 @@
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import {
getListMyConsentsQueryKey,
listMyConsents,
useGetMyConsentText,
useGrantMyConsent,
useRequestMyAccountDeletion,
useRevokeMyConsent,
useRevokeMyOrganizationContactConsent,
} from "../../../shared/api/endpoints/consent/consent";
import type {
ConsentDeletionRequest,
ConsentRecord,
ConsentSettingsPurpose,
ConsentSettingsRevokePurpose,
} from "../../../shared/api/schemas";
import { ApiRequestError } from "../../../shared/api";
import { Button, EmptyState, ErrorState, LoadingState, Section } from "../../../shared/ui";
import {
consentPurposeDetails,
consentSourceLabels,
consentStateLabels,
contactFieldLabels,
deletionRequestStatusMessage,
emptyPurposeHistoryMessage,
formatConsentDate,
groupConsentHistory,
groupOrganizationConsents,
} from "../../../entities/consent";
import type { OrganizationConsentGroup } from "../../../entities/consent";
import styles from "./consent-management.module.css";
const pageSize = 100;
const historyQueryKey = getListMyConsentsQueryKey({ limit: pageSize });
type ConsentAction =
| { kind: "account" }
| { kind: "purpose"; purpose: ConsentSettingsRevokePurpose }
| { kind: "organization"; organizationId: string };
function actionCopy(action: ConsentAction): {
title: string;
description: string;
acknowledgment: string;
button: string;
success: string;
} {
if (action.kind === "account") {
return {
title: "Запросить удаление аккаунта",
description:
"Запрос отзовет C1 и запустит отдельную процедуру удаления аккаунта и данных. Удаление не происходит сразу, а повторное согласие не отменит уже созданный запрос.",
acknowledgment:
"Я понимаю, что этот запрос запустит удаление аккаунта и не будет отменен повторным согласием.",
button: "Запросить удаление",
success:
"Запрос на удаление зарегистрирован. Он обрабатывается отдельно; данные не удаляются сразу. Проверьте обновленное состояние согласий ниже.",
};
}
if (action.kind === "organization") {
return {
title: "Отозвать C4 для этой компании",
description:
"Будущий доступ этой компании ко всем действующим согласиям C4 будет закрыт. Согласия для других компаний не изменятся.",
acknowledgment:
"Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.",
button: "Подтвердить отзыв",
success: "Запрос на отзыв C4 обработан. Проверьте обновленное состояние ниже.",
};
}
return {
title: `Отозвать C${action.purpose.slice(1)}`,
description: consentPurposeDetails[action.purpose].consequence,
acknowledgment: `Я понимаю последствия отзыва C${action.purpose.slice(1)}.`,
button: "Подтвердить отзыв",
success: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
};
}
function refreshFailureMessage(error: unknown): string {
if (error instanceof ApiRequestError && error.code === "csrf_check_failed") {
return "Не удалось подтвердить запрос. Данные обновлены; проверьте состояние и повторите действие.";
}
if (error instanceof ApiRequestError && error.status === 403) {
return "Сервер отклонил действие. Проверьте обновленное состояние и доступ к этому разделу.";
}
return "Не удалось изменить согласие. Текущее состояние сохранено; обновите список и попробуйте снова.";
}
function ConsentRecordView({ record }: { record: ConsentRecord }) {
return (
<article className={styles.record}>
<h3 className={styles["record-title"]}>Версия {record.text_version}</h3>
{record.purpose === "c4" && record.organization ? (
<p className={styles["organization-snapshot"]}>Компания: {record.organization.name}</p>
) : null}
<dl className={styles.facts}>
<dt>Состояние</dt>
<dd>{consentStateLabels[record.state]}</dd>
<dt>Выдано</dt>
<dd>{formatConsentDate(record.granted_at)}</dd>
<dt>Источник</dt>
<dd>{consentSourceLabels[record.source]}</dd>
{record.revoked_at ? (
<>
<dt>Отозвано</dt>
<dd>{formatConsentDate(record.revoked_at)}</dd>
</>
) : null}
{record.revocation_source ? (
<>
<dt>Кем отозвано</dt>
<dd>
{record.revocation_source === "support_request"
? "По обращению в поддержку"
: "В настройках согласий"}
</dd>
</>
) : null}
{record.purpose === "c4" && record.fields ? (
<>
<dt>Выбранные поля</dt>
<dd>{record.fields.map((field) => contactFieldLabels[field]).join(", ")}</dd>
{record.invitation_terms_version ? (
<>
<dt>Версия условий приглашения</dt>
<dd>{record.invitation_terms_version}</dd>
</>
) : null}
</>
) : null}
</dl>
</article>
);
}
type ActionConfirmationProps = {
action: ConsentAction;
accepted: boolean;
isBusy: boolean;
isReady: boolean;
onAcceptChange: (accepted: boolean) => void;
onCancel: () => void;
onConfirm: () => void;
};
function ActionConfirmation({
action,
accepted,
isBusy,
isReady,
onAcceptChange,
onCancel,
onConfirm,
}: ActionConfirmationProps) {
const id = useId();
const copy = actionCopy(action);
return (
<div className={styles.confirmation} role="group" aria-labelledby={`${id}-title`}>
<h4 id={`${id}-title`}>{copy.title}</h4>
<p id={`${id}-description`}>{copy.description}</p>
<label className={styles.checkbox} htmlFor={`${id}-accept`}>
<input
id={`${id}-accept`}
type="checkbox"
checked={accepted}
onChange={(event) => onAcceptChange(event.currentTarget.checked)}
/>
<span>{copy.acknowledgment}</span>
</label>
<div className={styles.actions}>
<Button
isBusy={isBusy}
aria-disabled={!isReady || undefined}
aria-describedby={`${id}-description`}
onClick={() => {
if (isReady && !isBusy) onConfirm();
}}
>
{copy.button}
</Button>
<Button variant="secondary" isBusy={isBusy} onClick={onCancel}>
Отмена
</Button>
</div>
</div>
);
}
type ConsentGrantPanelProps = {
purpose: ConsentSettingsPurpose;
activeRecord: ConsentRecord | undefined;
csrfToken: string | undefined;
isSubmitting: boolean;
onCancel: () => void;
onGrant: (purpose: ConsentSettingsPurpose, textVersion: string) => Promise<void>;
};
function ConsentGrantPanel({
purpose,
activeRecord,
csrfToken,
isSubmitting,
onCancel,
onGrant,
}: ConsentGrantPanelProps) {
const id = useId();
const text = useGetMyConsentText(purpose, {
query: { gcTime: 0, staleTime: 0, refetchOnMount: "always" },
});
const [acceptedVersion, setAcceptedVersion] = useState<string | null>(null);
const currentText = text.data;
const alreadyActive = Boolean(
currentText && activeRecord?.text_version === currentText.text_version,
);
const acceptedCurrentText = Boolean(
currentText && acceptedVersion === currentText.text_version && !text.isError,
);
const isReady = Boolean(
currentText &&
acceptedCurrentText &&
!text.isError &&
!text.isFetching &&
!isSubmitting &&
csrfToken,
);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!isReady || !currentText) return;
await onGrant(purpose, currentText.text_version);
}
return (
<div className={styles["grant-panel"]}>
<h3>Текущий текст C{purpose.slice(1)}</h3>
{text.isPending ? <LoadingState label="Загружаем текущий текст согласия..." /> : null}
{text.isError ? (
<ErrorState
error={text.error}
title="Не удалось загрузить текст согласия"
onRetry={() => void text.refetch()}
isRetrying={text.isRefetching}
/>
) : null}
{currentText && !text.isError ? (
<>
<p className={styles["text-metadata"]}>
Версия {currentText.text_version}, опубликовано{" "}
{formatConsentDate(currentText.published_at)}
</p>
<pre
className={styles["consent-text"]}
tabIndex={0}
aria-label={`Полный текст согласия C${purpose.slice(1)}, версия ${currentText.text_version}`}
>
{currentText.text}
</pre>
{alreadyActive ? (
<p role="status">Эта версия уже действует. Новое согласие не требуется.</p>
) : (
<form className={styles["grant-form"]} onSubmit={(event) => void submit(event)}>
{purpose === "c1" ? (
<p className={styles.notice}>
Повторное согласие не отменяет ранее созданный запрос на удаление аккаунта.
</p>
) : null}
<label className={styles.checkbox} htmlFor={`${id}-accept`}>
<input
id={`${id}-accept`}
type="checkbox"
checked={acceptedCurrentText && !text.isFetching}
disabled={text.isFetching || isSubmitting}
onChange={(event) => {
setAcceptedVersion(
event.currentTarget.checked ? currentText.text_version : null,
);
}}
aria-describedby={`${id}-version`}
/>
<span>Я прочитал(а) и принимаю только это согласие C{purpose.slice(1)}.</span>
</label>
<p className={styles["visually-hidden"]} id={`${id}-version`}>
Версия {currentText.text_version}
</p>
<div className={styles.actions}>
<Button
type="submit"
isBusy={isSubmitting}
aria-disabled={!isReady || undefined}
onClick={(event) => {
if (!isReady) event.preventDefault();
}}
>
Дать согласие C{purpose.slice(1)}
</Button>
<Button variant="secondary" isBusy={isSubmitting} onClick={onCancel}>
Закрыть
</Button>
</div>
</form>
)}
</>
) : null}
</div>
);
}
function OrganizationConsent({
group,
records,
confirming,
accepted,
isBusy,
isReady,
onBegin,
onAcceptChange,
onCancel,
onConfirm,
}: {
group: OrganizationConsentGroup;
records: ConsentRecord[];
confirming: boolean;
accepted: boolean;
isBusy: boolean;
isReady: boolean;
onBegin: () => void;
onAcceptChange: (accepted: boolean) => void;
onCancel: () => void;
onConfirm: () => void;
}) {
const hasActiveRecord = records.some((record) => record.state === "active");
const action: ConsentAction = { kind: "organization", organizationId: group.organizationId };
return (
<article className={styles["organization-group"]}>
<h3 className={styles["record-title"]}>{group.displayName}</h3>
<div className={styles["record-list"]}>
{records.map((record) => (
<ConsentRecordView key={record.id} record={record} />
))}
</div>
{hasActiveRecord && !confirming ? (
<Button variant="secondary" onClick={onBegin}>
Отозвать C4 для этой компании
</Button>
) : null}
{hasActiveRecord && confirming ? (
<ActionConfirmation
action={action}
accepted={accepted}
isBusy={isBusy}
isReady={isReady && accepted}
onAcceptChange={onAcceptChange}
onCancel={onCancel}
onConfirm={onConfirm}
/>
) : null}
</article>
);
}
export function ConsentManagement() {
const queryClient = useQueryClient();
const session = useGetCurrentSession();
const csrfToken = session.data?.csrf_token;
const request = {
headers: csrfToken ? { "X-CSRF-Token": csrfToken } : {},
};
const history = useInfiniteQuery({
queryKey: historyQueryKey,
queryFn: ({ pageParam, signal }) =>
listMyConsents(
pageParam === undefined ? { limit: pageSize } : { limit: pageSize, cursor: pageParam },
{ signal },
),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) =>
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
refetchOnMount: "always",
});
const grant = useGrantMyConsent({ request, mutation: { gcTime: 0 } });
const revoke = useRevokeMyConsent({ request, mutation: { gcTime: 0 } });
const revokeOrganization = useRevokeMyOrganizationContactConsent({
request,
mutation: { gcTime: 0 },
});
const deleteAccount = useRequestMyAccountDeletion({ request, mutation: { gcTime: 0 } });
const [grantPurpose, setGrantPurpose] = useState<ConsentSettingsPurpose | null>(null);
const [confirmation, setConfirmation] = useState<ConsentAction | null>(null);
const [acceptedConfirmation, setAcceptedConfirmation] = useState(false);
const [statusMessage, setStatusMessage] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const actionErrorRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (actionError) actionErrorRef.current?.focus();
}, [actionError]);
const records = history.data?.pages.flatMap((page) => page.items) ?? [];
const purposeGroups = groupConsentHistory(records);
const c4Groups = groupOrganizationConsents(
purposeGroups.find(({ purpose }) => purpose === "c4")?.records ?? [],
);
const isSubmitting =
grant.isPending || revoke.isPending || revokeOrganization.isPending || deleteAccount.isPending;
const canMutate =
Boolean(csrfToken) && !session.isPending && !session.isFetching && !session.isError;
const canConfirm = canMutate && !history.isFetching && acceptedConfirmation;
function beginConfirmation(action: ConsentAction) {
setConfirmation(action);
setAcceptedConfirmation(false);
setStatusMessage(null);
setActionError(null);
}
function cancelConfirmation() {
if (isSubmitting) return;
setConfirmation(null);
setAcceptedConfirmation(false);
}
async function refreshHistory(): Promise<boolean> {
try {
await queryClient.invalidateQueries(
{ queryKey: getListMyConsentsQueryKey() },
{ throwOnError: true },
);
return queryClient.getQueryState(historyQueryKey)?.status === "success";
} catch {
return false;
}
}
async function refreshAfterFailure(error: unknown): Promise<void> {
if (error instanceof ApiRequestError && error.status === 403) {
await queryClient.invalidateQueries(
{ queryKey: getGetCurrentSessionQueryKey() },
{ throwOnError: false },
);
}
await queryClient.invalidateQueries(
{ queryKey: getListMyConsentsQueryKey() },
{ throwOnError: false },
);
}
async function submitGrant(purpose: ConsentSettingsPurpose, textVersion: string): Promise<void> {
setActionError(null);
setStatusMessage(null);
try {
await grant.mutateAsync({ purpose, data: { text_version: textVersion, accepted: true } });
if (!(await refreshHistory())) {
setActionError(
"Сервер принял запрос, но не удалось обновить список согласий. Перезагрузите страницу перед повтором.",
);
return;
}
setGrantPurpose(null);
setStatusMessage(
`Согласие C${purpose.slice(1)} сохранено. Проверьте обновленную историю ниже.`,
);
} catch (error: unknown) {
await refreshAfterFailure(error);
setActionError(refreshFailureMessage(error));
}
}
async function submitConfirmation(): Promise<void> {
if (!confirmation || !canConfirm || isSubmitting) return;
const action = confirmation;
setActionError(null);
setStatusMessage(null);
try {
let deletionStatus: ConsentDeletionRequest["status"] | undefined;
if (action.kind === "account") {
const deletionRequest = await deleteAccount.mutateAsync();
deletionStatus = deletionRequest.status;
} else if (action.kind === "purpose") {
await revoke.mutateAsync({ purpose: action.purpose });
} else {
await revokeOrganization.mutateAsync({ orgId: action.organizationId });
}
if (!(await refreshHistory())) {
setConfirmation(null);
setActionError(
"Сервер принял запрос, но не удалось обновить список согласий. Перезагрузите страницу перед повтором.",
);
return;
}
setConfirmation(null);
setAcceptedConfirmation(false);
setStatusMessage(
action.kind === "account" && deletionStatus
? deletionRequestStatusMessage(deletionStatus)
: actionCopy(action).success,
);
} catch (error: unknown) {
await refreshAfterFailure(error);
setActionError(refreshFailureMessage(error));
}
}
if (history.isPending && !history.data) {
return <LoadingState label="Загружаем согласия и историю..." />;
}
if (history.isError && !history.data) {
return (
<ErrorState
error={history.error}
title="Не удалось загрузить согласия"
onRetry={() => void history.refetch()}
isRetrying={history.isRefetching}
/>
);
}
return (
<div className={styles.root}>
{statusMessage ? (
<p className={styles["status-message"]} role="status" aria-live="polite">
{statusMessage}
</p>
) : null}
{actionError ? (
<div
ref={actionErrorRef}
className={styles["action-error"]}
role="alert"
aria-live="assertive"
tabIndex={-1}
>
{actionError}
</div>
) : null}
{history.isError && history.data ? (
<div className={styles["action-error"]} role="alert">
Не удалось обновить историю. Показаны последние загруженные данные.
<Button
variant="quiet"
isBusy={history.isRefetching}
onClick={() => void history.refetch()}
>
Обновить список
</Button>
</div>
) : null}
{!canMutate ? (
<p className={styles.notice} role="status">
Для изменения согласий нужно заново проверить вход. Обновите страницу.
</p>
) : null}
{history.hasNextPage ? (
<p className={styles.notice} role="status">
Показана часть истории. Загрузите более ранние записи, чтобы проверить все действующие
согласия и компании.
</p>
) : null}
<div className={styles["purpose-list"]}>
{purposeGroups.map(({ purpose, records: purposeRecords }) => {
const activeRecord = purposeRecords.find((record) => record.state === "active");
const emptyMessage = emptyPurposeHistoryMessage(purpose, history.hasNextPage);
const isConfirmingPurpose =
confirmation?.kind === "account"
? purpose === "c1"
: confirmation?.kind === "purpose" && confirmation.purpose === purpose;
const action: ConsentAction | null =
purpose === "c1"
? { kind: "account" }
: purpose === "c2" || purpose === "c3" || purpose === "c5"
? { kind: "purpose", purpose }
: null;
const canRevoke =
purpose === "c1" ? Boolean(activeRecord) : Boolean(activeRecord && action);
return (
<Section
key={purpose}
title={`C${purpose.slice(1)}. ${consentPurposeDetails[purpose].title}`}
description={consentPurposeDetails[purpose].consequence}
>
{purpose === "c4" ? (
c4Groups.length > 0 ? (
<div className={styles["organization-list"]}>
{c4Groups.map((group) => (
<OrganizationConsent
key={group.organizationId}
group={group}
records={group.records}
confirming={
confirmation?.kind === "organization" &&
confirmation.organizationId === group.organizationId
}
accepted={acceptedConfirmation}
isBusy={
confirmation?.kind === "organization" &&
confirmation.organizationId === group.organizationId &&
revokeOrganization.isPending
}
isReady={canConfirm}
onBegin={() =>
beginConfirmation({
kind: "organization",
organizationId: group.organizationId,
})
}
onAcceptChange={setAcceptedConfirmation}
onCancel={cancelConfirmation}
onConfirm={() => void submitConfirmation()}
/>
))}
</div>
) : (
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
)
) : (
<>
{purposeRecords.length > 0 ? (
<div className={styles["record-list"]}>
{purposeRecords.map((record) => (
<ConsentRecordView key={record.id} record={record} />
))}
</div>
) : (
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
)}
{canRevoke && action && !isConfirmingPurpose ? (
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
{purpose === "c1"
? "Отозвать C1 и запросить удаление"
: `Отозвать C${purpose.slice(1)}`}
</Button>
) : null}
{canRevoke && action && isConfirmingPurpose ? (
<ActionConfirmation
action={action}
accepted={acceptedConfirmation}
isBusy={purpose === "c1" ? deleteAccount.isPending : revoke.isPending}
isReady={canConfirm}
onAcceptChange={setAcceptedConfirmation}
onCancel={cancelConfirmation}
onConfirm={() => void submitConfirmation()}
/>
) : null}
<div className={styles["grant-actions"]}>
{grantPurpose === purpose ? (
<ConsentGrantPanel
key={purpose}
purpose={purpose}
activeRecord={activeRecord}
csrfToken={canMutate ? csrfToken : undefined}
isSubmitting={grant.isPending}
onCancel={() => setGrantPurpose(null)}
onGrant={submitGrant}
/>
) : (
<Button
variant="quiet"
aria-expanded={grantPurpose === purpose}
onClick={() => {
setStatusMessage(null);
setActionError(null);
setGrantPurpose(purpose);
}}
>
Прочитать текущий текст C{purpose.slice(1)}
</Button>
)}
</div>
</>
)}
</Section>
);
})}
</div>
{records.length === 0 && !history.hasNextPage ? (
<EmptyState
title="История согласий пока пуста"
description="Записи появятся здесь после явного принятия согласия или приглашения."
/>
) : null}
{history.hasNextPage ? (
<div className={styles["load-more"]}>
<Button
variant="secondary"
isBusy={history.isFetchingNextPage}
onClick={() => void history.fetchNextPage()}
>
{history.isFetchingNextPage ? "Загружаем историю..." : "Показать более ранние записи"}
</Button>
</div>
) : null}
</div>
);
}
@@ -2,7 +2,7 @@ import { Navigate } from "react-router-dom";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { getOnboardingDestination } from "../../../entities/session";
import { paths } from "../../../shared/config";
import { LoadingState, Page, Section, StatusView } from "../../../shared/ui";
import { ButtonLink, LoadingState, Page, Section, StatusView } from "../../../shared/ui";
export function CandidateOnboardingPage() {
const session = useGetCurrentSession();
@@ -41,7 +41,19 @@ export function CandidateOnboardingPage() {
return (
<Page title="Первые шаги" eyebrow="Кабинет кандидата">
<Section title={stepTitle} description={description}>
<p>Этот шаг сохранен в аккаунте и будет открыт после следующего входа.</p>
{step === "candidate_consents" ? (
<>
<p>
Состояние шага хранится на сервере. Просмотрите согласия и выберите каждое действие
отдельно.
</p>
<ButtonLink to={paths.candidate.privacy}>
Открыть согласия и настройки приватности
</ButtonLink>
</>
) : (
<p>Этот шаг сохранен в аккаунте и будет открыт после следующего входа.</p>
)}
</Section>
</Page>
);
+1
View File
@@ -0,0 +1 @@
export { ConsentsPage } from "./ui/consents-page";
@@ -0,0 +1,15 @@
import { ConsentManagement } from "../../../features/consent-management";
import { Page } from "../../../shared/ui";
export function ConsentsPage() {
return (
<Page
title="Согласия и настройки приватности"
eyebrow="Кабинет кандидата"
lead="Здесь можно проверить историю каждого согласия и отдельно изменить его состояние."
width="wide"
>
<ConsentManagement />
</Page>
);
}