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

@@ -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>
);
}