From 95b8e566c41b5936db56cc52b963b766fe9b6bad Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Thu, 8 Oct 2026 08:43:11 +0300 Subject: [PATCH] feat: add candidate privacy controls --- frontend/src/app/router/routes.test.tsx | 39 +- frontend/src/app/router/routes.tsx | 4 +- frontend/src/entities/candidate-view/index.ts | 26 + .../candidate-view/model/presentation.test.ts | 82 ++ .../candidate-view/model/presentation.ts | 271 +++++ .../candidate-view/model/publication.test.ts | 168 +++ .../candidate-view/model/query-keys.test.ts | 14 + .../candidate-view/model/query-keys.ts | 18 + .../src/features/profile-visibility/index.ts | 8 + .../model/publication-save.test.ts | 38 + .../model/publication-save.ts | 22 + .../model/session-guard.test.ts | 73 ++ .../profile-visibility/model/session-guard.ts | 40 + .../ui/visibility-controls.module.css | 87 ++ .../ui/visibility-controls.test.tsx | 87 ++ .../ui/visibility-controls.tsx | 228 ++++ frontend/src/pages/privacy/index.ts | 1 + .../pages/privacy/ui/privacy-page.module.css | 155 +++ .../pages/privacy/ui/privacy-page.test.tsx | 177 +++ .../src/pages/privacy/ui/privacy-page.tsx | 1065 +++++++++++++++++ 20 files changed, 2592 insertions(+), 11 deletions(-) create mode 100644 frontend/src/entities/candidate-view/index.ts create mode 100644 frontend/src/entities/candidate-view/model/presentation.test.ts create mode 100644 frontend/src/entities/candidate-view/model/presentation.ts create mode 100644 frontend/src/entities/candidate-view/model/publication.test.ts create mode 100644 frontend/src/entities/candidate-view/model/query-keys.test.ts create mode 100644 frontend/src/entities/candidate-view/model/query-keys.ts create mode 100644 frontend/src/features/profile-visibility/index.ts create mode 100644 frontend/src/features/profile-visibility/model/publication-save.test.ts create mode 100644 frontend/src/features/profile-visibility/model/publication-save.ts create mode 100644 frontend/src/features/profile-visibility/model/session-guard.test.ts create mode 100644 frontend/src/features/profile-visibility/model/session-guard.ts create mode 100644 frontend/src/features/profile-visibility/ui/visibility-controls.module.css create mode 100644 frontend/src/features/profile-visibility/ui/visibility-controls.test.tsx create mode 100644 frontend/src/features/profile-visibility/ui/visibility-controls.tsx create mode 100644 frontend/src/pages/privacy/index.ts create mode 100644 frontend/src/pages/privacy/ui/privacy-page.module.css create mode 100644 frontend/src/pages/privacy/ui/privacy-page.test.tsx create mode 100644 frontend/src/pages/privacy/ui/privacy-page.tsx diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index 5ecae16..6a99a3b 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -3,6 +3,7 @@ import { renderToString } from "react-dom/server"; import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom"; import { describe, expect, it } from "vitest"; import { assessmentQueryKeys } from "../../entities/assessment"; +import { candidateViewQueryKeys } from "../../entities/candidate-view"; import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent"; import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity"; import type { Session } from "../../shared/api/schemas"; @@ -55,6 +56,26 @@ async function render(path: string): Promise { } if (path.startsWith("/candidate/privacy")) { const hasMore = path.includes("history=partial"); + const actorId = "11111111-1111-4111-8111-111111111111"; + queryClient.setQueryData(candidateViewQueryKeys.settings(actorId), { + publication: { + state: "closed", + closed_reason: "never_published", + fields: [], + consent_id: null, + published_at: null, + version: 0, + }, + search_status: { + value: "not_looking", + lapsed: false, + confirmed_at: null, + lapses_at: null, + version: 0, + }, + hidden_organizations_total: 0, + }); + queryClient.setQueryData(["candidate-view", actorId, "consent-history-ready"], true); queryClient.setQueryData(getListMyConsentsQueryKey({ limit: 100 }), { pages: [ { @@ -133,7 +154,7 @@ describe("route groups", () => { ["/candidate/profile", "Профиль", "Разделы кабинета кандидата"], ["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"], ["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"], - ["/candidate/privacy", "Согласия и настройки приватности", "Разделы кабинета кандидата"], + ["/candidate/privacy", "Настройки приватности", "Разделы кабинета кандидата"], ["/candidate/assessment", "Проверка знаний", "Разделы кабинета кандидата"], [ "/candidate/assessment/01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80", @@ -235,20 +256,20 @@ describe("product readiness", () => { expect(html).toContain("Это не показатель готовности продукта"); }); - it("renders the consent settings route with server-backed history", async () => { + it("renders separate privacy controls while preparing actor-scoped consent history", async () => { const html = await renderHtml("/candidate/privacy"); - expect(html).toContain("Публикация карточки кандидата"); - expect(html).toContain("c2-2026-10-01"); - expect(html).toContain("Первая тестовая компания"); - expect(html).toContain("Электронная почта"); + expect(html).toContain("Публикация карточки"); + expect(html).toContain("Статус поиска"); + expect(html).toContain("Подготавливаем историю согласий..."); + expect(html).not.toContain("c2-2026-10-01"); + expect(html).not.toContain("Первая тестовая компания"); }); - it("does not call a purpose empty while older history pages remain", async () => { + it("does not call consent history empty before actor-scoped loading", async () => { const html = await renderHtml("/candidate/privacy?history=partial"); - expect(html).toContain("В загруженной части истории записей C3 пока нет"); - expect(html).toContain("Показать более ранние записи"); + expect(html).toContain("Подготавливаем историю согласий..."); expect(html).not.toContain("Записей C3 пока нет."); }); diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 165fe05..1946e5f 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -3,7 +3,7 @@ import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment"; import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth"; import { CandidateOnboardingPage } from "../../pages/candidate-onboarding"; import { CompanyPage } from "../../pages/company"; -import { ConsentsPage } from "../../pages/consents"; +import { PrivacyPage } from "../../pages/privacy"; import { SessionGate } from "../../entities/session"; import { NotFoundPage } from "../../pages/not-found"; import { NeedEditorPage } from "../../pages/need-editor"; @@ -84,7 +84,7 @@ export const routes: RouteObject[] = [ }, { path: paths.candidate.privacy, - element: , + element: , }, { path: paths.candidate.supportCases, element: }, { path: paths.candidate.supportNew, element: }, diff --git a/frontend/src/entities/candidate-view/index.ts b/frontend/src/entities/candidate-view/index.ts new file mode 100644 index 0000000..1af15b2 --- /dev/null +++ b/frontend/src/entities/candidate-view/index.ts @@ -0,0 +1,26 @@ +export { + cardAccessLabels, + cardFieldLabels, + buildSearchStatusSubmission, + buildPublicationSubmission, + currentC2State, + editableCardFields, + formatPrivacyDate, + hasUnsupportedPublishedFields, + isSamePublicationDraft, + organizationsAvailableToHide, + presentCandidatePreview, + publicationDraftFromSettings, + privacyEventLabels, + publishableCardFields, + specializationLabels, +} from "./model/presentation"; +export { candidateViewQueryKeys } from "./model/query-keys"; +export type { + C2State, + CandidateViewPresentation, + PublicationDraft, + PublicationSubmission, + PublishableCardField, + OrganizationReference, +} from "./model/presentation"; diff --git a/frontend/src/entities/candidate-view/model/presentation.test.ts b/frontend/src/entities/candidate-view/model/presentation.test.ts new file mode 100644 index 0000000..86aecbd --- /dev/null +++ b/frontend/src/entities/candidate-view/model/presentation.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; +import type { CardField, CardPreview } from "../../../shared/api/schemas"; +import { editableCardFields, presentCandidatePreview, publishableCardFields } from "./presentation"; + +function preview(card: NonNullable): CardPreview { + return { + state: "published", + fields: ["categories", "self_assessment", "stack", "experience", "work_formats"], + card, + generated_at: "2026-10-06T12:00:00Z", + }; +} + +describe("candidate card presentation", () => { + it("keeps confirmed categories separate from declared grades", () => { + const result = presentCandidatePreview( + preview({ + pseudonym: `cv1_${"a".repeat(43)}`, + categories: [{ specialization: "backend", grade: "junior", strength: "standard" }], + stack: ["go"], + self_assessment: [ + { + specialization: "network_engineer", + confirmation_status: "unconfirmed", + declared_grade: "middle", + }, + ], + experience_band: "1_3", + work_formats: ["remote"], + salary_compatibility: null, + }), + ); + + expect(result?.categories).toEqual([ + { + specialization: "Backend", + grade: "Junior", + strength: "Стандартное подтверждение", + }, + ]); + expect(result?.selfAssessments).toEqual([ + { + specialization: "Сетевое администрирование", + declaredGrade: "Middle", + confirmation: "Грейд не подтвержден", + }, + ]); + }); + + it("does not present a closed preview as an empty published card", () => { + expect( + presentCandidatePreview({ + state: "closed", + fields: [], + card: null, + generated_at: "2026-10-06T12:00:00Z", + }), + ).toBeNull(); + }); +}); + +describe("editable card fields", () => { + it("exposes only safe groups supported by the anonymous-card contract", () => { + const stored: CardField[] = [ + "categories", + "soft_skills", + "location", + "relocation", + "work_formats", + ]; + + expect(publishableCardFields).toEqual([ + "categories", + "self_assessment", + "stack", + "experience", + "work_formats", + "salary_compatibility", + ]); + expect(editableCardFields(stored)).toEqual(["categories", "work_formats"]); + }); +}); diff --git a/frontend/src/entities/candidate-view/model/presentation.ts b/frontend/src/entities/candidate-view/model/presentation.ts new file mode 100644 index 0000000..f674d85 --- /dev/null +++ b/frontend/src/entities/candidate-view/model/presentation.ts @@ -0,0 +1,271 @@ +import type { + CardAccess, + CardCategory, + CardField, + CardPreview, + CardSelfAssessment, + CandidateExperienceBand, + CandidateSalaryCompatibility, + CandidateWorkFormat, + ConsentRecord, + HiddenOrganization, + PrivacySettings, + PublicationUpdate, + SearchStatusUpdate, +} from "../../../shared/api/schemas"; + +export const publishableCardFields = [ + "categories", + "self_assessment", + "stack", + "experience", + "work_formats", + "salary_compatibility", +] as const satisfies readonly CardField[]; + +export type PublishableCardField = (typeof publishableCardFields)[number]; + +export type PublicationDraft = { + state: "closed" | "published"; + fields: PublishableCardField[]; + expectedVersion: number; +}; + +export type PublicationSubmission = + { ok: true; body: PublicationUpdate } | { ok: false; reason: "select_field" | "c2_required" }; + +export type OrganizationReference = { id: string; name: string }; + +export type C2State = "active" | "inactive" | "checking"; + +export function publicationDraftFromSettings(settings: PrivacySettings): PublicationDraft { + return { + state: settings.publication.state, + fields: editableCardFields(settings.publication.fields), + expectedVersion: settings.publication.version, + }; +} + +export function buildPublicationSubmission( + draft: PublicationDraft, + hasActiveC2: boolean, +): PublicationSubmission { + if (draft.state === "closed") { + return { + ok: true, + body: { + expected_version: draft.expectedVersion, + state: "closed", + fields: [], + }, + }; + } + + const fields = editableCardFields(draft.fields); + if (fields.length === 0) return { ok: false, reason: "select_field" }; + if (!hasActiveC2) return { ok: false, reason: "c2_required" }; + + return { + ok: true, + body: { + expected_version: draft.expectedVersion, + state: "published", + fields, + }, + }; +} + +export function buildSearchStatusSubmission( + settings: PrivacySettings, + value: SearchStatusUpdate["value"], +): SearchStatusUpdate { + return { expected_version: settings.search_status.version, value }; +} + +export function isSamePublicationDraft(first: PublicationDraft, second: PublicationDraft): boolean { + return ( + first.state === second.state && + first.expectedVersion === second.expectedVersion && + first.fields.length === second.fields.length && + first.fields.every((field, index) => field === second.fields[index]) + ); +} + +export function organizationsAvailableToHide( + accessRecords: readonly CardAccess[], + hiddenOrganizations: readonly HiddenOrganization[], +): OrganizationReference[] { + const hiddenIds = new Set(hiddenOrganizations.map((item) => item.organization.id)); + const visibleOrganizations = new Map(); + + for (const record of accessRecords) { + const organization = record.organization; + if ( + !organization || + hiddenIds.has(organization.id) || + visibleOrganizations.has(organization.id) + ) { + continue; + } + visibleOrganizations.set(organization.id, { + id: organization.id, + name: organization.name, + }); + } + + return [...visibleOrganizations.values()]; +} + +export function currentC2State( + records: readonly ConsentRecord[], + historyIsComplete: boolean, +): C2State { + if (records.some((record) => record.purpose === "c2" && record.state === "active")) { + return "active"; + } + return historyIsComplete ? "inactive" : "checking"; +} + +export function hasUnsupportedPublishedFields(settings: PrivacySettings): boolean { + return settings.publication.fields.some( + (field) => !publishableCardFields.includes(field as PublishableCardField), + ); +} + +export const cardFieldLabels: Readonly> = { + categories: "Подтвержденная категория и уровень", + self_assessment: "Самооценка по направлениям", + stack: "Технологии из подтвержденного профиля", + experience: "Общий опыт", + work_formats: "Форматы работы", + salary_compatibility: "Совместимость по зарплатным ожиданиям", +}; + +export const specializationLabels = { + backend: "Backend", + frontend: "Frontend", + mobile: "Мобильная разработка", + network_engineer: "Сетевое администрирование", + devops_sre: "DevOps/SRE", + data_analyst: "Аналитика данных", + ds_ml: "Data Science и машинное обучение", + information_security: "Информационная безопасность", + qa: "Тестирование", +} as const; + +const gradeLabels = { + intern: "Стажер", + junior: "Junior", + middle: "Middle", + senior: "Senior", +} as const; + +const stackLabels = { + go: "Go", + postgresql: "PostgreSQL", + kafka: "Kafka", + docker: "Docker", +} as const; + +const workFormatLabels: Readonly> = { + remote: "Удаленно", + office: "В офисе", + hybrid: "Гибридно", +}; + +const experienceBandLabels: Readonly> = { + "0_1": "До 1 года", + "1_3": "1-3 года", + "3_6": "3-6 лет", + "6_plus": "6 лет и больше", + "0_3": "0-3 года", + "3_plus": "3 года и больше", +}; + +const salaryCompatibilityLabels: Readonly> = { + compatible: "Ожидания совместимы", + not_compatible: "Ожидания не совпадают", +}; + +export type CategoryPresentation = { + specialization: string; + grade: string; + strength: string; +}; + +export type SelfAssessmentPresentation = { + specialization: string; + declaredGrade: string | null; + confirmation: string; +}; + +export type CandidateViewPresentation = { + pseudonym: string; + categories: readonly CategoryPresentation[] | null; + selfAssessments: readonly SelfAssessmentPresentation[] | null; + stack: readonly string[] | null; + experience: string | null; + workFormats: readonly string[] | null; + salaryCompatibility: string | null; +}; + +function categoryPresentation(category: CardCategory): CategoryPresentation { + return { + specialization: specializationLabels[category.specialization], + grade: gradeLabels[category.grade], + strength: + category.strength === "strong" ? "Сильное подтверждение" : "Стандартное подтверждение", + }; +} + +function selfAssessmentPresentation(item: CardSelfAssessment): SelfAssessmentPresentation { + return { + specialization: specializationLabels[item.specialization], + declaredGrade: item.declared_grade ? gradeLabels[item.declared_grade] : null, + confirmation: + item.confirmation_status === "confirmed" ? "Грейд подтвержден" : "Грейд не подтвержден", + }; +} + +export function presentCandidatePreview(preview: CardPreview): CandidateViewPresentation | null { + const card = preview.card; + if (!card) return null; + + return { + pseudonym: card.pseudonym, + categories: card.categories?.map(categoryPresentation) ?? null, + selfAssessments: card.self_assessment?.map(selfAssessmentPresentation) ?? null, + stack: card.stack?.map((tag) => stackLabels[tag]) ?? null, + experience: card.experience_band ? experienceBandLabels[card.experience_band] : null, + workFormats: card.work_formats?.map((format) => workFormatLabels[format]) ?? null, + salaryCompatibility: card.salary_compatibility + ? salaryCompatibilityLabels[card.salary_compatibility] + : null, + }; +} + +export function editableCardFields(fields: readonly CardField[]): PublishableCardField[] { + return publishableCardFields.filter((field) => fields.includes(field)); +} + +export function formatPrivacyDate(value: string): string { + return new Intl.DateTimeFormat("ru-RU", { + dateStyle: "medium", + timeStyle: "short", + }).format(new Date(value)); +} + +export const privacyEventLabels = { + publication_opened: "Профиль опубликован", + publication_changed: "Настройки публикации изменены", + publication_closed: "Публикация закрыта", + search_status_confirmed: "Подтвержден статус поиска", + search_status_cleared: "Статус поиска скрыт", + organization_hidden: "Профиль скрыт от компании", + organization_unhidden: "Профиль снова доступен компании", +} as const; + +export const cardAccessLabels = { + card_viewed: "Просмотрена карточка профиля", + contact_read: "Открыты контактные данные", +} as const; diff --git a/frontend/src/entities/candidate-view/model/publication.test.ts b/frontend/src/entities/candidate-view/model/publication.test.ts new file mode 100644 index 0000000..502efb9 --- /dev/null +++ b/frontend/src/entities/candidate-view/model/publication.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from "vitest"; +import type { ConsentRecord, PrivacySettings } from "../../../shared/api/schemas"; +import { + buildSearchStatusSubmission, + buildPublicationSubmission, + currentC2State, + hasUnsupportedPublishedFields, + isSamePublicationDraft, + organizationsAvailableToHide, + publicationDraftFromSettings, + type PublicationDraft, +} from "./presentation"; + +const settings: PrivacySettings = { + publication: { + state: "closed", + closed_reason: "never_published", + fields: [], + consent_id: null, + published_at: null, + version: 0, + }, + search_status: { + value: "not_looking", + lapsed: false, + confirmed_at: null, + lapses_at: null, + version: 0, + }, + hidden_organizations_total: 0, +}; + +function consent(purpose: ConsentRecord["purpose"], state: ConsentRecord["state"]): ConsentRecord { + return { + id: "00000000-0000-4000-8000-000000000001", + purpose, + state, + text_version: "2026-01", + source: "consent_settings", + granted_at: "2026-10-01T00:00:00Z", + revoked_at: state === "revoked" ? "2026-10-02T00:00:00Z" : null, + revocation_source: state === "revoked" ? "consent_settings" : null, + organization: null, + fields: null, + invitation_id: null, + invitation_terms_version: null, + }; +} + +describe("candidate privacy publication", () => { + it("starts from closed server state and submits only the closed field allowlist", () => { + const draft = publicationDraftFromSettings({ + ...settings, + publication: { + ...settings.publication, + state: "published", + fields: ["categories", "location", "soft_skills"], + }, + }); + + expect(draft).toEqual({ state: "published", fields: ["categories"], expectedVersion: 0 }); + expect(buildPublicationSubmission({ ...draft, expectedVersion: 4 }, true)).toEqual({ + ok: true, + body: { expected_version: 4, state: "published", fields: ["categories"] }, + }); + }); + + it("requires at least one explicit field and a separate active C2", () => { + expect( + buildPublicationSubmission({ state: "published", fields: [], expectedVersion: 0 }, true), + ).toEqual({ ok: false, reason: "select_field" }); + expect( + buildPublicationSubmission( + { state: "published", fields: ["stack"], expectedVersion: 0 }, + false, + ), + ).toEqual({ ok: false, reason: "c2_required" }); + expect( + buildPublicationSubmission({ state: "closed", fields: [], expectedVersion: 0 }, false), + ).toEqual({ ok: true, body: { expected_version: 0, state: "closed", fields: [] } }); + }); + + it("keeps publication writes pinned to the version that seeded the draft", () => { + const draft: PublicationDraft = { + state: "published", + fields: ["categories"], + expectedVersion: 3, + }; + + expect(buildPublicationSubmission({ ...draft, fields: [...draft.fields] }, true)).toEqual({ + ok: true, + body: { expected_version: 3, state: "published", fields: ["categories"] }, + }); + expect(isSamePublicationDraft(draft, { ...draft, expectedVersion: 4 })).toBe(false); + }); + + it("builds a search-status update from its own version, independent of publication", () => { + const unpublished = { + ...settings, + publication: { ...settings.publication, state: "closed" as const, version: 8 }, + search_status: { ...settings.search_status, version: 2 }, + }; + + expect(buildSearchStatusSubmission(unpublished, "looking")).toEqual({ + expected_version: 2, + value: "looking", + }); + }); + + it("offers hide actions only for organizations from access history that are not already hidden", () => { + const orgA = { id: "00000000-0000-4000-8000-000000000001", name: "Компания А" }; + const orgB = { id: "00000000-0000-4000-8000-000000000002", name: "Компания Б" }; + const accessRecords = [ + { + id: "00000000-0000-4000-8000-000000000011", + kind: "card_viewed" as const, + occurred_at: "2026-10-01T00:00:00Z", + organization: orgA, + }, + { + id: "00000000-0000-4000-8000-000000000012", + kind: "contact_read" as const, + occurred_at: "2026-10-02T00:00:00Z", + organization: orgA, + }, + { + id: "00000000-0000-4000-8000-000000000013", + kind: "card_viewed" as const, + occurred_at: "2026-10-03T00:00:00Z", + organization: null, + }, + { + id: "00000000-0000-4000-8000-000000000014", + kind: "card_viewed" as const, + occurred_at: "2026-10-04T00:00:00Z", + organization: orgB, + }, + ]; + + expect( + organizationsAvailableToHide(accessRecords, [ + { organization: orgB, hidden_at: "2026-10-05T00:00:00Z" }, + ]), + ).toEqual([orgA]); + }); + + it("does not call an incomplete consent page inactive and ignores C4 as a C2 grant", () => { + expect(currentC2State([consent("c4", "active")], false)).toBe("checking"); + expect(currentC2State([], true)).toBe("inactive"); + expect(currentC2State([consent("c2", "revoked")], true)).toBe("inactive"); + expect(currentC2State([consent("c2", "active")], false)).toBe("active"); + }); + + it("detects legacy fields without adding them to the current publication controls", () => { + expect( + hasUnsupportedPublishedFields({ + ...settings, + publication: { ...settings.publication, fields: ["soft_skills"] }, + }), + ).toBe(true); + expect( + hasUnsupportedPublishedFields({ + ...settings, + publication: { ...settings.publication, fields: ["categories"] }, + }), + ).toBe(false); + }); +}); diff --git a/frontend/src/entities/candidate-view/model/query-keys.test.ts b/frontend/src/entities/candidate-view/model/query-keys.test.ts new file mode 100644 index 0000000..2c13ca4 --- /dev/null +++ b/frontend/src/entities/candidate-view/model/query-keys.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { candidateViewQueryKeys } from "./query-keys"; + +describe("candidate view query keys", () => { + it("keeps each candidate's privacy data in a separate cache namespace", () => { + const first = "00000000-0000-4000-8000-000000000001"; + const second = "00000000-0000-4000-8000-000000000002"; + + expect(candidateViewQueryKeys.settings(first)).not.toEqual( + candidateViewQueryKeys.settings(second), + ); + expect(candidateViewQueryKeys.actor(first)).toEqual(["candidate-view", first]); + }); +}); diff --git a/frontend/src/entities/candidate-view/model/query-keys.ts b/frontend/src/entities/candidate-view/model/query-keys.ts new file mode 100644 index 0000000..4027bba --- /dev/null +++ b/frontend/src/entities/candidate-view/model/query-keys.ts @@ -0,0 +1,18 @@ +import { getListMyConsentsQueryKey } from "../../../shared/api/endpoints/consent/consent"; + +export const candidateViewQueryKeys = { + root: ["candidate-view"] as const, + actor: (accountId: string) => ["candidate-view", accountId] as const, + settings: (accountId: string) => ["candidate-view", accountId, "settings"] as const, + preview: (accountId: string) => ["candidate-view", accountId, "preview"] as const, + activeConsents: (accountId: string) => + [ + ...getListMyConsentsQueryKey({ state: "active", limit: 100 }), + "candidate-view", + accountId, + ] as const, + hiddenOrganizations: (accountId: string) => + ["candidate-view", accountId, "hidden-organizations"] as const, + privacyHistory: (accountId: string) => ["candidate-view", accountId, "privacy-history"] as const, + accessHistory: (accountId: string) => ["candidate-view", accountId, "access-history"] as const, +}; diff --git a/frontend/src/features/profile-visibility/index.ts b/frontend/src/features/profile-visibility/index.ts new file mode 100644 index 0000000..5644b85 --- /dev/null +++ b/frontend/src/features/profile-visibility/index.ts @@ -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"; diff --git a/frontend/src/features/profile-visibility/model/publication-save.test.ts b/frontend/src/features/profile-visibility/model/publication-save.test.ts new file mode 100644 index 0000000..02ae9f1 --- /dev/null +++ b/frontend/src/features/profile-visibility/model/publication-save.test.ts @@ -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); + }); +}); diff --git a/frontend/src/features/profile-visibility/model/publication-save.ts b/frontend/src/features/profile-visibility/model/publication-save.ts new file mode 100644 index 0000000..ff855c4 --- /dev/null +++ b/frontend/src/features/profile-visibility/model/publication-save.ts @@ -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"), + ); +} diff --git a/frontend/src/features/profile-visibility/model/session-guard.test.ts b/frontend/src/features/profile-visibility/model/session-guard.test.ts new file mode 100644 index 0000000..92487d3 --- /dev/null +++ b/frontend/src/features/profile-visibility/model/session-guard.test.ts @@ -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((resolve) => (finish = resolve)), + ); + + queryClient.setQueryData(getGetCurrentSessionQueryKey(), nextSession); + finish("old private response"); + + await expect(pending).rejects.toBeInstanceOf(CandidateSessionChangedError); + }); +}); diff --git a/frontend/src/features/profile-visibility/model/session-guard.ts b/frontend/src/features/profile-visibility/model/session-guard.ts new file mode 100644 index 0000000..a56a3da --- /dev/null +++ b/frontend/src/features/profile-visibility/model/session-guard.ts @@ -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(key); + const current = queryClient.getQueryData(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( + queryClient: QueryClient, + expected: Session, + operation: () => Promise, +): Promise { + if (!isCurrentCandidateSession(queryClient, expected)) { + throw new CandidateSessionChangedError(); + } + + const result = await operation(); + if (!isCurrentCandidateSession(queryClient, expected)) { + throw new CandidateSessionChangedError(); + } + + return result; +} diff --git a/frontend/src/features/profile-visibility/ui/visibility-controls.module.css b/frontend/src/features/profile-visibility/ui/visibility-controls.module.css new file mode 100644 index 0000000..a05afca --- /dev/null +++ b/frontend/src/features/profile-visibility/ui/visibility-controls.module.css @@ -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); + } +} diff --git a/frontend/src/features/profile-visibility/ui/visibility-controls.test.tsx b/frontend/src/features/profile-visibility/ui/visibility-controls.test.tsx new file mode 100644 index 0000000..aea2298 --- /dev/null +++ b/frontend/src/features/profile-visibility/ui/visibility-controls.test.tsx @@ -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( + , + ); + const search = renderToStaticMarkup( + , + ); + + 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( + , + ); + + expect(markup).toContain("Ваш черновик сохранен на экране."); + expect(markup).toContain('checked=""'); + expect(markup).toContain("Загрузить актуальные настройки"); + }); +}); diff --git a/frontend/src/features/profile-visibility/ui/visibility-controls.tsx b/frontend/src/features/profile-visibility/ui/visibility-controls.tsx new file mode 100644 index 0000000..763a57c --- /dev/null +++ b/frontend/src/features/profile-visibility/ui/visibility-controls.tsx @@ -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 ( +
+
+

