feat: add candidate privacy controls

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:43:11 +03:00
1 parent e6bd66c560
commit 95b8e566c4
20 files changed
+2592 -11

No files matched your search

@@ -0,0 +1,8 @@
export { PublicationControls, SearchStatusControl } from "./ui/visibility-controls";
export {
CandidateSessionChangedError,
isCurrentCandidateSession,
runForCurrentCandidate,
} from "./model/session-guard";
export { isPublicationSaveAllowed } from "./model/publication-save";
export type { PublicationSaveReadiness } from "./model/publication-save";
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { isPublicationSaveAllowed } from "./publication-save";
const draft = { state: "published" as const, fields: ["categories" as const], expectedVersion: 2 };
const readyState = {
sessionReady: true,
draft,
isDirty: true,
isStale: false,
consentHistoryFailed: false,
c2State: "active" as const,
};
describe("publication save readiness", () => {
it("blocks stale, unchanged, unauthenticated, and unverified drafts", () => {
expect(isPublicationSaveAllowed({ ...readyState, isStale: true })).toBe(false);
expect(isPublicationSaveAllowed({ ...readyState, isDirty: false })).toBe(false);
expect(isPublicationSaveAllowed({ ...readyState, sessionReady: false })).toBe(false);
expect(isPublicationSaveAllowed({ ...readyState, consentHistoryFailed: true })).toBe(false);
});
it("requires a complete active C2 history for a published draft", () => {
expect(isPublicationSaveAllowed({ ...readyState, c2State: "checking" })).toBe(false);
expect(isPublicationSaveAllowed({ ...readyState, c2State: "inactive" })).toBe(false);
expect(isPublicationSaveAllowed(readyState)).toBe(true);
});
it("allows an explicit close without C2", () => {
expect(
isPublicationSaveAllowed({
...readyState,
draft: { state: "closed", fields: [], expectedVersion: 2 },
c2State: "inactive",
}),
).toBe(true);
});
});
@@ -0,0 +1,22 @@
import type { C2State, PublicationDraft } from "../../../entities/candidate-view";
export type PublicationSaveReadiness = {
sessionReady: boolean;
draft: PublicationDraft | null;
isDirty: boolean;
isStale: boolean;
consentHistoryFailed: boolean;
c2State: C2State;
};
export function isPublicationSaveAllowed(readiness: PublicationSaveReadiness): boolean {
const { sessionReady, draft, isDirty, isStale, consentHistoryFailed, c2State } = readiness;
return Boolean(
sessionReady &&
draft &&
isDirty &&
!isStale &&
!consentHistoryFailed &&
(draft.state === "closed" || c2State === "active"),
);
}
@@ -0,0 +1,73 @@
import { QueryClient } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
import {
CandidateSessionChangedError,
isCurrentCandidateSession,
runForCurrentCandidate,
} from "./session-guard";
function session(accountId: string, csrfToken: string): Session {
return {
account: {
id: accountId,
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-01T00:00:00Z",
},
csrf_token: csrfToken,
};
}
function queryClientFor(current: Session): QueryClient {
const queryClient = new QueryClient();
queryClient.setQueryData(getGetCurrentSessionQueryKey(), current);
return queryClient;
}
describe("candidate privacy session guard", () => {
it("accepts the same account while its session query is fetching", () => {
const expected = session("00000000-0000-4000-8000-000000000001", "a".repeat(32));
const queryClient = queryClientFor(expected);
void queryClient.fetchQuery({
queryKey: getGetCurrentSessionQueryKey(),
queryFn: async () => expected,
});
expect(isCurrentCandidateSession(queryClient, expected)).toBe(true);
});
it("fails closed when cached session data is in an error state", async () => {
const expected = session("00000000-0000-4000-8000-000000000001", "a".repeat(32));
const queryClient = queryClientFor(expected);
queryClient.setQueryData(getGetCurrentSessionQueryKey(), undefined);
queryClient.setQueryData(getGetCurrentSessionQueryKey(), expected);
const query = queryClient.getQueryCache().find({ queryKey: getGetCurrentSessionQueryKey() });
query?.setState({ status: "error", error: new Error("expired") });
expect(isCurrentCandidateSession(queryClient, expected)).toBe(false);
await expect(
runForCurrentCandidate(queryClient, expected, async () => "private"),
).rejects.toBeInstanceOf(CandidateSessionChangedError);
});
it("does not return an old actor response after the session changes", async () => {
const oldSession = session("00000000-0000-4000-8000-000000000001", "a".repeat(32));
const nextSession = session("00000000-0000-4000-8000-000000000002", "b".repeat(32));
const queryClient = queryClientFor(oldSession);
let finish!: (value: string) => void;
const pending = runForCurrentCandidate(
queryClient,
oldSession,
() => new Promise<string>((resolve) => (finish = resolve)),
);
queryClient.setQueryData(getGetCurrentSessionQueryKey(), nextSession);
finish("old private response");
await expect(pending).rejects.toBeInstanceOf(CandidateSessionChangedError);
});
});
@@ -0,0 +1,40 @@
import type { QueryClient } from "@tanstack/react-query";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import type { Session } from "../../../shared/api/schemas";
export class CandidateSessionChangedError extends Error {
constructor() {
super("The candidate session changed during a privacy request.");
this.name = "CandidateSessionChangedError";
}
}
export function isCurrentCandidateSession(queryClient: QueryClient, expected: Session): boolean {
const key = getGetCurrentSessionQueryKey();
const state = queryClient.getQueryState<Session>(key);
const current = queryClient.getQueryData<Session>(key);
return Boolean(
state?.status === "success" &&
current?.account.scenario === "candidate" &&
current.account.id === expected.account.id &&
current.csrf_token === expected.csrf_token,
);
}
export async function runForCurrentCandidate<T>(
queryClient: QueryClient,
expected: Session,
operation: () => Promise<T>,
): Promise<T> {
if (!isCurrentCandidateSession(queryClient, expected)) {
throw new CandidateSessionChangedError();
}
const result = await operation();
if (!isCurrentCandidateSession(queryClient, expected)) {
throw new CandidateSessionChangedError();
}
return result;
}
@@ -0,0 +1,87 @@
.root {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.group {
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);
}
.group legend {
padding-inline: var(--space-1);
font-weight: var(--font-weight-bold);
}
.choice {
display: flex;
gap: var(--space-3);
align-items: flex-start;
width: fit-content;
max-width: 100%;
line-height: var(--line-height-body);
}
.choice input {
flex: none;
width: 1.15rem;
height: 1.15rem;
margin-top: 0.2em;
accent-color: var(--color-accent);
}
.choice input:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.help,
.current-state,
.notice,
.error,
.message {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.help {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.current-state {
font-weight: var(--font-weight-bold);
}
.notice,
.message,
.error {
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
}
.error {
border-inline-start-color: var(--color-danger);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
min-width: 0;
}
@media (width < 42rem) {
.group {
padding: var(--space-3);
}
}
@@ -0,0 +1,87 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import type { PrivacySettings } from "../../../shared/api/schemas";
import { PublicationControls, SearchStatusControl } from "./visibility-controls";
const settings: PrivacySettings = {
publication: {
state: "closed",
closed_reason: "never_published",
fields: [],
consent_id: null,
published_at: null,
version: 0,
},
search_status: {
value: "looking",
lapsed: false,
confirmed_at: "2026-10-01T00:00:00Z",
lapses_at: "2026-10-31T00:00:00Z",
version: 2,
},
hidden_organizations_total: 0,
};
describe("profile visibility controls", () => {
it("keeps explicit C2 and publication controls separate from search status", () => {
const publication = renderToStaticMarkup(
<PublicationControls
settings={settings}
c2State="inactive"
draft={{ state: "published", fields: ["categories"], expectedVersion: 0 }}
isDirty
isStale={false}
hasUnsupportedFields={false}
canSave={false}
isSaving={false}
message={null}
error={null}
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
/>,
);
const search = renderToStaticMarkup(
<SearchStatusControl
settings={settings}
isSaving={false}
message={null}
error={null}
onSetStatus={vi.fn()}
/>,
);
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2 ниже.");
expect(publication).toContain("Подтвержденная категория и уровень");
expect(publication).toContain("Самооценка по направлениям");
expect(publication).toContain('aria-disabled="true"');
expect(publication).toContain('disabled=""');
expect(search).toContain("Вы подтвердили, что ищете работу.");
expect(search).toContain("Скрыть статус поиска");
expect(search).toContain("Статус сам по себе не открывает карточку компаниям.");
});
it("keeps a stale publication draft visible and offers only an explicit reload", () => {
const markup = renderToStaticMarkup(
<PublicationControls
settings={settings}
c2State="active"
draft={{ state: "published", fields: ["self_assessment"], expectedVersion: 1 }}
isDirty
isStale
hasUnsupportedFields={false}
canSave={false}
isSaving={false}
message={null}
error={null}
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
/>,
);
expect(markup).toContain("Ваш черновик сохранен на экране.");
expect(markup).toContain('checked=""');
expect(markup).toContain("Загрузить актуальные настройки");
});
});
@@ -0,0 +1,228 @@
import { useId } from "react";
import {
cardFieldLabels,
publishableCardFields,
type C2State,
type PublicationDraft,
} from "../../../entities/candidate-view";
import type { PrivacySettings, SearchStatusUpdate } from "../../../shared/api/schemas";
import { Button, SavingStatus, Section } from "../../../shared/ui";
import styles from "./visibility-controls.module.css";
type PublicationControlsProps = {
settings: PrivacySettings;
c2State: C2State;
draft: PublicationDraft;
isDirty: boolean;
isStale: boolean;
hasUnsupportedFields: boolean;
canSave: boolean;
isSaving: boolean;
message: string | null;
error: string | null;
onDraftChange: (draft: PublicationDraft) => void;
onSave: () => void;
onReload: () => void;
};
export function PublicationControls({
settings,
c2State,
draft,
isDirty,
isStale,
hasUnsupportedFields,
canSave,
isSaving,
message,
error,
onDraftChange,
onSave,
onReload,
}: PublicationControlsProps) {
const stateId = useId();
const fieldsId = useId();
const c2Id = useId();
function toggleField(field: PublicationDraft["fields"][number], checked: boolean) {
const next = checked
? publishableCardFields.filter(
(candidate) => candidate === field || draft.fields.includes(candidate),
)
: draft.fields.filter((candidate) => candidate !== field);
onDraftChange({ ...draft, fields: [...next] });
}
return (
<Section
title="Публикация карточки"
description="C2, набор публикуемых полей и статус поиска управляются отдельно. Изменение статуса поиска не публикует карточку."
>
<div className={styles.root}>
<p className={styles["current-state"]} role="status">
Текущее состояние:{" "}
{settings.publication.state === "published" ? "опубликована" : "закрыта"}.
</p>
<fieldset className={styles.group} aria-describedby={stateId}>
<legend>Состояние карточки</legend>
<p id={stateId} className={styles.help}>
Закрытая карточка не доступна компаниям. Повторная публикация требует отдельного
действия.
</p>
<label className={styles.choice}>
<input
type="radio"
name="publication-state"
value="closed"
checked={draft.state === "closed"}
disabled={isSaving}
onChange={() => onDraftChange({ ...draft, state: "closed" })}
/>
<span>Оставить карточку закрытой</span>
</label>
<label className={styles.choice}>
<input
type="radio"
name="publication-state"
value="published"
checked={draft.state === "published"}
disabled={isSaving}
onChange={() => onDraftChange({ ...draft, state: "published" })}
/>
<span>Опубликовать выбранные поля</span>
</label>
</fieldset>
<fieldset className={styles.group} aria-describedby={fieldsId}>
<legend>Поля анонимной карточки</legend>
<p id={fieldsId} className={styles.help}>
Имя, контакты, работодатели и суммы зарплаты не публикуются. Подтвержденные категории и
самооценка показываются раздельно.
</p>
{publishableCardFields.map((field) => (
<label className={styles.choice} key={field}>
<input
type="checkbox"
checked={draft.fields.includes(field)}
disabled={isSaving}
onChange={(event) => toggleField(field, event.currentTarget.checked)}
/>
<span>{cardFieldLabels[field]}</span>
</label>
))}
</fieldset>
{hasUnsupportedFields ? (
<p className={styles.notice} role="status">
В сохраненных настройках есть поля прежнего формата. Они не показываются в карточке.
Выберите разрешенные поля или явно закройте публикацию.
</p>
) : null}
<p id={c2Id} className={styles.help}>
{c2State === "active"
? "Согласие C2 активно. Оно само по себе не включает публикацию."
: c2State === "checking"
? "Проверяем полную историю согласий C2. До завершения публикация недоступна."
: "Для публикации сначала отдельно примите согласие C2 ниже."}
</p>
{isStale ? (
<div className={styles.error} role="alert">
Настройки изменились на сервере. Ваш черновик сохранен на экране. Загрузите актуальные
настройки, чтобы начать заново.
</div>
) : null}
{error ? (
<div className={styles.error} role="alert">
{error}
</div>
) : null}
{message ? (
<p className={styles.message} role="status" aria-live="polite">
{message}
</p>
) : null}
<div className={styles.actions}>
<Button
aria-describedby={c2Id}
aria-disabled={!canSave || isSaving}
disabled={!canSave}
isBusy={isSaving}
onClick={onSave}
>
{draft.state === "closed" ? "Сохранить и закрыть карточку" : "Сохранить публикацию"}
</Button>
{isStale ? (
<Button variant="secondary" isBusy={isSaving} onClick={onReload}>
Загрузить актуальные настройки
</Button>
) : null}
<SavingStatus
state={isSaving ? "saving" : message ? "saved" : error ? "failed" : "idle"}
/>
</div>
{!isDirty && !isStale ? (
<p className={styles.help}>Нет несохраненных изменений публикации.</p>
) : null}
</div>
</Section>
);
}
type SearchStatusControlProps = {
settings: PrivacySettings;
isSaving: boolean;
message: string | null;
error: string | null;
onSetStatus: (value: SearchStatusUpdate["value"]) => void;
};
export function SearchStatusControl({
settings,
isSaving,
message,
error,
onSetStatus,
}: SearchStatusControlProps) {
const status = settings.search_status;
return (
<Section
title="Статус поиска"
description="Это заявление о поиске работы, а не согласие и не настройка публикации. Статус сам по себе не открывает карточку компаниям."
>
<div className={styles.root}>
<p className={styles["current-state"]} role="status">
{status.value === "looking"
? "Вы подтвердили, что ищете работу."
: "Вы не объявляете поиск работы."}
{status.lapsed ? " Срок подтверждения истек." : ""}
</p>
<div className={styles.actions}>
{status.value === "looking" ? (
<Button
variant="secondary"
isBusy={isSaving}
onClick={() => onSetStatus("not_looking")}
>
Скрыть статус поиска
</Button>
) : (
<Button isBusy={isSaving} onClick={() => onSetStatus("looking")}>
Подтвердить статус «Ищу»
</Button>
)}
</div>
{error ? (
<div className={styles.error} role="alert">
{error}
</div>
) : null}
{message ? (
<p className={styles.message} role="status" aria-live="polite">
{message}
</p>
) : null}
<SavingStatus state={isSaving ? "saving" : message ? "saved" : error ? "failed" : "idle"} />
</div>
</Section>
);
}