feat: add candidate privacy controls
This commit is contained in:
1 parent
e6bd66c560
commit
95b8e566c4
20 files changed
+2592
-11
No files matched your search
@@ -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<string | Response> {
|
||||
}
|
||||
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 пока нет.");
|
||||
});
|
||||
|
||||
|
||||
@@ -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: <ConsentsPage />,
|
||||
element: <PrivacyPage />,
|
||||
},
|
||||
{ path: paths.candidate.supportCases, element: <SupportCasesPage /> },
|
||||
{ path: paths.candidate.supportNew, element: <CreateSupportCasePage /> },
|
||||
|
||||
@@ -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";
|
||||
@@ -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["card"]>): 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"]);
|
||||
});
|
||||
});
|
||||
@@ -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<string, OrganizationReference>();
|
||||
|
||||
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<Record<PublishableCardField, string>> = {
|
||||
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<Record<CandidateWorkFormat, string>> = {
|
||||
remote: "Удаленно",
|
||||
office: "В офисе",
|
||||
hybrid: "Гибридно",
|
||||
};
|
||||
|
||||
const experienceBandLabels: Readonly<Record<CandidateExperienceBand, string>> = {
|
||||
"0_1": "До 1 года",
|
||||
"1_3": "1-3 года",
|
||||
"3_6": "3-6 лет",
|
||||
"6_plus": "6 лет и больше",
|
||||
"0_3": "0-3 года",
|
||||
"3_plus": "3 года и больше",
|
||||
};
|
||||
|
||||
const salaryCompatibilityLabels: Readonly<Record<CandidateSalaryCompatibility, string>> = {
|
||||
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;
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { PrivacyPage } from "./ui/privacy-page";
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
<PrivacyPreview preview={preview} isLoading={false} error={null} onRetry={vi.fn()} />,
|
||||
);
|
||||
|
||||
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(
|
||||
<OrganizationVisibility
|
||||
accessRecords={[accessRecord("00000000-0000-4000-8000-000000000011", orgA)]}
|
||||
accessLoading={false}
|
||||
accessError={null}
|
||||
accessHasMore={false}
|
||||
accessFetching={false}
|
||||
onLoadAccess={vi.fn()}
|
||||
hiddenOrganizations={[hiddenOrganization(orgB)]}
|
||||
hiddenLoading={false}
|
||||
hiddenError={null}
|
||||
hiddenHasMore
|
||||
hiddenFetching={false}
|
||||
onLoadHidden={vi.fn()}
|
||||
pendingAction={null}
|
||||
actionError={null}
|
||||
actionMessage={null}
|
||||
onHide={vi.fn()}
|
||||
onUnhide={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Компания Б");
|
||||
expect(markup).toContain("Снова разрешить просмотр");
|
||||
expect(markup).toContain(
|
||||
"Список действий появится после загрузки всех страниц скрытых компаний",
|
||||
);
|
||||
expect(markup).not.toContain("Скрыть профиль</button>");
|
||||
expect(markup).toContain("не восстанавливает C4");
|
||||
});
|
||||
|
||||
it("shows only organizations from access history as hide candidates", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<OrganizationVisibility
|
||||
accessRecords={[
|
||||
accessRecord("00000000-0000-4000-8000-000000000011", orgA),
|
||||
accessRecord("00000000-0000-4000-8000-000000000012", orgB),
|
||||
accessRecord("00000000-0000-4000-8000-000000000013", null),
|
||||
]}
|
||||
accessLoading={false}
|
||||
accessError={null}
|
||||
accessHasMore
|
||||
accessFetching={false}
|
||||
onLoadAccess={vi.fn()}
|
||||
hiddenOrganizations={[]}
|
||||
hiddenLoading={false}
|
||||
hiddenError={null}
|
||||
hiddenHasMore={false}
|
||||
hiddenFetching={false}
|
||||
onLoadHidden={vi.fn()}
|
||||
pendingAction={null}
|
||||
actionError={null}
|
||||
actionMessage={null}
|
||||
onHide={vi.fn()}
|
||||
onUnhide={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<PrivacyHistory
|
||||
events={[event]}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
hasMore
|
||||
isFetching={false}
|
||||
onLoad={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
const accessMarkup = renderToStaticMarkup(
|
||||
<CardAccessHistory
|
||||
records={[accessRecord("00000000-0000-4000-8000-000000000041", orgA)]}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
hasMore
|
||||
isFetching={false}
|
||||
onLoad={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(privacyMarkup).toContain("Показана только загруженная часть истории");
|
||||
expect(privacyMarkup).not.toContain("Показана вся история");
|
||||
expect(accessMarkup).toContain("Показана только загруженная часть истории");
|
||||
expect(accessMarkup).not.toContain("Показана вся история");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user