+ Текущее состояние:{" "} + {settings.publication.state === "published" ? "опубликована" : "закрыта"}. +

+
+ Состояние карточки +

+ Закрытая карточка не доступна компаниям. Повторная публикация требует отдельного + действия. +

+ + +
+ +
+ Поля анонимной карточки +

+ Имя, контакты, работодатели и суммы зарплаты не публикуются. Подтвержденные категории и + самооценка показываются раздельно. +

+ {publishableCardFields.map((field) => ( + + ))} +
+ + {hasUnsupportedFields ? ( +

+ В сохраненных настройках есть поля прежнего формата. Они не показываются в карточке. + Выберите разрешенные поля или явно закройте публикацию. +

+ ) : null} +

+ {c2State === "active" + ? "Согласие C2 активно. Оно само по себе не включает публикацию." + : c2State === "checking" + ? "Проверяем полную историю согласий C2. До завершения публикация недоступна." + : "Для публикации сначала отдельно примите согласие C2 ниже."} +

+ {isStale ? ( +
+ Настройки изменились на сервере. Ваш черновик сохранен на экране. Загрузите актуальные + настройки, чтобы начать заново. +
+ ) : null} + {error ? ( +
+ {error} +
+ ) : null} + {message ? ( +

+ {message} +

+ ) : null} +
+ + {isStale ? ( + + ) : null} + +
+ {!isDirty && !isStale ? ( +

Нет несохраненных изменений публикации.

+ ) : null} +
+
+ ); +} + +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 ( +
+
+

+ {status.value === "looking" + ? "Вы подтвердили, что ищете работу." + : "Вы не объявляете поиск работы."} + {status.lapsed ? " Срок подтверждения истек." : ""} +

+
+ {status.value === "looking" ? ( + + ) : ( + + )} +
+ {error ? ( +
+ {error} +
+ ) : null} + {message ? ( +

+ {message} +

+ ) : null} + +
+
+ ); +} diff --git a/frontend/src/pages/privacy/index.ts b/frontend/src/pages/privacy/index.ts new file mode 100644 index 0000000..cd7a7aa --- /dev/null +++ b/frontend/src/pages/privacy/index.ts @@ -0,0 +1 @@ +export { PrivacyPage } from "./ui/privacy-page"; diff --git a/frontend/src/pages/privacy/ui/privacy-page.module.css b/frontend/src/pages/privacy/ui/privacy-page.module.css new file mode 100644 index 0000000..9c2f73c --- /dev/null +++ b/frontend/src/pages/privacy/ui/privacy-page.module.css @@ -0,0 +1,155 @@ +.preview, +.organization-columns { + display: grid; + gap: var(--space-5); +} + +.preview-alias { + margin: 0; + font-size: 1.05rem; +} + +.note { + margin: 0.75rem 0 0; + color: var(--color-text-secondary); + font-size: 0.925rem; + line-height: 1.55; +} + +.preview-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-4); +} + +.preview-grid section, +.organization-columns section { + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-radius: var(--radius-m); + background: var(--color-surface); +} + +.preview-grid h3, +.organization-columns h3 { + margin: 0 0 var(--space-3); + font-size: 1rem; +} + +.preview-grid ul { + margin: 0; + padding-inline-start: 1.25rem; +} + +.preview-facts { + display: grid; + grid-template-columns: minmax(9rem, auto) minmax(0, 1fr); + gap: 0.45rem 1rem; + margin: 0; +} + +.preview-facts dt { + color: var(--color-text-secondary); +} + +.preview-facts dd { + min-width: 0; + margin: 0; + overflow-wrap: anywhere; +} + +.organization-columns { + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; +} + +.organization-list, +.history-list { + display: grid; + gap: var(--space-3); + margin: 0; + padding: 0; + list-style: none; +} + +.organization-list li, +.history-list li { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--space-2) var(--space-4); + padding-block: var(--space-3); + border-block-end: var(--line-thin) solid var(--color-divider); +} + +.organization-list li > div, +.history-list li { + min-width: 0; +} + +.organization-list li > div { + display: grid; + gap: 0.25rem; +} + +.organization-list time, +.history-list time, +.history-list span { + color: var(--color-text-secondary); + font-size: 0.9rem; +} + +.history-list li { + justify-content: start; +} + +.history-list strong, +.history-list span { + overflow-wrap: anywhere; +} + +.preview-grid li + li { + margin-block-start: 0.4rem; +} + +.pagination { + display: grid; + justify-items: start; + gap: var(--space-2); + margin-block-start: var(--space-3); +} + +.pagination .note { + margin: 0; +} + +.error { + margin-block-start: var(--space-3); + padding: var(--space-3); + border-inline-start: var(--line-strong) solid var(--color-danger); + background: var(--color-surface); + color: var(--color-text); +} + +.message { + margin-block-start: var(--space-3); + color: var(--color-text-secondary); +} + +@media (width < 48rem) { + .preview-grid, + .organization-columns { + grid-template-columns: minmax(0, 1fr); + } + + .preview-facts { + grid-template-columns: minmax(0, 1fr); + gap: 0.25rem; + } + + .preview-facts dd + dt { + margin-block-start: 0.75rem; + } +} diff --git a/frontend/src/pages/privacy/ui/privacy-page.test.tsx b/frontend/src/pages/privacy/ui/privacy-page.test.tsx new file mode 100644 index 0000000..5a65caf --- /dev/null +++ b/frontend/src/pages/privacy/ui/privacy-page.test.tsx @@ -0,0 +1,177 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; +import type { + CardAccess, + CardPreview, + HiddenOrganization, + PrivacyEventList, +} from "../../../shared/api/schemas"; +import { + CardAccessHistory, + OrganizationVisibility, + PrivacyHistory, + PrivacyPreview, +} from "./privacy-page"; + +const orgA = { + id: "00000000-0000-4000-8000-000000000001", + name: "Компания А", +}; +const orgB = { + id: "00000000-0000-4000-8000-000000000002", + name: "Компания Б", +}; + +function accessRecord( + id: string, + organization: typeof orgA | null, + kind: CardAccess["kind"] = "card_viewed", +): CardAccess { + return { + id, + kind, + occurred_at: "2026-10-01T10:00:00Z", + organization, + }; +} + +function hiddenOrganization(organization: typeof orgA): HiddenOrganization { + return { organization, hidden_at: "2026-10-02T10:00:00Z" }; +} + +describe("privacy page sections", () => { + it("keeps the owner preview alias separate from organization aliases and category evidence", () => { + const preview: CardPreview = { + state: "published", + fields: ["categories", "self_assessment"], + card: { + pseudonym: `cv1_${"a".repeat(43)}`, + categories: [{ specialization: "backend", grade: "junior", strength: "standard" }], + stack: null, + self_assessment: [ + { + specialization: "frontend", + confirmation_status: "unconfirmed", + declared_grade: "middle", + }, + ], + experience_band: null, + work_formats: null, + salary_compatibility: null, + }, + generated_at: "2026-10-03T10:00:00Z", + }; + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("Предварительный псевдоним"); + expect(markup).toContain("Это отдельный псевдоним предпросмотра"); + expect(markup).toContain("Подтвержденные категории"); + expect(markup).toContain("Backend: Junior"); + expect(markup).toContain("Самооценка по направлениям"); + expect(markup).toContain("Frontend: Middle; грейд не подтвержден"); + }); + + it("does not offer hide actions until the hidden list is fully loaded", () => { + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("Компания Б"); + expect(markup).toContain("Снова разрешить просмотр"); + expect(markup).toContain( + "Список действий появится после загрузки всех страниц скрытых компаний", + ); + expect(markup).not.toContain("Скрыть профиль"); + expect(markup).toContain("не восстанавливает C4"); + }); + + it("shows only organizations from access history as hide candidates", () => { + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain("Компания А"); + expect(markup).toContain("Компания Б"); + expect(markup).toContain("Скрыть профиль"); + expect(markup).toContain("Загрузить ранние записи"); + expect(markup).toContain("Снятие скрытия само по себе не восстанавливает C4"); + }); + + it("does not describe a partial history page as the complete history", () => { + const event: PrivacyEventList["items"][number] = { + id: "00000000-0000-4000-8000-000000000021", + kind: "publication_opened", + occurred_at: "2026-10-04T10:00:00Z", + fields: ["categories"], + consent_id: "00000000-0000-4000-8000-000000000031", + organization: null, + }; + const privacyMarkup = renderToStaticMarkup( + , + ); + const accessMarkup = renderToStaticMarkup( + , + ); + + expect(privacyMarkup).toContain("Показана только загруженная часть истории"); + expect(privacyMarkup).not.toContain("Показана вся история"); + expect(accessMarkup).toContain("Показана только загруженная часть истории"); + expect(accessMarkup).not.toContain("Показана вся история"); + }); +}); diff --git a/frontend/src/pages/privacy/ui/privacy-page.tsx b/frontend/src/pages/privacy/ui/privacy-page.tsx new file mode 100644 index 0000000..647cb7d --- /dev/null +++ b/frontend/src/pages/privacy/ui/privacy-page.tsx @@ -0,0 +1,1065 @@ +import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; +import { ConsentManagement } from "../../../features/consent-management"; +import { PublicationControls, SearchStatusControl } from "../../../features/profile-visibility"; +import { + buildPublicationSubmission, + buildSearchStatusSubmission, + cardAccessLabels, + cardFieldLabels, + currentC2State, + formatPrivacyDate, + hasUnsupportedPublishedFields, + isSamePublicationDraft, + organizationsAvailableToHide, + presentCandidatePreview, + privacyEventLabels, + publicationDraftFromSettings, + type OrganizationReference, + type PublicationDraft, +} from "../../../entities/candidate-view"; +import { + CandidateSessionChangedError, + isPublicationSaveAllowed, + isCurrentCandidateSession, + runForCurrentCandidate, +} from "../../../features/profile-visibility"; +import { + getGetCurrentSessionQueryKey, + useGetCurrentSession, +} from "../../../shared/api/endpoints/identity/identity"; +import { + getListMyConsentsQueryKey, + listMyConsents, +} from "../../../shared/api/endpoints/consent/consent"; +import { + getMyCardPreview, + getMyPrivacySettings, + hideOrganization, + listMyCardAccessHistory, + listMyHiddenOrganizations, + listMyPrivacyHistory, + setMyPublication, + setMySearchStatus, + unhideOrganization, +} from "../../../shared/api/endpoints/privacy/privacy"; +import type { Session } from "../../../shared/api/schemas"; +import type { + CardAccess, + CardPreview, + HiddenOrganization, + PrivacyEventList, + PrivacySettings, +} from "../../../shared/api/schemas"; +import { ApiRequestError } from "../../../shared/api"; +import { + Button, + EmptyState, + ErrorState, + ForbiddenState, + LoadingState, + Page, + Section, +} from "../../../shared/ui"; +import { candidateViewQueryKeys } from "../../../entities/candidate-view"; +import styles from "./privacy-page.module.css"; + +const pageSize = 100; +const privateQueryOptions = { + gcTime: 0, + staleTime: 0, + retry: false, + refetchOnMount: "always" as const, + refetchOnWindowFocus: "always" as const, +}; + +type PageAction = "publication" | "search" | `hide:${string}` | `unhide:${string}`; +type FeedbackScope = "publication" | "search" | "organization"; + +function feedbackScopeForAction(action: PageAction): FeedbackScope { + if (action === "publication" || action === "search") return action; + return "organization"; +} + +function authorizationFailure(error: unknown): boolean { + return error instanceof ApiRequestError && (error.status === 401 || error.status === 403); +} + +function actionErrorMessage(error: unknown): string { + if (error instanceof CandidateSessionChangedError) { + return "Сессия изменилась. Загрузите приватные настройки заново."; + } + if (error instanceof ApiRequestError && error.status === 412) { + return "Настройки изменились в другом запросе. Черновик сохранен на экране; загрузите текущие настройки перед повтором."; + } + if (error instanceof ApiRequestError && error.status === 429) { + return "Сервер временно ограничил изменения. Состояние не изменено; попробуйте позже."; + } + if (error instanceof ApiRequestError && error.status === 404) { + return "Компания больше не доступна в истории. Обновите списки и выберите компанию заново."; + } + if (error instanceof ApiRequestError && error.status === 409) { + return "Состояние изменилось на сервере. Обновите настройки перед повтором."; + } + return "Не удалось сохранить изменение. Проверьте текущее состояние и повторите запрос."; +} + +function clearCandidateQueries( + queryClient: ReturnType, + actor: Session, +): void { + queryClient.removeQueries({ queryKey: candidateViewQueryKeys.actor(actor.account.id) }); + queryClient.removeQueries({ queryKey: candidateViewQueryKeys.activeConsents(actor.account.id) }); + queryClient.removeQueries({ queryKey: getListMyConsentsQueryKey() }); +} + +function useConsentHistoryReady( + queryClient: ReturnType, + actorId: string | null, +): boolean { + const key = useMemo( + () => ["candidate-view", actorId ?? "no-candidate-session", "consent-history-ready"] as const, + [actorId], + ); + const serializedKey = JSON.stringify(key); + const subscribe = useCallback( + (notify: () => void) => + queryClient.getQueryCache().subscribe((event) => { + if (JSON.stringify(event.query.queryKey) === serializedKey) notify(); + }), + [queryClient, serializedKey], + ); + const getSnapshot = useCallback( + () => queryClient.getQueryData(key) === true, + [key, queryClient], + ); + + useEffect(() => { + if (!actorId || queryClient.getQueryData(key) === true) return; + queryClient.removeQueries({ + queryKey: getListMyConsentsQueryKey({ limit: pageSize }), + exact: true, + }); + queryClient.setQueryData(key, true); + }, [actorId, key, queryClient]); + + return useSyncExternalStore(subscribe, getSnapshot, () => false); +} + +export function PrivacyPreview({ + preview, + isLoading, + error, + onRetry, +}: { + preview: CardPreview | undefined; + isLoading: boolean; + error: unknown; + onRetry: () => void; +}) { + if (isLoading && !preview) return ; + if (error) + return ( + + ); + if (!preview) return ; + + const card = presentCandidatePreview(preview); + if (!card) { + return ( + + ); + } + + return ( +
+

+ Предварительный псевдоним: {card.pseudonym} +

+

+ Это отдельный псевдоним предпросмотра. В каждой организации используется свой псевдоним, а + ее фильтры и проверка размера группы могут дополнительно скрыть или обобщить данные. +

+
+
+

Подтвержденные категории

+ {card.categories?.length ? ( +
    + {card.categories.map((category) => ( +
  • + {category.specialization}: {category.grade}, {category.strength.toLowerCase()} +
  • + ))} +
+ ) : ( +

Подтвержденных категорий пока нет.

+ )} +
+
+

Самооценка по направлениям

+ {card.selfAssessments?.length ? ( +
    + {card.selfAssessments.map((item) => ( +
  • + {item.specialization}: {item.declaredGrade ?? "уровень не указан"};{" "} + {item.confirmation.toLowerCase()} +
  • + ))} +
+ ) : ( +

Самооценка не опубликована или отсутствует.

+ )} +
+
+

Другие выбранные группы

+
+ {card.stack ? ( + <> +
Технологии
+
{card.stack.join(", ") || "Нет данных"}
+ + ) : null} + {card.experience ? ( + <> +
Общий опыт
+
{card.experience}
+ + ) : null} + {card.workFormats ? ( + <> +
Форматы работы
+
{card.workFormats.join(", ") || "Нет данных"}
+ + ) : null} + {card.salaryCompatibility ? ( + <> +
Совместимость ожиданий
+
{card.salaryCompatibility}
+ + ) : null} + {!card.stack && !card.experience && !card.workFormats && !card.salaryCompatibility ? ( +
Другие группы не содержат значений.
+ ) : null} +
+
+
+
+ ); +} + +function PaginationControl({ + isLoaded, + hasMore, + isFetching, + onLoad, +}: { + isLoaded: boolean; + hasMore: boolean; + isFetching: boolean; + onLoad: () => void; +}) { + if (!isLoaded) return null; + if (!hasMore) return

Показана вся история.

; + return ( +
+

+ Показана только загруженная часть истории. Ранние записи доступны отдельно. +

+ +
+ ); +} + +export function OrganizationVisibility({ + accessRecords, + accessLoading, + accessError, + accessHasMore, + accessFetching, + onLoadAccess, + hiddenOrganizations, + hiddenLoading, + hiddenError, + hiddenHasMore, + hiddenFetching, + onLoadHidden, + pendingAction, + actionError, + actionMessage, + onHide, + onUnhide, +}: { + accessRecords: readonly CardAccess[]; + accessLoading: boolean; + accessError: unknown; + accessHasMore: boolean; + accessFetching: boolean; + onLoadAccess: () => void; + hiddenOrganizations: readonly HiddenOrganization[]; + hiddenLoading: boolean; + hiddenError: unknown; + hiddenHasMore: boolean; + hiddenFetching: boolean; + onLoadHidden: () => void; + pendingAction: PageAction | null; + actionError: string | null; + actionMessage: string | null; + onHide: (organization: OrganizationReference) => void; + onUnhide: (organization: OrganizationReference) => void; +}) { + const canChooseHiddenOrganizations = !hiddenHasMore && !hiddenError && !hiddenLoading; + const hideableOrganizations = canChooseHiddenOrganizations + ? organizationsAvailableToHide(accessRecords, hiddenOrganizations) + : []; + + return ( +
+
+
+

Профиль скрыт от компаний

+ {hiddenLoading && hiddenOrganizations.length === 0 ? ( + + ) : hiddenError ? ( + + ) : hiddenOrganizations.length === 0 && !hiddenHasMore ? ( + + ) : ( +
    + {hiddenOrganizations.map((entry) => ( +
  • +
    + {entry.organization.name} + +
    + +
  • + ))} +
+ )} + 0 || !hiddenLoading)} + hasMore={hiddenHasMore} + isFetching={hiddenFetching} + onLoad={onLoadHidden} + /> +
+ +
+

