feat: add candidate privacy controls

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

No files matched your search

@@ -0,0 +1,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,
};