feat(privacy): complete the publication, hiding and preview settings screen

This commit is contained in:
shira committed 2026-10-09 12:47:26 +03:00
1 parent c2a8d17195
commit 5edff21d2d
28 files changed
+2230 -428

No files matched your search

@@ -1 +1,2 @@
export { ConsentManagement } from "./ui/consent-management";
export { consentPurposeAnchorId } from "./model/anchors";
@@ -0,0 +1,4 @@
/** Id of the block of one consent purpose, for links that move the reader to it. */
export function consentPurposeAnchorId(purpose: string): string {
return `consent-purpose-${purpose}`;
}
@@ -176,3 +176,7 @@
padding: var(--space-3);
}
}
.purpose-anchor {
scroll-margin-block-start: var(--space-4);
}
@@ -33,10 +33,21 @@ import {
groupOrganizationConsents,
} from "../../../entities/consent";
import type { OrganizationConsentGroup } from "../../../entities/consent";
import { consentPurposeAnchorId } from "../model/anchors";
import styles from "./consent-management.module.css";
const pageSize = 100;
const historyQueryKey = getListMyConsentsQueryKey({ limit: pageSize });
const noOrganizations: ReadonlySet<string> = new Set();
type ConsentManagementProps = {
/**
* Organizations the candidate currently hides the profile from. A C4 record
* of such an organization stays in the ledger, so the list says that it
* does not reopen contact access while the profile is hidden.
*/
hiddenOrganizationIds?: ReadonlySet<string>;
};
type ConsentAction =
| { kind: "account" }
@@ -71,7 +82,8 @@ function actionCopy(action: ConsentAction): {
acknowledgment:
"Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.",
button: "Подтвердить отзыв",
success: "Запрос на отзыв C4 обработан. Проверьте обновленное состояние ниже.",
success:
"Запрос на отзыв C4 обработан. Будущие чтения контактов этой компанией закрыты; для нового доступа нужны новое приглашение и новое согласие C4. Проверьте обновленное состояние ниже.",
};
}
@@ -80,7 +92,10 @@ function actionCopy(action: ConsentAction): {
description: consentPurposeDetails[action.purpose].consequence,
acknowledgment: `Я понимаю последствия отзыва C${action.purpose.slice(1)}.`,
button: "Подтвердить отзыв",
success: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
success:
action.purpose === "c2"
? "C2 отозвано. Карточка закрыта, будущие чтения компаниями закрыты. Новое согласие C2 карточку не откроет: публикацию нужно включить отдельно. Бывшей компании для контактов нужны новое приглашение и новое согласие C4. Проверьте обновленное состояние ниже."
: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
};
}
@@ -317,6 +332,7 @@ function ConsentGrantPanel({
function OrganizationConsent({
group,
records,
isHidden,
confirming,
accepted,
isBusy,
@@ -328,6 +344,7 @@ function OrganizationConsent({
}: {
group: OrganizationConsentGroup;
records: ConsentRecord[];
isHidden: boolean;
confirming: boolean;
accepted: boolean;
isBusy: boolean;
@@ -343,6 +360,12 @@ function OrganizationConsent({
return (
<article className={styles["organization-group"]}>
<h3 className={styles["record-title"]}>{group.displayName}</h3>
{isHidden ? (
<p className={styles.notice} role="status">
Профиль скрыт от этой компании. Запись C4 остается в журнале, но не возвращает доступ к
контактам: он закрыт до нового приглашения и нового согласия C4.
</p>
) : null}
<div className={styles["record-list"]}>
{records.map((record) => (
<ConsentRecordView key={record.id} record={record} />
@@ -368,7 +391,9 @@ function OrganizationConsent({
);
}
export function ConsentManagement() {
export function ConsentManagement({
hiddenOrganizationIds = noOrganizations,
}: ConsentManagementProps) {
const queryClient = useQueryClient();
const session = useGetCurrentSession();
const csrfToken = session.data?.csrf_token;
@@ -587,102 +612,109 @@ export function ConsentManagement() {
purpose === "c1" ? Boolean(activeRecord) : Boolean(activeRecord && action);
return (
<Section
<div
key={purpose}
title={`C${purpose.slice(1)}. ${consentPurposeDetails[purpose].title}`}
description={consentPurposeDetails[purpose].consequence}
id={consentPurposeAnchorId(purpose)}
className={styles["purpose-anchor"]}
tabIndex={-1}
>
{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} />
<Section
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}
isHidden={hiddenOrganizationIds.has(group.organizationId)}
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>
)}
{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}
/>
)
) : (
<>
{purposeRecords.length > 0 ? (
<div className={styles["record-list"]}>
{purposeRecords.map((record) => (
<ConsentRecordView key={record.id} record={record} />
))}
</div>
) : (
<Button
variant="quiet"
aria-expanded={grantPurpose === purpose}
onClick={() => {
setStatusMessage(null);
setActionError(null);
setGrantPurpose(purpose);
}}
>
Прочитать текущий текст C{purpose.slice(1)}
</Button>
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
)}
</div>
</>
)}
</Section>
{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>
);
})}
</div>
@@ -72,6 +72,56 @@
border-inline-start-color: var(--color-danger);
}
.step {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
/* The state is stated in text; the stronger edge only repeats it for sighted users. */
.step[data-c2-state="inactive"] {
border-inline-start: var(--line-strong) solid var(--color-danger);
}
.step[data-c2-state="active"] {
border-inline-start: var(--line-strong) solid var(--color-accent);
}
.step-title {
margin: 0;
font-size: 1rem;
}
.step-text {
margin: 0;
overflow-wrap: anywhere;
}
.closure {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.closure-title {
margin: 0;
font-weight: var(--font-weight-bold);
}
.closure ul {
display: grid;
gap: var(--space-1);
margin: 0;
padding-inline-start: 1.25rem;
overflow-wrap: anywhere;
}
.actions {
display: flex;
flex-wrap: wrap;
@@ -39,6 +39,7 @@ describe("profile visibility controls", () => {
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
);
const search = renderToStaticMarkup(
@@ -51,7 +52,8 @@ describe("profile visibility controls", () => {
/>,
);
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2 ниже.");
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2");
expect(publication).toContain("Перейти к согласию C2");
expect(publication).toContain("Подтвержденная категория и уровень");
expect(publication).toContain("Самооценка по направлениям");
expect(publication).toContain('aria-disabled="true"');
@@ -77,6 +79,7 @@ describe("profile visibility controls", () => {
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
);
@@ -85,3 +88,58 @@ describe("profile visibility controls", () => {
expect(markup).toContain("Загрузить актуальные настройки");
});
});
describe("publication closure notice", () => {
const closedByRevocation: PrivacySettings = {
...settings,
publication: {
state: "closed",
closed_reason: "consent_revoked",
fields: [],
consent_id: "00000000-0000-4000-8000-000000000002",
published_at: "2026-10-02T00:00:00Z",
version: 3,
},
};
function render(value: PrivacySettings, c2State: "active" | "inactive") {
return renderToStaticMarkup(
<PublicationControls
settings={value}
c2State={c2State}
draft={{ state: "closed", fields: [], expectedVersion: value.publication.version }}
isDirty={false}
isStale={false}
hasUnsupportedFields={false}
canSave={false}
isSaving={false}
message={null}
error={null}
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
);
}
it("explains closed future reads and a new C4 after a revocation", () => {
const markup = render(closedByRevocation, "inactive");
expect(markup).toContain("Согласие C2 отозвано, карточка закрыта");
expect(markup).toContain("Будущие чтения карточки компаниями закрыты");
expect(markup).toContain("новое приглашение и новое согласие C4");
});
it("keeps a fresh C2 apart from the publication that it never reopens", () => {
const markup = render(closedByRevocation, "active");
expect(markup).toContain("Согласие C2 действует. Оно само по себе не включает публикацию.");
expect(markup).toContain("Новое согласие C2 не откроет карточку само");
expect(markup).not.toContain("Перейти к согласию C2");
});
it("shows no closure notice for a card that was never published", () => {
expect(render(settings, "inactive")).not.toContain("карточка закрыта");
});
});
@@ -1,6 +1,7 @@
import { useId } from "react";
import {
cardFieldLabels,
describePublicationClosure,
publishableCardFields,
type C2State,
type PublicationDraft,
@@ -23,8 +24,17 @@ type PublicationControlsProps = {
onDraftChange: (draft: PublicationDraft) => void;
onSave: () => void;
onReload: () => void;
/** Moves the reader to the C2 consent block. It never grants anything. */
onOpenConsent: () => void;
};
const c2StepText = {
active: "Согласие C2 действует. Оно само по себе не включает публикацию.",
checking: "Проверяем полную историю согласий C2. До завершения публикация недоступна.",
inactive:
"Для публикации сначала отдельно примите согласие C2 в блоке «C2. Публикация карточки кандидата» выше.",
} as const satisfies Record<C2State, string>;
export function PublicationControls({
settings,
c2State,
@@ -39,10 +49,12 @@ export function PublicationControls({
onDraftChange,
onSave,
onReload,
onOpenConsent,
}: PublicationControlsProps) {
const stateId = useId();
const fieldsId = useId();
const c2Id = useId();
const closure = describePublicationClosure(settings.publication);
function toggleField(field: PublicationDraft["fields"][number], checked: boolean) {
const next = checked
@@ -63,8 +75,33 @@ export function PublicationControls({
Текущее состояние:{" "}
{settings.publication.state === "published" ? "опубликована" : "закрыта"}.
</p>
{closure ? (
<div className={styles.closure} role="status">
<p className={styles["closure-title"]}>{closure.title}</p>
<ul>
{closure.points.map((point) => (
<li key={point}>{point}</li>
))}
</ul>
</div>
) : null}
<div className={styles.step} data-c2-state={c2State}>
<h3 className={styles["step-title"]}>Шаг 1. Согласие C2</h3>
<p id={c2Id} className={styles["step-text"]}>
{c2StepText[c2State]}
</p>
{c2State === "inactive" ? (
<div className={styles.actions}>
<Button variant="secondary" onClick={onOpenConsent}>
Перейти к согласию C2
</Button>
</div>
) : null}
</div>
<fieldset className={styles.group} aria-describedby={stateId}>
<legend>Состояние карточки</legend>
<legend>Шаг 2. Состояние карточки</legend>
<p id={stateId} className={styles.help}>
Закрытая карточка не доступна компаниям. Повторная публикация требует отдельного
действия.
@@ -94,7 +131,7 @@ export function PublicationControls({
</fieldset>
<fieldset className={styles.group} aria-describedby={fieldsId}>
<legend>Поля анонимной карточки</legend>
<legend>Шаг 3. Поля анонимной карточки</legend>
<p id={fieldsId} className={styles.help}>
Имя, контакты, работодатели и суммы зарплаты не публикуются. Подтвержденные категории и
самооценка показываются раздельно.
@@ -118,13 +155,6 @@ export function PublicationControls({
Выберите разрешенные поля или явно закройте публикацию.
</p>
) : null}
<p id={c2Id} className={styles.help}>
{c2State === "active"
? "Согласие C2 активно. Оно само по себе не включает публикацию."
: c2State === "checking"
? "Проверяем полную историю согласий C2. До завершения публикация недоступна."
: "Для публикации сначала отдельно примите согласие C2 ниже."}
</p>
{isStale ? (
<div className={styles.error} role="alert">
Настройки изменились на сервере. Ваш черновик сохранен на экране. Загрузите актуальные