Скрыть профиль от организации

+ {!canChooseHiddenOrganizations ? ( +

+ Список действий появится после загрузки всех страниц скрытых компаний и проверки, что + выбранная организация еще не скрыта. +

+ ) : accessLoading && accessRecords.length === 0 ? ( + + ) : accessError ? ( + + ) : hideableOrganizations.length === 0 ? ( + + ) : ( +
    + {hideableOrganizations.map((organization) => ( +
  • + {organization.name} + +
  • + ))} +
+ )} + 0 || !accessLoading)} + hasMore={accessHasMore} + isFetching={accessFetching} + onLoad={onLoadAccess} + /> +
+
+

+ Скрытие закрывает будущие чтения этой организации и закрывает действующий контактный доступ + в рамках серверной политики. Снятие скрытия само по себе не восстанавливает C4 или доступ к + контактам: для нового доступа потребуется отдельное действующее согласие. +

+ {actionError ? ( +
+ {actionError} +
+ ) : null} + {actionMessage ? ( +

+ {actionMessage} +

+ ) : null} +
+ ); +} + +export function PrivacyHistory({ + events, + isLoading, + error, + hasMore, + isFetching, + onLoad, +}: { + events: PrivacyEventList["items"]; + isLoading: boolean; + error: unknown; + hasMore: boolean; + isFetching: boolean; + onLoad: () => void; +}) { + return ( +
+ {isLoading && events.length === 0 ? ( + + ) : error ? ( + + ) : events.length === 0 && !hasMore ? ( + + ) : ( +
    + {events.map((event) => ( +
  1. + {privacyEventLabels[event.kind]} + + {event.organization ? {event.organization.name} : null} + {event.fields ? ( + + {event.fields.length === 0 + ? "Поля публикации закрыты" + : `Поля: ${event.fields + .map((field) => + field in cardFieldLabels + ? cardFieldLabels[field as keyof typeof cardFieldLabels] + : "ранее сохраненное поле", + ) + .join(", ")}`} + + ) : null} +
  2. + ))} +
+ )} + 0 || !isLoading)} + hasMore={hasMore} + isFetching={isFetching} + onLoad={onLoad} + /> +
+ ); +} + +export function CardAccessHistory({ + records, + isLoading, + error, + hasMore, + isFetching, + onLoad, +}: { + records: readonly CardAccess[]; + isLoading: boolean; + error: unknown; + hasMore: boolean; + isFetching: boolean; + onLoad: () => void; +}) { + return ( +
+ {isLoading && records.length === 0 ? ( + + ) : error ? ( + + ) : records.length === 0 && !hasMore ? ( + + ) : ( +
    + {records.map((record) => ( +
  1. + {cardAccessLabels[record.kind]} + + {record.organization?.name ?? "Компания недоступна"} +
  2. + ))} +
+ )} + 0 || !isLoading)} + hasMore={hasMore} + isFetching={isFetching} + onLoad={onLoad} + /> +
+ ); +} + +export function PrivacyPage() { + const queryClient = useQueryClient(); + const session = useGetCurrentSession({ query: { retry: false } }); + const actor = + session.isSuccess && session.data?.account.scenario === "candidate" ? session.data : null; + const actorId = actor?.account.id ?? null; + const sessionReady = actor !== null && !session.isFetching && !session.isError; + const [privateAccessLost, setPrivateAccessLost] = useState(false); + const [pendingAction, setPendingAction] = useState(null); + const [actionError, setActionError] = useState(null); + const [actionMessage, setActionMessage] = useState(null); + const [feedbackScope, setFeedbackScope] = useState("publication"); + const [draftState, setDraftState] = useState<{ actorId: string; value: PublicationDraft } | null>( + null, + ); + const previousActorId = useRef(null); + const previousC2State = useRef>("checking"); + + const handleAuthorizationFailure = useCallback( + (error: unknown, expected: Session) => { + if (!authorizationFailure(error)) return; + const current = isCurrentCandidateSession(queryClient, expected); + clearCandidateQueries(queryClient, expected); + if (!current) return; + if ( + error instanceof ApiRequestError && + error.status === 403 && + error.code !== "csrf_check_failed" + ) { + setPrivateAccessLost(true); + } + void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() }); + }, + [queryClient], + ); + + const runGuarded = useCallback( + async (expected: Session | null, operation: () => Promise): Promise => { + if (!expected) throw new CandidateSessionChangedError(); + try { + return await runForCurrentCandidate(queryClient, expected, operation); + } catch (error: unknown) { + handleAuthorizationFailure(error, expected); + throw error; + } + }, + [handleAuthorizationFailure, queryClient], + ); + + useEffect(() => { + const previous = previousActorId.current; + if (previous && previous !== actorId) { + queryClient.removeQueries({ queryKey: candidateViewQueryKeys.actor(previous) }); + queryClient.removeQueries({ queryKey: candidateViewQueryKeys.activeConsents(previous) }); + setDraftState(null); + setPrivateAccessLost(false); + setActionError(null); + setActionMessage(null); + } + previousActorId.current = actorId; + }, [actorId, queryClient]); + const consentHistoryReady = useConsentHistoryReady(queryClient, actorId); + + const settingsKey = useMemo( + () => candidateViewQueryKeys.settings(actorId ?? "no-candidate-session"), + [actorId], + ); + const previewKey = useMemo( + () => candidateViewQueryKeys.preview(actorId ?? "no-candidate-session"), + [actorId], + ); + const settingsQuery = useQuery({ + queryKey: settingsKey, + queryFn: ({ signal }) => runGuarded(actor, () => getMyPrivacySettings({ signal })), + enabled: sessionReady && !privateAccessLost, + ...privateQueryOptions, + }); + const previewQuery = useQuery({ + queryKey: previewKey, + queryFn: ({ signal }) => runGuarded(actor, () => getMyCardPreview({ signal })), + enabled: sessionReady && !privateAccessLost, + ...privateQueryOptions, + }); + const activeConsents = useInfiniteQuery({ + queryKey: candidateViewQueryKeys.activeConsents(actorId ?? "no-candidate-session"), + initialPageParam: undefined as string | undefined, + queryFn: ({ pageParam, signal }) => + runGuarded(actor, () => + listMyConsents( + { state: "active", limit: pageSize, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal }, + ), + ), + getNextPageParam: (lastPage) => + lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, + enabled: sessionReady && !privateAccessLost, + ...privateQueryOptions, + }); + const hiddenOrganizationsQuery = useInfiniteQuery({ + queryKey: candidateViewQueryKeys.hiddenOrganizations(actorId ?? "no-candidate-session"), + initialPageParam: undefined as string | undefined, + queryFn: ({ pageParam, signal }) => + runGuarded(actor, () => + listMyHiddenOrganizations( + { limit: pageSize, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal }, + ), + ), + getNextPageParam: (lastPage) => + lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, + enabled: sessionReady && !privateAccessLost, + ...privateQueryOptions, + }); + const privacyHistory = useInfiniteQuery({ + queryKey: candidateViewQueryKeys.privacyHistory(actorId ?? "no-candidate-session"), + initialPageParam: undefined as string | undefined, + queryFn: ({ pageParam, signal }) => + runGuarded(actor, () => + listMyPrivacyHistory( + { limit: pageSize, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal }, + ), + ), + getNextPageParam: (lastPage) => + lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, + enabled: sessionReady && !privateAccessLost, + ...privateQueryOptions, + }); + const accessHistory = useInfiniteQuery({ + queryKey: candidateViewQueryKeys.accessHistory(actorId ?? "no-candidate-session"), + initialPageParam: undefined as string | undefined, + queryFn: ({ pageParam, signal }) => + runGuarded(actor, () => + listMyCardAccessHistory( + { limit: pageSize, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal }, + ), + ), + getNextPageParam: (lastPage) => + lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, + enabled: sessionReady && !privateAccessLost, + ...privateQueryOptions, + }); + + const settings = settingsQuery.data; + const activeConsentRecords = activeConsents.data?.pages.flatMap((page) => page.items) ?? []; + const c2State = + activeConsents.isPending || activeConsents.isFetching || activeConsents.isError + ? "checking" + : currentC2State(activeConsentRecords, !activeConsents.hasNextPage); + const draft = + actor && draftState?.actorId === actor.account.id + ? draftState.value + : settings + ? publicationDraftFromSettings(settings) + : null; + const publicationSettings = settings ? publicationDraftFromSettings(settings) : null; + const draftIsDirty = Boolean( + draft && publicationSettings && !isSamePublicationDraft(draft, publicationSettings), + ); + const draftIsStale = Boolean( + draft && settings && draft.expectedVersion !== settings.publication.version, + ); + const publicationCanSave = isPublicationSaveAllowed({ + sessionReady, + draft, + isDirty: draftIsDirty, + isStale: draftIsStale, + consentHistoryFailed: activeConsents.isError, + c2State, + }); + const publicationIsBusy = pendingAction !== null || settingsQuery.isFetching; + const accessRecords = useMemo( + () => accessHistory.data?.pages.flatMap((page) => page.items) ?? [], + [accessHistory.data], + ); + const hiddenOrganizations = useMemo( + () => hiddenOrganizationsQuery.data?.pages.flatMap((page) => page.items) ?? [], + [hiddenOrganizationsQuery.data], + ); + const privacyEvents = useMemo( + () => privacyHistory.data?.pages.flatMap((page) => page.items) ?? [], + [privacyHistory.data], + ); + + useEffect(() => { + const previous = previousC2State.current; + previousC2State.current = c2State; + if (previous !== "active" || c2State !== "inactive" || !actor) return; + + queryClient.removeQueries({ queryKey: previewKey }); + void queryClient + .invalidateQueries({ queryKey: settingsKey }, { throwOnError: true }) + .then(() => { + if (!isCurrentCandidateSession(queryClient, actor)) return; + const latest = queryClient.getQueryData(settingsKey); + if (latest?.publication.state === "closed") { + setDraftState({ actorId: actor.account.id, value: publicationDraftFromSettings(latest) }); + } + }) + .catch(() => undefined); + }, [actor, c2State, previewKey, queryClient, settingsKey]); + + const canShowConsentManagement = actorId !== null && consentHistoryReady; + const csrfRequest = actor ? { headers: { "X-CSRF-Token": actor.csrf_token } } : undefined; + + async function refreshAfterChange(): Promise { + const keys = [ + settingsKey, + previewKey, + candidateViewQueryKeys.hiddenOrganizations(actorId ?? "no-candidate-session"), + candidateViewQueryKeys.privacyHistory(actorId ?? "no-candidate-session"), + candidateViewQueryKeys.accessHistory(actorId ?? "no-candidate-session"), + ]; + for (const queryKey of keys) { + await queryClient.invalidateQueries({ queryKey }, { throwOnError: true }); + } + } + + async function performAction( + action: PageAction, + operation: (currentActor: Session) => Promise, + onAccepted?: (result: T) => void, + successMessage?: string, + ): Promise { + if (!actor || !csrfRequest || pendingAction) return; + setPendingAction(action); + setFeedbackScope(feedbackScopeForAction(action)); + setActionError(null); + setActionMessage(null); + let accepted = false; + try { + const result = await runGuarded(actor, () => operation(actor)); + accepted = true; + if (!isCurrentCandidateSession(queryClient, actor)) return; + onAccepted?.(result); + await refreshAfterChange(); + if (!isCurrentCandidateSession(queryClient, actor)) return; + setActionMessage(successMessage ?? "Изменение сохранено. Проверьте обновленное состояние."); + } catch (error: unknown) { + if (!isCurrentCandidateSession(queryClient, actor)) return; + setActionError( + accepted + ? "Запрос принят, но не удалось обновить данные. Перезагрузите страницу, чтобы проверить серверное состояние." + : actionErrorMessage(error), + ); + if (error instanceof ApiRequestError && error.status === 412) { + void settingsQuery.refetch(); + } + } finally { + if (isCurrentCandidateSession(queryClient, actor)) setPendingAction(null); + } + } + + async function savePublication(): Promise { + if (!settings || !draft || !publicationCanSave || publicationIsBusy) return; + const submission = buildPublicationSubmission(draft, c2State === "active"); + if (!submission.ok) { + setFeedbackScope("publication"); + setActionError( + submission.reason === "c2_required" + ? "Сначала примите согласие C2 отдельно. Это действие не включает публикацию." + : "Выберите хотя бы одну группу полей или явно закройте карточку.", + ); + return; + } + await performAction( + "publication", + (currentActor) => + setMyPublication(submission.body, { + headers: { "X-CSRF-Token": currentActor.csrf_token }, + }), + (publication) => { + queryClient.setQueryData(settingsKey, (current) => + current ? { ...current, publication } : current, + ); + if (actor) { + setDraftState({ + actorId: actor.account.id, + value: publicationDraftFromSettings({ ...settings, publication }), + }); + } + }, + "Публикация обновлена. Проверьте предварительный просмотр.", + ); + } + + async function reloadPublicationSettings(): Promise { + if (!actor || !isCurrentCandidateSession(queryClient, actor)) return; + setFeedbackScope("publication"); + setActionError(null); + try { + const result = await settingsQuery.refetch(); + if (!isCurrentCandidateSession(queryClient, actor) || !result.data || result.isError) return; + setDraftState({ + actorId: actor.account.id, + value: publicationDraftFromSettings(result.data), + }); + setActionMessage("Загружены актуальные настройки публикации."); + } catch { + if (isCurrentCandidateSession(queryClient, actor)) { + setActionError("Не удалось загрузить актуальные настройки. Черновик сохранен на экране."); + } + } + } + + async function setSearchStatus(value: "looking" | "not_looking"): Promise { + if (!settings) return; + const body = buildSearchStatusSubmission(settings, value); + await performAction( + "search", + (currentActor) => + setMySearchStatus(body, { headers: { "X-CSRF-Token": currentActor.csrf_token } }), + (searchStatus) => { + queryClient.setQueryData(settingsKey, (current) => + current ? { ...current, search_status: searchStatus } : current, + ); + }, + "Статус поиска обновлен. Настройки публикации не изменены.", + ); + } + + function hideFromOrganization(organization: OrganizationReference): void { + const stillAllowed = organizationsAvailableToHide(accessRecords, hiddenOrganizations).some( + (candidate) => candidate.id === organization.id, + ); + if (!stillAllowed || hiddenOrganizationsQuery.hasNextPage || hiddenOrganizationsQuery.isError) { + setFeedbackScope("organization"); + setActionError("Обновите историю доступа и список скрытых компаний перед этим действием."); + return; + } + void performAction( + `hide:${organization.id}`, + (currentActor) => + hideOrganization(organization.id, { headers: { "X-CSRF-Token": currentActor.csrf_token } }), + undefined, + `Профиль скрыт от компании «${organization.name}». Сервер закрывает действующий доступ к контактам.`, + ); + } + + function unhideOrganizationForCandidate(organization: OrganizationReference): void { + if (!hiddenOrganizations.some((entry) => entry.organization.id === organization.id)) { + setFeedbackScope("organization"); + setActionError("Обновите список скрытых компаний перед этим действием."); + return; + } + void performAction( + `unhide:${organization.id}`, + (currentActor) => + unhideOrganization(organization.id, { + headers: { "X-CSRF-Token": currentActor.csrf_token }, + }), + undefined, + `Скрытие компании «${organization.name}» снято. Действующий C4 не восстанавливается.`, + ); + } + + if (session.isError) { + return ( + + void session.refetch()} + title="Не удалось проверить сессию" + /> + + ); + } + if (session.isPending || session.isFetching) + return ; + if (session.data?.account.scenario !== "candidate") { + return ( + + + + ); + } + if (privateAccessLost) { + return ( + + + + ); + } + if (settingsQuery.isError) { + return ( + + void settingsQuery.refetch()} + title="Не удалось загрузить настройки приватности" + /> + + ); + } + if (!settings) return ; + + return ( + + {canShowConsentManagement ? ( + + ) : ( +
+ +
+ )} + +
+ {c2State === "active" ? ( +

+ Действующее согласие C2 найдено. Публикация все равно требует отдельного сохранения. +

+ ) : c2State === "inactive" ? ( +

Проверена вся активная история: действующего C2 нет.

+ ) : activeConsents.isError ? ( + void activeConsents.refetch()} + title="Не удалось проверить согласие C2" + /> + ) : activeConsents.isPending ? ( + + ) : ( +

+ Полная история активных согласий еще не загружена. Отсутствие C2 на текущей странице не + означает, что его нет. +

+ )} + {activeConsents.hasNextPage ? ( + + ) : null} +
+ + { + if (actor) setDraftState({ actorId: actor.account.id, value }); + }} + onSave={() => void savePublication()} + onReload={() => void reloadPublicationSettings()} + /> + + void setSearchStatus(value)} + /> + +
+ void previewQuery.refetch()} + /> +
+ + void accessHistory.fetchNextPage()} + hiddenOrganizations={hiddenOrganizations} + hiddenLoading={hiddenOrganizationsQuery.isPending} + hiddenError={hiddenOrganizationsQuery.error} + hiddenHasMore={Boolean(hiddenOrganizationsQuery.hasNextPage)} + hiddenFetching={hiddenOrganizationsQuery.isFetchingNextPage} + onLoadHidden={() => void hiddenOrganizationsQuery.fetchNextPage()} + pendingAction={pendingAction} + actionError={feedbackScope === "organization" ? actionError : null} + actionMessage={feedbackScope === "organization" ? actionMessage : null} + onHide={hideFromOrganization} + onUnhide={unhideOrganizationForCandidate} + /> + + void privacyHistory.fetchNextPage()} + /> + + void accessHistory.fetchNextPage()} + /> +
+ ); +}